From f42fed75cc8e10ebba6842c1d512871feb148ec9 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:27:48 +0100 Subject: [PATCH 01/47] Give every CAS request its own window and cap decision loops Each request binds `cas_request_window_ms` when it is sent; requests share no deadline. `Retry::bind` takes the smallest of the window, an outside cap (a tool's own deadline) and the lease, and records which one won in `Retry::Bound::Source`. Decision loops end after `kCasMaxDecisions` (100) with `GaveUp::Why::Attempts`; a fence or lease lost during the last request is reported instead of the count. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressed/Backend/CasHotKeys.cpp | 9 +- .../ContentAddressed/Backend/CasHotKeys.h | 3 +- .../ContentAddressed/Backend/CasRequests.cpp | 229 +++++--- .../ContentAddressed/Backend/CasRequests.h | 126 ++-- .../ContentAddressed/Backend/CasRetry.cpp | 18 +- .../ContentAddressed/Backend/CasRetry.h | 72 ++- .../ContentAddressed/Backend/CasWriteResult.h | 5 +- .../ContentAddressedSettings.cpp | 2 +- .../ContentAddressed/Pool/CasPartWriteTxn.cpp | 2 + .../ContentAddressed/Pool/CasServerRoot.cpp | 2 + src/Disks/tests/cas_test_helpers.h | 18 + src/Disks/tests/cas_time_taking_backend.h | 257 +++++++++ src/Disks/tests/gtest_cas_pool_meta.cpp | 15 +- src/Disks/tests/gtest_cas_requests.cpp | 341 ++++++++++- src/Disks/tests/gtest_cas_shared_deadline.cpp | 538 ++++++++++++++++++ 15 files changed, 1458 insertions(+), 179 deletions(-) create mode 100644 src/Disks/tests/cas_time_taking_backend.h create mode 100644 src/Disks/tests/gtest_cas_shared_deadline.cpp diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp index 81b7096808608..020bd20020d07 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp @@ -32,7 +32,7 @@ namespace GaveUp::Source sourceFor(const Retry::Bound & bound) { - return bound.lease_bound ? GaveUp::Source::Lease : GaveUp::Source::Policy; + return bound.source == Retry::Bound::Source::Lease ? GaveUp::Source::Lease : GaveUp::Source::Policy; } /// The wait slice: how late, at most, a waiter notices its own fence or deadline. A handover wakes it @@ -194,8 +194,7 @@ void CasHotKeys::leave(const String & key, Item & item, bool entered_hold, uint6 } } -WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry & policy, const Retry::Bound & bound, - const Decide & decide) +WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry & policy, const Decide & decide) { CasOperation::WriteState state; std::optional base; @@ -214,13 +213,13 @@ WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry const auto read_base = [&]() -> std::optional { ProfileEvents::increment(ProfileEvents::CASHotKeyReadStarts); - CasOperation::Resolved resolved = op.observe(key, policy, bound); + CasOperation::Resolved resolved = op.observe(key, policy); state.last_seen = resolved.seen; base.reset(); if (const auto * object = std::get_if(&state.last_seen)) base = *object; else if (!std::holds_alternative(state.last_seen)) - return op.gaveUpAfterFailedObservation(resolved.stop, state, bound); + return op.gaveUpAfterFailedObservation(resolved, state); return std::nullopt; }; if (!from_cache) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h index d41ec95e16525..5114e364e8bf5 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h @@ -104,8 +104,7 @@ class CasHotKeys }; using Cache = CacheBase, RememberedWeight>; - WriteResult hold(const String & key, CasOperation & op, const Retry & policy, const Retry::Bound & bound, - const Decide & decide); + WriteResult hold(const String & key, CasOperation & op, const Retry & policy, const Decide & decide); void leave(const String & key, Item & item, bool entered_hold, uint64_t entered_ms, CasOperation & op) noexcept; std::optional cached(const String & key) const; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp index d8d5474334646..cc71dba14cda7 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp @@ -100,6 +100,11 @@ void logCasWriteRetryLater(const String & why) throw Exception(ErrorCodes::NETWORK_ERROR, "CAS write could not be committed ({}); retrying later", why); } +[[noreturn]] void throwDidNotConverge(std::string_view what, uint32_t count, std::string_view unit) +{ + throwCasWriteRetryLater(fmt::format("{}: did not converge after {} {}", what, count, unit)); +} + [[noreturn]] void throwCasRequestRetryLater(const String & why) { LogSeriesLimiter log(getLogger("CasRequestRetryLater"), /*allowed_count=*/1, /*interval_s=*/30); @@ -200,7 +205,7 @@ bool isAuthoritativeAbsence([[maybe_unused]] const std::exception & e) GaveUp::Source sourceFor(const Retry::Bound & bound) { - return bound.lease_bound ? GaveUp::Source::Lease : GaveUp::Source::Policy; + return bound.source == Retry::Bound::Source::Lease ? GaveUp::Source::Lease : GaveUp::Source::Policy; } /// Could the precondition this write was built with still be met by what the resolve read saw? A @@ -504,7 +509,7 @@ Retry CasOperation::freeze(const Retry & policy) const bool CasOperation::oneAttemptFitsBefore(uint64_t deadline_ms) const { - return fits(reservedFor(0, 1), Retry::Bound{.deadline_ms = deadline_ms, .lease_bound = false}); + return fits(reservedFor(0, 1), Retry::Bound{.deadline_ms = deadline_ms, .source = Retry::Bound::Source::OutsideCap}); } std::optional CasOperation::pauseBeforeRedecide(uint64_t ms, const GaveUp & unresolved, const Retry & policy) @@ -513,10 +518,61 @@ std::optional CasOperation::pauseBeforeRedecide(uint64_t ms, const state.attempts_sent = unresolved.attempts_sent; state.sent_any = unresolved.sent_any; state.last_seen = unresolved.last_seen; - /// Room for the next decision's two requests: its catalog read and its write. - constexpr uint32_t envelopes_for_next_decision = 2; - return gatedPause(ms, envelopes_for_next_decision, state, owner.bindPolicy(policy), detail::recordReissue, - /*should_sleep=*/true); + return pauseBetweenDecisions(ms, state, policy, PauseAfter::Failure); +} + +std::optional CasOperation::pauseUnderPolicy(uint64_t ms, const Retry & policy, PauseAfter after, + void (*record)()) +{ + /// Admission for `needed_ms` of pause, so a pause never outlives the mount lease. A window belongs to + /// one request and the next request binds its own when it is sent, so only the policy's absolute limits + /// can refuse a pause. The owner is checked last, so a lost fence or lease stays the typed outcome. + auto check_pause = [&](uint64_t needed_ms) -> std::optional + { + switch (gate(needed_ms)) + { + case Gate::FenceLost: return PauseStop::FenceLost; + case Gate::NoBudget: return PauseStop::NoBudget; + case Gate::Ok: break; + } + if (policy.lease_deadline_ms && !fits(needed_ms, {.deadline_ms = *policy.lease_deadline_ms, .source = Retry::Bound::Source::Lease})) + return PauseStop::Lease; + if (policy.outside_cap_ms && !fits(needed_ms, {.deadline_ms = *policy.outside_cap_ms, .source = Retry::Bound::Source::OutsideCap})) + return PauseStop::OutsideCap; + throwIfBackgroundStopped(); + if (after == PauseAfter::Failure && !insideOwed() && queryStopRequested()) + return PauseStop::QueryStopped; + return std::nullopt; + }; + if (auto stop = check_pause(ms)) + return stop; + record(); + /// A query cut short here is reported by the check below, after the typed bounds. + if (after == PauseAfter::Failure) + sleepUnlessQueryStops(ms, [this](uint64_t slice_ms) { sleep(slice_ms); }); + else + sleep(ms); + /// A sleep can end on or past a limit it fitted before, and `decide` must not run after it. + return check_pause(0); +} + +std::optional CasOperation::pauseBetweenDecisions(uint64_t ms, WriteState & state, const Retry & policy, + PauseAfter after, void (*record)()) +{ + const std::optional stop = pauseUnderPolicy(ms, policy, after, record); + if (!stop) + return std::nullopt; + switch (*stop) + { + /// Named the way every request names a lost fence: by the bound the policy would get now. + case PauseStop::FenceLost: return gaveUp(GaveUp::Why::FenceLost, sourceFor(owner.bindPolicy(policy)), state); + case PauseStop::NoBudget: return gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, state); + case PauseStop::Lease: return gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, state); + case PauseStop::OutsideCap: return gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Policy, state); + /// The failure the pause followed stays unresolved; no decision follows it. + case PauseStop::QueryStopped: return gaveUp(GaveUp::Why::Unresolved, sourceFor(owner.bindPolicy(policy)), state); + } + UNREACHABLE(); } bool CasOperation::fits(uint64_t needed_ms, const Retry::Bound & bound) const @@ -570,17 +626,16 @@ void CasOperation::giveUpReadNoBudget(std::string_view verb, const String & subj } void CasOperation::giveUpReadDeadline(std::string_view verb, const String & subject, - const Retry::Bound & bound, uint32_t attempts_made) + GaveUp::Source source, uint32_t attempts_made) { last_read_stop = ReadStop::PolicyExhausted; throwCasRequestRetryLater(fmt::format("{} of '{}': gave up at the {} deadline after {} attempt(s)", - verb, subject, bound.lease_bound ? "lease" : "policy", attempts_made)); + verb, subject, source == GaveUp::Source::Lease ? "lease" : "policy", attempts_made)); } -std::optional CasOperation::readUnder( - const String & key, const Retry & policy, const Retry::Bound & bound, OnMemoryLimit on_memory_limit) +std::optional CasOperation::readUnder(const String & key, const Retry & policy, OnMemoryLimit on_memory_limit) { - return readLoop("read", key, policy, bound, [&](auto & access) -> std::optional + return readLoop("read", key, policy, [&](auto & access) -> std::optional { auto raw = owner.backend->read(key, access); if (!raw) @@ -589,9 +644,9 @@ std::optional CasOperation::readUnder( }, on_memory_limit); } -std::optional CasOperation::headUnder(const String & key, const Retry & policy, const Retry::Bound & bound) +std::optional CasOperation::headUnder(const String & key, const Retry & policy) { - return readLoop("head", key, policy, bound, [&](auto & access) -> std::optional + return readLoop("head", key, policy, [&](auto & access) -> std::optional { auto raw = owner.backend->head(key, access); if (!raw) @@ -600,10 +655,9 @@ std::optional CasOperation::headUnder(const String & key, const Retry & po }); } -ListPage CasOperation::listUnder(const String & prefix, const String & cursor, size_t limit, - const Retry & policy, const Retry::Bound & bound) +ListPage CasOperation::listUnder(const String & prefix, const String & cursor, size_t limit, const Retry & policy) { - return readLoop("list", prefix, policy, bound, [&](auto & access) + return readLoop("list", prefix, policy, [&](auto & access) { Backend::RawListPage raw = owner.backend->list(prefix, cursor, limit, access); ListPage page; @@ -620,10 +674,11 @@ ListPage CasOperation::listUnder(const String & prefix, const String & cursor, s }); } -Removal CasOperation::removeUnder(const String & key, const String & expected_value, - const Retry & policy, const Retry::Bound & bound) +Removal CasOperation::removeUnder(const String & key, const String & expected_value, const Retry & policy) { - const Backend::RawRemoval raw = readLoop("remove", key, policy, bound, [&](auto & access) + /// A mutation, so unlike a read it does not start for a stopped background owner. + throwIfBackgroundStopped(); + const Backend::RawRemoval raw = readLoop("remove", key, policy, [&](auto & access) { return owner.backend->remove(key, expected_value, access); }); @@ -643,17 +698,17 @@ Removal CasOperation::removeUnder(const String & key, const String & expected_va std::optional CasOperation::read(const String & key, const Retry & policy, OnMemoryLimit on_memory_limit) { - return readUnder(key, policy, owner.bindPolicy(policy), on_memory_limit); + return readUnder(key, policy, on_memory_limit); } std::optional CasOperation::head(const String & key, const Retry & policy) { - return headUnder(key, policy, owner.bindPolicy(policy)); + return headUnder(key, policy); } ListPage CasOperation::list(const String & prefix, const String & cursor, size_t limit, const Retry & policy) { - return listUnder(prefix, cursor, limit, policy, owner.bindPolicy(policy)); + return listUnder(prefix, cursor, limit, policy); } void CasOperation::forEachListedKey(const String & prefix, const ListedKeyFn & fn, const Retry & per_page, @@ -684,7 +739,7 @@ void CasOperation::removeManyWriteOnce(const std::vector & keys, c return; const Retry::Bound bound = owner.bindPolicy(policy); const String subject = fmt::format("{} (+{} keys)", keys.front().str(), keys.size() - 1); - readLoop("removeManyWriteOnce", subject, policy, bound, [&](auto & access) + readLoop("removeManyWriteOnce", subject, policy, [&](auto & access) { owner.backend->removeManyWriteOnce(keys, access); return true; @@ -693,18 +748,17 @@ void CasOperation::removeManyWriteOnce(const std::vector & keys, c Removal CasOperation::remove(const String & key, const Etag & seen, const Retry & policy) { - return removeUnder(key, owner.valueFor(key, seen), policy, owner.bindPolicy(policy)); + return removeUnder(key, owner.valueFor(key, seen), policy); } Removal CasOperation::removeCurrent(const String & key, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); for (uint32_t attempt = 1;; ++attempt) { - const std::optional seen = headUnder(key, policy, bound); + const std::optional seen = headUnder(key, policy); if (!seen) return Removal::Gone; - const Removal removed = removeUnder(key, owner.valueFor(key, seen->etag), policy, bound); + const Removal removed = removeUnder(key, owner.valueFor(key, seen->etag), policy); if (removed != Removal::Mismatch) return removed; @@ -715,20 +769,32 @@ Removal CasOperation::removeCurrent(const String & key, const Retry & policy) throwCasRequestRetryLater(fmt::format( "removeCurrent of '{}': the observed incarnation was replaced and the policy allows no reissue", key)); + if (attempt == kCasMaxDecisions) + { + if (const std::optional lost = lostAdmission()) + { + if (*lost == AdmissionLoss::Fence) + giveUpReadFenceLost("removeCurrent", key, "at the decision cap"); + giveUpReadNoBudget("removeCurrent", key, "at the decision cap"); + } + throwDidNotConverge(fmt::format("CAS remove of '{}'", key), kCasMaxDecisions, "decisions"); + } + /// Another incarnation became current between the observation and the delete. Re-observe, paced - /// like every other reissue: the reservation covers the next `head` and the `remove` after it. - const uint64_t pause_ms = Retry::backoff(attempt); - const uint64_t needed = reservedFor(pause_ms, 2); - switch (gate(needed)) + /// like every other reissue; the next `head` and `remove` bind their own windows. + if (const std::optional stop + = pauseUnderPolicy(Retry::backoff(attempt), policy, PauseAfter::Conflict, detail::recordReissue)) { - case Gate::FenceLost: giveUpReadFenceLost("removeCurrent", key, "before the reissue"); - case Gate::NoBudget: giveUpReadNoBudget("removeCurrent", key, "for the reissue"); - case Gate::Ok: break; + switch (*stop) + { + case PauseStop::FenceLost: giveUpReadFenceLost("removeCurrent", key, "before the reissue"); + case PauseStop::NoBudget: giveUpReadNoBudget("removeCurrent", key, "for the reissue"); + case PauseStop::Lease: giveUpReadDeadline("removeCurrent", key, GaveUp::Source::Lease, attempt); + case PauseStop::OutsideCap: giveUpReadDeadline("removeCurrent", key, GaveUp::Source::Policy, attempt); + /// Only a pause after a failure reports a stopped query, and this one follows a conflict. + case PauseStop::QueryStopped: UNREACHABLE(); + } } - if (!fits(needed, bound)) - giveUpReadDeadline("removeCurrent", key, bound, attempt); - detail::recordReissue(); - sleep(pause_ms); } } @@ -752,7 +818,7 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry /// answer; before the first one the caller is told no request happened. if (last_probe) return *last_probe; - giveUpReadDeadline("probeSentinel", key, bound, attempt - 1); + giveUpReadDeadline("probeSentinel", key, sourceFor(bound), attempt - 1); } detail::recordAttempt(); @@ -803,8 +869,7 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry std::unique_ptr CasOperation::stream(const String & key, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); - std::unique_ptr body = readLoop("stream", key, policy, bound, [&](auto & access) + std::unique_ptr body = readLoop("stream", key, policy, [&](auto & access) { return owner.backend->stream(key, access); }); @@ -817,8 +882,8 @@ std::unique_ptr CasOperation::stream(const String & key, const Retry void CasOperation::publish(const BlobPublishRequest & request, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); - readLoop("publish", request.destination_key, policy, bound, [&](auto & access) + throwIfBackgroundStopped(); + readLoop("publish", request.destination_key, policy, [&](auto & access) { owner.backend->publish(request, access); }); @@ -883,29 +948,61 @@ WriteResult CasOperation::gaveUp(GaveUp::Why why, GaveUp::Source source, WriteSt return GaveUp{why, source, state.sent_any, state.last_seen, state.attempts_sent}; } -WriteResult CasOperation::gaveUpForReadStop(ReadStop stop, WriteState & state, const Retry::Bound & bound) const +WriteResult CasOperation::gaveUpForReadStop(ReadStop stop, GaveUp::Source source, WriteState & state) const { switch (stop) { case ReadStop::FenceLost: - return gaveUp(GaveUp::Why::FenceLost, sourceFor(bound), state); + return gaveUp(GaveUp::Why::FenceLost, source, state); case ReadStop::NoBudgetLease: /// The fence's budget IS the mount lease, so the lease is the bound that ended this call. return gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, state); case ReadStop::PolicyExhausted: - return gaveUp(GaveUp::Why::Deadline, sourceFor(bound), state); + return gaveUp(GaveUp::Why::Deadline, source, state); } UNREACHABLE(); } -WriteResult CasOperation::gaveUpAfterFailedObservation(std::optional stop, WriteState & state, - const Retry::Bound & bound) const +WriteResult CasOperation::gaveUpAfterFailedObservation(const Resolved & resolved, WriteState & state) const { - if (stop) - return gaveUpForReadStop(*stop, state, bound); + if (resolved.stop) + return gaveUpForReadStop(*resolved.stop, resolved.source, state); /// No bound refused; the read itself failed. That is what `Unresolved` names, and it is the honest /// answer -- claiming a deadline the clock never reached would misreport which bound to widen. - return gaveUp(GaveUp::Why::Unresolved, sourceFor(bound), state); + return gaveUp(GaveUp::Why::Unresolved, resolved.source, state); +} + +std::optional CasOperation::lostAdmission() const +{ + switch (gate(0)) + { + case Gate::FenceLost: return AdmissionLoss::Fence; + case Gate::NoBudget: return AdmissionLoss::Lease; + case Gate::Ok: return std::nullopt; + } + UNREACHABLE(); +} + +WriteResult CasOperation::gaveUpAfterDecisionCap(WriteState & state, const Retry & policy) const +{ + if (const std::optional lost = lostAdmission()) + return *lost == AdmissionLoss::Fence + ? gaveUp(GaveUp::Why::FenceLost, sourceFor(owner.bindPolicy(policy)), state) + : gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, state); + return gaveUp(GaveUp::Why::Attempts, GaveUp::Source::Policy, state); +} + +std::optional CasOperation::pauseAfterConflict(uint32_t decisions, WriteState & state, const Retry & policy) +{ + if (decisions == kCasMaxDecisions) + return gaveUpAfterDecisionCap(state, policy); + /// A clean lost race is settled: the resolve read holds the fresh object and the next + /// iteration decides on it. Only a conflict that settled a transport fault is paced by the + /// growing schedule. Either way the conflict is an answer, so the pause does not consult the query. + return state.any_ambiguous + ? pauseBetweenDecisions(reissuePause(state, Retry::backoff(++state.reissues)), state, policy, PauseAfter::Conflict) + : pauseBetweenDecisions(reissuePause(state, Retry::conflictBackoff()), state, policy, PauseAfter::Conflict, + detail::recordConflictPause); } WriteResult CasOperation::postCommit(Etag inc, bool resolved_by_read, WriteState & state, const Retry::Bound & bound) @@ -982,9 +1079,9 @@ std::optional CasOperation::reissueAtOnce(WriteState & state, const } WriteResult CasOperation::writeLoop(const String & key, const String & bytes, const std::optional & expected, - const Retry & policy, const Retry::Bound & bound, WriteState & state, - ResolveWith resolve_refusal_with) + const Retry & policy, WriteState & state, ResolveWith resolve_refusal_with) { + const Retry::Bound bound = owner.bindPolicy(policy); std::optional expected_value; if (expected) expected_value = owner.valueFor(key, *expected); @@ -1197,29 +1294,28 @@ WriteResult CasOperation::writeLoop(const String & key, const String & bytes, co WriteResult CasOperation::create(const String & key, const String & bytes, const Retry & policy) { WriteState state; - return writeLoop(key, bytes, std::nullopt, policy, owner.bindPolicy(policy), state, ResolveWith::Body); + return writeLoop(key, bytes, std::nullopt, policy, state, ResolveWith::Body); } WriteResult CasOperation::replace(const String & key, const String & bytes, const Etag & seen, const Retry & policy) { WriteState state; - return writeLoop(key, bytes, seen, policy, owner.bindPolicy(policy), state, ResolveWith::Body); + return writeLoop(key, bytes, seen, policy, state, ResolveWith::Body); } WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObject & decide, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); WriteState state; - Resolved resolved = observe(key, policy, bound); + Resolved resolved = observe(key, policy); state.last_seen = resolved.seen; std::optional current; if (const auto * obj = std::get_if(&state.last_seen)) current = *obj; else if (!std::holds_alternative(state.last_seen)) - return gaveUpAfterFailedObservation(resolved.stop, state, bound); + return gaveUpAfterFailedObservation(resolved, state); - for (;;) + for (uint32_t decisions = 1;; ++decisions) { /// Outside every classification: `decide` is the caller's own control flow, and an exception /// from it is theirs to see unchanged. @@ -1228,7 +1324,7 @@ WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObje return Declined{state.last_seen}; WriteResult result = writeLoop(key, *next, - current ? std::optional(current->etag) : std::nullopt, policy, bound, state, + current ? std::optional(current->etag) : std::nullopt, policy, state, ResolveWith::Body); if (!std::holds_alternative(result)) return result; @@ -1252,21 +1348,20 @@ WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObje /// what the store held. if (std::holds_alternative(state.last_seen)) { - resolved = observe(key, policy, bound); + resolved = observe(key, policy); state.last_seen = resolved.seen; if (const auto * obj = std::get_if(&state.last_seen)) current = *obj; else if (std::holds_alternative(state.last_seen)) current.reset(); else - return gaveUpAfterFailedObservation(resolved.stop, state, bound); + return gaveUpAfterFailedObservation(resolved, state); } } } WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const DecideOnMeta & decide, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); WriteState state; Resolved resolved = observePresence(key, policy, bound); @@ -1275,16 +1370,16 @@ WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const De if (const auto * meta = std::get_if(&state.last_seen)) current = *meta; else if (!std::holds_alternative(state.last_seen)) - return gaveUpAfterFailedObservation(resolved.stop, state, bound); + return gaveUpAfterFailedObservation(resolved, state); - for (;;) + for (uint32_t decisions = 1;; ++decisions) { const std::optional next = decide(current); if (!next) return Declined{state.last_seen}; WriteResult result = writeLoop(key, *next, - current ? std::optional(current->etag) : std::nullopt, policy, bound, state, + current ? std::optional(current->etag) : std::nullopt, policy, state, ResolveWith::Presence); /// A refused precondition was settled by a HEAD, but proving an ambiguous attempt landed needs /// the bytes; this loop is presence-only by contract, so that body stops here. @@ -1314,7 +1409,7 @@ WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const De else if (std::holds_alternative(state.last_seen)) current.reset(); else - return gaveUpAfterFailedObservation(resolved.stop, state, bound); + return gaveUpAfterFailedObservation(resolved, state); } } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h index c318187262bef..de9d894c8bbb2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h @@ -122,6 +122,10 @@ String describeRequestFailure(std::string_view verb, const String & key, const s /// commit: a read, a probe, a delete, or recovery and maintenance work. [[noreturn]] void throwCasRequestRetryLater(const String & why); +/// For a loop that capped its own iterations and has no `WriteResult` to carry `GaveUp::Why::Attempts`. +/// Same class as `throwCasWriteRetryLater`; `unit` names what `count` counts. +[[noreturn]] void throwDidNotConverge(std::string_view what, uint32_t count, std::string_view unit); + /// Same classification as `throwCasWriteRetryLater`, but returns the exception as a /// `std::exception_ptr` for call sites that fail a pending future/promise rather than throw directly. /// Both entry points route through the SAME construction internally, so the error code / message shape @@ -329,30 +333,31 @@ class CasOperation Dialect backendDialect() const; /// A caller's own inter-iteration wait, paced through the same clock the engine's own sleeps use -- /// so a test that replaces the sleep sees no real time pass in either. For the hand-written loops - /// that reissue something the engine must not reissue for them. - void pause(uint64_t ms) { sleep(ms); } - /// The pause before a loop re-decides after `unresolved`, gated like the engine's own reissue - /// pause. Returns the give-up instead of sleeping when the fence is lost or the pause plus two - /// attempt reservations (the re-read and the write) do not fit in `policy`. - std::optional pauseBeforeRedecide(uint64_t ms, const GaveUp & unresolved, const Retry & policy); + /// that reissue something the engine must not reissue for them. It only sleeps: no owner, fence or deadline check. + void sleepFor(uint64_t ms) { sleep(ms); } + /// The pause before a loop re-decides after `unresolved`. Returns the give-up instead of sleeping + /// when the fence is lost, the mount lease has no room for the pause, or the pause does not fit before `policy`'s + /// lease or absolute deadline; and after sleeping when any of these holds at wake-up, or when the query stopped + /// during it. No window is consulted: the next decision's requests bind their own. + std::optional pauseAfterUnresolvedWrite(uint64_t ms, const GaveUp & unresolved, const Retry & policy); /// The verdict point: is this operation still admitted? For the sites that guard a decision rather /// than a request. bool admitted() const { return gate(0) == Gate::Ok; } + enum class AdmissionLoss : uint8_t { Fence, Lease }; + /// Why this operation is no longer admitted, or nullopt while it is. A loop asks at its count cap: a + /// fence lost or a lease spent during the last request is the answer, not the count. + std::optional lostAdmission() const; void observeRequests(RequestObserver observer_) { observer = std::move(observer_); } /// The write lane for keys several writers of this pool share. CasHotKeys & hotKeys() const { return *owner.hot_keys; } - /// `policy` with its window turned into an absolute deadline on this operation's clock, taken NOW. - /// A hand-written loop freezes its policy once before it starts and passes the frozen value to - /// every call it makes, so the loop ends when the window it was given ends -- rather than granting - /// each verb of each iteration a fresh one, which is how a bounded document promise became hours - /// of paced retrying. A policy that already carries a deadline is returned unchanged, so freezing - /// twice cannot extend it. - Retry freeze(const Retry & policy) const; - /// Would a read verb start its first attempt now under a policy frozen to `deadline_ms`? The same test the - /// verb applies before it sends, without any lease bound. A caller with a deadline of its own asks first, so - /// its running out of time is its own error and not the verb's retry-later give-up. + /// Would a read verb (one envelope; a conditional write reserves two) start its first attempt now under + /// `policy`? The same deadline test the verb applies before it sends, lease bound included, not its + /// fence check. A caller with a deadline of its own asks first, so its running out of time is its own + /// error and not the verb's retry-later give-up. + bool oneAttemptFits(const Retry & policy) const; + /// The same, before an absolute `deadline_ms` and without any lease bound. bool oneAttemptFitsBefore(uint64_t deadline_ms) const; /// `OnMemoryLimit::Propagate` makes a `MEMORY_LIMIT_EXCEEDED` from an admitted attempt escape at once: the @@ -450,31 +455,33 @@ class CasOperation /// `NETWORK_ERROR`, so a caller that SWALLOWS the exception -- only the resolve read does -- cannot /// recover from it which bound refused, and reporting a lease refusal as a policy deadline is the /// confusion `GaveUp::Source` exists to prevent. `PolicyExhausted` names the `Retry` bound, whose - /// own source is `Bound::lease_bound`. + /// own source is `Bound::source`. enum class ReadStop : uint8_t { FenceLost, NoBudgetLease, PolicyExhausted }; /// What the resolve read saw, and why it stopped when it saw nothing. `stop` is set ONLY when a /// bound refused; a read that failed at the transport leaves it empty, and that is the one case - /// `NotObserved` is still the whole story. + /// `NotObserved` is still the whole story. `source` is the source of the read's own bound. struct Resolved { Observation seen; std::optional stop; + GaveUp::Source source = GaveUp::Source::Policy; + /// The read failed and saw its query stopped. + bool observed_stop = false; }; - /// One read-class request under the policy: admission, attempt, classification, jittered reissue. - /// Returns whatever `once` returns, or throws -- the read surface reports failure by exception. + /// One read-class request under the policy: admission, attempt, classification, jittered reissue, + /// all within the window it binds at its start. Returns whatever `once` returns, or throws -- the + /// read surface reports failure by exception. template auto readLoop(std::string_view verb, const String & subject, const Retry & policy, - const Retry::Bound & bound, Fn && once, OnMemoryLimit on_memory_limit = OnMemoryLimit::Reissue); + Fn && once, OnMemoryLimit on_memory_limit = OnMemoryLimit::Reissue); - std::optional readUnder(const String & key, const Retry & policy, const Retry::Bound & bound, + std::optional readUnder(const String & key, const Retry & policy, OnMemoryLimit on_memory_limit = OnMemoryLimit::Reissue); - std::optional headUnder(const String & key, const Retry & policy, const Retry::Bound & bound); - ListPage listUnder(const String & prefix, const String & cursor, size_t limit, - const Retry & policy, const Retry::Bound & bound); - Removal removeUnder(const String & key, const String & expected_value, - const Retry & policy, const Retry::Bound & bound); + std::optional headUnder(const String & key, const Retry & policy); + ListPage listUnder(const String & prefix, const String & cursor, size_t limit, const Retry & policy); + Removal removeUnder(const String & key, const String & expected_value, const Retry & policy); /// How a write settles a REFUSED PRECONDITION, which needs only to know what is at the key. An /// ambiguous attempt always reads the body, whichever this says, because only the bytes can prove @@ -484,7 +491,8 @@ class CasOperation /// The write engine: one call, any policy. `Committed` and `Conflict` are proven by an exact read /// or by the reissue's own 2xx before they are reported; an attempt whose transport error named a /// failed connection is reissued before its read. `Refused`, `Declined` and `GaveUp` report what - /// the store or the bounds said. + /// the store or the bounds said. The window bound at entry governs every send of these bytes; the + /// read that settles an attempt is a request of its own and binds its own window from `policy`. WriteResult writeLoop(const String & key, const String & bytes, const std::optional & expected, const Retry & policy, const Retry::Bound & bound, WriteState & state, ResolveWith resolve_refusal_with); @@ -497,26 +505,45 @@ class CasOperation WriteResult postCommit(Etag inc, bool resolved_by_read, WriteState & state, const Retry::Bound & bound); WriteResult gaveUp(GaveUp::Why why, GaveUp::Source source, WriteState & state) const; /// The bound that refused the resolve read, reported as the outcome it actually is. - WriteResult gaveUpForReadStop(ReadStop stop, WriteState & state, const Retry::Bound & bound) const; + WriteResult gaveUpForReadStop(ReadStop stop, GaveUp::Source source, WriteState & state) const; /// A resolve read that produced nothing. The fence is NOT resampled: a second sample reports a /// state the read never saw, which is how a lease refusal used to be reported as a policy deadline. - WriteResult gaveUpAfterFailedObservation(std::optional stop, WriteState & state, - const Retry::Bound & bound) const; + WriteResult gaveUpAfterFailedObservation(const Resolved & resolved, WriteState & state) const; + /// The loops' answer after their last allowed decision lost its race. + WriteResult gaveUpAfterDecisionCap(WriteState & state, const Retry & policy) const; + + /// Why a pause between decisions ended the call. + /// `QueryStopped` follows only `PauseAfter::Failure`. + enum class PauseStop : uint8_t { FenceLost, NoBudget, Lease, OutsideCap, QueryStopped }; + /// What the pause follows. A query's stop is consulted only after a failure: a conflict is an answer, + /// and the work after it proceeds for a killed query as on plain S3. + enum class PauseAfter : uint8_t { Conflict, Failure }; + /// The pause between two decisions: admission for the pause, then the policy's explicit lease and outside cap, + /// then the sleep, then admission, lease and cap again so no `decide` runs past them. It consults + /// no window: the next decision's requests bind their own when they are sent. + std::optional pauseUnderPolicy(uint64_t ms, const Retry & policy, PauseAfter after, void (*record)()); + /// `pauseUnderPolicy` reported as a give-up. A value means the call ended; nullopt means + /// `decide` may run again. + std::optional pauseBetweenDecisions(uint64_t ms, WriteState & state, const Retry & policy, PauseAfter after, + void (*record)() = detail::recordReissue); + /// The read-modify-write loops' step after a lost decision: the decision cap, else the pause before the next + /// decision. A value means the call ended. + std::optional pauseAfterConflict(uint32_t decisions, WriteState & state, const Retry & policy); + /// The caller may send another attempt. + struct ResumeAfterPause {}; + /// A query stopped in the pause and vetoes the next attempt; the pause also set `state.observed_stop`. + struct QueryVetoedResend {}; + /// How a gated pause ended: resume, a query's veto, or the call's outcome. + using PauseOutcome = std::variant; /// The shared shape behind every gated pause below: admission for `envelopes` attempt reservations /// plus `pause_ms`, the deadline check, the counter this pause records itself under, then the sleep /// -- called even with a zero `pause_ms` UNLESS `should_sleep` is false, which is reserved for the - /// fuse's zero-pause reissue (a pace of "no pause", not "a zero-length one"). A value means the call - /// ended during it; nullopt means the caller may send another attempt. - std::optional gatedPause(uint64_t pause_ms, uint32_t envelopes, WriteState & state, - const Retry::Bound & bound, void (*record)(), bool should_sleep); - /// Admission, then the jittered sleep. A value means the call ended during it; nullopt means the - /// caller may send another attempt. Under `WriteState::spacing` this and the two siblings below - /// sleep `reissuePause` instead. - std::optional pauseAndReissue(WriteState & state, const Retry::Bound & bound); - /// The sibling for a clean lost race: the same admission and the same reservation, a flat - /// `Retry::conflictBackoff` sleep, and `state.reissues` untouched, so a transport fault that follows - /// starts its own schedule at the beginning. - std::optional pauseForConflict(WriteState & state, const Retry::Bound & bound); + /// fuse's zero-pause reissue (a pace of "no pause", not "a zero-length one"). + PauseOutcome gatedPause(uint64_t pause_ms, uint32_t envelopes, WriteState & state, + const Retry::Bound & bound, void (*record)(), bool should_sleep); + /// Admission, then the jittered sleep. Under `WriteState::spacing` this and the two siblings below + /// sleep `reissuePause` instead. Only a write's own reissues use these, with the write's own bound. + PauseOutcome pauseAndReissue(WriteState & state, const Retry::Bound & bound); /// The sibling for a failure text that named a failed connection. The same admission and the same /// reservation, a flat `kConnectHintPauseMs` sleep, and `state.reissues` untouched. std::optional pauseFlat(WriteState & state, const Retry::Bound & bound); @@ -545,7 +572,7 @@ class CasOperation [[noreturn]] void giveUpReadFenceLost(std::string_view verb, const String & subject, std::string_view when); [[noreturn]] void giveUpReadNoBudget(std::string_view verb, const String & subject, std::string_view what); [[noreturn]] void giveUpReadDeadline(std::string_view verb, const String & subject, - const Retry::Bound & bound, uint32_t attempts_made); + GaveUp::Source source, uint32_t attempts_made); CasRequests & owner; uint64_t admitted_generation; @@ -554,13 +581,18 @@ class CasOperation /// Written immediately before a read-class give-up throws, cleared and read only by the resolve /// read that swallows it. Every other caller lets the exception carry the verdict. std::optional last_read_stop; + /// The source of the bound the latest read-class request was given, for the same reader. + GaveUp::Source last_read_source = GaveUp::Source::Policy; RequestObserver observer; }; template auto CasOperation::readLoop(std::string_view verb, const String & subject, const Retry & policy, - const Retry::Bound & bound, Fn && once, OnMemoryLimit on_memory_limit) + Fn && once, OnMemoryLimit on_memory_limit) { + const Retry::Bound bound = owner.bindPolicy(policy); + const GaveUp::Source source = bound.source == Retry::Bound::Source::Lease ? GaveUp::Source::Lease : GaveUp::Source::Policy; + last_read_source = source; bool refresh_attempted = false; uint64_t attempt_started_ms = 0; /// Two counters, deliberately kept separate: `attempt_no` is the PHYSICAL attempt count handed to @@ -578,7 +610,7 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const case Gate::Ok: break; } if (!fits(reservation, bound)) - giveUpReadDeadline(verb, subject, bound, attempt_no - 1); + giveUpReadDeadline(verb, subject, source, attempt_no - 1); if (policy.attempt_spacing_ms) attempt_started_ms = owner.now_ms(); @@ -620,7 +652,7 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const case Gate::Ok: break; } if (!fits(needed, bound)) - giveUpReadDeadline(verb, subject, bound, attempt_no); + giveUpReadDeadline(verb, subject, source, attempt_no); detail::recordReissue(); continue; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp index 5ccf6ecc1de79..86f680da7ea60 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp @@ -36,14 +36,16 @@ uint64_t Retry::drawSpacing(uint64_t attempt_spacing_ms_) Retry::Bound Retry::bind(uint64_t now_ms, uint64_t default_window_ms) const { const uint64_t effective_window_ms = window_ms.value_or(default_window_ms); - const uint64_t own_deadline_ms = policy_deadline_ms - ? *policy_deadline_ms - : (now_ms > std::numeric_limits::max() - effective_window_ms - ? std::numeric_limits::max() - : now_ms + effective_window_ms); - if (lease_deadline_ms && *lease_deadline_ms < own_deadline_ms) - return {*lease_deadline_ms, true}; - return {own_deadline_ms, false}; + Bound bound{ + .deadline_ms = now_ms > std::numeric_limits::max() - effective_window_ms + ? std::numeric_limits::max() + : now_ms + effective_window_ms, + .source = Bound::Source::RequestWindow}; + if (outside_cap_ms && *outside_cap_ms < bound.deadline_ms) + bound = {*outside_cap_ms, Bound::Source::OutsideCap}; + if (lease_deadline_ms && *lease_deadline_ms < bound.deadline_ms) + bound = {*lease_deadline_ms, Bound::Source::Lease}; + return bound; } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h index c5e30b29df3cc..1214195e42c3f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h @@ -6,13 +6,37 @@ namespace DB::Cas { -/// A retry policy for one logical CAS write, expressed WITHOUT touching a clock: `window_ms` is the -/// policy's own budget measured from the call's start (empty: the default window of the request plane), -/// and `lease_deadline_ms` (already reduced by the caller's safety margin) is an absolute bound on -/// whatever clock the caller's mount lease is tracked against. Binding a policy to an absolute deadline -/// is deferred to `bind`, which takes the caller's own `now_ms` -- `CasRequests` runs on an injected clock in tests, so a `Retry` built at -/// construction time from the real clock could never be exercised deterministically, and `GaveUp` -/// could not tell a lease-caused deadline from a policy-caused one without recording which bound won. +/// Caps on a hand-written loop's own iterations, independent of any clock: a loop that keeps +/// deciding again on fresh reads must end even when every iteration is quick. +/// An update of a shared object that keeps losing races fails at this count with `NETWORK_ERROR` "did not converge"; +/// there is no total time budget, and each request has its own window. +inline constexpr uint32_t kCasMaxDecisions = 100; +/// The walk that fails at this count propagates its own error; a restart at it fails as "did not converge". +inline constexpr uint32_t kCasMaxRecoveryWalks = 8; + +/// A retry policy for one logical CAS request, expressed WITHOUT touching a clock. +/// +/// Every request gets its OWN window, measured from the entry of the engine call that sends it: `window_ms` +/// if set, else the default window of the plane it runs on. A window bounds one request or one local wait +/// (the hot-key queue wait), so `cas_request_window_ms` means one step. +/// +/// A loop that runs too long gets a smaller count, an owner's stop, or a time budget that decides only whether its +/// next pass starts (the copy-source confirm poll, the GC janitor's pages, the GC ref intake), never a deadline of its +/// own shared between its requests: a shared one leaves a later request no time after a slow early one and can refuse +/// the read that settles a write already sent. The only shared deadlines are absolute bounds from outside the loop, +/// below. Accepted cost: a conflict loop on a slow store can run about 100 windows. Two have neither: a paged listing +/// (`CasOperation::forEachListedKey`) runs until its callback stops it, and a request under `untilDefinitive` has no +/// window. +/// +/// Two things can end a request earlier, and `bind` takes the minimum of all three: +/// - `lease_deadline_ms`: an absolute bound (already reduced by the caller's safety margin) on the clock +/// the mount lease is tracked against; `GaveUp` reports it as the lease's, and an expired window or cap as the +/// policy's. +/// - `outside_cap_ms`: an absolute bound from a caller that has a deadline of its own (an offline tool's +/// `--timeout`). Successive requests under it share it. Set it only through `cappedAt`, never by hand, and +/// never to carry a loop's own budget: a cap never lengthens a window. +/// Binding is deferred to `bind`, which takes the caller's `now_ms`: `CasRequests` runs on an injected clock +/// in tests, and `GaveUp` must tell the lease's bound from the others. struct Retry { std::optional window_ms; @@ -28,12 +52,8 @@ struct Retry /// paths ignore it. Clear it only in a loop that decides again on a fresh read (`casUpdateImpl` /// with `CasOperation::pauseBeforeRedecide`); any other caller gets a bare `GaveUp::Unresolved`. bool resend_unresolved = true; - /// An ABSOLUTE bound on the caller's own clock, replacing `window_ms` in `bind`. A hand-written - /// loop freezes one before it starts (`CasOperation::freeze`) and shares it across every call it - /// makes, so the loop as a whole ends when that deadline does instead of granting each of its - /// iterations a fresh window. Empty for a single verb, which gets its window from where it is - /// called. - std::optional policy_deadline_ms = std::nullopt; + /// An absolute bound on the caller's clock that can only shorten the request. See `cappedAt`. + std::optional outside_cap_ms = std::nullopt; /// When set, a reissue in `CasOperation`'s write and read loops waits until a draw from [0.8, 1.2] /// of this has passed since the failed attempt started, instead of the growing backoff. A /// first-attempt fuse timeout is still reissued at once. @@ -56,12 +76,12 @@ struct Retry static Retry within(uint64_t ms) { return {.window_ms = ms, .lease_deadline_ms = std::nullopt, .single_attempt = false}; } /// The default write policy: the window of the request plane it runs on. static Retry standard() { return {.window_ms = std::nullopt, .lease_deadline_ms = std::nullopt, .single_attempt = false}; } - /// A policy bound by the mount lease: `lease_deadline_ms` minus `margin`, clamped at 0 -- never - /// risk a write landing after this node's fence may already be gone. `window_ms` defaults to the - /// window of the request plane; a caller whose own budget is deliberately much smaller (the - /// graceful-shutdown farewell, whose window is derived from what ONE write costs, not from the - /// standard policy) passes its own window explicitly, and `bind` still takes whichever of the two - /// bounds is smaller. + /// A policy bound by the mount lease: an attempt starts only if its reserved time ends before + /// `lease_deadline_ms` minus `margin`, clamped at 0. That bounds when attempts start, not when they + /// land. `window_ms` defaults to the window of the request plane; a caller whose own budget is + /// deliberately much smaller (the graceful-shutdown farewell, whose window is derived from what ONE + /// write costs, not from the standard policy) passes its own window explicitly, and `bind` still + /// takes whichever of the two bounds is smaller. static Retry untilLeaseSafe(uint64_t lease_deadline_ms, uint64_t margin, std::optional window_ms = std::nullopt) { @@ -103,21 +123,19 @@ struct Retry Retry cappedAt(uint64_t deadline_ms) const { Retry copy = *this; - copy.policy_deadline_ms = policy_deadline_ms && *policy_deadline_ms < deadline_ms ? *policy_deadline_ms : deadline_ms; + copy.outside_cap_ms = outside_cap_ms && *outside_cap_ms < deadline_ms ? *outside_cap_ms : deadline_ms; return copy; } - /// A policy bound to an absolute deadline on the caller's own clock, plus which bound produced - /// it -- the caller's own budget, or the (smaller) lease bound. + /// A policy bound to an absolute deadline on the caller's own clock, plus which bound produced it. struct Bound { + enum class Source : uint8_t { RequestWindow, OutsideCap, Lease }; uint64_t deadline_ms; - bool lease_bound; + Source source; }; - /// Bind this policy to `now_ms`: `deadline_ms = min(policy_deadline_ms ?: now_ms + (window_ms ?: - /// default_window_ms), lease_deadline_ms)`, `lease_bound` true exactly when the lease bound was the - /// smaller of the two. Called once at call entry with the owner's `now_ms()`. A frozen policy therefore keeps - /// the lease bound honest: the smaller of the two still wins, and still says so. + /// `deadline_ms = min(now_ms + (window_ms ?: default_window_ms), outside_cap_ms, lease_deadline_ms)`. A bound + /// is the `source` only when strictly smaller than the ones before it in that order. Bound bind(uint64_t now_ms, uint64_t default_window_ms) const; }; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h index 722c6c2aa7449..9cabbcfa88cdc 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h @@ -1,5 +1,6 @@ #pragma once #include +#include #include #include @@ -59,7 +60,7 @@ struct Refused { int store_error; String message; uint32_t attempts_sent = 0; /// No attempt landed and none can be proven safe to keep making. struct GaveUp { - enum class Why : uint8_t { Deadline, FenceLost, Unresolved }; + enum class Why : uint8_t { Deadline, FenceLost, Unresolved, Attempts }; enum class Source : uint8_t { Policy, Lease }; Why why; Source deadline_source; bool sent_any; Observation last_seen; /// The HTTP attempts this call made, the same count `Committed` carries. Operator counters -- the @@ -120,6 +121,8 @@ inline std::optional orThrow(WriteResult && result, std::string_view what) throwCasTransientUnavailable(String(what), "mount fence tripped: the durable write is refused because this node no longer holds the mount incarnation it was admitted under"); case GaveUp::Why::Deadline: throwCasWriteRetryLater(fmt::format("{}: gave up at the {} deadline after {} attempt(s)", what, g.deadline_source == GaveUp::Source::Lease ? "lease" : "policy", g.sent_any ? "one or more" : "zero")); + case GaveUp::Why::Attempts: + throwCasWriteRetryLater(fmt::format("{}: did not converge after {} decisions", what, kCasMaxDecisions)); case GaveUp::Why::Unresolved: throwCasWriteRetryLater(g.sent_any ? fmt::format("{}: the write is unresolved (sent, resolve read found {})", what, renderObservation(g.last_seen)) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp index 7933094762862..59ec17f6724d5 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp @@ -91,7 +91,7 @@ constexpr std::string_view CAS_KEY_PREFIX = "cas_"; DECLARE(UInt64, gc_io_concurrency, 16, "Maximum number of threads in the GC I/O pool. Used for fold and rebuild read-ahead, deletion-intent creates, orphan-manifest sweep planning reads, pending_deletes HEAD plus conditional DELETE, and namespace janitor batch deletes. Other GC requests run on the round thread. 1 disables parallel GC I/O", 0) \ DECLARE(UInt64, gc_bulk_delete_chunk_keys, 1000, "Most keys per batch delete request in GC's write-once families (owner-removed manifest bodies, covered ref logs and snapshots, the namespace janitor's dead ref logs and snapshots), capped by the storage's batch-delete limit; 1 to 1000", 0) \ DECLARE(UInt64, attempt_timeout_ms, 5000, "Budget for one HTTP attempt of a writable Native mount's control-plane requests (read, head, list, remove, conditional write), at least 1. With the connect cap it forms the attempt envelope the lease arithmetic reserves", 0) \ - DECLARE(UInt64, request_window_ms, 120000, "How long a failing request, including the blob publication loop, keeps retrying before it gives up with a retryable error, in milliseconds, measured from the call's start. Must exceed twice the attempt envelope for a writable disk and the envelope for a read-only one, or the disk refuses to open. The ref-table recovery budget is twice this value", 0) \ + DECLARE(UInt64, request_window_ms, 120000, "How long one failing request keeps starting attempts before it gives up with a retryable error, in milliseconds, measured from the start of that request. The same value bounds, on its own, the wait in the catalog queue and the time after which a copy-source confirm starts no new poll pass. The read that settles an unclear write has its own window. Loops are capped by count: a conditional update is decided at most 100 times, a catalog update submitted at most 100 times, a blob publication tried at most 8 times, and recovery of a table walks at most 8 times. Must exceed twice the attempt envelope for a writable disk and the envelope for a read-only one, or the disk refuses to open", 0) \ DECLARE(UInt64, lease_safety_margin_ms, 2000, "Startup-only margin validated against the mount lease TTL: attempt envelope + this must be strictly less than the TTL, and renew period + 2 × envelope + this too", 0) \ DECLARE(String, staging_backend, "local", "Blob staging backend (local | s3); s3 is opt-in", 0) \ diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index ecc586c4454e8..c4d1db292cba0 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -600,6 +600,8 @@ String describeManifestPutGiveUp(const GaveUp & gave_up) if (lease) return "was not sent: the mount lease has too little time left, so writes are paused"; return "was not sent: the request window ran out before the first attempt"; + case GaveUp::Why::Attempts: + throw Exception(ErrorCodes::LOGICAL_ERROR, "A single part write is never capped by a decision count"); case GaveUp::Why::Unresolved: if (gave_up.sent_any) return fmt::format( diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp index aba6503d21a38..a6f3ef4ba9f73 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp @@ -2176,6 +2176,8 @@ MountRenewResult MountLeaseRenewer::renewOn( case GaveUp::Why::Unresolved: classification = MountRenewTerminalClassification::Unresolved; break; + case GaveUp::Why::Attempts: + throw Exception(ErrorCodes::LOGICAL_ERROR, "A mount renewal write is never capped by a decision count"); } markMountRenewTermination(classification); result.failure = makeCasWriteRetryLaterExceptionPtr(fmt::format( diff --git a/src/Disks/tests/cas_test_helpers.h b/src/Disks/tests/cas_test_helpers.h index 84faee2796fae..4038ea9fe8366 100644 --- a/src/Disks/tests/cas_test_helpers.h +++ b/src/Disks/tests/cas_test_helpers.h @@ -132,6 +132,24 @@ inline String tokenText(const std::optional & token) namespace DB::Cas::tests { +/// The `DB::Exception` code `call` throws, -1 for any other exception, 0 when it returns. +inline int exceptionCodeOf(const std::function & call) +{ + try + { + call(); + } + catch (const DB::Exception & e) + { + return e.code(); + } + catch (...) + { + return -1; + } + return 0; +} + /// A `CasRequests` over an always-open fence, for a fixture that has a backend but no mounted pool. /// Every operation admitted from it holds a reference to it, so it must be named and outlive them. inline DB::Cas::CasRequests openRequestsForTest(DB::Cas::BackendPtr backend) diff --git a/src/Disks/tests/cas_time_taking_backend.h b/src/Disks/tests/cas_time_taking_backend.h new file mode 100644 index 0000000000000..5ff2e92e992d2 --- /dev/null +++ b/src/Disks/tests/cas_time_taking_backend.h @@ -0,0 +1,257 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace DB::Cas::tests +{ + +/// A clock a test moves by exact amounts. A sleep moves it by one millisecond more than it was asked +/// for, because a jittered pause can be zero and a clock that stands still never closes a window. +/// Held by `shared_ptr`: a pool keeps the closures and can outlive the test's frame. +class ManualClock +{ +public: + explicit ManualClock(uint64_t start_ms = 1'000'000) : now_ms(start_ms) {} + + uint64_t now() const { return now_ms.load(); } + void advance(uint64_t ms) { now_ms.fetch_add(ms); } + + static std::function nowFnOf(std::shared_ptr owned) + { + return [clock = std::move(owned)] { return clock->now(); }; + } + static std::function sleepFnOf(std::shared_ptr owned) + { + return [clock = std::move(owned)](uint64_t ms) { clock->advance(ms + 1); }; + } + +private: + std::atomic now_ms; +}; + +/// A store in which a chosen request takes time: the clock the request engine reads moves INSIDE the +/// request, after the engine bound its policy and before the answer comes back. An instantaneous store +/// cannot show a deadline that was fixed before a long step and is consulted after it. +class TimeTakingBackend final : public CountingBackend +{ +public: + enum class Verb : uint8_t { Read, Head, List, Write, Remove, Publish, Stream }; + enum class Ending : uint8_t + { + Answered, + /// The request fails with a timeout and changes nothing. + LostBeforeLanding, + /// The request takes effect and its response is lost. + LostAfterLanding, + }; + + /// One request as the store received it. + struct Seen + { + Verb verb; + String key; + uint64_t at_ms; + }; + + void useClock(std::shared_ptr clock_) + { + std::lock_guard lock(rules_mutex); + clock = std::move(clock_); + } + + /// The clock the journal stamps requests with. + void stampWith(std::function now_ms_) + { + std::lock_guard lock(rules_mutex); + now_ms = std::move(now_ms_); + } + + /// Each of the next `times` matching requests takes `takes_ms` and then ends as `ending`. + void arm(Verb verb, std::function matches, uint64_t takes_ms, size_t times = 1, + Ending ending = Ending::Answered) + { + armWith(verb, std::move(matches), [this, takes_ms] + { + std::shared_ptr current; + { + std::lock_guard lock(rules_mutex); + current = clock; + } + if (current && takes_ms) + current->advance(takes_ms); + }, times, ending); + } + + /// `while_in_flight` runs inside each of the next `times` matching requests, on the requesting + /// thread and with no lock of this backend held: it is what happens elsewhere while the request + /// is in flight, and it may send requests of its own. + void armWith(Verb verb, std::function matches, std::function while_in_flight, + size_t times = 1, Ending ending = Ending::Answered) + { + std::lock_guard lock(rules_mutex); + rules.push_back(Rule{verb, std::move(matches), std::move(while_in_flight), times, ending}); + } + + /// The keys of the requests a rule applied to, in order. + std::vector slowedKeys() const + { + std::lock_guard lock(rules_mutex); + return slowed_keys; + } + + /// Every request received, in order, a refused or failed one included. + std::vector seen() const + { + std::lock_guard lock(rules_mutex); + return seen_requests; + } + + /// Requests of `verb` to `key` received at or after position `from` of the journal. + size_t seenSince(size_t from, Verb verb, const String & key) const + { + std::lock_guard lock(rules_mutex); + size_t count = 0; + for (size_t i = from; i < seen_requests.size(); ++i) + if (seen_requests[i].verb == verb && seen_requests[i].key == key) + ++count; + return count; + } + + size_t seenCount() const + { + std::lock_guard lock(rules_mutex); + return seen_requests.size(); + } + + /// Publications REQUESTED for `key`, whether or not they stored anything. + uint64_t publicationsOf(const String & key) const + { + std::lock_guard lock(rules_mutex); + const auto it = publications.find(key); + return it == publications.end() ? 0 : it->second; + } + + uint64_t serverSideCopiesOf(const String & key) const + { + std::lock_guard lock(rules_mutex); + const auto it = server_side_copies.find(key); + return it == server_side_copies.end() ? 0 : it->second; + } + + std::optional read(const String & key, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::Read, key), "read"); + return CountingBackend::read(key, access); + } + + std::optional head(const String & key, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::Head, key), "head"); + return CountingBackend::head(key, access); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::List, prefix), "list"); + return CountingBackend::list(prefix, cursor, limit, access); + } + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + const Ending ending = spend(Verb::Write, key).value_or(Ending::Answered); + failIfLostBeforeLanding(ending, "write"); + auto answer = CountingBackend::write(key, bytes, expected_value, access); + if (ending == Ending::LostAfterLanding) + throw Poco::TimeoutException("TimeTakingBackend: the write was applied and its response was lost"); + return answer; + } + + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::Remove, key), "remove"); + return CountingBackend::remove(key, expected_value, access); + } + + std::unique_ptr stream(const String & key, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::Stream, key), "stream"); + return CountingBackend::stream(key, access); + } + + void publish(const BlobPublishRequest & request, TransportAccess & access) override + { + { + std::lock_guard lock(rules_mutex); + ++publications[request.destination_key]; + if (std::holds_alternative(request.publication)) + ++server_side_copies[request.destination_key]; + } + const Ending ending = spend(Verb::Publish, request.destination_key).value_or(Ending::Answered); + if (ending == Ending::LostBeforeLanding) + throw Poco::TimeoutException("TimeTakingBackend: the publication timed out and stored nothing"); + CountingBackend::publish(request, access); + if (ending == Ending::LostAfterLanding) + throw Poco::TimeoutException("TimeTakingBackend: the publication was stored and its response was lost"); + } + +private: + struct Rule + { + Verb verb; + std::function matches; + std::function while_in_flight; + size_t remaining; + Ending ending; + }; + + static void failIfLostBeforeLanding(std::optional ending, const char * verb) + { + if (ending == Ending::LostBeforeLanding) + throw Poco::TimeoutException(String("TimeTakingBackend: the ") + verb + " timed out"); + } + + std::optional spend(Verb verb, const String & key) + { + std::function while_in_flight; + Ending ending = Ending::Answered; + { + std::lock_guard lock(rules_mutex); + seen_requests.push_back(Seen{verb, key, now_ms ? now_ms() : 0}); + auto rule = rules.begin(); + for (; rule != rules.end(); ++rule) + if (rule->verb == verb && rule->remaining != 0 && rule->matches(key)) + break; + if (rule == rules.end()) + return std::nullopt; + --rule->remaining; + slowed_keys.push_back(key); + while_in_flight = rule->while_in_flight; + ending = rule->ending; + } + while_in_flight(); + return ending; + } + + mutable std::mutex rules_mutex; + std::shared_ptr clock; + std::function now_ms; + std::vector rules; + std::vector slowed_keys; + std::vector seen_requests; + std::map publications; + std::map server_side_copies; +}; + +} diff --git a/src/Disks/tests/gtest_cas_pool_meta.cpp b/src/Disks/tests/gtest_cas_pool_meta.cpp index bd43763bafafa..0eb79caff1320 100644 --- a/src/Disks/tests/gtest_cas_pool_meta.cpp +++ b/src/Disks/tests/gtest_cas_pool_meta.cpp @@ -34,7 +34,7 @@ CasRequests makeRequests(BackendPtr backend, FakeClock & clock, Fence fence = Fe } -TEST(CASPoolMeta, AdmitOrValidateEndsAtTheDeadlineUnderPerpetualConflict) +TEST(CASPoolMeta, AdmitOrValidateEndsAfterAHundredDecisionsUnderPerpetualConflict) { FakeClock clock; auto backend = std::make_shared(); @@ -53,10 +53,12 @@ TEST(CASPoolMeta, AdmitOrValidateEndsAtTheDeadlineUnderPerpetualConflict) const String key = layout.poolMetaKey(); EXPECT_TRUE(clock.sleeps.empty()); /// nothing paced yet -- the trailing check below is about THIS call bool inside_hook = false; + size_t decisions = 0; backend->onBeforeWrite(key, [&] { if (inside_hook) return; + ++decisions; inside_hook = true; auto hook_requests = DB::Cas::tests::openRequestsForTest(BackendPtr(backend)); auto hook_op = hook_requests.admit(); @@ -65,18 +67,17 @@ TEST(CASPoolMeta, AdmitOrValidateEndsAtTheDeadlineUnderPerpetualConflict) inside_hook = false; }); - /// `orThrow`'s `GaveUp{Deadline}` arm throws exactly `NETWORK_ERROR` (`throwCasWriteRetryLater`), - /// pinning the deadline outcome apart from the two failures a wrong migration could also throw as - /// a `DB::Exception` here: `LOGICAL_ERROR` (the absence branch) or `BAD_ARGUMENTS` (`allow_new` - /// plumbing regressed). + /// The cap text sets this apart from the two failures a wrong migration could also throw here: + /// `LOGICAL_ERROR` (the absence branch) or `BAD_ARGUMENTS` (`allow_new` plumbing regressed). auto admit_op = requests.admit(); - expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 decisions", [&] { (void)PoolMeta::createOrValidate( admit_op, layout, 256, /*gc_shards=*/1, BlobHashAlgo::XXH3_128, /*allow_new=*/true, /*allow_mint=*/false); }); - /// Bounded by the deadline, not a live-lock: it paced its retries rather than spinning. + EXPECT_EQ(decisions, kCasMaxDecisions); + /// It paced its decisions rather than spinning. EXPECT_FALSE(clock.sleeps.empty()); } diff --git a/src/Disks/tests/gtest_cas_requests.cpp b/src/Disks/tests/gtest_cas_requests.cpp index 3c5004c539423..7b31f39ba281d 100644 --- a/src/Disks/tests/gtest_cas_requests.cpp +++ b/src/Disks/tests/gtest_cas_requests.cpp @@ -147,19 +147,17 @@ TEST(CASRetry, PoliciesAreShapedAsSpecified) { const uint64_t now = 1'000'000; EXPECT_EQ(Retry::standard().bind(now, kEngineTestWindowMs).deadline_ms, now + 90'000); - EXPECT_FALSE(Retry::standard().bind(now, kEngineTestWindowMs).lease_bound); + EXPECT_NE(Retry::standard().bind(now, kEngineTestWindowMs).source, Retry::Bound::Source::Lease); EXPECT_FALSE(Retry::standard().single_attempt); EXPECT_TRUE(Retry::once().single_attempt); const Retry::Bound lease = Retry::untilLeaseSafe(now + 10'000, 2'000).bind(now, kEngineTestWindowMs); EXPECT_EQ(lease.deadline_ms, now + 8'000); - EXPECT_TRUE(lease.lease_bound); + EXPECT_EQ(lease.source, Retry::Bound::Source::Lease); EXPECT_EQ(Retry::within(1'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 1'000); } -/// A frozen policy is ONE absolute deadline: time passing does not buy a later one, freezing again -/// cannot extend it, and the lease bound still wins when it is the smaller of the two -- which is what -/// keeps `GaveUp::Source` able to say which bound refused. -TEST(CASRetry, AFrozenPolicyIsOneDeadlineAndTheLeaseStillWins) +/// A cap later than the request's own window leaves the window. +TEST(CASRetry, AnOutsideCapLaterThanTheWindowLeavesTheWindow) { FakeClock clock; auto backend = std::make_shared(); @@ -176,8 +174,14 @@ TEST(CASRetry, AFrozenPolicyIsOneDeadlineAndTheLeaseStillWins) EXPECT_EQ(frozen.asSingleAttempt().policy_deadline_ms, frozen.policy_deadline_ms); EXPECT_TRUE(frozen.asSingleAttempt().single_attempt); - clock.now += 50'000; - EXPECT_EQ(op.freeze(frozen).policy_deadline_ms, frozen.policy_deadline_ms); +/// A bound names the bound that set its deadline; a tie goes to the request window, then to the outside cap. +TEST(CASRetry, BindNamesTheExactSourceOfItsDeadline) +{ + using Source = Retry::Bound::Source; + const uint64_t now = 1'000'000; + EXPECT_EQ(Retry::standard().bind(now, kEngineTestWindowMs).source, Source::RequestWindow); + EXPECT_EQ(Retry::standard().cappedAt(now + 10'000).bind(now, kEngineTestWindowMs).source, Source::OutsideCap); + EXPECT_EQ(Retry::untilLeaseSafe(now + 10'000, 2'000).bind(now, kEngineTestWindowMs).source, Source::Lease); const Retry::Bound leashed = op.freeze(Retry::untilLeaseSafe(start + 10'000, 2'000)).bind(clock.now, kEngineTestWindowMs); EXPECT_EQ(leashed.deadline_ms, start + 8'000); @@ -274,6 +278,227 @@ TEST(CASWriteResult, OrThrowMapsEveryAlternative) [&] { orThrow(WriteResult{unresolved}, "t"); }); } +TEST(CASRequests, GaveUpAttemptsThrowsRetryLaterWithTheDecisionCount) +{ + const GaveUp capped{ + .why = GaveUp::Why::Attempts, .deadline_source = GaveUp::Source::Policy, + .sent_any = true, .last_seen = NotObserved{}}; + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 decisions", + [&] { orThrow(WriteResult{capped}, "t"); }); +} + +TEST(CASRequests, ThrowDidNotConvergeNamesItsUnit) +{ + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "casUpdate: did not converge after 7 submissions", + [&] { throwDidNotConverge("casUpdate", 7, "submissions"); }); +} + +TEST(CASRequests, PauseBeforeRedecideSleepsWithTheSmallestValidWindow) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + const GaveUp unresolved{ + .why = GaveUp::Why::Unresolved, .deadline_source = GaveUp::Source::Policy, + .sent_any = true, .last_seen = NotObserved{}}; + /// Two envelopes plus 1 ms is the smallest window a write accepts; a 2 ms pause must not need more. + const Retry policy = Retry::within(2 * requests.attemptReservationMs() + 1); + + EXPECT_FALSE(op.pauseAfterUnresolvedWrite(2, unresolved, policy).has_value()); + ASSERT_EQ(clock.sleeps.size(), 1u); + EXPECT_EQ(clock.sleeps.front(), 2u); +} + +namespace +{ + +GaveUp unresolvedAfterOneSend() +{ + return GaveUp{.why = GaveUp::Why::Unresolved, .deadline_source = GaveUp::Source::Policy, + .sent_any = true, .last_seen = NotObserved{}, .attempts_sent = 1}; +} + +/// The give-up `pauseAfterUnresolvedWrite` returned for a 2 ms pause, which must not have slept. +GaveUp refusedPause(CasOperation & op, FakeClock & clock, const Retry & policy) +{ + const std::optional given_up = op.pauseAfterUnresolvedWrite(2, unresolvedAfterOneSend(), policy); + EXPECT_TRUE(clock.sleeps.empty()); + if (!given_up || !std::holds_alternative(*given_up)) + { + ADD_FAILURE() << "the pause was not refused"; + return unresolvedAfterOneSend(); + } + return std::get(*given_up); +} + +} + +TEST(CASRequests, PauseBeforeRedecideRefusesAPauseThatEndsAfterTheOutsideCap) +{ + FakeClock clock; + auto requests = makeRequests(std::make_shared(), clock); + auto op = requests.admit(); + + const GaveUp gave_up = refusedPause(op, clock, Retry::standard().cappedAt(clock.now + 1)); + EXPECT_EQ(gave_up.why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up.deadline_source, GaveUp::Source::Policy); + EXPECT_EQ(gave_up.attempts_sent, 1u); +} + +TEST(CASRequests, PauseBeforeRedecideRefusesAPauseThatEndsAfterTheExplicitLease) +{ + FakeClock clock; + auto requests = makeRequests(std::make_shared(), clock); + auto op = requests.admit(); + + const GaveUp gave_up = refusedPause(op, clock, Retry::untilLeaseSafe(clock.now + 1, /*margin=*/0)); + EXPECT_EQ(gave_up.why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up.deadline_source, GaveUp::Source::Lease); +} + +/// A lost fence names the bound a request would be given now, as every request does: the lease only +/// when it ends before the window. +TEST(CASRequests, PauseBeforeRedecideRefusesAfterAFenceLossAndNamesTheBoundARequestWouldGet) +{ + FakeClock clock; + Fence lost{ + [] { return uint64_t(1); }, + [](uint64_t, uint64_t) { return Fence::Admit::LostOrRearmed; }, + [](uint64_t) {}}; + auto requests = makeRequests(std::make_shared(), clock, lost); + auto op = requests.admit(); + + const GaveUp under_window = refusedPause(op, clock, Retry::standard()); + EXPECT_EQ(under_window.why, GaveUp::Why::FenceLost); + EXPECT_EQ(under_window.deadline_source, GaveUp::Source::Policy); + + const GaveUp under_near_lease = refusedPause(op, clock, Retry::untilLeaseSafe(clock.now + 1'000, /*margin=*/0)); + EXPECT_EQ(under_near_lease.why, GaveUp::Why::FenceLost); + EXPECT_EQ(under_near_lease.deadline_source, GaveUp::Source::Lease); + + const GaveUp under_far_lease = refusedPause(op, clock, Retry::untilLeaseSafe(clock.now + 10 * kEngineTestWindowMs, /*margin=*/0)); + EXPECT_EQ(under_far_lease.why, GaveUp::Why::FenceLost); + EXPECT_EQ(under_far_lease.deadline_source, GaveUp::Source::Policy); +} + +/// The mount lease has less time left than the pause: the call ends unslept and names the lease. A +/// shorter pause still sleeps. +TEST(CASRequests, PauseBeforeRedecideRefusesAPauseLongerThanTheMountLeaseLeft) +{ + FakeClock clock; + const uint64_t lease_left_ms = 1'000; + Fence short_lease{ + [] { return uint64_t{0}; }, + [&](uint64_t, uint64_t needed_ms) { return needed_ms >= lease_left_ms ? Fence::Admit::NoBudget : Fence::Admit::Ok; }, + [](uint64_t) {}}; + auto requests = makeRequests(std::make_shared(), clock, short_lease); + auto op = requests.admit(); + + const std::optional given_up = op.pauseAfterUnresolvedWrite(lease_left_ms, unresolvedAfterOneSend(), Retry::standard()); + EXPECT_TRUE(clock.sleeps.empty()); + ASSERT_TRUE(given_up.has_value()); + const auto * gave_up = std::get_if(&*given_up); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Lease); + EXPECT_EQ(gave_up->attempts_sent, 1u); + + EXPECT_FALSE(op.pauseAfterUnresolvedWrite(lease_left_ms - 1, unresolvedAfterOneSend(), Retry::standard()).has_value()); + EXPECT_EQ(clock.sleeps, std::vector{lease_left_ms - 1}); +} + +/// A pause that fits exactly ends on the limit, and the call ends there instead of deciding again. +TEST(CASRequests, PauseBeforeRedecideEndingOnTheOutsideCapEndsTheCall) +{ + FakeClock clock; + auto requests = makeRequests(std::make_shared(), clock); + auto op = requests.admit(); + + const std::optional given_up + = op.pauseAfterUnresolvedWrite(50, unresolvedAfterOneSend(), Retry::standard().cappedAt(clock.now + 50)); + EXPECT_EQ(clock.sleeps.size(), 1u); + ASSERT_TRUE(given_up.has_value()); + const auto * gave_up = std::get_if(&*given_up); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); +} + +TEST(CASRequests, PauseBeforeRedecideEndingOnTheExplicitLeaseEndsTheCall) +{ + FakeClock clock; + auto requests = makeRequests(std::make_shared(), clock); + auto op = requests.admit(); + + const std::optional given_up + = op.pauseAfterUnresolvedWrite(50, unresolvedAfterOneSend(), Retry::untilLeaseSafe(clock.now + 50, /*margin=*/0)); + EXPECT_EQ(clock.sleeps.size(), 1u); + ASSERT_TRUE(given_up.has_value()); + const auto * gave_up = std::get_if(&*given_up); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Lease); +} + +namespace +{ + +/// One lost race, then a pause that sleeps 10 s past what it asked for. `policy_ending_at` builds the +/// policy from the instant the room for one write and one conflict pause ends. Returns the result and +/// how many times `decide` ran. +std::pair raceThenOversleep(const std::function & policy_ending_at) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto rival_requests = makeRequests(backend, clock); + auto rival = rival_requests.admit(); + requests.setSleepFnForTest([&](uint64_t ms) { clock.sleepFn()(ms + 10'000); }); + bool staged = false; + backend->onBeforeWrite("k", [&] + { + if (staged) + return; + staged = true; + orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + }); + + int decisions = 0; + auto op = requests.admit(); + const Retry policy = policy_ending_at(clock.now + 2 * requests.attemptReservationMs() + 1'000); + WriteResult result = op.readModifyWrite("k", + [&](const std::optional &) -> std::optional + { + ++decisions; + return String("mine"); + }, + policy); + return {std::move(result), decisions}; +} + +} + +TEST(CASRequests, ReadModifyWriteWakingPastTheOutsideCapRunsNoSecondDecide) +{ + const auto [result, decisions] = raceThenOversleep([](uint64_t end) { return Retry::standard().cappedAt(end); }); + EXPECT_EQ(decisions, 1); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); +} + +TEST(CASRequests, ReadModifyWriteWakingPastTheExplicitLeaseRunsNoSecondDecide) +{ + const auto [result, decisions] = raceThenOversleep([](uint64_t end) { return Retry::untilLeaseSafe(end, /*margin=*/0); }); + EXPECT_EQ(decisions, 1); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Lease); +} + TEST(CASFence, OpenFenceAdmitsEverythingAndNeverMoves) { Fence f = Fence::open(); @@ -645,18 +870,18 @@ TEST(CASRetry, BindSaturatesAndLeavesAnEqualLeaseOffTheLeaseSource) /// A window one short of the whole range, so any `now` above 1 overflows a naive addition. EXPECT_EQ(Retry::within(largest - 1).bind(2, kEngineTestWindowMs).deadline_ms, largest); EXPECT_EQ(Retry::within(largest - 1).bind(1, kEngineTestWindowMs).deadline_ms, largest); - EXPECT_FALSE(Retry::within(largest - 1).bind(2, kEngineTestWindowMs).lease_bound); + EXPECT_NE(Retry::within(largest - 1).bind(2, kEngineTestWindowMs).source, Retry::Bound::Source::Lease); const uint64_t now = 1'000'000; /// The lease bound lands exactly on the policy deadline. The lease is taken only when it is /// STRICTLY smaller, so the tie belongs to the policy and `GaveUp` will not name the lease. const Retry::Bound tie = Retry::untilLeaseSafe(now + 92'000, 2'000).bind(now, kEngineTestWindowMs); EXPECT_EQ(tie.deadline_ms, now + 90'000); - EXPECT_FALSE(tie.lease_bound); + EXPECT_NE(tie.source, Retry::Bound::Source::Lease); const Retry::Bound lease = Retry::untilLeaseSafe(now + 91'999, 2'000).bind(now, kEngineTestWindowMs); EXPECT_EQ(lease.deadline_ms, now + 89'999); - EXPECT_TRUE(lease.lease_bound); + EXPECT_EQ(lease.source, Retry::Bound::Source::Lease); } TEST(CASRetrySpacing, UntilDefinitiveHasNoDeadlineAndSpacesItsAttempts) @@ -670,7 +895,7 @@ TEST(CASRetrySpacing, UntilDefinitiveHasNoDeadlineAndSpacesItsAttempts) { const Retry::Bound bound = policy.bind(now, kEngineTestWindowMs); EXPECT_EQ(bound.deadline_ms, largest) << "now " << now; - EXPECT_FALSE(bound.lease_bound) << "now " << now; + EXPECT_NE(bound.source, Retry::Bound::Source::Lease) << "now " << now; } EXPECT_FALSE(Retry::standard().attempt_spacing_ms.has_value()); EXPECT_FALSE(Retry::untilLeaseSafe(2'000'000, 2'000).attempt_spacing_ms.has_value()); @@ -1510,6 +1735,94 @@ TEST(CASRequests, OnPresenceReportsMetaEvenWhenItHadToFetchTheBody) EXPECT_EQ(backend->getTotal(), 1u); } +TEST(CASRequests, AFenceLostDuringThePauseRunsNoSecondDecide) +{ + FakeClock clock; + auto backend = std::make_shared(); + bool lost = false; + Fence fence{ + [] { return uint64_t(1); }, + [&](uint64_t, uint64_t) { return lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }, + [&](uint64_t) {}}; + auto requests = makeRequests(backend, clock, fence); + auto rival_requests = makeRequests(backend, clock); + auto rival = rival_requests.admit(); + requests.setSleepFnForTest([&](uint64_t ms) + { + clock.sleepFn()(ms); + lost = true; + }); + + bool staged = false; + backend->onBeforeWrite("k", [&] + { + if (staged) + return; + staged = true; + orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + }); + + int decisions = 0; + auto op = requests.admit(); + WriteResult result = op.readModifyWrite("k", + [&](const std::optional &) -> std::optional + { + ++decisions; + return String("mine"); + }, + Retry::standard()); + + /// The conflict was informative, so the loop would decide again; the fence moved in the pause. + EXPECT_EQ(decisions, 1); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); +} + +TEST(CASRequests, AFenceLostDuringThePauseRunsNoSecondDecideOnPresence) +{ + FakeClock clock; + auto backend = std::make_shared(); + bool lost = false; + Fence fence{ + [] { return uint64_t(1); }, + [&](uint64_t, uint64_t) { return lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }, + [&](uint64_t) {}}; + auto requests = makeRequests(backend, clock, fence); + auto rival_requests = makeRequests(backend, clock); + auto rival = rival_requests.admit(); + requests.setSleepFnForTest([&](uint64_t ms) + { + clock.sleepFn()(ms); + lost = true; + }); + + bool staged = false; + backend->onBeforeWrite("k", [&] + { + if (staged) + return; + staged = true; + orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + }); + + int decisions = 0; + auto op = requests.admit(); + WriteResult result = op.readModifyWriteOnPresence("k", + [&](const std::optional &) -> std::optional + { + ++decisions; + return String("mine"); + }, + Retry::standard()); + + /// The conflict was informative, so the loop would decide again; the fence moved in the pause. + EXPECT_EQ(decisions, 1); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); +} + TEST(CASRequests, AmbiguousReplaceWhoseResolveShowsThePreconditionUnchangedIsReissued) { FakeClock clock; @@ -1832,7 +2145,7 @@ TEST(CASRequests, ReadModifyWriteLosesNoIncrementUnderContentionAndBoundsAHotKey ASSERT_TRUE(counted.has_value()); EXPECT_EQ(counted->bytes, "100"); /// every conflict re-decided against what the resolve read saw - /// A key rewritten under EVERY attempt is bounded by the deadline instead of looping forever. + /// A key rewritten under EVERY attempt is bounded by the decision cap instead of looping forever. FakeClock clock; auto hot = makeRequests(backend, clock); auto competitor = makeRequests(backend, clock); @@ -1852,7 +2165,7 @@ TEST(CASRequests, ReadModifyWriteLosesNoIncrementUnderContentionAndBoundsAHotKey WriteResult result = op.readModifyWrite("ctr", increment, Retry::standard()); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); - EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->why, GaveUp::Why::Attempts); EXPECT_TRUE(gave_up->sent_any); EXPECT_FALSE(clock.sleeps.empty()); /// it paced its retries rather than spinning } diff --git a/src/Disks/tests/gtest_cas_shared_deadline.cpp b/src/Disks/tests/gtest_cas_shared_deadline.cpp new file mode 100644 index 0000000000000..6d8a044bab552 --- /dev/null +++ b/src/Disks/tests/gtest_cas_shared_deadline.cpp @@ -0,0 +1,538 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +/// Each request of the engine binds its own window when it is sent. In the first two sections a first step +/// takes all but one millisecond of a window and succeeds, and the test checks that the next request +/// is still sent and the operation completes; its failure text carries what the first step used and +/// what a window shared with the next request would have left. The other sections check a lost +/// write's settlement and the caps on decisions and submissions. + +namespace DB::ErrorCodes +{ +extern const int NETWORK_ERROR; +} + +using namespace DB::Cas; +using DB::Cas::tests::ManualClock; +using DB::Cas::tests::TimeTakingBackend; +using DB::Cas::tests::idOf; + +namespace +{ + +using Verb = TimeTakingBackend::Verb; +using Ending = TimeTakingBackend::Ending; + +constexpr uint64_t kWindowMs = kDefaultRequestWindowMs; +/// What one attempt reserves on a disk with default settings: `cas_attempt_timeout_ms` 5000 and two +/// connect caps of 1000. A read reserves one, a write two. +constexpr uint64_t kEnvelopeMs = 7'000; +constexpr uint64_t kFirstStepMs = kWindowMs - 1; +/// The longest pause `Retry::backoff` draws. +constexpr uint64_t kMaxBackoffMs = 5'000; + +std::function exactly(const String & wanted) +{ + return [wanted](const String & key) { return key == wanted; }; +} + +/// Runs `step` and returns the text of whatever it threw, or nothing. +std::optional failureOf(const std::function & step) +{ + try + { + step(); + } + catch (...) + { + return DB::getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + return std::nullopt; +} + +String orNone(const std::optional & failure) +{ + return failure ? *failure : String("none"); +} + +/// The two numbers of a case, as text for a failure message. `sent` counts the requests of the next +/// step the store received after the first step ended. +String sharedWindow(uint64_t window_ms, uint64_t started_ms, uint64_t first_step_ended_ms, const String & next, size_t sent) +{ + const uint64_t used_ms = first_step_ended_ms - started_ms; + const uint64_t left_ms = window_ms > used_ms ? window_ms - used_ms : 0; + return fmt::format( + "\n first step: {} ms of the shared {} ms\n next ({}): {} ms of {} left, {}\n ", + used_ms, window_ms, next, left_ms, window_ms, + sent == 0 ? String("refused unsent, 0 attempt(s)") : fmt::format("sent {} time(s)", sent)); +} + +/// Requests of `verb` to `key` that reached the store at or after `from_ms`. +size_t sentSince(const TimeTakingBackend & backend, uint64_t from_ms, Verb verb, const String & key) +{ + size_t count = 0; + for (const TimeTakingBackend::Seen & request : backend.seen()) + if (request.verb == verb && request.key == key && request.at_ms >= from_ms) + ++count; + return count; +} + +String whyOf(GaveUp::Why why) +{ + switch (why) + { + case GaveUp::Why::Deadline: return "deadline"; + case GaveUp::Why::FenceLost: return "fence lost"; + case GaveUp::Why::Unresolved: return "unresolved"; + case GaveUp::Why::Attempts: return "attempts"; + } + return "unknown"; +} + +String outcomeOf(const WriteResult & result) +{ + if (std::holds_alternative(result)) + return "committed"; + if (std::holds_alternative(result)) + return "conflict"; + if (std::holds_alternative(result)) + return "declined"; + if (const auto * refused = std::get_if(&result)) + return "refused by the store: " + refused->message; + const GaveUp & gave_up = std::get(result); + return fmt::format("gave up ({}, {} bound) after {} attempt(s)", whyOf(gave_up.why), + gave_up.deadline_source == GaveUp::Source::Lease ? "lease" : "policy", gave_up.attempts_sent); +} + +/// A request plane over an open fence, with the reservation of a real disk and a clock the test moves. +struct Plane +{ + std::shared_ptr backend = std::make_shared(); + std::shared_ptr clock = std::make_shared(); + CasRequests requests; + CasOperation op; + + explicit Plane(CasHotKeys * lane = nullptr, Fence fence = Fence::open()) + : requests(backend, std::move(fence), ManualClock::nowFnOf(clock), ManualClock::sleepFnOf(clock), lane, kWindowMs) + , op(requests.admit()) + { + requests.setAttemptReservationForTest(kEnvelopeMs); + backend->stampWith(ManualClock::nowFnOf(clock)); + } + + void seed(const String & key, const String & bytes) + { + ASSERT_TRUE(std::holds_alternative(op.create(key, bytes, Retry::standard()))); + } + + String bytesOf(const String & key) + { + const std::optional object = op.read(key, Retry::standard()); + return object ? object->bytes : String(""); + } + + /// The next `verb` of `key` takes all but one millisecond of a window. + void slowDown(Verb verb, const String & key, Ending ending = Ending::Answered) + { + backend->armWith(verb, exactly(key), [clock_ = clock] { clock_->advance(kFirstStepMs); }, /*times=*/1, ending); + } + + /// The next `times` requests of `verb` to `key` each take `ms` and end as `ending`. + void takeTime(Verb verb, const String & key, uint64_t ms, size_t times, Ending ending = Ending::Answered) + { + backend->armWith(verb, exactly(key), [clock_ = clock, ms] { clock_->advance(ms); }, times, ending); + } + + /// Counts the pauses of the plane's own operation; the clock still moves as before. + void countPauses(size_t & pauses) + { + requests.setSleepFnForTest([clock_ = clock, &pauses](uint64_t ms) + { + ++pauses; + clock_->advance(ms + 1); + }); + } +}; + +/// A second writer on the plane's store. Inside each of the plane's next `times` requests of `verb` to +/// `key` it replaces the object, so that request meets a moved precondition. +struct Rival +{ + Rival(Plane & plane, Verb verb, const String & key_, size_t times) + : key(key_) + , requests(plane.backend, Fence::open(), ManualClock::nowFnOf(plane.clock), ManualClock::sleepFnOf(plane.clock), + nullptr, kWindowMs) + , op(requests.admit()) + { + requests.setAttemptReservationForTest(kEnvelopeMs); + plane.backend->armWith(verb, [this](const String & k) { return k == key && !inside; }, [this] { move(); }, times); + } + + void move() + { + inside = true; + if (const auto current = op.read(key, Retry::once())) + (void)op.replace(key, current->bytes + "r", current->etag, Retry::once()); + else + (void)op.create(key, "r", Retry::once()); + inside = false; + ++moves; + if (after_move) + after_move(); + } + + String key; + bool inside = false; + size_t moves = 0; + /// Runs inside the plane's request, after the move. + std::function after_move; + CasRequests requests; + CasOperation op; +}; + +/// --------------------------------------------------------------------------------------------- +/// The request engine: every request binds its own window when it is sent. +/// --------------------------------------------------------------------------------------------- + +TEST(CASSharedDeadline, ReadModifyWriteSendsItsWriteAfterASlowRead) +{ + Plane plane; + plane.seed("k", "v1"); + plane.slowDown(Verb::Read, "k"); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.readModifyWrite( + "k", [](const std::optional &) -> std::optional { return "v2"; }, Retry::standard()); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_TRUE(std::holds_alternative(result)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the conditional write", sentSince(*plane.backend, first_ended_ms, Verb::Write, "k")) + << "result: " << outcomeOf(result); + EXPECT_EQ(plane.bytesOf("k"), "v2"); +} + +/// The same verb when the caller's `decide` takes the time: a decision may read other keys under +/// windows of their own. +TEST(CASSharedDeadline, ReadModifyWriteSendsItsWriteAfterASlowDecide) +{ + Plane plane; + plane.seed("k", "v1"); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional &) -> std::optional + { + plane.clock->advance(kFirstStepMs); + return "v2"; + }, Retry::standard()); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_TRUE(std::holds_alternative(result)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the conditional write", sentSince(*plane.backend, first_ended_ms, Verb::Write, "k")) + << "result: " << outcomeOf(result); + EXPECT_EQ(plane.bytesOf("k"), "v2"); +} + +TEST(CASSharedDeadline, ReadModifyWriteOnPresenceSendsItsWriteAfterASlowHead) +{ + Plane plane; + plane.slowDown(Verb::Head, "k"); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.readModifyWriteOnPresence( + "k", [](const std::optional &) -> std::optional { return "created"; }, Retry::standard()); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_TRUE(std::holds_alternative(result)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the create", sentSince(*plane.backend, first_ended_ms, Verb::Write, "k")) + << "result: " << outcomeOf(result); + EXPECT_EQ(plane.bytesOf("k"), "created"); +} + +TEST(CASSharedDeadline, RemoveCurrentSendsItsRemoveAfterASlowHead) +{ + Plane plane; + plane.seed("k", "v1"); + plane.slowDown(Verb::Head, "k"); + + const uint64_t started_ms = plane.clock->now(); + std::optional removed; + const auto failure = failureOf([&] { removed = plane.op.removeCurrent("k", Retry::standard()); }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_EQ(removed, std::optional(Removal::Removed)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the conditional delete", sentSince(*plane.backend, first_ended_ms, Verb::Remove, "k")) + << "error: " << orNone(failure); +} + +/// Verbs called one after another with `Retry::standard` are bound at their own call, so nothing is shared. +TEST(CASSharedDeadline, EachVerbCalledWithTheStandardPolicyStartsItsOwnWindow) +{ + Plane plane; + plane.seed("k", "v1"); + plane.slowDown(Verb::Head, "k"); + plane.slowDown(Verb::Read, "k"); + + const uint64_t started_ms = plane.clock->now(); + const std::optional meta = plane.op.head("k", Retry::standard()); + const std::optional object = plane.op.read("k", Retry::standard()); + ASSERT_TRUE(meta.has_value()); + ASSERT_TRUE(object.has_value()); + const WriteResult replaced = plane.op.replace("k", "v2", object->etag, Retry::standard()); + + EXPECT_GT(plane.clock->now() - started_ms, kWindowMs); + EXPECT_TRUE(std::holds_alternative(replaced)) << outcomeOf(replaced); +} + +/// A slow page costs the next one nothing. +TEST(CASSharedDeadline, ForEachListedKeyGivesEachPageItsOwnWindow) +{ + Plane plane; + for (int i = 0; i < 5; ++i) + plane.seed("list/" + std::to_string(i), "x"); + plane.backend->armWith(Verb::List, exactly("list/"), [clock = plane.clock] { clock->advance(kFirstStepMs); }, /*times=*/3); + + const uint64_t started_ms = plane.clock->now(); + std::vector keys; + plane.op.forEachListedKey("list/", [&](const ListedKey & listed) + { + keys.push_back(listed.key); + return true; + }, Retry::standard(), /*page_limit=*/2); + + EXPECT_EQ(keys.size(), 5u); + EXPECT_GT(plane.clock->now() - started_ms, 2 * kWindowMs) << "the pages were not slow"; +} + +/// A stream's window bounds only its open; the body is read under no deadline. +TEST(CASSharedDeadline, StreamBodyIsNotMeasuredAgainstTheWindowOfItsOpen) +{ + Plane plane; + const String body(4096, 'b'); + plane.seed("big", body); + plane.backend->setStreamChunkForTest(1024); + plane.slowDown(Verb::Stream, "big"); + + std::unique_ptr stream = plane.op.stream("big", Retry::standard()); + ASSERT_TRUE(stream); + plane.clock->advance(10 * kWindowMs); + String read; + DB::readStringUntilEOF(read, *stream); + EXPECT_EQ(read, body); +} + +/// --------------------------------------------------------------------------------------------- +/// A write whose response is lost: the settling read is a request with its own window. +/// --------------------------------------------------------------------------------------------- + +TEST(CASSharedDeadline, ALostWriteThatLandedIsProvenAfterItsWindow) +{ + Plane plane; + plane.takeTime(Verb::Write, "k", kWindowMs + 1, /*times=*/1, Ending::LostAfterLanding); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.create("k", "landed", Retry::standard()); + const uint64_t write_ended_ms = started_ms + kWindowMs + 1; + + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Write, "k"), 1u); + EXPECT_EQ(sentSince(*plane.backend, write_ended_ms, Verb::Read, "k"), 1u) << "result: " << outcomeOf(result); + const auto * committed = std::get_if(&result); + ASSERT_NE(committed, nullptr) << outcomeOf(result); + EXPECT_TRUE(committed->resolved_by_read); + EXPECT_EQ(plane.bytesOf("k"), "landed"); +} + +/// The settling read proves the write absent; resending the same bytes is still governed by the +/// write's own window, which is spent. +TEST(CASSharedDeadline, ALostWriteThatDidNotLandIsNotSentAgain) +{ + Plane plane; + plane.takeTime(Verb::Write, "k", kWindowMs + 1, /*times=*/1, Ending::LostBeforeLanding); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.create("k", "lost", Retry::standard()); + const uint64_t write_ended_ms = started_ms + kWindowMs + 1; + + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Write, "k"), 1u); + EXPECT_EQ(sentSince(*plane.backend, write_ended_ms, Verb::Read, "k"), 1u) << "result: " << outcomeOf(result); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_TRUE(std::holds_alternative(gave_up->last_seen)); + EXPECT_EQ(plane.bytesOf("k"), ""); +} + +/// The settling read fails until its own window ends, and the give-up names the bound of that read: +/// the policy's window, or an explicit lease that ends before it. +TEST(CASSharedDeadline, AFailingSettlementReportsItsOwnStop) +{ + const auto settle = [](std::optional lease_after_ms, GaveUp::Source expected) + { + SCOPED_TRACE(lease_after_ms ? "with an explicit lease" : "under the window"); + Plane plane; + const uint64_t started_ms = plane.clock->now(); + const Retry policy = lease_after_ms ? Retry::untilLeaseSafe(started_ms + *lease_after_ms, 0) : Retry::standard(); + plane.takeTime(Verb::Write, "k", kFirstStepMs, /*times=*/1, Ending::LostAfterLanding); + plane.takeTime(Verb::Read, "k", 1'000, /*times=*/1'000, Ending::LostBeforeLanding); + + const WriteResult result = plane.op.create("k", "landed", policy); + const uint64_t write_ended_ms = started_ms + kFirstStepMs; + const uint64_t read_end_ms = lease_after_ms ? started_ms + *lease_after_ms : write_ended_ms + kWindowMs; + + EXPECT_GT(sentSince(*plane.backend, write_ended_ms, Verb::Read, "k"), 1u) << outcomeOf(result); + EXPECT_GT(plane.clock->now(), read_end_ms - kEnvelopeMs - kMaxBackoffMs); + EXPECT_LE(plane.clock->now(), read_end_ms); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, expected); + EXPECT_EQ(gave_up->attempts_sent, 1u); + }; + settle(std::nullopt, GaveUp::Source::Policy); + /// The write is bound by the window, the settling read by the lease. + settle(kWindowMs + kWindowMs / 2, GaveUp::Source::Lease); +} + +/// A write that meets nothing but transport failures ends at its own window, measured from when it +/// was sent rather than from when its operation started. +TEST(CASSharedDeadline, ATransportStormEndsInsideTheRequestsOwnWindow) +{ + Plane plane; + plane.takeTime(Verb::Write, "k", 1'000, /*times=*/1'000, Ending::LostBeforeLanding); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional &) -> std::optional + { + plane.clock->advance(kWindowMs + 1); + return "v"; + }, Retry::standard()); + const uint64_t write_started_ms = started_ms + kWindowMs + 1; + + EXPECT_GT(sentSince(*plane.backend, write_started_ms, Verb::Write, "k"), 1u) << outcomeOf(result); + /// Every attempt, the resends included, starts only with room in the write's own window for itself and its + /// settling read. + for (const TimeTakingBackend::Seen & request : plane.backend->seen()) + if (request.verb == Verb::Write && request.key == "k" && request.at_ms >= write_started_ms) + EXPECT_LE(request.at_ms + 2 * kEnvelopeMs, write_started_ms + kWindowMs) + << "an attempt started " << request.at_ms - write_started_ms << " ms into the write's window"; + /// The write stops only when the next attempt, its settling read and the pause before it no longer fit. + EXPECT_GT(plane.clock->now() - write_started_ms, kWindowMs - 2 * kEnvelopeMs - kMaxBackoffMs); + EXPECT_LE(plane.clock->now() - write_started_ms, kWindowMs + kEnvelopeMs + kMaxBackoffMs); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_TRUE(gave_up->sent_any); +} + +/// --------------------------------------------------------------------------------------------- +/// Loops that decide again end on a count of decisions. +/// --------------------------------------------------------------------------------------------- + +TEST(CASSharedDeadline, ReadModifyWriteSucceedsOnTheHundredthDecision) +{ + Plane plane; + plane.seed("k", "v"); + Rival rival(plane, Verb::Write, "k", kCasMaxDecisions - 1); + size_t pauses = 0; + plane.countPauses(pauses); + + size_t decisions = 0; + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional & current) -> std::optional + { + ++decisions; + return current->bytes + "x"; + }, Retry::standard()); + + ASSERT_TRUE(std::holds_alternative(result)) << outcomeOf(result); + EXPECT_EQ(decisions, kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 1); + EXPECT_EQ(rival.moves, kCasMaxDecisions - 1); + EXPECT_EQ(std::get(result).attempts_sent, kCasMaxDecisions); +} + +TEST(CASSharedDeadline, ReadModifyWriteEndsAfterAHundredDecisions) +{ + Plane plane; + plane.seed("k", "v"); + Rival rival(plane, Verb::Write, "k", 10 * kCasMaxDecisions); + size_t pauses = 0; + plane.countPauses(pauses); + const uint64_t started_ms = plane.clock->now(); + + size_t decisions = 0; + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional & current) -> std::optional + { + ++decisions; + return current->bytes + "x"; + }, Retry::standard()); + + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, GaveUp::Why::Attempts); + EXPECT_EQ(gave_up->attempts_sent, kCasMaxDecisions); + EXPECT_EQ(decisions, kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 1); + /// Every write was settled: the plane's own reads are the first one and one per write. + EXPECT_EQ(rival.moves, kCasMaxDecisions); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Read, "k") - rival.moves, 1 + kCasMaxDecisions); + const auto * seen = std::get_if(&gave_up->last_seen); + ASSERT_NE(seen, nullptr); + EXPECT_EQ(seen->bytes, plane.bytesOf("k")); +} + +TEST(CASSharedDeadline, RemoveCurrentSucceedsOnTheHundredthDecision) +{ + Plane plane; + plane.seed("k", "v"); + Rival rival(plane, Verb::Remove, "k", kCasMaxDecisions - 1); + size_t pauses = 0; + plane.countPauses(pauses); + const uint64_t started_ms = plane.clock->now(); + + std::optional removed; + const auto failure = failureOf([&] { removed = plane.op.removeCurrent("k", Retry::standard()); }); + + EXPECT_EQ(removed, std::optional(Removal::Removed)) << "error: " << orNone(failure); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Head, "k"), kCasMaxDecisions); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Remove, "k"), kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 1); +} + +TEST(CASSharedDeadline, RemoveCurrentEndsAfterAHundredDecisions) +{ + Plane plane; + plane.seed("k", "v"); + Rival rival(plane, Verb::Remove, "k", 10 * kCasMaxDecisions); + size_t pauses = 0; + plane.countPauses(pauses); + const uint64_t started_ms = plane.clock->now(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "CAS remove of 'k': did not converge after 100 decisions", + [&] { (void)plane.op.removeCurrent("k", Retry::standard()); }); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Head, "k"), kCasMaxDecisions); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Remove, "k"), kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 1); + EXPECT_NE(plane.bytesOf("k"), ""); +} + From 31088ee89cfc68ede59363be10b43f41dc67abc1 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:27:49 +0100 Subject: [PATCH 02/47] Bound CAS loops above the engine by counts, not shared deadlines The hot-key lane, catalog updates and erases, namespace life and drop, the blob publication loop and the copy-source confirm poll no longer freeze one deadline for the whole loop. Each request binds its own window. The loops end at count caps (100 decisions or submissions, 8 blob publications); the confirm poll's deadline only decides whether another pass starts. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressed/Backend/CasHotKeys.cpp | 17 +- .../ContentAddressed/Backend/CasHotKeys.h | 6 +- .../Gc/CatalogLifecycleReconciler.h | 2 +- .../ContentAddressed/Parts/PartFolderAccess.h | 3 +- .../ContentAddressed/Pool/CasPartWriteTxn.cpp | 38 +- .../ContentAddressed/Pool/CasPool.cpp | 11 +- .../ContentAddressed/Pool/CasPool.h | 14 +- .../ContentAddressed/Pool/CasRefCatalog.cpp | 31 +- .../ContentAddressed/Pool/CasRefCatalog.h | 9 +- .../ContentAddressed/Pool/CasRefLedger.cpp | 89 ++- .../ContentAddressed/Pool/CasRefLedger.h | 6 +- .../tests/gtest_cas_confirm_exact_ref.cpp | 138 +++- src/Disks/tests/gtest_cas_deadline_gaps.cpp | 483 ++++++++++++ .../tests/gtest_cas_gc_frontier_gate.cpp | 38 +- src/Disks/tests/gtest_cas_part_write.cpp | 96 ++- src/Disks/tests/gtest_cas_ref_catalog.cpp | 112 ++- .../gtest_cas_ref_catalog_birth_wiring.cpp | 58 +- src/Disks/tests/gtest_cas_shared_deadline.cpp | 736 ++++++++++++++++++ 18 files changed, 1654 insertions(+), 233 deletions(-) create mode 100644 src/Disks/tests/gtest_cas_deadline_gaps.cpp diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp index 020bd20020d07..7e45e72beab53 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp @@ -61,10 +61,8 @@ CasHotKeys::~CasHotKeys() WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide) { - /// Frozen here so that the queue wait and the write share one deadline; a policy already frozen - /// by the caller's loop is returned unchanged. - const Retry frozen = op.freeze(policy); - const Retry::Bound bound = op.owner.bindPolicy(frozen); + /// The wait has its own end, taken here; each request after it binds its own window. + const Retry::Bound wait_end = op.owner.bindPolicy(policy); const uint64_t entered_ms = op.owner.now_ms(); Item item{}; @@ -112,7 +110,7 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr switch (op.gate(0)) { case CasOperation::Gate::FenceLost: - leaving = op.gaveUp(GaveUp::Why::FenceLost, sourceFor(bound), nothing_sent); + leaving = op.gaveUp(GaveUp::Why::FenceLost, sourceFor(wait_end), nothing_sent); break; case CasOperation::Gate::NoBudget: leaving = op.gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, nothing_sent); @@ -120,8 +118,11 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr case CasOperation::Gate::Ok: break; } - if (!leaving && !op.fits(0, bound)) - leaving = op.gaveUp(GaveUp::Why::Deadline, sourceFor(bound), nothing_sent); + if (!leaving && !op.fits(0, wait_end)) + leaving = op.gaveUp(GaveUp::Why::Deadline, sourceFor(wait_end), nothing_sent); + /// The front caller gets its first read. Waiters check their background owner after fence admission. + if (waited && !leaving) + throwIfBackgroundStopped(); /// Read outside the mutex, as `leave` already does: the mutex is a leaf that calls nothing, /// and `now_ms` is a closure the pool injects, not a fixed clock. @@ -139,7 +140,7 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr lane.cv.wait_for(lock, kWaitSlice); } ProfileEvents::increment(ProfileEvents::CASHotKeyQueueWaitMicroseconds, (op.owner.now_ms() - entered_ms) * 1000); - return hold(key, op, frozen, bound, decide); + return hold(key, op, policy, decide); } void CasHotKeys::leave(const String & key, Item & item, bool entered_hold, uint64_t entered_ms, CasOperation & op) noexcept diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h index 5114e364e8bf5..cda89bc1b80b2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h @@ -57,9 +57,9 @@ class CasHotKeys using Decide = std::function(const std::optional &)>; /// One hold on `key`: wait for the turn, obtain a base, run `decide`, one engine write, remember. - /// `policy` is frozen at entry, so time in the queue spends the caller's window. Returns the - /// engine's own result for that write, in class and content, and propagates a `decide`'s - /// exception as `readModifyWrite` does, never from a cached base. + /// The wait ends at the window of `policy`, or its earlier lease, taken at entry; the base read and + /// the write each bind their own. Returns the engine's own result for that write, in class and + /// content, and propagates a `decide`'s exception as `readModifyWrite` does, never from a cached base. WriteResult submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide); /// Items in the key's queue, the holder included; 0 for a key with no lane. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.h index 2221c7957b36e..709779447eb9c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.h @@ -58,7 +58,7 @@ class CatalogLifecycleReconciler /// every erase is authorised by a reading taken in its own attempt, and it is run once more before /// the drain-complete verdict, which would otherwise report from the reading its last erase left. /// It is a refresh, not a verdict: the verdict stays `op.admitted()`. Each call receives the policy that - /// bounds its reads: a cancel's own frozen policy inside the catalog lane, `Retry::standard` elsewhere. + /// bounds its reads: the cancel's policy inside the catalog lane, `Retry::standard` elsewhere. /// /// `before_erase` is called with each `Removing` life before its first erase attempt, so the caller /// can record the retirement while the row still exists; the erase may not follow. A `Creating` life diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.h index 2f990d088e927..5a5562818faaf 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.h @@ -323,7 +323,8 @@ class CachedPartFolderAccess /// committed map alone could be a drop that is durable but not yet applied. Reads the pinned table only, then /// reads the mount slot when the ledger confirms. Anything but `Yes` is a refusal: `No` when the source is /// not the current binding, `Unknown` when it cannot be shown to be before the request deadline. A transient - /// transport failure of the slot read is reissued until that deadline; any other failure propagates at once. + /// transport failure of the slot read is reissued until the end of the read's own request window; + /// any other failure propagates at once. /// Call it with no ledger lock held. ConfirmAnswer confirmCopySource(const CopySource & source) const; /// Moves a committed ref by publishing the source entries at `dst` and then dropping `src` only while it still diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index c4d1db292cba0..53108c5de7be1 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -323,17 +323,6 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// a dependency under an incarnation the precommit never saw. The build's own facts -- cancellation /// and a superseded writer epoch -- stay in `requireAlive`, where each states which one refused. CasOperation op = store->mountRequests().resume(txn_generation); - /// ONE bound for the whole publication loop, frozen before it starts: every HEAD and intent read - /// below shares this deadline, so a body whose publication keeps coming back ambiguous is refused - /// as retry-later inside one standard window instead of spending a fresh window per verb across - /// eight iterations. The paced retry is a bare sleep that does not consult the deadline, so the - /// loop can sleep one backoff (at most 5 s) past it before the next verb refuses to start. The - /// attempt cap below is the secondary bound. - const Retry policy = op.freeze(Retry::standard()); - /// The unrepeatable publication, under the SAME bound: the engine may never reissue an envelope - /// (see the publication call below), but the loop's deadline still governs whether one may start. - const Retry publication_policy = policy.asSingleAttempt(); - const BlobRef & ref = req.ref; const BlobSource & source = req.source; const String key = store->layout().blobKey(ref); @@ -366,8 +355,7 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) }; constexpr int max_publication_attempts = 8; - /// Every exit by exception after a failed attempt gave up on the blob, the attempt cap and the - /// loop's deadline alike. + /// Every exit by exception after a failed attempt gave up on the blob. int failed_attempts = 0; const int exceptions_at_entry = std::uncaught_exceptions(); SCOPE_EXIT({ @@ -409,7 +397,7 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// Sent after this `HEAD` answered. A 404 does not prove no round condemned this incarnation: a transition /// deletes the old intent after condemning. Adopting is safe because the edge was durable before the /// `HEAD`, so the next destructive cut counts it. - if (readBlobIntent(op, store->layout(), ref, *identity, policy)) + if (readBlobIntent(op, store->layout(), ref, *identity, Retry::standard())) { reason = BlobPublicationReason::IntentPresent; ProfileEvents::increment(ProfileEvents::CASBlobReuseIntentPresent); @@ -488,7 +476,7 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// each iteration of this loop builds one. The verbatim staged copy is additionally /// once-only per staging object: `beginPublication` spends a flag that the caller shares /// among every source over that object. - op.publish(BlobPublishRequest{key, std::move(publication)}, publication_policy); + op.publish(BlobPublishRequest{key, std::move(publication)}, Retry::once()); } catch (const std::exception & error) { @@ -497,27 +485,17 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) if (isDeterministicBlobPublicationFailure(error) || !op.admitted()) throw; ++failed_attempts; - recordFailedPublicationAttempt(key, transport, attempt, max_publication_attempts, error.what()); + last_failure = std::current_exception(); + /// `Poco::Exception::what` is only the class name; the message carries the cause. + const String message = getCurrentExceptionMessage(/*with_stacktrace=*/false); + recordFailedPublicationAttempt(key, transport, attempt, max_publication_attempts, message); if (attempt + 1 == max_publication_attempts) throwCasWriteRetryLater(fmt::format( "PartWriteTxn::ensureBlobPresent: publication of {} remained ambiguous after {} " "attempts: {}", key, max_publication_attempts, - error.what())); - continue; - } - catch (...) - { - ++failed_attempts; - recordFailedPublicationAttempt( - key, transport, attempt, max_publication_attempts, getCurrentExceptionMessage(/*with_stacktrace=*/false)); - if (attempt + 1 == max_publication_attempts) - throwCasWriteRetryLater(fmt::format( - "PartWriteTxn::ensureBlobPresent: publication of {} remained ambiguous after {} " - "attempts", - key, - max_publication_attempts)); + message)); continue; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp index e7b054599ca19..e634ebd3ffa53 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp @@ -2273,7 +2273,7 @@ ConfirmAnswer Pool::confirmPinnedRef(const CasRefLedger::TablePin & table, const /// Every pass repeats the ownership capture, the ledger snapshot and the slot read. The destination's reference is durable /// before the first pass and GC deletes a body only on an untouched zero of a complete cut, so a later full pass proves the /// same ownership overlap as an earlier one. An exact name and token may legitimately reappear after a move away and back. - const Retry slot_read_policy = Retry::standard().cappedAt(deadline_ms); + const Retry slot_read_policy = Retry::standard(); for (uint32_t pass = 1;; ++pass) { throwIfConfirmTornDown(ns, ref_name); @@ -2287,10 +2287,11 @@ ConfirmAnswer Pool::confirmPinnedRef(const CasRefLedger::TablePin & table, const if (now_ms >= deadline_ms) return verdict.answer; throwIfConfirmTornDown(ns, ref_name); - /// Teardown does not wake this pause, and no query cancellation reaches this layer. - mount_requests.pause(std::min(Retry::backoff(pass), deadline_ms - now_ms)); - /// A pass whose slot read could not finish by the deadline would fail on the read instead of refusing. - if (!mount_requests.admit().oneAttemptFitsBefore(deadline_ms)) + /// Teardown does not wake this pause; the owner is asked before and after it. + mount_requests.sleepFor(std::min(Retry::backoff(pass), deadline_ms - now_ms)); + Cas::throwIfBackgroundStopped(); + /// A pass starts only before the poll's end; a started pass finishes, its slot read binds its own window. + if (bootMsNow() >= deadline_ms) return verdict.answer; } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h index ed020b7b3c1c6..f355f6ee7452c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h @@ -637,13 +637,15 @@ class Pool : public std::enable_shared_from_this /// throws, and the storage layer answers `Unknown`. Any other ledger answer issues no request. ConfirmAnswer confirmExactRef(const RootNamespace & ns, const String & ref_name, const ManifestRef & manifest_ref) const; /// The same gate for an in-process copy, on the table runtime `table` pinned when the source was resolved - /// (`CasRefLedger::confirmPinnedRef`). One deadline, the request window from the call's start, decides whether the - /// ledger waits for a held state lock again and bounds the mount-slot read, which reissues a transient transport failure until then; - /// any other failure propagates at once. One wait for the lock is not bounded. - /// A pass that answers `Unknown` is asked again, paced by `Retry::backoff`, until `Yes`, `No`, the deadline, a + /// (`CasRefLedger::confirmPinnedRef`). The poll's end, the request window from the call's start, decides whether the + /// ledger waits for a held state lock again and whether another pass starts. The mount-slot read of a pass binds its own + /// request window when it starts, and reissues a transient transport failure until that window ends; any other failure + /// propagates at once. + /// One wait for the lock is not bounded. + /// A pass that answers `Unknown` is asked again, paced by `Retry::backoff`, until `Yes`, `No`, the poll's end, a /// refusal of a state the pinned runtime cannot leave, or a pin that can never confirm - /// (`CasRefLedger::pinnedTableRetired`). No ledger lock is held between passes. Throws `ABORTED` once the pool's - /// teardown has begun. + /// (`CasRefLedger::pinnedTableRetired`). A started pass finishes, even past the poll's end. + /// No ledger lock is held between passes. Throws `ABORTED` once the pool's teardown has begun. ConfirmAnswer confirmPinnedRef(const CasRefLedger::TablePin & table, const RootNamespace & ns, const String & ref_name, const ManifestRef & manifest_ref) const; /// TEST SEAM: runs between the ownership capture and the ledger snapshot. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp index 2a2d0b3fe020a..8df63d5ae2293 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp @@ -137,15 +137,6 @@ struct CatalogFenceMovedMarker : std::exception {}; struct CatalogEntryMismatchMarker : std::exception {}; struct CatalogCreatorStillLiveMarker : std::exception {}; -/// Live-lock brake for the ONE loop below that is written by hand rather than driven by the engine: -/// the catalog is a single object mutated by every lifecycle transition of every namespace in the -/// pool, so persistent contention is a real, not theoretical, exit condition to plan for. -/// -/// It bounds ATTEMPTS, and is the SECONDARY bound: the loop freezes one `Retry` before it starts and -/// every verb of every iteration shares that absolute deadline, so wall-clock time is already bounded -/// by one standard window. This cap exists so a call that somehow converges on neither still ends. -constexpr size_t kMaxCatalogCasAttempts = 100; - /// Proven absence of the catalog, for a caller that takes it as an answer rather than as corruption. struct CatalogAbsentMarker : std::exception {}; @@ -504,13 +495,7 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov .catalog_snapshot = std::move(catalog_snapshot)}; }; - /// ONE bound for the whole loop, frozen before the first iteration: every erase and every - /// resolution read below shares this deadline, so a permanently contended catalog gives up - /// retry-later within one standard window rather than spending a fresh window per verb per - /// iteration. The pause after a refused erase is a bare sleep that does not consult the deadline; - /// the read that follows it does, so a pause that crosses the deadline ends the call before the - /// next erase is sent. - const Retry policy = op.freeze(Retry::standard()); + const Retry policy = Retry::standard(); bool retirement_announced = false; for (size_t attempt = 0; attempt < kMaxCatalogCasAttempts; ++attempt) @@ -547,9 +532,10 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov /// Pause before the read: that read is the snapshot the next erase is conditioned on, and a /// write landing during a pause taken after it would refuse that erase every time. - /// The argument counts reissues so far: `backoff(0)` is no wait at all. - if (std::holds_alternative(erase)) - op.pause(Retry::backoff(static_cast(attempt) + 1)); + /// The argument counts reissues so far: `backoff(0)` is no wait at all. No erase follows the + /// last attempt, so nothing waits for it. + if (erase_again && attempt + 1 < kCasMaxDecisions) + op.sleepFor(Retry::backoff(attempt + 1)); /// An operation whose admission is gone cannot issue the resolution read either, so the call /// ends HERE and reports the cut it was given rather than a fresh one. There is nothing further @@ -601,13 +587,10 @@ CasRefCatalog::StalledCreatingCancelOutcome CasRefCatalog::cancelStalledCreating "creator fence", observed.ns.string()); - /// One deadline for the cancel and its in-lane authority check, so a slow check cannot hold the lane - /// after the cancel could no longer write. - const Retry frozen = op.freeze(policy); const auto mutate = [&](const RefCatalog & cur) -> RefCatalog { /// Inside the lane: a leader deposed while it queued must not write on a reading taken before. - refresh_authority(frozen); + refresh_authority(policy); if (!op.admitted()) throw CatalogFenceMovedMarker{}; @@ -626,7 +609,7 @@ CasRefCatalog::StalledCreatingCancelOutcome CasRefCatalog::cancelStalledCreating /// unfinished life. try { - casUpdateImpl(op, layout, mutate, [](const RefCatalog & c) { return encodeRefCatalog(c); }, frozen, + casUpdateImpl(op, layout, mutate, [](const RefCatalog & c) { return encodeRefCatalog(c); }, policy, /*absence_is_an_answer=*/catalog_absent != nullptr); } catch (const CatalogAbsentMarker &) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h index d6c154b8f61ed..5a4c00759d176 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h @@ -68,9 +68,8 @@ class CasRefCatalog /// re-encoding the stale candidate. `mutate` must return a canonically ordered, grammar-valid /// candidate; `encodeRefCatalog` (called internally) enforces that. /// - /// The engine's own policy is the bound: persistent conflict ends at the write deadline with the - /// typed retryable error `throwCasWriteRetryLater`, rather than spinning forever against a - /// pathologically busy catalog. + /// Persistent conflict ends after `kCasMaxDecisions` submissions with the typed retryable error + /// `throwCasWriteRetryLater`, rather than spinning forever against a pathologically busy catalog. /// /// A read that finds the object ABSENT is corruption, not a fresh bootstrap -- `mutate` is never /// offered an absent catalog to build a replacement authority from, so no mutation can replace @@ -193,8 +192,8 @@ class CasRefCatalog /// `_ckpt` or other physical cleanup; debris belongs to the janitor. /// `refresh_authority` runs in every attempt, inside the catalog's hot-key lane and before `op`'s /// admission is checked, for a caller whose liveness is a cached flag; a caller whose liveness needs - /// no refresh passes a no-op. Its reads hold the lane, so it receives the cancel's own frozen policy to - /// bound them; a refresh that cannot finish in time must leave `op` unadmitted. The predicate runs + /// no refresh passes a no-op. Its reads hold the lane, so it receives the cancel's policy to bound + /// them; a refresh that cannot finish in time must leave `op` unadmitted. The predicate runs /// there too, on the catalog the attempt writes over. /// A cancel whose response is lost returns `Cancelled` while the catalog still holds the bytes it wrote, /// and `EntryChanged` once a later write replaced them. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index 384d7ef16a011..5cad334b0035b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -765,7 +765,7 @@ void CasRefLedger::cancelIdleOwnCreatingRows( { LOG_ERROR(getLogger("CasRefLedger"), "CAS ref catalog '{}': mandatory catalog absent; skipping owner cleanup", key); }; - const Retry policy = op.freeze(Retry::standard()); + const Retry policy = Retry::standard(); const std::optional got = op.read(key, policy); if (!got) { @@ -1484,20 +1484,12 @@ NamespaceLifeId CasRefLedger::resolveNamespaceLife( const RootNamespace & ns, uint64_t admitted_generation, uint64_t live_epoch, bool * lifecycle_refusal) { - /// The SECONDARY bound. Wall-clock time is already bounded by the frozen policy below, which - /// every verb of every iteration shares; this cap exists so a sequence that somehow converges on - /// neither a resolution nor the deadline still ends. A duel between two openers (one creating, one - /// reconciling a stale creator) converges in a handful of rounds. + /// A duel between two openers (one creating, one reconciling a stale creator) converges in a + /// handful of rounds. static constexpr size_t kMaxResolveAttempts = 32; const CreatorFence our_fence{server_root_id, live_epoch, admitted_generation}; CasOperation op = mount_requests.resume(admitted_generation); - - /// ONE bound for the whole loop, frozen before the first iteration: every read and every protocol - /// call below shares this deadline, so a namespace whose catalog entry keeps moving gives up - /// retry-later within one standard window rather than spending a fresh window per verb per - /// iteration. The paced re-read below is a bare sleep that does not consult the deadline, so the - /// loop can sleep one backoff (at most 5 s) past it before the next read refuses to start. - const Retry policy = op.freeze(Retry::standard()); + const Retry policy = Retry::standard(); for (size_t attempt = 0; attempt < kMaxResolveAttempts; ++attempt) { @@ -5749,9 +5741,7 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( /// check (it only ever shrinks state; see `flushRefBatch`'s `state_growing` filter). ColdAdmission admission = beginColdAdmission(ns); CasOperation initial_op = mount_requests.admit(); - /// One deadline for every request that leads to the removal decision. The wait for the lane to - /// drain and for another removal attempt counts against it but is never cut short. - const Retry policy = initial_op.freeze(Retry::standard()); + const Retry policy = Retry::standard(); const CasRefCatalog::Snapshot initial_catalog = CasRefCatalog::read(initial_op, layout, policy); const auto initial_it = std::find_if(initial_catalog.catalog.entries.begin(), initial_catalog.catalog.entries.end(), [&](const CatalogEntry & entry) { return entry.ns == ns; }); @@ -5863,6 +5853,42 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( observed_live = *initial_it; bool removing_durable = false; bool removal_write_outcome_unknown = false; + + /// Resolves the removal state from a fresh catalog read. Returns true when the row is the durable + /// `Removing` of this life. Reopens the lane only when the row is exactly the observed `Live` one, + /// the mount fence is still admitted, and no `Removing` write may still land: that is, + /// `removal_write_outcome_unknown`, `rt->removal_write_may_land` and `rt->removing_observed` are all + /// clear. Every other case leaves the lane closed. + const auto resolveRemovalState = [&](CasOperation & op) + { + /// Owed to the closed lane: a stopped owner must not leave a proven `Live` lane closed. + const auto owed = Cas::OwnerScope::owed(); + const CasRefCatalog::Snapshot fresh = CasRefCatalog::read(op, layout, policy); + if (removal_reopen_read_hook_for_test) + removal_reopen_read_hook_for_test(); + const auto fresh_it = std::find_if(fresh.catalog.entries.begin(), fresh.catalog.entries.end(), + [&](const CatalogEntry & entry) { return entry.ns == ns; }); + if (observed_live + && fresh_it != fresh.catalog.entries.end() + && fresh_it->incarnation == observed_live->incarnation + && fresh_it->state == NsState::Removing) + { + return true; + } + if (observed_live && fresh_it != fresh.catalog.entries.end() && *fresh_it == *observed_live) + { + refuseUnlessAdmitted(op, "reopening the removal lane"); + std::lock_guard queue_lock(ref_queue_mutex); + if (!removal_write_outcome_unknown && !rt->removal_write_may_land && !rt->removing_observed) + { + rt->removal_admission_closed = false; + rt->cv.notify_all(); + } + } + return false; + }; + + std::optional removal_op; try { refuseUnlessAdmitted(removal_op, "beginning removal"); @@ -5925,35 +5951,16 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( } catch (...) { - /// Resolve an ambiguous transition before deciding whether this lane may reopen. `Removing` - /// under the same life is conclusive success. Reopening also needs a fresh exact `Live` row, the - /// same mount fence and no `Removing` observation of this runtime, which may land after the read; - /// every other case stays closed and propagates the original error. + /// An ambiguous transition is resolved before the lane may reopen; otherwise the original error propagates. + /// A failure before the removal operation exists sent nothing: its error propagates even if the row reads `Removing`. try { - /// A fresh standard window, not `policy`: an expired policy would fail this read at once and - /// leave a healthy table closed. - const CasRefCatalog::Snapshot fresh = CasRefCatalog::read(removal_op, layout); - if (removal_reopen_read_hook_for_test) - removal_reopen_read_hook_for_test(); - const auto fresh_it = std::find_if(fresh.catalog.entries.begin(), fresh.catalog.entries.end(), - [&](const CatalogEntry & entry) { return entry.ns == ns; }); - if (observed_live - && fresh_it != fresh.catalog.entries.end() - && fresh_it->incarnation == observed_live->incarnation - && fresh_it->state == NsState::Removing) - { - removing_durable = true; - } - else if (observed_live && fresh_it != fresh.catalog.entries.end() && *fresh_it == *observed_live) + if (removal_op) + removing_durable = resolveRemovalState(*removal_op); + else { - refuseUnlessAdmitted(removal_op, "reopening the removal lane"); - std::lock_guard queue_lock(ref_queue_mutex); - if (!removal_write_outcome_unknown && !rt->removal_write_may_land && !rt->removing_observed) - { - rt->removal_admission_closed = false; - rt->cv.notify_all(); - } + CasOperation reopen_op = mount_requests.resume(rt->admitted_fence_generation, runtime_live); + resolveRemovalState(reopen_op); } } catch (...) // NOLINT(bugprone-empty-catch) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h index b8df5f5484ade..c5353342fde3a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h @@ -1275,10 +1275,8 @@ class CasRefLedger /// Every `createNamespace`/`completeCreation`/`reconcileStaleCreator` outcome that writes nothing /// (`FencedOut`, `Superseded`, a reconciled entry, `EntryChanged`) re-reads the catalog and loops; /// `CreatorFenceStillLive` throws the retry-later class, which this function's caller (the transient - /// retry loop) or a higher one re-drives. One `Retry` is frozen before the loop and shared by every - /// read and every protocol call it makes, so the whole resolution ends within one standard window; - /// a re-read forced by a competing actor is paced by a jittered sleep, and an iteration cap is the - /// secondary bound. + /// retry loop) or a higher one re-drives. A re-read forced by a competing actor is paced by a + /// jittered sleep, and a cap on rounds ends the loop. NamespaceLifeId resolveNamespaceLife( const RootNamespace & ns, uint64_t admitted_generation, uint64_t live_epoch, bool * lifecycle_refusal = nullptr); diff --git a/src/Disks/tests/gtest_cas_confirm_exact_ref.cpp b/src/Disks/tests/gtest_cas_confirm_exact_ref.cpp index 3d59d1b37a577..b1fd11d47cda4 100644 --- a/src/Disks/tests/gtest_cas_confirm_exact_ref.cpp +++ b/src/Disks/tests/gtest_cas_confirm_exact_ref.cpp @@ -2442,6 +2442,9 @@ class TimingOutSlotReadBackend : public CountingBackend std::vector read_times; }; +/// What one read reserves with default settings (`cas_attempt_timeout_ms` 5000 and a connect cap of 1000, twice). +constexpr uint64_t kDefaultAttemptEnvelopeMs = 7000; + constexpr uint64_t kSlotReadFailsForever = std::numeric_limits::max(); PoolPtr openPoolOnClock(const std::shared_ptr & backend, tests::FakeClock & clock, @@ -2534,24 +2537,27 @@ TEST(CASConfirmExactRef, CopyConfirmPropagatesAPersistentSlotReadFailureCountedO EXPECT_EQ(slotMovedCount() - moved_before, 0u) << "a failed read is not a moved slot"; } -/// The retries end at the deadline the confirm took at its start, not at a fresh window from the read: half the -/// window is spent before the read, so a fresh window would keep reading past the caller's deadline. -TEST(CASConfirmExactRef, CopyConfirmStopsRetryingTheSlotReadAtTheCallersDeadline) +/// The slot read binds its own window when it starts, not the poll's: half the poll's window is spent before the read, +/// and the retries still run a full window from the read's start. +TEST(CASConfirmExactRef, CopyConfirmStopsRetryingTheSlotReadAtItsOwnWindow) { tests::FakeClock clock; auto backend = std::make_shared(); - /// A lease far longer than the window, so the policy deadline and not the lease ends the retries. + /// A lease far longer than the window, so the read's window and not the lease ends the retries. auto store = openPoolOnClock(backend, clock, std::chrono::minutes(10)); + store->mountRequests().setAttemptReservationForTest(kDefaultAttemptEnvelopeMs); const RootNamespace ns{"srv1/confirm_copy_slot_deadline"}; const ManifestId id = publishEmptyPart(store, ns, "x"); const auto pinned = store->resolveRefPinned(ns, "x"); ASSERT_TRUE(pinned.has_value()); const uint64_t window_ms = PoolConfig{}.cas_request_budget.request_window_ms; - const uint64_t deadline_ms = clock.now.load() + window_ms; + const uint64_t poll_deadline_ms = clock.now.load() + window_ms; + uint64_t read_started_ms = 0; store->setConfirmAfterLedgerSnapshotHookForTest([&] { clock.now.fetch_add(window_ms / 2); + read_started_ms = clock.now.load(); }); backend->watched_key = mountSlotKey(store); backend->failures_left = kSlotReadFailsForever; @@ -2561,12 +2567,13 @@ TEST(CASConfirmExactRef, CopyConfirmStopsRetryingTheSlotReadAtTheCallersDeadline EXPECT_FALSE(outcome.answer.has_value()); EXPECT_EQ(outcome.error_code, std::optional(DB::ErrorCodes::NETWORK_ERROR)) << outcome.error_message; - EXPECT_NE(outcome.error_message.find("policy deadline"), String::npos) << outcome.error_message; const std::vector times = backend->slotReadTimes(); ASSERT_GT(times.size(), 1u) << "the failure was retried"; - EXPECT_LT(times.back(), deadline_ms) << "a read was sent at or after the caller's deadline"; + const uint64_t read_deadline_ms = read_started_ms + window_ms; + EXPECT_GT(times.back(), poll_deadline_ms) << "the retries stopped at the poll's end instead of the read's own window"; + EXPECT_LT(times.back(), read_deadline_ms) << "a read was sent at or after its own window's end"; /// The loop stops only when the next pause plus attempt no longer fits; a pause is at most 5000 ms. - EXPECT_GE(clock.now.load() + 5000 + backend->attemptEnvelopeMs(), deadline_ms) << "the retries stopped short of the deadline"; + EXPECT_GE(clock.now.load() + 5000 + kDefaultAttemptEnvelopeMs, read_deadline_ms) << "the retries stopped short of the window"; } /// The confirm a peer asks for makes one attempt at the slot read: the peer times out and retries from its own queue. @@ -2700,7 +2707,7 @@ TEST(CASConfirmExactRef, CopyConfirmReconfirmsOnceAMutationNamingTheSourceComple } /// The mutation stays queued: the confirm keeps asking until the deadline it took at its start and then refuses. It -/// neither gives up while a pass still fits nor starts one that could not finish by the deadline. +/// does not give up before the poll's end and starts no pass at or after it. TEST(CASConfirmExactRef, CopyConfirmRefusesAtItsDeadlineWhileAMutationNamingTheSourceStaysQueued) { tests::FakeClock clock; @@ -2734,8 +2741,117 @@ TEST(CASConfirmExactRef, CopyConfirmRefusesAtItsDeadlineWhileAMutationNamingTheS ASSERT_GT(pass_times.size(), 1u) << "the confirm did not ask again"; EXPECT_EQ(inFlightRefusals() - in_flight_before, pass_times.size()) << "every pass refused for the queued mutation"; EXPECT_LE(answered_at, deadline_ms) << "the confirm answered after its deadline"; - EXPECT_GE(answered_at + backend->attemptEnvelopeMs(), deadline_ms) << "the confirm gave up while a pass still fit"; - EXPECT_LT(pass_times.back() + backend->attemptEnvelopeMs(), deadline_ms) << "a pass started that could not finish"; + EXPECT_EQ(answered_at, deadline_ms) << "the poll stopped before its end"; + EXPECT_LT(pass_times.back(), deadline_ms) << "a pass started at or after the poll's end"; +} + +/// A pass starts whenever the poll's end is still ahead, even with less than one attempt envelope left: its slot read +/// binds its own window. +TEST(CASConfirmExactRef, APassWithLessThanOneEnvelopeLeftStillStarts) +{ + tests::FakeClock clock; + auto backend = std::make_shared(); + auto on_pause = std::make_shared>(); + auto store = openPoolOnFakeClock(backend, clock, on_pause); + store->mountRequests().setAttemptReservationForTest(kDefaultAttemptEnvelopeMs); + const RootNamespace ns{"srv1/confirm_copy_short_tail"}; + const ManifestId id = publishEmptyPart(store, ns, "x"); + const auto pinned = store->resolveRefPinned(ns, "x"); + ASSERT_TRUE(pinned.has_value()); + + LeaderLatch latch; + latch.arm(store); + std::thread appender([&] { appendPrecommitPairNaming(store, ns, "x"); }); + SCOPE_EXIT({ + latch.release(); + appender.join(); + store->setRefPreCarveHookForTest(nullptr); + }); + latch.awaitEntered(); + + const uint64_t deadline_ms = clock.now.load() + store->poolConfig().cas_request_budget.request_window_ms; + const uint64_t left_ms = kDefaultAttemptEnvelopeMs / 2; + size_t pauses = 0; + *on_pause = [&] + { + if (++pauses == 1) + clock.now.store(deadline_ms - left_ms); + }; + std::vector pass_times; + store->setConfirmAfterOwnershipCaptureHookForTest([&] { pass_times.push_back(clock.now.load()); }); + SCOPE_EXIT({ store->setConfirmAfterOwnershipCaptureHookForTest(nullptr); }); + const ConfirmOutcome outcome = confirmPinned(store, *pinned, ns, id); + + EXPECT_FALSE(outcome.error_code.has_value()) << "the confirm threw: " << outcome.error_message; + EXPECT_EQ(outcome.answer, std::optional(ConfirmAnswer::Unknown)); + ASSERT_GT(pass_times.size(), 1u) << "no pass started with less than one envelope left"; + EXPECT_EQ(pass_times[1], deadline_ms - left_ms); +} + +/// The poll's end stops only new passes: a ledger check that crosses it still sends the slot read. +TEST(CASConfirmExactRef, ALedgerCheckThatCrossesThePollEndStillSendsItsSlotRead) +{ + tests::FakeClock clock; + auto backend = std::make_shared(); + auto store = openPoolOnClock(backend, clock, std::chrono::minutes(10)); + const RootNamespace ns{"srv1/confirm_copy_check_crosses_end"}; + const ManifestId id = publishEmptyPart(store, ns, "x"); + const auto pinned = store->resolveRefPinned(ns, "x"); + ASSERT_TRUE(pinned.has_value()); + + const uint64_t window_ms = PoolConfig{}.cas_request_budget.request_window_ms; + const uint64_t deadline_ms = clock.now.load() + window_ms; + store->setConfirmAfterLedgerSnapshotHookForTest([&] { clock.now.fetch_add(window_ms + 1); }); + backend->watched_key = mountSlotKey(store); + const ConfirmOutcome outcome = confirmPinned(store, *pinned, ns, id); + store->setConfirmAfterLedgerSnapshotHookForTest(nullptr); + + EXPECT_FALSE(outcome.error_code.has_value()) << "the confirm threw: " << outcome.error_message; + EXPECT_EQ(outcome.answer, std::optional(ConfirmAnswer::Yes)); + const std::vector times = backend->slotReadTimes(); + ASSERT_EQ(times.size(), 1u); + EXPECT_GT(times.front(), deadline_ms) << "the slot read was sent before the poll's end"; +} + +/// A pause that reaches the poll's end starts no pass. +TEST(CASConfirmExactRef, APauseThatReachesThePollEndStartsNoPass) +{ + tests::FakeClock clock; + auto backend = std::make_shared(); + auto on_pause = std::make_shared>(); + auto store = openPoolOnFakeClock(backend, clock, on_pause); + const RootNamespace ns{"srv1/confirm_copy_pause_reaches_end"}; + const ManifestId id = publishEmptyPart(store, ns, "x"); + const auto pinned = store->resolveRefPinned(ns, "x"); + ASSERT_TRUE(pinned.has_value()); + + LeaderLatch latch; + latch.arm(store); + std::thread appender([&] { appendPrecommitPairNaming(store, ns, "x"); }); + SCOPE_EXIT({ + latch.release(); + appender.join(); + store->setRefPreCarveHookForTest(nullptr); + }); + latch.awaitEntered(); + + const uint64_t deadline_ms = clock.now.load() + store->poolConfig().cas_request_budget.request_window_ms; + size_t passes = 0; + store->setConfirmAfterOwnershipCaptureHookForTest([&] { ++passes; }); + /// The first pause ends exactly at the poll's end, whatever length the jitter gave it. + size_t pauses = 0; + *on_pause = [&] + { + if (++pauses == 1) + clock.now.store(deadline_ms); + }; + SCOPE_EXIT({ store->setConfirmAfterOwnershipCaptureHookForTest(nullptr); }); + const ConfirmOutcome outcome = confirmPinned(store, *pinned, ns, id); + + EXPECT_FALSE(outcome.error_code.has_value()) << "the confirm threw: " << outcome.error_message; + EXPECT_EQ(outcome.answer, std::optional(ConfirmAnswer::Unknown)); + EXPECT_EQ(passes, 1u); + EXPECT_EQ(clock.now.load(), deadline_ms) << "the pause was not clamped to the poll's end"; } /// `No` says the source is no longer the binding the copy read; no later pass can change that, so it is answered at once. diff --git a/src/Disks/tests/gtest_cas_deadline_gaps.cpp b/src/Disks/tests/gtest_cas_deadline_gaps.cpp new file mode 100644 index 0000000000000..f34d51ad3c0d1 --- /dev/null +++ b/src/Disks/tests/gtest_cas_deadline_gaps.cpp @@ -0,0 +1,483 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace DB::Cas; +using DB::Cas::tests::OperationForTest; +using DB::Cas::tests::TimeTakingBackend; +using DB::Cas::tests::VirtualRetryClock; +using DB::Cas::tests::idOf; + +namespace +{ + +constexpr uint64_t kTenMinutesMs = 10 * 60 * 1000; + +using Verb = TimeTakingBackend::Verb; +using Ending = TimeTakingBackend::Ending; + +struct OpenedPool +{ + PoolPtr store; + std::shared_ptr clock; +}; + +/// Every request plane of the pool and the backend's own delays share one virtual clock. +OpenedPool openPoolOn(const std::shared_ptr & backend) +{ + /// A pool closed while a build still owes its cleanup leaves no clean farewell; the reopen must not + /// spend a lease TTL of real time observing the slot. + PoolPtr store = Pool::open( + backend, PoolConfig{.pool_prefix = "p", .server_root_id = "test", .unsafe_remount_no_delay = true}); + auto clock = VirtualRetryClock::installOn(store); + backend->useClock(clock); + return {std::move(store), std::move(clock)}; +} + +PartWriteTxnPtr startBuildFor(const PoolPtr & store, const RootNamespace & ns, const String & ref) +{ + PartWriteInfo info; + info.intended_ref = ns.string() + "/" + ref; + return store->beginPartWrite(info); +} + +ManifestEntry blobManifestEntry(const String & path, const String & payload) +{ + ManifestEntry entry; + entry.path = path; + entry.placement = EntryPlacement::Blob; + entry.ref = idOf(payload); + entry.blob_size = payload.size(); + return entry; +} + +std::function exactly(const String & wanted) +{ + return [wanted](const String & key) { return key == wanted; }; +} + +enum class BodyTransport : uint8_t { Streaming, ServerSideCopy }; + +const char * transportName(BodyTransport transport) +{ + return transport == BodyTransport::Streaming ? "Streaming" : "ServerSideCopy"; +} + +/// A re-readable source of `payload`. For a server-side copy it also stores the staging object the +/// copy publishes verbatim: the pool's fixed-length envelope followed by the payload. +BlobSource sourceOf(BodyTransport transport, TimeTakingBackend & backend, const PoolPtr & store, const String & payload) +{ + BlobSource source; + source.size = payload.size(); + source.open = [payload]() -> std::unique_ptr + { + return std::make_unique(payload); + }; + if (transport == BodyTransport::ServerSideCopy) + { + const String staging_key = "p/staging/test/" + payload; + OperationForTest seed(backend); + const WriteResult seeded + = (*seed).create(staging_key, String(store->poolMeta().blob_header_len, 'h') + payload, Retry::once()); + EXPECT_TRUE(std::holds_alternative(seeded)); + source.server_side_copy_from = staging_key; + } + return source; +} + +/// Runs `step` and returns the text of whatever it threw, or nothing. +std::optional failureOf(const std::function & step) +{ + try + { + step(); + } + catch (...) + { + return DB::getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + return std::nullopt; +} + +void publishOnePart(const PoolPtr & store, const RootNamespace & ns, const String & ref, const String & payload) +{ + auto build = startBuildFor(store, ns, ref); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, ref, id); + build->putBlob(idOf(payload), BlobSource::fromString(payload)); + build->promote(ns, ref, build->buildId(), id); +} + +/// A pool reopened over a table with two committed parts, so the table's ref state is not in memory. +struct ColdTable +{ + std::shared_ptr backend = std::make_shared(); + RootNamespace ns{"srv/tbl"}; + OpenedPool pool; + + ColdTable() + { + { + const OpenedPool first = openPoolOn(backend); + publishOnePart(first.store, ns, "part_a", "payload-a"); + publishOnePart(first.store, ns, "part_b", "payload-b"); + } + pool = openPoolOn(backend); + } + + /// The first read of the removal that is not the catalog read belongs to the table's recovery. + void armSlowRecovery() const + { + backend->arm(Verb::Read, [catalog = pool.store->layout().refCatalogKey()](const String & key) { return key != catalog; }, + kTenMinutesMs); + } +}; + +} + +/// --------------------------------------------------------------------------------------------- +/// A publication that takes longer than the request window. +/// --------------------------------------------------------------------------------------------- + +class CASDeadlineGapsLongPublication : public ::testing::TestWithParam +{ +}; + +INSTANTIATE_TEST_SUITE_P(CASTransport, CASDeadlineGapsLongPublication, + ::testing::Values(BodyTransport::Streaming, BodyTransport::ServerSideCopy), + [](const ::testing::TestParamInfo & param) { return String(transportName(param.param)); }); + +/// The transfer of a body is bounded by its own send and receive timeouts only, so a publication five +/// times the request window long must still end in a committed part: no request that follows it may be +/// measured against a deadline taken before it started. +TEST_P(CASDeadlineGapsLongPublication, Commits) +{ + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-that-takes-ten-minutes"; + const String key = pool.store->layout().blobKey(idOf(payload)); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + backend->arm(Verb::Publish, exactly(key), kTenMinutesMs); + const uint64_t started_ms = pool.clock->nowMs(); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload), sourceOf(GetParam(), *backend, pool.store, payload)); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(backend->slowedKeys(), std::vector{key}) << "the publication never ran slowly"; + ASSERT_GT(pool.clock->nowMs() - started_ms, kDefaultRequestWindowMs); + ASSERT_FALSE(failure.has_value()) << *failure; + EXPECT_EQ(backend->publicationsOf(key), 1u); + EXPECT_EQ(backend->serverSideCopiesOf(key), GetParam() == BodyTransport::ServerSideCopy ? 1u : 0u); + EXPECT_TRUE(pool.store->resolveRef(ns, "part").has_value()); +} + +namespace +{ + +struct LostPublication +{ + BodyTransport transport; + bool landed; +}; + +class CASDeadlineGapsLostLongPublication : public ::testing::TestWithParam +{ +}; + +} + +INSTANTIATE_TEST_SUITE_P(CASTransport, CASDeadlineGapsLostLongPublication, + ::testing::Values( + LostPublication{BodyTransport::Streaming, false}, LostPublication{BodyTransport::Streaming, true}, + LostPublication{BodyTransport::ServerSideCopy, false}, LostPublication{BodyTransport::ServerSideCopy, true}), + [](const ::testing::TestParamInfo & param) + { + return String(transportName(param.param.transport)) + (param.param.landed ? "Landed" : "NotLanded"); + }); + +/// The publication loop allows eight attempts. A first attempt that ran for ten minutes before its +/// response was lost has used none of the time a reissue needs: the next observation of the key, and the +/// publication after it when the body did not land, must still be sent. +TEST_P(CASDeadlineGapsLostLongPublication, IsReissuedInPlaceAndCommits) +{ + const LostPublication lost = GetParam(); + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-whose-first-response-is-lost"; + const String key = pool.store->layout().blobKey(idOf(payload)); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + backend->arm(Verb::Publish, exactly(key), kTenMinutesMs, /*times=*/1, + lost.landed ? Ending::LostAfterLanding : Ending::LostBeforeLanding); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload), sourceOf(lost.transport, *backend, pool.store, payload)); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(backend->slowedKeys(), std::vector{key}) << "the publication never ran slowly"; + ASSERT_FALSE(failure.has_value()) + << "after " << backend->publicationsOf(key) << " publication(s) the build failed: " << *failure; + /// A stored body has no deletion intent, so the reissue adopts it; an absent one is published again. + EXPECT_EQ(backend->publicationsOf(key), lost.landed ? 1u : 2u); + EXPECT_TRUE(pool.store->resolveRef(ns, "part").has_value()); +} + +/// A part of sixteen bodies whose last upload takes ten minutes. The fifteen dependency proofs taken +/// before it are consumed by the promote ten minutes later, and nothing may re-measure them against +/// the time they were taken at. +TEST(CASDeadlineGaps, BodiesPublishedBeforeASlowOneAreStillAcceptedAtPromote) +{ + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + constexpr size_t bodies = 16; + + std::vector payloads; + std::vector entries; + for (size_t i = 0; i < bodies; ++i) + { + payloads.push_back(fmt::format("body-{}-of-a-wide-part", i)); + entries.push_back(blobManifestEntry(fmt::format("column_{}.bin", i), payloads.back())); + } + const String slow_key = pool.store->layout().blobKey(idOf(payloads.back())); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest(entries); + build->precommitAdd(ns, "part", id); + + backend->arm(Verb::Publish, exactly(slow_key), kTenMinutesMs); + std::vector results; + const auto failure = failureOf([&] + { + /// The order of the upload fan-out's join: every result is kept until the slowest task ends. + for (const String & payload : payloads) + results.push_back(build->uploadBlobDetached( + BlobUploadRequest{idOf(payload), BlobSource::fromString(payload), payload.size()})); + build->mergeBlobUploadResults(results); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(backend->slowedKeys(), std::vector{slow_key}) << "the last publication never ran slowly"; + ASSERT_FALSE(failure.has_value()) << *failure; + for (const String & payload : payloads) + EXPECT_EQ(backend->publicationsOf(pool.store->layout().blobKey(idOf(payload))), 1u); + EXPECT_TRUE(pool.store->resolveRef(ns, "part").has_value()); +} + +/// GC rounds run while a body uploads for ten minutes. The build's precommit was durable before the +/// upload started, so neither the manifest it staged nor the sibling body it already published may be +/// reclaimed, and the promote that follows must find its precommit. +TEST(CASDeadlineGaps, GcRoundsDuringALongPublicationSpareTheBuild) +{ + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + const String payload_a = "body-a-published-before-the-long-upload"; + const String payload_b = "body-b-uploads-for-ten-minutes"; + const String key_a = pool.store->layout().blobKey(idOf(payload_a)); + const String key_b = pool.store->layout().blobKey(idOf(payload_b)); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload_a), blobManifestEntry("b.bin", payload_b)}); + build->precommitAdd(ns, "part", id); + build->putBlob(idOf(payload_a), BlobSource::fromString(payload_a)); + + Gc gc(pool.store, hexToU128("00000000000000000000000000000001")); + size_t rounds_during_upload = 0; + backend->armWith(Verb::Publish, exactly(key_b), [&] + { + for (size_t i = 0; i < 3; ++i) + { + pool.clock->advance(kTenMinutesMs / 3); + /// What the renewal thread does every period while the upload runs. + pool.store->renewWatermarkOnce(); + (void)DB::Cas::tests::runRegularRoundReclaiming(gc); + ++rounds_during_upload; + } + }); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload_b), BlobSource::fromString(payload_b)); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(rounds_during_upload, 3u) << "no GC round ran during the publication"; + ASSERT_FALSE(failure.has_value()) << *failure; + for (size_t i = 0; i < 3; ++i) + { + pool.store->renewWatermarkOnce(); + (void)DB::Cas::tests::runRegularRoundReclaiming(gc); + } + EXPECT_EQ(backend->publicationsOf(key_a), 1u); + EXPECT_EQ(backend->publicationsOf(key_b), 1u); + EXPECT_TRUE(DB::Cas::tests::objectPresent(*backend, key_a)); + EXPECT_TRUE(DB::Cas::tests::objectPresent(*backend, key_b)); + ASSERT_TRUE(pool.store->resolveRef(ns, "part").has_value()); + EXPECT_EQ(pool.store->readManifest(id).entries.size(), 2u); +} + +/// One upload outlives twenty mount lease TTLs. The lease is renewed every period by its own thread +/// and a renewal does not move the fence generation, so the build admitted before the upload is still +/// admitted after it and commits. +TEST(CASDeadlineGaps, ABuildSurvivesAnUploadLongerThanManyLeaseTtls) +{ + auto backend = std::make_shared(); + /// One clock for the lease and for every request window, as on a server. + auto boot_ms = std::make_shared>(1'000'000); + const PoolPtr store = Pool::open(backend, PoolConfig{ + .pool_prefix = "p", .server_root_id = "test", + .boot_ms_fn = [boot_ms] { return boot_ms->load(); }}); + store->setCasRetrySleepForTest([boot_ms](uint64_t ms) { boot_ms->fetch_add(ms + 1); }); + const uint64_t ttl_ms = static_cast(store->poolConfig().mount_lease_ttl_ms.count()); + const uint64_t period_ms = static_cast(store->poolConfig().mount_renew_period.count()); + + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-that-outlives-the-lease"; + const String key = store->layout().blobKey(idOf(payload)); + auto build = startBuildFor(store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + const uint64_t generation_before = store->fenceGeneration(); + const uint64_t started_ms = boot_ms->load(); + backend->armWith(Verb::Publish, exactly(key), [&] + { + for (uint64_t elapsed_ms = 0; elapsed_ms < kTenMinutesMs; elapsed_ms += period_ms) + { + boot_ms->fetch_add(period_ms); + store->renewWatermarkOnce(); + } + }); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload), BlobSource::fromString(payload)); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(backend->slowedKeys(), std::vector{key}) << "the publication never ran slowly"; + ASSERT_GE(boot_ms->load() - started_ms, 20 * ttl_ms); + ASSERT_FALSE(failure.has_value()) << *failure; + EXPECT_EQ(store->fenceGeneration(), generation_before); + EXPECT_EQ(backend->publicationsOf(key), 1u); + EXPECT_TRUE(store->resolveRef(ns, "part").has_value()); +} + +/// The eighth publication is the last the loop makes. When its response is lost after the body landed +/// the loop does not observe the key again: the write fails and the caller's retry adopts the body. +TEST(CASDeadlineGaps, ABodyThatLandsOnTheEighthLostPublicationStillFails) +{ + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-landing-on-the-last-attempt"; + const String key = pool.store->layout().blobKey(idOf(payload)); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + size_t journal_at_eighth = 0; + backend->arm(Verb::Publish, exactly(key), /*takes_ms=*/0, /*times=*/7, Ending::LostBeforeLanding); + backend->armWith(Verb::Publish, exactly(key), [&] { journal_at_eighth = backend->seenCount(); }, /*times=*/1, + Ending::LostAfterLanding); + const auto failure = failureOf([&] { build->putBlob(idOf(payload), BlobSource::fromString(payload)); }); + + ASSERT_TRUE(failure.has_value()) << "the loop must not commit a body whose last publication was lost"; + EXPECT_NE(failure->find("remained ambiguous"), String::npos) << *failure; + EXPECT_EQ(backend->publicationsOf(key), 8u); + EXPECT_TRUE(DB::Cas::tests::objectPresent(*backend, key)); + EXPECT_EQ(backend->seenSince(journal_at_eighth, Verb::Head, key), 0u) << "the loop observed the key after its last publication"; +} + +/// --------------------------------------------------------------------------------------------- +/// A table removal whose ref-table recovery takes longer than the request window. +/// --------------------------------------------------------------------------------------------- + +/// Recovery of a table reads its checkpoint, snapshot and log tail, and its length grows with the +/// table. The removal's catalog read and its `Live -> Removing` write come after it and are single +/// requests, so they need a window of their own. +TEST(CASDeadlineGaps, RemovalOfATableWhoseRecoveryOutlastsTheWindowCompletes) +{ + const ColdTable table; + const PoolPtr & store = table.pool.store; + ASSERT_FALSE(store->refTableRecoveredForTest(table.ns)) << "the table must be recovered by the removal itself"; + + table.armSlowRecovery(); + const uint64_t started_ms = table.pool.clock->nowMs(); + std::optional recovery_took_ms; + store->setRemovalAttemptHookForTest([&] { recovery_took_ms = table.pool.clock->nowMs() - started_ms; }); + const auto failure = failureOf([&] { store->dropNamespace(table.ns); }); + store->setRemovalAttemptHookForTest({}); + + ASSERT_EQ(table.backend->slowedKeys().size(), 1u) << "no read of the recovery ran slowly"; + ASSERT_TRUE(recovery_took_ms.has_value()) << "the removal never reached its first request"; + ASSERT_GT(*recovery_took_ms, kDefaultRequestWindowMs); + ASSERT_FALSE(failure.has_value()) << *failure; + EXPECT_FALSE(store->resolveRef(table.ns, "part_a").has_value()); + EXPECT_FALSE(store->resolveRef(table.ns, "part_b").has_value()); +} + +/// The recovery a failed removal paid for stays in memory, so the next removal of the same table has +/// nothing long in front of its requests. The first removal fails at its `gc/state` read, after the +/// recovery and before any catalog write. +TEST(CASDeadlineGaps, RepeatedRemovalAfterASlowRecoveryCompletes) +{ + const ColdTable table; + const PoolPtr & store = table.pool.store; + const String gc_state_key = store->layout().gcStateKey(); + const String catalog_key = store->layout().refCatalogKey(); + + table.armSlowRecovery(); + auto gc_state_fails = std::make_shared>(false); + table.backend->arm(Verb::Read, [gc_state_fails, gc_state_key](const String & key) + { + return gc_state_fails->load() && key == gc_state_key; + }, /*takes_ms=*/0, std::numeric_limits::max(), TimeTakingBackend::Ending::LostBeforeLanding); + store->setRemovalAttemptHookForTest([gc_state_fails] { gc_state_fails->store(true); }); + const size_t requests_before = table.backend->seenCount(); + const auto first_failure = failureOf([&] { store->dropNamespace(table.ns); }); + store->setRemovalAttemptHookForTest({}); + gc_state_fails->store(false); + + ASSERT_TRUE(first_failure.has_value()) << "the first removal must fail"; + EXPECT_GT(table.backend->seenSince(requests_before, Verb::Read, gc_state_key), 0u) << "the gc/state read was never sent"; + ASSERT_EQ(table.backend->seenSince(requests_before, Verb::Write, catalog_key), 0u) << "a catalog write was sent"; + const std::vector slowed = table.backend->slowedKeys(); + ASSERT_EQ(std::count_if(slowed.begin(), slowed.end(), [&](const String & key) { return key != gc_state_key; }), 1) + << "no read of the recovery ran slowly"; + + ASSERT_TRUE(store->refTableRecoveredForTest(table.ns)) << "the first removal left the table unrecovered"; + const uint64_t recoveries_before = store->recoveryInstallCountForTest(); + const auto failure = failureOf([&] { store->dropNamespace(table.ns); }); + ASSERT_FALSE(failure.has_value()) << *failure; + EXPECT_EQ(store->recoveryInstallCountForTest(), recoveries_before) << "the repeated removal recovered the table again"; + EXPECT_FALSE(store->resolveRef(table.ns, "part_a").has_value()); + EXPECT_FALSE(store->resolveRef(table.ns, "part_b").has_value()); +} diff --git a/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp b/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp index f25858508d8a4..6950be2aa8d0a 100644 --- a/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp +++ b/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp @@ -3590,7 +3590,7 @@ TEST(CASCatalogLifecycleReconciler, ALeaderDeposedWhileQueuedForTheCatalogLaneSe std::thread other_writer([&] { CasOperation other_op = requests.admit(); - (void)other_op.hotKeys().submit(catalog_key, other_op, other_op.freeze(Retry::standard()), + (void)other_op.hotKeys().submit(catalog_key, other_op, Retry::standard(), [&](const std::optional &) -> std::optional { holding.count_down(); @@ -3628,10 +3628,11 @@ TEST(CASCatalogLifecycleReconciler, ALeaderDeposedWhileQueuedForTheCatalogLaneSe EXPECT_EQ(catalogRow(op, layout, stalled.ns), std::optional{stalled}); } -/// The leader reaches the catalog lane with a quarter of its cancel's window left, and every read of -/// `gc/state` fails retryably. The authority check ends by the cancel's deadline: no cancel is sent, the -/// row stays, and the writer queued behind gets the lane by then. -TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsByTheCancelDeadline) +/// The leader reaches the catalog lane after three quarters of a window in the queue, and every read +/// of `gc/state` fails retryably. The authority check in the lane gets a window of its own, measured +/// from its start: no cancel is sent, the row stays, and the writer queued behind gets the lane once +/// that window ends. +TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsOneWindowAfterItsStart) { auto backend = std::make_shared(); auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); @@ -3646,14 +3647,19 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy const CatalogEntry stalled = seedStalledCreating(op, store, "00/slow-authority@cas@", hexToU128("000000000000000000000000000000d5"), CreatorFence{.server_root_id = "gone", .writer_epoch = 1, .fence_generation = 1}); backend->clearJournal(); - backend->afterReadOf(gc_state_key, [] { throw Poco::TimeoutException("injected timeout of the gc/state read"); }); + std::atomic last_authority_read_at = 0; + backend->afterReadOf(gc_state_key, [&] + { + last_authority_read_at = clock.now.load(); + throw Poco::TimeoutException("injected timeout of the gc/state read"); + }); std::latch holding(1); std::latch release(1); std::thread other_writer([&] { CasOperation other_op = requests.admit(); - (void)other_op.hotKeys().submit(catalog_key, other_op, other_op.freeze(Retry::standard()), + (void)other_op.hotKeys().submit(catalog_key, other_op, Retry::standard(), [&](const std::optional &) -> std::optional { holding.count_down(); @@ -3665,8 +3671,10 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy /// Fail-closed like the GC leader's own refresh: authority is held only after a completed read. std::atomic authority_held = true; + std::atomic last_check_started_at = 0; const auto refresh = [&](const Retry & bound) { + last_check_started_at = clock.now.load(); authority_held = false; try { @@ -3680,8 +3688,9 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy } }; CasOperation leader_op = requests.admit([&] { return authority_held.load(); }); - /// The cancel freezes `Retry::standard` before it queues; no fake time passes before that. - const uint64_t cancel_deadline = clock.now.load() + DB::Cas::kDefaultRequestWindowMs; + /// The end a window shared by the queue wait and the check would have; no fake time passes before + /// the leader queues. + const uint64_t shared_deadline = clock.now.load() + DB::Cas::kDefaultRequestWindowMs; const CasFoldSeal parent; CatalogLifecycleReconciler reconciler(leader_op, layout, parent, everyCreatorTerminal); CatalogLifecycleReconcileResult result; @@ -3705,7 +3714,7 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy { CasOperation queued_op = requests.admit(); (void)queued_op.hotKeys().submit(catalog_key, queued_op, - queued_op.freeze(Retry::within(10 * DB::Cas::kDefaultRequestWindowMs)), + Retry::within(10 * DB::Cas::kDefaultRequestWindowMs), [&](const std::optional &) -> std::optional { lane_reached_at = clock.now.load(); @@ -3731,8 +3740,11 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy EXPECT_EQ(reconciler.cancelledCreating(), 0u); EXPECT_EQ(catalogRow(op, layout, stalled.ns), std::optional{stalled}); ASSERT_NE(lane_reached_at.load(), 0u) << "the writer queued behind the leader got the lane"; - EXPECT_LE(lane_reached_at.load(), cancel_deadline) - << "the lane was held " << lane_reached_at.load() - cancel_deadline << " ms past the cancel's deadline"; + EXPECT_GT(last_authority_read_at.load(), shared_deadline) << "the check in the lane was cut at the shared deadline"; + /// One envelope and the longest backoff past the check's own window. + const uint64_t check_end = last_check_started_at.load() + DB::Cas::kDefaultRequestWindowMs; + EXPECT_LE(lane_reached_at.load(), check_end + requests.attemptReservationMs() + 5'000) + << "the lane was held " << lane_reached_at.load() - check_end << " ms past the check's own window"; } /// One creator root has rows at two writer epochs, and its slot is live at the later one. The earlier @@ -5060,7 +5072,7 @@ TEST(CASOwnCreatingCancel, AnAdmissionStartingInsideTheLaneKeepsTheRow) std::thread holder([&] { CasOperation holder_op = store->mountRequests().admit(); - (void)holder_op.hotKeys().submit(catalog_key, holder_op, holder_op.freeze(Retry::standard()), + (void)holder_op.hotKeys().submit(catalog_key, holder_op, Retry::standard(), [&](const std::optional &) -> std::optional { holding.count_down(); diff --git a/src/Disks/tests/gtest_cas_part_write.cpp b/src/Disks/tests/gtest_cas_part_write.cpp index 5e09d2ea7ae77..9c36c9cacf3fb 100644 --- a/src/Disks/tests/gtest_cas_part_write.cpp +++ b/src/Disks/tests/gtest_cas_part_write.cpp @@ -2520,6 +2520,8 @@ class BlobPutFaultBackend final : public InMemoryBackend using InMemoryBackend::head; int fault_count = 0; /// remaining ambiguous faults on matching create attempts bool land_despite_fault = false; /// the faulted attempt's own write actually lands (response lost) + bool fault_is_not_std_exception = false; /// the injected fault does not derive from `std::exception` + std::exception_ptr fault; /// thrown instead of the ambiguous timeout when set int publish_stream_attempts = 0; /// unconditional streaming publications observed int publish_copy_attempts = 0; /// unconditional native-copy publications observed int blob_head_attempts = 0; /// transaction-level blob observations @@ -2556,12 +2558,20 @@ class BlobPutFaultBackend final : public InMemoryBackend InMemoryBackend::publish(request, access); else if (const auto * streaming = std::get_if(&request.publication)) (void)streaming->open_payload(); + if (fault_is_not_std_exception) + throw NotAStdException{}; + if (fault) + std::rethrow_exception(fault); throw Poco::TimeoutException("BlobPutFaultBackend: simulated ambiguous publication (response lost)"); } InMemoryBackend::publish(request, access); } private: + struct NotAStdException + { + }; + static bool isBlobBodyKey(const String & key) { return key.find("/blobs/") != String::npos && !key.ends_with(".meta"); @@ -2696,16 +2706,10 @@ TEST(CASPartWrite, EveryPhysicalPublicationMintsAFreshIncarnationTag) << "a repeated incarnation_tag is a repeated incarnation: GC's condemn would name the live body"; } -/// The publication loop captures ONE bound before it starts, and every verb of every iteration shares -/// it -- so eight iterations cannot spend eight request windows. Here each ambiguous -/// publication burns four ninths of the window on the injected clock, so the third one carries the loop -/// past the window it captured and the next iteration's HEAD refuses to start. The insert is refused as -/// retry-later, which is what a caller can act on; the alternative is a single blob upload sitting on -/// the request for twenty-five minutes. The eight-attempt cap stays as the secondary bound. -/// -/// The throw and the publication count are what fail if the shared bound regresses: without it this -/// same fixture publishes a fourth time and the call SUCCEEDS. -TEST(CASPartWrite, EnsureBlobPresentIsBoundedByTheOneWindowItCaptured) +/// Each request of the publication loop has a window of its own, so a publication that burns four ninths +/// of a window does not shorten the next request. The loop ends at the eight-publication cap and the +/// retry-later error it throws carries the last publication's message. +TEST(CASPartWrite, EnsureBlobPresentEndsAtTheEighthAmbiguousPublication) { auto b = std::make_shared(); auto s = openBlobFaultPool(b); @@ -2721,16 +2725,74 @@ TEST(CASPartWrite, EnsureBlobPresentIsBoundedByTheOneWindowItCaptured) build->precommitAdd(ns, "part_blob_long_loop", id); int payload_streams = 0; - b->fault_count = 3; - expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] + b->fault_count = 8; + String message; + try { (void)build->putBlob(idOf(payload), countingSource(payload, payload_streams)); - }); + ADD_FAILURE() << "the eighth ambiguous publication must end the loop"; + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::NETWORK_ERROR); + message = e.message(); + } + + EXPECT_EQ(b->publish_stream_attempts, 8); + EXPECT_NE(message.find("simulated ambiguous publication"), String::npos) << message; + /// More than three request windows: no window spans the loop's requests. + EXPECT_GT(now->load(), kDefaultRequestWindowMs * 3); +} + +/// The eighth publication is the last one the loop may make: a body that lands on it is committed. +TEST(CASPartWrite, ABodyPublishedOnTheEighthAttemptCommits) +{ + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-eighth"; + auto build = startBuildFor(s, ns, "part_blob_eighth"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload)}); + build->precommitAdd(ns, "part_blob_eighth", id); + + int payload_streams = 0; + b->fault_count = 7; + const PutBlobResult res = build->putBlob(idOf(payload), countingSource(payload, payload_streams)); + + EXPECT_EQ(res.size, payload.size()); + EXPECT_EQ(b->publish_stream_attempts, 8); + EXPECT_NO_THROW(build->promote(ns, "part_blob_eighth", build->buildId(), id)); +} + +/// A fault that is not a `std::exception` ends the loop like any other ambiguous publication, and +/// the error still says what the last publication failed with. +TEST(CASPartWrite, ANonStdExceptionOnTheEighthPublicationKeepsItsMessage) +{ + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-non-std"; + auto build = startBuildFor(s, ns, "part_blob_non_std"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload)}); + build->precommitAdd(ns, "part_blob_non_std", id); + + int payload_streams = 0; + b->fault_count = 8; + b->fault_is_not_std_exception = true; + String message; + try + { + (void)build->putBlob(idOf(payload), countingSource(payload, payload_streams)); + ADD_FAILURE() << "the eighth ambiguous publication must end the loop"; + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::NETWORK_ERROR); + message = e.message(); + } - EXPECT_EQ(b->publish_stream_attempts, 3) << "the fourth iteration must not start a publication"; - /// The clock is past the captured deadline when the loop stops, which is what stopped it: two - /// publications leave it inside the window and the third carries it past. - EXPECT_GE(now->load(), kDefaultRequestWindowMs); + EXPECT_EQ(b->publish_stream_attempts, 8); + EXPECT_NE(message.find("NotAStdException"), String::npos) << message; } namespace diff --git a/src/Disks/tests/gtest_cas_ref_catalog.cpp b/src/Disks/tests/gtest_cas_ref_catalog.cpp index 686cb22de8200..7587017056eef 100644 --- a/src/Disks/tests/gtest_cas_ref_catalog.cpp +++ b/src/Disks/tests/gtest_cas_ref_catalog.cpp @@ -1115,13 +1115,12 @@ TEST(CASRefCatalogDeathTest, CasUpdateThrowsOnVanishMidRetryInsteadOfReplacingTh } #endif -/// Persistent contention ends at the write policy's DEADLINE, with the typed retryable error -- not -/// after a fixed number of unslept iterations, and not in an infinite spin. `mutate` re-arms the -/// one-shot conflict injection on every call, so every attempt is refused; the injected clock reaches -/// the deadline without the test sleeping at all. -TEST(CASRefCatalog, CasUpdateEndsAtTheDeadlineNotAfterAHundredUnsleptIterations) +/// Persistent contention ends after 100 submissions, each refusal but the last followed by a pause, +/// with the typed retryable error. `mutate` re-arms the one-shot conflict injection on every call, so +/// every write is refused. +TEST(CASRefCatalog, CasUpdateEndsAfterAHundredPacedSubmissions) { - auto backend = std::make_shared(); + auto backend = std::make_shared(); DB::Cas::tests::FakeClock clock; CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); requests.setNowFnForTest(clock.nowFn()); @@ -1129,10 +1128,9 @@ TEST(CASRefCatalog, CasUpdateEndsAtTheDeadlineNotAfterAHundredUnsleptIterations) CasOperation op = requests.admit(); Layout layout("p"); CasRefCatalog::initializeEmptyForNewPool(op, layout); - const uint64_t started_at = clock.now; + const uint64_t writes_before = backend->writes(layout.refCatalogKey()); - int mutate_calls = 0; - DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 submissions)", [&] { CasRefCatalog::casUpdate(op, layout, [&](const RefCatalog & cur) { @@ -1142,11 +1140,8 @@ TEST(CASRefCatalog, CasUpdateEndsAtTheDeadlineNotAfterAHundredUnsleptIterations) return next; }); }); - EXPECT_GT(mutate_calls, 1); /// genuinely retried, not a single-shot failure - EXPECT_FALSE(clock.sleeps.empty()) << "every retry must back off; an unslept loop would burn the " - "deadline on requests instead of waiting out the contention"; - EXPECT_GE(clock.now - started_at, kDefaultRequestWindowMs - 5000) - << "the loop ended at the policy's own deadline, not at an iteration count"; + EXPECT_EQ(backend->writes(layout.refCatalogKey()) - writes_before, 100u); + EXPECT_EQ(clock.sleeps.size(), 99u) << "every refusal but the last is paced"; } TEST(CASRefCatalog, CasAdmitEntryAcceptsAnOrdinaryCreation) @@ -1544,7 +1539,7 @@ TEST(CASRefCatalogRemoval, AWriterLandingDuringEveryBackoffCannotStarveTheErase) EXPECT_EQ(current.entries.front().ns, RootNamespace{"b0"}) << "the writer's row stays, the erased row is gone"; } - /// A pause that itself runs past the window is followed by no erase write. + /// A pause that runs past a whole window is followed by the next erase: it binds its own window. { auto backend = std::make_shared(); DB::Cas::tests::FakeClock clock; @@ -1553,24 +1548,17 @@ TEST(CASRefCatalogRemoval, AWriterLandingDuringEveryBackoffCannotStarveTheErase) auto pause = clock.sleepFn(); requests.setSleepFnForTest([&](uint64_t ms) { pause(ms + 200'000); }); CasOperation op = requests.admit(); - const Layout layout("erase-pause-past-deadline"); + const Layout layout("erase-pause-past-a-window"); seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); const uint64_t writes_after_seed = backend->writes(layout.refCatalogKey()); backend->refuseNextWrite(layout.refCatalogKey()); - try - { - (void)deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh); - ADD_FAILURE() << "a pause that crosses the window must end the call"; - } - catch (const DB::Exception & e) - { - EXPECT_EQ(e.code(), DB::ErrorCodes::NETWORK_ERROR); - EXPECT_NE(e.message().find("deadline"), String::npos) << e.message(); - } - EXPECT_EQ(backend->writes(layout.refCatalogKey()) - writes_after_seed, 1u) - << "only the refused erase; nothing is sent after the pause crossed the deadline"; - EXPECT_EQ(CasRefCatalog::read(op, layout).catalog.entries, std::vector{removing}); + EXPECT_EQ(deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh), + CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); + EXPECT_EQ(clock.sleeps.size(), 1u); + EXPECT_EQ(backend->writes(layout.refCatalogKey()) - writes_after_seed, 2u) + << "the refused erase and the erase after the pause"; + EXPECT_TRUE(CasRefCatalog::read(op, layout).catalog.entries.empty()); } } @@ -1855,13 +1843,9 @@ TEST(CASRefCatalogRemoval, ACommitTheResolutionReadContradictsFailsRetryLaterIns << "the message must name the life still observed: " << message; } -/// The loop captures ONE bound before it starts and every call it makes shares it, so a permanently -/// contended catalog gives up "retry later" inside one request window rather than spending a fresh -/// window per verb across a hundred paced iterations -- which is hours against a document that -/// promises one window. Every erase is refused and the injected clock absorbs every paced retry, -/// so what ends the call is visible in the virtual time it took. The attempt cap stays as the -/// secondary bound; it is not what ends this call. -TEST(CASRefCatalogRemoval, PerpetualConflictGivesUpWithinOneWindowNotAtTheAttemptCap) +/// Every erase is refused. Each request binds its own window, so the attempt cap ends the call: 100 +/// erases, a pause after each refusal but the last, and the resolution read after every erase. +TEST(CASRefCatalogRemoval, PerpetualConflictGivesUpAfterAHundredErases) { class AlwaysRefusesCatalogWrites final : public WriteCountingBackend { @@ -1911,7 +1895,7 @@ TEST(CASRefCatalogRemoval, PerpetualConflictGivesUpWithinOneWindowNotAtTheAttemp .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); backend->refused_key = layout.refCatalogKey(); - const uint64_t start = clock.now; + const size_t sleeps_before = clock.sleeps.size(); String message; try { @@ -2667,20 +2651,62 @@ TEST(CASRefCatalog, CreateNamespaceStep1FailsAtOnceWhenItsCatalogReadIsRefused) } #endif -/// The pause before a new decision is gated like the engine's own reissue pause: with no room left -/// for the pause and one attempt, the call ends without sleeping. -TEST(CASRefCatalog, CreateNamespaceStep1DoesNotPausePastItsDeadline) +/// The first step-1 write takes more than a window and its response is lost. The next decision's read +/// and write each bind their own window, so the row is created. +TEST(CASRefCatalog, CreateNamespaceStep1PausesThenDecidesAgainInItsOwnWindow) { Step1Fixture t; t.f.pool.setAttemptReservationForTest(1'000); t.backend->failNextWriteWith(t.backend->catalog_key, lostResponse()); - /// Leaves 1.5 s of the window: enough for the settle read, too little for a pause plus two envelopes. + bool slowed = false; + uint64_t first_write_ended_ms = 0; + t.backend->on_write = [&] + { + if (std::exchange(slowed, true)) + return; + t.f.clock.now.fetch_add(kDefaultRequestWindowMs + 1); + first_write_ended_ms = t.f.clock.now.load(); + }; + const size_t sleeps_before = t.f.clock.sleeps.size(); + + ASSERT_EQ(t.createA(), CasRefCatalog::NamespaceCreationOutcome::Live); + t.expectDistinctIncarnationsAndTheLastOneLive(); + EXPECT_EQ(t.step1Incarnations().size(), 2u); + EXPECT_EQ(t.f.clock.sleeps.size() - sleeps_before, 1u); + /// Only pauses move the clock after the slow write, so the call ends well inside the next window. + EXPECT_LE(t.f.clock.now.load() - first_write_ended_ms, kDefaultRequestWindowMs + 1'000 + 5'000); +} + +/// The same with an explicit lease that leaves 1.5 s: the pause fits under the lease, the next write's +/// two envelopes do not, so no second write is sent. +TEST(CASRefCatalog, CreateNamespaceStep1PausesThenSendsNoWriteWithoutRoomUnderItsLease) +{ + Step1Fixture t; + t.f.pool.setAttemptReservationForTest(1'000); + t.backend->failNextWriteWith(t.backend->catalog_key, lostResponse()); + const Retry policy = Retry::untilLeaseSafe(t.f.clock.now.load() + kDefaultRequestWindowMs, 0); t.backend->on_write = [&] { t.f.clock.now.fetch_add(kDefaultRequestWindowMs - 1'500); }; const size_t sleeps_before = t.f.clock.sleeps.size(); - DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { (void)t.createA(); }); + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, + [&] { (void)CasRefCatalog::createNamespace(t.pool_op, t.layout, 1, RootNamespace{"a"}, t.creator, policy); }); EXPECT_EQ(t.backend->bodies.size(), 1u); - EXPECT_EQ(t.f.clock.sleeps.size() - sleeps_before, 0u); + EXPECT_EQ(t.f.clock.sleeps.size() - sleeps_before, 1u); +} + +/// The smallest window a write accepts is two envelopes and 1 ms. After a lost step-1 write the next +/// decision's write gets a whole such window of its own, so the row is created. +TEST(CASRefCatalog, CreateNamespaceStep1DecidesAgainWithTheSmallestValidWindow) +{ + Step1Fixture t; + t.f.pool.setAttemptReservationForTest(1'000); + t.backend->failNextWriteWith(t.backend->catalog_key, lostResponse()); + /// Each catalog write takes 2 ms, so no window that started before a write has room for another. + t.backend->on_write = [&] { t.f.clock.now.fetch_add(2); }; + + ASSERT_EQ(CasRefCatalog::createNamespace(t.pool_op, t.layout, 1, RootNamespace{"a"}, t.creator, Retry::within(2'001)), + CasRefCatalog::NamespaceCreationOutcome::Live); + t.expectDistinctIncarnationsAndTheLastOneLive(); } /// The step-1 write lands and its response is lost; before the next decision a sibling completes the diff --git a/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp b/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp index e1b618bc31ce9..b7eeba9ea65a6 100644 --- a/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp +++ b/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -683,11 +684,15 @@ class ChurningCatalogBackend final : public InMemoryBackend } bool churning = false; + size_t churned_reads = 0; std::optional read(const String & key, DB::Cas::TransportAccess & access) override { if (churning && key == catalog_key) + { + ++churned_reads; bumpEveryCreatorFence(access); + } return InMemoryBackend::read(key, access); } @@ -711,15 +716,16 @@ class ChurningCatalogBackend final : public InMemoryBackend } /// A catalog entry that moves under every read drives `resolveNamespaceLife`'s state machine for ever. -/// One `Retry` frozen before the loop bounds the WHOLE resolution to a single standard window, and -/// every re-read a competing actor forces is paced by a jittered sleep -- so a permanently churning -/// catalog costs one window, not one fresh window per verb per iteration hammered with no wait between -/// them. -/// -/// What the clock bound below does NOT check: it bounds this call's own wall time, not the number of -/// requests the loop sent, and it says nothing about the paths that converge. -TEST(CASRefCatalogBirthWiring, APerpetuallyChurningCatalogEntryIsPacedAndEndsWithinOneWindow) +/// Every re-read a competing actor forces is paced, and the loop ends after its 32 rounds. The pause +/// before the last round carries the clock past a whole window, so the last round is sent only if each +/// of its requests binds its own window. +TEST(CASRefCatalogBirthWiring, APerpetuallyChurningCatalogEntryIsPacedAndEndsAfterItsRounds) { + constexpr size_t kRounds = 32; + /// One attempt's reservation on a disk with default settings, and the longest `Retry::backoff` draw. + constexpr uint64_t kEnvelopeMs = 7'000; + constexpr uint64_t kMaxBackoffMs = 5'000; + auto backend = std::make_shared(Layout{"p"}.refCatalogKey()); CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); CasOperation op = requests.admit(); @@ -735,18 +741,28 @@ TEST(CASRefCatalogBirthWiring, APerpetuallyChurningCatalogEntryIsPacedAndEndsWit .creator = CreatorFence{.server_root_id = "foreign-creator", .writer_epoch = 7, .fence_generation = 1}}; CasRefCatalog::casAdmitEntry(op, layout, 1, creating); - auto clock = DB::Cas::tests::VirtualRetryClock::installOn(store); + auto now_ms = std::make_shared(0); + size_t pauses = 0; + std::optional last_round_started_ms; + size_t reads_before_last_round = 0; + store->setCasRequestNowFnForTest([now_ms] { return *now_ms; }); + store->setCasRetrySleepForTest([&, now_ms](uint64_t ms) + { + *now_ms += ms; + if (++pauses == kRounds - 1) + { + *now_ms += DB::Cas::kDefaultRequestWindowMs; + last_round_started_ms = *now_ms; + reads_before_last_round = backend->churned_reads; + } + }); backend->churning = true; - const size_t pauses_before = clock->pauseCount(); - const uint64_t now_before = clock->nowMs(); - - expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { store->namespaceLife(ns); }); - - /// Sixteen jittered draws cannot exhaust the request window even at their ceiling, so an unpaced loop - /// reaches its iteration cap having slept nothing at all. - EXPECT_GE(clock->pauseCount() - pauses_before, 16u) << "each forced re-read is paced"; - /// The frozen window, plus at most one backoff draw the pace does not consult the deadline for, - /// plus the virtual clock's one extra millisecond per pause. - EXPECT_LE(clock->nowMs() - now_before, DB::Cas::kDefaultRequestWindowMs + 5'000 + 100) - << "one standard window bounds the whole loop"; + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, fmt::format("after {} attempts", kRounds), + [&] { store->namespaceLife(ns); }); + + EXPECT_GE(pauses, kRounds - 1) << "each re-read a lost round forced is paced"; + ASSERT_TRUE(last_round_started_ms.has_value()); + EXPECT_EQ(backend->churned_reads - reads_before_last_round, 2u) << "the last round's loop read and its decision read"; + EXPECT_LE(*now_ms - *last_round_started_ms, kEnvelopeMs + kMaxBackoffMs); } diff --git a/src/Disks/tests/gtest_cas_shared_deadline.cpp b/src/Disks/tests/gtest_cas_shared_deadline.cpp index 6d8a044bab552..3a0d895b74178 100644 --- a/src/Disks/tests/gtest_cas_shared_deadline.cpp +++ b/src/Disks/tests/gtest_cas_shared_deadline.cpp @@ -27,6 +27,11 @@ /// what a window shared with the next request would have left. The other sections check a lost /// write's settlement and the caps on decisions and submissions. +namespace ProfileEvents +{ +extern const Event CASRefRecoveryRetries; +} + namespace DB::ErrorCodes { extern const int NETWORK_ERROR; @@ -210,6 +215,139 @@ struct Rival CasOperation op; }; +/// A mount fence the test trips: by re-arming its generation, or by letting the lease run out. +struct TrippableFence +{ + enum class Trip : uint8_t { Rearm, LeaseExpiry }; + + uint64_t generation = 0; + bool lease_expired = false; + + Fence fence() + { + return Fence{ + [this] { return generation; }, + [this](uint64_t admitted_generation, uint64_t) + { + if (admitted_generation != generation) + return Fence::Admit::LostOrRearmed; + return lease_expired ? Fence::Admit::NoBudget : Fence::Admit::Ok; + }, + [](uint64_t) {}}; + } + + void trip(Trip how) + { + if (how == Trip::Rearm) + ++generation; + else + lease_expired = true; + } +}; + +String tripName(TrippableFence::Trip how) +{ + return how == TrippableFence::Trip::Rearm ? "re-armed generation" : "expired lease"; +} + +CatalogEntry liveEntry(const String & ns, uint64_t incarnation) +{ + return CatalogEntry{.ns = RootNamespace{ns}, .state = NsState::Live, .incarnation = UInt128(incarnation)}; +} + +/// Another server writing the ref catalog. Inside each of the plane's next `times` writes of the catalog +/// it admits a new row, so that write meets a moved precondition. +struct CatalogRival +{ + CatalogRival(Plane & plane, const Layout & layout_, size_t times) + : layout(layout_) + , requests(plane.backend, Fence::open(), ManualClock::nowFnOf(plane.clock), ManualClock::sleepFnOf(plane.clock), + nullptr, kWindowMs) + , op(requests.admit()) + { + requests.setAttemptReservationForTest(kEnvelopeMs); + plane.backend->armWith(Verb::Write, [this](const String & k) { return k == layout.refCatalogKey() && !inside; }, + [this] { move(); }, times); + } + + void move() + { + inside = true; + CasRefCatalog::casAdmitEntry(op, layout, 1, liveEntry(fmt::format("rival{}", moves), 1000 + moves)); + inside = false; + ++moves; + } + + Layout layout; + bool inside = false; + size_t moves = 0; + CasRequests requests; + CasOperation op; +}; + +/// A mounted pool whose request planes read a clock the test moves and reserve what a real disk does. +struct PoolOnManualClock +{ + std::shared_ptr backend = std::make_shared(); + std::shared_ptr clock = std::make_shared(); + PoolPtr store; + + PoolOnManualClock() + { + store = Pool::open(backend, PoolConfig{.pool_prefix = "p", .server_root_id = "test"}); + store->setCasRequestNowFnForTest(ManualClock::nowFnOf(clock)); + store->setCasRetrySleepForTest(ManualClock::sleepFnOf(clock)); + store->mountRequests().setAttemptReservationForTest(kEnvelopeMs); + backend->stampWith(ManualClock::nowFnOf(clock)); + } + + void slowDown(Verb verb, const String & key) + { + backend->armWith(verb, exactly(key), [clock_ = clock] { clock_->advance(kFirstStepMs); }); + } +}; + +/// A pool whose LEASE clock is the test's too, for the bounds that are kept on it. The lease is an +/// hour long, so the request window and not the lease is what ends a wait. +PoolPtr openOnBootClock(const std::shared_ptr & backend, const std::shared_ptr & clock) +{ + PoolConfig config; + config.pool_prefix = "p"; + config.server_root_id = "test"; + config.mount_lease_ttl_ms = std::chrono::hours(1); + config.unsafe_remount_no_delay = true; + config.boot_ms_fn = ManualClock::nowFnOf(clock); + PoolPtr store = Pool::open(backend, config); + store->setCasRetrySleepForTest(ManualClock::sleepFnOf(clock)); + store->mountRequests().setAttemptReservationForTest(kEnvelopeMs); + backend->stampWith(ManualClock::nowFnOf(clock)); + return store; +} + +ManifestEntry blobManifestEntry(const String & path, const String & payload) +{ + ManifestEntry entry; + entry.path = path; + entry.placement = EntryPlacement::Blob; + entry.ref = idOf(payload); + entry.blob_size = payload.size(); + return entry; +} + +ManifestId publishOnePart(const PoolPtr & store, const RootNamespace & ns, const String & ref, const String & payload) +{ + PartWriteInfo info; + info.intended_ref = ns.string() + "/" + ref; + auto build = store->beginPartWrite(info); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, ref, id); + build->putBlob(idOf(payload), BlobSource::fromString(payload)); + build->promote(ns, ref, build->buildId(), id); + return id; +} + +} + /// --------------------------------------------------------------------------------------------- /// The request engine: every request binds its own window when it is sent. /// --------------------------------------------------------------------------------------------- @@ -340,6 +478,306 @@ TEST(CASSharedDeadline, StreamBodyIsNotMeasuredAgainstTheWindowOfItsOpen) EXPECT_EQ(read, body); } +/// --------------------------------------------------------------------------------------------- +/// The hot-key lane and the ref catalog loops over it. +/// --------------------------------------------------------------------------------------------- + +/// Nobody else is in the lane: the base read alone uses a window. +TEST(CASSharedDeadline, HotKeyLaneSendsItsWriteAfterASlowBaseRead) +{ + CasHotKeys lane(0); + Plane plane(&lane); + plane.seed("k", "1"); + plane.slowDown(Verb::Read, "k"); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = lane.submit("k", plane.op, Retry::standard(), + [](const std::optional & current) -> std::optional { return current->bytes + ",2"; }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_TRUE(std::holds_alternative(result)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the conditional write", sentSince(*plane.backend, first_ended_ms, Verb::Write, "k")) + << "result: " << outcomeOf(result); + EXPECT_EQ(plane.bytesOf("k"), "1,2"); +} + +/// Another writer holds the key while all but one millisecond of the waiter's window passes. No +/// request of the waiter was slow: the wait is the lane's own. +TEST(CASSharedDeadline, HotKeyLaneServesAWriterThatWaitedBehindAnother) +{ + CasHotKeys lane(0); + Plane plane(&lane); + std::latch parked{1}; + std::latch release{1}; + plane.backend->armWith(Verb::Write, exactly("k"), [&] + { + parked.count_down(); + release.wait(); + }); + + std::optional held; + std::optional waited; + std::thread holder([&] + { + auto op = plane.requests.admit(); + held = lane.submit("k", op, Retry::standard(), [](const std::optional &) -> std::optional { return "1"; }); + }); + parked.wait(); + const uint64_t started_ms = plane.clock->now(); + std::thread waiter([&] + { + auto op = plane.requests.admit(); + waited = lane.submit("k", op, Retry::standard(), [](const std::optional & current) -> std::optional + { + return (current ? current->bytes : String()) + ",2"; + }); + }); + while (lane.queueDepthForTest("k") < 2) + std::this_thread::yield(); + plane.clock->advance(kFirstStepMs); + release.count_down(); + holder.join(); + waiter.join(); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_TRUE(held.has_value()); + ASSERT_TRUE(waited.has_value()); + ASSERT_TRUE(std::holds_alternative(*held)) << "the holder itself failed: " << outcomeOf(*held); + EXPECT_TRUE(std::holds_alternative(*waited)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the waiter's base read", sentSince(*plane.backend, first_ended_ms, Verb::Read, "k")) + << "result: " << outcomeOf(*waited); + EXPECT_EQ(plane.bytesOf("k"), "1,2"); +} + +/// Another server wins the first race late. The update decides again on what the lost write's +/// settling read saw, and its own change lands next to the other server's. +TEST(CASSharedDeadline, CasUpdateDecidesAgainAfterALostRaceThatTookTheWindow) +{ + CasHotKeys lane(0); + Plane plane(&lane); + CasRequests other_server = DB::Cas::tests::openRequestsForTest(plane.backend); + CasOperation other_op = other_server.admit(); + const Layout layout("p"); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + + const String key = layout.refCatalogKey(); + size_t after_the_other_server = 0; + plane.backend->armWith(Verb::Write, exactly(key), [&] + { + plane.clock->advance(kFirstStepMs); + CasRefCatalog::casAdmitEntry(other_op, layout, 1, liveEntry("b", 2)); + after_the_other_server = plane.backend->seenCount(); + }); + + const uint64_t started_ms = plane.clock->now(); + size_t decisions = 0; + const auto failure = failureOf([&] + { + CasRefCatalog::casUpdate(plane.op, layout, [&](const RefCatalog & current) + { + ++decisions; + RefCatalog next = current; + for (CatalogEntry & entry : next.entries) + { + if (entry.ns == RootNamespace{"a"}) + { + entry.state = NsState::Removing; + entry.removal_started_round = 1; + } + } + return next; + }); + }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_FALSE(failure.has_value()) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the read that settles the lost race", + plane.backend->seenSince(after_the_other_server, Verb::Read, key)) + << "decisions made: " << decisions << "; error: " << orNone(failure); + EXPECT_EQ(decisions, 2u); + const RefCatalog durable = CasRefCatalog::read(other_op, layout).catalog; + ASSERT_EQ(durable.entries.size(), 2u); + EXPECT_EQ(durable.entries[0].ns, RootNamespace{"a"}); + EXPECT_EQ(durable.entries[0].state, NsState::Removing) << "the update's own change did not land"; + EXPECT_EQ(durable.entries[1].ns, RootNamespace{"b"}); + EXPECT_EQ(durable.entries[1].state, NsState::Live); +} + +/// The erase landed slowly; the read that resolves it is a request of its own. +TEST(CASSharedDeadline, DeleteCompletedRemovingSendsItsResolutionReadAfterASlowErase) +{ + Plane plane; + const Layout layout("p"); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, .state = NsState::Removing, .incarnation = UInt128{7}, .removal_started_round = 13}; + plane.seed(layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + + const String key = layout.refCatalogKey(); + plane.slowDown(Verb::Write, key); + uint64_t started_ms = 0; + std::optional outcome; + const auto failure = failureOf([&] + { + /// The helper reads the catalog first; the erase loop starts at the first authority refresh. + outcome = DB::Cas::tests::deleteCompletedRemovingForTest(plane.op, layout, removing, ready_parent, + [&] { started_ms = started_ms ? started_ms : plane.clock->now(); }).outcome; + }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_EQ(outcome, std::optional(CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the resolution read", sentSince(*plane.backend, first_ended_ms, Verb::Read, key)) + << "error: " << orNone(failure); + /// The erase's own acknowledgment is not the answer; the resolution read is. + EXPECT_EQ(sentSince(*plane.backend, first_ended_ms, Verb::Read, key), 1u); +} + +/// The leader's authority check in the lane passes late; the cancel it authorised is a request of its own. +TEST(CASSharedDeadline, CancelStalledCreatingSendsItsWriteAfterASlowAuthorityCheck) +{ + CasHotKeys lane(0); + Plane plane(&lane); + const Layout layout("p"); + const CatalogEntry creating{ + .ns = RootNamespace{"c"}, .state = NsState::Creating, .incarnation = UInt128{9}, + .creator = CreatorFence{.server_root_id = "gone", .writer_epoch = 1, .fence_generation = 1}}; + const String key = layout.refCatalogKey(); + plane.seed(key, encodeRefCatalog(RefCatalog{.entries = {creating}})); + + const uint64_t started_ms = plane.clock->now(); + bool checked = false; + std::optional outcome; + const auto failure = failureOf([&] + { + outcome = CasRefCatalog::cancelStalledCreating( + plane.op, layout, creating, [](const CreatorFence &) { return true; }, + [&](const Retry &) + { + if (!std::exchange(checked, true)) + plane.clock->advance(kFirstStepMs); + }); + }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_EQ(outcome, std::optional(CasRefCatalog::StalledCreatingCancelOutcome::Cancelled)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the cancelling write", sentSince(*plane.backend, first_ended_ms, Verb::Write, key)) + << "error: " << orNone(failure); + EXPECT_TRUE(CasRefCatalog::read(plane.op, layout).catalog.entries.empty()); +} + +/// --------------------------------------------------------------------------------------------- +/// A mounted pool: the loops of the ref ledger. +/// --------------------------------------------------------------------------------------------- + +/// The first catalog read of `resolveNamespaceLife` is slow; the next request of the loop is a request +/// of its own, so the first insert into a new table succeeds. +TEST(CASSharedDeadline, ResolveNamespaceLifeSendsItsNextRequestAfterASlowCatalogRead) +{ + PoolOnManualClock pool; + const RootNamespace ns{"srv/new_table"}; + const String key = pool.store->layout().refCatalogKey(); + /// The admission reads the catalog once before the loop; the read after it is the loop's first. + pool.backend->armWith(Verb::Read, [key, reads = std::make_shared(0)](const String & read_key) + { + return read_key == key && ++*reads == 2; + }, [clock = pool.clock] { clock->advance(kFirstStepMs); }); + + const uint64_t started_ms = pool.clock->now(); + const auto failure = failureOf([&] { publishOnePart(pool.store, ns, "part", "payload"); }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_EQ(pool.backend->slowedKeys(), std::vector{key}) << "no catalog read ran slowly"; + EXPECT_FALSE(failure.has_value()) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the next catalog read", sentSince(*pool.backend, first_ended_ms, Verb::Read, key)) + << "error: " << orNone(failure); + EXPECT_TRUE(pool.store->resolveRef(ns, "part").has_value()); +} + +/// The first cancel of `cancelIdleOwnCreatingRows` is slow and lands; the second row's cancel is a +/// request of its own. +TEST(CASSharedDeadline, CancelIdleOwnCreatingRowsCancelsTheSecondRowAfterASlowFirstCancel) +{ + PoolOnManualClock pool; + const Layout & layout = pool.store->layout(); + CasRequests other_requests = DB::Cas::tests::openRequestsForTest(pool.backend); + CasOperation other_op = other_requests.admit(); + const CreatorFence ours{ + .server_root_id = "test", .writer_epoch = pool.store->liveWriterEpoch(), .fence_generation = pool.store->fenceGeneration()}; + for (uint64_t i = 1; i <= 2; ++i) + CasRefCatalog::casAdmitEntry(other_op, layout, 1, CatalogEntry{ + .ns = RootNamespace{fmt::format("srv/own_row_{}", i)}, .state = NsState::Creating, .incarnation = UInt128{i}, + .creator = ours}); + ASSERT_EQ(CasRefCatalog::read(other_op, layout).catalog.entries.size(), 2u); + + const String key = layout.refCatalogKey(); + pool.slowDown(Verb::Write, key); + const uint64_t started_ms = pool.clock->now(); + const auto failure = failureOf([&] { pool.store->cancelIdleOwnCreatingRows(); }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_EQ(pool.backend->slowedKeys(), std::vector{key}) << "no cancel ran slowly"; + const size_t rows_left = CasRefCatalog::read(other_op, layout).catalog.entries.size(); + EXPECT_EQ(rows_left, 0u) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the second row's cancel", sentSince(*pool.backend, first_ended_ms, Verb::Write, key)) + << "rows left: " << rows_left << "; error: " << orNone(failure); +} + +/// The first catalog read of `dropNamespaceImpl` is slow; the table is in memory and nothing else takes +/// time. The removal's next requests are requests of their own. +TEST(CASSharedDeadline, DropNamespaceSendsItsNextRequestAfterASlowFirstRead) +{ + PoolOnManualClock pool; + const RootNamespace ns{"srv/tbl"}; + publishOnePart(pool.store, ns, "part", "payload"); + const String key = pool.store->layout().refCatalogKey(); + pool.slowDown(Verb::Read, key); + + const uint64_t started_ms = pool.clock->now(); + const auto failure = failureOf([&] { pool.store->dropNamespace(ns); }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_EQ(pool.backend->slowedKeys(), std::vector{key}) << "no catalog read ran slowly"; + EXPECT_FALSE(failure.has_value()) + << "catalog reads after the slow read: " << sentSince(*pool.backend, first_ended_ms, Verb::Read, key) + << "; error: " << orNone(failure); + EXPECT_FALSE(pool.store->resolveRef(ns, "part").has_value()); +} + +/// The body `HEAD` is slow and finds nothing; the publication that follows is a request of its own and +/// must still be sent. +TEST(CASSharedDeadline, BlobLoopStartsItsPublicationAfterASlowHead) +{ + PoolOnManualClock pool; + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-behind-a-slow-head"; + const String key = pool.store->layout().blobKey(idOf(payload)); + + PartWriteInfo info; + info.intended_ref = ns.string() + "/part"; + auto build = pool.store->beginPartWrite(info); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + pool.slowDown(Verb::Head, key); + const uint64_t started_ms = pool.clock->now(); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload), BlobSource::fromString(payload)); + build->promote(ns, "part", build->buildId(), id); + }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_EQ(pool.backend->slowedKeys(), std::vector{key}) << "the body `HEAD` never ran slowly"; + EXPECT_FALSE(failure.has_value()) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the body publication", sentSince(*pool.backend, first_ended_ms, Verb::Publish, key)) + << "error: " << orNone(failure); + EXPECT_EQ(pool.backend->publicationsOf(key), 1u); +} + /// --------------------------------------------------------------------------------------------- /// A write whose response is lost: the settling read is a request with its own window. /// --------------------------------------------------------------------------------------------- @@ -536,3 +974,301 @@ TEST(CASSharedDeadline, RemoveCurrentEndsAfterAHundredDecisions) EXPECT_NE(plane.bytesOf("k"), ""); } +/// The fence trips while the read that settles the hundredth lost race is in flight. That read still +/// answers, and the call reports the trip, as the pause before a next decision would have, not the count. +TEST(CASSharedDeadline, ReadModifyWriteReportsAFenceTripDuringItsLastSettlementNotTheCount) +{ + const auto run = [](TrippableFence::Trip how, GaveUp::Why why, GaveUp::Source source) + { + SCOPED_TRACE(tripName(how)); + TrippableFence mount; + Plane plane(nullptr, mount.fence()); + plane.seed("k", "v"); + Rival rival(plane, Verb::Write, "k", 10 * kCasMaxDecisions); + bool tripped = false; + plane.backend->armWith(Verb::Read, + [&](const String & key) { return key == "k" && !rival.inside && rival.moves == kCasMaxDecisions; }, + [&] + { + mount.trip(how); + tripped = true; + }); + const size_t journal_from = plane.backend->seenCount(); + + size_t decisions = 0; + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional & current) -> std::optional + { + ++decisions; + return current->bytes + "x"; + }, Retry::standard()); + + ASSERT_TRUE(tripped) << "the hundredth settling read was never sent; " << outcomeOf(result); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, why) << outcomeOf(result); + EXPECT_EQ(gave_up->deadline_source, source) << outcomeOf(result); + EXPECT_EQ(gave_up->attempts_sent, kCasMaxDecisions); + EXPECT_EQ(decisions, kCasMaxDecisions); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, "k") - rival.moves, kCasMaxDecisions); + }; + run(TrippableFence::Trip::Rearm, GaveUp::Why::FenceLost, GaveUp::Source::Policy); + run(TrippableFence::Trip::LeaseExpiry, GaveUp::Why::Deadline, GaveUp::Source::Lease); +} + +/// The fence trips while the hundredth conditional delete is in flight and meets a replaced object. +TEST(CASSharedDeadline, RemoveCurrentReportsAFenceTripDuringItsLastDeleteNotTheCount) +{ + const auto run = [](TrippableFence::Trip how, const String & expected) + { + SCOPED_TRACE(tripName(how)); + TrippableFence mount; + Plane plane(nullptr, mount.fence()); + plane.seed("k", "v"); + Rival rival(plane, Verb::Remove, "k", 10 * kCasMaxDecisions); + rival.after_move = [&] + { + if (rival.moves == kCasMaxDecisions) + mount.trip(how); + }; + const size_t journal_from = plane.backend->seenCount(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, expected, + [&] { (void)plane.op.removeCurrent("k", Retry::standard()); }); + EXPECT_EQ(rival.moves, kCasMaxDecisions); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Head, "k"), kCasMaxDecisions); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Remove, "k"), kCasMaxDecisions); + }; + run(TrippableFence::Trip::Rearm, "mount fence tripped"); + run(TrippableFence::Trip::LeaseExpiry, "no lease budget"); +} + +/// The fence trips while the read that settles the hundredth refused submission is in flight. +TEST(CASSharedDeadline, CasUpdateReportsAFenceTripDuringItsLastSettlementNotTheCount) +{ + TrippableFence mount; + CasHotKeys lane(16ULL << 20); + Plane plane(&lane, mount.fence()); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + CatalogRival rival(plane, layout, 10 * kCasMaxDecisions); + bool tripped = false; + plane.backend->armWith(Verb::Read, + [&](const String & k) { return k == key && !rival.inside && rival.moves == kCasMaxDecisions; }, + [&] + { + mount.trip(TrippableFence::Trip::Rearm); + tripped = true; + }); + const size_t journal_from = plane.backend->seenCount(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "mount fence tripped", [&] + { + CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) { return current; }); + }); + EXPECT_TRUE(tripped) << "the hundredth settling read was never sent"; + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions); +} + +/// `casUpdate` counts submissions to the hot-key lane: one submission can run its `decide` twice on a +/// cached catalog, so the tests count the plane's writes of the catalog, not the calls of `mutate`. +TEST(CASSharedDeadline, CasUpdateSucceedsOnTheHundredthSubmission) +{ + CasHotKeys lane(16ULL << 20); + Plane plane(&lane); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + CatalogRival rival(plane, layout, kCasMaxDecisions - 1); + size_t pauses = 0; + plane.countPauses(pauses); + const size_t journal_from = plane.backend->seenCount(); + + const auto failure = failureOf([&] + { + CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) + { + RefCatalog next = current; + next.entries.front().state = NsState::Removing; + next.entries.front().removal_started_round = 1; + return next; + }); + }); + + EXPECT_FALSE(failure.has_value()) << orNone(failure); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions); + EXPECT_EQ(rival.moves, kCasMaxDecisions - 1); + EXPECT_EQ(pauses, kCasMaxDecisions - 1); + const RefCatalog durable = CasRefCatalog::read(plane.op, layout).catalog; + EXPECT_EQ(durable.entries.size(), 1 + rival.moves); + EXPECT_EQ(durable.entries.front().state, NsState::Removing); +} + +/// Every write meets a moved precondition. The hundredth refusal ends the call without a pause after +/// it, and the error names a clean conflict. +TEST(CASSharedDeadline, CasUpdateEndsAfterAHundredSubmissionsOnACleanConflict) +{ + CasHotKeys lane(16ULL << 20); + Plane plane(&lane); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + CatalogRival rival(plane, layout, 10 * kCasMaxDecisions); + size_t pauses = 0; + plane.countPauses(pauses); + const size_t journal_from = plane.backend->seenCount(); + + /// The closing parenthesis is the end of the reason: nothing names an unresolved write. + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + fmt::format("CAS ref catalog '{}' update: did not converge after 100 submissions)", key), [&] + { + CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) { return current; }); + }); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions); + EXPECT_EQ(rival.moves, kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 1); +} + +/// Namespace-create step 1 decides again after a write whose fate is unknown. When the hundredth +/// write is that one, the error says the write may have landed. +TEST(CASSharedDeadline, CasUpdateEndsAfterAHundredSubmissionsAfterAnUnresolvedLastWrite) +{ + CasHotKeys lane(16ULL << 20); + Plane plane(&lane); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + plane.takeTime(Verb::Write, key, 0, 10 * kCasMaxDecisions, Ending::LostBeforeLanding); + size_t pauses = 0; + plane.countPauses(pauses); + const size_t journal_from = plane.backend->seenCount(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + fmt::format("CAS ref catalog '{0}' update: a sent write's outcome is unresolved; the call ended with: Code: 210. DB::Exception: " + "CAS write could not be committed (CAS ref catalog '{0}' update: did not converge after 100 submissions)", key), + [&] + { + (void)CasRefCatalog::createNamespace(plane.op, layout, 1, RootNamespace{"a"}, + CreatorFence{.server_root_id = "srv", .writer_epoch = 1, .fence_generation = 1}); + }); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key), kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 1); + EXPECT_TRUE(CasRefCatalog::read(plane.op, layout).catalog.entries.empty()); +} + +/// The lease expires while the read that settles the hundredth unresolved write is in flight. The error +/// names the lease and still says the last write may have landed. +TEST(CASSharedDeadline, CasUpdateReportsTheLeaseAndAnUnresolvedLastWriteAtTheHundredthSubmission) +{ + TrippableFence mount; + CasHotKeys lane(16ULL << 20); + Plane plane(&lane, mount.fence()); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + size_t writes = 0; + plane.backend->armWith(Verb::Write, exactly(key), [&] { ++writes; }, 10 * kCasMaxDecisions, Ending::LostBeforeLanding); + bool tripped = false; + plane.backend->armWith(Verb::Read, [&](const String & k) { return k == key && writes == kCasMaxDecisions; }, [&] + { + mount.trip(TrippableFence::Trip::LeaseExpiry); + tripped = true; + }); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + fmt::format("CAS ref catalog '{0}' update: a sent write's outcome is unresolved; the call ended with: Code: 210. DB::Exception: " + "CAS write could not be committed (CAS ref catalog '{0}' update: gave up at the lease deadline after 100 submissions)", key), + [&] + { + (void)CasRefCatalog::createNamespace(plane.op, layout, 1, RootNamespace{"a"}, + CreatorFence{.server_root_id = "srv", .writer_epoch = 1, .fence_generation = 1}); + }); + EXPECT_TRUE(tripped) << "the hundredth settling read was never sent"; + EXPECT_EQ(writes, kCasMaxDecisions); +} + +/// The slot read of `Pool::confirmPinnedRef` binds its own request window: a ledger check that took all but +/// one millisecond of the poll's window does not shorten it. +TEST(CASSharedDeadline, ConfirmPinnedRefSendsItsSlotReadAfterASlowLedgerCheck) +{ + auto backend = std::make_shared(); + auto clock = std::make_shared(); + const PoolPtr store = openOnBootClock(backend, clock); + const RootNamespace ns{"srv/source"}; + const ManifestId id = publishOnePart(store, ns, "x", "payload"); + const auto pinned = store->resolveRefPinned(ns, "x"); + ASSERT_TRUE(pinned.has_value()); + const String slot_key = store->layout().mountKey("test"); + + const uint64_t started_ms = clock->now(); + bool waited = false; + store->setConfirmAfterLedgerSnapshotHookForTest([&] + { + if (!std::exchange(waited, true)) + clock->advance(kFirstStepMs); + }); + std::optional answer; + const auto failure = failureOf([&] { answer = store->confirmPinnedRef(pinned->table, ns, "x", id.ref); }); + store->setConfirmAfterLedgerSnapshotHookForTest(nullptr); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_TRUE(waited) << "the confirm never reached its ledger check"; + EXPECT_EQ(answer, std::optional(ConfirmAnswer::Yes)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the mount slot read", sentSince(*backend, first_ended_ms, Verb::Read, slot_key)) + << "error: " << orNone(failure); +} + +/// A recovery walk whose reads were slow and whose last read then failed for one request window is +/// retried: no elapsed-time limit ends recovery, only the cap on the number of walks. +TEST(CASSharedDeadline, RecoveryRetriesAWalkThatFailedLateInItsBudget) +{ + auto backend = std::make_shared(); + auto clock = std::make_shared(); + const RootNamespace ns{"srv/tbl"}; + { + const PoolPtr first = openOnBootClock(backend, clock); + publishOnePart(first, ns, "part_a", "payload-a"); + publishOnePart(first, ns, "part_b", "payload-b"); + } + const PoolPtr store = openOnBootClock(backend, clock); + ASSERT_FALSE(store->refTableRecoveredForTest(ns)); + const String catalog_key = store->layout().refCatalogKey(); + + const uint64_t started_ms = clock->now(); + constexpr uint64_t slow_read_ms = kWindowMs + 20'000; + /// Later reads fail for one request window, then the store answers again. + const uint64_t fault_ends_ms = started_ms + slow_read_ms + kWindowMs; + backend->armWith(Verb::Read, [catalog_key](const String & key) { return key != catalog_key; }, + [clock] { clock->advance(slow_read_ms); }); + backend->armWith(Verb::Read, + [catalog_key, clock, fault_ends_ms](const String & key) { return key != catalog_key && clock->now() < fault_ends_ms; }, + [] {}, /*times=*/std::numeric_limits::max(), Ending::LostBeforeLanding); + + const uint64_t retries_before = ProfileEvents::global_counters[ProfileEvents::CASRefRecoveryRetries]; + size_t refs = 0; + uint64_t walk_ended_ms = 0; + const auto failure = failureOf([&] + { + try + { + refs = store->listRefs(ns).size(); + } + catch (...) + { + walk_ended_ms = clock->now(); + throw; + } + }); + const uint64_t retries = ProfileEvents::global_counters[ProfileEvents::CASRefRecoveryRetries] - retries_before; + + ASSERT_GE(backend->slowedKeys().size(), 2u) << "the walk made fewer than two reads, so none failed after the slow one"; + const uint64_t used_ms = (walk_ended_ms ? walk_ended_ms : clock->now()) - started_ms; + EXPECT_FALSE(failure.has_value()) + << fmt::format("\n first walk took {} ms; {} retry(ies)\n ", used_ms, retries) + << "error: " << orNone(failure); + EXPECT_EQ(refs, 2u); + EXPECT_GE(retries, 1u) << "a second walk was started"; +} From 74be207c20e71a609da4e57b8362f459fa43034b Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:27:51 +0100 Subject: [PATCH 03/47] Cap CAS ref-table recovery at 8 walks and remove its time budget `recovery_retry_budget_ms` is removed. The walk that fails at `kCasMaxRecoveryWalks` rethrows its own error; a restart at the cap fails as "did not converge". Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../Backend/CasRequestBudget.cpp | 3 - .../Backend/CasRequestBudget.h | 13 +- .../ContentAddressed/Pool/CasRefLedger.cpp | 63 +-- src/Disks/tests/gtest_cas_ref_writer.cpp | 368 +++++++++++++++--- src/Disks/tests/gtest_cas_settings.cpp | 12 +- 5 files changed, 355 insertions(+), 104 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.cpp index a0cc03c1c113a..7fe6e68aa8f4f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.cpp @@ -31,9 +31,6 @@ uint64_t CasRequestBudget::attemptEnvelopeMs() const void setCasRequestWindow(CasRequestBudget & budget, uint64_t window_ms) { budget.request_window_ms = window_ms; - budget.recovery_retry_budget_ms = window_ms > std::numeric_limits::max() / 2 - ? std::numeric_limits::max() - : 2 * window_ms; } void validateCasRequestWindow(const CasRequestBudget & budget) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.h index f87bcfc01692d..eb2139f3338ff 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.h @@ -11,7 +11,7 @@ inline constexpr uint64_t kDefaultRequestWindowMs = 120000; /// The limits a writable mount is configured with. `CasMountRuntime::admit` measures a request against /// `lease_safety_margin_ms` plus a caller-supplied need expressed in attempt envelopes (one for an /// ordinary attempt, TWO for a ref-log append's write-plus-settlement-read -- see -/// `CasMountRuntime::refAppendFenceOk`), and the three `recovery_retry_*` fields bound a whole +/// `CasMountRuntime::refAppendFenceOk`), and the `recovery_retry_*` backoff fields pace a whole /// ref-table recovery; see `validateCasRequestBudget` for the relationship a writable mount enforces /// at startup. struct CasRequestBudget @@ -42,19 +42,14 @@ struct CasRequestBudget /// Recovery-level retry (`CasRefLedger::ensureRefTableRecovered`): a whole ref-table recovery /// attempt (LIST + snapshot/log GETs + seal PUT) that fails with a transient NETWORK_ERROR is - /// retried, with capped-exponential backoff, until this total wall-clock budget is spent — then the - /// error propagates and the table's load fails for this touch (the `lazy_load_tables` database - /// setting makes the NEXT touch retry). This sits ON TOP of each write's own `Retry` policy window - /// (`request_window_ms`): one recovery attempt may itself burn that long inside a single seal PUT, so the - /// storage layer sets this to twice the window. Not part of the inequality set validated in + /// retried, with capped-exponential backoff, until `kCasMaxRecoveryWalks` walks have started — then + /// the error propagates and the table's load fails for this touch (the `lazy_load_tables` database + /// setting makes the NEXT touch retry). Not part of the inequality set validated in /// `validateCasRequestBudget`. - uint64_t recovery_retry_budget_ms = 2 * kDefaultRequestWindowMs; uint64_t recovery_retry_initial_backoff_ms = 1000; uint64_t recovery_retry_max_backoff_ms = 30000; }; -/// Sets `request_window_ms` and derives `recovery_retry_budget_ms` as twice the window, saturating: one -/// recovery attempt can spend a whole window inside a single write. void setCasRequestWindow(CasRequestBudget & budget, uint64_t window_ms); /// Throws `BAD_ARGUMENTS` unless `attemptEnvelopeMs() < request_window_ms`: the bound of a read-only open, diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index 5cad334b0035b..eff1435975b81 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -1659,7 +1659,7 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// /// Captured for the WHOLE call, not per attempt, for the same reason: the transient-retry loop below /// exists for object-store blips, and a generation that moved is not one. The loop refuses to - /// re-drive under a moved generation (below), so the budget is never burned on a doomed retry. + /// re-drive under a moved generation (below), so no walk is spent on a doomed retry. const uint64_t admitted_generation = rt.admitted_fence_generation; refuseUnlessAdmitted(mount_requests.resume(admitted_generation), "ref recovery walk admission"); /// Preserve this runtime's exact writer identity across the unlocked walk. The runtime stays in @@ -1673,11 +1673,12 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// Outer transient-retry loop, so a blip does not fail a table load for good: a whole recovery attempt that /// fails with a TRANSIENT object-store transport error (`isTransientRecoveryError` -- `S3_ERROR`/ /// socket/timeout from the direct LIST/GET backend calls, or a controller `NETWORK_ERROR`) is retried - /// with capped-exponential backoff until `recovery_retry_budget_ms` is spent, instead of propagating - /// and failing this table's async load permanently. Non-transient errors (corruption, decode, a moved - /// fence, logic, resource limits) fail fast; so do the latched terminal cases below. - const uint64_t recovery_start_ms = boot_ms_now_fn(); + /// with capped-exponential backoff until `kCasMaxRecoveryWalks` walks have started, instead of + /// propagating and failing this table's async load permanently. Non-transient errors (corruption, + /// decode, a moved fence, logic, resource limits) fail fast; so do the latched terminal cases below. uint64_t recovery_retry_num = 0; + /// Walks started so far, retried or restarted alike. + uint32_t walks_started = 0; bool vanish_brake_tripped = false; bool cancelled = false; for (;;) @@ -1692,7 +1693,7 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( if (attempt > kRefRecoveryMaxRestarts) { /// Terminal, NOT a transient object-store outage: latch so the outer retry loop - /// rethrows immediately instead of re-driving this brake for the whole budget. + /// rethrows immediately instead of re-driving this brake for the remaining walks. vanish_brake_tripped = true; if (hole_detail) throw Exception(ErrorCodes::CORRUPTED_DATA, @@ -1717,6 +1718,7 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// and `rt` is read only through atomics the poll consults. Unlocking is what keeps a /// recovery's full I/O envelope from stalling every reader of this table -- and what lets /// the self-remount barrier take the lock promptly to JOIN us. + ++walks_started; lock.unlock(); std::optional walked; try @@ -1740,7 +1742,20 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( lock.lock(); if (!walked) + { + /// When the structural brake also trips on the next pass, it reports the more specific cause. + if (walks_started >= kCasMaxRecoveryWalks && attempt < kRefRecoveryMaxRestarts) + { + /// A fence lost during the last walk is the answer, not the count. + refuseUnlessAdmitted(mount_requests.resume(admitted_generation), "ref recovery restart"); + throwCasRequestRetryLater(fmt::format( + "CAS ref-table recovery for namespace '{}': did not converge after {} walks ({})", + ns.string(), walks_started, + hole_detail ? "last walk found: " + *hole_detail + : String("the last walk restarted because the checkpoint or its base moved"))); + } continue; /// restart requested (vanished base, or a hole worth one more reading) + } if (life_removed) break; @@ -1820,16 +1835,12 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( if (rt.recovery_cancel_requested.load(std::memory_order_acquire)) checkRecoveryStillAdmitted(ns, rt, cancelled, token); - const uint64_t elapsed_ms = boot_ms_now_fn() - recovery_start_ms; - /// Fail closed BEFORE sleeping: budget spent, mount fence lost, this runtime superseded by a - /// self-remount, or the incarnation that admitted this recovery has moved (retrying under a - /// generation that is already stale can only ever be refused at the install). - if (elapsed_ms >= cas_request_budget.recovery_retry_budget_ms - || (token && token->stopping()) - || !fence_ok_fn() - || rt.catalog_life_invalidated.load(std::memory_order_acquire) - || rt.superseded_by_remount.load(std::memory_order_acquire) - || fence_generation_fn() != admitted_generation) + /// Fail closed BEFORE sleeping. + if (!mayRetry()) + throw; + + /// The walk cap ends the loop without a pause; the original error propagates like the exits above. + if (walks_started >= kCasMaxRecoveryWalks) throw; /// Saturating `initial << recovery_retry_num`: `initial > cap >> n` implies the unshifted @@ -1844,9 +1855,9 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( ProfileEvents::increment(ProfileEvents::CASRefRecoveryRetries); LOG_WARNING(getLogger("CasRefLedger"), "CAS ref-table recovery for namespace '{}' hit a transient object-store error " - "(code {}: {}); retry #{} after {}ms backoff (elapsed {}ms / budget {}ms)", + "(code {}: {}); retry #{} after {}ms backoff", ns.string(), code, getCurrentExceptionMessage(/*with_stacktrace=*/false), - recovery_retry_num, backoff_ms, elapsed_ms, cas_request_budget.recovery_retry_budget_ms); + recovery_retry_num, backoff_ms); lock.unlock(); /// Re-acquire the lock before letting any exception from the sleep unwind, so the SCOPE_EXIT @@ -1862,16 +1873,12 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( throw; } lock.lock(); - /// The fence/supersession/budget can all change during the unlocked sleep -- re-check before - /// starting the next full attempt so we never re-drive recovery on an orphaned runtime, past - /// the budget, or under a lost or moved fence (the sliced sleep may have woken early on fence - /// loss). - if (boot_ms_now_fn() - recovery_start_ms >= cas_request_budget.recovery_retry_budget_ms - || (token && token->stopping()) - || !fence_ok_fn() - || rt.catalog_life_invalidated.load(std::memory_order_acquire) - || rt.superseded_by_remount.load(std::memory_order_acquire) - || fence_generation_fn() != admitted_generation) + /// A query stopped in the pause vetoes the next walk. + if (walk_failed && Cas::queryStopRequested()) + std::rethrow_exception(unresolved_error ? unresolved_error : std::current_exception()); + /// The fence and supersession can change during the unlocked sleep, which may also have woken + /// early on fence loss. + if (!mayRetry()) throw; /// loop: re-run recovery from a fresh checkpoint read, exact replay and walk } diff --git a/src/Disks/tests/gtest_cas_ref_writer.cpp b/src/Disks/tests/gtest_cas_ref_writer.cpp index a38d877aa0926..ce4df2b2bc342 100644 --- a/src/Disks/tests/gtest_cas_ref_writer.cpp +++ b/src/Disks/tests/gtest_cas_ref_writer.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -5327,6 +5328,47 @@ TEST(CASRefWriterNamespaceRemoval, AmbiguousBeginRemovingKeepsTheWriteLaneClosed EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); } +/// A failure after the lane closed but before the removal's error handler is armed sent nothing, +/// so it must not leave a `Live` lane closed. +TEST(CASRefWriterNamespaceRemoval, ThrowDuringRemovalSetupCannotStrandLiveLane) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/throw_during_removal_setup"}; + publishEmptyPart(store, ns, "owned"); + + store->setRemovalAttemptHookForTest([] { throw std::runtime_error("setup failed"); }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + EXPECT_THROW(store->dropNamespace(ns), std::runtime_error); + store->setRemovalAttemptHookForTest({}); + + EXPECT_NO_THROW(updatePublishedAt(store, ns)) << "the lane of a Live namespace must be open again"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + EXPECT_NO_THROW(store->dropNamespace(ns)); +} + +/// The guard must not reopen after an earlier ambiguous `Live -> Removing` send: that write may still land. +TEST(CASRefWriterNamespaceRemoval, ThrowDuringRemovalSetupAfterAmbiguousWriteKeepsTheLaneClosed) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/throw_in_setup_after_ambiguous_write"}; + publishEmptyPart(store, ns, "owned"); + + dropWithAmbiguousCatalogWrite(backend, store, ns); + + store->setRemovalAttemptHookForTest([] { throw std::runtime_error("setup failed"); }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + EXPECT_THROW(store->dropNamespace(ns), std::runtime_error); + store->setRemovalAttemptHookForTest({}); + expectPositiveLaneClosed(store, ns); + + EXPECT_NO_THROW(store->dropNamespace(ns)) << "a retried removal completes"; + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} + /// The uncertainty outlives the call that created it: a retried removal that fails before it sends /// anything, then sees an unchanged `Live` row, must not reopen the lane. TEST(CASRefWriterNamespaceRemoval, FailedRetryAfterAmbiguousBeginRemovingDoesNotReopenTheLane) @@ -5375,9 +5417,9 @@ TEST(CASRefWriterNamespaceRemoval, AmbiguousBeginRemovingSurvivesRefTableEvictio EXPECT_NO_THROW(store->dropNamespace(ns)); } -/// Upper bound on the virtual time one drop may spend: the window frozen at its entry, one backoff draw -/// the pace does not consult the deadline for (the cap of `Retry::backoff`), and slack for -/// the virtual clock's extra millisecond per pause. +/// Upper bound on the virtual time a request may spend after it starts: its own window, one backoff draw +/// the pace does not consult the deadline for (the cap of `Retry::backoff`), and slack for the virtual +/// clock's extra millisecond per pause. const uint64_t kMaxBackoffDrawMs = 5000; const uint64_t kVirtualClockPauseSlackMs = 100; const uint64_t kOneWindowPlusBackoffMs @@ -5880,9 +5922,9 @@ TEST(CASRefWriterNamespaceRemoval, EntryChangedAfterASentAttemptKeepsTheLaneClos expectPositiveLaneClosed(store, ns); } -/// A creator-fence read made while the drop decides must draw on the drop's one frozen window: a slow -/// first read plus a failing fence read must not exceed that window. -TEST(CASRefWriterNamespaceRemoval, DropWithASlowCreatorFenceReadEndsAtTheEntryDeadline) +/// A slow first catalog read carries the clock past a whole window; the creator-fence read after it is +/// sent and ends at its own window. +TEST(CASRefWriterNamespaceRemoval, DropSendsItsCreatorFenceReadAfterASlowFirstRead) { auto backend = std::make_shared(); auto store = openPool(backend, wedgeTestBudget()); @@ -5898,14 +5940,14 @@ TEST(CASRefWriterNamespaceRemoval, DropWithASlowCreatorFenceReadEndsAtTheEntryDe creating.creator = CreatorFence{.server_root_id = foreign_creator, .writer_epoch = 7, .fence_generation = 1}; casAdmitEntryForTest(backend, layout, 1, creating); - bool first_catalog_read_done = false; + std::optional first_read_ended_ms; size_t fence_reads = 0; backend->read_observer = [&](const String & key) { - if (key == layout.refCatalogKey() && !first_catalog_read_done) + if (key == layout.refCatalogKey() && !first_read_ended_ms) { - first_catalog_read_done = true; - clock->advance(60'000); + clock->advance(kDefaultRequestWindowMs + 10'000); + first_read_ended_ms = clock->nowMs(); } if (key == layout.mountKey(foreign_creator)) { @@ -5917,31 +5959,31 @@ TEST(CASRefWriterNamespaceRemoval, DropWithASlowCreatorFenceReadEndsAtTheEntryDe const uint64_t now_before = clock->nowMs(); EXPECT_THROW(store->dropNamespace(ns), DB::Exception); - ASSERT_TRUE(first_catalog_read_done); + ASSERT_TRUE(first_read_ended_ms.has_value()); EXPECT_GT(fence_reads, 0U) << "the creator fence was never read"; - EXPECT_LE(clock->nowMs() - now_before, kOneWindowPlusBackoffMs) - << "the drop spent more than the one window frozen at its entry"; + EXPECT_LE(clock->nowMs() - *first_read_ended_ms, kOneWindowPlusBackoffMs) + << "the creator-fence read outlived its own window"; } -/// The `gc/state` read is part of the removal decision, so it draws on the same window as the catalog read -/// that came before it. -TEST(CASRefWriterNamespaceRemoval, DropSpendsOneWindowAcrossItsReads) +/// A slow first catalog read carries the clock past a whole window; the `gc/state` read of the removal +/// decision is sent and ends at its own window. +TEST(CASRefWriterNamespaceRemoval, DropSendsItsGcStateReadAfterASlowFirstRead) { auto backend = std::make_shared(); auto store = openPool(backend, wedgeTestBudget()); auto clock = VirtualRetryClock::installOn(store); const Layout & layout = store->layout(); - const RootNamespace ns{"srv1/one_window_across_reads"}; + const RootNamespace ns{"srv1/gc_state_read_after_slow_read"}; publishEmptyPart(store, ns, "owned"); - bool first_catalog_read_done = false; + std::optional first_read_ended_ms; size_t gc_state_reads = 0; backend->read_observer = [&](const String & key) { - if (key == layout.refCatalogKey() && !first_catalog_read_done) + if (key == layout.refCatalogKey() && !first_read_ended_ms) { - first_catalog_read_done = true; - clock->advance(60'000); + clock->advance(kDefaultRequestWindowMs + 10'000); + first_read_ended_ms = clock->nowMs(); } if (key == layout.gcStateKey()) { @@ -5953,32 +5995,32 @@ TEST(CASRefWriterNamespaceRemoval, DropSpendsOneWindowAcrossItsReads) const uint64_t now_before = clock->nowMs(); EXPECT_THROW(store->dropNamespace(ns), DB::Exception); - ASSERT_TRUE(first_catalog_read_done); - EXPECT_GT(gc_state_reads, 0U) << "the gc/state read was never reached"; - EXPECT_LE(clock->nowMs() - now_before, kOneWindowPlusBackoffMs) - << "the drop spent more than the one window frozen at its entry"; + ASSERT_TRUE(first_read_ended_ms.has_value()); + EXPECT_GT(gc_state_reads, 0U) << "the gc/state read was never sent"; + EXPECT_LE(clock->nowMs() - *first_read_ended_ms, kOneWindowPlusBackoffMs) + << "the gc/state read outlived its own window"; } -/// The `Live -> Removing` catalog update draws on the drop's one frozen window too: a slow first read -/// plus catalog writes that never land must not exceed that window. -TEST(CASRefWriterNamespaceRemoval, DropSpendsOneWindowAcrossItsCatalogUpdate) +/// A slow first catalog read carries the clock past a whole window; the `Live -> Removing` catalog +/// update is sent and ends at its own window. +TEST(CASRefWriterNamespaceRemoval, DropSendsItsCatalogUpdateAfterASlowFirstRead) { auto backend = std::make_shared(); auto store = openPool(backend, wedgeTestBudget()); auto clock = VirtualRetryClock::installOn(store); const Layout & layout = store->layout(); - const RootNamespace ns{"srv1/one_window_across_catalog_update"}; + const RootNamespace ns{"srv1/catalog_update_after_slow_read"}; publishEmptyPart(store, ns, "owned"); backend->catalog_fault_key = layout.refCatalogKey(); backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::ThrowUncommitted; - bool first_catalog_read_done = false; + std::optional first_read_ended_ms; backend->read_observer = [&](const String & key) { - if (key == layout.refCatalogKey() && !first_catalog_read_done) + if (key == layout.refCatalogKey() && !first_read_ended_ms) { - first_catalog_read_done = true; - clock->advance(60'000); + clock->advance(kDefaultRequestWindowMs + 10'000); + first_read_ended_ms = clock->nowMs(); } }; SCOPE_EXIT({ backend->read_observer = nullptr; }); @@ -5986,27 +6028,51 @@ TEST(CASRefWriterNamespaceRemoval, DropSpendsOneWindowAcrossItsCatalogUpdate) const uint64_t now_before = clock->nowMs(); EXPECT_THROW(store->dropNamespace(ns), DB::Exception); backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::None; - ASSERT_TRUE(first_catalog_read_done); - EXPECT_TRUE(backend->catalog_cas_fault_fired) << "no catalog write was attempted"; - EXPECT_LE(clock->nowMs() - now_before, kOneWindowPlusBackoffMs) - << "the drop spent more than the one window frozen at its entry"; + ASSERT_TRUE(first_read_ended_ms.has_value()); + EXPECT_TRUE(backend->catalog_cas_fault_fired) << "no catalog write was sent"; + EXPECT_LE(clock->nowMs() - *first_read_ended_ms, kOneWindowPlusBackoffMs) + << "the catalog update outlived its own window"; } -/// A local wait that outlasts the window is not cut short. The next read gives up at once with nothing -/// sent, the catch-side read has its own window and finds the row `Live`, and the lane reopens. -TEST(CASRefWriterNamespaceRemoval, AWaitLongerThanTheWindowEndsTheDropAndLeavesTheLaneOpen) +/// A gap longer than the window between two requests of the removal does not end it: the reads after +/// the gap are sent. +/// The `gc/state` read then fails before any write is sent, the catch-side read finds the row `Live`, and +/// the lane reopens. +TEST(CASRefWriterNamespaceRemoval, AReadFailingAfterAGapLongerThanTheWindowLeavesTheLaneOpen) { auto backend = std::make_shared(); auto store = openPool(backend, wedgeTestBudget()); auto clock = VirtualRetryClock::installOn(store); const Layout & layout = store->layout(); - const RootNamespace ns{"srv1/wait_longer_than_window"}; + const RootNamespace ns{"srv1/gap_longer_than_window"}; publishEmptyPart(store, ns, "owned"); - store->setRemovalAttemptHookForTest([&] { clock->advance(kDefaultRequestWindowMs + 10'000); }); + std::optional gap_ended_ms; + store->setRemovalAttemptHookForTest([&] + { + clock->advance(kDefaultRequestWindowMs + 10'000); + gap_ended_ms = clock->nowMs(); + }); SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + size_t gc_state_reads = 0; + backend->read_observer = [&](const String & key) + { + if (key == layout.gcStateKey() && gap_ended_ms) + { + ++gc_state_reads; + throw DB::Exception(DB::ErrorCodes::S3_ERROR, "simulated transient GET failure"); + } + }; + SCOPE_EXIT({ backend->read_observer = nullptr; }); + const size_t catalog_writes_before = catalogWritesInJournal(backend, layout); - expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { store->dropNamespace(ns); }); + expectThrowsCodeWithMessage( + DB::ErrorCodes::NETWORK_ERROR, "gave up at the policy deadline", [&] { store->dropNamespace(ns); }); + ASSERT_TRUE(gap_ended_ms.has_value()); + EXPECT_GT(gc_state_reads, 0U) << "the removal's reads after the gap were never sent"; + EXPECT_LE(clock->nowMs() - *gap_ended_ms, kOneWindowPlusBackoffMs) + << "the gc/state read outlived its own window"; + EXPECT_EQ(catalogWritesInJournal(backend, layout), catalog_writes_before) << "a catalog write was sent"; EXPECT_EQ(catalogEntryOrThrow(backend, layout, ns).state, NsState::Live); EXPECT_NO_THROW(updatePublishedAt(store, ns)); } @@ -7753,7 +7819,7 @@ CasRequestBudget sealTestTinyBudget() /// =================================================================================== /// Layer 1 of the stuck-table-load fix: `ensureRefTableRecovered` retries a whole recovery attempt -/// after a TRANSIENT object-store NETWORK_ERROR (bounded by `recovery_retry_budget_ms`), instead of +/// after a TRANSIENT object-store NETWORK_ERROR (bounded by `kCasMaxRecoveryWalks`), instead of /// failing the table's async load permanently. Non-transient errors and the terminal vanish-race /// brake still fail fast. /// =================================================================================== @@ -7857,11 +7923,13 @@ TEST(CASRefWriterRecoveryRetry, RecoveryDoesNotEnumerateItsStream) << "the chain is closed by one tombstone without enumerating the stream"; } -TEST(CASRefWriterRecoveryRetry, TransientFailureLongerThanBudgetPropagates) +/// A transient failure that never clears ends recovery after `kCasMaxRecoveryWalks` walks, however much +/// time the pauses take: seven 60 s pauses pass and no elapsed-time check ends the loop. +TEST(CASRefWriterRecoveryRetry, TransientFailureThatNeverClearsPropagatesAfterTheWalkCap) { auto backend = std::make_shared(); const Layout layout("p"); - const RootNamespace ns{"srv1/retry_budget"}; + const RootNamespace ns{"srv1/retry_cap"}; seedSealFixtureDeadEpochs(backend, layout, ns); seedUncleanPredecessorMount(backend, layout, /*epoch=*/2); @@ -7873,13 +7941,11 @@ TEST(CASRefWriterRecoveryRetry, TransientFailureLongerThanBudgetPropagates) PoolConfig config; config.server_id = UInt128(1); - /// Lease TTL >> the recovery budget so the CLOCK-advancing backoff below trips the budget check, - /// not the mount fence -- this test specifically exercises the budget-exhaustion path. - config.mount_lease_ttl_ms = std::chrono::milliseconds(600000); + /// Lease TTL far above the total pause time, so the fence never ends the loop before the cap does. + config.mount_lease_ttl_ms = std::chrono::milliseconds(3'600'000); config.cas_request_budget = sealTestTinyBudget(); - config.cas_request_budget.recovery_retry_budget_ms = 5000; /// small, deterministic - config.cas_request_budget.recovery_retry_initial_backoff_ms = 1000; - config.cas_request_budget.recovery_retry_max_backoff_ms = 30000; + config.cas_request_budget.recovery_retry_initial_backoff_ms = 60'000; + config.cas_request_budget.recovery_retry_max_backoff_ms = 60'000; config.boot_ms_fn = [fake_now] { return fake_now->load(); }; config.wait_sleep_fn = [](uint64_t) {}; auto store = openPoolWithConfig(backend, config); @@ -7889,9 +7955,16 @@ TEST(CASRefWriterRecoveryRetry, TransientFailureLongerThanBudgetPropagates) /// The tombstone at `{2,2}`, the slot after the chain's last record, is the first log the walk writes. const RefTxnId seal_id{2, 2}; backend->fault_key_substr = layout.refLogKey(DB::Cas::tests::fixture::fixtureLife(ns), seal_id); - backend->fault_count = 1000; /// never stops failing within the budget + backend->fault_latched = true; + using ProfileEvents::global_counters; + const auto retries_before = global_counters[ProfileEvents::CASRefRecoveryRetries]; + const uint64_t clock_before = fake_now->load(); expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { store->listRefs(ns); }); + + EXPECT_EQ(global_counters[ProfileEvents::CASRefRecoveryRetries], retries_before + (kCasMaxRecoveryWalks - 1)) + << "eight walks mean seven pauses"; + EXPECT_GE(fake_now->load() - clock_before, uint64_t{7} * 60'000) << "420 s of pauses passed, so no elapsed-time check ended the loop"; } TEST(CASRefWriterRecoveryRetry, NonNetworkErrorIsNotRetried) @@ -8020,6 +8093,195 @@ TEST(CASRefWriterRecoveryRetry, ThrowingBackoffSleepDoesNotWedgeRecovery) EXPECT_EQ(store->listRefs(ns).size(), 2u) << "a second touch must recover; the retry lane is not wedged"; } +/// =================================================================================== +/// The recovery loop ends after `kCasMaxRecoveryWalks` walks in total, whichever mix of transient +/// failures and structural restarts spent them. Pauses are no-ops, so only the cap can end the loop. +/// =================================================================================== + +namespace +{ + +enum class WalkFate : uint8_t +{ + Succeed, + FailTransiently, + /// The walk ends by finding `_ckpt` replaced, which asks for a restart. + Restart, + Corrupt, +}; + +/// Decides each walk's fate from its position; a walk past the end of the script succeeds. +struct RecoveryWalkScript +{ + std::vector fates; + int transient_code = DB::ErrorCodes::S3_ERROR; + /// Set before the recovery starts; run on the recovering thread. + std::function before_walk; + std::function on_pause; + std::function on_read; + std::atomic armed{false}; + std::atomic walks{0}; + std::atomic pauses{0}; + std::atomic ckpt_reads_in_walk{0}; + std::atomic replacing_ckpt{false}; + + WalkFate current() const + { + const uint32_t n = walks.load(); + return n >= 1 && n <= fates.size() ? fates[n - 1] : WalkFate::Succeed; + } +}; + +struct ScriptedRecovery +{ + std::shared_ptr backend; + std::shared_ptr script; + PoolPtr store; + RootNamespace ns; +}; + +/// With `production_backoff_ms`, the pool keeps its own backoff and pauses that long after a failed walk. +ScriptedRecovery openScriptedRecovery(std::vector fates, std::optional production_backoff_ms = std::nullopt) +{ + ScriptedRecovery scripted; + scripted.backend = std::make_shared(); + scripted.script = std::make_shared(); + scripted.script->fates = std::move(fates); + scripted.ns = RootNamespace{"srv1/walk_cap"}; + const Layout layout("p"); + + seedSealFixtureDeadEpochs(scripted.backend, layout, scripted.ns); + seedUncleanPredecessorMount(scripted.backend, layout, /*epoch=*/2); + + PoolConfig config; + config.server_id = UInt128(1); + config.mount_lease_ttl_ms = std::chrono::milliseconds(500); + config.cas_request_budget = sealTestTinyBudget(); + config.boot_ms_fn = [] { return uint64_t{1'000'000}; }; + config.wait_sleep_fn = [](uint64_t) {}; + if (production_backoff_ms) + { + config.cas_request_budget.recovery_retry_initial_backoff_ms = *production_backoff_ms; + config.cas_request_budget.recovery_retry_max_backoff_ms = *production_backoff_ms; + } + config.recovery_pre_first_request_hook_for_test = [script = scripted.script] + { + if (!script->armed) + return; + const uint32_t walk = ++script->walks; + script->ckpt_reads_in_walk = 0; + if (script->before_walk) + script->before_walk(walk); + if (script->current() == WalkFate::FailTransiently) + throw DB::Exception(script->transient_code, "scripted walk failure"); + if (script->current() == WalkFate::Corrupt) + throw DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "scripted walk corruption"); + }; + scripted.store = openPoolWithConfig(scripted.backend, config); + if (!production_backoff_ms) + { + scripted.store->setCasRetrySleepForTest([](uint64_t) {}); + scripted.store->setRefRecoveryRetrySleepForTest([script = scripted.script](uint64_t, const auto &) + { + ++script->pauses; + if (script->on_pause) + script->on_pause(); + }); + } + + /// A walk reads `_ckpt` first and last; replacing it between the two makes the last read disagree. + const NamespaceLifeId life = lifeIfCatalogedForTest(scripted.backend, layout, scripted.ns).value(); + const String ckpt_key = layout.refCkptKey(life); + scripted.backend->read_observer = [script = scripted.script, ckpt_key, layout, life, + weak_backend = std::weak_ptr(scripted.backend)](const String & key) + { + if (script->armed && script->on_read) + script->on_read(key); + if (!script->armed || key != ckpt_key || script->replacing_ckpt) + return; + if (++script->ckpt_reads_in_walk != 2 || script->current() != WalkFate::Restart) + return; + script->replacing_ckpt = true; + SCOPE_EXIT({ script->replacing_ckpt = false; }); + const BackendPtr backend_ptr = weak_backend.lock(); + ASSERT_TRUE(backend_ptr); + const auto sampled = readCkptForTest(backend_ptr, layout, life); + ASSERT_TRUE(sampled); + ASSERT_TRUE(replaceForTest(backend_ptr, ckpt_key, encodeRefCkptAtGeneration(sampled->ckpt, 3), sampled->etag)); + }; + scripted.script->armed = true; + return scripted; +} + +} + +TEST(CASRefWriterRecoveryRetry, SuccessOnTheEighthWalkInstalls) +{ + auto scripted = openScriptedRecovery(std::vector(7, WalkFate::FailTransiently)); + + EXPECT_EQ(scripted.store->listRefs(scripted.ns).size(), 2u); + EXPECT_EQ(scripted.script->walks.load(), 8u); +} + +TEST(CASRefWriterRecoveryRetry, ATransientFailureOnTheEighthWalkRethrows) +{ + auto scripted = openScriptedRecovery(std::vector(8, WalkFate::FailTransiently)); + + /// The failure of the last walk propagates unchanged, not recoded as a retry-later error. + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 8u) << "no ninth walk after the cap"; + EXPECT_EQ(scripted.script->pauses.load(), 7u) << "a pause follows every failed walk except the last"; +} + +TEST(CASRefWriterRecoveryRetry, AStructuralRestartOnTheEighthWalkReportsExhaustion) +{ + std::vector fates(5, WalkFate::FailTransiently); + fates.insert(fates.end(), 3, WalkFate::Restart); + auto scripted = openScriptedRecovery(std::move(fates)); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "the last walk restarted because the checkpoint or its base moved", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 8u) << "no ninth walk after the cap"; + EXPECT_EQ(scripted.script->pauses.load(), 5u); +} + +TEST(CASRefWriterRecoveryRetry, MixedFailuresEndAtEightWalks) +{ + using enum WalkFate; + auto scripted = openScriptedRecovery({Restart, FailTransiently, Restart, Restart, FailTransiently, Restart, + FailTransiently, FailTransiently}); + + /// Transient failures end at walks 2, 5, 7 and 8; the last one is not followed by a pause. + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 8u) << "no ninth walk after the cap"; + EXPECT_EQ(scripted.script->pauses.load(), 3u); +} + +/// The eighth walk is also the fourth restart in a row, so the structural brake reports it. +TEST(CASRefWriterRecoveryRetry, TheEighthWalkAsTheFourthConsecutiveRestartHitsTheBrake) +{ + std::vector fates(4, WalkFate::FailTransiently); + fates.insert(fates.end(), 4, WalkFate::Restart); + auto scripted = openScriptedRecovery(std::move(fates)); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "restarted 3 times", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 8u); +} + +/// Guard: restarts alone stop at the structural brake (the initial walk plus three restarts), well +/// before the cap. +TEST(CASRefWriterRecoveryRetry, TheStructuralBrakeEndsBeforeEightWalks) +{ + auto scripted = openScriptedRecovery(std::vector(20, WalkFate::Restart)); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "restarted 3 times", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 4u); +} + /// =================================================================================== /// Task 16: `hasAnyRefWithPrefix` -- pure existence probe, same recovery preamble as `listRefs` but /// without materializing the full ref map (an early-exit scan). diff --git a/src/Disks/tests/gtest_cas_settings.cpp b/src/Disks/tests/gtest_cas_settings.cpp index b22ab0823a6ad..864ce810d82d4 100644 --- a/src/Disks/tests/gtest_cas_settings.cpp +++ b/src/Disks/tests/gtest_cas_settings.cpp @@ -856,11 +856,9 @@ TEST(CASContentAddressedSettings, RequestWindowDefaultAndValidation) [&] { DB::Cas::validateCasRequestWindow(budget); }); budget.request_window_ms = budget.attemptEnvelopeMs() + 1; EXPECT_NO_THROW(DB::Cas::validateCasRequestWindow(budget)); - - EXPECT_EQ(DB::Cas::CasRequestBudget{}.recovery_retry_budget_ms, 240'000u); } -TEST(CASContentAddressedSettings, RequestWindowSettingSetsTheWindowAndTwiceTheRecoveryBudget) +TEST(CASContentAddressedSettings, RequestWindowSettingSetsTheWindow) { auto cfg = makeConfig("srv190000"); ContentAddressedSettings s; @@ -869,12 +867,4 @@ TEST(CASContentAddressedSettings, RequestWindowSettingSetsTheWindowAndTwiceTheRe DB::Cas::PoolConfig pool_config; DB::Cas::setCasRequestWindow(pool_config.cas_request_budget, s[ContentAddressedSetting::request_window_ms].value); EXPECT_EQ(pool_config.cas_request_budget.request_window_ms, 90'000u); - EXPECT_EQ(pool_config.cas_request_budget.recovery_retry_budget_ms, 180'000u); - - constexpr uint64_t max = std::numeric_limits::max(); - DB::Cas::setCasRequestWindow(pool_config.cas_request_budget, max / 2); - EXPECT_EQ(pool_config.cas_request_budget.recovery_retry_budget_ms, max - 1); - DB::Cas::setCasRequestWindow(pool_config.cas_request_budget, max / 2 + 1); - EXPECT_EQ(pool_config.cas_request_budget.recovery_retry_budget_ms, max); - EXPECT_EQ(pool_config.cas_request_budget.request_window_ms, max / 2 + 1); } From fe109412a1c6da1e649121bc55681670511a75b3 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:27:53 +0100 Subject: [PATCH 04/47] Remove `CasOperation::freeze` and `Retry::asSingleAttempt` No loop freezes a deadline any more. A tool's own deadline stays an outside cap through `Retry::cappedAt`. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressed/Backend/CasRequests.cpp | 8 +- .../ContentAddressed/Backend/CasRetry.h | 13 +- .../ContentAddressed/Tools/CasToolDeadline.h | 4 +- src/Disks/tests/gtest_cas_hot_keys.cpp | 114 +++++++++--------- src/Disks/tests/gtest_cas_pool.cpp | 9 +- src/Disks/tests/gtest_cas_requests.cpp | 69 ++++++++--- 6 files changed, 121 insertions(+), 96 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp index cc71dba14cda7..a9d6d884369a7 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp @@ -498,13 +498,9 @@ uint64_t CasOperation::reservedFor(uint64_t sleep_ms, uint32_t envelopes) const return total; } -Retry CasOperation::freeze(const Retry & policy) const +bool CasOperation::oneAttemptFits(const Retry & policy) const { - if (policy.policy_deadline_ms) - return policy; - Retry frozen = policy; - frozen.policy_deadline_ms = saturatingAdd(owner.now_ms(), policy.window_ms.value_or(owner.default_window_ms)); - return frozen; + return fits(reservedFor(0, 1), owner.bindPolicy(policy)); } bool CasOperation::oneAttemptFitsBefore(uint64_t deadline_ms) const diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h index 1214195e42c3f..38ed1364c7720 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h @@ -109,17 +109,8 @@ struct Retry return spacedPause(drawSpacing(attempt_spacing_ms_), attempt_started_ms, now_ms); } - /// This policy, made single-attempt. A frozen loop policy keeps its absolute deadline through it, - /// which is what lets a loop send an unrepeatable request under the same bound as the rest. - Retry asSingleAttempt() const - { - Retry copy = *this; - copy.single_attempt = true; - return copy; - } - - /// This policy ending no later than `deadline_ms` on the caller's clock. The deadline replaces `window_ms` as a - /// frozen one does; an earlier frozen deadline stays. + /// This policy ending no later than `deadline_ms` on the caller's clock; the window and the lease bound + /// still apply, and an earlier cap stays. Retry cappedAt(uint64_t deadline_ms) const { Retry copy = *this; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasToolDeadline.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasToolDeadline.h index 995e38f68a0b3..ed7815fc2efc1 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasToolDeadline.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasToolDeadline.h @@ -66,8 +66,8 @@ class ToolDeadline check(phase); if (!requests) return Retry::standard(); - const Retry chosen = op.freeze(Retry::standard()).cappedAt(deadline_ms); - if (!op.oneAttemptFitsBefore(*chosen.policy_deadline_ms)) + const Retry chosen = Retry::standard().cappedAt(deadline_ms); + if (!op.oneAttemptFits(chosen)) throwExceeded(phase); return chosen; } diff --git a/src/Disks/tests/gtest_cas_hot_keys.cpp b/src/Disks/tests/gtest_cas_hot_keys.cpp index e0a48872fac9f..22333f1a344b6 100644 --- a/src/Disks/tests/gtest_cas_hot_keys.cpp +++ b/src/Disks/tests/gtest_cas_hot_keys.cpp @@ -127,7 +127,7 @@ TEST(CASHotKeys, SubmissionsOfOneKeyAreSerializedInArrivalOrder) { go[i].wait(); auto op = requests.admit(); - results[i] = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(i + 1)); + results[i] = hot_keys.submit("k", op, Retry::standard(), appendTicket(i + 1)); }); } /// The first holder is released into its write and parked there; every later thread is released @@ -173,7 +173,7 @@ TEST(CASHotKeys, ADecideRunsWithTheLaneMutexReleased) /// `queueDepthForTest` takes the lane's mutex; a `decide` run under it would deadlock this test, /// which hangs the whole `CAS*` gate rather than being reported by a per-test timeout. The call is /// the assertion. - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), + WriteResult result = hot_keys.submit("k", op, Retry::standard(), [&](const std::optional &) -> std::optional { EXPECT_EQ(hot_keys.queueDepthForTest("k"), 1u); @@ -190,11 +190,11 @@ TEST(CASHotKeys, AFailedEnqueueLeavesNoEmptyLaneBehind) CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto op = requests.admit(); hot_keys.enter_after_lane_hook_for_test = [] { throw std::bad_alloc(); }; - EXPECT_THROW(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)), std::bad_alloc); + EXPECT_THROW(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)), std::bad_alloc); EXPECT_EQ(hot_keys.laneCountForTest(), 0u); EXPECT_EQ(backend->writeCount("k"), 0u); hot_keys.enter_after_lane_hook_for_test = {}; - EXPECT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + EXPECT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); } TEST(CASHotKeys, ResultsAreTheEnginesOwn) @@ -205,20 +205,20 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) CasHotKeys hot_keys(0); CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto op = requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); #if USE_AWS_S3 /// The store refuses the bytes: the caller gets that `Refused`, at once. backend->failNextWriteWith("k", s3Error(Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)); + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); ASSERT_TRUE(std::holds_alternative(result)); } #endif /// A clean refused precondition with the store unchanged: `Conflict` carrying the occupant. backend->refuseNextWrite("k"); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(3)); + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(3)); const auto * conflict = std::get_if(&result); ASSERT_NE(conflict, nullptr); EXPECT_TRUE(std::holds_alternative(conflict->seen)); @@ -230,7 +230,7 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) backend->refuseNextWrite("k"); backend->onBeforeWrite("k", [&] { backend->failNextReadWith("k", std::make_exception_ptr(Poco::TimeoutException("resolve"))); }); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::once()), appendTicket(4)); + WriteResult result = hot_keys.submit("k", op, Retry::once(), appendTicket(4)); const auto * conflict = std::get_if(&result); ASSERT_NE(conflict, nullptr); EXPECT_TRUE(std::holds_alternative(conflict->seen)); @@ -241,7 +241,7 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) backend->injectAmbiguousWrite("k"); backend->onBeforeWrite("k", [&] { backend->failNextReadWith("k", std::make_exception_ptr(Poco::TimeoutException("resolve"))); }); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::once()), appendTicket(5)); + WriteResult result = hot_keys.submit("k", op, Retry::once(), appendTicket(5)); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); @@ -252,7 +252,7 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) bool alive = true; auto fenced = requests.admit([&] { return alive; }); { - WriteResult result = hot_keys.submit("k", fenced, fenced.freeze(Retry::standard()), + WriteResult result = hot_keys.submit("k", fenced, Retry::standard(), [&](const std::optional & current) -> std::optional { alive = false; @@ -267,7 +267,7 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) alive = true; backend->onWriteCommitted("k", [&] { alive = false; }); { - WriteResult result = hot_keys.submit("k", fenced, fenced.freeze(Retry::standard()), appendTicket(7)); + WriteResult result = hot_keys.submit("k", fenced, Retry::standard(), appendTicket(7)); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); @@ -277,9 +277,9 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) backend->onWriteCommitted("k", [] {}); /// The engine call throws a local fault: it reaches the caller and the key is handed over. backend->failNextWriteWith("k", std::make_exception_ptr(std::logic_error("local"))); - EXPECT_THROW(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(8)), std::logic_error); + EXPECT_THROW(hot_keys.submit("k", op, Retry::standard(), appendTicket(8)), std::logic_error); EXPECT_EQ(hot_keys.laneCountForTest(), 0u); - EXPECT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(9)))); + EXPECT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(9)))); } TEST(CASHotKeys, ABaseReadThatFailsGivesUpAsReadModifyWriteDoes) @@ -295,7 +295,7 @@ TEST(CASHotKeys, ABaseReadThatFailsGivesUpAsReadModifyWriteDoes) /// Enough armed failures to outlast a standard window: the read loop gives up at its deadline. for (int i = 0; i < 64; ++i) backend->failNextReadWith("k", std::make_exception_ptr(Poco::TimeoutException("read"))); - WriteResult lane = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)); + WriteResult lane = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); for (int i = 0; i < 64; ++i) backend->failNextReadWith("k", std::make_exception_ptr(Poco::TimeoutException("read"))); WriteResult verb = op.readModifyWrite("k", appendTicket(2), Retry::standard()); @@ -319,7 +319,7 @@ TEST(CASHotKeys, ABaseReadThatFailsGivesUpAsReadModifyWriteDoes) CasRequests fenced_requests(backend, fence, clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto fenced = fenced_requests.admit(); refuse_reservations = true; - WriteResult result = hot_keys.submit("k", fenced, fenced.freeze(Retry::standard()), appendTicket(3)); + WriteResult result = hot_keys.submit("k", fenced, Retry::standard(), appendTicket(3)); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); @@ -342,7 +342,7 @@ TEST(CASHotKeys, WaitersLeaveOnTheirOwnFenceLeaseAndDeadline) std::thread holder([&] { auto op = requests.admit(); - (void)hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)); + (void)hot_keys.submit("k", op, Retry::standard(), appendTicket(1)); }); park.parked.wait(); @@ -352,7 +352,7 @@ TEST(CASHotKeys, WaitersLeaveOnTheirOwnFenceLeaseAndDeadline) std::thread deadline_waiter([&] { auto op = requests.admit(); - by_deadline = hot_keys.submit("k", op, op.freeze(Retry::within(500)), appendTicket(2)); + by_deadline = hot_keys.submit("k", op, Retry::within(500), appendTicket(2)); }); /// A waiter whose task stops. std::atomic alive{true}; @@ -360,7 +360,7 @@ TEST(CASHotKeys, WaitersLeaveOnTheirOwnFenceLeaseAndDeadline) std::thread liveness_waiter([&] { auto op = requests.admit([&] { return alive.load(); }); - by_liveness = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(3)); + by_liveness = hot_keys.submit("k", op, Retry::standard(), appendTicket(3)); }); while (hot_keys.queueDepthForTest("k") < 3) std::this_thread::yield(); @@ -392,7 +392,7 @@ TEST(CASHotKeys, WaitersLeaveOnTheirOwnFenceLeaseAndDeadline) std::thread lease_waiter([&] { auto op = requests.admit([&] { return alive.load(); }); - by_lease = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(4)); + by_lease = hot_keys.submit("k", op, Retry::standard(), appendTicket(4)); }); lease_waiter.join(); { @@ -441,7 +441,7 @@ TEST(CASHotKeys, AThrottledHolderKeepsTheWaitersQueuedThroughItsBackoff) threads.emplace_back([&] { auto op = requests.admit(); - results[0] = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)); + results[0] = hot_keys.submit("k", op, Retry::standard(), appendTicket(1)); }); parked.wait(); /// Each waiter is spawned only once the previous one is seen queued, so arrival order -- and so @@ -451,7 +451,7 @@ TEST(CASHotKeys, AThrottledHolderKeepsTheWaitersQueuedThroughItsBackoff) threads.emplace_back([&, i] { auto op = requests.admit(); - results[i] = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(i + 1)); + results[i] = hot_keys.submit("k", op, Retry::standard(), appendTicket(i + 1)); }); while (hot_keys.queueDepthForTest("k") < static_cast(i + 1)) std::this_thread::yield(); @@ -478,14 +478,14 @@ TEST(CASHotKeys, TheNextHoldStartsFromTheLandedObjectWithoutARead) auto op = requests.admit(); const auto cache_starts_before = counter(ProfileEvents::CASHotKeyCacheStarts); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); EXPECT_EQ(backend->getCount("k"), 1u); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(2)))); EXPECT_EQ(backend->getCount("k"), 1u) << "the second hold started from the cache"; EXPECT_EQ(counter(ProfileEvents::CASHotKeyCacheStarts) - cache_starts_before, 1u); /// Under `once` the one attempt is on fresh state: a read, no cached start. - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::once()), appendTicket(3)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::once(), appendTicket(3)))); EXPECT_EQ(backend->getCount("k"), 2u); /// `expectBytes` issues its own read, so it comes after every count assertion, not between them. DB::Cas::tests::expectBytes(*backend, "k", "1,2,3"); @@ -500,7 +500,7 @@ TEST(CASHotKeys, AnExternalWriterCostsOneResolveReadAndOneRetry) auto op = requests.admit(); CasRequests external_requests = DB::Cas::tests::openRequestsForTest(backend); auto external = external_requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); const auto current = external.read("k", Retry::standard()); (void)orThrow(external.replace("k", "E", current->etag, Retry::standard()), "external"); @@ -511,7 +511,7 @@ TEST(CASHotKeys, AnExternalWriterCostsOneResolveReadAndOneRetry) std::optional result; for (int i = 0; i < 3 && !result; ++i) { - WriteResult attempt = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)); + WriteResult attempt = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); if (std::holds_alternative(attempt)) op.pause(Retry::conflictBackoff()); else @@ -521,7 +521,7 @@ TEST(CASHotKeys, AnExternalWriterCostsOneResolveReadAndOneRetry) EXPECT_EQ(backend->getCount("k") - gets_before, 1u) << "one resolve read"; EXPECT_EQ(backend->writeCount("k") - writes_before, 2u) << "one refused write, one that landed"; /// The submission after that starts from the cache. - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(3)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(3)))); EXPECT_EQ(backend->getCount("k") - gets_before, 1u); /// `expectBytes` issues its own read, so it comes after every count assertion, not between them. DB::Cas::tests::expectBytes(*backend, "k", "E,2,3"); @@ -543,27 +543,27 @@ TEST(CASHotKeys, MalformedBytesRepairedExternallyRaiseNoCorruptionVerdict) throw DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "not a ticket list"); return current ? current->bytes + ",9" : String("9"); }; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), strict))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), strict))); auto current = external.read("k", Retry::standard()); const Etag garbage = *orThrow(external.replace("k", "garbage", current->etag, Retry::standard()), "break"); /// The lane's next hold starts from its cache, loses to the garbage, and remembers the garbage /// its resolve read saw; the caller pauses and submits again. - WriteResult first = hot_keys.submit("k", op, op.freeze(Retry::standard()), strict); + WriteResult first = hot_keys.submit("k", op, Retry::standard(), strict); ASSERT_TRUE(std::holds_alternative(first)); (void)orThrow(external.replace("k", "9", garbage, Retry::standard()), "repair"); const auto reread_before = counter(ProfileEvents::CASHotKeyCacheVerdictsReread); /// The verdict on the cached garbage is not delivered: one read, and the decide lands on the repair. - WriteResult second = hot_keys.submit("k", op, op.freeze(Retry::standard()), strict); + WriteResult second = hot_keys.submit("k", op, Retry::standard(), strict); ASSERT_TRUE(std::holds_alternative(second)); EXPECT_EQ(counter(ProfileEvents::CASHotKeyCacheVerdictsReread) - reread_before, 1u); DB::Cas::tests::expectBytes(*backend, "k", "9,9"); /// And when the read is garbage too, that is the real corruption. current = external.read("k", Retry::standard()); (void)orThrow(external.replace("k", "garbage", current->etag, Retry::standard()), "break again"); - (void)hot_keys.submit("k", op, op.freeze(Retry::standard()), strict); /// conflict: the cache now holds garbage + (void)hot_keys.submit("k", op, Retry::standard(), strict); /// conflict: the cache now holds garbage DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::CORRUPTED_DATA, - [&] { (void)hot_keys.submit("k", op, op.freeze(Retry::standard()), strict); }); + [&] { (void)hot_keys.submit("k", op, Retry::standard(), strict); }); } TEST(CASHotKeys, ADeclineOnAHintIsRerenderedOnARead) @@ -582,10 +582,10 @@ TEST(CASHotKeys, ADeclineOnAHintIsRerenderedOnARead) return std::nullopt; return String("1"); }; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), idempotent))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), idempotent))); /// On a fresh read the decline is the caller's answer. { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::once()), idempotent); + WriteResult result = hot_keys.submit("k", op, Retry::once(), idempotent); const auto * declined = std::get_if(&result); ASSERT_NE(declined, nullptr); EXPECT_TRUE(std::holds_alternative(declined->seen)); @@ -595,12 +595,12 @@ TEST(CASHotKeys, ADeclineOnAHintIsRerenderedOnARead) const auto current = external.read("k", Retry::standard()); (void)orThrow(external.replace("k", "0", current->etag, Retry::standard()), "external"); const uint64_t gets_before = backend->getCount("k"); - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), idempotent); + WriteResult result = hot_keys.submit("k", op, Retry::standard(), idempotent); ASSERT_TRUE(std::holds_alternative(result)); EXPECT_EQ(backend->getCount("k") - gets_before, 1u); DB::Cas::tests::expectBytes(*backend, "k", "1"); /// On an absent key the decline names absence. - WriteResult absent = hot_keys.submit("missing", op, op.freeze(Retry::standard()), + WriteResult absent = hot_keys.submit("missing", op, Retry::standard(), [](const std::optional &) -> std::optional { return std::nullopt; }); const auto * declined = std::get_if(&absent); ASSERT_NE(declined, nullptr); @@ -615,16 +615,16 @@ TEST(CASHotKeys, TheCacheForgetsWhatItCannotVouchFor) CasHotKeys hot_keys(16ULL << 20); CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto op = requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); const auto reads = [&] { return backend->getCount("k"); }; uint64_t before = reads(); #if USE_AWS_S3 /// Refused: dropped, the next hold reads. backend->failNextWriteWith("k", s3Error(Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(2)))); EXPECT_EQ(reads(), before); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(2)))); EXPECT_EQ(reads(), before + 1); #endif @@ -646,39 +646,39 @@ TEST(CASHotKeys, TheCacheForgetsWhatItCannotVouchFor) }); before = reads(); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::once()), appendTicket(3)); + WriteResult result = hot_keys.submit("k", op, Retry::once(), appendTicket(3)); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); EXPECT_TRUE(gave_up->sent_any); } backend->onBeforeWrite("k", [] {}); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(3)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(3)))); EXPECT_EQ(reads(), before + 3); /// the base read, the failed resolve read, the next hold's read after the entry was dropped /// An exception out of the write: dropped. backend->failNextWriteWith("k", std::make_exception_ptr(std::logic_error("local"))); before = reads(); - EXPECT_THROW(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(4)), std::logic_error); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(4)))); + EXPECT_THROW(hot_keys.submit("k", op, Retry::standard(), appendTicket(4)), std::logic_error); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(4)))); EXPECT_EQ(reads(), before + 1); /// A give-up that sent nothing leaves the entry as it was: the next hold starts from it. bool alive = true; auto fenced = requests.admit([&] { return alive; }); before = reads(); - WriteResult nothing_sent = hot_keys.submit("k", fenced, fenced.freeze(Retry::standard()), + WriteResult nothing_sent = hot_keys.submit("k", fenced, Retry::standard(), [&](const std::optional & current) -> std::optional { alive = false; return current->bytes + ",5"; }); ASSERT_TRUE(std::holds_alternative(nothing_sent)); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(5)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(5)))); EXPECT_EQ(reads(), before); /// A fill that throws after a landed write: the result stands, the next hold reads. hot_keys.cache_fill_hook_for_test = [] { throw std::bad_alloc(); }; before = reads(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(6)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(6)))); hot_keys.cache_fill_hook_for_test = {}; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(7)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(7)))); EXPECT_EQ(reads(), before + 1); DB::Cas::tests::expectBytes(*backend, "k", kFinalBytes); } @@ -698,18 +698,18 @@ TEST(CASHotKeys, TheBudgetBoundsBytesAndEntries) auto op = requests.admit(); const CasHotKeys::Decide one_byte = [](const std::optional &) -> std::optional { return String("x"); }; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("a", op, op.freeze(Retry::standard()), one_byte))); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("b", op, op.freeze(Retry::standard()), one_byte))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("a", op, Retry::standard(), one_byte))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("b", op, Retry::standard(), one_byte))); EXPECT_EQ(hot_keys.cacheEntriesForTest(), 1u) << "the older entry was evicted"; const uint64_t gets_a = backend->getCount("a"); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("a", op, op.freeze(Retry::standard()), one_byte))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("a", op, Retry::standard(), one_byte))); EXPECT_EQ(backend->getCount("a"), gets_a + 1) << "the evicted key reads"; /// An object above the budget is not stored. const CasHotKeys::Decide big = [&](const std::optional &) -> std::optional { return String(one_entry * 2, 'y'); }; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("c", op, op.freeze(Retry::standard()), big))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("c", op, Retry::standard(), big))); const uint64_t gets_c = backend->getCount("c"); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("c", op, op.freeze(Retry::standard()), big))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("c", op, Retry::standard(), big))); EXPECT_EQ(backend->getCount("c"), gets_c + 1); /// Empty objects weigh their key and their allowance: N of them stay bounded by the budget. @@ -718,7 +718,7 @@ TEST(CASHotKeys, TheBudgetBoundsBytesAndEntries) auto small_op = small_requests.admit(); const CasHotKeys::Decide empty = [](const std::optional &) -> std::optional { return String(); }; for (int i = 0; i < 40; ++i) - ASSERT_TRUE(std::holds_alternative(small.submit("e" + std::to_string(i), small_op, small_op.freeze(Retry::standard()), empty))); + ASSERT_TRUE(std::holds_alternative(small.submit("e" + std::to_string(i), small_op, Retry::standard(), empty))); EXPECT_LE(small.cacheEntriesForTest(), 4u); } @@ -730,12 +730,12 @@ TEST(CASHotKeys, ACachedStartPastTheDeadlineSendsNothing) CasHotKeys hot_keys(16ULL << 20); CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto op = requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); /// The window fits the wait's zero reservation but not the write's two attempt envelopes. int decided = 0; const uint64_t writes_before = backend->writeCount("k"); - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::within(500)), + WriteResult result = hot_keys.submit("k", op, Retry::within(500), [&](const std::optional & current) -> std::optional { ++decided; return current->bytes + ",2"; }); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); @@ -754,7 +754,7 @@ TEST(CASHotKeys, AnIdenticalCandidateLandedByAnotherServerIsTheEnginesCommit) auto op = requests.admit(); CasRequests external_requests = DB::Cas::tests::openRequestsForTest(backend); auto external = external_requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); /// Another server lands exactly the candidate this hold will compute from its stale hint, and this /// hold's own refused write loses its answer. The resolve read finds the candidate's bytes under @@ -762,7 +762,7 @@ TEST(CASHotKeys, AnIdenticalCandidateLandedByAnotherServerIsTheEnginesCommit) const auto current = external.read("k", Retry::standard()); const Etag theirs = *orThrow(external.replace("k", "1,2", current->etag, Retry::standard()), "identical"); backend->injectAmbiguousWrite("k"); - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)); + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); const auto * committed = std::get_if(&result); ASSERT_NE(committed, nullptr); EXPECT_TRUE(committed->resolved_by_read); diff --git a/src/Disks/tests/gtest_cas_pool.cpp b/src/Disks/tests/gtest_cas_pool.cpp index 47c1d5b260ffc..1f1ea69929cc1 100644 --- a/src/Disks/tests/gtest_cas_pool.cpp +++ b/src/Disks/tests/gtest_cas_pool.cpp @@ -202,7 +202,7 @@ ManifestId publishPartWithEntries( } /// The disk's request window reaches every request plane a pool exposes, not only the one a give-up -/// test happens to use. A plane built with the default window would freeze a 120 s deadline here. +/// test happens to use. A plane built with the default window would bind a 120 s deadline here. TEST(CASPool, EveryExposedRequestPlaneTakesTheConfiguredRequestWindow) { constexpr uint64_t window_ms = 20'000; @@ -217,9 +217,10 @@ TEST(CASPool, EveryExposedRequestPlaneTakesTheConfiguredRequestWindow) for (const auto & [name, plane] : planes) { DB::Cas::CasOperation op = plane->admit(); - const DB::Cas::Retry frozen = op.freeze(DB::Cas::Retry::standard()); - ASSERT_TRUE(frozen.policy_deadline_ms) << name; - EXPECT_EQ(*frozen.policy_deadline_ms, clock->nowMs() + window_ms) << name; + plane->setAttemptReservationForTest(window_ms - 1'000); + EXPECT_NO_THROW(op.head("k", DB::Cas::Retry::standard())) << name << ": sent when one envelope fits the window"; + plane->setAttemptReservationForTest(window_ms + 1'000); + EXPECT_THROW(op.head("k", DB::Cas::Retry::standard()), DB::Exception) << name << ": refused unsent past the window"; } } diff --git a/src/Disks/tests/gtest_cas_requests.cpp b/src/Disks/tests/gtest_cas_requests.cpp index 7b31f39ba281d..f4cc31db774e3 100644 --- a/src/Disks/tests/gtest_cas_requests.cpp +++ b/src/Disks/tests/gtest_cas_requests.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -159,20 +160,31 @@ TEST(CASRetry, PoliciesAreShapedAsSpecified) /// A cap later than the request's own window leaves the window. TEST(CASRetry, AnOutsideCapLaterThanTheWindowLeavesTheWindow) { - FakeClock clock; - auto backend = std::make_shared(); - auto requests = makeRequests(backend, clock); - auto op = requests.admit(); + const uint64_t now = 1'000'000; + EXPECT_EQ(Retry::standard().cappedAt(now + 3'600'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 90'000); + EXPECT_EQ(Retry::within(5'000).cappedAt(now + 60'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 5'000); +} - const uint64_t start = clock.now; - const Retry frozen = op.freeze(Retry::standard()); - ASSERT_TRUE(frozen.policy_deadline_ms.has_value()); - EXPECT_EQ(frozen.bind(start, kEngineTestWindowMs).deadline_ms, start + 90'000); - EXPECT_EQ(frozen.bind(start + 50'000, kEngineTestWindowMs).deadline_ms, start + 90'000); - EXPECT_FALSE(frozen.bind(start + 50'000, kEngineTestWindowMs).lease_bound); - /// The single-attempt view of a frozen policy keeps the deadline rather than starting a window. - EXPECT_EQ(frozen.asSingleAttempt().policy_deadline_ms, frozen.policy_deadline_ms); - EXPECT_TRUE(frozen.asSingleAttempt().single_attempt); +/// An earlier cap or an earlier lease bound wins, and the lease bound still says so when it is the one that won. +TEST(CASRetry, AnEarlierOutsideCapAndAnEarlierLeaseBothWin) +{ + const uint64_t now = 1'000'000; + const Retry::Bound capped = Retry::standard().cappedAt(now + 10'000).bind(now, kEngineTestWindowMs); + EXPECT_EQ(capped.deadline_ms, now + 10'000); + EXPECT_NE(capped.source, Retry::Bound::Source::Lease); + + Retry both = Retry::untilLeaseSafe(now + 10'000, 2'000).cappedAt(now + 20'000); + EXPECT_EQ(both.bind(now, kEngineTestWindowMs).deadline_ms, now + 8'000); + EXPECT_EQ(both.bind(now, kEngineTestWindowMs).source, Retry::Bound::Source::Lease); + + both = Retry::untilLeaseSafe(now + 10'000, 2'000).cappedAt(now + 3'000); + EXPECT_EQ(both.bind(now, kEngineTestWindowMs).deadline_ms, now + 3'000); + EXPECT_NE(both.bind(now, kEngineTestWindowMs).source, Retry::Bound::Source::Lease); + + EXPECT_EQ(Retry::standard().cappedAt(now + 20'000).cappedAt(now + 5'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 5'000); + EXPECT_EQ(Retry::standard().cappedAt(now + 60'000).bind(now + 50'000, kEngineTestWindowMs).deadline_ms, now + 60'000); + EXPECT_EQ(Retry::standard().cappedAt(now + 5'000).cappedAt(now + 20'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 5'000); +} /// A bound names the bound that set its deadline; a tie goes to the request window, then to the outside cap. TEST(CASRetry, BindNamesTheExactSourceOfItsDeadline) @@ -183,9 +195,34 @@ TEST(CASRetry, BindNamesTheExactSourceOfItsDeadline) EXPECT_EQ(Retry::standard().cappedAt(now + 10'000).bind(now, kEngineTestWindowMs).source, Source::OutsideCap); EXPECT_EQ(Retry::untilLeaseSafe(now + 10'000, 2'000).bind(now, kEngineTestWindowMs).source, Source::Lease); - const Retry::Bound leashed = op.freeze(Retry::untilLeaseSafe(start + 10'000, 2'000)).bind(clock.now, kEngineTestWindowMs); - EXPECT_EQ(leashed.deadline_ms, start + 8'000); - EXPECT_TRUE(leashed.lease_bound); + const Retry::Bound all_equal + = Retry::untilLeaseSafe(now + 92'000, 2'000).cappedAt(now + 90'000).bind(now, kEngineTestWindowMs); + EXPECT_EQ(all_equal.deadline_ms, now + 90'000); + EXPECT_EQ(all_equal.source, Source::RequestWindow); + + const Retry::Bound cap_equals_lease + = Retry::untilLeaseSafe(now + 12'000, 2'000).cappedAt(now + 10'000).bind(now, kEngineTestWindowMs); + EXPECT_EQ(cap_equals_lease.deadline_ms, now + 10'000); + EXPECT_EQ(cap_equals_lease.source, Source::OutsideCap); +} + +TEST(CASRetry, BindSaturatesWhenTheWindowOverflows) +{ + const uint64_t now = std::numeric_limits::max() - 10; + EXPECT_EQ(Retry::within(1'000).bind(now, kEngineTestWindowMs).deadline_ms, std::numeric_limits::max()); +} + +/// The tool's preflight checks the bound the engine will apply, so a plane window too short for one attempt +/// is the tool's timeout even when the tool's own deadline is far away. +TEST(CASRequests, ToolDeadlinePreflightChecksTheWindowNotOnlyTheCap) +{ + FakeClock clock; + auto backend = std::make_shared(); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, 1'000); + requests.setAttemptReservationForTest(5'000); + const ToolDeadline deadline(requests, std::chrono::hours(1), "tool", "raise --timeout"); + auto op = requests.admit(); + EXPECT_THROW(deadline.bound(op, "phase"), DB::Exception); } /// A policy that names no window takes the window of the plane it runs on; one that names its own keeps it. From 8f2282985a6692c1be487b5b7c03453e296bad5b Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:27:55 +0100 Subject: [PATCH 05/47] Add `CasOwner` to let the owner of CAS work stop it The owner is the query or a background owner (`OwnerScope::background`). `OwnerScope::owed` marks work owed to a possibly-sent write or a failed commit; `OwnerScope::shared` marks work done for several callers. `CasOwner.h` lists where work may end and the facts that classify a failure. Adds the killable-query test fixture. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressed/Backend/CasOwner.cpp | 238 ++++++ .../ContentAddressed/Backend/CasOwner.h | 173 +++++ src/Disks/tests/cas_killable_query.h | 219 ++++++ src/Disks/tests/gtest_cas_killable_query.cpp | 42 + src/Disks/tests/gtest_cas_owner_stop.cpp | 721 ++++++++++++++++++ 5 files changed, 1393 insertions(+) create mode 100644 src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp create mode 100644 src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h create mode 100644 src/Disks/tests/cas_killable_query.h create mode 100644 src/Disks/tests/gtest_cas_killable_query.cpp create mode 100644 src/Disks/tests/gtest_cas_owner_stop.cpp diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp new file mode 100644 index 0000000000000..7fe8fde5bf080 --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp @@ -0,0 +1,238 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace DB::ErrorCodes +{ + extern const int CANNOT_SCHEDULE_TASK; + extern const int LOGICAL_ERROR; +} + +namespace DB::Cas +{ + +thread_local OwnerScope::State OwnerScope::current; + +namespace +{ + +/// The exception `check` throws, or null. +template +std::exception_ptr exceptionOf(Check && check) +{ + try + { + check(); + } + catch (...) + { + return std::current_exception(); + } + return nullptr; +} + +} + +std::exception_ptr ownerStopRequested() +{ + const auto & owner = OwnerScope::current; + if (owner.shared) + return nullptr; + return exceptionOf([&] + { + CurrentThread::checkIfNotCancelled(); + if (owner.background) + owner.background(); + }); +} + +bool queryStopRequested() +{ + return !OwnerScope::current.shared && exceptionOf([] { CurrentThread::checkIfNotCancelled(); }) != nullptr; +} + +void throwIfBackgroundStopped() +{ + const auto & owner = OwnerScope::current; + if (!owner.owed && !owner.shared && owner.background) + owner.background(); +} + +void throwIfQueryStopped() +{ + const auto & owner = OwnerScope::current; + if (!owner.owed && !owner.shared) + CurrentThread::checkIfNotCancelled(); +} + +bool insideOwed() +{ + return OwnerScope::current.owed; +} + +std::exception_ptr backgroundStopRequested() +{ + const auto & owner = OwnerScope::current; + if (owner.shared || !owner.background) + return nullptr; + return exceptionOf(owner.background); +} + +namespace +{ + +/// The throwing check builds a new exception on each call for a query killed without a stored cause, so it runs only +/// after the kill flag that check reads is set. +bool isStoredCauseOfThisThreadsQuery(const std::exception_ptr & e) +{ + if (!e) + return false; + const ContextPtr query = CurrentThread::tryGetQueryContext(); + if (!query || !query->isCurrentQueryKilled()) + return false; + return e == exceptionOf([] { CurrentThread::checkIfNotCancelled(); }); +} + +} + +bool isQueryStoredCause(const std::exception_ptr & e) +{ + return !OwnerScope::current.shared && isStoredCauseOfThisThreadsQuery(e); +} + +void addMessageUnlessQueryStoredCause(Exception & e, const std::string & message) +{ + if (!isStoredCauseOfThisThreadsQuery(std::current_exception())) + e.addMessage(message); +} + +void rethrowOwnCopy(const std::exception_ptr & e) +{ + if (!e) + throw Exception(ErrorCodes::LOGICAL_ERROR, "rethrowOwnCopy: no exception to rethrow"); + if (isStoredCauseOfThisThreadsQuery(e)) + std::rethrow_exception(e); + try + { + std::rethrow_exception(e); + } + catch (const Poco::Exception & shared) + { + /// The copy allocates; a receiver at its memory limit must still get the shared failure. + LockMemoryExceptionInThread lock_memory_tracker(VariableContext::Global); + shared.rethrow(); + } +} + +void rethrowIfStoppedOwnersFailure() +{ + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(std::move(stop)); + if (queryStopRequested()) + throw; +} + +void throwUnlessInThreadGroup(const ThreadGroupPtr & expected, std::string_view worker) +{ + if (expected && CurrentThread::getGroup() != expected) + throw Exception(ErrorCodes::CANNOT_SCHEDULE_TASK, + "{} could not join its thread group, so it sends nothing", worker); +} + +bool sleepUnlessQueryStops(uint64_t ms, const std::function & sleep) +{ + if (insideOwed() || !CurrentThread::getGroup()) + { + sleep(ms); + return true; + } + constexpr auto slice_ms = static_cast(kOwnerStopSlice.count()); + uint64_t left = ms; + do + { + if (queryStopRequested()) + return false; + const uint64_t slice = std::min(left, slice_ms); + sleep(slice); + left -= slice; + } while (left > 0); + return !queryStopRequested(); +} + +void waitStoppable(std::condition_variable & cv, std::unique_lock & lock, const std::function & ready) +{ + /// Only a background owner is polled; without one in effect a notification is the only way out. + if (!OwnerScope::effectiveCheck()) + { + cv.wait(lock, ready); + return; + } + while (true) + { + /// The predicate is leaf-locked by contract (`OwnerScope::background`); unlocking keeps the caller's mutex + /// free while it builds its exception. + lock.unlock(); + std::exception_ptr verdict = backgroundStopRequested(); + lock.lock(); + if (verdict) + std::rethrow_exception(std::move(verdict)); + if (ready()) + return; + cv.wait_for(lock, kOwnerStopSlice); + } +} + +OwnerScope::OwnerScope(State next) + : saved(std::exchange(current, std::move(next))) +{ +} + +OwnerScope::OwnerScope(OwnerScope && other) noexcept + : saved(std::move(other.saved)) + , active(std::exchange(other.active, false)) +{ +} + +OwnerScope::~OwnerScope() +{ + if (active) + current = std::move(saved); +} + +OwnerScope OwnerScope::background(std::function throw_if_stopped) +{ + if (current.background) + throw_if_stopped = [outer = current.background, inner = std::move(throw_if_stopped)] + { + outer(); + inner(); + }; + return OwnerScope(State{current.owed, current.shared, std::move(throw_if_stopped)}); +} + +OwnerScope OwnerScope::owed() +{ + return OwnerScope(State{true, current.shared, current.background}); +} + +OwnerScope OwnerScope::shared() +{ + return OwnerScope(State{current.owed, true, current.background}); +} + +std::function OwnerScope::effectiveCheck() +{ + if (current.owed || current.shared) + return {}; + return current.background; +} + +} diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h new file mode 100644 index 0000000000000..fab5f4478f5f9 --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h @@ -0,0 +1,173 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace DB +{ +class Exception; +class ThreadGroup; +using ThreadGroupPtr = std::shared_ptr; +} + +namespace DB::Cas +{ + +/// Lets the owner of CAS work stop it: the query, or a background owner. The background owners are the GC scheduler's +/// stop and server shutdown's removal of an `Atomic` table's namespace. Pool teardown is not one: it ends work through +/// the operation's liveness and the detached-work stop token. +/// +/// Decision points, where work may end. Inside `owed` or `shared` they do nothing, except that the catch helper +/// still acts inside `owed` and the thread-group guard throws in every scope: +/// +/// | Point in the code | Helper | +/// |----------------------------------------------------|---------------------------------------------------------| +/// | Before more work: a retry, a decision, a next page | `throwIfBackgroundStopped` | +/// | Head of a CAS-owned resumable scan | `throwIfQueryStopped`, then `throwIfBackgroundStopped` | +/// | A pause after a failure | `sleepUnlessQueryStops` | +/// | A wait on a condition variable | `waitStoppable` | +/// | A worker that switched to the submitter's group | `throwUnlessInThreadGroup` | +/// | A catch that would swallow, convert or retry | `rethrowIfStoppedOwnersFailure`, also inside `owed` | +/// +/// Facts, for code that classifies a failure. They hold inside `owed` too and decide nothing: +/// +/// | Question | Helper | +/// |----------------------------------------------------|---------------------------------------------------------| +/// | Did an owner ask to stop, and with what verdict | `ownerStopRequested`, `queryStopRequested`, `backgroundStopRequested` | +/// | Is this exception the query's stored cause | `isQueryStoredCause` | +/// | Annotating or rethrowing a caught exception | `addMessageUnlessQueryStoredCause`, `rethrowOwnCopy` | +/// +/// A query is consulted only where stopping leaves the state a storage failure there would leave: after a failed +/// attempt (its retry, its pause, a catch that would swallow or convert it) and at a scan head. It does not end a first +/// attempt, a decision after an accepted conflict, a wait, compensation, `abandon`, namespace removal, `FORGET`, or +/// recovery's first walk. The `SYSTEM CAS FSCK` scan has no scan head. +/// +/// What a stop ends with: +/// - A stopped owner's exception is not a store answer: neither absence, nor a refusal, nor a local fault. A local +/// fault is surfaced unchanged. +/// - A vetoed retry of a read or a blob publication ends with the failed attempt's exception, whatever its code: a +/// timed-out attempt's `TIMEOUT_EXCEEDED` is that attempt's own. A vetoed retry after a credential refusal ends as +/// a retry-later `NETWORK_ERROR` carrying the refusal, unless the read already refreshed after an earlier failure. +/// - A vetoed resend of a conditional write ends as the retry-later `NETWORK_ERROR` "unresolved", naming what its +/// settling read saw, not the store's error. With no earlier attempt unanswered, a refusal keeps the store's error, +/// except that a vetoed resend with refreshed credentials ends as a retry-later `NETWORK_ERROR` carrying the +/// refusal. A scan head throws the query's verdict. +/// - A killed query's conditional write that loses a race can end as `ABORTED` "conflict": the S3 client replaces the +/// 412 with the query's exception, and the settling read shows the other writer's object. +/// - An unresolved sent write keeps its "outcome unknown" exit; a later owner verdict does not overwrite it. +/// - `OwnerScope::owed` removes the checks before work and the query's cut of a pause: the pause runs to its end, and +/// the next attempt is sent unless the fence, the lease or a deadline refuses it after the pause. A failure after a +/// stop is still not retried, and a background owner's verdict still replaces it. `OwnerScope::shared` removes the +/// owner. Neither hides a query from the S3 client, which replaces a failed request's answer with the query's +/// verdict; a bulk delete that succeeds with an error for one key keeps that key's error. +/// - Code above the engine may still do follow-up work its own counts bound, such as another recovery walk. With a +/// lease loss or a credential refusal at the same time, the error can be the less specific of the two. + +/// How late a waiter that nobody notifies notices its owner's stop. +inline constexpr std::chrono::milliseconds kOwnerStopSlice{200}; + +/// The verdict of the owner of this thread's work if it asked to stop: the query's +/// (`CurrentThread::checkIfNotCancelled`), then the background owners' in scope. Null inside `shared`. +std::exception_ptr ownerStopRequested(); + +/// True when the thread's query, not a background owner, asked to stop. False inside `shared`. +/// The S3 client throws the query's verdict in place of a failed request's answer, but not of one key's error in a +/// bulk delete that succeeded, and it cannot see a background owner. +bool queryStopRequested(); + +/// Rethrows the verdict of the background owners in scope, except inside `owed` or `shared`. Ignores the query. +void throwIfBackgroundStopped(); + +/// Rethrows the query's verdict, except inside `owed` or `shared`. Ignores background owners. For a scan head only. +void throwIfQueryStopped(); + +/// True inside `owed`: owner checks do not throw, and `observe` reports a stopped owner's failed read as not observed. +bool insideOwed(); + +/// The background owners' verdict, also inside `owed`; ignores the query. Null inside `shared`. +std::exception_ptr backgroundStopRequested(); + +/// True when `e` is the query's stored cancellation cause, the one verdict rethrown as the same object to every thread +/// the query stops; false inside `shared`. A kill or timeout without a stored cause and every background owner's verdict +/// are built anew on each check, so they never match. Such a cause is neither a store answer nor a local fault, +/// whatever its code or type. +bool isQueryStoredCause(const std::exception_ptr & e); + +/// Adds `message` to `e`, the exception being handled, unless `e` is the query's stored cause, whatever the scope: +/// several threads may hold that one object, so annotating it would race. +void addMessageUnlessQueryStoredCause(Exception & e, const std::string & message); + +/// Rethrows `e`, which several threads may hold, as this thread's own copy made by `Poco::Exception::rethrow`, so a +/// caller that annotates what it catches races with nobody. The query's stored cause and an exception that is not a +/// `Poco::Exception` are rethrown as they are. A memory limit does not replace the copy. +[[noreturn]] void rethrowOwnCopy(const std::exception_ptr & e); + +/// For a catch about to swallow, convert or retry the exception being handled: rethrows the background owners' +/// verdict, or the exception being handled when the query stopped. A killed query keeps the error of its own failure. +void rethrowIfStoppedOwnersFailure(); + +/// For work that switched to `expected`, such as a pool worker joining the group that submitted it: throws +/// `CANNOT_SCHEDULE_TASK` unless the thread is in it; no check when it is null. `ThreadGroupSwitcher` swallows its own +/// failure, and a request sent outside the intended group sees the wrong query. +void throwUnlessInThreadGroup(const ThreadGroupPtr & expected, std::string_view worker); + +/// Sleeps `ms` through `sleep`. Outside `owed`, on a thread with a thread group, sleeps in `kOwnerStopSlice` slices and +/// checks the query before each slice and after the last; false when it stopped, leaving the rest unslept. +bool sleepUnlessQueryStops(uint64_t ms, const std::function & sleep); + +/// Waits until `ready` holds, throwing as `throwIfBackgroundStopped` does. Checks the owners with `lock` released +/// before each evaluation of `ready`; with no background owner in effect it is a plain `cv.wait`. Returns and throws +/// with `lock` held. +void waitStoppable(std::condition_variable & cv, std::unique_lock & lock, const std::function & ready); + +/// Thread-scoped like query cancellation, so no owner parameter crosses the request engine. Scopes nest; +/// a nested scope never lifts an enclosing `owed` or `shared`. Destruction restores the enclosing scope. +class OwnerScope +{ +public: + /// An owner with no thread group predicate; `throw_if_stopped` throws its verdict. It runs under CAS + /// mutexes, so it is lock-free or takes a leaf lock. Enclosing background owners stay checked first. + static OwnerScope background(std::function throw_if_stopped); + /// Work owed to a possibly-sent write, a failed commit or a claimed resource: no throwing check. + static OwnerScope owed(); + /// Work for several callers: CAS owner checks see no owner. The S3 client still replaces a failed answer with the + /// exception of the thread's query. + static OwnerScope shared(); + + /// This thread's background owner check, to keep calling inside a later `shared` scope. Valid only while the + /// scope that installed it is alive. Empty without a background owner and inside `owed` or `shared`. + static std::function effectiveCheck(); + + OwnerScope(OwnerScope && other) noexcept; + ~OwnerScope(); + +private: + struct State + { + bool owed = false; + bool shared = false; + std::function background; + }; + + explicit OwnerScope(State next); + + friend std::exception_ptr ownerStopRequested(); + friend bool queryStopRequested(); + friend bool insideOwed(); + friend void throwIfBackgroundStopped(); + friend void throwIfQueryStopped(); + friend std::exception_ptr backgroundStopRequested(); + friend bool isQueryStoredCause(const std::exception_ptr & e); + static thread_local State current; + + State saved; + bool active = true; +}; + +} diff --git a/src/Disks/tests/cas_killable_query.h b/src/Disks/tests/cas_killable_query.h new file mode 100644 index 0000000000000..a4b3157ce5ec1 --- /dev/null +++ b/src/Disks/tests/cas_killable_query.h @@ -0,0 +1,219 @@ +#pragma once + +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace DB::ErrorCodes +{ +extern const int ABORTED; +} + +/// Skips a test that enables a fail point in a build without libfiu, where enabling one throws `SUPPORT_IS_DISABLED`. +#define CAS_SKIP_WITHOUT_FAILPOINTS() \ + do \ + { \ + if constexpr (!::DB::Cas::tests::kFailPointsAvailable) \ + GTEST_SKIP() << "built without libfiu, so fail points are unavailable"; \ + } while (false) + +namespace DB::Cas::tests +{ + +inline constexpr bool kFailPointsAvailable = USE_LIBFIU; + +/// A query registered in the process list, so a kill reaches CAS code through the thread group as it +/// does in the server. Construct it on a thread that has a `ThreadStatus`; the constructing +/// thread stays attached. Destroy it after every worker thread joined. +struct CasKillableQuery +{ + explicit CasKillableQuery(ContextPtr global); + ~CasKillableQuery(); + + CasKillableQuery(const CasKillableQuery &) = delete; + CasKillableQuery & operator=(const CasKillableQuery &) = delete; + + /// For a worker thread with its own `ThreadStatus`, as a query's thread pool attaches its workers. + void attachCurrentThread(); + + /// `KILL QUERY`; with `cause`, the query throws that exception instead of `QUERY_WAS_CANCELLED`. + void kill(std::exception_ptr cause = nullptr); + + ContextMutablePtr context; + ThreadGroupPtr group; + ProcessList::EntryPtr entry; + QueryStatusPtr status; +}; + +/// Runs `body` on a fresh thread, with a `ThreadStatus` when `with_thread_status`, joins it, and rethrows on the calling +/// thread an exception that left `body`, which would otherwise terminate the test process. Thread-local owner +/// state and the gtest main thread's missing `ThreadStatus` make a raw thread the only clean starting point. +template +void onThread(bool with_thread_status, Body && body) +{ + std::exception_ptr error; + std::thread worker([&] + { + std::optional thread_status; + if (with_thread_status) + thread_status.emplace(); + try + { + body(); + } + catch (...) + { + error = std::current_exception(); + } + }); + worker.join(); + if (error) + std::rethrow_exception(error); +} + +/// Runs `body(query)` on a fresh thread with a `ThreadStatus`, attached to a fresh query registered in the process +/// list as a SQL query's thread is, and joins it. +template +void onKillableQueryThread(Body && body) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + body(query); + }); +} + +enum class StoppedBy : uint8_t { Background, Query }; + +inline const char * nameOf(StoppedBy owner) +{ + return owner == StoppedBy::Background ? "background owner" : "killed query"; +} + +/// A background owner on the calling thread whose check throws `ABORTED` once `*stopped` is set. +inline OwnerScope backgroundOwnerStoppedBy(const std::shared_ptr> & stopped) +{ + return OwnerScope::background([stopped] + { + if (stopped->load()) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); +} + +/// The stop of `owner`: kills `query`, or sets `*background_stopped`. +inline std::function stopperOf(StoppedBy owner, CasKillableQuery & query, + const std::shared_ptr> & background_stopped) +{ + if (owner == StoppedBy::Query) + return [&query] { query.kill(); }; + return [background_stopped] { *background_stopped = true; }; +} + +namespace client_like_detail +{ + +template +auto checkedOnThrow(Call && call) +{ + try + { + return call(); + } + catch (...) + { + CurrentThread::checkIfNotCancelled(); + throw; + } +} + +template +auto checkedUnless(Call && call, Succeeded && succeeded) +{ + auto answer = checkedOnThrow(std::forward(call)); + if (!succeeded(answer)) + CurrentThread::checkIfNotCancelled(); + return answer; +} + +} + +/// Forwards to `inner` and, as the S3 client does after every unsuccessful response, checks the current +/// thread's query on each miss, conflict or failure before answering. Success is never checked. The +/// sentinel probe stays the base default, which goes through the decorated `head` and `read`. +class CasClientLikeBackend final : public Backend +{ +public: + explicit CasClientLikeBackend(BackendPtr inner_) : inner(std::move(inner_)) {} + + std::optional read(const String & key, TransportAccess & access) override + { + return client_like_detail::checkedUnless([&] { return inner->read(key, access); }, [](const auto & r) { return r.has_value(); }); + } + + std::optional head(const String & key, TransportAccess & access) override + { + return client_like_detail::checkedUnless([&] { return inner->head(key, access); }, [](const auto & r) { return r.has_value(); }); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + return client_like_detail::checkedOnThrow([&] { return inner->list(prefix, cursor, limit, access); }); + } + + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + return client_like_detail::checkedUnless( + [&] { return inner->remove(key, expected_value, access); }, [](RawRemoval r) { return r == RawRemoval::Removed; }); + } + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + return client_like_detail::checkedUnless( + [&] { return inner->write(key, bytes, expected_value, access); }, [](const auto & r) { return r.has_value(); }); + } + + std::unique_ptr stream(const String & key, TransportAccess & access) override + { + return client_like_detail::checkedUnless([&] { return inner->stream(key, access); }, [](const auto & r) { return r != nullptr; }); + } + + void publish(const BlobPublishRequest & request, TransportAccess & access) override + { + client_like_detail::checkedOnThrow([&] { inner->publish(request, access); }); + } + + void removeManyWriteOnce(const std::vector & keys, TransportAccess & access) override + { + client_like_detail::checkedOnThrow([&] { inner->removeManyWriteOnce(keys, access); }); + } + + Dialect dialect() const override { return inner->dialect(); } + bool supportsListTokens() const override { return inner->supportsListTokens(); } + uint64_t attemptTimeoutMs() const override { return inner->attemptTimeoutMs(); } + uint64_t attemptEnvelopeMs() const override { return inner->attemptEnvelopeMs(); } + size_t bulkDeleteKeyLimit() const override { return inner->bulkDeleteKeyLimit(); } + bool refreshCredentials() override { return inner->refreshCredentials(); } + void checkPoolPreconditions() override { inner->checkPoolPreconditions(); } + void checkSkipAccessCheckSupport() override { inner->checkSkipAccessCheckSupport(); } + void checkConditionalWriteSingleAttemptSupport() override { inner->checkConditionalWriteSingleAttemptSupport(); } + +private: + BackendPtr inner; +}; + +} diff --git a/src/Disks/tests/gtest_cas_killable_query.cpp b/src/Disks/tests/gtest_cas_killable_query.cpp new file mode 100644 index 0000000000000..506a966670e61 --- /dev/null +++ b/src/Disks/tests/gtest_cas_killable_query.cpp @@ -0,0 +1,42 @@ +#include + +#include +#include + +namespace DB::Cas::tests +{ + +CasKillableQuery::CasKillableQuery(ContextPtr global) + : context(Context::createCopy(global)) +{ + context->setCurrentQueryId(""); + group = std::make_shared(context, 0); + attachCurrentThread(); + /// The process list binds the query to the group of the inserting thread, so attach first. + entry = context->getProcessList().insert( + /*query_=*/"", /*normalized_query_hash=*/0, /*ast=*/nullptr, context, + /*watch_start_nanoseconds=*/clock_gettime_ns(), /*is_internal=*/true); + status = entry->getQueryStatus(); + context->setProcessListElement(status); +} + +CasKillableQuery::~CasKillableQuery() +{ + /// `ThreadStatus` checks on destruction that an attached query's context is still alive. + if (group && CurrentThread::getGroup() == group) + CurrentThread::detachFromGroupIfNotDetached(); + context->setProcessListElement(nullptr); + entry.reset(); +} + +void CasKillableQuery::attachCurrentThread() +{ + CurrentThread::attachToGroup(group); +} + +void CasKillableQuery::kill(std::exception_ptr cause) +{ + status->cancelQuery(CancelReason::CANCELLED_BY_USER, cause); +} + +} diff --git a/src/Disks/tests/gtest_cas_owner_stop.cpp b/src/Disks/tests/gtest_cas_owner_stop.cpp new file mode 100644 index 0000000000000..e73e3813ed831 --- /dev/null +++ b/src/Disks/tests/gtest_cas_owner_stop.cpp @@ -0,0 +1,721 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#if USE_AWS_S3 +#include +#endif + +namespace DB::ErrorCodes +{ + extern const int ABORTED; + extern const int BAD_ARGUMENTS; + extern const int CORRUPTED_DATA; + extern const int FILE_DOESNT_EXIST; + extern const int MEMORY_LIMIT_EXCEEDED; + extern const int NETWORK_ERROR; + extern const int NOT_IMPLEMENTED; + extern const int QUERY_WAS_CANCELLED; + extern const int READONLY; + extern const int S3_ERROR; + extern const int TIMEOUT_EXCEEDED; +} + +using namespace DB; +using namespace DB::Cas; +using DB::Cas::tests::CasClientLikeBackend; +using DB::Cas::tests::CasKillableQuery; +using DB::Cas::tests::StoppedBy; +using DB::Cas::tests::nameOf; +using DB::Cas::tests::onThread; +using DB::Cas::tests::CountingBackend; +using DB::Cas::tests::ManualClock; +using DB::Cas::tests::TimeTakingBackend; +using DB::Cas::tests::openRequestsForTest; + +namespace +{ + +constexpr auto WATCHDOG = std::chrono::seconds(30); + +/// 0 for no exception. +int codeOf(const std::exception_ptr & e) +{ + if (!e) + return 0; + try + { + std::rethrow_exception(e); + } + catch (const Exception & ex) + { + return ex.code(); + } + catch (...) + { + return -1; + } +} + +/// Empty for no exception. +String messageOf(const std::exception_ptr & e) +{ + if (!e) + return {}; + try + { + std::rethrow_exception(e); + } + catch (const std::exception & ex) + { + return ex.what(); + } + catch (...) + { + return {}; + } +} + +/// The query's verdict, then the background owners': both checks, in the order a scan head runs them. +std::exception_ptr checkOnce() +{ + try + { + throwIfQueryStopped(); + throwIfBackgroundStopped(); + } + catch (...) + { + return std::current_exception(); + } + return nullptr; +} + +/// A background owner that throws a fresh `ABORTED` once `stop` is set. +OwnerScope backgroundStoppedBy(const std::atomic & stop) +{ + return OwnerScope::background([&stop] + { + if (stop.load()) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); +} + +/// Wakes `cv` once, after its waiter released `mutex` to wait. Start it while the waiter holds the lock. +std::thread wakeOnceWaiting(std::mutex & mutex, std::condition_variable & cv) +{ + return std::thread([&mutex, &cv] + { + std::lock_guard lock(mutex); + cv.notify_all(); + }); +} + +} + +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_move_constructible_v); + +/// An exception that leaves the body of `onThread` fails the calling test instead of terminating the test process. +TEST(CASOwnerScope, OnThreadRethrowsTheBodysExceptionOnTheCallingThread) +{ + EXPECT_THROW(onThread(false, [] { throw Exception(ErrorCodes::ABORTED, "thrown on the raw thread"); }), Exception); +} + +TEST(CASOwnerScope, NoScopeNoQueryIsANoOp) +{ + for (bool with_thread_status : {false, true}) + { + onThread(with_thread_status, [&] + { + EXPECT_EQ(ownerStopRequested(), nullptr); + EXPECT_NO_THROW(throwIfQueryStopped()); + EXPECT_NO_THROW(throwIfBackgroundStopped()); + EXPECT_FALSE(insideOwed()); + EXPECT_FALSE(OwnerScope::effectiveCheck()); + }); + } +} + +TEST(CASOwnerScope, BackgroundStopIsThrown) +{ + onThread(false, [&] + { + std::atomic stop{false}; + { + auto scope = backgroundStoppedBy(stop); + EXPECT_EQ(checkOnce(), nullptr); + stop = true; + auto verdict = checkOnce(); + ASSERT_NE(verdict, nullptr); + EXPECT_EQ(codeOf(verdict), ErrorCodes::ABORTED); + EXPECT_EQ(codeOf(ownerStopRequested()), ErrorCodes::ABORTED); + } + EXPECT_EQ(checkOnce(), nullptr); + EXPECT_EQ(ownerStopRequested(), nullptr); + }); +} + +TEST(CASOwnerScope, OwedSuppressesTheThrowButNotTheVerdict) +{ + onThread(false, [&] + { + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + { + auto owed = OwnerScope::owed(); + EXPECT_TRUE(insideOwed()); + EXPECT_EQ(checkOnce(), nullptr); + EXPECT_EQ(codeOf(ownerStopRequested()), ErrorCodes::ABORTED); + } + EXPECT_FALSE(insideOwed()); + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::ABORTED); + }); +} + +TEST(CASOwnerScope, SharedHidesEveryOwner) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + query.kill(); + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::QUERY_WAS_CANCELLED); + { + auto shared = OwnerScope::shared(); + EXPECT_EQ(ownerStopRequested(), nullptr); + EXPECT_EQ(checkOnce(), nullptr); + EXPECT_FALSE(insideOwed()); + auto inner_background = backgroundStoppedBy(stop); + EXPECT_EQ(ownerStopRequested(), nullptr); + } + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::QUERY_WAS_CANCELLED); + }); +} + +TEST(CASOwnerScope, ScopesNestAndRestore) +{ + onThread(false, [&] + { + std::atomic outer_stop{false}; + std::atomic inner_stop{false}; + auto outer = OwnerScope::background([&] + { + if (outer_stop.load()) + throw Exception(ErrorCodes::ABORTED, "outer"); + }); + { + auto inner = OwnerScope::background([&] + { + if (inner_stop.load()) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "inner"); + }); + inner_stop = true; + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::BAD_ARGUMENTS); + outer_stop = true; + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::ABORTED) << "an enclosing owner is checked first"; + { + auto owed = OwnerScope::owed(); + auto background_in_owed = backgroundStoppedBy(inner_stop); + EXPECT_TRUE(insideOwed()) << "a nested scope never lifts an enclosing owed"; + EXPECT_EQ(checkOnce(), nullptr); + { + auto shared = OwnerScope::shared(); + EXPECT_EQ(ownerStopRequested(), nullptr); + } + EXPECT_TRUE(insideOwed()); + EXPECT_NE(ownerStopRequested(), nullptr); + } + EXPECT_FALSE(insideOwed()); + outer_stop = false; + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::BAD_ARGUMENTS); + } + EXPECT_EQ(checkOnce(), nullptr) << "the inner owner left with its scope"; + + /// A moved-from scope restores nothing; the moved-to one restores once. + std::optional first; + first.emplace(OwnerScope::owed()); + { + OwnerScope second(std::move(*first)); + EXPECT_TRUE(insideOwed()); + } + EXPECT_FALSE(insideOwed()); + { + auto owed = OwnerScope::owed(); + first.reset(); + EXPECT_TRUE(insideOwed()) << "destroying a moved-from scope must not restore"; + } + }); +} + +TEST(CASOwnerScope, EffectiveCheckIsEmptyInsideOwedAndShared) +{ + onThread(false, [&] + { + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + { + auto owed = OwnerScope::owed(); + EXPECT_FALSE(OwnerScope::effectiveCheck()); + } + { + auto shared = OwnerScope::shared(); + EXPECT_FALSE(OwnerScope::effectiveCheck()); + } + auto check = OwnerScope::effectiveCheck(); + ASSERT_TRUE(check); + EXPECT_THROW(check(), Exception); + }); +} + +/// The captured check carries the background owner to another thread and leaves the query behind: a shared +/// flush run for a killed leader proceeds as the leader's own requests would on plain S3. +TEST(CASOwnerScope, EffectiveCheckCapturesOnlyTheBackgroundOwner) +{ + onThread(true, [&] + { + std::atomic stop{false}; + auto background = backgroundStoppedBy(stop); + auto check = OwnerScope::effectiveCheck(); + ASSERT_TRUE(check); + + std::exception_ptr seen; + std::thread other([&] + { + stop = true; + try + { + check(); + } + catch (...) + { + seen = std::current_exception(); + } + }); + other.join(); + EXPECT_EQ(codeOf(seen), ErrorCodes::ABORTED); + }); + + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + query.kill(); + EXPECT_FALSE(OwnerScope::effectiveCheck()) << "a killed query is not a background owner"; + }); +} + +/// Each check consults its own owner only; `owed` and `shared` silence both. +TEST(CASOwnerScope, BackgroundAndQueryChecksAreSeparate) +{ + const auto thrownBy = [](void (*check)()) -> int + { + try + { + check(); + } + catch (...) + { + return codeOf(std::current_exception()); + } + return 0; + }; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + std::atomic stop{true}; + { + auto background = backgroundStoppedBy(stop); + EXPECT_EQ(thrownBy(throwIfBackgroundStopped), ErrorCodes::ABORTED); + EXPECT_EQ(thrownBy(throwIfQueryStopped), 0) << "a live query is not stopped by a background owner"; + } + query.kill(); + EXPECT_EQ(thrownBy(throwIfQueryStopped), ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(thrownBy(throwIfBackgroundStopped), 0) << "a killed query is not a background owner"; + auto background = backgroundStoppedBy(stop); + { + auto owed = OwnerScope::owed(); + EXPECT_EQ(thrownBy(throwIfBackgroundStopped), 0); + EXPECT_EQ(thrownBy(throwIfQueryStopped), 0); + } + { + auto shared = OwnerScope::shared(); + EXPECT_EQ(thrownBy(throwIfBackgroundStopped), 0); + EXPECT_EQ(thrownBy(throwIfQueryStopped), 0); + } + }); +} + +/// A killed query's wait ends when the condition holds, as a wait on plain S3 would; only a background owner +/// ends it early. +TEST(CASOwnerScope, WaitStoppableIgnoresAKilledQuery) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + query.kill(); + std::mutex mutex; + std::condition_variable cv; + std::unique_lock lock(mutex); + int evaluations = 0; + std::thread waker = wakeOnceWaiting(mutex, cv); + EXPECT_NO_THROW(waitStoppable(cv, lock, [&] { return ++evaluations >= 2; })); + EXPECT_EQ(evaluations, 2); + EXPECT_TRUE(lock.owns_lock()); + lock.unlock(); + waker.join(); + }); +} + +TEST(CASOwnerScope, RealQueryKillIsThrown) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + EXPECT_EQ(checkOnce(), nullptr); + query.kill(); + auto verdict = checkOnce(); + EXPECT_EQ(codeOf(verdict), ErrorCodes::QUERY_WAS_CANCELLED); + + std::exception_ptr worker_verdict; + std::thread worker([&] + { + ThreadStatus worker_status; + query.attachCurrentThread(); + worker_verdict = checkOnce(); + }); + worker.join(); + EXPECT_EQ(codeOf(worker_verdict), ErrorCodes::QUERY_WAS_CANCELLED) << "an attached worker sees the kill"; + }); +} + +TEST(CASOwnerScope, RealQueryStoredCauseIsThrown) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto cause = std::make_exception_ptr(Exception(ErrorCodes::BAD_ARGUMENTS, "stored cause")); + query.kill(cause); + auto verdict = checkOnce(); + EXPECT_EQ(codeOf(verdict), ErrorCodes::BAD_ARGUMENTS); + EXPECT_EQ(verdict, cause) << "the query's own exception, not a copy"; + }); +} + +TEST(CASOwnerScope, WaitStoppableChecksBeforeReturningWhenAlreadyReady) +{ + onThread(false, [&] + { + std::mutex mutex; + std::condition_variable cv; + std::atomic stop{false}; + auto background = backgroundStoppedBy(stop); + + std::unique_lock lock(mutex); + EXPECT_NO_THROW(waitStoppable(cv, lock, [] { return true; })); + EXPECT_TRUE(lock.owns_lock()); + + stop = true; + try + { + waitStoppable(cv, lock, [] { return true; }); + ADD_FAILURE() << "a stopped owner must be reported even when the wait is already satisfied"; + } + catch (...) + { + EXPECT_EQ(codeOf(std::current_exception()), ErrorCodes::ABORTED); + } + EXPECT_TRUE(lock.owns_lock()); + }); +} + +TEST(CASOwnerScope, WaitStoppableHoldsTheLockOnThrow) +{ + std::mutex mutex; + std::condition_variable cv; + std::atomic stop{false}; + std::promise waiting; + std::promise done; + std::atomic held_on_throw{false}; + std::atomic asked_owner_while_locked{false}; + std::atomic give_up{false}; + std::atomic code{0}; + + std::thread waiter([&] + { + std::unique_lock lock(mutex); + auto background = OwnerScope::background([&] + { + if (lock.owns_lock()) + asked_owner_while_locked = true; + if (stop.load()) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); + bool announced = false; + try + { + /// Nobody ever notifies: only the slice timeout can bring the stop to the waiter. + waitStoppable(cv, lock, [&] + { + if (!announced) + { + announced = true; + waiting.set_value(); + } + return give_up.load(); + }); + } + catch (...) + { + held_on_throw = lock.owns_lock(); + code = codeOf(std::current_exception()); + } + done.set_value(); + }); + + const bool started = waiting.get_future().wait_for(WATCHDOG) == std::future_status::ready; + stop = true; + const bool returned = done.get_future().wait_for(WATCHDOG) == std::future_status::ready; + if (!returned) + { + /// Release a waiter that ignores the stop, so the test fails instead of hanging. + { + std::lock_guard lock(mutex); + give_up = true; + } + cv.notify_all(); + } + waiter.join(); + ASSERT_TRUE(started) << "the waiter never evaluated its condition"; + ASSERT_TRUE(returned) << "a stopped waiter did not leave within the watchdog"; + EXPECT_EQ(code.load(), ErrorCodes::ABORTED); + EXPECT_TRUE(held_on_throw.load()); + EXPECT_FALSE(asked_owner_while_locked.load()) << "the owner is asked with the lock released"; +} + +TEST(CASOwnerScope, WaitStoppableSatisfyingWakeRaceStillChecks) +{ + std::mutex mutex; + std::condition_variable cv; + bool ready = false; + std::atomic stop{false}; + std::promise waiting; + std::promise done; + std::atomic code{0}; + + std::thread waiter([&] + { + auto background = backgroundStoppedBy(stop); + std::unique_lock lock(mutex); + bool announced = false; + try + { + waitStoppable(cv, lock, [&] + { + if (!announced) + { + announced = true; + waiting.set_value(); + } + return ready; + }); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + done.set_value(); + }); + + const bool started = waiting.get_future().wait_for(WATCHDOG) == std::future_status::ready; + { + /// The waiter holds the mutex from its first `ready` until it waits, so this wake meets a waiter. + std::lock_guard lock(mutex); + ready = true; + stop = true; + } + cv.notify_all(); + const bool returned = done.get_future().wait_for(WATCHDOG) == std::future_status::ready; + waiter.join(); + ASSERT_TRUE(started) << "the waiter never evaluated its condition"; + ASSERT_TRUE(returned) << "a woken waiter did not leave within the watchdog"; + EXPECT_EQ(code.load(), ErrorCodes::ABORTED) << "the wake that satisfied the wait must not hide the stop"; +} + +TEST(CASOwnerScope, WaitStoppableInsideOwedDoesNotThrow) +{ + onThread(false, [&] + { + std::mutex mutex; + std::condition_variable cv; + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + auto owed = OwnerScope::owed(); + std::unique_lock lock(mutex); + int evaluations = 0; + std::thread waker = wakeOnceWaiting(mutex, cv); + EXPECT_NO_THROW(waitStoppable(cv, lock, [&] { return ++evaluations >= 2; })) << "owed work finishes its wait"; + EXPECT_EQ(evaluations, 2); + EXPECT_TRUE(lock.owns_lock()); + lock.unlock(); + waker.join(); + }); +} + +/// With no background owner to ask, nothing but a notification can end the wait, so it does not wake on a timer. +TEST(CASOwnerScope, WaitStoppableWithNoOwnerToAskWaitsForANotification) +{ + enum class Scope : uint8_t { None, OwedOverBackground, SharedOverBackground }; + for (const Scope scope : {Scope::None, Scope::OwedOverBackground, Scope::SharedOverBackground}) + { + SCOPED_TRACE(static_cast(scope)); + onThread(false, [&] + { + std::atomic stop{false}; + std::optional background; + std::optional inner; + if (scope != Scope::None) + { + background.emplace(backgroundStoppedBy(stop)); + inner.emplace(scope == Scope::OwedOverBackground ? OwnerScope::owed() : OwnerScope::shared()); + } + std::mutex mutex; + std::condition_variable cv; + bool ready = false; + int evaluations = 0; + std::unique_lock lock(mutex); + /// Three owner-stop slices: a waiter that polls evaluates `ready` at least once per slice. + std::thread notifier([&] + { + std::this_thread::sleep_for(3 * kOwnerStopSlice); + { + std::lock_guard notifier_lock(mutex); + ready = true; + } + cv.notify_all(); + }); + waitStoppable(cv, lock, [&] + { + ++evaluations; + return ready; + }); + EXPECT_TRUE(ready) << "the wait returned before the notification"; + lock.unlock(); + notifier.join(); + EXPECT_LE(evaluations, 2) << "the wait woke on a timer"; + inner.reset(); + }); + } +} + +TEST(CASOwnerScope, ClientLikeBackendThrowsTheKillOnlyOnAnUnsuccessfulAnswer) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(std::make_shared()); + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("present", "v", Retry::once()))); + EXPECT_FALSE(op.read("absent", Retry::once()).has_value()); + + query.kill(); + EXPECT_TRUE(op.read("present", Retry::once()).has_value()) << "a successful answer is not checked"; + try + { + op.read("absent", Retry::once()); + ADD_FAILURE() << "a miss of a killed query must surface the kill"; + } + catch (...) + { + EXPECT_EQ(codeOf(std::current_exception()), ErrorCodes::QUERY_WAS_CANCELLED); + } + }); +} + +TEST(CASOwnerScope, OwedInsideSharedStaysShared) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + query.kill(); + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + auto shared = OwnerScope::shared(); + auto owed = OwnerScope::owed(); + EXPECT_TRUE(insideOwed()); + EXPECT_EQ(ownerStopRequested(), nullptr) << "owed work inside shared work still has no owner"; + EXPECT_FALSE(OwnerScope::effectiveCheck()); + }); +} + +TEST(CASOwnerScope, ScopesStayOnTheirThread) +{ + std::promise scope_open; + std::promise peer_checked; + std::thread holder([&] + { + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + auto owed = OwnerScope::owed(); + scope_open.set_value(); + peer_checked.get_future().wait_for(WATCHDOG); + }); + + const bool opened = scope_open.get_future().wait_for(WATCHDOG) == std::future_status::ready; + onThread(false, [&] + { + EXPECT_EQ(ownerStopRequested(), nullptr) << "another thread's background owner is not this thread's"; + EXPECT_FALSE(insideOwed()) << "another thread's owed scope is not this thread's"; + EXPECT_EQ(checkOnce(), nullptr); + }); + peer_checked.set_value(); + holder.join(); + ASSERT_TRUE(opened) << "the holder never opened its scope"; +} + From c0c7e9b8cc937eb778aea688e90eeb2278627a3b Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:27:57 +0100 Subject: [PATCH 06/47] Stop CAS requests at their owner's request, keeping the error A query's stop is consulted only after a failed attempt: it vetoes the retry, and the call ends with that attempt's error. A write attempt is classified first, then the loop picks its next step; a sent write that stays unresolved ends as `NETWORK_ERROR` (210). Local faults surface unchanged, and a stopped owner's exception is no store answer in the backend or the sentinel probe. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressed/Backend/CasBackend.h | 11 +- .../Backend/CasObjectStorageBackend.cpp | 15 + .../ContentAddressed/Backend/CasRequests.cpp | 613 ++-- .../ContentAddressed/Backend/CasRequests.h | 99 +- .../ContentAddressed/Backend/CasRetry.h | 2 +- .../ContentAddressed/Backend/CasWriteResult.h | 4 +- .../Parts/PartFolderAccess.cpp | 10 + .../ContentAddressed/Pool/CasPartWriteTxn.cpp | 16 + .../ContentAddressed/Pool/CasPool.cpp | 2 +- .../ContentAddressed/Pool/CasRefCatalog.cpp | 6 +- .../ContentAddressed/Pool/CasRefLedger.cpp | 2 +- .../ContentAddressed/Pool/CasServerRoot.cpp | 4 +- src/Disks/tests/gtest_cas_owner_stop.cpp | 3139 +++++++++++++++++ src/Disks/tests/gtest_cas_sentinel_probe.cpp | 373 +- 14 files changed, 4009 insertions(+), 287 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasBackend.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasBackend.h index 951efdab36567..4da87153c7009 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasBackend.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasBackend.h @@ -37,6 +37,10 @@ extern const int CORRUPTED_DATA; namespace DB::Cas { +/// Neither a store or transport answer nor a stopped query's stored cause: a bug or a resource report, which +/// request loops and backend adapters surface unchanged. +bool isLocalFault(const std::exception_ptr & e); + /// Typed erasure evidence for one key or one prefix. Ordinary `head`/`read` answer only two things /// for a plain caller: the object, or nullopt for the store's own authoritative "key not found" (see /// `isObjectNotFound`) -- every other fault (a missing bucket/container, a permission failure, a @@ -297,8 +301,9 @@ class Backend /// Authoritative, cache-bypassing probe of one key -- see `ProbeOutcome`. DEFAULT (used by every /// backend without sharper raw-error evidence, e.g. `InMemoryBackend`): derived from `head`/`read` - /// alone, so it can only distinguish `Present` from `KeyAbsent`, and ANY exception from either - /// call is `Indeterminate` -- never promoted to `KeyAbsent`. A backend able to surface real + /// alone, so it can only distinguish `Present` from `KeyAbsent`, and any other answer from either + /// call is `Indeterminate` -- never promoted to `KeyAbsent`. A local fault propagates (`isLocalFault`), in + /// every override too. A backend able to surface real /// container/permission evidence (the S3-native and Local paths of `ObjectStorageBackend`) /// overrides this to sharpen the classification. virtual SentinelProbeResult probeSentinelRaw(const String & key, TransportAccess & access) @@ -316,6 +321,8 @@ class Backend } catch (...) { + if (isLocalFault(std::current_exception())) + throw; return {ProbeOutcome::Indeterminate, std::nullopt}; } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp index f0cbdf2e4dc90..ad32d87eeda5c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -264,6 +265,9 @@ detail::ConditionalWriteOutcome detail::finalizeConditionalWrite(WriteBuffer & b } catch (const S3Exception & e) { + /// A stopped query's stored cause can be a `412` and says nothing about the write; any other `412` is the store's. + if (isQueryStoredCause(std::current_exception())) + throw; if (e.isPreconditionFailed() || e.getExceptionName() == "NoSuchKey" || e.getS3ErrorCode() == Aws::S3::S3Errors::NO_SUCH_KEY) @@ -355,6 +359,10 @@ std::expected ObjectStorageBackend::nativeConditio /// Any other error (network, auth, throttle, corruption) propagates unchanged — fail-closed. static bool isObjectNotFound(const std::exception & e) { + /// A stopped query's stored cause can carry a not-found code and says nothing about the key. Any other miss + /// is the store's answer: the S3 client replaces a miss it sees under a killed query with the query's exception. + if (isQueryStoredCause(std::current_exception())) + return false; #if USE_AWS_S3 if (const auto * s3e = dynamic_cast(&e)) return s3e->getS3ErrorCode() == Aws::S3::S3Errors::NO_SUCH_KEY @@ -765,6 +773,9 @@ SentinelProbeResult ObjectStorageBackend::probeSentinelUnder(const String & key, #if USE_AWS_S3 catch (const S3Exception & e) { + /// A stopped query's stored cause says nothing about the key; any other error is the store's answer. + if (isQueryStoredCause(std::current_exception())) + return {ProbeOutcome::Indeterminate, std::nullopt}; /// `read` already answers the key-absent half of the store's 404 family (see /// `isObjectNotFound`), so what reaches here is what it deliberately does not flatten. /// The limit of the one-read shape: every case below classifies an error a GET raised, so @@ -784,6 +795,8 @@ SentinelProbeResult ObjectStorageBackend::probeSentinelUnder(const String & key, #endif catch (...) { + if (isLocalFault(std::current_exception())) + throw; return {ProbeOutcome::Indeterminate, std::nullopt}; } } @@ -803,6 +816,8 @@ SentinelProbeResult ObjectStorageBackend::probeSentinelUnder(const String & key, } catch (...) { + if (isLocalFault(std::current_exception())) + throw; return {ProbeOutcome::Indeterminate, std::nullopt}; } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp index a9d6d884369a7..caeec9ef6f15f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -112,11 +113,15 @@ void logCasWriteRetryLater(const String & why) throw Exception(ErrorCodes::NETWORK_ERROR, "CAS request did not complete ({}); retrying later", why); } -std::exception_ptr makeCasWriteRetryLaterExceptionPtr(const String & why) +Exception makeCasWriteRetryLaterException(const String & why) { logCasWriteRetryLater(why); - return std::make_exception_ptr( - Exception(ErrorCodes::NETWORK_ERROR, "CAS write could not be committed ({}); retrying later", why)); + return Exception(ErrorCodes::NETWORK_ERROR, "CAS write could not be committed ({}); retrying later", why); +} + +std::exception_ptr makeCasWriteRetryLaterExceptionPtr(const String & why) +{ + return std::make_exception_ptr(makeCasWriteRetryLaterException(why)); } [[noreturn]] void throwCasTransientUnavailable(const String & subject, const String & condition) @@ -322,6 +327,24 @@ bool isStoreAnswer(const std::exception & e) return dynamic_cast(&e) && !(db && isDeterministicLocalFailure(db->code())); } +bool isLocalFault(const std::exception_ptr & e) +{ + if (isQueryStoredCause(e)) + return false; + try + { + std::rethrow_exception(e); + } + catch (const std::exception & ex) + { + return !isStoreAnswer(ex); + } + catch (...) + { + return true; + } +} + String describeRequestFailure(std::string_view verb, const String & key, const std::exception & e) { const auto & poco = dynamic_cast(e); @@ -337,6 +360,12 @@ String describeRequestFailure(std::string_view verb, const String & key, const s return fmt::format("{} {}: {} {} {}", verb, key, isDefinitelyRefusedWrite(e) ? "refused" : "transport", code, poco.message()); } +void detail::throwVetoedCredentialRetry(std::string_view verb, const String & subject, const std::exception & e) +{ + throwCasRequestRetryLater(fmt::format("the query stopped before the credential retry; {}", + describeRequestFailure(verb, subject, e))); +} + CasRequests::CasRequests(BackendPtr backend_, Fence fence_, std::function now_ms_, std::function sleep_ms_, CasHotKeys * hot_keys_, uint64_t default_window_ms_) @@ -483,8 +512,8 @@ CasOperation::Gate CasOperation::gate(uint64_t needed_ms) const case Fence::Admit::NoBudget: return Gate::NoBudget; case Fence::Admit::Ok: break; } - /// The caller's own facts are the second half of admission, and the engine does not need to know - /// which of the two refused: a stopping task and a lost lease end the operation the same way. + /// The caller's authority facts and pool teardown are the second half of admission, and the engine + /// does not need to know which of the two refused. A query's or a background owner's stop never feeds it. if (liveness && !liveness()) return Gate::FenceLost; return Gate::Ok; @@ -508,7 +537,7 @@ bool CasOperation::oneAttemptFitsBefore(uint64_t deadline_ms) const return fits(reservedFor(0, 1), Retry::Bound{.deadline_ms = deadline_ms, .source = Retry::Bound::Source::OutsideCap}); } -std::optional CasOperation::pauseBeforeRedecide(uint64_t ms, const GaveUp & unresolved, const Retry & policy) +std::optional CasOperation::pauseAfterUnresolvedWrite(uint64_t ms, const GaveUp & unresolved, const Retry & policy) { WriteState state; state.attempts_sent = unresolved.attempts_sent; @@ -584,12 +613,9 @@ bool CasOperation::fits(uint64_t needed_ms, const Retry::Bound & bound) const bool CasOperation::refreshAndClassifyReadFault(const std::exception & e, bool & refresh_attempted, bool & refreshed) { - if (const auto * db_e = dynamic_cast(&e); db_e && isDeterministicLocalFailure(db_e->code())) - return true; /// A local failure -- a bad allocation, a logic error raised inside the attempt -- is not a - /// transport fault, and reissuing it would spend the whole deadline replaying the same bug. Every - /// exception the transport raises is a `Poco::Exception`, `DB::Exception` included. - if (!dynamic_cast(&e)) + /// transport fault, and reissuing it would spend the whole deadline replaying the same bug. + if (!isStoreAnswer(e)) return true; /// A credential failure gets ONE refresh per call -- the storage hands back a fresh client every /// time it is asked, so refreshing per attempt would reissue a permanent denial to the deadline. @@ -733,7 +759,7 @@ void CasOperation::removeManyWriteOnce(const std::vector & keys, c keys.size(), kBulkDeleteMaxKeys); if (keys.empty()) return; - const Retry::Bound bound = owner.bindPolicy(policy); + throwIfBackgroundStopped(); const String subject = fmt::format("{} (+{} keys)", keys.front().str(), keys.size() - 1); readLoop("removeManyWriteOnce", subject, policy, [&](auto & access) { @@ -801,6 +827,9 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry std::optional last_probe; for (uint32_t attempt = 1;; ++attempt) { + /// Not before the first probe: a healthy probe is never refused. + if (attempt > 1) + throwIfBackgroundStopped(); const uint64_t reservation = reservedFor(0, 1); switch (gate(reservation)) { @@ -819,6 +848,7 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry detail::recordAttempt(); SentinelProbeResult result{ProbeOutcome::Indeterminate, std::nullopt}; + std::exception_ptr cause; try { result = owner.withTransportAccess(attempt, [&](auto & access) @@ -828,6 +858,12 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry } catch (const std::exception & e) { + /// A local fault surfaces unchanged, as in the write loop; a query's stored cause can carry any code. + if (!isStoreAnswer(e) && !isQueryStoredCause(std::current_exception())) + throw; + /// A stopped owner's failure is no store answer: neither reissued nor a credential refresh. A stopped + /// query keeps the failure. + rethrowIfStoppedOwnersFailure(); /// The probe never counts a fuse, so whether this fault was a credential reissue is not /// interesting here -- only the write and read loops guard a counter with it. bool refreshed = false; @@ -835,6 +871,22 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry throw; /// The probe reports every transport failure as `Indeterminate` rather than by throwing, so /// a decorator that does throw is folded onto the same inconclusive outcome. + cause = std::current_exception(); + } + + /// The native and default backends fold a stopped owner's exception into `Indeterminate`, so the + /// background verdict is recovered here. A stopped query gets the inconclusive outcome itself, or its cause, + /// and no reissue. An authoritative outcome stays a store answer. + if (result.outcome == ProbeOutcome::Indeterminate) + { + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(stop); + if (queryStopRequested()) + { + if (cause) + std::rethrow_exception(cause); + return result; + } } /// The reissue is driven by the OUTCOME: this is the one primitive whose failures never reach a @@ -859,7 +911,12 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry return result; last_probe = std::move(result); detail::recordReissue(); - sleep(pause_ms); + if (!sleepUnlessQueryStops(pause_ms, [this](uint64_t slice_ms) { sleep(slice_ms); })) + { + if (cause) + std::rethrow_exception(cause); + return *last_probe; + } } } @@ -885,60 +942,47 @@ void CasOperation::publish(const BlobPublishRequest & request, const Retry & pol }); } -CasOperation::Resolved CasOperation::observe(const String & key, const Retry & policy, const Retry::Bound & bound) +CasOperation::Resolved CasOperation::observe(const String & key, const Retry & policy, ResolveWith what) { last_read_stop.reset(); try { - auto got = readUnder(key, policy, bound); - if (!got) - return {ProvenAbsent{}, std::nullopt}; - return {std::move(*got), std::nullopt}; - } - catch (const Exception & e) - { - /// A local bug replays identically on every reissue, so it is never swallowed into "nothing - /// observed". Anything else settled nothing -- and `last_read_stop` says whether a bound - /// refused the read or the transport itself failed, which the exception cannot. - if (isDeterministicLocalFailure(e.code())) - throw; - return {NotObserved{}, last_read_stop}; + if (what == ResolveWith::Presence) + { + if (auto meta = headUnder(key, policy)) + return {std::move(*meta), std::nullopt}; + } + else if (auto object = readUnder(key, policy)) + return {std::move(*object), std::nullopt}; + return {ProvenAbsent{}, std::nullopt}; } catch (const std::exception & e) { - /// A failure that is not the transport's is not an observation: it is the same local bug the - /// read loop refuses to reissue, and swallowing it here would hide it just as thoroughly. - if (!dynamic_cast(&e)) - throw; - return {NotObserved{}, last_read_stop}; - } -} - -CasOperation::Resolved CasOperation::observePresence(const String & key, const Retry & policy, const Retry::Bound & bound) -{ - last_read_stop.reset(); - try - { - auto got = headUnder(key, policy, bound); - if (!got) - return {ProvenAbsent{}, std::nullopt}; - return {std::move(*got), std::nullopt}; - } - catch (const Exception & e) - { - if (isDeterministicLocalFailure(e.code())) + /// A local bug replays identically on every reissue, so it is never swallowed into "nothing + /// observed". A stopped owner's failure is not a store answer: it is reported only when a bound + /// refused the read or the read is owed. `last_read_stop` says which bound refused it. + bool observed_stop = false; + if (!isStoreAnswer(e) && !isQueryStoredCause(std::current_exception())) throw; - return {NotObserved{}, last_read_stop}; - } - catch (const std::exception & e) - { - if (!dynamic_cast(&e)) + if (auto stop = backgroundStopRequested()) + { + /// The verdict, not `e`: the stop can land after the read's own check classified `e`. + if (!last_read_stop && !insideOwed()) + std::rethrow_exception(stop); + } + else if (queryStopRequested()) + { + observed_stop = true; + if (!last_read_stop && !insideOwed()) + throw; + } + else if (!isStoreAnswer(e)) throw; - return {NotObserved{}, last_read_stop}; + return {NotObserved{}, last_read_stop, last_read_source, observed_stop}; } } -WriteResult CasOperation::gaveUp(GaveUp::Why why, GaveUp::Source source, WriteState & state) const +GaveUp CasOperation::gaveUp(GaveUp::Why why, GaveUp::Source source, WriteState & state) const { ProfileEvents::increment(ProfileEvents::CASRequestGaveUp); return GaveUp{why, source, state.sent_any, state.last_seen, state.attempts_sent}; @@ -1019,7 +1063,7 @@ WriteResult CasOperation::postCommit(Etag inc, bool resolved_by_read, WriteState return Committed{std::move(inc), state.attempts_sent, resolved_by_read}; } -std::optional CasOperation::gatedPause(uint64_t pause_ms, uint32_t envelopes, WriteState & state, +CasOperation::PauseOutcome CasOperation::gatedPause(uint64_t pause_ms, uint32_t envelopes, WriteState & state, const Retry::Bound & bound, void (*record)(), bool should_sleep) { const uint64_t needed = reservedFor(pause_ms, envelopes); @@ -1034,12 +1078,15 @@ std::optional CasOperation::gatedPause(uint64_t pause_ms, uint32_t record(); /// `should_sleep` is false ONLY for the fuse's zero-pause reissue: that pause is not "zero /// milliseconds", it is NO PAUSE AT ALL, so it must not call `sleep_ms` even with a zero argument. - /// The three ordinary callers always sleep, even when a drawn jitter happens to be exactly zero -- - /// `Retry::backoff`'s full jitter includes zero -- so their call to `sleep_ms(0)` is kept - /// unconditional here to leave their observable behaviour exactly as it was before this collapse. - if (should_sleep) - sleep(pause_ms); - return std::nullopt; + /// The two ordinary callers always sleep, even when a drawn jitter happens to be exactly zero -- + /// `Retry::backoff`'s full jitter includes zero. + const bool query_stopped = should_sleep + ? !sleepUnlessQueryStops(pause_ms, [this](uint64_t slice_ms) { sleep(slice_ms); }) + : !insideOwed() && queryStopRequested(); + if (!query_stopped) + return ResumeAfterPause{}; + state.observed_stop = true; + return QueryVetoedResend{}; } uint64_t CasOperation::reissuePause(const WriteState & state, uint64_t unspaced_ms) const @@ -1049,31 +1096,165 @@ uint64_t CasOperation::reissuePause(const WriteState & state, uint64_t unspaced_ return Retry::pauseAfterAttempt(state.spacing->spacing_ms, state.spacing->attempt_started_ms, owner.now_ms()); } -std::optional CasOperation::pauseAndReissue(WriteState & state, const Retry::Bound & bound) +CasOperation::PauseOutcome CasOperation::pauseAndReissue(WriteState & state, const Retry::Bound & bound) { const uint64_t pause_ms = reissuePause(state, Retry::backoff(++state.reissues)); return gatedPause(pause_ms, 2, state, bound, detail::recordReissue, /*should_sleep=*/true); } -std::optional CasOperation::pauseForConflict(WriteState & state, const Retry::Bound & bound) -{ - return gatedPause(reissuePause(state, Retry::conflictBackoff()), 2, state, bound, detail::recordConflictPause, - /*should_sleep=*/true); -} - /// A flat pause before reissuing an attempt whose failure text named a failed connection. static constexpr uint64_t kConnectHintPauseMs = 50; -std::optional CasOperation::pauseFlat(WriteState & state, const Retry::Bound & bound) +CasOperation::PauseOutcome CasOperation::pauseFlat(WriteState & state, const Retry::Bound & bound) { return gatedPause(reissuePause(state, kConnectHintPauseMs), 2, state, bound, detail::recordReissue, /*should_sleep=*/true); } -std::optional CasOperation::reissueAtOnce(WriteState & state, const Retry::Bound & bound) +CasOperation::PauseOutcome CasOperation::reissueAtOnce(WriteState & state, const Retry::Bound & bound) { return gatedPause(0, 2, state, bound, detail::recordReissue, /*should_sleep=*/false); } +CasOperation::Resolved CasOperation::settlingRead(const String & key, const Retry & policy, const WriteState & state, + ResolveWith resolve_refusal_with) +{ + ProfileEvents::increment(ProfileEvents::CASRequestResolveRead); + /// Owed to the write: a stopped owner must not lose the proof of what its attempt did. + const auto owed = OwnerScope::owed(); + return observe(key, policy, state.any_ambiguous ? ResolveWith::Body : resolve_refusal_with); +} + +std::optional CasOperation::adjudicate(const Resolved & resolved, const String & bytes, + const std::optional & expected, WriteState & state, + const Retry::Bound & write_bound) +{ + state.last_seen = resolved.seen; + state.observed_stop = state.observed_stop || resolved.observed_stop; + /// A bound of the resolve read refused it, so say WHICH. Erasing it here is what let a lost + /// fence be reported as an ordinary conflict and a lease refusal as a policy deadline. + if (resolved.stop) + return gaveUpForReadStop(*resolved.stop, resolved.source, state); + + /// No attempt of this inner write is unresolved, so the refused precondition IS the answer. + /// Identical bytes here are somebody else's object, and the caller that owns the key's meaning + /// decides what that means. + if (!state.any_ambiguous) + return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous, state.observed_stop}; + + if (!preconditionStillSatisfiable(state.last_seen, expected)) + { + /// The precondition has MOVED, and THAT is what makes byte equality a proof: an attempt + /// that never applied leaves the key exactly as it found it, so under an incarnation that + /// did not move our own bytes cannot be told from the bytes already there. A create reaches + /// here for every object it sees -- an occupied key never satisfies its precondition. + if (const auto * obj = std::get_if(&state.last_seen); obj && obj->bytes == bytes) + return postCommit(obj->etag, /*resolved_by_read=*/true, state, write_bound); + /// Nothing of this inner write's is at the key, and a reissue would be refused too. + return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous, state.observed_stop}; + } + return std::nullopt; +} + +namespace +{ + +/// What one conditional write attempt proved, from its reply alone. +enum class AttemptKind : uint8_t +{ + Committed, + /// The precondition was refused: this attempt wrote nothing. + Conflict, + /// Refused before anything was written, the same way on every resend. + Refused, + /// Refused before anything was written; fresh credentials may let a resend through. + CredentialRefused, + /// No proof either way: the attempt may have landed. + Ambiguous, + /// The query's stored verdict replaced the store's answer, which may have landed. + QueryStoredCause, + /// Not a store answer: surfaced unchanged. + LocalFault, +}; + +struct WriteAttempt +{ + explicit WriteAttempt(AttemptKind kind_) : kind(kind_) {} + + AttemptKind kind; + /// For `Committed`. + std::optional landed; + /// For every thrown kind. + std::exception_ptr error; + /// For `Refused` and `CredentialRefused`. + int refusal_code = 0; + String refusal_message; + /// An owner had asked to stop when the attempt failed. + bool failed_after_stop = false; + /// For a thrown store answer: the text named a failed connection. + bool connect_hint = false; + /// For `Ambiguous`: the first attempt met the adaptive timeout. + bool fuse = false; +}; + +/// Only the transport can have landed anything, and every exception it raises is a `Poco::Exception`; a local fault +/// settled by a read would bury the bug behind an outcome the store never gave. +WriteAttempt classifyWriteFailure(const std::exception & e, size_t attempt_no) +{ + WriteAttempt attempt(AttemptKind::Ambiguous); + attempt.error = std::current_exception(); + attempt.failed_after_stop = ownerStopRequested() != nullptr; + if (isQueryStoredCause(attempt.error)) + attempt.kind = AttemptKind::QueryStoredCause; + else if (!isStoreAnswer(e)) + attempt.kind = AttemptKind::LocalFault; + else + { + attempt.connect_hint = isConnectFailureHint(e); + if (isDefinitelyRefusedWrite(e)) + { + attempt.kind = isRefreshableCredentialError(e) ? AttemptKind::CredentialRefused : AttemptKind::Refused; + const auto & refusal = dynamic_cast(e); + attempt.refusal_code = refusal.code(); + attempt.refusal_message = refusal.message(); + } + else + { + /// False when the text is also a hint: such an attempt stays a hint. + attempt.fuse = isFirstAttemptFuseTimeout(e, attempt_no); + } + } + return attempt; +} + +/// `on_failure` takes the exception object, which only a rethrow recovers from an `exception_ptr`. +void reportWriteFailure(const RequestObserver & observer, const String & key, const std::exception_ptr & error) +{ + if (!observer.on_failure) + return; + try + { + std::rethrow_exception(error); + } + catch (const std::exception & e) + { + observer.on_failure("PUT", key, e); + } +} + +[[noreturn]] void throwVetoedCredentialRetryOfWrite(const String & key, const std::exception_ptr & refusal) +{ + try + { + std::rethrow_exception(refusal); + } + catch (const std::exception & e) + { + detail::throwVetoedCredentialRetry("PUT", key, e); + } +} + +} + WriteResult CasOperation::writeLoop(const String & key, const String & bytes, const std::optional & expected, const Retry & policy, WriteState & state, ResolveWith resolve_refusal_with) { @@ -1086,11 +1267,54 @@ WriteResult CasOperation::writeLoop(const String & key, const String & bytes, co /// write of the same call sent DIFFERENT bytes and ended in a conflict, which proved its attempts /// dead -- carrying its ambiguity forward is how a competitor's identical object gets claimed. state.any_ambiguous = false; + /// False while an ambiguous attempt awaits its settling read: a connect hint resends before reading. + bool latest_attempt_settled = true; + /// A stopped owner gets its latest attempt settled instead of a reissue. + const auto settle_for_stopped_owner = [&]() -> WriteResult + { + if (!latest_attempt_settled) + if (auto settled = adjudicate(settlingRead(key, policy, state, ResolveWith::Body), bytes, expected, state, bound)) + return *settled; + return gaveUp(GaveUp::Why::Unresolved, sourceFor(bound), state); + }; + + const auto send_attempt = [&]() -> WriteAttempt + { + std::optional> reply; + try + { + reply = owner.withTransportAccess(state.attempts_sent + policy.attempts_already_sent, [&](auto & access) + { + return owner.backend->write(key, bytes, expected_value, access); + }); + } + catch (const std::exception & e) + { + return classifyWriteFailure(e, state.attempts_sent + policy.attempts_already_sent); + } + if (!reply->has_value()) + return WriteAttempt(AttemptKind::Conflict); + /// A 2xx carrying a value no grammar accepts may well have landed: an ambiguity, never a corruption verdict. + std::optional landed = owner.tryMint(key, std::move(**reply)); + WriteAttempt attempt(landed ? AttemptKind::Committed : AttemptKind::Ambiguous); + attempt.landed = std::move(landed); + return attempt; + }; for (;;) { - /// A write reserves TWO envelopes: the attempt, and the exact read that settles it. That is - /// what keeps "every conflict is settled by one read" true at the deadline edge. + /// A query that stopped during a failure pause gets the latest attempt settled instead of a reissue. + if (state.observed_stop) + return settle_for_stopped_owner(); + /// Once an attempt may have landed, a stopped background owner gets that attempt settled instead of its + /// verdict. A stopped query is consulted only on the failure path below, which records what it saw. + if (!state.any_ambiguous) + throwIfBackgroundStopped(); + else if (!insideOwed() && backgroundStopRequested()) + return settle_for_stopped_owner(); + + /// An attempt starts only with room for TWO envelopes: itself and the read that settles it. This + /// bounds when the attempt starts, not when it lands or whether its settling read completes. const uint64_t reservation = reservedFor(0, 2); switch (gate(reservation)) { @@ -1109,181 +1333,100 @@ WriteResult CasOperation::writeLoop(const String & key, const String & bytes, co if (observer.on_write_attempt) observer.on_write_attempt(state.attempts_sent); - /// Disengaged means the attempt threw: its fate is unproven, and nothing may be read out of it. - std::optional> outcome; - /// A credential answer is given BEFORE the store applies anything, so the attempt provably did - /// not land. It is the one failure that is neither a commit nor an ambiguity, and keeping it out - /// of `any_ambiguous` is what lets a second credential failure of this inner write be refused - /// instead of resolved by a read and reissued to the deadline. - bool credential_answer = false; - bool refreshed = false; - /// Set once `refreshed` is known: true only when the credential-owned reissue below (the one - /// guarded by this exact expression) is what will actually resend this attempt. An earlier - /// ambiguity of this inner write routes the reissue through the ordinary hint/fuse/backoff - /// mechanisms instead -- the credential answer never gets to skip their read or their pacing -- - /// so a hint or fuse counter must still count in that case even though credentials were refreshed. - bool refresh_owns_reissue = false; - bool connect_hint = false; - bool fuse = false; - try + /// "This attempt did not land" says nothing about an earlier attempt of this write whose reply was lost. + const bool earlier_attempt_unanswered = state.any_ambiguous; + WriteAttempt attempt = send_attempt(); + const bool refused = attempt.kind == AttemptKind::Refused || attempt.kind == AttemptKind::CredentialRefused; + + if (attempt.kind == AttemptKind::LocalFault) + std::rethrow_exception(attempt.error); + if (attempt.kind == AttemptKind::Committed) + return postCommit(std::move(*attempt.landed), /*resolved_by_read=*/false, state, bound); + + /// Nothing is resent after the owner stopped: a failure that may have landed, or a refusal that cannot answer + /// for an earlier unanswered attempt, is settled and ends the call. A refusal with nothing unanswered is kept. + if (attempt.failed_after_stop && !(refused && !earlier_attempt_unanswered)) { - outcome = owner.withTransportAccess(state.attempts_sent + policy.attempts_already_sent, [&](auto & access) - { - return owner.backend->write(key, bytes, expected_value, access); - }); + state.any_ambiguous = true; + latest_attempt_settled = false; + state.observed_stop = state.observed_stop || queryStopRequested(); + return settle_for_stopped_owner(); } - catch (const Exception & e) + + if (attempt.error) + reportWriteFailure(observer, key, attempt.error); + bool refreshed = false; + if (refused) { - if (isDeterministicLocalFailure(e.code())) - throw; - if (observer.on_failure) - observer.on_failure("PUT", key, e); - /// ONE refresh per call, only for the class a credential could explain, and only when a - /// reissue could sign with what it installs. So an oversized entity never triggers a - /// re-acquisition, a denial fresh credentials do not fix is refused on the second look - /// rather than reissued to the deadline (the storage hands back a new client every time it - /// is asked), and under a single-attempt policy the refusal below is literally "no refresh - /// installed credentials and no earlier ambiguity". - credential_answer = isRefreshableCredentialError(e); - if (credential_answer && !state.refresh_attempted && !policy.single_attempt) + /// One refresh per call, and only when a resend could sign with what it installs. + if (attempt.kind == AttemptKind::CredentialRefused && !attempt.failed_after_stop && !state.refresh_attempted + && !policy.single_attempt) { state.refresh_attempted = true; refreshed = owner.backend->refreshCredentials(); } - /// Mirrors the condition guarding the credential-owned reissue below exactly, so the two - /// can never drift: `state.any_ambiguous` here is still this attempt's INCOMING value, - /// because the update below only fires when `!credential_answer`, which `refreshed` implies - /// false for. `!policy.single_attempt` is redundant today -- `refreshed` can only be set - /// above under `!policy.single_attempt` already -- but it is kept so this stays an exact - /// copy of the reissue branch's condition rather than a hand-simplified one that could - /// silently stop matching it. - refresh_owns_reissue = refreshed && !policy.single_attempt && !state.any_ambiguous; - /// A refusal that FOLLOWS an ambiguous attempt of this inner write proves nothing about that - /// attempt, so it is settled by the read below instead of ending the call here. - const bool definitely_refused = !refreshed && isDefinitelyRefusedWrite(e); - if (definitely_refused && !state.any_ambiguous) + /// With an earlier attempt unanswered the refusal proves nothing about it, so the read below settles it. + if (!earlier_attempt_unanswered) { + if (refreshed) + { + PauseOutcome paused = pauseAndReissue(state, bound); + if (auto * ended = std::get_if(&paused)) + return std::move(*ended); + /// The store refused this attempt, so a vetoed resend leaves no outcome unknown. + if (std::holds_alternative(paused)) + throwVetoedCredentialRetryOfWrite(key, attempt.error); + continue; + } ProfileEvents::increment(ProfileEvents::CASRequestRefused); - return Refused{e.code(), e.message(), state.attempts_sent}; + return Refused{attempt.refusal_code, std::move(attempt.refusal_message), state.attempts_sent}; } - /// A refusal-class exception is never a hint, even when an earlier ambiguity of this inner - /// write kept it from ending the call above: that earlier attempt's fate is what the read - /// below must settle, and a hint reissue would skip it. Both counters below are recorded - /// here, at classification, regardless of `policy.single_attempt` (`Retry::once` never acts - /// on either, but the attempt's transport error still named what it named) -- except when - /// the credential answer OWNS the reissue: a credential answer whose text happens to also - /// match a hint or fuse text is a credential reissue, not a hint or fuse one, and must not - /// inflate these counts. When an earlier ambiguity of this inner write keeps the credential - /// answer from owning the reissue, the hint/fuse mechanism reissues it instead, exactly as - /// if credentials had never been refreshed, so the counter must still count it. - connect_hint = !definitely_refused && isConnectFailureHint(e); - if (connect_hint && !refresh_owns_reissue) - ProfileEvents::increment(ProfileEvents::CASRequestConnectFailureHint); - /// Checked AFTER the hint, so a hinted attempt stays hinted (reissued before its read); a - /// fuse timeout is reissued after the settle read runs below. - fuse = isFirstAttemptFuseTimeout(e, state.attempts_sent + policy.attempts_already_sent); - if (fuse && !refresh_owns_reissue) - ProfileEvents::increment(ProfileEvents::CASRequestFirstAttemptFuse); } - catch (const std::exception & e) + else if (attempt.kind != AttemptKind::Conflict) { - /// Only the transport can have landed anything, and every exception it raises is a - /// `Poco::Exception`. A local fault -- a bad allocation, a logic error raised inside the - /// attempt -- is not a store answer, and settling it by a read would bury the bug behind an - /// outcome the store never gave. What is left is an unmodeled transport failure that may - /// still have landed, so `outcome` stays disengaged and the read below settles it. - if (!dynamic_cast(&e)) - throw; - if (observer.on_failure) - observer.on_failure("PUT", key, e); - } - - if (outcome && outcome->has_value()) - { - if (auto inc = owner.tryMint(key, std::move(**outcome))) - return postCommit(std::move(*inc), /*resolved_by_read=*/false, state, bound); - /// A 2xx carrying a value no grammar accepts: the write may well have landed, so this is an - /// ambiguity to settle by reading, never a corruption verdict about the object. - outcome.reset(); - } - if (!outcome && !credential_answer) state.any_ambiguous = true; - - /// Nothing for a read to settle: this attempt did not apply, and no EARLIER attempt of this - /// inner write is unresolved either. Re-send it under the credentials the refresh installed. - if (refresh_owns_reissue) - { - if (auto given_up = pauseAndReissue(state, bound)) - return *given_up; - continue; + latest_attempt_settled = false; } - /// The failure text named a failed CONNECTION -- counted above, at classification, whether or - /// not this policy or the deadline/fence gates below let the reissue actually happen. A read now - /// would meet the same broken condition, so the reissue itself is the cheaper probe: the attempt - /// stays ambiguous (`any_ambiguous` is set above), and if the reissue meets a refused precondition - /// the read below settles it. + /// A refusal that fresh credentials may cure is resent like an ambiguity. Counted whether or not the policy + /// or the gates let the resend happen. + const bool connect_hint = attempt.connect_hint && (attempt.kind == AttemptKind::Ambiguous || refreshed); + if (connect_hint) + ProfileEvents::increment(ProfileEvents::CASRequestConnectFailureHint); + if (attempt.fuse) + ProfileEvents::increment(ProfileEvents::CASRequestFirstAttemptFuse); + /// A read now would meet the same broken connection, so the resend is the cheaper probe; a refused + /// precondition it meets is settled by the read below. if (connect_hint && !policy.single_attempt && policy.resend_unresolved) { - if (auto given_up = pauseFlat(state, bound)) - return *given_up; + PauseOutcome paused = pauseFlat(state, bound); + if (auto * ended = std::get_if(&paused)) + return std::move(*ended); + if (std::holds_alternative(paused)) + return settle_for_stopped_owner(); continue; } - /// Every refused precondition, and every ambiguous attempt that was not reissued on a - /// connect-failure hint, is settled by ONE exact read, under every policy: a refused - /// precondition does not say WHO holds the key, and a 404 and a 412 reach here as the same - /// answer. A hinted attempt reaches this read after a reissue that met a refused - /// precondition, or at once under a policy that never resends it (`single_attempt`, - /// `resend_unresolved = false`). A refused precondition needs only to know WHAT is there, so a presence-only - /// caller settles it with a HEAD; proving an ambiguous attempt landed needs the bytes, and there - /// the body read is unavoidable. - ProfileEvents::increment(ProfileEvents::CASRequestResolveRead); - const Resolved resolved = resolve_refusal_with == ResolveWith::Presence && !state.any_ambiguous - ? observePresence(key, policy, bound) - : observe(key, policy, bound); - state.last_seen = resolved.seen; - /// A bound refused the resolve, so say WHICH. Erasing it here is what let a lost fence be - /// reported as an ordinary conflict and a lease refusal as a policy deadline. - if (resolved.stop) - return gaveUpForReadStop(*resolved.stop, state, bound); - - /// No attempt of this inner write is unresolved, so the refused precondition IS the answer. - /// Identical bytes here are somebody else's object, and the caller that owns the key's meaning - /// decides what that means. - if (!state.any_ambiguous) - return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous}; + /// One exact read settles every refused precondition and every ambiguity, under every policy: a refused + /// precondition does not say WHO holds the key. A presence-only caller settles a refusal with a HEAD; proving + /// an ambiguous attempt landed needs the bytes. + if (auto settled = adjudicate(settlingRead(key, policy, state, resolve_refusal_with), bytes, expected, state, bound)) + return *settled; + latest_attempt_settled = true; - if (!preconditionStillSatisfiable(state.last_seen, expected)) - { - /// The precondition has MOVED, and THAT is what makes byte equality a proof: an attempt - /// that never applied leaves the key exactly as it found it, so under an incarnation that - /// did not move our own bytes cannot be told from the bytes already there. A create reaches - /// here for every object it sees -- an occupied key never satisfies its precondition. - if (const auto * obj = std::get_if(&state.last_seen); obj && obj->bytes == bytes) - return postCommit(obj->etag, /*resolved_by_read=*/true, state, bound); - /// Nothing of this inner write's is at the key, and a reissue would be refused too. - return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous}; - } - - /// Unresolved but repeatable: the precondition would still be met -- or nothing was observed at - /// all, which proves neither way and leaves this write's ambiguity alive. A reissue is what - /// settles it, and re-sending the same bytes under the same precondition is safe: it ends at - /// the store's own answer. A policy with no reissue has to say it settled nothing. + /// Unresolved: the precondition would still be met, or the read observed nothing. Re-sending the same bytes + /// under the same precondition is safe: it ends at the store's own answer. if (policy.single_attempt || !policy.resend_unresolved) return gaveUp(GaveUp::Why::Unresolved, sourceFor(bound), state); - /// The first attempt met the adaptive first-attempt timeout: a connection-quality answer, not a - /// store fault. The read above settled nothing new about it, so re-send at once as attempt 2 - /// under the full attempt budget; the backoff index is untouched because no store fault was - /// seen yet. - if (fuse) - { - if (auto given_up = reissueAtOnce(state, bound)) - return *given_up; - continue; - } - if (auto given_up = pauseAndReissue(state, bound)) - return *given_up; + /// A stop during the settling read ends the call here instead of after a pause. + if (state.observed_stop || (!insideOwed() && ownerStopRequested())) + return gaveUp(GaveUp::Why::Unresolved, sourceFor(bound), state); + /// A first-attempt timeout is a connection-quality answer, not a store fault: resend at once. + PauseOutcome paused = attempt.fuse ? reissueAtOnce(state, bound) : pauseAndReissue(state, bound); + if (auto * ended = std::get_if(&paused)) + return std::move(*ended); + if (std::holds_alternative(paused)) + return settle_for_stopped_owner(); } } @@ -1332,12 +1475,9 @@ WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObje else if (std::holds_alternative(state.last_seen)) current.reset(); - if (policy.single_attempt) + if (policy.single_attempt || state.observed_stop) return result; - /// A clean lost race is settled: the resolve read holds the fresh object and the next - /// iteration decides on it. Only a conflict that settled a transport fault is paced by the - /// growing schedule. - if (auto given_up = state.any_ambiguous ? pauseAndReissue(state, bound) : pauseForConflict(state, bound)) + if (const std::optional given_up = pauseAfterConflict(decisions, state, policy)) return *given_up; /// Only when the resolve settled nothing is a fresh read owed; otherwise `current` already is @@ -1360,7 +1500,7 @@ WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const De { WriteState state; - Resolved resolved = observePresence(key, policy, bound); + Resolved resolved = observe(key, policy, ResolveWith::Presence); state.last_seen = resolved.seen; std::optional current; if (const auto * meta = std::get_if(&state.last_seen)) @@ -1388,17 +1528,14 @@ WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const De else if (std::holds_alternative(state.last_seen)) current.reset(); - if (policy.single_attempt) - return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous}; - /// A clean lost race is settled: the resolve read holds the fresh object and the next - /// iteration decides on it. Only a conflict that settled a transport fault is paced by the - /// growing schedule. - if (auto given_up = state.any_ambiguous ? pauseAndReissue(state, bound) : pauseForConflict(state, bound)) + if (policy.single_attempt || state.observed_stop) + return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous, state.observed_stop}; + if (const std::optional given_up = pauseAfterConflict(decisions, state, policy)) return *given_up; if (std::holds_alternative(state.last_seen)) { - resolved = observePresence(key, policy, bound); + resolved = observe(key, policy, ResolveWith::Presence); state.last_seen = resolved.seen; if (const auto * meta = std::get_if(&state.last_seen)) current = *meta; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h index de9d894c8bbb2..e122f2b6084b0 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -131,6 +132,8 @@ String describeRequestFailure(std::string_view verb, const String & key, const s /// Both entry points route through the SAME construction internally, so the error code / message shape /// has exactly one place that decides it. std::exception_ptr makeCasWriteRetryLaterExceptionPtr(const String & why); +/// The same exception by value, for a caller that throws it as a subclass. +Exception makeCasWriteRetryLaterException(const String & why); /// Throw `CAS_OWNERSHIP_CONFLICT`: the committed ref a caller read moved, dropped or changed owner before the /// caller's write landed; the caller must re-resolve the part before trying again. Counted in @@ -205,6 +208,9 @@ void recordAttempt(); void recordReissue(); void recordConflictPause(); void recordFirstAttemptFuse(); +/// For a credential refusal whose retry a stopped query vetoed: the retry-later class carrying it, so the refusal is +/// not read as damage. +[[noreturn]] void throwVetoedCredentialRetry(std::string_view verb, const String & subject, const std::exception & e); } class CasOperation; @@ -254,7 +260,7 @@ class CasRequests /// A caller's own inter-iteration wait, paced through the same clock the engine's own sleeps use -- /// so a test that replaces the sleep sees no real time pass in either. `CasOperation` carries the /// same call for the loops that hold an operation rather than the plane it was admitted on. - void pause(uint64_t ms) { sleep_ms(ms); } + void sleepFor(uint64_t ms) { sleep_ms(ms); } void setNowFnForTest(std::function now_ms_); void setSleepFnForTest(std::function sleep_ms_); @@ -442,6 +448,9 @@ class CasOperation Observation last_seen = NotObserved{}; uint32_t reissues = 0; bool refresh_attempted = false; + /// An operation of this call failed and saw its query stopped: a write attempt, its settling read, or the + /// pause before a reissue. The call starts no further discretionary request, also after a settled conflict. + bool observed_stop = false; /// Under `Retry::attempt_spacing_ms`: that spacing, and when the latest attempt was sent. struct Spacing { @@ -494,16 +503,20 @@ class CasOperation /// the store or the bounds said. The window bound at entry governs every send of these bytes; the /// read that settles an attempt is a request of its own and binds its own window from `policy`. WriteResult writeLoop(const String & key, const String & bytes, const std::optional & expected, - const Retry & policy, const Retry::Bound & bound, WriteState & state, - ResolveWith resolve_refusal_with); - /// The resolve read: an exact read under the same policy and deadline, reporting what it saw and, - /// when it saw nothing, which bound stopped it. - Resolved observe(const String & key, const Retry & policy, const Retry::Bound & bound); - /// The presence-only sibling, for the one loop that must not fetch a body. - Resolved observePresence(const String & key, const Retry & policy, const Retry::Bound & bound); + const Retry & policy, WriteState & state, ResolveWith resolve_refusal_with); + /// The resolve read: an exact read (a `HEAD` for `Presence`) under its own window from `policy`, reporting + /// what it saw and, when it saw nothing, which of its bounds stopped it. A stopped owner's failure is + /// `NotObserved` only when a bound refused the read or inside `owed`; otherwise it propagates. + Resolved observe(const String & key, const Retry & policy, ResolveWith what = ResolveWith::Body); + /// The read that settles this inner write's latest attempt, run `owed`. A body read once an attempt is ambiguous. + Resolved settlingRead(const String & key, const Retry & policy, const WriteState & state, ResolveWith resolve_refusal_with); + /// What the settling read proves: `Committed`, `Conflict` or the bound that refused it. Nullopt + /// when a resend under the same precondition could still apply. + std::optional adjudicate(const Resolved & resolved, const String & bytes, const std::optional & expected, + WriteState & state, const Retry::Bound & write_bound); WriteResult postCommit(Etag inc, bool resolved_by_read, WriteState & state, const Retry::Bound & bound); - WriteResult gaveUp(GaveUp::Why why, GaveUp::Source source, WriteState & state) const; + GaveUp gaveUp(GaveUp::Why why, GaveUp::Source source, WriteState & state) const; /// The bound that refused the resolve read, reported as the outcome it actually is. WriteResult gaveUpForReadStop(ReadStop stop, GaveUp::Source source, WriteState & state) const; /// A resolve read that produced nothing. The fence is NOT resampled: a second sample reports a @@ -546,11 +559,11 @@ class CasOperation PauseOutcome pauseAndReissue(WriteState & state, const Retry::Bound & bound); /// The sibling for a failure text that named a failed connection. The same admission and the same /// reservation, a flat `kConnectHintPauseMs` sleep, and `state.reissues` untouched. - std::optional pauseFlat(WriteState & state, const Retry::Bound & bound); + PauseOutcome pauseFlat(WriteState & state, const Retry::Bound & bound); /// The sibling for a first-attempt fuse timeout: the same admission and the same reservation, NO /// sleep at all, and `state.reissues` untouched -- the fuse is a connection-quality answer about a /// fresh connection, not a store fault, so nothing here is paced against it. - std::optional reissueAtOnce(WriteState & state, const Retry::Bound & bound); + PauseOutcome reissueAtOnce(WriteState & state, const Retry::Bound & bound); /// The pause before a write reissue: `unspaced_ms`, or `Retry::pauseAfterAttempt` under `state.spacing`. uint64_t reissuePause(const WriteState & state, uint64_t unspaced_ms) const; @@ -598,10 +611,13 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const /// Two counters, deliberately kept separate: `attempt_no` is the PHYSICAL attempt count handed to /// the transport (so a reissue is seen as attempt >= 2); `ordinary_reissues` is the /// exponential-backoff index. They advance together on an ordinary failure, but the first-attempt - /// fuse below advances `attempt_no` alone (via `continue`, skipping the backoff pause) so a - /// following ordinary failure's backoff still starts from `backoff(1)`, undisturbed. + /// fuse below advances `attempt_no` alone (no backoff pause) so a following ordinary failure's + /// backoff still starts from `backoff(1)`, undisturbed. for (uint32_t attempt_no = 1, ordinary_reissues = 0;; ++attempt_no) { + /// Not before the first attempt: a healthy read is never refused, as on a plain S3 disk. + if (attempt_no > 1) + throwIfBackgroundStopped(); const uint64_t reservation = reservedFor(0, 1); switch (gate(reservation)) { @@ -621,6 +637,20 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const } catch (const std::exception & e) { + /// A local fault surfaces unchanged, as in the write loop; a query's stored cause can carry any code. + if (!isStoreAnswer(e) && !isQueryStoredCause(std::current_exception())) + throw; + /// Checked even inside `owed`, before classifying: a stopped owner's failure is not reissued. A background + /// owner reports its verdict; a stopped query keeps the failure, as on a plain S3 disk. + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(stop); + if (queryStopRequested()) + { + if (!refresh_attempted && !policy.single_attempt && isRefreshableCredentialError(e) + && !isQueryStoredCause(std::current_exception())) + detail::throwVetoedCredentialRetry(verb, subject, e); + throw; + } if (observer.on_failure && verb == "read" && isStoreAnswer(e)) observer.on_failure("GET", subject, e); if (on_memory_limit == OnMemoryLimit::Propagate && isMemoryLimitExceeded(e)) @@ -638,13 +668,10 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const detail::recordFirstAttemptFuse(); if (policy.single_attempt) throw; - /// A first-attempt fuse is a connection-quality answer, not a store fault: re-check - /// admission for the reissue alone and send it at once. `ordinary_reissues` stays put, so a - /// following ordinary failure's backoff starts at `backoff(1)`, exactly as if this attempt - /// had never happened. - if (fuse) + + const auto admit_reissue = [&](uint64_t pause_ms) { - const uint64_t needed = reservedFor(0, 1); + const uint64_t needed = reservedFor(pause_ms, 1); switch (gate(needed)) { case Gate::FenceLost: giveUpReadFenceLost(verb, subject, "before the reissue"); @@ -654,25 +681,29 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const if (!fits(needed, bound)) giveUpReadDeadline(verb, subject, source, attempt_no); detail::recordReissue(); + }; + /// A first-attempt fuse is a connection-quality answer, not a store fault: re-check + /// admission for the reissue alone and send it at once. `ordinary_reissues` stays put, so a + /// following ordinary failure's backoff starts at `backoff(1)`, exactly as if this attempt + /// had never happened. + if (fuse) + { + admit_reissue(0); continue; } - } - ++ordinary_reissues; - const uint64_t pause_ms = policy.attempt_spacing_ms - ? Retry::pauseAfterAttempt(*policy.attempt_spacing_ms, attempt_started_ms, owner.now_ms()) - : Retry::backoff(ordinary_reissues); - const uint64_t needed = reservedFor(pause_ms, 1); - switch (gate(needed)) - { - case Gate::FenceLost: giveUpReadFenceLost(verb, subject, "before the reissue"); - case Gate::NoBudget: giveUpReadNoBudget(verb, subject, "for the reissue"); - case Gate::Ok: break; + ++ordinary_reissues; + const uint64_t pause_ms = policy.attempt_spacing_ms + ? Retry::pauseAfterAttempt(*policy.attempt_spacing_ms, attempt_started_ms, owner.now_ms()) + : Retry::backoff(ordinary_reissues); + admit_reissue(pause_ms); + if (!sleepUnlessQueryStops(pause_ms, [this](uint64_t ms) { sleep(ms); })) + { + if (refreshed) + detail::throwVetoedCredentialRetry(verb, subject, e); + throw; + } } - if (!fits(needed, bound)) - giveUpReadDeadline(verb, subject, bound, attempt_no); - detail::recordReissue(); - sleep(pause_ms); } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h index 38ed1364c7720..591dfeb97044d 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h @@ -50,7 +50,7 @@ struct Retry /// `GaveUp::Unresolved` so the caller decides new bytes. For namespace-create step 1, whose catalog /// row must differ per attempt. A clean conflict and a credential reissue are unaffected. Read /// paths ignore it. Clear it only in a loop that decides again on a fresh read (`casUpdateImpl` - /// with `CasOperation::pauseBeforeRedecide`); any other caller gets a bare `GaveUp::Unresolved`. + /// with `CasOperation::pauseAfterUnresolvedWrite`); any other caller gets a bare `GaveUp::Unresolved`. bool resend_unresolved = true; /// An absolute bound on the caller's clock that can only shorten the request. See `cappedAt`. std::optional outside_cap_ms = std::nullopt; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h index 9cabbcfa88cdc..73a391abdeb37 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h @@ -52,7 +52,9 @@ struct Declined { Observation seen; }; /// caller outside the engine paces such a conflict on the growing schedule, as the engine's own /// loops do, and a clean lost race on the flat one. `attempts_sent` cannot stand in for it: a /// throttled first attempt whose resolve read finds the key moved is one attempt, ambiguous. -struct Conflict { Observation seen; uint32_t attempts_sent = 0; bool any_ambiguous = false; }; +/// `observed_stop` is true when an operation of the call failed and saw its query stopped: a loop takes the +/// conflict as the answer and starts no further decision. +struct Conflict { Observation seen; uint32_t attempts_sent = 0; bool any_ambiguous = false; bool observed_stop = false; }; /// The store itself refused the request (not a lost precondition) -- `store_error` is a ClickHouse /// error code and `message` explains it. `attempts_sent` is the same count `Conflict` carries, for /// the same reason. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp index 3c8f4e4542bc9..25be9bf06e2c2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -287,6 +288,10 @@ std::shared_ptr CachedPartFolderAccess::buildView( { return future.get(); /// Rethrows the leader's exception, if any. } + catch (const LeaderStopped &) + { + continue; + } catch (const std::exception & e) { /// The leader ran out of its own query's memory, which says nothing about this query's budget. @@ -814,6 +819,11 @@ void CachedPartFolderAccess::dropRefIfPresent(const PartRefKey & key) { if (e.code() != ErrorCodes::FILE_DOESNT_EXIST) throw; + /// A stopped background owner's miss is its verdict. A query's stored cause is no miss; a real one is. + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(stop); + if (isQueryStoredCause(std::current_exception())) + throw; eraseView(key); return; /// Raced away between the gate and dropRef; nothing was actually dropped here. } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index 53108c5de7be1..27a822fde859e 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -122,6 +122,22 @@ void recordFailedPublicationAttempt( LOG_WARNING(log, "Publication of CAS blob {} ({}) failed, attempt {} of {}: {}", key, transport_name, attempt + 1, max_attempts, error); } +/// The failure that a stopped query's veto of the next publication ends with. A credential refusal becomes retry-later +/// carrying it, so it does not read as damage. +[[noreturn]] void rethrowVetoedPublicationFailure(const String & key, const std::exception_ptr & failure) +{ + try + { + std::rethrow_exception(failure); + } + catch (const std::exception & e) + { + if (isRefreshableCredentialError(e) && !isQueryStoredCause(failure)) + detail::throwVetoedCredentialRetry("publish", key, e); + throw; + } +} + bool isDeterministicBlobPublicationFailure(const std::exception & error) { /// A refused write, EXCEPT the class a fresh credential fixes: the engine refreshes once before it diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp index e634ebd3ffa53..81a99d28b50b3 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp @@ -1288,7 +1288,7 @@ void Pool::cancelIdleOwnCreatingRows(const std::function & stop_requeste /// The pass keeps the mount fence but backs off on the open plane's sleep, which `beginTeardown` wakes; /// the mount plane's sleep would hold a scheduler join for a whole pause. ref_ledger.cancelIdleOwnCreatingRows( - [this] { return !teardownBegun(); }, [this](uint64_t ms) { gc_requests.pause(ms); }, stop_requested); + [this] { return !teardownBegun(); }, [this](uint64_t ms) { gc_requests.sleepFor(ms); }, stop_requested); } void Pool::beginTeardown() noexcept diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp index 8df63d5ae2293..c9e7fd1bac81d 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp @@ -530,6 +530,9 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov if (erase_acknowledged && std::holds_alternative(erase)) erase_acknowledged(old_life); + /// The erase saw its query stop on a failure: no further erase follows it. + const auto * conflict = std::get_if(&erase); + const bool erase_again = conflict && !conflict->observed_stop; /// Pause before the read: that read is the snapshot the next erase is conditioned on, and a /// write landing during a pause taken after it would refuse that erase every time. /// The argument counts reissues so far: `backoff(0)` is no wait at all. No erase follows the @@ -559,7 +562,7 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov /// The row survived the attempt. Only a refused precondition may be tried again against the /// mandatory resolution snapshot above; every other alternative is terminal for this call, and /// a commit the resolution read contradicts is reported rather than believed. - if (!std::holds_alternative(erase)) + if (!erase_again) { if (std::holds_alternative(erase)) throwCasWriteRetryLater(fmt::format( @@ -569,6 +572,7 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov throwCatalogWriteFailure(std::move(erase), fmt::format( "CAS ref catalog erase for namespace '{}'", observed.ns.string())); } + throwIfBackgroundStopped(); } throwCasWriteRetryLater(fmt::format( diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index eff1435975b81..81735b6456102 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -1496,7 +1496,7 @@ NamespaceLifeId CasRefLedger::resolveNamespaceLife( /// Paces ONLY the re-reads a competing actor forced. A `Live` outcome is this open's own /// success and its single confirming re-read is not contention, so it is never delayed. The /// argument is the number of collisions so far, so the first one waits the shortest draw. - const auto paceReRead = [&] { op.pause(Retry::backoff(static_cast(attempt) + 1)); }; + const auto paceReRead = [&] { op.sleepFor(Retry::backoff(static_cast(attempt) + 1)); }; const CasRefCatalog::Snapshot snap = CasRefCatalog::read(op, layout, policy); const auto it = std::find_if(snap.catalog.entries.begin(), snap.catalog.entries.end(), diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp index a6f3ef4ba9f73..e9f4110f18d2a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp @@ -1968,7 +1968,7 @@ Observation MountLeaseRenewer::readUntilObserved( uint64_t pause_ms = Retry::pauseAfterAttempt(*policy.attempt_spacing_ms, write_started_boot_ms, boot_clock()); while (op.admitted()) { - op.pause(pause_ms); + op.sleepFor(pause_ms); try { std::optional got = op.read(key, policy); @@ -2080,7 +2080,7 @@ MountRenewResult MountLeaseRenewer::renewOn( { break; } - op.pause(pause_ms); + op.sleepFor(pause_ms); written = op.replace(key, body, expected, policy); } } diff --git a/src/Disks/tests/gtest_cas_owner_stop.cpp b/src/Disks/tests/gtest_cas_owner_stop.cpp index e73e3813ed831..a09e62b603bee 100644 --- a/src/Disks/tests/gtest_cas_owner_stop.cpp +++ b/src/Disks/tests/gtest_cas_owner_stop.cpp @@ -719,3 +719,3142 @@ TEST(CASOwnerScope, ScopesStayOnTheirThread) ASSERT_TRUE(opened) << "the holder never opened its scope"; } +namespace +{ + +/// The first write of `key` stores its bytes and loses the response; the first read of `key` fails. +class LostWriteThenLostReadBackend final : public InMemoryBackend +{ +public: + explicit LostWriteThenLostReadBackend(String key_) : key(std::move(key_)) {} + + std::atomic writes{0}; + std::atomic reads{0}; + + std::expected write(const String & k, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + if (k == key && writes.fetch_add(1) == 0) + { + (void)InMemoryBackend::write(k, bytes, expected_value, access); + throw Poco::TimeoutException("LostWriteThenLostReadBackend: stored, response lost"); + } + return InMemoryBackend::write(k, bytes, expected_value, access); + } + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key && reads.fetch_add(1) == 0) + throw Poco::TimeoutException("LostWriteThenLostReadBackend: read response lost"); + return InMemoryBackend::read(k, access); + } + +private: + const String key; +}; + +} + +/// The settling read of a possibly-sent write is owed to that write: when its first attempt fails while +/// the owner is live and the owner stops during the backoff, the read is still reissued and proves the +/// write landed. +TEST(CASOwnerStop, OwedSettlingReadReissuesAfterAFailure) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared("settled"); + std::atomic pauses{0}; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + if (backend->reads.load() > 0 && pauses.fetch_add(1) == 0) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + + std::optional written; + EXPECT_NO_THROW(written = op.create("settled", "bytes", Retry::standard())); + + ASSERT_TRUE(written.has_value()); + EXPECT_TRUE(std::holds_alternative(*written)) << "the reissued settling read proves the write landed"; + EXPECT_EQ(backend->writes.load(), 1) << "a landed write is not resent"; + EXPECT_EQ(backend->reads.load(), 2) << "the failed settling read was reissued"; + EXPECT_EQ(pauses.load(), 1); + EXPECT_NE(codeOf(ownerStopRequested()), 0) << "the owner stopped before the reissue"; + }); +} + +namespace +{ + +/// Fails the first read or head of `key` with `failure`, and counts the requests to `key` and the +/// credential refreshes. Wrapped in `CasClientLikeBackend`, a stopped query's verdict replaces the +/// failure, as the S3 client does. +class FailFirstRequestBackend final : public InMemoryBackend +{ +public: + explicit FailFirstRequestBackend(String key_) : key(std::move(key_)) {} + + std::exception_ptr failure = std::make_exception_ptr(Exception(ErrorCodes::TIMEOUT_EXCEEDED, "the read timed out")); + std::atomic fail_next{true}; + std::atomic requests{0}; + std::atomic refreshes{0}; + + std::optional read(const String & k, TransportAccess & access) override + { + countAndMaybeFail(k); + return InMemoryBackend::read(k, access); + } + + std::optional head(const String & k, TransportAccess & access) override + { + countAndMaybeFail(k); + return InMemoryBackend::head(k, access); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } + +private: + void countAndMaybeFail(const String & k) + { + if (k != key) + return; + ++requests; + if (fail_next.exchange(false)) + std::rethrow_exception(failure); + } + + const String key; +}; + +enum class ReadSurface { Read, ReadModifyWrite, ReadModifyWriteOnPresence }; + +struct FailedFirstRequest +{ + ReadSurface surface = ReadSurface::Read; + /// What the first request to the key throws when no verdict replaces it. + std::exception_ptr failure; + /// Stops the query before the call; empty leaves the owner live. + std::function stop; + /// Runs the call under a stopped background owner instead. + bool stopped_background = false; + /// Runs during the pause before a reissue. + std::function during_pause; +}; + +struct FailedFirstRequestOutcome +{ + int code = 0; + String message; + bool has_value = false; + bool gave_up = false; + int requests = 0; + int refreshes = 0; + int pauses = 0; +}; + +/// One call whose first request to an existing key fails. The single-attempt surfaces would turn a +/// failed observation into `GaveUp` with `NotObserved`. +FailedFirstRequestOutcome runFailedFirstRequest(const FailedFirstRequest & arm) +{ + FailedFirstRequestOutcome out; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared("k"); + if (arm.failure) + inner->failure = arm.failure; + auto backend = std::make_shared(inner); + std::atomic pauses{0}; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + ++pauses; + if (arm.during_pause) + arm.during_pause(query); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("k", "v", Retry::once()))); + inner->requests = 0; + + std::optional background; + if (arm.stopped_background) + background.emplace(OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); })); + if (arm.stop) + arm.stop(query); + try + { + switch (arm.surface) + { + case ReadSurface::Read: + out.has_value = op.read("k", Retry::standard()).has_value(); + break; + case ReadSurface::ReadModifyWrite: + out.gave_up = std::holds_alternative( + op.readModifyWrite("k", [](const std::optional &) { return std::optional{}; }, Retry::once())); + break; + case ReadSurface::ReadModifyWriteOnPresence: + out.gave_up = std::holds_alternative( + op.readModifyWriteOnPresence("k", [](const std::optional &) { return std::optional{}; }, Retry::once())); + break; + } + } + catch (...) + { + out.code = codeOf(std::current_exception()); + out.message = getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + out.requests = inner->requests.load(); + out.refreshes = inner->refreshes.load(); + out.pauses = pauses.load(); + }); + return out; +} + +/// `LocalObjectStorage` whose next small-object read fails the way the S3 client fails a request of a +/// stopped query: it asks the query first, so the query's verdict replaces the failure. +class ClientLikeLocalObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + mutable std::atomic fail_next{false}; + mutable std::atomic reads{0}; + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, + const DB::ReadSettings & read_settings, + size_t max_size_bytes, + std::optional read_hint) const override + { + ++reads; + if (fail_next.exchange(false)) + { + CurrentThread::checkIfNotCancelled(); + throw Poco::TimeoutException("ClientLikeLocalObjectStorage: the read timed out"); + } + return DB::LocalObjectStorage::readSmallObjectAndGetObjectMetadata(object, read_settings, max_size_bytes, read_hint); + } +}; + +template +std::shared_ptr makeLocalObjectStorageOf() +{ + static std::atomic counter{0}; + const auto root = (std::filesystem::temp_directory_path() + / ("cas_owner_stop_unit_" + std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)))).string(); + std::filesystem::remove_all(root); + std::filesystem::create_directories(root); + DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); + return DB::Cas::tests::ownedByDirectory(std::make_shared(std::move(settings)), root); +} + +std::shared_ptr makeClientLikeLocalObjectStorage() +{ + return makeLocalObjectStorageOf(); +} + +/// `LocalObjectStorage` whose small-object reads and container checks first run a hook, which may throw. +class HookedReadLocalObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + std::function on_read; + std::function on_exists; + mutable std::atomic reads{0}; + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, + const DB::ReadSettings & read_settings, + size_t max_size_bytes, + std::optional read_hint) const override + { + ++reads; + if (on_read) + on_read(); + return DB::LocalObjectStorage::readSmallObjectAndGetObjectMetadata(object, read_settings, max_size_bytes, read_hint); + } + + bool existsOrHasAnyChild(const std::string & path) const override + { + if (on_exists) + on_exists(); + return DB::LocalObjectStorage::existsOrHasAnyChild(path); + } +}; + +#if USE_AWS_S3 +/// `LocalObjectStorage` that answers every small-object read with the store's own `NoSuchKey`. +class NoSuchKeyLocalObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + mutable std::atomic reads{0}; + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, const DB::ReadSettings &, size_t, std::optional) const override + { + ++reads; + throw DB::S3Exception("the store answered NoSuchKey for " + object.remote_path, Aws::S3::S3Errors::NO_SUCH_KEY, "NoSuchKey"); + } +}; +#endif + +std::exception_ptr storedCause(int code) +{ + return std::make_exception_ptr(Exception(code, "the query's stored cause")); +} + +} + +/// A stopped owner's exception after a failed first attempt is not a store answer: it is not reissued, +/// refreshed or paced, is never read as absence, and a single-attempt observation surfaces it rather +/// than reporting `NotObserved`. A live owner's same failure is reissued. +TEST(CASOwnerStop, StoppedOwnersFailedReadIsNotReissued) +{ + struct Stop + { + const char * name; + std::function stop; + int code; + }; + const std::vector stops = { + {"timeout", [](CasKillableQuery & q) { q.kill(storedCause(ErrorCodes::TIMEOUT_EXCEEDED)); }, ErrorCodes::TIMEOUT_EXCEEDED}, + {"kill", [](CasKillableQuery & q) { q.kill(); }, ErrorCodes::QUERY_WAS_CANCELLED}, + {"stored BAD_ARGUMENTS", [](CasKillableQuery & q) { q.kill(storedCause(ErrorCodes::BAD_ARGUMENTS)); }, ErrorCodes::BAD_ARGUMENTS}, + {"stored FILE_DOESNT_EXIST", [](CasKillableQuery & q) { q.kill(storedCause(ErrorCodes::FILE_DOESNT_EXIST)); }, + ErrorCodes::FILE_DOESNT_EXIST}, + }; + for (const auto & stop : stops) + { + for (const auto surface : {ReadSurface::Read, ReadSurface::ReadModifyWrite, ReadSurface::ReadModifyWriteOnPresence}) + { + SCOPED_TRACE(fmt::format("{}, surface {}", stop.name, static_cast(surface))); + FailedFirstRequest arm; + arm.surface = surface; + arm.stop = stop.stop; + const auto out = runFailedFirstRequest(arm); + EXPECT_EQ(out.code, stop.code) << "the owner's verdict surfaces"; + EXPECT_FALSE(out.has_value); + EXPECT_FALSE(out.gave_up) << "a stopped owner's failed observation is not NotObserved"; + EXPECT_EQ(out.requests, 1) << "no reissue"; + EXPECT_EQ(out.refreshes, 0); + EXPECT_EQ(out.pauses, 0); + } + } + +#if USE_AWS_S3 + { + SCOPED_TRACE("background owner, credential failure"); + FailedFirstRequest arm; + arm.failure = std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); + arm.stopped_background = true; + const auto out = runFailedFirstRequest(arm); + EXPECT_EQ(out.code, ErrorCodes::ABORTED); + EXPECT_EQ(out.refreshes, 0) << "a stopped owner's failure is not a credential answer"; + EXPECT_EQ(out.requests, 1); + } +#endif + + { + SCOPED_TRACE("live owner"); + const auto out = runFailedFirstRequest({}); + EXPECT_EQ(out.code, 0); + EXPECT_TRUE(out.has_value) << "a live owner's timeout is reissued"; + EXPECT_EQ(out.requests, 2); + EXPECT_EQ(out.pauses, 1); + } + + { + SCOPED_TRACE("stored FILE_DOESNT_EXIST through the native backend"); + auto storage = makeClientLikeLocalObjectStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "present"); + { + auto out = storage->writeObject(DB::StoredObject(key), DB::WriteMode::Rewrite); + DB::writeString(String("body"), *out); + out->finalize(); + } + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + int code = 0; + bool read_absent = false; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + query.kill(storedCause(ErrorCodes::FILE_DOESNT_EXIST)); + storage->reads = 0; + storage->fail_next = true; + try + { + read_absent = !op.read(key, Retry::standard()).has_value(); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_FALSE(read_absent) << "a stopped owner's stored FILE_DOESNT_EXIST is never absence"; + EXPECT_EQ(code, ErrorCodes::FILE_DOESNT_EXIST); + EXPECT_EQ(storage->reads.load(), 1); + } +} + +/// A stop during the pause before a reissue starts no further request, even one that would succeed. The read ends +/// with its own failure, which came before the kill, so the client-like backend did not replace it. +TEST(CASOwnerStop, StopDuringBackoffStartsNoReissue) +{ + FailedFirstRequest arm; + arm.during_pause = [](CasKillableQuery & q) { q.kill(); }; + const auto out = runFailedFirstRequest(arm); + EXPECT_EQ(out.code, ErrorCodes::TIMEOUT_EXCEEDED); + EXPECT_FALSE(out.has_value); + EXPECT_EQ(out.pauses, 1); + EXPECT_EQ(out.requests, 1) << "the reissue, configured to succeed, never starts"; +} + +namespace +{ + +/// The first write of `key` stores its bytes, runs `on_lost_response` and loses the response; the first +/// read of `key` runs `on_failed_read` and fails. +class LostResponseBackend final : public InMemoryBackend +{ +public: + explicit LostResponseBackend(String key_) : key(std::move(key_)) {} + + std::function on_lost_response; + std::function on_failed_read; + std::atomic writes{0}; + std::atomic reads{0}; + std::atomic refreshes{0}; + + std::expected write(const String & k, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + if (k == key && writes.fetch_add(1) == 0) + { + (void)InMemoryBackend::write(k, bytes, expected_value, access); + if (on_lost_response) + on_lost_response(); + throw Poco::TimeoutException("LostResponseBackend: stored, response lost"); + } + return InMemoryBackend::write(k, bytes, expected_value, access); + } + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key && reads.fetch_add(1) == 0) + { + if (on_failed_read) + on_failed_read(); + throw Poco::TimeoutException("LostResponseBackend: read response lost"); + } + return InMemoryBackend::read(k, access); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } + +private: + const String key; +}; + +Retry withoutResend() +{ + Retry policy = Retry::standard(); + policy.resend_unresolved = false; + return policy; +} + +} + +/// Inside `owed`, a stopped owner's failed settling read is neither refreshed nor reissued, and the +/// observation reports `NotObserved`: no local-bug rethrow for a stored `BAD_ARGUMENTS` either. +TEST(CASOwnerStop, OwedFailedReadBecomesNotObserved) +{ + const auto run_arm = [](int stored) + { + std::optional written; + int code = 0; + int reads = 0; + int refreshes = 0; + int pauses = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared("settled"); + /// After the write's failure, so only the settling read sees the stop. + inner->on_failed_read = [&] { query.kill(stored ? storedCause(stored) : nullptr); }; + auto backend = std::make_shared(inner); + std::atomic pause_count{0}; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) { ++pause_count; }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + written = op.create("settled", "bytes", withoutResend()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + reads = inner->reads.load(); + refreshes = inner->refreshes.load(); + pauses = pause_count.load(); + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + const auto * gave_up = std::get_if(&*written); + ASSERT_NE(gave_up, nullptr) << "the settling read proved nothing"; + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved) << "no bound refused the read"; + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_TRUE(std::holds_alternative(gave_up->last_seen)); + EXPECT_EQ(reads, 1) << "the failed settling read was not reissued"; + EXPECT_EQ(refreshes, 0); + EXPECT_EQ(pauses, 0); + }; + for (const int stored : {0, ErrorCodes::BAD_ARGUMENTS}) + { + SCOPED_TRACE(stored ? "stored BAD_ARGUMENTS" : "kill"); + run_arm(stored); + } +} + +/// A fence refusal recorded by the settling read survives the owed observation of a stopped owner: +/// the write reports the lost fence, not an unresolved outcome. +TEST(CASOwnerStop, FenceRefusalSurvivesOwedObservation) +{ + std::optional written; + int reads = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared("fenced"); + std::atomic fence_lost{false}; + backend->on_lost_response = [&] + { + fence_lost = true; + query.kill(); + }; + Fence fence = Fence::open(); + fence.admit = [&fence_lost](uint64_t, uint64_t) { return fence_lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }; + CasRequests requests(backend, fence, {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + written = op.create("fenced", "bytes", withoutResend()); + reads = backend->reads.load(); + }); + ASSERT_TRUE(written.has_value()); + const auto * gave_up = std::get_if(&*written); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(reads, 0) << "the fence refused the settling read before it was sent"; +} + +/// The first attempt of a read is sent for an owner that already stopped, and a healthy answer is returned. +TEST(CASOwnerStop, HealthyFirstReadIsNotRefused) +{ + for (const bool background : {false, true}) + { + SCOPED_TRACE(background ? "background owner" : "killed query"); + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(); + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("present", "v", Retry::once()))); + + std::optional scope; + if (background) + scope.emplace(OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); })); + else + query.kill(); + ASSERT_NE(ownerStopRequested(), nullptr); + + const auto present = op.read("present", Retry::standard()); + ASSERT_TRUE(present.has_value()); + EXPECT_EQ(present->bytes, "v"); + EXPECT_FALSE(op.read("absent", Retry::standard()).has_value()); + EXPECT_TRUE(op.head("present", Retry::standard()).has_value()); + EXPECT_FALSE(op.head("absent", Retry::standard()).has_value()); + }); + } + +#if USE_AWS_S3 + { + /// The S3 client never sees a background owner, so the store's own 404 reaches the backend. + SCOPED_TRACE("background owner, the store's NoSuchKey through the native backend"); + auto storage = makeLocalObjectStorageOf(); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + onThread(false, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + auto scope = OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); }); + ASSERT_NE(ownerStopRequested(), nullptr); + std::optional got; + EXPECT_NO_THROW(got = op.read(DB::Cas::tests::nativeKeyUnder(storage, "absent"), Retry::standard())); + EXPECT_FALSE(got.has_value()) << "a healthy 404 is absence"; + }); + EXPECT_EQ(storage->reads.load(), 1); + } +#endif +} + +/// A stopped owner's catalog update whose base read the fence refuses keeps the typed fence outcome. +TEST(CASOwnerStop, StoppedOwnersFencedCatalogReadIsFencedOut) +{ + onThread(false, [&] + { + auto backend = std::make_shared(); + const Layout layout("p"); + const CatalogEntry observed{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(1)}; + { + /// A plane of its own, so the update below reads the catalog rather than starting from a cached hint. + auto setup_requests = openRequestsForTest(backend); + auto setup = setup_requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + CasRefCatalog::casAdmitEntry(setup, layout, 1, observed); + } + auto requests = openRequestsForTest(backend); + /// Admitted at the hot-key lane's own check, refused from the base read on. + int admissions = 0; + auto op = requests.admit([&admissions] { return admissions++ == 0; }); + auto scope = OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); }); + + std::optional outcome; + EXPECT_NO_THROW(outcome = CasRefCatalog::beginRemoving(op, layout, observed, /*removal_started_round*/ 13)); + ASSERT_TRUE(outcome.has_value()); + EXPECT_EQ(*outcome, CasRefCatalog::BeginRemovingOutcome::FencedOut); + EXPECT_GE(admissions, 2) << "the base read reached its own admission"; + }); +} + +namespace +{ + +enum class DecisionLoop : uint8_t { BodyReadModifyWrite, PresenceReadModifyWrite, Catalog }; + +struct ConflictPauseArm +{ + DecisionLoop loop; + /// 50 writes that each take 500 ms on the manual clock and lose their precondition, the stop in the + /// third pause; otherwise every write loses and the stop comes in the first pause. + bool slow; +}; + +class CASOwnerStopLoop : public ::testing::TestWithParam +{ +}; + +enum class PauseOwner : uint8_t { Background, Query }; + +struct ConflictPauseRun +{ + std::exception_ptr error; + /// The read-modify-write loops' answer; the catalog loop returns none. + std::optional result; + int decisions = 0; + int decisions_at_stop = -1; + uint64_t writes = 0; + uint64_t writes_at_stop = 0; +}; + +/// Runs `arm`'s loop against lost races and stops `who` in the first pause, or in the third on the slow schedule. A +/// background owner sees every write lose; a query sees only the writes before its kill lose, since an unsuccessful +/// answer after it would carry the kill. +ConflictPauseRun runConflictPause(const ConflictPauseArm & arm, PauseOwner who) +{ + const int stop_at_pause = arm.slow ? 3 : 1; + ConflictPauseRun run; + onThread(who == PauseOwner::Query, [&] + { + std::optional query; + if (who == PauseOwner::Query) + query.emplace(getContext().context); + auto backend = std::make_shared(); + auto clock = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + const Layout layout("p"); + const String key = arm.loop == DecisionLoop::Catalog ? layout.refCatalogKey() : String("k"); + std::atomic stop{false}; + int pauses = 0; + const auto sleep_on_clock = ManualClock::sleepFnOf(clock); + const BackendPtr engine_backend = who == PauseOwner::Query + ? BackendPtr(std::make_shared(backend)) : BackendPtr(backend); + CasRequests requests(engine_backend, Fence::open(), ManualClock::nowFnOf(clock), [&](uint64_t ms) + { + sleep_on_clock(ms); + if (++pauses == stop_at_pause) + { + stop = true; + if (query) + query->kill(); + run.decisions_at_stop = run.decisions; + run.writes_at_stop = backend->writeCount(key); + } + }, &hot_keys, kDefaultRequestWindowMs); + auto op = requests.admit(); + if (arm.loop == DecisionLoop::Catalog) + { + CasRefCatalog::initializeEmptyForNewPool(op, layout); + CasRefCatalog::casAdmitEntry(op, layout, 1, + CatalogEntry{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(1)}); + } + else + { + ASSERT_TRUE(std::holds_alternative(op.create(key, "v0", Retry::once()))); + } + ASSERT_EQ(pauses, 0); + + int conflicts_left = arm.slow ? 50 : 1000; + backend->onBeforeWrite(key, [&] + { + const bool lose = who == PauseOwner::Query ? !stop.load() : conflicts_left-- > 0; + if (lose) + backend->refuseNextWrite(key); + }); + if (arm.slow) + backend->armWith(TimeTakingBackend::Verb::Write, [key](const String & k) { return k == key; }, + [clock] { clock->advance(500); }, 50); + + std::optional owner; + if (who == PauseOwner::Background) + owner.emplace(backgroundStoppedBy(stop)); + try + { + switch (arm.loop) + { + case DecisionLoop::BodyReadModifyWrite: + run.result = op.readModifyWrite(key, [&](const std::optional & current) + { + ++run.decisions; + return std::optional(current ? current->bytes + "+" : String("v")); + }, Retry::standard()); + break; + case DecisionLoop::PresenceReadModifyWrite: + run.result = op.readModifyWriteOnPresence(key, [&](const std::optional &) + { + ++run.decisions; + return std::optional("v" + std::to_string(run.decisions)); + }, Retry::standard()); + break; + case DecisionLoop::Catalog: + (void)CasRefCatalog::casUpdate(op, layout, [&](const RefCatalog & current) + { + ++run.decisions; + return current; + }); + break; + } + } + catch (...) + { + run.error = std::current_exception(); + } + run.writes = backend->writeCount(key); + }); + return run; +} + +} + +/// A stop during the pause after a lost race ends the loop: no decision and no write after it. +TEST_P(CASOwnerStopLoop, StopDuringConflictPauseSkipsNextDecision) +{ + const ConflictPauseArm arm = GetParam(); + const ConflictPauseRun run = runConflictPause(arm, PauseOwner::Background); + EXPECT_EQ(codeOf(run.error), ErrorCodes::ABORTED); + EXPECT_EQ(run.decisions_at_stop, arm.slow ? 3 : 1) << "one pause after each lost race"; + EXPECT_EQ(run.decisions, run.decisions_at_stop) << "no decision after the stop"; + EXPECT_EQ(run.writes, run.writes_at_stop) << "no write after the stop"; +} + +/// A killed query is not stopped by an accepted conflict: the pause after a lost race is not a safe point, so the +/// next decision runs and its write, sent on a healthy store, commits. +TEST_P(CASOwnerStopLoop, KilledQueryDecidesAgainAfterConflictPause) +{ + const ConflictPauseArm arm = GetParam(); + const ConflictPauseRun run = runConflictPause(arm, PauseOwner::Query); + EXPECT_EQ(codeOf(run.error), 0) << messageOf(run.error); + if (run.result) + EXPECT_TRUE(std::holds_alternative(*run.result)); + EXPECT_EQ(run.decisions_at_stop, arm.slow ? 3 : 1) << "one pause after each lost race"; + EXPECT_EQ(run.decisions, run.decisions_at_stop + 1) << "one decision after the kill"; + EXPECT_EQ(run.writes, run.writes_at_stop + 1) << "one write after the kill"; +} + +INSTANTIATE_TEST_SUITE_P(CASOwnerStopLoops, CASOwnerStopLoop, + ::testing::Values( + ConflictPauseArm{DecisionLoop::BodyReadModifyWrite, false}, + ConflictPauseArm{DecisionLoop::PresenceReadModifyWrite, false}, + ConflictPauseArm{DecisionLoop::Catalog, false}, + ConflictPauseArm{DecisionLoop::BodyReadModifyWrite, true}, + ConflictPauseArm{DecisionLoop::PresenceReadModifyWrite, true}, + ConflictPauseArm{DecisionLoop::Catalog, true}), + [](const ::testing::TestParamInfo & param_info) + { + const char * loop = param_info.param.loop == DecisionLoop::BodyReadModifyWrite ? "Body" + : param_info.param.loop == DecisionLoop::PresenceReadModifyWrite ? "Presence" : "Catalog"; + return std::string(loop) + (param_info.param.slow ? "Slow" : "Fast"); + }); + +namespace +{ + +/// Counts the reads of `key` after `arm` saw a new write of it, and runs `on_read_after_write` with that count. +class ReadAfterWriteHookBackend final : public CountingBackend +{ +public: + explicit ReadAfterWriteHookBackend(String key_) : key(std::move(key_)) {} + + std::function on_read_after_write; + std::atomic reads_after_write{0}; + + void arm() { writes_at_arm = writeCount(key); } + uint64_t writesSinceArm() const { return writeCount(key) - writes_at_arm.value_or(0); } + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key && writes_at_arm && writeCount(key) > *writes_at_arm) + { + const int n = ++reads_after_write; + if (on_read_after_write) + on_read_after_write(n); + } + return CountingBackend::read(k, access); + } + +private: + const String key; + std::optional writes_at_arm; +}; + +enum class UnresolvedStop : uint8_t +{ + /// During the owed settling read of the lost step-1 write. + BeforePause, + /// During the redecide pause. + InsidePause, + /// After the pause, past the first owner check that follows it. + AfterPause, + /// While the next submission waits behind a predecessor parked in its decision. + InQueue, + /// A killed query whose next base read fails: the client-like backend raises the kill, recorded by no owner check. + UnrecordedClientVerdict, + /// The fence is lost and the owner stops during the redecide pause. + FenceLostInsidePause, + /// Another server admits the namespace during the redecide pause; the owner stops between the check + /// before `decide` and the marker that `decide` then throws. + DecisionMarkerWhileStopping, + /// The second decision's write is refused with 412, and the query is killed in the read that settles the refusal. + KillSettlingSecondWrite, + /// As `KillSettlingSecondWrite`, but every write after the lost one is refused and the kill comes in the read + /// that settles the last submission the cap allows. + KillSettlingLastAllowedWrite, + /// The second decision's write is refused as `READONLY` by the store while the owner stops, so the engine returns + /// that refusal. + RefusedSecondWriteWhileStopping, + /// The second decision's write fails locally with `CORRUPTED_DATA`; the owner stays live. + LocalFaultInSecondWrite, +}; + +struct UnresolvedCreateOutcome +{ + std::optional outcome; + int code = 0; + String message; + uint64_t catalog_writes = 0; + int reads_after_write = 0; + bool returned_while_parked = false; + std::optional predecessor; + size_t lanes_after = 0; + int sleeps = 0; +}; + +/// `createNamespace` whose step-1 write loses its reply without landing; the settling read finds the +/// catalog unchanged, which proves nothing under `resend_unresolved = false`, so step 1 decides again +/// after the redecide pause. `stop_at` empty keeps the owner live. +UnresolvedCreateOutcome runUnresolvedCreate(std::optional stop_at) +{ + UnresolvedCreateOutcome out; + onThread(true, [&] + { + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto inner = std::make_shared(key); + { + auto setup_requests = openRequestsForTest(inner); + auto setup = setup_requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + } + std::optional query; + if (stop_at == UnresolvedStop::UnrecordedClientVerdict || stop_at == UnresolvedStop::KillSettlingSecondWrite + || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) + query.emplace(getContext().context); + BackendPtr backend = query ? BackendPtr(std::make_shared(inner)) : BackendPtr(inner); + + auto clock = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + std::atomic stop{false}; + std::atomic fence_lost{false}; + std::atomic caller_returned{false}; + std::atomic returned_while_parked{false}; + bool slept = false; + int checks_after_sleep = 0; + int sleeps = 0; + std::latch parked{1}; + std::latch release{1}; + std::optional predecessor; + std::optional watcher; + CasRequests * requests_ptr = nullptr; + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + std::atomic competitor_admitted{false}; + std::atomic base_read_after_competitor{false}; + int checks_after_base_read = 0; + + Fence fence = Fence::open(); + fence.admit = [&fence_lost](uint64_t, uint64_t) { return fence_lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }; + CasRequests requests(backend, fence, ManualClock::nowFnOf(clock), [&](uint64_t ms) + { + clock->advance(ms + 1); + if (++sleeps != 1) + return; + slept = true; + if (stop_at == UnresolvedStop::InsidePause) + stop = true; + if (stop_at == UnresolvedStop::DecisionMarkerWhileStopping) + { + CasRefCatalog::casAdmitEntry(competitor, layout, 1, + CatalogEntry{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(7)}); + competitor_admitted = true; + } + if (stop_at == UnresolvedStop::FenceLostInsidePause) + { + fence_lost = true; + stop = true; + } + if (stop_at == UnresolvedStop::InQueue) + { + predecessor.emplace([&] + { + auto predecessor_op = requests_ptr->admit(); + out.predecessor = hot_keys.submit(key, predecessor_op, Retry::standard(), + [&](const std::optional &) -> std::optional + { + parked.count_down(); + release.wait(); + return std::nullopt; + }); + }); + parked.wait(); + watcher.emplace([&] + { + const auto deadline = std::chrono::steady_clock::now() + WATCHDOG; + while (hot_keys.queueDepthForTest(key) < 2 && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + stop = true; + while (!caller_returned && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + returned_while_parked = caller_returned.load(); + release.count_down(); + }); + } + }, &hot_keys, kDefaultRequestWindowMs); + requests_ptr = &requests; + + std::optional owner; + if (!query) + owner.emplace(OwnerScope::background([&] + { + if (stop_at == UnresolvedStop::AfterPause && slept && ++checks_after_sleep >= 2) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + /// The first check after the caller's base read is the one before `decide`, which passes. + if (base_read_after_competitor && ++checks_after_base_read >= 2) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + if (stop) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + })); + inner->on_read_after_write = [&](int n) + { + if (competitor_admitted) + base_read_after_competitor = true; + if (stop_at == UnresolvedStop::BeforePause && n == 1) + stop = true; + if (stop_at == UnresolvedStop::UnrecordedClientVerdict && n == 2) + { + query->kill(); + throw Poco::TimeoutException("ReadAfterWriteHookBackend: the read timed out"); + } + if (stop_at == UnresolvedStop::KillSettlingSecondWrite && inner->writesSinceArm() == 2) + { + query->kill(); + throw Poco::TimeoutException("ReadAfterWriteHookBackend: the settling read timed out"); + } + if (stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) + { + if (inner->writesSinceArm() == kCasMaxDecisions) + { + query->kill(); + throw Poco::TimeoutException("ReadAfterWriteHookBackend: the settling read timed out"); + } + if (inner->writesSinceArm() >= 2) + inner->refuseNextWrite(key); + } + }; + + auto op = requests.admit(); + inner->arm(); + inner->injectAmbiguousWrite(key); + if (stop_at == UnresolvedStop::KillSettlingSecondWrite || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) + inner->refuseNextWrite(key); + if (stop_at == UnresolvedStop::RefusedSecondWriteWhileStopping) + inner->onBeforeWrite(key, [&] + { + if (inner->writesSinceArm() != 2) + return; + stop = true; + throw Exception(ErrorCodes::READONLY, "ReadAfterWriteHookBackend: the store is read-only"); + }); + if (stop_at == UnresolvedStop::LocalFaultInSecondWrite) + inner->onBeforeWrite(key, [&] + { + if (inner->writesSinceArm() == 2) + throw Exception(ErrorCodes::CORRUPTED_DATA, "ReadAfterWriteHookBackend: a local decode failure"); + }); + try + { + out.outcome = CasRefCatalog::createNamespace(op, layout, 1, RootNamespace{"a"}, + CreatorFence{.server_root_id = "srv1", .writer_epoch = 5, .fence_generation = 1}); + } + catch (...) + { + out.code = codeOf(std::current_exception()); + out.message = messageOf(std::current_exception()); + } + caller_returned = true; + if (watcher) + watcher->join(); + if (predecessor) + predecessor->join(); + out.returned_while_parked = returned_while_parked; + out.catalog_writes = inner->writesSinceArm(); + out.reads_after_write = inner->reads_after_write.load(); + out.lanes_after = hot_keys.laneCountForTest(); + out.sleeps = sleeps; + owner.reset(); + }); + return out; +} + +} + +/// A stop after a sent step-1 write whose outcome stays unresolved keeps the unresolved exit: one write, +/// no second decision, the 210 that names the unresolved send. A live owner decides again and creates the row. +TEST(CASOwnerStop, StoppedNamespaceCreateKeepsUnresolvedExit) +{ + for (const UnresolvedStop stop_at : {UnresolvedStop::BeforePause, UnresolvedStop::InsidePause, UnresolvedStop::AfterPause, + UnresolvedStop::InQueue, UnresolvedStop::UnrecordedClientVerdict}) + { + SCOPED_TRACE(static_cast(stop_at)); + const auto out = runUnresolvedCreate(stop_at); + EXPECT_FALSE(out.outcome.has_value()); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR); + EXPECT_NE(out.message.find("a sent write's outcome is unresolved"), String::npos) << out.message; + EXPECT_EQ(out.catalog_writes, 1u) << "one PUT"; + /// The settling read, plus the predecessor's base read or the failed base read where the arm has one: + /// no base read for a second decision of the caller's. + const int expected_reads = stop_at == UnresolvedStop::InQueue || stop_at == UnresolvedStop::UnrecordedClientVerdict ? 2 : 1; + EXPECT_EQ(out.reads_after_write, expected_reads); + EXPECT_EQ(out.lanes_after, 0u); + if (stop_at == UnresolvedStop::BeforePause) + EXPECT_EQ(out.sleeps, 0) << "the check before the redecide sleep ends the call"; + if (stop_at == UnresolvedStop::InQueue) + { + EXPECT_TRUE(out.returned_while_parked) << "the caller left while the predecessor was still parked"; + ASSERT_TRUE(out.predecessor.has_value()); + EXPECT_TRUE(std::holds_alternative(*out.predecessor)); + } + } + + { + SCOPED_TRACE("a lost fence observed in the pause stays the typed fence outcome"); + const auto out = runUnresolvedCreate(UnresolvedStop::FenceLostInsidePause); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.outcome.has_value()); + EXPECT_EQ(*out.outcome, CasRefCatalog::NamespaceCreationOutcome::FencedOut); + EXPECT_EQ(out.catalog_writes, 1u); + } + + { + SCOPED_TRACE("a marker the decision throws stays as it is"); + const auto out = runUnresolvedCreate(UnresolvedStop::DecisionMarkerWhileStopping); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.outcome.has_value()); + EXPECT_EQ(*out.outcome, CasRefCatalog::NamespaceCreationOutcome::Superseded); + EXPECT_EQ(out.catalog_writes, 2u) << "the lost step-1 write and the other server's admission"; + } + + { + SCOPED_TRACE("live owner"); + const auto out = runUnresolvedCreate(std::nullopt); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.outcome.has_value()); + EXPECT_EQ(*out.outcome, CasRefCatalog::NamespaceCreationOutcome::Live); + EXPECT_EQ(out.catalog_writes, 3u) << "the lost step-1 write, its second decision, step 3"; + } +} + +/// A refused write whose settling read fails after a kill does not answer the first write, whose outcome is still +/// unknown: the call keeps the unresolved exit and sends nothing more, also at the last submission the cap allows. +TEST(CASOwnerStop, ObservedStopConflictKeepsAnEarlierUnresolvedExit) +{ + for (const auto & [stop_at, writes] : {std::pair{UnresolvedStop::KillSettlingSecondWrite, uint64_t{2}}, + std::pair{UnresolvedStop::KillSettlingLastAllowedWrite, uint64_t{kCasMaxDecisions}}}) + { + SCOPED_TRACE(writes); + const auto out = runUnresolvedCreate(stop_at); + EXPECT_FALSE(out.outcome.has_value()); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR) << out.message; + EXPECT_NE(out.message.find("a sent write's outcome is unresolved"), String::npos) << out.message; + EXPECT_EQ(out.message.find("did not converge"), String::npos) << out.message; + EXPECT_EQ(out.catalog_writes, writes) << "the lost write and the refused ones, nothing after"; + } +} + +/// The store refuses the second decision's write while the owner stops. That refusal says nothing about the first +/// write, whose outcome is still unknown, so the call ends with the unresolved 210 rather than the refusal. +TEST(CASOwnerStop, RefusalUnderAStopKeepsAnEarlierUnresolvedExit) +{ + const auto out = runUnresolvedCreate(UnresolvedStop::RefusedSecondWriteWhileStopping); + EXPECT_FALSE(out.outcome.has_value()); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR) << out.message; + EXPECT_NE(out.message.find("a sent write's outcome is unresolved"), String::npos) << out.message; + EXPECT_NE(out.message.find("the store is read-only"), String::npos) << "names what ended the call: " << out.message; + EXPECT_EQ(out.catalog_writes, 2u) << "the lost write and the refused one, nothing after"; +} + +/// A local fault after an unresolved write is a bug or resource report, not a store answer: it reaches the caller +/// unchanged rather than as the retryable unresolved exit. +TEST(CASOwnerStop, LocalFaultAfterAnUnresolvedWriteIsNotReplaced) +{ + const auto out = runUnresolvedCreate(UnresolvedStop::LocalFaultInSecondWrite); + EXPECT_FALSE(out.outcome.has_value()); + EXPECT_EQ(out.code, ErrorCodes::CORRUPTED_DATA) << out.message; + EXPECT_NE(out.message.find("a local decode failure"), String::npos) << out.message; + EXPECT_EQ(out.message.find("a sent write's outcome is unresolved"), String::npos) << out.message; + EXPECT_EQ(out.catalog_writes, 2u) << "the lost write and the failed one, nothing after"; +} + +/// A catalog update that lost a race to another server stops before its next submission starts when the +/// owner stops in the conflict pause. A lost fence the settling read observed stays the typed fence outcome. +TEST(CASOwnerStop, ConflictedCatalogUpdateStopsAtTheNextSubmission) +{ + for (const bool fence_lost_in_flight : {false, true}) + { + SCOPED_TRACE(fence_lost_in_flight ? "fence lost while the write is in flight" : "stop in the conflict pause"); + onThread(false, [&] + { + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto backend = std::make_shared(); + const CatalogEntry observed{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(1)}; + auto competitor_requests = openRequestsForTest(backend); + auto competitor = competitor_requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(competitor, layout); + CasRefCatalog::casAdmitEntry(competitor, layout, 1, observed); + + std::atomic stop{false}; + std::atomic fence_lost{false}; + int pauses = 0; + uint64_t reads_at_pause = 0; + Fence fence = Fence::open(); + fence.admit = [&fence_lost](uint64_t, uint64_t) { return fence_lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }; + /// No cache: a next submission would start with a base read, so the read count shows whether it started. + CasHotKeys hot_keys(0); + CasRequests requests(backend, fence, {}, [&](uint64_t) + { + ++pauses; + reads_at_pause = backend->getCount(key); + stop = true; + }, &hot_keys, kDefaultRequestWindowMs); + auto op = requests.admit(); + + bool competing = false; + int competitor_writes = 0; + backend->onBeforeWrite(key, [&] + { + if (competing || competitor_writes > 0) + return; + competing = true; + CasRefCatalog::casAdmitEntry(competitor, layout, 1, + CatalogEntry{.ns = RootNamespace{"b"}, .state = NsState::Live, .incarnation = UInt128(2)}); + ++competitor_writes; + competing = false; + if (fence_lost_in_flight) + { + fence_lost = true; + stop = true; + } + }); + const uint64_t writes_before = backend->writeCount(key); + + auto owner = backgroundStoppedBy(stop); + std::optional outcome; + std::exception_ptr error; + try + { + outcome = CasRefCatalog::beginRemoving(op, layout, observed, /*removal_started_round*/ 13); + } + catch (...) + { + error = std::current_exception(); + } + EXPECT_EQ(backend->writeCount(key) - writes_before, 2u) << "the competitor's write and one of the caller's"; + if (fence_lost_in_flight) + { + EXPECT_EQ(codeOf(error), 0) << messageOf(error); + ASSERT_TRUE(outcome.has_value()); + EXPECT_EQ(*outcome, CasRefCatalog::BeginRemovingOutcome::FencedOut); + EXPECT_EQ(pauses, 0); + } + else + { + EXPECT_EQ(codeOf(error), ErrorCodes::ABORTED) << messageOf(error); + EXPECT_EQ(pauses, 1); + EXPECT_EQ(backend->getCount(key), reads_at_pause) << "no base read for a next submission"; + } + const auto snap = CasRefCatalog::read(competitor, layout); + ASSERT_EQ(snap.catalog.entries.size(), 2u); + EXPECT_EQ(snap.catalog.entries.at(0).state, NsState::Live) << "the next submission never started"; + }); + } +} + +namespace +{ + +/// The first remove of `key` meets a new incarnation another writer put there, so it answers `Mismatch`. +class ReplacedBeforeFirstRemoveBackend final : public CountingBackend +{ +public: + explicit ReplacedBeforeFirstRemoveBackend(String key_) : key(std::move(key_)) {} + + std::function on_replaced; + + RawRemoval remove(const String & k, const String & expected_value, TransportAccess & access) override + { + if (k == key && !replaced.exchange(true)) + { + const auto current = InMemoryBackend::head(k, access); + (void)InMemoryBackend::write(k, "replaced", current->value, access); + if (on_replaced) + on_replaced(); + } + return CountingBackend::remove(k, expected_value, access); + } + +private: + const String key; + std::atomic replaced{false}; +}; + +} + +/// A stop around the reissue pause of `removeCurrent` sends no second HEAD: before the pause the call +/// ends without sleeping, during the pause it ends before the HEAD. +TEST(CASOwnerStop, StopAroundRemoveReissuePauseSendsNoHead) +{ + for (const bool during_sleep : {false, true}) + { + SCOPED_TRACE(during_sleep ? "stop during the sleep" : "stop before the pause"); + onThread(false, [&] + { + auto backend = std::make_shared("k"); + std::atomic stop{false}; + int sleeps = 0; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + ++sleeps; + if (during_sleep) + stop = true; + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("k", "v", Retry::once()))); + if (!during_sleep) + backend->on_replaced = [&stop] { stop = true; }; + + auto owner = backgroundStoppedBy(stop); + int code = 0; + try + { + (void)op.removeCurrent("k", Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + EXPECT_EQ(code, ErrorCodes::ABORTED); + EXPECT_EQ(backend->headCount("k"), 1u); + EXPECT_EQ(backend->deleteCount("k"), 1u); + EXPECT_EQ(sleeps, during_sleep ? 1 : 0); + }); + } +} + +namespace +{ + +/// The first write of `key` runs `on_first_write`, stores its bytes when `land` is set, and throws `failure`. +/// Every read of `key` runs `on_read` first. +class FirstWriteFailsBackend final : public InMemoryBackend +{ +public: + explicit FirstWriteFailsBackend(String key_) : key(std::move(key_)) {} + + std::exception_ptr failure = std::make_exception_ptr(Poco::TimeoutException("FirstWriteFailsBackend: the write timed out")); + bool land = false; + std::function on_first_write; + std::function on_write; + std::function on_read; + std::atomic writes{0}; + std::atomic reads{0}; + std::atomic refreshes{0}; + + std::expected write(const String & k, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + if (k == key) + { + if (on_write) + on_write(); + if (writes.fetch_add(1) == 0 && failure) + { + if (land) + (void)InMemoryBackend::write(k, bytes, expected_value, access); + if (on_first_write) + on_first_write(); + std::rethrow_exception(failure); + } + } + return InMemoryBackend::write(k, bytes, expected_value, access); + } + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key) + { + ++reads; + if (on_read) + on_read(); + } + return InMemoryBackend::read(k, access); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } + +private: + const String key; +}; + +/// One write call under an owner that `stop` stops: a background owner, or a query whose failed answers +/// the client-like backend replaces with its verdict. +struct StoppableWrite +{ + StoppedBy owner = StoppedBy::Background; + /// Arms the backend; `stop` stops the owner. + std::function & stop)> prepare_backend; + /// Runs during each pause, with `stop`. + std::function & stop)> during_pause; + /// Whether the `create` of the key runs inside `OwnerScope::owed`. + bool owed = false; + /// The cause a killed query throws instead of `QUERY_WAS_CANCELLED`. + std::exception_ptr kill_cause; +}; + +struct StoppableWriteOutcome +{ + std::optional result; + int code = 0; + String message; + std::exception_ptr error; + int writes = 0; + int reads = 0; + int pauses = 0; + int refreshes = 0; +}; + +constexpr auto STOPPABLE_KEY = "k"; + +StoppableWriteOutcome runStoppableWrite(const StoppableWrite & arm) +{ + StoppableWriteOutcome out; + onThread(true, [&] + { + std::optional query; + if (arm.owner == StoppedBy::Query) + query.emplace(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + BackendPtr backend = query ? BackendPtr(std::make_shared(inner)) : BackendPtr(inner); + std::atomic stopped{false}; + const std::function stop = [&] + { + stopped = true; + if (query) + query->kill(arm.kill_cause); + }; + std::atomic pauses{0}; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + ++pauses; + if (arm.during_pause) + arm.during_pause(stop); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + if (arm.prepare_backend) + arm.prepare_backend(*inner, stop); + inner->writes = 0; + inner->reads = 0; + + std::optional background; + if (arm.owner == StoppedBy::Background) + background.emplace(backgroundStoppedBy(stopped)); + try + { + std::optional owed; + if (arm.owed) + owed.emplace(OwnerScope::owed()); + out.result = op.create(STOPPABLE_KEY, "bytes", Retry::standard()); + } + catch (...) + { + out.error = std::current_exception(); + out.code = codeOf(out.error); + out.message = messageOf(out.error); + } + out.writes = inner->writes.load(); + out.reads = inner->reads.load(); + out.pauses = pauses.load(); + out.refreshes = inner->refreshes.load(); + }); + return out; +} + +void expectUnresolved(const StoppableWriteOutcome & out) +{ + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * gave_up = std::get_if(&*out.result); + ASSERT_NE(gave_up, nullptr) << "index " << out.result->index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(gave_up->attempts_sent, 1u); +} + +void expectCommittedByRead(const StoppableWriteOutcome & out) +{ + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * committed = std::get_if(&*out.result); + ASSERT_NE(committed, nullptr) << "index " << out.result->index(); + EXPECT_TRUE(committed->resolved_by_read); + EXPECT_EQ(committed->attempts_sent, 1u); +} + +} + +/// A store's definite refusal of a write whose every attempt was answered is the call's answer, also when a background +/// owner stopped during that attempt: nothing landed, so there is nothing to settle and no credential refresh to try. +/// After an earlier unanswered attempt the same refusal proves nothing about it, so the write still settles. +TEST(CASOwnerStop, BackgroundStopKeepsADefiniteRefusal) +{ + std::vector>> refusals{ + {"READONLY", [] { return std::make_exception_ptr(DB::Exception(DB::ErrorCodes::READONLY, "the store is read-only")); }}}; +#if USE_AWS_S3 + refusals.emplace_back("AccessDenied", [] + { + return std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); + }); +#endif + for (const auto & [name, refusal] : refusals) + { + { + SCOPED_TRACE(fmt::format("{}, every attempt answered", name)); + StoppableWrite arm; + arm.prepare_backend = [make = refusal](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.failure = make(); + backend.on_first_write = stop; + }; + const auto out = runStoppableWrite(arm); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + EXPECT_TRUE(std::holds_alternative(*out.result)) << "index " << out.result->index(); + EXPECT_EQ(out.writes, 1); + EXPECT_EQ(out.reads, 0) << "a refusal needs no settling read"; + EXPECT_EQ(out.refreshes, 0); + } + { + SCOPED_TRACE(fmt::format("{}, after an unanswered attempt", name)); + StoppableWrite arm; + arm.prepare_backend = [make = refusal](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.on_write = [&backend, stop, make] + { + if (backend.writes.load() == 1) + { + stop(); + std::rethrow_exception(make()); + } + }; + }; + const auto out = runStoppableWrite(arm); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * gave_up = std::get_if(&*out.result); + ASSERT_NE(gave_up, nullptr) << "index " << out.result->index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); + EXPECT_EQ(gave_up->attempts_sent, 2u); + } + } +} + +/// A stop that lands while a possibly-sent write waits to resend ends it without the resend: one `PUT`. +/// The settling read is owed only where it had not run yet, which is the connect-hint pause. +TEST(CASOwnerStop, StopInsideEachPauseSettlesWithoutResend) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + { + SCOPED_TRACE(fmt::format("{}, inside pauseAndReissue", nameOf(owner))); + StoppableWrite arm; + arm.owner = owner; + arm.during_pause = [](const auto & stop) { stop(); }; + const auto out = runStoppableWrite(arm); + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1) << "the settling read before the pause, none after it"; + EXPECT_EQ(out.pauses, 1); + } + { + SCOPED_TRACE(fmt::format("{}, after a repeatable settlement", nameOf(owner))); + StoppableWrite arm; + arm.owner = owner; + arm.prepare_backend = [](FirstWriteFailsBackend & backend, const std::function & stop) { backend.on_read = stop; }; + const auto out = runStoppableWrite(arm); + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1); + EXPECT_EQ(out.pauses, 0) << "no pause before a resend that cannot happen"; + } +#if USE_AWS_S3 + for (const bool landed : {false, true}) + { + SCOPED_TRACE(fmt::format("{}, inside pauseFlat, {}", nameOf(owner), landed ? "landed" : "not landed")); + StoppableWrite arm; + arm.owner = owner; + arm.prepare_backend = [landed](FirstWriteFailsBackend & backend, const std::function &) + { + backend.land = landed; + backend.failure = std::make_exception_ptr( + DB::S3Exception("Connection refused", Aws::S3::S3Errors::NETWORK_CONNECTION)); + }; + arm.during_pause = [](const auto & stop) { stop(); }; + const auto out = runStoppableWrite(arm); + if (landed) + expectCommittedByRead(out); + else + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1) << "the owed settling read the hinted attempt had not had"; + EXPECT_EQ(out.pauses, 1); + } +#endif + } +} + +/// A query killed with a stored cause while its write's reply is lost: the client-like backend surfaces the cause, and it +/// is the query's verdict whatever its code or type. A local-bug code is no local bug of the attempt, an exception the +/// transport cannot raise is caught before any classification, and `READONLY` is no refusal. The write is settled. +TEST(CASOwnerStop, LostReplyWithStoredCauseSettles) +{ + const std::vector>> causes{ + {"BAD_ARGUMENTS", [] { return storedCause(ErrorCodes::BAD_ARGUMENTS); }}, + {"runtime_error", [] { return std::make_exception_ptr(std::runtime_error("the query's stored cause")); }}, + {"READONLY", [] { return storedCause(ErrorCodes::READONLY); }}}; + for (const auto & [name, cause] : causes) + { + for (const bool landed : {false, true}) + { + SCOPED_TRACE(fmt::format("{}, {}", name, landed ? "landed" : "not landed")); + StoppableWrite arm; + arm.owner = StoppedBy::Query; + arm.kill_cause = cause(); + arm.prepare_backend = [landed](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.land = landed; + backend.on_first_write = stop; + }; + const auto out = runStoppableWrite(arm); + if (landed) + expectCommittedByRead(out); + else + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1) << "the owed settling read"; + EXPECT_EQ(out.pauses, 0); + } + } +} + +#if USE_AWS_S3 + +namespace +{ + +/// Finalizes by running `on_finalize`, asking the thread's query as the S3 client does, then running `on_reply` and +/// failing with the store's own `412 PreconditionFailed`. +class PreconditionFailedWriteBuffer final : public DB::WriteBufferFromFileBase +{ +public: + PreconditionFailedWriteBuffer(std::function on_finalize_, std::function on_reply_) + : DB::WriteBufferFromFileBase(DB::DBMS_DEFAULT_BUFFER_SIZE, nullptr, 0) + , on_finalize(std::move(on_finalize_)) + , on_reply(std::move(on_reply_)) + { + } + + void sync() override { next(); } + std::string getFileName() const override { return "precondition-failed-write-buffer"; } + +private: + void nextImpl() override {} + + void finalizeImpl() override + { + next(); + if (on_finalize) + on_finalize(); + CurrentThread::checkIfNotCancelled(); + if (on_reply) + on_reply(); + throw DB::S3Exception("the store answered 412", Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); + } + + std::function on_finalize; + std::function on_reply; +}; + +class PreconditionFailedLocalObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + std::function on_finalize; + std::function on_reply; + std::atomic writes{0}; + + std::unique_ptr writeObject( + const DB::StoredObject &, DB::WriteMode, std::optional, size_t, const DB::WriteSettings &) override + { + ++writes; + return std::make_unique(on_finalize, on_reply); + } +}; + +} + +/// The native classifier reads a stopped query's `412` as no store answer: the S3 client throws the query's +/// stored cause in place of whatever the store said. A stopped background owner is invisible to the client, +/// so its genuine `412` stays a conflict. +TEST(CASOwnerStop, StoredPreconditionFailedIsNotAConflict) +{ + for (const StoppedBy owner : {StoppedBy::Query, StoppedBy::Background}) + { + SCOPED_TRACE(nameOf(owner)); + auto storage = makeLocalObjectStorageOf(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "absent"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + std::optional written; + int code = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + std::atomic stopped{false}; + storage->on_finalize = [&] + { + stopped = true; + if (owner == StoppedBy::Query) + query.kill(std::make_exception_ptr( + DB::S3Exception("the query's stored cause", Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"))); + }; + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + std::optional background; + if (owner == StoppedBy::Background) + background.emplace(backgroundStoppedBy(stopped)); + try + { + written = op.create(key, "bytes", Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + EXPECT_EQ(storage->writes.load(), 1); + if (owner == StoppedBy::Query) + { + const auto * gave_up = std::get_if(&*written); + ASSERT_NE(gave_up, nullptr) << "a stopped query's stored 412 is no conflict; index " << written->index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); + } + else + { + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "index " << written->index(); + EXPECT_FALSE(conflict->any_ambiguous); + } + } +} + +/// The store's own `412` reached the classifier, and the query was killed only after the S3 client let it through: +/// the refusal is still the store's answer, so the write ends as a conflict, not as an unresolved send. +TEST(CASOwnerStop, AKillAfterTheStoresOwn412KeepsTheConflict) +{ + auto storage = makeLocalObjectStorageOf(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "absent"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + std::optional written; + int code = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + storage->on_reply = [&] { query.kill(); }; + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + written = op.create(key, "bytes", Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + EXPECT_EQ(storage->writes.load(), 1); + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "a genuine 412 is a conflict; index " << written->index(); + EXPECT_FALSE(conflict->any_ambiguous); +} + +/// The probe's half of the test above: the store's own `NoSuchBucket` passed the S3 client, then the query was +/// killed before the probe classified it, and the answer stays the store's. +TEST(CASOwnerStop, AKillAfterTheStoresOwnProbeAnswerKeepsIt) +{ + auto storage = makeLocalObjectStorageOf(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "sentinel"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + std::optional probed; + int code = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + storage->on_read = [&] + { + CurrentThread::checkIfNotCancelled(); + query.kill(); + throw DB::S3Exception("the store answered NoSuchBucket", Aws::S3::S3Errors::NO_SUCH_BUCKET); + }; + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + probed = op.probeSentinel(key, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(probed.has_value()); + EXPECT_EQ(probed->outcome, ProbeOutcome::ContainerAbsent); + EXPECT_EQ(storage->reads.load(), 1); +} + +#endif + +namespace +{ + +/// Counts the requests that change the store, and fails the next one with a transport-class error while `fail_next` +/// is set. +class MutationCountingBackend final : public InMemoryBackend +{ +public: + std::atomic mutations{0}; + std::atomic fail_next{false}; + + std::expected write(const String & k, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + countAndMaybeFail(); + return InMemoryBackend::write(k, bytes, expected_value, access); + } + + RawRemoval remove(const String & k, const String & expected_value, TransportAccess & access) override + { + countAndMaybeFail(); + return InMemoryBackend::remove(k, expected_value, access); + } + + void removeManyWriteOnce(const std::vector & keys, TransportAccess & access) override + { + countAndMaybeFail(); + InMemoryBackend::removeManyWriteOnce(keys, access); + } + + void publish(const BlobPublishRequest & request, TransportAccess & access) override + { + countAndMaybeFail(); + InMemoryBackend::publish(request, access); + } + +private: + void countAndMaybeFail() + { + ++mutations; + if (fail_next.exchange(false)) + throw Exception(ErrorCodes::S3_ERROR, "the first mutation failed"); + } +}; + +enum class MutatingVerb : uint8_t { Create, Replace, Remove, BulkRemove, Publish }; + +struct MutationRun +{ + int code = 0; + int mutations = 0; +}; + +/// Calls `verb` once on a store holding `present`, through a backend that answers a failure under a killed query with +/// the query's verdict, as the S3 client does. `stopped_before` stops its owner before the call; `fail_first` fails +/// the call's first mutation and kills the query in the pause after it. +MutationRun runMutatingVerb(MutatingVerb verb, std::optional stopped_before, bool fail_first) +{ + MutationRun run; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(); + CasRequests requests(std::make_shared(backend), Fence::open(), {}, [&](uint64_t) + { + if (fail_first) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + const auto present = op.create("present", "v", Retry::once()); + ASSERT_TRUE(std::holds_alternative(present)); + const Etag seen = std::get(present).etag; + backend->mutations = 0; + backend->fail_next = fail_first; + + std::atomic stopped{true}; + std::optional background; + if (stopped_before == StoppedBy::Background) + background.emplace(backgroundStoppedBy(stopped)); + else if (stopped_before == StoppedBy::Query) + query.kill(); + const String payload = "payload"; + try + { + switch (verb) + { + case MutatingVerb::Create: (void)op.create("new", "v", Retry::standard()); break; + case MutatingVerb::Replace: (void)op.replace("present", "w", seen, Retry::standard()); break; + case MutatingVerb::Remove: (void)op.remove("present", seen, Retry::standard()); break; + case MutatingVerb::BulkRemove: + op.removeManyWriteOnce({Layout("p").writeOnceBlobIntentProbeKey("probe")}, Retry::standard()); + break; + case MutatingVerb::Publish: + op.publish(BlobPublishRequest{ + .destination_key = "blob", + .publication = StreamingBlobPublication{ + .payload_size = payload.size(), + .fresh_envelope = "fresh", + .open_payload = [payload] { return std::make_unique(payload); }, + .expected_ref = DB::Cas::tests::idOf(payload)}}, Retry::standard()); + break; + } + } + catch (...) + { + run.code = codeOf(std::current_exception()); + } + run.mutations = backend->mutations.load(); + }); + return run; +} + +/// Calls each mutating verb once `owner` stopped. +void runEachMutatingVerbAfterStop(StoppedBy owner) +{ + using enum MutatingVerb; + for (const MutatingVerb verb : {Create, Replace, Remove, BulkRemove, Publish}) + { + SCOPED_TRACE(fmt::format("{}, verb {}", nameOf(owner), static_cast(verb))); + const MutationRun run = runMutatingVerb(verb, owner, /*fail_first=*/false); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(run.code, ErrorCodes::ABORTED); + EXPECT_EQ(run.mutations, 0) << "nothing sent"; + } + else + { + EXPECT_EQ(run.code, 0) << "a healthy first attempt of a killed query succeeds"; + EXPECT_EQ(run.mutations, 1) << "exactly the first attempt is sent"; + } + } +} + +} + +/// A background owner that stopped before a mutating call gets its verdict before anything is sent. +TEST(CASOwnerStop, BackgroundStopBeforeFirstSendSendsNothing) +{ + runEachMutatingVerbAfterStop(StoppedBy::Background); +} + +/// A killed query's first attempt of each mutating verb is sent and, on a healthy store, succeeds, as on plain S3. +TEST(CASOwnerStop, KilledQuerysFirstAttemptIsSent) +{ + runEachMutatingVerbAfterStop(StoppedBy::Query); +} + +/// A body read-modify-write whose write meets a competitor's replacement while the owner stops sends one +/// `PUT` and decides once. A background owner's verdict surfaces at the next decision. A killed query's write +/// failed with the kill, so its settled conflict is the answer and no decision follows. A stored credential cause +/// is no credential answer: no refresh, no resend. +TEST(CASOwnerStop, ConflictThenStopUnderStandardRmwDecidesOnce) +{ + struct Arm + { + const char * name; + StoppedBy owner; + std::function cause; + /// 0: the call returns a `Conflict`. + int code; + }; + std::vector arms = { + {"background owner", StoppedBy::Background, [] { return std::exception_ptr{}; }, ErrorCodes::ABORTED}, + {"killed query", StoppedBy::Query, [] { return std::exception_ptr{}; }, 0}, + }; +#if USE_AWS_S3 + arms.push_back({"killed query, stored AccessDenied", StoppedBy::Query, + [] { return std::make_exception_ptr(DB::S3Exception("the query's stored cause", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); }, + 0}); +#endif + for (const auto & arm : arms) + { + SCOPED_TRACE(arm.name); + int code = 0; + std::optional written; + int decisions = 0; + int writes = 0; + int refreshes = 0; + onThread(true, [&] + { + std::optional query; + if (arm.owner == StoppedBy::Query) + query.emplace(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + inner->failure = nullptr; + BackendPtr backend = query ? BackendPtr(std::make_shared(inner)) : BackendPtr(inner); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + ASSERT_TRUE(std::holds_alternative(competitor.create(STOPPABLE_KEY, "v0", Retry::once()))); + + std::atomic stopped{false}; + bool competing = false; + inner->writes = 0; + inner->on_write = [&] + { + if (competing || stopped) + return; + competing = true; + const auto current = competitor.read(STOPPABLE_KEY, Retry::once()); + ASSERT_TRUE(std::holds_alternative(competitor.replace(STOPPABLE_KEY, "competitor", current->etag, Retry::once()))); + competing = false; + stopped = true; + if (query) + query->kill(arm.cause()); + }; + std::optional background; + if (arm.owner == StoppedBy::Background) + background.emplace(backgroundStoppedBy(stopped)); + const int writes_before = inner->writes.load(); + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [&](const std::optional & current) + { + ++decisions; + return std::optional(current ? current->bytes + "+" : String("v")); + }, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + /// The competitor's own write passes through the same backend. + writes = inner->writes.load() - writes_before - 1; + refreshes = inner->refreshes.load(); + }); + EXPECT_EQ(code, arm.code); + if (arm.code == 0) + { + ASSERT_TRUE(written.has_value()); + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "index " << written->index(); + EXPECT_TRUE(conflict->observed_stop); + EXPECT_TRUE(std::holds_alternative(conflict->seen)) << "the settling read saw the competitor"; + } + EXPECT_EQ(decisions, 1); + EXPECT_EQ(writes, 1) << "one PUT"; + EXPECT_EQ(refreshes, 0); + } +} + +/// A clean 412 whose settling read fails after the kill: a one-shot caller gets the `Conflict`, and a loop starts no +/// reread, decision or write after it. +TEST(CASOwnerStop, KilledQuerysConflictWithFailedSettlementEndsTheLoop) +{ + for (const bool once : {true, false}) + { + SCOPED_TRACE(once ? "Retry::once" : "Retry::standard"); + std::optional written; + int code = 0; + int decisions = 0; + int writes = 0; + int reads = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + inner->failure = nullptr; + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [](uint64_t) {}, nullptr, + kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create(STOPPABLE_KEY, "v0", Retry::once()))); + inner->refuseNextWrite(STOPPABLE_KEY); + inner->writes = 0; + inner->reads = 0; + inner->on_read = [&] + { + if (inner->writes.load() == 0) + return; + query.kill(); + throw Poco::TimeoutException("FirstWriteFailsBackend: the settling read timed out"); + }; + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [&](const std::optional & current) + { + ++decisions; + return std::optional(current->bytes + "+"); + }, once ? Retry::once() : Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + reads = inner->reads.load(); + }); + EXPECT_EQ(code, 0) << "the conflict is the answer, not the kill"; + ASSERT_TRUE(written.has_value()); + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "index " << written->index(); + EXPECT_TRUE(std::holds_alternative(conflict->seen)); + EXPECT_EQ(decisions, 1); + EXPECT_EQ(writes, 1) << "the refused PUT only"; + EXPECT_EQ(reads, 2) << "the base read and the failed settling read, no reread"; + } +} + +/// A catalog update whose 412 is followed by a settling read that fails after the kill submits nothing more: no +/// reread, no decision, no write. +TEST(CASOwnerStop, KilledQuerysCatalogUpdateStopsAfterAFailedSettlement) +{ + int code = 0; + int writes = 0; + int reads = 0; + int reads_at_failed_settlement = -1; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto inner = std::make_shared(key); + inner->failure = nullptr; + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [](uint64_t) {}, &hot_keys, + kDefaultRequestWindowMs); + auto op = requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(op, layout); + CasRefCatalog::casAdmitEntry(op, layout, 1, + CatalogEntry{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(1)}); + inner->refuseNextWrite(key); + inner->writes = 0; + inner->reads = 0; + inner->on_read = [&] + { + if (inner->writes.load() == 0 || query.status->isKilled()) + return; + reads_at_failed_settlement = inner->reads.load(); + query.kill(); + throw Poco::TimeoutException("FirstWriteFailsBackend: the settling read timed out"); + }; + try + { + (void)CasRefCatalog::casUpdate(op, layout, [](const RefCatalog & current) { return current; }); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + reads = inner->reads.load(); + }); + EXPECT_EQ(code, ErrorCodes::ABORTED) << "the conflict ends the update"; + EXPECT_EQ(writes, 1) << "the refused PUT only"; + EXPECT_GE(reads_at_failed_settlement, 1); + EXPECT_EQ(reads, reads_at_failed_settlement) << "no read after the failed settlement"; +} + +/// A catalog erase whose 412 is followed by a settling read that fails after the kill still runs its mandatory +/// resolution read, and sends no second erase. +TEST(CASOwnerStop, KilledQuerysCatalogEraseSendsNoSecondErase) +{ + std::optional outcome; + int code = 0; + int writes = 0; + int reads = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto inner = std::make_shared(key); + inner->failure = nullptr; + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [](uint64_t) {}, nullptr, + kDefaultRequestWindowMs); + auto op = requests.admit(); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, .state = NsState::Removing, .incarnation = UInt128{7}, .removal_started_round = 13}; + ASSERT_TRUE(std::holds_alternative(op.create(key, encodeRefCatalog(RefCatalog{.entries = {removing}}), Retry::once()))); + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + CasRefCatalog::Snapshot cut = CasRefCatalog::read(op, layout); + + /// A competitor adds a row between the cut and the erase, so the erase meets a genuine 412. + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + const CatalogEntry other{.ns = RootNamespace{"b"}, .state = NsState::Live, .incarnation = UInt128{8}}; + const auto seen_by_competitor = competitor.read(key, Retry::once()); + ASSERT_TRUE(seen_by_competitor.has_value()); + ASSERT_TRUE(std::holds_alternative(competitor.replace( + key, encodeRefCatalog(RefCatalog{.entries = {removing, other}}), seen_by_competitor->etag, Retry::once()))); + inner->writes = 0; + inner->reads = 0; + bool settlement_failed = false; + inner->on_read = [&] + { + if (inner->writes.load() == 0 || std::exchange(settlement_failed, true)) + return; + query.kill(); + throw Poco::TimeoutException("FirstWriteFailsBackend: the settling read timed out"); + }; + try + { + outcome = CasRefCatalog::deleteCompletedRemovingAtSnapshot(op, layout, std::move(cut), removing, ready_parent, {}, {}, {}) + .outcome; + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + reads = inner->reads.load(); + }); + EXPECT_FALSE(outcome.has_value()) << "outcome " << static_cast(*outcome); + EXPECT_EQ(code, ErrorCodes::ABORTED) << "the conflict ends the erase"; + EXPECT_EQ(writes, 1) << "no second erase"; + EXPECT_EQ(reads, 2) << "the failed settling read and the mandatory resolution read"; +} + +/// A stopped background owner's unresolved catalog erase is followed by a resolution read that fails locally. The +/// local fault is the call's answer, not the erase's unresolved outcome. +TEST(CASOwnerStop, StoppedCatalogEraseKeepsALocalFaultOfItsResolutionRead) +{ + int code = 0; + int writes = 0; + int failed_reads = 0; + onThread(true, [&] + { + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto inner = std::make_shared(key); + CasRequests requests(inner, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, .state = NsState::Removing, .incarnation = UInt128{7}, .removal_started_round = 13}; + const auto failure = std::exchange(inner->failure, nullptr); + ASSERT_TRUE(std::holds_alternative(op.create(key, encodeRefCatalog(RefCatalog{.entries = {removing}}), Retry::once()))); + inner->failure = failure; + inner->writes = 0; + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + CasRefCatalog::Snapshot cut = CasRefCatalog::read(op, layout); + + /// The erase's own settling read stops the owner, so the erase ends unresolved without a resend. + std::atomic stopped{false}; + int reads_after_erase = 0; + inner->on_read = [&] + { + if (inner->writes.load() == 0) + return; + if (++reads_after_erase == 1) + { + stopped = true; + return; + } + ++failed_reads; + throw Exception(ErrorCodes::CORRUPTED_DATA, "the resolution read decoded a malformed catalog"); + }; + auto background = backgroundStoppedBy(stopped); + try + { + (void)CasRefCatalog::deleteCompletedRemovingAtSnapshot(op, layout, std::move(cut), removing, ready_parent, {}, {}, {}); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + }); + EXPECT_EQ(writes, 1) << "one erase, whose outcome is unresolved"; + EXPECT_EQ(failed_reads, 1) << "only the resolution read fails, after the erase's settling read"; + EXPECT_EQ(code, ErrorCodes::CORRUPTED_DATA) << "the local fault was replaced"; +} + +/// A transport fault, then a 412 settled by a successful read: the conflict is an answer, so a kill in the pause after +/// it does not stop the next decision, whose write commits on a healthy store. +TEST(CASOwnerStop, SettledConflictAfterAFaultPermitsTheNextDecisionAfterAKill) +{ + std::optional written; + int code = 0; + int decisions = 0; + int writes = 0; + int reads = 0; + int pauses = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [&](uint64_t) + { + /// The first pause precedes the resend of the timed-out attempt, the second follows the settled conflict. + if (++pauses == 2) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + /// The backend fails only the first write it sees; the seed is not it. + const auto failure = std::exchange(inner->failure, nullptr); + const auto created = competitor.create(STOPPABLE_KEY, "v0", Retry::once()); + ASSERT_TRUE(std::holds_alternative(created)); + const Etag base = std::get(created).etag; + inner->failure = failure; + inner->writes = 0; + inner->reads = 0; + bool competing = false; + inner->on_write = [&] + { + if (competing || inner->writes.load() != 1) + return; + competing = true; + ASSERT_TRUE(std::holds_alternative(competitor.replace(STOPPABLE_KEY, "competitor", base, Retry::once()))); + }; + auto op = requests.admit(); + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [&](const std::optional & current) + { + ++decisions; + return std::optional(current->bytes + "+"); + }, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + /// The competitor's write passes through the same backend. + writes = inner->writes.load() - 1; + reads = inner->reads.load(); + }); + EXPECT_EQ(code, 0) << "the kill does not stop a decision after a settled conflict"; + ASSERT_TRUE(written.has_value()); + EXPECT_TRUE(std::holds_alternative(*written)) << "index " << written->index(); + EXPECT_EQ(pauses, 2); + EXPECT_EQ(decisions, 2); + EXPECT_EQ(writes, 3) << "the timed-out PUT, its refused resend, and the PUT of the next decision"; + EXPECT_EQ(reads, 3) << "the base read and two settling reads"; +} + +/// A genuine refused precondition stays a conflict when the owner stops while its settling read is in +/// flight: the read is owed, and its failure is "nothing observed", not the owner's verdict. +TEST(CASOwnerStop, GenuineConflictThenStopDuringSettlementIsAConflict) +{ + std::optional written; + int code = 0; + int reads = 0; + onThread(false, [&] + { + auto backend = std::make_shared(STOPPABLE_KEY); + backend->failure = nullptr; + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create(STOPPABLE_KEY, "v0", Retry::once()))); + backend->refuseNextWrite(STOPPABLE_KEY); + backend->reads = 0; + + std::atomic stopped{false}; + backend->on_read = [&] + { + if (backend->writes.load() < 2) + return; + stopped = true; + throw Poco::TimeoutException("FirstWriteFailsBackend: the settling read timed out"); + }; + auto owner = backgroundStoppedBy(stopped); + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [](const std::optional & current) + { + return std::optional(current->bytes + "+"); + }, Retry::once()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + reads = backend->reads.load(); + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "index " << written->index(); + EXPECT_TRUE(std::holds_alternative(conflict->seen)); + EXPECT_EQ(conflict->attempts_sent, 1u); + EXPECT_EQ(reads, 2) << "the base read and the failed settling read"; +} + +/// A `PUT` that succeeds while the owner stops is committed and reaches the caller's bookkeeping. +TEST(CASOwnerStop, SuccessfulPutJustBeforeStopReachesBookkeeping) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + SCOPED_TRACE(nameOf(owner)); + StoppableWrite arm; + arm.owner = owner; + arm.prepare_backend = [](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.failure = nullptr; + backend.on_write = stop; + }; + const auto out = runStoppableWrite(arm); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * committed = std::get_if(&*out.result); + ASSERT_NE(committed, nullptr) << "index " << out.result->index(); + EXPECT_FALSE(committed->resolved_by_read); + EXPECT_EQ(out.writes, 1); + EXPECT_EQ(out.reads, 0); + } +} + +/// Owed work runs without the owner's stop: an owed write whose attempt failed while the owner was live +/// is resent after a stop in its pause, as an owed read is reissued. +TEST(CASOwnerStop, OwedWriteResendsAfterAStopInItsPause) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + SCOPED_TRACE(nameOf(owner)); + StoppableWrite arm; + arm.owner = owner; + arm.during_pause = [](const auto & stop) { stop(); }; + arm.owed = true; + const auto out = runStoppableWrite(arm); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * committed = std::get_if(&*out.result); + ASSERT_NE(committed, nullptr) << "index " << out.result->index(); + EXPECT_EQ(out.writes, 2) << "the resend"; + EXPECT_EQ(out.pauses, 1); + } +} + +/// An attempt that fails after the owner stopped is settled and never resent, inside `owed` too. +TEST(CASOwnerStop, OwedWriteFailedForAStoppedOwnerIsNotResent) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + SCOPED_TRACE(nameOf(owner)); + StoppableWrite arm; + arm.owner = owner; + arm.prepare_backend = [](FirstWriteFailsBackend & backend, const std::function & stop) { backend.on_first_write = stop; }; + arm.owed = true; + const auto out = runStoppableWrite(arm); + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1) << "the owed settling read"; + EXPECT_EQ(out.pauses, 0); + } +} + +#if USE_AWS_S3 + +/// A killed owner whose generation was replaced during the connect-hint pause leaves through the exit's +/// owed settling read, which the original generation refuses: the typed fence outcome and `sent_any` are +/// kept, and nothing is sent under the replacement generation. +TEST(CASOwnerStop, KilledOwnerWhoseGenerationRefusesSettlement) +{ + std::optional written; + int code = 0; + int writes = 0; + int reads = 0; + int admits_under_replacement = 0; + int pauses = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + inner->failure = std::make_exception_ptr(DB::S3Exception("Connection refused", Aws::S3::S3Errors::NETWORK_CONNECTION)); + auto backend = std::make_shared(inner); + + std::atomic live_generation{1}; + std::atomic replacement_admits{0}; + Fence fence = Fence::open(); + fence.generation = [&] { return live_generation.load(); }; + fence.admit = [&](uint64_t admitted, uint64_t) + { + if (admitted != 1) + ++replacement_admits; + return admitted == live_generation.load() ? Fence::Admit::Ok : Fence::Admit::LostOrRearmed; + }; + std::atomic pause_count{0}; + CasRequests requests(backend, fence, {}, [&](uint64_t) + { + ++pause_count; + live_generation = 2; + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + written = op.create(STOPPABLE_KEY, "bytes", Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + reads = inner->reads.load(); + admits_under_replacement = replacement_admits.load(); + pauses = pause_count.load(); + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + const auto * gave_up = std::get_if(&*written); + ASSERT_NE(gave_up, nullptr) << "index " << written->index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost) << "the refused settling read keeps its typed outcome"; + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(gave_up->attempts_sent, 1u); + EXPECT_EQ(pauses, 1); + EXPECT_EQ(writes, 1) << "no resend"; + EXPECT_EQ(reads, 0) << "the fence refused the settling read before it was sent"; + EXPECT_EQ(admits_under_replacement, 0) << "nothing is admitted under the replacement generation"; +} + +#endif + +/// A local fault of a stopped owner's write attempt is not settled as a possibly-sent write: it propagates, +/// and no settling read runs. +TEST(CASOwnerStop, LocalFaultOfAStoppedOwnersWriteIsNotSettled) +{ + struct LocalFault + { + const char * name; + std::exception_ptr error; + }; + const LocalFault faults[] = { + {"BAD_ARGUMENTS", std::make_exception_ptr(Exception(ErrorCodes::BAD_ARGUMENTS, "a local bug of the attempt"))}, + {"std::bad_alloc", std::make_exception_ptr(std::bad_alloc())}, + }; + for (const LocalFault & fault : faults) + { + SCOPED_TRACE(fault.name); + StoppableWrite arm; + arm.owner = StoppedBy::Background; + arm.prepare_backend = [&fault](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.failure = fault.error; + backend.on_first_write = stop; + }; + const auto out = runStoppableWrite(arm); + EXPECT_FALSE(out.result.has_value()) << "index " << (out.result ? out.result->index() : 0); + EXPECT_EQ(out.error, fault.error) << "not the fault itself: " << out.message; + EXPECT_EQ(out.writes, 1); + EXPECT_EQ(out.reads, 0) << "a local fault got a settling read"; + } +} + +namespace +{ + +/// Every read and `HEAD` of `key` runs `on_request`, then throws `failure`. The sentinel probe is the default adapter's, +/// over these two. +class LocalFaultReadBackend final : public InMemoryBackend +{ +public: + explicit LocalFaultReadBackend(String key_) : key(std::move(key_)) {} + + using InMemoryBackend::head; + + std::exception_ptr failure; + std::function on_request; + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key) + fail(); + return InMemoryBackend::read(k, access); + } + + std::optional head(const String & k, TransportAccess & access) override + { + if (k == key) + fail(); + return InMemoryBackend::head(k, access); + } + +private: + void fail() + { + if (on_request) + on_request(); + std::rethrow_exception(failure); + } + + const String key; +}; + +} + +/// A local fault of a read, of an observation or of a sentinel probe propagates unchanged when a background owner +/// stopped during the attempt, inside `owed` too: the owner's verdict does not replace it, and an observation does not +/// report it as nothing observed, as the write loop does not settle it. +TEST(CASOwnerStop, LocalFaultOfAStoppedOwnersReadOrProbeIsNotReplaced) +{ + enum class Surface : uint8_t { Read, Observation, Probe }; + struct LocalFault + { + const char * name; + std::function error; + }; + const LocalFault faults[] = { + {"CORRUPTED_DATA", [] { return std::make_exception_ptr(Exception(ErrorCodes::CORRUPTED_DATA, "a local decode failure")); }}, + {"std::bad_alloc", [] { return std::make_exception_ptr(std::bad_alloc()); }}, + }; + for (const LocalFault & fault : faults) + { + for (const Surface surface : {Surface::Read, Surface::Observation, Surface::Probe}) + { + for (const bool owed : {false, true}) + { + SCOPED_TRACE(fmt::format("{}, surface {}{}", fault.name, static_cast(surface), owed ? ", owed" : "")); + onThread(false, [&] + { + auto backend = std::make_shared("k"); + std::atomic stop{false}; + backend->failure = fault.error(); + backend->on_request = [&stop] { stop = true; }; + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + auto background = backgroundStoppedBy(stop); + std::optional owed_scope; + if (owed) + owed_scope.emplace(OwnerScope::owed()); + std::exception_ptr error; + try + { + if (surface == Surface::Probe) + (void)op.probeSentinel("k", Retry::standard()); + else if (surface == Surface::Observation) + (void)op.readModifyWrite("k", [](const std::optional &) { return String("v"); }, + Retry::standard()); + else + (void)op.read("k", Retry::standard()); + } + catch (...) + { + error = std::current_exception(); + } + ASSERT_TRUE(stop.load()) << "the attempt never ran"; + EXPECT_EQ(error, backend->failure) << "not the fault itself: " << messageOf(error); + }); + } + } + } +} + +/// The object-storage adapter's probe, native and emulated, lets a local fault of the storage call through as the same +/// exception; a transport failure stays `Indeterminate`. +TEST(CASOwnerStop, ObjectStorageProbeLetsALocalFaultThrough) +{ + struct Failure + { + const char * name; + std::function error; + bool local; + }; + const Failure failures[] = { + {"CORRUPTED_DATA", [] { return std::make_exception_ptr(Exception(ErrorCodes::CORRUPTED_DATA, "a local decode failure")); }, true}, + {"std::bad_alloc", [] { return std::make_exception_ptr(std::bad_alloc()); }, true}, + {"transport timeout", [] { return std::make_exception_ptr(Poco::TimeoutException("the probe timed out")); }, false}, + }; + for (const auto mode : {ObjectStorageBackend::Mode::Native, ObjectStorageBackend::Mode::EmulatedSingleProcess}) + { + for (const Failure & failure : failures) + { + const bool native = mode == ObjectStorageBackend::Mode::Native; + SCOPED_TRACE(fmt::format("{}, {}", native ? "native" : "emulated", failure.name)); + auto storage = makeLocalObjectStorageOf(); + const std::exception_ptr error = failure.error(); + (native ? storage->on_read : storage->on_exists) = [error] { std::rethrow_exception(error); }; + auto backend = std::make_shared(storage, mode); + const String key = native ? DB::Cas::tests::nativeKeyUnder(storage, "sentinel") : String("sentinel"); + std::optional probed; + std::exception_ptr thrown; + onThread(false, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + probed = op.probeSentinel(key, Retry::once()); + } + catch (...) + { + thrown = std::current_exception(); + } + }); + if (failure.local) + { + EXPECT_FALSE(probed.has_value()); + EXPECT_EQ(thrown, error) << "not the fault itself: " << messageOf(thrown); + } + else + { + EXPECT_EQ(thrown, nullptr) << messageOf(thrown); + ASSERT_TRUE(probed.has_value()); + EXPECT_EQ(probed->outcome, ProbeOutcome::Indeterminate); + } + } + } +} + +/// A stop that lands after a failed base read's own owner check, before `observe` reports the failure, is +/// reported as the owner's verdict, not as the store's failure. +TEST(CASOwnerStop, StopAfterTheReadsOwnCheckIsReportedByObserve) +{ + onThread(false, [&] + { + auto backend = std::make_shared("k"); + backend->failure = std::make_exception_ptr(Exception(ErrorCodes::NETWORK_ERROR, "the read failed")); + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + int checks_after_failure = 0; + const auto owner = OwnerScope::background([&] + { + if (backend->requests.load() > 0 && checks_after_failure++ > 0) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); + int code = 0; + try + { + /// A single-attempt submission reads its base through `observe` with no hint. + (void)op.hotKeys().submit("k", op, Retry::once(), [](const std::optional &) { return std::optional("bytes"); }); + } + catch (const Exception & e) + { + code = e.code(); + } + EXPECT_EQ(checks_after_failure, 2) << "premise: the read's own check saw no stop, and observe's did"; + EXPECT_EQ(code, ErrorCodes::ABORTED); + }); +} + +/// A decision on a warm catalog hint that finds the GC authority lost while the owner is stopped reports the +/// lost authority, as the same decision on a fresh read does. +TEST(CASOwnerStop, StoppedOwnersLostAuthorityOnAWarmHintIsFencedOut) +{ + onThread(false, [&] + { + auto backend = std::make_shared(); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + const CatalogEntry stalled{ + .ns = RootNamespace{"a"}, .state = NsState::Creating, .incarnation = UInt128(1), + .creator = CreatorFence{.server_root_id = "srv", .writer_epoch = 1, .fence_generation = 1}}; + /// One plane with a cached lane for the setup and the cancel, so the cancel starts from the hint the setup left. + CasHotKeys hot_keys(/*cache_budget_bytes=*/1 << 20); + CasRequests requests(backend, Fence::open(), {}, {}, &hot_keys, kDefaultRequestWindowMs); + { + auto setup = requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + CasRefCatalog::casAdmitEntry(setup, layout, 1, stalled); + } + std::atomic authority_held = true; + std::atomic stopped = false; + auto op = requests.admit([&authority_held] { return authority_held.load(); }); + const auto owner = backgroundStoppedBy(stopped); + const uint64_t reads_before = backend->getCount(key); + std::optional reads_at_first_decision; + + std::optional outcome; + EXPECT_NO_THROW(outcome = CasRefCatalog::cancelStalledCreating( + op, layout, stalled, [](const CreatorFence &) { return true; }, + [&](const Retry &) + { + if (!reads_at_first_decision) + reads_at_first_decision = backend->getCount(key); + authority_held = false; + stopped = true; + })); + ASSERT_TRUE(reads_at_first_decision.has_value()); + EXPECT_EQ(*reads_at_first_decision, reads_before) << "premise: the first decision ran on the warm hint"; + ASSERT_TRUE(outcome.has_value()); + EXPECT_EQ(*outcome, CasRefCatalog::StalledCreatingCancelOutcome::FencedOut); + }); +} + +/// A killed query's first attempt is sent on a healthy store; when it fails and the query stops before the reissue, +/// nothing more is sent and the attempt's own error propagates, not the query's verdict. +TEST(CASOwnerStop, KilledQuerysFailedFirstAttemptKeepsItsError) +{ + using enum MutatingVerb; + for (const MutatingVerb verb : {Remove, BulkRemove, Publish}) + { + SCOPED_TRACE(fmt::format("verb {}", static_cast(verb))); + const MutationRun run = runMutatingVerb(verb, std::nullopt, /*fail_first=*/true); + EXPECT_EQ(run.code, ErrorCodes::S3_ERROR) << "the failed attempt's own error"; + EXPECT_EQ(run.mutations, 1) << "no reissue after the kill"; + } +} + +/// A long pause before a reissue is slept in slices, each checking the query: a kill in the third slice ends it there, +/// with the failed read's own error and no further request. +TEST(CASOwnerStop, LongFailurePauseChecksTheQueryEverySlice) +{ + std::vector slices; + int code = 0; + int sent = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared("k"); + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [&](uint64_t ms) + { + slices.push_back(ms); + if (slices.size() == 3) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("k", "v", Retry::once()))); + inner->requests = 0; + Retry policy = Retry::standard(); + /// A pause of at least 1600 ms: eight slices or more. + policy.attempt_spacing_ms = 2000; + try + { + (void)op.read("k", policy); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + sent = inner->requests.load(); + }); + EXPECT_EQ(code, ErrorCodes::TIMEOUT_EXCEEDED) << "the failed read's own error"; + EXPECT_EQ(slices.size(), 3u) << "the pause ends at the slice the kill landed in"; + /// A literal, not the constant: 200 ms is the published bound on how long a pause outlives a stop. + for (const uint64_t slice : slices) + EXPECT_LE(slice, 200u); + EXPECT_EQ(sent, 1) << "no reissue"; +} + +/// A query's stored cause with the `NOT_IMPLEMENTED` code is no batch-capability refusal: no single-key deletes. +TEST(CASOwnerStop, StoredNotImplementedStartsNoSingleKeyDeletes) +{ + class BulkFailsBackend final : public InMemoryBackend + { + public: + std::atomic bulk{0}; + std::atomic single{0}; + + void removeManyWriteOnce(const std::vector & keys, TransportAccess & access) override + { + if (keys.size() > 1) + { + ++bulk; + throw Poco::TimeoutException("BulkFailsBackend: the batch delete timed out"); + } + ++single; + InMemoryBackend::removeManyWriteOnce(keys, access); + } + }; + + int code = 0; + int bulk = 0; + int single = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(); + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [](uint64_t) {}, nullptr, + kDefaultRequestWindowMs); + auto op = requests.admit(); + const Layout layout("p"); + query.kill(storedCause(ErrorCodes::NOT_IMPLEMENTED)); + try + { + (void)removeChunkWriteOnceOrOneByOne( + op, {layout.writeOnceBlobIntentProbeKey("a"), layout.writeOnceBlobIntentProbeKey("b")}, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + bulk = inner->bulk.load(); + single = inner->single.load(); + }); + EXPECT_EQ(code, ErrorCodes::NOT_IMPLEMENTED) << "the query's stored cause propagates"; + EXPECT_EQ(bulk, 1); + EXPECT_EQ(single, 0) << "no single-key delete after the stored cause"; +} + +/// A local miss is the store's answer under a stopped background owner too, as an S3 `NoSuchKey` is: a background +/// verdict is a fresh exception, so it never arrives as a miss. +TEST(CASOwnerStop, LocalMissUnderAStoppedBackgroundOwnerIsAbsence) +{ + auto storage = makeLocalObjectStorageOf(); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + int code = 0; + bool read_absent = false; + onThread(false, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + const auto background = OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); }); + try + { + read_absent = !op.read(DB::Cas::tests::nativeKeyUnder(storage, "absent"), Retry::standard()).has_value(); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + EXPECT_TRUE(read_absent); +} + +#if USE_AWS_S3 +/// A credential refusal the engine would have retried after a refresh ends as retry-later when the query stops before +/// the retry, carrying the refusal: a raw `AccessDenied` would read as damage to the part loader. +TEST(CASOwnerStop, VetoedCredentialRetryEndsAsRetryLater) +{ + FailedFirstRequest arm; + arm.failure = std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); + arm.during_pause = [](CasKillableQuery & q) { q.kill(); }; + const auto out = runFailedFirstRequest(arm); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR); + EXPECT_NE(out.message.find("the store answered AccessDenied"), String::npos) + << "the refusal is not the cause: " << out.message; + EXPECT_EQ(out.refreshes, 1) << "the live query's refusal was refreshed"; + EXPECT_EQ(out.requests, 1) << "the retry never starts"; +} + +namespace +{ + +/// Writes of "k" throw `failures` in order, then succeed; every refresh installs new credentials. +class ScriptedWriteBackend final : public InMemoryBackend +{ +public: + std::vector failures; + std::atomic writes{0}; + std::atomic refreshes{0}; + + std::expected write(const String & key, const String & bytes, const std::optional & expected_value, + TransportAccess & access) override + { + if (key == "k") + { + const size_t n = static_cast(writes++); + if (n < failures.size()) + std::rethrow_exception(failures[n]); + } + return InMemoryBackend::write(key, bytes, expected_value, access); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } +}; + +struct VetoedWriteOutcome +{ + std::optional result; + int code = 0; + String message; + int writes = 0; + int refreshes = 0; +}; + +/// `create("k")` whose writes fail with `failures`; the query is killed in pause number `kill_in_pause`. +VetoedWriteOutcome runVetoedWrite(std::vector failures, int kill_in_pause) +{ + VetoedWriteOutcome out; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(); + inner->failures = std::move(failures); + int pauses = 0; + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [&](uint64_t) + { + if (++pauses == kill_in_pause) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + out.result = op.create("k", "v", Retry::standard()); + } + catch (...) + { + out.code = codeOf(std::current_exception()); + out.message = getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + out.writes = inner->writes.load(); + out.refreshes = inner->refreshes.load(); + }); + return out; +} + +std::exception_ptr accessDenied() +{ + return std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); +} + +} + +/// A conditional write whose credential retry the query vetoes ends as retry-later carrying the refusal: the store +/// refused that attempt, so its outcome is known. After an earlier unanswered attempt the write stays unresolved. +TEST(CASOwnerStop, VetoedCredentialRetryOfAWriteEndsAsRetryLater) +{ + { + SCOPED_TRACE("refused first attempt"); + const auto out = runVetoedWrite({accessDenied()}, /*kill_in_pause=*/1); + EXPECT_FALSE(out.result.has_value()); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR) << out.message; + EXPECT_NE(out.message.find("the store answered AccessDenied"), String::npos) << out.message; + EXPECT_NE(out.message.find("credential retry"), String::npos) << out.message; + EXPECT_EQ(out.writes, 1) << "the retry is not sent"; + EXPECT_EQ(out.refreshes, 1); + } + { + SCOPED_TRACE("refused after an unanswered attempt"); + const auto out = runVetoedWrite( + {std::make_exception_ptr(Poco::TimeoutException("the write timed out")), accessDenied()}, /*kill_in_pause=*/2); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * gave_up = std::get_if(&*out.result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(out.writes, 2); + } +} + +/// A stored `NoSuchKey` of a stopped query is not absence. A genuine `NoSuchKey` is the store's answer and stays +/// absence when the query is already killed. +TEST(CASOwnerStop, StoredNoSuchKeyIsNotAbsenceAGenuineOneIs) +{ + { + SCOPED_TRACE("stored NoSuchKey"); + auto storage = makeClientLikeLocalObjectStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "present"); + { + auto out = storage->writeObject(DB::StoredObject(key), DB::WriteMode::Rewrite); + DB::writeString(String("body"), *out); + out->finalize(); + } + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + int code = 0; + bool read_absent = false; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + query.kill(std::make_exception_ptr( + DB::S3Exception("the query's stored cause", Aws::S3::S3Errors::NO_SUCH_KEY, "NoSuchKey"))); + storage->reads = 0; + storage->fail_next = true; + try + { + read_absent = !op.read(key, Retry::standard()).has_value(); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_FALSE(read_absent) << "a stored NoSuchKey is never absence"; + EXPECT_EQ(code, ErrorCodes::S3_ERROR); + EXPECT_EQ(storage->reads.load(), 1); + } + { + SCOPED_TRACE("genuine NoSuchKey after the kill"); + auto storage = makeLocalObjectStorageOf(); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + int code = 0; + bool read_absent = false; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + query.kill(); + try + { + read_absent = !op.read(DB::Cas::tests::nativeKeyUnder(storage, "absent"), Retry::standard()).has_value(); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + EXPECT_TRUE(read_absent) << "the store's own miss is absence"; + EXPECT_EQ(storage->reads.load(), 1); + } +} +#endif + +namespace +{ + +/// Outlives the positive control's allocation, so the compiler cannot elide it. +[[maybe_unused]] String own_copy_allocation_sink; + +} + +/// A receiver at its memory limit still gets its own copy of a shared failure, not `MEMORY_LIMIT_EXCEEDED`: copying the +/// failure allocates, and that allocation is not where the limit is reported. +TEST(CASOwnerStop, OwnCopyOfASharedFailureIgnoresTheMemoryLimit) +{ +#if defined(SANITIZER) + GTEST_SKIP() << "a sanitizer build does not charge operator new to the memory tracker"; +#else + /// Only allocations of at least 8 MiB are checked against the 16 MiB limit; the copied text is 32 MiB. + const String text(32 << 20, 'x'); + const std::exception_ptr shared = std::make_exception_ptr(Exception(ErrorCodes::NETWORK_ERROR, "shared failure {}", text)); + const UInt64 saved_threshold = CurrentMemoryTracker::getMinAllocationSizeBytesToThrow(); + CurrentMemoryTracker::setMinAllocationSizeBytesToThrow(8 << 20); + SCOPE_EXIT({ CurrentMemoryTracker::setMinAllocationSizeBytesToThrow(saved_threshold); }); + + int control_code = 0; + int code = 0; + bool own_copy = false; + std::thread limited([&] + { + MemoryTracker limit_tracker(&total_memory_tracker, VariableContext::Process, /*log_peak_memory_usage_in_destructor_=*/false); + limit_tracker.setHardLimit(16 << 20); + ThreadStatus thread_status; + thread_status.memory_tracker.setParent(&limit_tracker); + thread_status.untracked_memory_limit = 0; + try + { + own_copy_allocation_sink = text; + } + catch (const Exception & e) + { + control_code = e.code(); + } + own_copy_allocation_sink.clear(); + own_copy_allocation_sink.shrink_to_fit(); + try + { + rethrowOwnCopy(shared); + } + catch (const Exception & e) + { + code = e.code(); + own_copy = std::current_exception() != shared; + } + }); + limited.join(); + + ASSERT_EQ(control_code, ErrorCodes::MEMORY_LIMIT_EXCEEDED) << "premise: the limit is enforced at that size"; + EXPECT_EQ(code, ErrorCodes::NETWORK_ERROR); + EXPECT_TRUE(own_copy); +#endif +} diff --git a/src/Disks/tests/gtest_cas_sentinel_probe.cpp b/src/Disks/tests/gtest_cas_sentinel_probe.cpp index 399b2871e3eac..4ec8d2dddf4f8 100644 --- a/src/Disks/tests/gtest_cas_sentinel_probe.cpp +++ b/src/Disks/tests/gtest_cas_sentinel_probe.cpp @@ -7,26 +7,39 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include +#include +#include +#include +#include #include #include #include +#include +#include #include +#include + #if USE_AWS_S3 #include #endif namespace DB::ErrorCodes { +extern const int ABORTED; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; +extern const int S3_ERROR; } using namespace DB::Cas; @@ -56,9 +69,9 @@ CasRequests makeRequests(Backend & backend, DB::Cas::tests::FakeClock * clock = return CasRequests(std::move(ptr), Fence::open(), {}, {}, nullptr, DB::Cas::kDefaultRequestWindowMs); } -/// A Backend decorator whose read/head/list all throw an untyped runtime error when armed — modelling -/// a backend with no sharper evidence than "something went wrong" (a network timeout, a 5xx, an -/// unclassifiable failure). The fault is injected on the PRIMITIVES, which is what +/// A Backend decorator whose read/head/list all throw a transport timeout when armed — modelling a +/// backend with no sharper evidence than "something went wrong". An exception that is not a +/// `Poco::Exception` is a local fault, which the probe lets through. The fault is injected on the PRIMITIVES, which is what /// `Backend::probeSentinelRaw`'s default derives its answer from; every other operation delegates to /// InMemoryBackend unchanged. class TransportFaultBackend final : public InMemoryBackend @@ -67,21 +80,21 @@ class TransportFaultBackend final : public InMemoryBackend std::optional head(const String & key, TransportAccess & access) override { if (fail.load()) - throw std::runtime_error("injected fault: transport error"); + throw Poco::TimeoutException("injected fault: transport error"); return InMemoryBackend::head(key, access); } std::optional read(const String & key, TransportAccess & access) override { if (fail.load()) - throw std::runtime_error("injected fault: transport error"); + throw Poco::TimeoutException("injected fault: transport error"); return InMemoryBackend::read(key, access); } RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override { if (fail.load()) - throw std::runtime_error("injected fault: transport error"); + throw Poco::TimeoutException("injected fault: transport error"); return InMemoryBackend::list(prefix, cursor, limit, access); } @@ -396,3 +409,351 @@ TEST(CASSentinelProbe, InstrumentedBackendForwardsToInnerClassification) } #endif + +namespace +{ + +using DB::Cas::tests::CasKillableQuery; +using DB::Cas::tests::onThread; + +struct ProbeObserved +{ + bool returned = false; + ProbeOutcome outcome = ProbeOutcome::Indeterminate; + int code = 0; + String what; +}; + +ProbeObserved probeOnce(CasRequests & requests, const String & key, const Retry & policy) +{ + ProbeObserved seen; + auto op = requests.admit(); + try + { + seen.outcome = probeSentinel(op, key, policy).outcome; + seen.returned = true; + } + catch (const DB::Exception & e) + { + seen.code = e.code(); + seen.what = e.message(); + } + catch (const std::exception & e) + { + seen.code = -1; + seen.what = e.what(); + } + return seen; +} + +/// Counts probes and credential refreshes. A failure first asks the thread's query, as the S3 client does. +class FailingProbeBackend final : public InMemoryBackend +{ +public: + enum class Mode { Throw, ReturnIndeterminate, ReturnPresent }; + + Mode mode = Mode::Throw; + std::exception_ptr failure = std::make_exception_ptr(Poco::TimeoutException("the probe timed out")); + std::atomic probes{0}; + std::atomic refreshes{0}; + + SentinelProbeResult probeSentinelRaw(const String &, TransportAccess &) override + { + ++probes; + DB::CurrentThread::checkIfNotCancelled(); + if (mode == Mode::ReturnIndeterminate) + return {ProbeOutcome::Indeterminate, std::nullopt}; + if (mode == Mode::ReturnPresent) + return {ProbeOutcome::Present, String("v")}; + std::rethrow_exception(failure); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } +}; + +/// What the store answers to a request it refuses for credentials. +std::exception_ptr credentialFailure() +{ +#if USE_AWS_S3 + return std::make_exception_ptr(DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); +#else + return std::make_exception_ptr(Poco::IOException("the store answered AccessDenied")); +#endif +} + +void stopBackground(std::optional & scope) +{ + scope.emplace(OwnerScope::background([] { throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); })); +} + +} + +/// A stopped owner's probe surfaces the owner's verdict: no reissue, no credential refresh, and no +/// `Indeterminate` returned in its place. +TEST(CASSentinelProbe, StoppedProbePreservesCallerVerdict) +{ + for (const bool once : {true, false}) + { + const Retry policy = once ? Retry::once() : Retry::standard(); + SCOPED_TRACE(once ? "once" : "standard"); + + for (const auto mode : {FailingProbeBackend::Mode::Throw, FailingProbeBackend::Mode::ReturnIndeterminate}) + { + SCOPED_TRACE(mode == FailingProbeBackend::Mode::Throw ? "backend throws" : "backend returns Indeterminate"); + ProbeObserved seen; + int probes = 0; + int refreshes = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(); + backend->mode = mode; + backend->failure = credentialFailure(); + DB::Cas::tests::FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + query.kill(); + seen = probeOnce(requests, "k", policy); + probes = backend->probes.load(); + refreshes = backend->refreshes.load(); + }); + EXPECT_FALSE(seen.returned) << "the verdict, not an outcome"; + EXPECT_EQ(seen.code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(probes, 1); + EXPECT_EQ(refreshes, 0); + } + + { + SCOPED_TRACE("background owner, backend returns Indeterminate"); + ProbeObserved seen; + int probes = 0; + onThread(false, [&] + { + auto backend = std::make_shared(); + backend->mode = FailingProbeBackend::Mode::ReturnIndeterminate; + DB::Cas::tests::FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + std::optional scope; + stopBackground(scope); + seen = probeOnce(requests, "k", policy); + probes = backend->probes.load(); + }); + EXPECT_FALSE(seen.returned) << "the returned Indeterminate is replaced by the verdict"; + EXPECT_EQ(seen.code, DB::ErrorCodes::ABORTED); + EXPECT_EQ(probes, 1); + } + + { + SCOPED_TRACE("background owner, backend throws a credential answer"); + ProbeObserved seen; + int probes = 0; + int refreshes = 0; + onThread(false, [&] + { + auto backend = std::make_shared(); + backend->failure = credentialFailure(); + DB::Cas::tests::FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + std::optional scope; + stopBackground(scope); + seen = probeOnce(requests, "k", policy); + probes = backend->probes.load(); + refreshes = backend->refreshes.load(); + }); + EXPECT_FALSE(seen.returned); + EXPECT_EQ(seen.code, DB::ErrorCodes::ABORTED); + EXPECT_EQ(probes, 1); + EXPECT_EQ(refreshes, 0); + } + } +} + +/// A stop that lands during the pause before a reissue starts no further probe, even one that would succeed. The +/// probe ends with what the failed one had: the exception behind it, or the inconclusive outcome itself. +TEST(CASSentinelProbe, StopDuringProbeBackoffStartsNoReissue) +{ + for (const bool with_cause : {false, true}) + { + SCOPED_TRACE(with_cause ? "the failed probe threw" : "the failed probe returned Indeterminate"); + ProbeObserved seen; + int probes = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(); + backend->mode = with_cause ? FailingProbeBackend::Mode::Throw : FailingProbeBackend::Mode::ReturnIndeterminate; + DB::Cas::tests::FakeClock clock; + auto sleep = clock.sleepFn(); + CasRequests requests(backend, Fence::open(), clock.nowFn(), [&](uint64_t ms) + { + sleep(ms); + backend->mode = FailingProbeBackend::Mode::ReturnPresent; /// the reissue would succeed: it must not start + query.kill(); + }, nullptr, DB::Cas::kDefaultRequestWindowMs); + seen = probeOnce(requests, "k", Retry::standard()); + probes = backend->probes.load(); + }); + if (with_cause) + { + EXPECT_FALSE(seen.returned); + EXPECT_EQ(seen.code, -1) << "the probe's own Poco timeout, not the query's verdict"; + EXPECT_EQ(seen.what, "Timeout"); + } + else + { + ASSERT_TRUE(seen.returned) << seen.what; + EXPECT_EQ(seen.outcome, ProbeOutcome::Indeterminate); + } + EXPECT_EQ(probes, 1); + } +} + +/// A healthy first probe is never refused, whoever stopped. +TEST(CASSentinelProbe, HealthyFirstProbeIsNotRefused) +{ + for (const bool background : {false, true}) + { + SCOPED_TRACE(background ? "background owner" : "killed query"); + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + InMemoryBackend backend; + auto requests = makeRequests(backend); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("k", "v", Retry::once()))); + std::optional scope; + if (background) + stopBackground(scope); + else + query.kill(); + ASSERT_NE(ownerStopRequested(), nullptr); + EXPECT_EQ(probeSentinel(op, "k", Retry::standard()).outcome, ProbeOutcome::Present); + EXPECT_EQ(probeSentinel(op, "missing", Retry::standard()).outcome, ProbeOutcome::KeyAbsent); + }); + } +} + +#if USE_AWS_S3 + +namespace +{ + +/// Fails every access with `code` after asking the thread's query, as the S3 client does. +class ClientLikeS3ObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + mutable std::atomic accesses{0}; + Aws::S3::S3Errors code = Aws::S3::S3Errors::SERVICE_UNAVAILABLE; + + std::unique_ptr readObject( + const DB::StoredObject & object, const DB::ReadSettings &, std::optional, bool, bool) const override + { + fail(object.remote_path); + } + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, const DB::ReadSettings &, size_t, std::optional) const override + { + fail(object.remote_path); + } + + DB::ObjectMetadata getObjectMetadata(const std::string & path, bool) const override { fail(path); } + +private: + [[noreturn]] void fail(const String & path) const + { + ++accesses; + DB::CurrentThread::checkIfNotCancelled(); + throw DB::S3Exception("the store answered for " + path, code); + } +}; + +std::shared_ptr makeClientLikeS3Storage(Aws::S3::S3Errors code) +{ + static std::atomic counter{0}; + const auto root = (std::filesystem::temp_directory_path() + / ("cas_sentinel_probe_stop_" + std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)))).string(); + std::filesystem::remove_all(root); + std::filesystem::create_directories(root); + DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); + auto storage = DB::Cas::tests::ownedByDirectory(std::make_shared(std::move(settings)), root); + storage->code = code; + return storage; +} + +} + +/// A stopped query's native probe is inconclusive, a stored cause that is itself an `S3Exception` `NoSuchBucket` or +/// `AccessDenied` included: none of them becomes an authoritative outcome, and the probe is not reissued. +TEST(CASSentinelProbe, StoppedQueryNativeProbeIsNotAnAuthoritativeOutcome) +{ + struct Arm + { + const char * name; + Aws::S3::S3Errors store_code; + std::function cause; + }; + const std::vector arms = { + {"plain kill", Aws::S3::S3Errors::SERVICE_UNAVAILABLE, [] { return std::exception_ptr{}; }}, + {"stored NoSuchBucket", Aws::S3::S3Errors::NO_SUCH_BUCKET, + [] { return std::make_exception_ptr(DB::S3Exception("stored cause", Aws::S3::S3Errors::NO_SUCH_BUCKET)); }}, + {"stored AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, + [] { return std::make_exception_ptr(DB::S3Exception("stored cause", Aws::S3::S3Errors::ACCESS_DENIED)); }}, + }; + for (const bool once : {true, false}) + { + for (const auto & arm : arms) + { + SCOPED_TRACE(String(once ? "once, " : "standard, ") + arm.name); + auto storage = makeClientLikeS3Storage(arm.store_code); + ObjectStorageBackend backend(storage, ObjectStorageBackend::Mode::Native); + ProbeObserved seen; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + DB::Cas::tests::FakeClock clock; + auto requests = makeRequests(backend, &clock); + query.kill(arm.cause()); + seen = probeOnce(requests, nativeKeyUnder(storage, "some/key"), once ? Retry::once() : Retry::standard()); + }); + ASSERT_TRUE(seen.returned) << seen.what; + EXPECT_EQ(seen.outcome, ProbeOutcome::Indeterminate); + EXPECT_EQ(storage->accesses.load(), 1) << "no reissue"; + } + } +} + +/// The S3 client cannot see a background owner, so the store's own answer stays authoritative. +TEST(CASSentinelProbe, BackgroundOwnerKeepsTheStoresAnswer) +{ + const std::vector> answers = { + {Aws::S3::S3Errors::NO_SUCH_BUCKET, ProbeOutcome::ContainerAbsent}, + {Aws::S3::S3Errors::ACCESS_DENIED, ProbeOutcome::AccessDenied}, + {Aws::S3::S3Errors::NO_SUCH_KEY, ProbeOutcome::KeyAbsent}, + }; + for (const auto & [code, expected] : answers) + { + SCOPED_TRACE(static_cast(code)); + auto storage = makeClientLikeS3Storage(code); + ObjectStorageBackend backend(storage, ObjectStorageBackend::Mode::Native); + ProbeObserved seen; + onThread(false, [&] + { + auto requests = makeRequests(backend); + std::optional scope; + stopBackground(scope); + ASSERT_NE(ownerStopRequested(), nullptr); + seen = probeOnce(requests, nativeKeyUnder(storage, "some/key"), Retry::standard()); + }); + ASSERT_TRUE(seen.returned) << seen.what; + EXPECT_EQ(seen.outcome, expected); + EXPECT_EQ(storage->accesses.load(), 1); + } +} + +#endif From 9426c0be9eec557d1ebb46dd3bf608d9f7db59b1 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:27:58 +0100 Subject: [PATCH 07/47] Stop CAS catalog updates and hot-key submissions at the owner's request A catalog step decides its exit before the submission cap and the pause, by one rule. A write that saw its query stop starts no further discretionary request. An earlier unresolved write is reported at every non-commit exit, also from the catalog erase. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressed/Backend/CasHotKeys.cpp | 18 +- .../ContentAddressed/Backend/CasRequests.cpp | 2 + .../ContentAddressed/Pool/CasRefCatalog.cpp | 191 +++++++++++++----- src/Disks/tests/gtest_cas_hot_keys.cpp | 177 +++++++++++++++- src/Disks/tests/gtest_cas_ref_catalog.cpp | 136 ++++++++++++- 5 files changed, 452 insertions(+), 72 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp index 7e45e72beab53..42441d332388e 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -35,10 +36,6 @@ GaveUp::Source sourceFor(const Retry::Bound & bound) return bound.source == Retry::Bound::Source::Lease ? GaveUp::Source::Lease : GaveUp::Source::Policy; } -/// The wait slice: how late, at most, a waiter notices its own fence or deadline. A handover wakes it -/// at once through the lane's condition variable. -constexpr auto kWaitSlice = std::chrono::milliseconds(200); - } CasHotKeys::CasHotKeys(uint64_t cache_budget_bytes_) @@ -99,7 +96,7 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr ~Leave() noexcept { owner.leave(key, item, entered_hold, entered_ms, op); } } guard{*this, key, item, entered_hold, entered_ms, op}; - for (;;) + for (bool waited = false;; waited = true) { /// Outside the mutex: the engine's own admission in the engine's order (the fence generation, /// the lease budget, then the caller's liveness, which the engine reports as a lost fence), @@ -137,7 +134,8 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr entered_hold = true; break; } - lane.cv.wait_for(lock, kWaitSlice); + /// The slice also bounds how late the waiter notices its own fence or deadline; a handover wakes it at once. + lane.cv.wait_for(lock, kOwnerStopSlice); } ProfileEvents::increment(ProfileEvents::CASHotKeyQueueWaitMicroseconds, (op.owner.now_ms() - entered_ms) * 1000); return hold(key, op, policy, decide); @@ -229,6 +227,7 @@ WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry std::optional candidate; bool verdict_on_hint = false; + throwIfBackgroundStopped(); try { candidate = decide(base); @@ -238,6 +237,12 @@ WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry { if (!from_cache) throw; + /// A stopped background owner's exception says nothing about the hint, so it is not worth a reread. A + /// lost admission `decide` may have thrown on goes first: the reread's own gate reports it. A killed + /// query rereads, as a healthy read is never refused. + if (op.admitted()) + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(stop); verdict_on_hint = true; } if (verdict_on_hint) @@ -250,6 +255,7 @@ WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry if (auto refused = read_base()) return *refused; from_cache = false; + throwIfBackgroundStopped(); candidate = decide(base); } if (!candidate) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp index caeec9ef6f15f..7fe86a9a660b3 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp @@ -1456,6 +1456,7 @@ WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObje for (uint32_t decisions = 1;; ++decisions) { + throwIfBackgroundStopped(); /// Outside every classification: `decide` is the caller's own control flow, and an exception /// from it is theirs to see unchanged. const std::optional next = decide(current); @@ -1510,6 +1511,7 @@ WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const De for (uint32_t decisions = 1;; ++decisions) { + throwIfBackgroundStopped(); const std::optional next = decide(current); if (!next) return Declined{state.last_seen}; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp index c9e7fd1bac81d..259e6c5d81373 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -140,6 +141,13 @@ struct CatalogCreatorStillLiveMarker : std::exception {}; /// Proven absence of the catalog, for a caller that takes it as an answer rather than as corruption. struct CatalogAbsentMarker : std::exception {}; +/// What `decide` threw, which `casUpdateImpl` delivers unchanged: a decision is not a sent write. +struct CatalogDecisionFailure : std::exception +{ + explicit CatalogDecisionFailure(std::exception_ptr error_) : error(std::move(error_)) {} + std::exception_ptr error; +}; + /// Shared body of `casUpdate`/`casAdmitEntry`. `encode` turns a freshly `mutate`d candidate into the /// bytes to write: the plain path just grammar-checks (`encodeRefCatalog`), the admitting path also /// runs both admission predicates (`checkCatalogAdmission`) first. A refused precondition re-runs @@ -152,70 +160,126 @@ RefCatalog casUpdateImpl( const Retry & policy = Retry::standard(), bool absence_is_an_answer = false) { const String key = layout.refCatalogKey(); + const String what = fmt::format("CAS ref catalog '{}' update", key); /// The candidate the LAST `decide` produced, which is the one the engine wrote: every earlier one /// belongs to an attempt whose precondition was refused. std::optional written; const auto decide = [&](const std::optional & current) -> std::optional { - /// Absence of the mandatory catalog is corruption, not a fresh bootstrap. Refusing here is - /// what stops any mutation from replacing every other namespace with a one-update catalog. - if (!current) + try { - if (absence_is_an_answer) - throw CatalogAbsentMarker{}; - throwMandatoryCatalogAbsent(key); + /// Absence of the mandatory catalog is corruption, not a fresh bootstrap. Refusing here is + /// what stops any mutation from replacing every other namespace with a one-update catalog. + if (!current) + { + if (absence_is_an_answer) + throw CatalogAbsentMarker{}; + throwMandatoryCatalogAbsent(key); + } + const RefCatalog durable = decodeRefCatalog(current->bytes); + CatalogLifeIndex(durable).throwIfAmbiguous("CAS ref catalog mutation"); + RefCatalog candidate = mutate(durable); + String bytes = encode(candidate); + written = std::move(candidate); + return bytes; + } + catch (...) + { + throw CatalogDecisionFailure(std::current_exception()); } - const RefCatalog durable = decodeRefCatalog(current->bytes); - CatalogLifeIndex(durable).throwIfAmbiguous("CAS ref catalog mutation"); - RefCatalog candidate = mutate(durable); - String bytes = encode(candidate); - written = std::move(candidate); - return bytes; }; - /// One hold at a time per pool on this key, from the pool's last known catalog when the lane holds - /// one. The loop is this function's: a `Conflict` is a lost race against another server (the lane - /// never conflicts with itself), repaid after the flat jitter, or after the growing schedule when - /// the conflict settled a transport fault. Under a single-attempt policy the first `Conflict` is - /// the answer, as the engine's own verb answers it. - const Retry frozen = op.freeze(policy); - /// Under `resend_unresolved = false` the engine returns an attempt whose fate is unknown instead of - /// resending its bytes, and this loop decides again on a fresh read. Attempt numbering continues, - /// so the next write is not a first attempt with the adaptive timeout again. - Retry attempt_policy = frozen; - uint32_t settled_faults = 0; - for (;;) - { - WriteResult result = op.hotKeys().submit(key, op, attempt_policy, decide); - /// A write decided on a cached body can be refused by a deletion; its settling read already proved it. - if (const auto * conflict = std::get_if(&result); - absence_is_an_answer && conflict && std::holds_alternative(conflict->seen)) - throw CatalogAbsentMarker{}; - if (const auto * unresolved = std::get_if(&result); - unresolved && unresolved->why == GaveUp::Why::Unresolved && unresolved->sent_any - && !frozen.resend_unresolved && !frozen.single_attempt) + /// Set once a submission sent a write whose outcome stayed unresolved. That write can still land, so every exit + /// below but a commit, the typed outcomes, a failed decision and a local fault reports it. + bool sent_unresolved = false; + try + { + /// One hold at a time per pool on this key, from the pool's last known catalog when the lane holds + /// one. The loop is this function's: a `Conflict` is a lost race against another server (the lane + /// never conflicts with itself), repaid after the flat jitter, or after the growing schedule when + /// the conflict settled a transport fault. Under a single-attempt policy the first `Conflict` is + /// the answer, as the engine's own verb answers it. Each request binds its own window, so the + /// count of submissions is what ends a loop that keeps losing; one submission may run `decide` + /// twice on a cached catalog, so `decide` calls are not counted. + /// + /// Under `resend_unresolved = false` the engine returns an attempt whose fate is unknown instead of + /// resending its bytes, and this loop decides again on a fresh read. Attempt numbering continues, + /// so the next write is not a first attempt with the adaptive timeout again. + Retry attempt_policy = policy; + uint32_t settled_faults = 0; + for (uint32_t submissions = 1;; ++submissions) { - attempt_policy.attempts_already_sent += unresolved->attempts_sent; - auto given_up = op.pauseBeforeRedecide(Retry::backoff(++settled_faults), *unresolved, frozen); - if (!given_up) + if (submissions > 1) + throwIfBackgroundStopped(); + WriteResult result = op.hotKeys().submit(key, op, attempt_policy, decide); + if (std::holds_alternative(result)) + return std::move(*written); + + /// Every other final outcome ends the call here, so the cap below never meets an operation that must end. + const auto * conflict = std::get_if(&result); + const auto * gave_up = std::get_if(&result); + /// A write decided on a cached body can be refused by a deletion; its settling read already proved it. + if (absence_is_an_answer && conflict && std::holds_alternative(conflict->seen)) + throw CatalogAbsentMarker{}; + /// The fence can be lost in two places and both mean the same to a lifecycle caller: inside + /// `decide`, which throws the marker itself, and between two attempts, where the engine + /// notices it first and no further `decide` runs. Normalising the second onto the first is + /// what keeps "the fence moved" a returned outcome rather than an exception. + if (gave_up && gave_up->why == GaveUp::Why::FenceLost) + throw CatalogFenceMovedMarker{}; + + /// The only two reasons to submit again: another writer won the race, or the policy decides again + /// after a write whose outcome is unknown. + const bool lost_race = conflict && !conflict->observed_stop && !policy.single_attempt; + const bool decide_again_on_unresolved = gave_up && gave_up->why == GaveUp::Why::Unresolved + && gave_up->sent_any && !policy.resend_unresolved && !policy.single_attempt; + if (!lost_race && !decide_again_on_unresolved) + throwCatalogWriteFailure(std::move(result), what); + sent_unresolved = sent_unresolved || decide_again_on_unresolved; + + if (submissions == kCasMaxDecisions) + { + const std::optional lost = op.lostAdmission(); + if (!lost) + throwDidNotConverge(what, kCasMaxDecisions, "submissions"); + if (*lost == CasOperation::AdmissionLoss::Fence) + throw CatalogFenceMovedMarker{}; + throwCasWriteRetryLater(fmt::format("{}: gave up at the lease deadline after {} submissions", what, kCasMaxDecisions)); + } + if (lost_race) + { + op.sleepFor(conflict->any_ambiguous ? Retry::backoff(++settled_faults) : Retry::conflictBackoff()); continue; - result = std::move(*given_up); - } - if (const auto * conflict = std::get_if(&result); conflict && !frozen.single_attempt) - { - op.pause(conflict->any_ambiguous ? Retry::backoff(++settled_faults) : Retry::conflictBackoff()); - continue; + } + attempt_policy.attempts_already_sent += gave_up->attempts_sent; + std::optional stopped = op.pauseAfterUnresolvedWrite(Retry::backoff(++settled_faults), *gave_up, policy); + if (!stopped) + continue; + if (stopped->why == GaveUp::Why::FenceLost) + throw CatalogFenceMovedMarker{}; + throwCatalogWriteFailure(std::move(*stopped), what); } - /// The fence can be lost in two places and both mean the same to a lifecycle caller: inside - /// `decide`, which throws the marker itself, and between two attempts, where the engine - /// notices it first and no further `decide` runs. Normalising the second onto the first is - /// what keeps "the fence moved" a returned outcome rather than an exception. - if (const auto * gave_up = std::get_if(&result); gave_up && gave_up->why == GaveUp::Why::FenceLost) - throw CatalogFenceMovedMarker{}; - if (!std::holds_alternative(result)) - throwCatalogWriteFailure(std::move(result), fmt::format("CAS ref catalog '{}' update", key)); - return std::move(*written); + } + catch (const CatalogDecisionFailure & failure) + { + std::rethrow_exception(failure.error); + } + catch (const CatalogFenceMovedMarker &) + { + throw; + } + catch (const CatalogAbsentMarker &) + { + throw; + } + catch (...) + { + if (!sent_unresolved || isLocalFault(std::current_exception())) + throw; + throwCasWriteRetryLater(fmt::format("{}: a sent write's outcome is unresolved; the call ended with: {}", what, + getCurrentExceptionMessage(/*with_stacktrace=*/false, /*check_embedded_stacktrace=*/false, + /*with_extra_info=*/false, /*with_version=*/false))); } } @@ -498,7 +562,8 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov const Retry policy = Retry::standard(); bool retirement_announced = false; - for (size_t attempt = 0; attempt < kMaxCatalogCasAttempts; ++attempt) + /// Each request binds its own window, so only the count ends a loop that keeps losing the catalog. + for (uint32_t attempt = 0; attempt < kCasMaxDecisions; ++attempt) { /// So the admission consulted below is not one reading taken before the first attempt. if (refresh_authority) @@ -549,7 +614,23 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov /// The response to a conditional erase is not authority for what became durable. Resolve every /// attempted erase through one complete catalog read. This snapshot is also the next /// retry/selection cut, so no second read separates them. - catalog_snapshot = read(op, layout, policy); + try + { + /// Owed to the attempted erase: a landed erase must be observed. + const auto owed = OwnerScope::owed(); + catalog_snapshot = read(op, layout, policy); + } + catch (...) + { + /// The erase may still land, so a stopped owner's failed read keeps its "outcome unknown" exit. A local + /// fault says nothing about the erase and propagates unchanged. + const auto * gave_up = std::get_if(&erase); + if (gave_up && gave_up->why == GaveUp::Why::Unresolved && gave_up->sent_any && ownerStopRequested() + && !isLocalFault(std::current_exception())) + throwCatalogWriteFailure(std::move(erase), fmt::format( + "CAS ref catalog erase for namespace '{}'", observed.ns.string())); + throw; + } const auto current_it = findEntry(catalog_snapshot.catalog, observed.ns); const bool old_life_still_cataloged = current_it != catalog_snapshot.catalog.entries.end() @@ -575,9 +656,7 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov throwIfBackgroundStopped(); } - throwCasWriteRetryLater(fmt::format( - "CAS ref catalog erase for namespace '{}' did not converge after {} attempts", - observed.ns.string(), kMaxCatalogCasAttempts)); + throwDidNotConverge(fmt::format("CAS ref catalog erase for namespace '{}'", observed.ns.string()), kCasMaxDecisions, "attempts"); } CasRefCatalog::StalledCreatingCancelOutcome CasRefCatalog::cancelStalledCreating( diff --git a/src/Disks/tests/gtest_cas_hot_keys.cpp b/src/Disks/tests/gtest_cas_hot_keys.cpp index 22333f1a344b6..39cec4c7bd0d6 100644 --- a/src/Disks/tests/gtest_cas_hot_keys.cpp +++ b/src/Disks/tests/gtest_cas_hot_keys.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "cas_test_helpers.h" #include @@ -16,6 +17,8 @@ #include #include +#include +#include #include #include #include @@ -33,6 +36,11 @@ namespace ProfileEvents extern const Event CASRequestGaveUp; } +namespace DB::ErrorCodes +{ + extern const int ABORTED; +} + using namespace DB::Cas; using DB::Cas::tests::CountingBackend; @@ -513,7 +521,7 @@ TEST(CASHotKeys, AnExternalWriterCostsOneResolveReadAndOneRetry) { WriteResult attempt = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); if (std::holds_alternative(attempt)) - op.pause(Retry::conflictBackoff()); + op.sleepFor(Retry::conflictBackoff()); else result = std::move(attempt); } @@ -769,3 +777,170 @@ TEST(CASHotKeys, AnIdenticalCandidateLandedByAnotherServerIsTheEnginesCommit) EXPECT_TRUE(identicalToken(committed->etag, theirs)); DB::Cas::tests::expectBytes(*backend, "k", "1,2"); } + +/// A waiter whose owner stops while the holder is parked leaves the queue at once, and the waiter +/// behind it takes its turn in order. +TEST(CASHotKeys, CancelledWaiterWithdrawsWhileHolderIsParked) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(0); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + ParkFirstWrite park; + park.install(*backend, "k"); + std::atomic stop{false}; + std::atomic released{false}; + + std::optional holder_result; + std::thread holder([&] + { + auto op = requests.admit(); + holder_result = hot_keys.submit("k", op, Retry::standard(), appendTicket(1)); + }); + park.parked.wait(); + + std::promise cancelled_code; + auto cancelled_returned = cancelled_code.get_future(); + bool returned_while_parked = false; + std::thread cancelled([&] + { + auto owner = OwnerScope::background([&stop] + { + if (stop) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + auto op = requests.admit(); + int code = 0; + try + { + (void)hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + returned_while_parked = !released; + cancelled_code.set_value(code); + }); + while (hot_keys.queueDepthForTest("k") < 2) + std::this_thread::yield(); + + std::optional next_result; + std::thread next([&] + { + auto op = requests.admit(); + next_result = hot_keys.submit("k", op, Retry::standard(), appendTicket(3)); + }); + while (hot_keys.queueDepthForTest("k") < 3) + std::this_thread::yield(); + + stop = true; + const bool in_time = cancelled_returned.wait_for(std::chrono::seconds(30)) == std::future_status::ready; + EXPECT_TRUE(in_time) << "the cancelled waiter stayed queued behind the parked holder"; + if (in_time) + EXPECT_EQ(hot_keys.queueDepthForTest("k"), 2u) << "the cancelled item left the queue"; + released = true; + park.release.count_down(); + holder.join(); + cancelled.join(); + next.join(); + + EXPECT_EQ(cancelled_returned.get(), DB::ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_parked); + ASSERT_TRUE(holder_result && std::holds_alternative(*holder_result)); + ASSERT_TRUE(next_result && std::holds_alternative(*next_result)); + EXPECT_EQ(backend->writeCount("k"), 2u) << "the cancelled waiter wrote nothing"; + DB::Cas::tests::expectBytes(*backend, "k", "1,3"); + EXPECT_EQ(hot_keys.laneCountForTest(), 0u); +} + +/// A decision on a cached hint that ends because its owner stopped is no verdict on the hint: the +/// stop is thrown, with no reread and no second decision. +TEST(CASHotKeys, CancelledHintDecisionDoesNotReread) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); + const uint64_t gets_before = backend->getCount("k"); + const uint64_t writes_before = backend->writeCount("k"); + const auto reread_before = counter(ProfileEvents::CASHotKeyCacheVerdictsReread); + + std::atomic stop{false}; + auto owner = OwnerScope::background([&stop] + { + if (stop) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + int decisions = 0; + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::ABORTED, [&] + { + (void)hot_keys.submit("k", op, Retry::standard(), [&](const std::optional & current) -> std::optional + { + ++decisions; + /// The owner stops while the decision runs, and the code it calls asks the owner. + stop = true; + throwIfBackgroundStopped(); + return current->bytes + ",2"; + }); + }); + EXPECT_EQ(decisions, 1); + EXPECT_EQ(backend->getCount("k") - gets_before, 0u) << "no reread"; + EXPECT_EQ(backend->writeCount("k") - writes_before, 0u); + EXPECT_EQ(counter(ProfileEvents::CASHotKeyCacheVerdictsReread) - reread_before, 0u); +} + +namespace +{ + +/// Runs `on_read` before each read. +class ReadHookBackend final : public CountingBackend +{ +public: + std::function on_read; + + std::optional read(const String & key, TransportAccess & access) override + { + if (on_read) + on_read(); + return CountingBackend::read(key, access); + } +}; + +} + +/// A decline on a cached hint is reread; when the owner stops during that read, the decision on it does +/// not run. +TEST(CASHotKeys, StopDuringHintRereadSkipsTheSecondDecision) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); + const uint64_t gets_before = backend->getCount("k"); + const auto reread_before = counter(ProfileEvents::CASHotKeyCacheVerdictsReread); + + std::atomic stop{false}; + auto owner = OwnerScope::background([&stop] + { + if (stop) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + backend->on_read = [&stop] { stop = true; }; + int decisions = 0; + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::ABORTED, [&] + { + (void)hot_keys.submit("k", op, Retry::standard(), [&](const std::optional &) -> std::optional + { + ++decisions; + return std::nullopt; + }); + }); + EXPECT_EQ(decisions, 1) << "the decision on the reread did not run"; + EXPECT_EQ(backend->getCount("k") - gets_before, 1u); + EXPECT_EQ(counter(ProfileEvents::CASHotKeyCacheVerdictsReread) - reread_before, 1u); +} diff --git a/src/Disks/tests/gtest_cas_ref_catalog.cpp b/src/Disks/tests/gtest_cas_ref_catalog.cpp index 7587017056eef..1f2fb0146386f 100644 --- a/src/Disks/tests/gtest_cas_ref_catalog.cpp +++ b/src/Disks/tests/gtest_cas_ref_catalog.cpp @@ -1,6 +1,7 @@ #include "cas_format_test_battery.h" #include "cas_test_helpers.h" #include +#include #include #include #include @@ -13,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -64,6 +66,7 @@ class GcRoundPlanSignatureAccess namespace DB::ErrorCodes { + extern const int ABORTED; extern const int CORRUPTED_DATA; extern const int LOGICAL_ERROR; extern const int LIMIT_EXCEEDED; @@ -1134,7 +1137,6 @@ TEST(CASRefCatalog, CasUpdateEndsAfterAHundredPacedSubmissions) { CasRefCatalog::casUpdate(op, layout, [&](const RefCatalog & cur) { - ++mutate_calls; backend->refuseNextWrite(layout.refCatalogKey()); RefCatalog next = cur; return next; @@ -1907,14 +1909,130 @@ TEST(CASRefCatalogRemoval, PerpetualConflictGivesUpAfterAHundredErases) EXPECT_EQ(e.code(), DB::ErrorCodes::NETWORK_ERROR); message = e.message(); } - EXPECT_NE(message.find("deadline"), String::npos) - << "the shared bound, not the attempt cap, is what ended this call: " << message; - /// Two windows, so the assertion survives the jitter of the paced retries while still failing a - /// loop that binds a fresh window per iteration -- that one spends minutes here. - EXPECT_LT(clock.now - start, 2 * kDefaultRequestWindowMs) << "the loop outlived the window it captured"; - EXPECT_LT(backend->refusedAttempts(), 100u) << "the attempt cap must not be what ends this call"; - /// Greater than one is what proves the loop iterated rather than failing on its first attempt. - EXPECT_GT(backend->refusedAttempts(), 1u); + EXPECT_NE(message.find("did not converge after 100 attempts"), String::npos) << message; + EXPECT_EQ(backend->refusedAttempts(), 100u); + EXPECT_EQ(clock.sleeps.size() - sleeps_before, 99u) << "no pause after the last refusal"; + EXPECT_EQ(CasRefCatalog::read(op, layout).catalog.entries, std::vector{removing}); +} + +namespace +{ + +CatalogEntry removingEntryForStopTests() +{ + return CatalogEntry{.ns = RootNamespace{"a"}, .state = NsState::Removing, .incarnation = UInt128{7}, .removal_started_round = 13}; +} + +CasFoldSeal readyParentForStopTests() +{ + CasFoldSeal parent; + parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + return parent; +} + +/// Loses the reply of the next catalog write, running `on_lost` first; every catalog read after it fails. +class LostEraseUnreadableCatalogBackend final : public WriteCountingBackend +{ +public: + String catalog_key; + std::function on_lost; + + std::optional read(const String & key, DB::Cas::TransportAccess & access) override + { + if (lost && key == catalog_key) + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected catalog read failure"); + return WriteCountingBackend::read(key, access); + } + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (key != catalog_key || !on_lost || lost) + return WriteCountingBackend::write(key, bytes, expected_value, access); + lost = true; + on_lost(); + throw Poco::TimeoutException("injected lost catalog erase reply"); + } + +private: + bool lost = false; +}; + +} + +/// An erase whose reply was lost, whose owner stopped, and whose resolution read cannot complete ends with the +/// erase's "outcome unknown" exit: the erase may still land. +TEST(CASRefCatalogRemoval, UnresolvedEraseOfAStoppedOwnerKeepsItsExit) +{ + auto backend = std::make_shared(); + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout layout("erase-unresolved-stop"); + const CatalogEntry removing = removingEntryForStopTests(); + seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + std::atomic stopped = false; + backend->catalog_key = layout.refCatalogKey(); + backend->on_lost = [&stopped] { stopped = true; }; + + String message; + { + const auto owner = OwnerScope::background([&stopped] + { + if (stopped) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] + { + try + { + (void)deleteCompletedRemovingForTest(op, layout, removing, readyParentForStopTests(), noAuthorityRefresh); + } + catch (const DB::Exception & e) + { + message = e.message(); + throw; + } + }); + } + EXPECT_NE(message.find("unresolved"), String::npos) << message; + EXPECT_EQ(backend->writes(layout.refCatalogKey()), 1u) << "only the seed: the lost erase bypasses the count, and nothing was resent"; +} + +/// An owner that stops while a conflicted erase is resolved starts no second decision: no authority refresh +/// and no erase follow the resolution read. +TEST(CASRefCatalogRemoval, StopDuringAConflictedErasesResolutionStartsNoNextDecision) +{ + auto backend = std::make_shared(); + FakeClock clock; + std::atomic stopped = false; + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + requests.setNowFnForTest(clock.nowFn()); + /// The conflict's pause comes before the resolution read. + requests.setSleepFnForTest([&stopped](uint64_t) { stopped = true; }); + CasOperation op = requests.admit(); + const Layout layout("erase-conflict-stop"); + const CatalogEntry removing = removingEntryForStopTests(); + seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + backend->refuseNextWrite(layout.refCatalogKey()); + + size_t refreshes = 0; + { + const auto owner = OwnerScope::background([&stopped] + { + if (stopped) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::ABORTED, [&] + { + (void)deleteCompletedRemovingForTest(op, layout, removing, readyParentForStopTests(), [&refreshes] { ++refreshes; }); + }); + } + ASSERT_TRUE(stopped) << "premise: the erase conflicted and paused"; + EXPECT_EQ(refreshes, 1u) << "a refresh for a second decision"; + EXPECT_EQ(backend->writes(layout.refCatalogKey()), 2u) << "the seed and the conflicted erase"; EXPECT_EQ(CasRefCatalog::read(op, layout).catalog.entries, std::vector{removing}); } From c4bea6bc110b2ee0ac11988d444365af026bd61d Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:28:00 +0100 Subject: [PATCH 08/47] Let stopped callers leave the CAS ref-log queue A stopped follower withdraws its queued item, or waits for its result once a leader carved it. A leader checks its owner before each flush and withdraws its own pending item. An exceptional erase notifies waiters; a shared failure is rethrown as each thread's own copy. The leader flushes in its caller's thread group under `OwnerScope::shared`: CAS's owner checks do not reach shared work, but the S3 client still reports an unsuccessful answer as a killed leader's stop. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../Parts/PartFolderAccess.cpp | 7 +- .../ContentAddressed/Pool/CasPool.h | 3 + .../ContentAddressed/Pool/CasRefLedger.cpp | 77 ++- .../ContentAddressed/Pool/CasRefLedger.h | 36 +- src/Disks/tests/gtest_cas_parallel_commit.cpp | 156 +++++ .../tests/gtest_cas_ref_chunked_flush.cpp | 626 ++++++++++++++++++ 6 files changed, 887 insertions(+), 18 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp index 25be9bf06e2c2..6eea08da074c5 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp @@ -296,7 +296,7 @@ std::shared_ptr CachedPartFolderAccess::buildView( { /// The leader ran out of its own query's memory, which says nothing about this query's budget. if (!isMemoryLimitExceeded(e)) - throw; + rethrowOwnCopy(std::current_exception()); continue; } } @@ -316,8 +316,9 @@ std::shared_ptr CachedPartFolderAccess::buildView( catch (...) { retire(); - promise.set_exception(std::current_exception()); - throw; + /// The followers copy the published failure, so the leader leaves it untouched and throws its own copy. + promise.set_exception(ownerStopRequested() ? std::make_exception_ptr(LeaderStopped{}) : std::current_exception()); + rethrowOwnCopy(std::current_exception()); } promise.set_value(view); retire(); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h index f355f6ee7452c..06165e171f6f7 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h @@ -1091,6 +1091,9 @@ class Pool : public std::enable_shared_from_this /// caller's item join `rt->pending` before the carve, forcing deterministic co-batching. void setRefPreCarveHookForTest(std::function hook) { ref_ledger.setRefPreCarveHookForTest(std::move(hook)); } + /// Test-only: fires on a queued ref-log follower at each evaluation of its wait condition. + void setRefFollowerWaitHookForTest(std::function hook) { ref_ledger.setRefFollowerWaitHookForTest(std::move(hook)); } + /// Test-only: pre-tenure fault seam for the append-lane leadership acquisition; forwards to /// `CasRefLedger::setRefPreTenureHookForTest` (see it for the baton-safety contract). void setRefPreTenureHookForTest(std::function hook) { ref_ledger.setRefPreTenureHookForTest(std::move(hook)); } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index 81735b6456102..75bf59cb1c1a2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -2432,6 +2433,8 @@ RefTxnId CasRefLedger::appendRefOpsOnRuntime( catch (...) { std::erase(rt->pending, item); + /// The queue may now be drained, and a removal waits for that without a timeout. + rt->cv.notify_all(); throw; } @@ -2460,7 +2463,7 @@ RefTxnId CasRefLedger::appendRefOpsOnRuntime( } else { - rt->cv.wait(lk); + waitAsFollower(rt, item, lk); } } lk.unlock(); @@ -2468,16 +2471,50 @@ RefTxnId CasRefLedger::appendRefOpsOnRuntime( ProfileEvents::increment(ProfileEvents::CASRefQueueWaitMicroseconds, std::chrono::duration_cast( std::chrono::steady_clock::now() - enqueued_at).count()); + /// One failure can complete several items, each rethrown on its own caller's thread. if (item->error) - std::rethrow_exception(item->error); + rethrowOwnCopy(item->error); return item->committed_id; } +void CasRefLedger::waitAsFollower( + const std::shared_ptr & rt, const std::shared_ptr & item, std::unique_lock & lk) +{ + try + { + Cas::waitStoppable(rt->cv, lk, [&] + { + runRefFollowerWaitHook(FollowerWaitPhase::Queued); + return item->done || !rt->leader_active; + }); + } + catch (...) + { + /// A queued item still belongs to its caller and is withdrawn. Otherwise a leader owns it (or it is + /// done) and completes it, so the caller leaves only with that result; this wait has no owner check. + if (std::erase(rt->pending, item) > 0) + { + rt->cv.notify_all(); + throw; + } + rt->cv.wait(lk, [&] + { + runRefFollowerWaitHook(FollowerWaitPhase::Carved); + return item->done; + }); + } +} + void CasRefLedger::runRefQueueLeader(const RootNamespace & ns, const std::shared_ptr & rt, const std::shared_ptr & own, std::vector> & owned_items) { + /// Captured before `shared`, which leaves no owner to ask. + const std::function owner_check = Cas::OwnerScope::effectiveCheck(); + /// One caller's owner must not decide work done for several callers. + const auto shared = Cas::OwnerScope::shared(); + /// Fairness baton pass: serve flushes only until the caller's OWN item is done, then hand off to a /// woken waiter. while (true) @@ -2487,7 +2524,9 @@ void CasRefLedger::runRefQueueLeader(const RootNamespace & ns, const std::shared if (own->done) return; } - flushRefBatch(ns, rt, owned_items); + if (owner_check) + owner_check(); + flushRefBatch(ns, rt, owned_items, own, owner_check); } } @@ -3421,7 +3460,8 @@ bool CasRefLedger::ensureEpochOpenForAppend(const RootNamespace & ns, const std: } void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr & rt, - std::vector> & owned_items) + std::vector> & owned_items, + const std::shared_ptr & own, const std::function & owner_check) { /// One flush = one carved batch through one attempted append. Contract: every ORDINARY outcome /// (validation reject, DefiniteFailure, Unresolved/wedge, Committed) lands in the affected items so @@ -3445,12 +3485,18 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr } rt->cv.notify_all(); }; - auto carve_all_pending = [&]() -> std::vector> + /// Takes the error already built and allocates nothing, so no failure can leave a taken item neither queued + /// nor completed. + auto fail_all_pending = [&](const std::exception_ptr & e) { std::lock_guard g(ref_queue_mutex); - std::vector> all(rt->pending.begin(), rt->pending.end()); + for (const auto & it : rt->pending) + { + it->error = e; + it->done = true; + } rt->pending.clear(); - return all; + rt->cv.notify_all(); }; RefRecoveryOutcome recovery_outcome = RefRecoveryOutcome::Recovered; @@ -3460,13 +3506,12 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr } catch (...) { - complete_error(carve_all_pending(), std::current_exception()); + fail_all_pending(std::current_exception()); return; } if (recovery_outcome == RefRecoveryOutcome::LifeRemoved) { - complete_error(carve_all_pending(), - makeCasWriteRetryLaterExceptionPtr(recoveredLifeRemovedMessage(ns, rt->life))); + fail_all_pending(makeCasWriteRetryLaterExceptionPtr(recoveredLifeRemovedMessage(ns, rt->life))); return; } @@ -3474,7 +3519,7 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr /// Fails the WHOLE queue -- every caller would have gotten the same refusal alone. if (!may_mutate()) { - complete_error(carve_all_pending(), makeCasWriteRetryLaterExceptionPtr(fmt::format( + fail_all_pending(makeCasWriteRetryLaterExceptionPtr(fmt::format( "CAS mount lost / lease expired — refusing to append ref-log transactions for server_root '{}'", config.server_root_id))); return; @@ -3488,7 +3533,7 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr /// reaching this AFTER passing `mayMutate` above proves the swap happened. if (rt->superseded_by_remount.load(std::memory_order_acquire)) { - complete_error(carve_all_pending(), makeCasWriteRetryLaterExceptionPtr(fmt::format( + fail_all_pending(makeCasWriteRetryLaterExceptionPtr(fmt::format( "CAS ref-log append for server_root '{}': this cached table was superseded by a self-remount — " "retry against the fresh mount incarnation", config.server_root_id))); @@ -3517,7 +3562,7 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr case WedgeResolution::Rejected: case WedgeResolution::StillWedged: case WedgeResolution::Corrupted: - complete_error(carve_all_pending(), resolution.survivor_error); + fail_all_pending(resolution.survivor_error); return; } } @@ -3557,7 +3602,7 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr /// `CORRUPTED_DATA` about a stale premise this lane was never entitled to use. if (rt->superseded_by_remount.load(std::memory_order_acquire)) { - complete_error(carve_all_pending(), makeCasWriteRetryLaterExceptionPtr(fmt::format( + fail_all_pending(makeCasWriteRetryLaterExceptionPtr(fmt::format( "CAS ref-log append for server_root '{}': this cached table was superseded by a self-remount " "before its batch was carved — retry against the fresh mount incarnation", config.server_root_id))); @@ -3583,6 +3628,10 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr std::vector> batch; { std::lock_guard g(ref_queue_mutex); + /// Until carved, the leader's own item is still its caller's to withdraw; the leadership exit guard + /// removes it from `pending`. Outside the prelude's catch, which would fail the whole queue for one caller's stop. + if (owner_check && std::find(rt->pending.begin(), rt->pending.end(), own) != rt->pending.end()) + owner_check(); const size_t cap = table_live ? kMaxRefBatch : 1; /// --- PLAN --- diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h index c5353342fde3a..0a670278ffa0e 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h @@ -36,6 +36,22 @@ namespace DB::Cas /// re-validating anything. enum class ResolveAudit : uint8_t { Emit, Deferred }; +/// Where a queued ref-log follower evaluates its wait condition: `Queued` while it waits stoppably, `Carved` once +/// its owner stopped and a leader owns its item, a wait it must not leave before the item is done. +enum class FollowerWaitPhase : uint8_t { Queued, Carved }; + +/// Thrown when a namespace's positive ref-mutation admission is closed for a removal: the call was refused +/// before its mutation was queued, so it wrote nothing and bound nothing. Catch sites match by type; the code +/// and text are those of `throwCasWriteRetryLater`. +class RefAdmissionRefusedException : public Exception +{ +public: + explicit RefAdmissionRefusedException(const Exception & retry_later) : Exception(retry_later) {} + + RefAdmissionRefusedException * clone() const override { return new RefAdmissionRefusedException(*this); } + void rethrow() const override { throw *this; } // NOLINT +}; + /// The complete state of one table's append lane. It is guarded by `RefTableRuntime::state_mutex`; /// there is no independent apply marker or durable-id floor whose combinations form a second, /// implicit state machine. @@ -530,6 +546,10 @@ class CasRefLedger /// Installs the pre-tenure fault seam (see `ref_pre_tenure_hook_for_test`). void setRefPreTenureHookForTest(std::function hook) { ref_pre_tenure_hook_for_test = std::move(hook); } + /// Runs on a queued follower each time it evaluates its wait condition, under the queue mutex. It must not + /// lock anything, and it runs as `noexcept`: a throw terminates rather than unwinding out of the `Carved` wait. + void setRefFollowerWaitHookForTest(std::function hook) { ref_follower_wait_hook_for_test = std::move(hook); } + /// Pauses an ordinary append after it captured an exact runtime but before recovery or enqueue. void setAppendAfterRuntimeCaptureHookForTest(std::function hook) { @@ -1139,6 +1159,12 @@ class CasRefLedger /// idle (baton un-taken, the caller's item un-enqueued), never a permanently non-idle namespace with /// no live leader. Null in production. See `appendRefOps`. std::function ref_pre_tenure_hook_for_test; + std::function ref_follower_wait_hook_for_test; + void runRefFollowerWaitHook(FollowerWaitPhase phase) const noexcept + { + if (ref_follower_wait_hook_for_test) + ref_follower_wait_hook_for_test(phase); + } /// Test-only hook fired at each carve/validation phase point (see `CarvePhaseForTest`); null in /// production. @@ -1333,10 +1359,17 @@ class CasRefLedger /// Every item this leader becomes responsible for -- its own `own` plus each item a flush removes /// from `pending` to form a batch -- is recorded into `owned_items`, so the caller's leadership guard /// can complete + de-pend any that a flush leaves unfinished on an exceptional exit. + /// Every leader flushes in its caller's thread group under `OwnerScope::shared`. Its own item stays withdrawable by + /// its background owner until carved. void runRefQueueLeader(const RootNamespace & ns, const std::shared_ptr & rt, const std::shared_ptr & own, std::vector> & owned_items); + /// Waits, with `lk` held on return and on throw, until `item` is done or the lane needs a leader. + /// A stopped follower withdraws its queued item or waits for its carved result. + void waitAsFollower(const std::shared_ptr & rt, const std::shared_ptr & item, + std::unique_lock & lk); + /// Validates, durably appends, and applies one compatible batch while preserving copy-before-commit /// and apply-after-commit ordering -- the LIVE state is still only ever advanced once the object is /// durable; `commitRefChunk`'s pre-`PUT` apply targets a private candidate that nothing else can @@ -1346,7 +1379,8 @@ class CasRefLedger /// `ref_txn_max_ops`, the validation loop emits SEVERAL ref-log transactions in one tenure via /// `commitRefChunk` -- each a complete commit boundary. void flushRefBatch(const RootNamespace & ns, const std::shared_ptr & rt, - std::vector> & owned_items); + std::vector> & owned_items, + const std::shared_ptr & own, const std::function & owner_check); /// The lane's tombstone step, run by `flushRefBatch` before the batch copies its working state. /// True: the chain epoch equals the live epoch, or the stream is terminal, and the batch may proceed. diff --git a/src/Disks/tests/gtest_cas_parallel_commit.cpp b/src/Disks/tests/gtest_cas_parallel_commit.cpp index 0b275fe67863d..f0ded315df661 100644 --- a/src/Disks/tests/gtest_cas_parallel_commit.cpp +++ b/src/Disks/tests/gtest_cas_parallel_commit.cpp @@ -2,11 +2,16 @@ #include #include #include +#include #include +#include +#include #include #include #include #include +#include +#include /// Task 2 of the CAS parallel-write-path plan (docs/superpowers/sdd): `promoteBuild`/`repointRef` /// return an exact, in-lane-derived `Cas::CommitOutcome` instead of `void`/`bool`, and @@ -306,3 +311,154 @@ TEST(CASCommitRollback, RepointByOtherWriterSurvivesRollback) EXPECT_TRUE(fx.partAccess().existsRef(key, Cas::Freshness::ForceFresh)); EXPECT_EQ(fx.currentManifest(key), fx.lastRepointManifest()); } + +/// A commit whose query is killed between two part publications still rolls back the ref it created: +/// the compensation is owed to the failed commit, and it leads the ref-log queue on the killed thread. +/// The concurrent-repoint arm proves the compensation stays conditional on the manifest it bound. +TEST(CASPartFolderAccess, KilledCommitStillRollsBackCreatedRef) +{ + { + SCOPED_TRACE("created ref, nobody repoints it"); + auto fx = makeCaWiringFixture(); + const Cas::PartRefKey key{fx.ns(), "a_created_1_1_0"}; + auto txn = fx.beginTxn(); + fx.stageInto(txn, key, 1); + fx.stageInto(txn, {fx.ns(), "z_poison_1_1_0"}, 1); + fx.armPromoteFailure({fx.ns(), "z_poison_1_1_0"}); + bool killed = false; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + fx.armAfterPromoteHook(key, [&] { query.kill(); killed = true; }); + EXPECT_ANY_THROW(txn->commit({})); + }); + ASSERT_TRUE(killed) << "the query was not killed between the publications"; + EXPECT_FALSE(fx.partAccess().existsRef(key, Cas::Freshness::ForceFresh)) << "the created ref is rolled back"; + } + { + SCOPED_TRACE("created ref, another writer repoints it before the rollback"); + auto fx = makeCaWiringFixture(); + const Cas::PartRefKey key{fx.ns(), "a_shared_1_1_0"}; + auto txn = fx.beginTxn(); + fx.stageInto(txn, key, 1); + fx.stageInto(txn, {fx.ns(), "z_poison_1_1_0"}, 1); + fx.armPromoteFailure({fx.ns(), "z_poison_1_1_0"}); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + /// The repoint stands for another, live writer, so it lands before this query is killed. + fx.armAfterPromoteHook(key, [&] + { + fx.repointToFreshManifest(key); + query.kill(); + }); + EXPECT_ANY_THROW(txn->commit({})); + }); + EXPECT_TRUE(fx.partAccess().existsRef(key, Cas::Freshness::ForceFresh)); + EXPECT_EQ(fx.currentManifest(key), fx.lastRepointManifest()) << "another writer's binding survives"; + } +} + +/// The compensation of a killed commit stays owed when it queues behind another caller's flush: it is not +/// withdrawn as a stopped follower would be, and the created ref is rolled back. +TEST(CASPartFolderAccess, KilledCommitCompensationQueuedBehindLeaderStillRollsBack) +{ + auto fx = makeCaWiringFixture(); + const auto pool = fx.storage->poolForTest(); + const Cas::PartRefKey key{fx.ns(), "a_created_1_1_0"}; + auto txn = fx.beginTxn(); + fx.stageInto(txn, key, 1); + fx.stageInto(txn, {fx.ns(), "z_poison_1_1_0"}, 1); + fx.armPromoteFailure({fx.ns(), "z_poison_1_1_0"}); + + std::atomic follower_evaluations{0}; + std::atomic leader_entered{false}; + pool->setRefFollowerWaitHookForTest([&](DB::Cas::FollowerWaitPhase) { follower_evaluations.fetch_add(1); }); + const auto spin_until = [](auto ready) + { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (!ready() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + return ready(); + }; + std::thread other_leader; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + fx.armAfterPromoteHook(key, [&] + { + /// Armed only now: the commit's own publication has flushed already. The parked leader waits for the + /// compensation to queue, then for it to have either run its wait condition (owed, so it stays) or + /// left the queue (withdrawn). + pool->setRefPreCarveHookForTest([&] + { + if (leader_entered.exchange(true)) + return; + EXPECT_TRUE(spin_until([&] { return pool->refQueuePendingForTest(fx.ns()) >= 2; })) << "the compensation never queued"; + EXPECT_TRUE(spin_until([&] { return follower_evaluations.load() >= 1 || pool->refQueuePendingForTest(fx.ns()) < 2; })); + }); + other_leader = std::thread([&] { try { pool->dropRef(fx.ns(), "z_other_ref"); } catch (...) {} }); + EXPECT_TRUE(spin_until([&] { return leader_entered.load(); })) << "the other leader never parked"; + query.kill(); + }); + EXPECT_ANY_THROW(txn->commit({})); + }); + other_leader.join(); + pool->setRefPreCarveHookForTest(nullptr); + pool->setRefFollowerWaitHookForTest(nullptr); + + EXPECT_GE(follower_evaluations.load(), 1) << "the compensation never queued behind the leader"; + EXPECT_FALSE(fx.partAccess().existsRef(key, Cas::Freshness::ForceFresh)) << "the created ref is rolled back"; +} + +/// `ATTACH PART` and `DROP DETACHED PART` rename a detached part to a reserved name before they act, and +/// undo that rename with `moveFile` on failure. A query killed after the durable rename still gets its +/// original name back, and a retry succeeds. +TEST(CASPartFolderAccess, KilledAttachStillRestoresDetachedName) +{ + for (const std::string prefix : {"attaching_", "deleting_"}) + { + SCOPED_TRACE(prefix); + auto fx = makeCaWiringFixture(); + const std::string table = CaTxnRollbackFixture::tablePrefix(); + const std::string part = "all_1_1_0"; + const std::string detached = table + "/detached/" + part; + const std::string reserved = table + "/detached/" + prefix + part; + fx.commitSimplePart({fx.ns(), part}, 1); + { + auto txn = fx.beginTxn(); + txn->moveDirectory(table + "/" + part, detached); + txn->commit(DB::NoCommitOptions{}); + } + { + auto txn = fx.beginTxn(); + txn->moveDirectory(detached, reserved); + txn->commit(DB::NoCommitOptions{}); + } + ASSERT_TRUE(fx.storage->existsDirectory(reserved)); + + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + query.kill(); + auto txn = fx.beginTxn(); + EXPECT_NO_THROW({ + txn->moveFile(reserved, detached); + txn->commit(DB::NoCommitOptions{}); + }); + }); + + EXPECT_TRUE(fx.storage->existsDirectory(detached)) << "the original detached name is back"; + EXPECT_FALSE(fx.storage->existsDirectory(reserved)); + + { + auto txn = fx.beginTxn(); + txn->moveDirectory(detached, reserved); + txn->commit(DB::NoCommitOptions{}); + } + auto txn = fx.beginTxn(); + if (prefix == "attaching_") + txn->moveDirectory(reserved, table + "/all_2_2_0"); + else + txn->removeRecursive(reserved, nullptr); + txn->commit(DB::NoCommitOptions{}); + EXPECT_FALSE(fx.storage->existsDirectory(reserved)) << "the retry completes"; + EXPECT_EQ(fx.storage->existsDirectory(table + "/all_2_2_0"), prefix == "attaching_"); + } +} diff --git a/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp b/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp index d65a2e3b1ec66..34295f4079788 100644 --- a/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp +++ b/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp @@ -4,6 +4,7 @@ #include +#include #include #include #include @@ -13,13 +14,19 @@ #include #include #include +#include +#include #include #include +#include +#include #include #include +#include + #include #include #include @@ -39,6 +46,7 @@ extern const int LIMIT_EXCEEDED; extern const int CORRUPTED_DATA; extern const int NETWORK_ERROR; extern const int LOGICAL_ERROR; +extern const int ABORTED; } namespace ProfileEvents @@ -46,6 +54,7 @@ namespace ProfileEvents extern const Event CASRefBatchFlushes; extern const Event CASRefBatchedMutations; extern const Event CASRefSnapshotPublishDispatched; +extern const Event CASRefAppendWedged; } /// Task 8 (stage-1 §3 "Budget: counts only, chunked flush"): the counts-only admission caps -- @@ -1135,3 +1144,620 @@ TEST(CASRefWriterChunkedFlush, SnapshotPublisherLatchedAcrossChunks) EXPECT_FALSE(*newest < chunk2_id) << "settlement must re-fire the dropped chunk-2 trigger so a snapshot covers chunk 2 (no lost trigger)"; } + +/// =================================================================================== +/// A leader flushes in its caller's thread group. A killed query does not stop the shared flush, and a stopped +/// background owner can still withdraw the leader's own item until the carve. +/// =================================================================================== + +namespace +{ + +using DB::Cas::tests::CasClientLikeBackend; +using DB::Cas::tests::CasKillableQuery; +using DB::Cas::tests::StoppedBy; +using DB::Cas::tests::backgroundOwnerStoppedBy; +using DB::Cas::tests::nameOf; +using DB::Cas::tests::stopperOf; + +constexpr auto KILL_WATCHDOG = std::chrono::seconds(30); + +/// Calls `before_answer` before the first ref-log create under `log_prefix` after `armed` is set, then stores it. +class LeaderKillLogPutBackend final : public DB::Cas::tests::CountingBackend +{ +public: + String log_prefix; + std::function before_answer; + std::atomic armed{false}; + std::atomic fired{false}; + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (!expected_value && key.starts_with(log_prefix) && armed.exchange(false)) + { + fired = true; + if (before_answer) + before_answer(); + } + return CountingBackend::write(key, bytes, expected_value, access); + } +}; + +struct KilledLeaderFixture +{ + std::shared_ptr faults = std::make_shared(); + PoolPtr store; + std::shared_ptr clock; + RootNamespace ns; + + explicit KilledLeaderFixture(const String & ns_suffix) + : ns(String("srv1/") + ns_suffix) + { + store = openPoolWith(std::make_shared(faults), PoolConfig{}); + clock = VirtualRetryClock::installOn(store); + publishEmptyPart(store, ns, "seed"); + faults->log_prefix = store->layout().namespaceStreamPrefix(DB::Cas::tests::fixture::fixtureLife(ns)) + "_log/"; + } +}; + +int exceptionCode(const std::exception_ptr & e) +{ + if (!e) + return 0; + try + { + std::rethrow_exception(e); + } + catch (const DB::Exception & ex) + { + return ex.code(); + } + catch (...) + { + return -1; + } +} + +/// The leader's side of a killed-leader case, run on a raw thread with its own `ThreadStatus` and a +/// query registered in the process list. `body` gets the query and returns the append's result. +struct LeaderRun +{ + AppendResult result; + bool group_restored = false; +}; + +template +std::future launchQueryLeader(std::thread & thread, Body leader_body) +{ + auto prom = std::make_shared>(); + std::future fut = prom->get_future(); + thread = std::thread([prom, body = std::move(leader_body)]() mutable + { + std::optional thread_status; + thread_status.emplace(); + LeaderRun run; + { + CasKillableQuery query(getContext().context); + run.result = body(query); + run.group_restored = DB::CurrentThread::getGroup() == query.group; + } + prom->set_value(run); + }); + return fut; +} + +/// The leader's item and a neighbor's share one chunk; the leader's query is killed between the carve +/// and the chunk's first answer. +struct KilledLeaderOutcome +{ + LeaderRun leader; + AppendResult neighbor; + int neighbor_builds = 0; +}; + +KilledLeaderOutcome runKilledLeaderChunk(KilledLeaderFixture & fx) +{ + auto sync = std::make_shared(); + armPreCarveBlock(fx.store, fx.ns, sync, 2); + auto neighbor_builds = std::make_shared>(0); + + std::thread leader_thread; + std::future leader = launchQueryLeader(leader_thread, [&fx](CasKillableQuery & query) + { + fx.faults->before_answer = [&query] { query.kill(); }; + fx.faults->armed = true; + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [](const RefTableState &) { return addRemovePrecommitPairs("item_leader", 1, 910000001); }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + return r; + }); + waitEntered(sync); + AppendCaller neighbor = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_neighbor"), + addRemovePrecommitPairs("item_neighbor", 1, 910000002), neighbor_builds); + waitPendingAtLeast(fx.store, fx.ns, 2); + sync->cv.notify_all(); + + KilledLeaderOutcome out; + EXPECT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the killed leader must not hang"; + EXPECT_EQ(neighbor.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the neighbor must not hang"; + out.leader = leader.get(); + out.neighbor = neighbor.fut.get(); + leader_thread.join(); + neighbor.t.join(); + fx.faults->before_answer = {}; + fx.store->setRefPreCarveHookForTest(nullptr); + out.neighbor_builds = neighbor_builds->load(); + return out; +} + +} + +/// A leader's query killed after the carve, on a store that answers every request successfully: the kill does not +/// stop the shared flush, so the chunk commits once for the leader's item and the neighbor's. +TEST(CASRefWriterChunkedFlush, KilledLeaderOnHealthyStoreCommitsWithNeighbor) +{ + KilledLeaderFixture fx("killed_leader_healthy_store"); + const uint64_t wedged_before = ProfileEvents::global_counters[ProfileEvents::CASRefAppendWedged]; + + const KilledLeaderOutcome out = runKilledLeaderChunk(fx); + + ASSERT_TRUE(fx.faults->fired) << "the kill never ran before the chunk's create"; + EXPECT_EQ(exceptionCode(out.leader.result.err), 0) << "a killed query's carved item commits"; + EXPECT_EQ(exceptionCode(out.neighbor.err), 0) << "a live neighbor must commit"; + EXPECT_EQ(out.leader.result.id, out.neighbor.id) << "both items were in one chunk"; + EXPECT_EQ(out.neighbor_builds, 1); + EXPECT_TRUE(out.leader.group_restored); + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRefAppendWedged] - wedged_before, 0u); + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + EXPECT_EQ(std::count_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == out.neighbor.id; }), 1) + << "the chunk is durable exactly once"; +} + +/// Leaving a query's thread group finalizes the thread's counters and writes a `system.query_thread_log` row, so a +/// leader must flush in its caller's group: the same group before the append, inside the flush and after it. +TEST(CASRefWriterChunkedFlush, LeaderFlushesInItsCallersThreadGroup) +{ + KilledLeaderFixture fx("leader_keeps_thread_group"); + DB::ThreadGroupPtr group_before; + DB::ThreadGroupPtr group_inside_flush; + DB::ThreadGroupPtr group_after; + bool hook_ran = false; + + std::thread leader_thread; + std::future leader = launchQueryLeader(leader_thread, [&](CasKillableQuery &) + { + group_before = DB::CurrentThread::getGroup(); + fx.store->setRefPreCarveHookForTest([&] + { + hook_ran = true; + group_inside_flush = DB::CurrentThread::getGroup(); + }); + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [](const RefTableState &) { return addRemovePrecommitPairs("item_leader", 1, 945000001); }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + group_after = DB::CurrentThread::getGroup(); + return r; + }); + ASSERT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready); + const LeaderRun run = leader.get(); + leader_thread.join(); + fx.store->setRefPreCarveHookForTest(nullptr); + + EXPECT_EQ(exceptionCode(run.result.err), 0); + ASSERT_TRUE(hook_ran) << "the hook did not run inside the flush"; + ASSERT_NE(group_before, nullptr); + EXPECT_EQ(group_inside_flush, group_before) << "the flush left the caller's thread group"; + EXPECT_EQ(group_after, group_before); + EXPECT_TRUE(run.group_restored); +} + +namespace +{ + +/// The leader's owner stops during the flush prelude while a live waiter's item is queued behind it. +void runLeaderStoppedDuringFlushPrelude(StoppedBy owner) +{ + KilledLeaderFixture fx("killed_leader_withdraws"); + auto leader_builds = std::make_shared>(0); + auto neighbor_builds = std::make_shared>(0); + auto sync = std::make_shared(); + std::function stop_leader; + + fx.store->setRefPreCarveHookForTest([&, sync] + { + std::unique_lock lk(sync->m); + if (sync->entered) + return; + sync->entered = true; + sync->cv.notify_all(); + sync->cv.wait_for(lk, KILL_WATCHDOG, [&] { return fx.store->refQueuePendingForTest(fx.ns) >= 2; }); + stop_leader(); + }); + + std::thread leader_thread; + std::future leader = launchQueryLeader(leader_thread, [&](CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = backgroundOwnerStoppedBy(background_stopped); + stop_leader = stopperOf(owner, query, background_stopped); + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [leader_builds](const RefTableState &) + { + leader_builds->fetch_add(1); + return addRemovePrecommitPairs("item_leader", 1, 920000001); + }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + return r; + }); + waitEntered(sync); + AppendCaller neighbor = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_neighbor"), + addRemovePrecommitPairs("item_neighbor", 1, 920000002), neighbor_builds); + waitPendingAtLeast(fx.store, fx.ns, 2); + sync->cv.notify_all(); + + ASSERT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the stopped leader must not hang"; + ASSERT_EQ(neighbor.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the neighbor must not hang"; + const LeaderRun run = leader.get(); + const AppendResult rn = neighbor.fut.get(); + leader_thread.join(); + neighbor.t.join(); + fx.store->setRefPreCarveHookForTest(nullptr); + + EXPECT_EQ(exceptionCode(rn.err), 0) << "the live waiter commits"; + EXPECT_EQ(neighbor_builds->load(), 1); + EXPECT_TRUE(run.group_restored); + EXPECT_EQ(fx.store->refQueuePendingForTest(fx.ns), 0u); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + const auto neighbor_txn = std::find_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == rn.id; }); + ASSERT_NE(neighbor_txn, logs.end()); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(exceptionCode(run.result.err), DB::ErrorCodes::ABORTED); + EXPECT_EQ(leader_builds->load(), 0) << "a withdrawn item is never built"; + EXPECT_EQ(neighbor_txn->ops, addRemovePrecommitPairs("item_neighbor", 1, 920000002)) << "the neighbor commits alone"; + } + else + { + EXPECT_EQ(exceptionCode(run.result.err), 0) << "a killed leader's item commits"; + EXPECT_EQ(leader_builds->load(), 1); + EXPECT_EQ(run.result.id, rn.id) << "both items were carved into one chunk"; + } +} + +} + +/// A background stop during the flush prelude withdraws the leader's own item at the carve: its `build_ops` never +/// runs, it gets the owner's verdict, and the live waiter's item commits alone. +TEST(CASRefWriterChunkedFlush, BackgroundStoppedLeaderWithdrawsOwnItemAtCarve) +{ + runLeaderStoppedDuringFlushPrelude(StoppedBy::Background); +} + +/// A leader killed during the flush prelude keeps its item: it is carved with the waiter's and the chunk commits for both. +TEST(CASRefWriterChunkedFlush, KilledLeadersItemIsCarvedAndCommitted) +{ + runLeaderStoppedDuringFlushPrelude(StoppedBy::Query); +} + +namespace +{ + +/// A leader whose owner stopped before its flush, on a lane with an outstanding wedge. +void runLeaderStoppedBeforeItsFlush(StoppedBy owner) +{ + KilledLeaderFixture fx("killed_leader_before_flush"); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + ASSERT_FALSE(logs.empty()); + RefLogTxn wedged; + wedged.ns = fx.ns.string(); + wedged.txn_id = logs.back().txn_id; + ++wedged.txn_id.ref_sequence; + wedged.ops = addRemovePrecommitPairs("item_wedged", 1, 940000002); + fx.store->forceWedgeForTest(fx.ns, wedged.txn_id.writer_epoch, wedged.txn_id.ref_sequence, + fx.store->layout().refLogKey(DB::Cas::tests::fixture::fixtureLife(fx.ns), wedged.txn_id), + sealObject(FormatId::RefLog, encodeRefLogTxn(wedged))); + auto builds = std::make_shared>(0); + size_t requests = 0; + + std::thread leader_thread; + std::future leader = launchQueryLeader(leader_thread, [&](CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = backgroundOwnerStoppedBy(background_stopped); + stopperOf(owner, query, background_stopped)(); + const size_t before = fx.faults->journal().size(); + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [builds](const RefTableState &) + { + builds->fetch_add(1); + return addRemovePrecommitPairs("item_leader", 1, 940000001); + }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + requests = fx.faults->journal().size() - before; + return r; + }); + ASSERT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the stopped leader must not hang"; + const LeaderRun run = leader.get(); + leader_thread.join(); + + EXPECT_EQ(fx.store->refQueuePendingForTest(fx.ns), 0u); + EXPECT_TRUE(run.group_restored); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(exceptionCode(run.result.err), DB::ErrorCodes::ABORTED); + EXPECT_EQ(requests, 0u) << "a stopped leader starts no flush"; + EXPECT_EQ(builds->load(), 0); + EXPECT_TRUE(fx.store->refLaneWedgedForTest(fx.ns)) << "the wedge is left for a live leader"; + } + else + { + EXPECT_EQ(exceptionCode(run.result.err), 0) << "a killed query's leader flushes on a healthy store"; + EXPECT_GT(requests, 0u); + EXPECT_EQ(builds->load(), 1); + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)) << "the leader resolved the wedge"; + } +} + +} + +/// A leader whose background owner stopped before its flush sends nothing: not even the read that resolves the lane's +/// outstanding wedge. The carve check alone would let that read go out first. +TEST(CASRefWriterChunkedFlush, BackgroundStoppedLeaderSendsNothingBeforeItsFlush) +{ + runLeaderStoppedBeforeItsFlush(StoppedBy::Background); +} + +/// A leader whose query was killed before its flush flushes on a healthy store: it resolves the wedge and commits its +/// item. +TEST(CASRefWriterChunkedFlush, KilledLeaderResolvesTheWedgeAndCommits) +{ + runLeaderStoppedBeforeItsFlush(StoppedBy::Query); +} + +namespace +{ + +template +void waitUntil(const char * what, Body ready) +{ + const auto deadline = std::chrono::steady_clock::now() + KILL_WATCHDOG; + while (!ready() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + ASSERT_TRUE(ready()) << what; +} + +/// A follower on its own query thread. Its `build_ops` runs `on_build` and writes into a local of the follower's +/// own frame, so a follower that returned while its item was carved would leave the leader writing to a dead +/// frame (ASan reports it). `returned` is set when the follower's call has returned. +std::future launchQueryFollower( + std::thread & thread, KilledLeaderFixture & fx, const String & ref, std::atomic & builds, int64_t seed, + std::function & kill, std::function on_build, std::atomic & returned, StoppedBy owner) +{ + return launchQueryLeader( + thread, [&fx, ref, &builds, seed, &kill, build_hook = std::move(on_build), &returned, owner](CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = backgroundOwnerStoppedBy(background_stopped); + kill = stopperOf(owner, query, background_stopped); + int frame_slot = 0; + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref(ref), + [&builds, &frame_slot, build_hook, ref, seed](const RefTableState &) + { + builds.fetch_add(1); + if (build_hook) + build_hook(); + frame_slot = 1; + return addRemovePrecommitPairs(ref, 1, seed); + }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + returned = true; + return r; + }); +} + +} + +namespace +{ + +/// A follower's owner stops while its item is queued behind a parked leader. +void runFollowerStoppedWhileQueued(StoppedBy owner) +{ + KilledLeaderFixture fx("killed_pending_follower"); + auto sync = std::make_shared(); + bool released = false; + fx.store->setRefPreCarveHookForTest([sync, &released] + { + std::unique_lock lk(sync->m); + if (sync->entered) + return; + sync->entered = true; + sync->cv.notify_all(); + sync->cv.wait_for(lk, KILL_WATCHDOG, [&] { return released; }); + }); + auto leader_builds = std::make_shared>(0); + std::atomic follower_builds{0}; + std::atomic follower_returned{false}; + std::function stop_follower; + std::atomic follower_wait_checks{0}; + fx.store->setRefFollowerWaitHookForTest([&](FollowerWaitPhase) { follower_wait_checks.fetch_add(1); }); + + AppendCaller leader = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_leader"), + addRemovePrecommitPairs("item_leader", 1, 950000001), leader_builds); + waitEntered(sync); + std::thread follower_thread; + std::future follower = launchQueryFollower( + follower_thread, fx, "item_follower", follower_builds, 950000002, stop_follower, {}, follower_returned, owner); + waitPendingAtLeast(fx.store, fx.ns, 2); + ASSERT_GE(fx.store->refQueuePendingForTest(fx.ns), 2u); + const int checks_before_stop = follower_wait_checks.load(); + stop_follower(); + /// The leader stays parked until a stopped background owner's follower has left the queue. A killed query's + /// follower is given two evaluations of its wait, so its owner was asked after the kill, and must still be queued. + if (owner == StoppedBy::Background) + { + waitUntil("the stopped follower never withdrew its item", [&] { return fx.store->refQueuePendingForTest(fx.ns) <= 1; }); + } + else + { + waitUntil("the follower's wait was not re-evaluated", [&] { return follower_wait_checks.load() >= checks_before_stop + 2; }); + EXPECT_EQ(fx.store->refQueuePendingForTest(fx.ns), 2u) << "a killed query's follower withdrew its item"; + } + { + std::lock_guard lk(sync->m); + released = true; + } + sync->cv.notify_all(); + + ASSERT_EQ(follower.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the stopped follower must not hang"; + ASSERT_EQ(leader.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the leader must not hang"; + const LeaderRun run = follower.get(); + const AppendResult rl = leader.fut.get(); + follower_thread.join(); + leader.t.join(); + fx.store->setRefPreCarveHookForTest(nullptr); + fx.store->setRefFollowerWaitHookForTest(nullptr); + + EXPECT_EQ(exceptionCode(rl.err), 0); + EXPECT_EQ(leader_builds->load(), 1); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + const auto leader_txn = std::find_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == rl.id; }); + ASSERT_NE(leader_txn, logs.end()); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(exceptionCode(run.result.err), DB::ErrorCodes::ABORTED); + EXPECT_EQ(follower_builds.load(), 0) << "a withdrawn item is never built"; + EXPECT_EQ(leader_txn->ops, addRemovePrecommitPairs("item_leader", 1, 950000001)) << "the withdrawn item is absent"; + } + else + { + EXPECT_EQ(exceptionCode(run.result.err), 0) << "a killed query's queued item commits"; + EXPECT_EQ(follower_builds.load(), 1); + const bool follower_committed + = std::any_of(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == run.result.id; }); + EXPECT_TRUE(follower_committed); + } +} + +} + +/// A follower whose background owner stopped while its item is queued withdraws it: it gets the owner's verdict, its +/// `build_ops` never runs, nothing of it reaches the log, and the leader then commits alone. +TEST(CASRefWriterChunkedFlush, BackgroundStoppedPendingFollowerWithdrawsWhileLeaderBlocked) +{ + runFollowerStoppedWhileQueued(StoppedBy::Background); +} + +/// A follower whose query was killed while its item is queued stays queued and commits with the leader. +TEST(CASRefWriterChunkedFlush, KilledPendingFollowerStaysQueuedAndCommits) +{ + runFollowerStoppedWhileQueued(StoppedBy::Query); +} + +/// A follower whose item was carved belongs to the batch: its background owner stops after the carve and before +/// its `build_ops` returns, and the follower sees the stop while the item is carved and not done. It still waits +/// for the chunk and returns the committed id. A killed query's follower never sees a stop and gets the same id. +TEST(CASRefWriterChunkedFlush, KilledCarvedFollowerWaitsForActualResult) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + SCOPED_TRACE(nameOf(owner)); + KilledLeaderFixture fx("killed_carved_follower"); + auto sync = std::make_shared(); + armPreCarveBlock(fx.store, fx.ns, sync, 2); + auto leader_builds = std::make_shared>(0); + std::atomic follower_builds{0}; + std::atomic follower_returned{false}; + std::atomic carved_waits{0}; + std::function stop_follower; + fx.store->setRefFollowerWaitHookForTest([&](FollowerWaitPhase phase) + { + if (phase == FollowerWaitPhase::Carved) + carved_waits.fetch_add(1); + }); + /// Runs on the leader's thread, after the carve: stop the follower, then hold the batch until a stopped + /// background owner's follower has seen the stop and entered its carved wait, or has wrongly returned. + const auto stop_follower_while_carved = [&] + { + stop_follower(); + if (owner == StoppedBy::Query) + return; + const auto deadline = std::chrono::steady_clock::now() + KILL_WATCHDOG; + while (carved_waits.load() == 0 && !follower_returned && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + }; + + AppendCaller leader = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_leader"), + addRemovePrecommitPairs("item_leader", 1, 960000001), leader_builds); + waitEntered(sync); + std::thread follower_thread; + std::future follower = launchQueryFollower( + follower_thread, fx, "item_follower", follower_builds, 960000002, stop_follower, stop_follower_while_carved, + follower_returned, owner); + waitPendingAtLeast(fx.store, fx.ns, 2); + sync->cv.notify_all(); + + ASSERT_EQ(follower.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the carved follower must not hang"; + ASSERT_EQ(leader.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the leader must not hang"; + const LeaderRun run = follower.get(); + const AppendResult rl = leader.fut.get(); + follower_thread.join(); + leader.t.join(); + fx.store->setRefFollowerWaitHookForTest(nullptr); + fx.store->setRefPreCarveHookForTest(nullptr); + + if (owner == StoppedBy::Background) + EXPECT_GE(carved_waits.load(), 1) << "the follower never saw its stop while its item was carved"; + else + EXPECT_EQ(carved_waits.load(), 0) << "a killed query is not a stop for the follower's wait"; + EXPECT_EQ(exceptionCode(run.result.err), 0) << "a carved item reports its chunk's result, not its owner's verdict"; + EXPECT_EQ(exceptionCode(rl.err), 0); + EXPECT_EQ(run.result.id, rl.id) << "both items were in one chunk"; + EXPECT_EQ(follower_builds.load(), 1); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + EXPECT_EQ(std::count_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == rl.id; }), 1); + } +} From ec2a7ea7727296e33418a296e33816b998f54f74 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:28:02 +0100 Subject: [PATCH 09/47] Stop CAS ref-table recovery between failed walks Only a walk that threw lets a stopped owner end recovery; the walk itself is owed. A sent stamp or tombstone that stays unresolved keeps its retry-later exit after a stop, and a query stop confirms real corruption before ending recovery. The backoff sleeps in slices, and a stopped background owner leaves the wait for another caller's recovery. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressed/Pool/CasPool.cpp | 5 + .../ContentAddressed/Pool/CasPool.h | 3 + .../ContentAddressed/Pool/CasRefCkpt.cpp | 8 +- .../ContentAddressed/Pool/CasRefCkpt.h | 4 + .../ContentAddressed/Pool/CasRefLedger.cpp | 192 +++- .../ContentAddressed/Pool/CasRefLedger.h | 21 +- .../ContentAddressed/Pool/CasRefProtocol.cpp | 5 +- .../ContentAddressed/Pool/CasRefProtocol.h | 5 +- src/Disks/tests/gtest_cas_detached_work.cpp | 92 ++ .../tests/gtest_cas_recovery_streaming.cpp | 103 ++ .../tests/gtest_cas_ref_recovery_cas_walk.cpp | 416 ++++++- src/Disks/tests/gtest_cas_ref_writer.cpp | 1018 ++++++++++++++++- 12 files changed, 1810 insertions(+), 62 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp index 81a99d28b50b3..0b6e60b669def 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp @@ -2202,6 +2202,11 @@ void Pool::setRefRecoveryRetrySleepForTest( ref_ledger.setRefRecoveryRetrySleepForTest(std::move(sleep_fn)); } +void Pool::setRefRecoveryRetrySliceSleepForTest(std::function sleep_fn) +{ + ref_ledger.setRefRecoveryRetrySliceSleepForTest(std::move(sleep_fn)); +} + std::optional Pool::resolveRef(const RootNamespace & ns, const String & ref_name, bool allow_stale, ResolveAudit audit) { return ref_ledger.resolveRef(ns, ref_name, allow_stale, audit); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h index 06165e171f6f7..40dea0b2ea08f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h @@ -1194,6 +1194,9 @@ class Pool : public std::enable_shared_from_this void setRefRecoveryRetrySleepForTest( std::function &)> sleep_fn); + /// Test-only: replace the single-slice sleep inside the default recovery retry delay. Same rule. + void setRefRecoveryRetrySliceSleepForTest(std::function sleep_fn); + /// Queue depth for the ref-append-lane tests (mirrors `shardQueuePendingForTest`): how many /// `appendRefOps` callers are enqueued for `ns` right now. size_t refQueuePendingForTest(const RootNamespace & ns) { return ref_ledger.refQueuePendingForTest(ns); } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.cpp index 84872f6173970..7b7682fe8116d 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.cpp @@ -175,9 +175,11 @@ CkptStampResult stampCkptGeneration3(CasOperation & op, const Layout & layout, c return CkptStampResult{.outcome = CkptStampOutcome::Stamped, .stamped = CkptSample{.ckpt = std::move(stamped), .etag = committed->etag}}; } - if (std::holds_alternative(result)) - return CkptStampResult{.outcome = CkptStampOutcome::TokenMismatch, .stamped = std::nullopt}; - return CkptStampResult{.outcome = CkptStampOutcome::Unresolved, .stamped = std::nullopt}; + if (const auto * conflict = std::get_if(&result)) + return CkptStampResult{.outcome = CkptStampOutcome::TokenMismatch, .stamped = std::nullopt, + .observed_stop = conflict->observed_stop}; + const auto * gave_up = std::get_if(&result); + return CkptStampResult{.outcome = CkptStampOutcome::Unresolved, .stamped = std::nullopt, .sent_any = gave_up && gave_up->sent_any}; } MissingBaseVerdict classifyMissingSampledBase(const Etag & sampled, const std::optional & current) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.h index eb0d1dba32253..d070a46d4ad6b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.h @@ -90,6 +90,10 @@ struct CkptStampResult CkptStampOutcome outcome; /// Set iff `Stamped`: the body now durable and the token it was written under. std::optional stamped; + /// True only for an `Unresolved` write that was sent and may still land; false when nothing that may land was sent. + bool sent_any = false; + /// For `TokenMismatch`: the query stopped and cut short the read that settles the refusal. + bool observed_stop = false; }; /// One conditional replace on `accepted.etag` with `{life_epoch, checkpoint_snapshot_id}` at generation 3. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index 75bf59cb1c1a2..0099e2f13e268 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -285,22 +285,34 @@ CasRefLedger::CasRefLedger( , cancel_inflight_builds(std::move(cancel_inflight_builds_)) , recovery_pre_first_request_hook_for_test(std::move(recovery_pre_first_request_hook_for_test_)) { - /// Default backoff sleep for the recovery retry loop (`ensureRefTableRecovered`): sleep in short - /// slices and stop early if the mount fence drops (shutdown / lease loss), so teardown never waits - /// out a full 30s backoff. This is deliberate, bounded backoff against external object-store I/O - /// failure -- NOT masking a race -- exactly like the request engine's own inter-attempt sleep; the - /// slice loop additionally makes it interruptible, which that one is not. - recovery_retry_sleep_fn = [this](uint64_t total_ms, const std::optional & token) - { - constexpr uint64_t slice_ms = 200; - uint64_t slept = 0; - while (slept < total_ms && fence_ok_fn() && !(token && token->stopping())) - { - const uint64_t chunk = std::min(slice_ms, total_ms - slept); - sleepForMilliseconds(chunk); - slept += chunk; + recovery_retry_slice_sleep_fn = [](uint64_t ms) { sleepForMilliseconds(ms); }; +} + +void CasRefLedger::pauseBeforeRecoveryRetry(uint64_t total_ms, const std::optional & token) +{ + /// A test's whole-pause sleep is one slice, so the checks below run before it as before every slice. + const uint64_t slice_ms = recovery_retry_pause_sleep_for_test ? total_ms : static_cast(Cas::kOwnerStopSlice.count()); + uint64_t slept = 0; + do + { + if (!fence_ok_fn() || (token && token->stopping())) + return; + /// A stopped owner ends the pause before a new walk, as it ends the pause before an S3 reissue: a + /// background owner with its verdict, a query by returning early to the caller's veto. + Cas::throwIfBackgroundStopped(); + if (!Cas::insideOwed() && Cas::queryStopRequested()) + return; + if (recovery_retry_pause_sleep_for_test) + { + recovery_retry_pause_sleep_for_test(total_ms, token); + return; } - }; + if (total_ms == 0) + return; + const uint64_t chunk = std::min(slice_ms, total_ms - slept); + recovery_retry_slice_sleep_fn(chunk); + slept += chunk; + } while (slept < total_ms); } WriteResult CasRefLedger::stagingPutIfAbsent(const String & key, const String & bytes) @@ -330,7 +342,7 @@ void CasRefLedger::throwNotAdmitted(std::string_view what) const void CasRefLedger::setCasRetrySleepForTest(std::function sleep_fn) { mount_requests.setSleepFnForTest(sleep_fn); - recovery_retry_sleep_fn = [recovery_sleep_fn = std::move(sleep_fn)]( + recovery_retry_pause_sleep_for_test = [recovery_sleep_fn = std::move(sleep_fn)]( uint64_t total_ms, const std::optional &) { recovery_sleep_fn(total_ms); @@ -340,7 +352,12 @@ void CasRefLedger::setCasRetrySleepForTest(std::function sleep_f void CasRefLedger::setRefRecoveryRetrySleepForTest( std::function &)> sleep_fn) { - recovery_retry_sleep_fn = std::move(sleep_fn); + recovery_retry_pause_sleep_for_test = std::move(sleep_fn); +} + +void CasRefLedger::setRefRecoveryRetrySliceSleepForTest(std::function sleep_fn) +{ + recovery_retry_slice_sleep_fn = std::move(sleep_fn); } @@ -1163,7 +1180,7 @@ void CasRefLedger::checkRecoveryStillAdmitted(const RootNamespace & ns, RefTable std::optional CasRefLedger::runRecoveryWalkOnce( const RootNamespace & ns, RefTableRuntime & rt, uint64_t admitted_generation, const LiveEpochPair & live, const std::optional & retained_attempt, std::optional & hole_detail, - bool & cancelled, const std::optional & token) + bool & cancelled, bool & unresolved_sent, const std::optional & token) { /// One attempt. Runs with NO lock held: everything below is either read-only I/O or a conditional /// write at a key this namespace owns, and the replayed candidate is PRIVATE until the caller @@ -1182,13 +1199,15 @@ std::optional CasRefLedger::runRecoveryWalkOnce( /// is the fence's. The predicate is a bool where the poll throws, so the poll still runs at the /// boundaries: it turns each of these facts into the right exception and LATCHES a cancellation for /// the caller's retry classification. - CasOperation op = mount_requests.resume(admitted_generation, [&rt, &token] + /// An admission check, not an owner: its terms hold inside an owed walk too. + const auto recovery_request_still_admitted = [&rt, &token] { return !(token && token->stopping()) && !rt.recovery_cancel_requested.load(std::memory_order_acquire) && !rt.catalog_life_invalidated.load(std::memory_order_acquire) && !rt.superseded_by_remount.load(std::memory_order_acquire); - }); + }; + CasOperation op = mount_requests.resume(admitted_generation, recovery_request_still_admitted); /// ---- The checkpoint and the base ---- /// The runtime was admitted for this exact life before entering recovery, so this walk takes no @@ -1225,7 +1244,8 @@ std::optional CasRefLedger::runRecoveryWalkOnce( } catch (const Exception & e) { - if (!failureJudgedAgainstCkpt(e.code())) + /// A query's stored cause says nothing about the checkpoint, whatever its code. + if (!failureJudgedAgainstCkpt(e.code()) || Cas::isQueryStoredCause(std::current_exception())) throw; /// A newer checkpoint may have re-anchored recovery while cleanup retired this old anchor's @@ -1302,6 +1322,13 @@ std::optional CasRefLedger::runRecoveryWalkOnce( return true; }; + /// Marks the error of a sent write that may still land, so a later owner stop does not replace it. + const auto throwUnresolved = [&unresolved_sent](bool sent_any, const String & message) + { + unresolved_sent = sent_any; + throwCasRequestRetryLater(message); + }; + /// The walk never re-reads `_ckpt` itself: the re-read after the last read or write of this attempt /// covers its end and every tombstone create. RefChainOrigin origin{ @@ -1360,10 +1387,15 @@ std::optional CasRefLedger::runRecoveryWalkOnce( { checkRecoveryStillAdmitted(ns, rt, cancelled, token); CkptStampResult stamp = stampCkptGeneration3(op, layout, life, accepted); + /// The 412 proves the stamp did not land; the stop ends this walk rather than starting another. + if (stamp.outcome == CkptStampOutcome::TokenMismatch && stamp.observed_stop) + throwCasRequestRetryLater(fmt::format( + "CAS ref-table recovery for namespace '{}': the query stopped after its refused generation 3 stamp " + "of `_ckpt`; nothing is installed", ns.string())); if (stamp.outcome == CkptStampOutcome::TokenMismatch) return std::nullopt; if (stamp.outcome == CkptStampOutcome::Unresolved) - throwCasRequestRetryLater(fmt::format( + throwUnresolved(stamp.sent_any, fmt::format( "CAS ref-table recovery for namespace '{}': the generation 3 stamp of its `_ckpt` is " "unresolved; nothing is installed", ns.string())); accepted = std::move(*stamp.stamped); @@ -1437,7 +1469,7 @@ std::optional CasRefLedger::runRecoveryWalkOnce( } if (const auto * gave_up = std::get_if(&created)) - throwCasRequestRetryLater(fmt::format( + throwUnresolved(gave_up->sent_any, fmt::format( "CAS ref-table recovery for namespace '{}': the tombstone at {}-{} is UNRESOLVED ({}); the " "table stays unrecovered", ns.string(), id.writer_epoch, id.ref_sequence, gave_up->sent_any ? "the outcome of the attempt is unknown" : "nothing was sent")); @@ -1625,14 +1657,15 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( return RefRecoveryOutcome::Recovered; /// A concurrent second caller waits here rather than racing an independent walk against the first - /// caller's unlocked I/O. + /// caller's unlocked I/O. The walk belongs to another caller, so this caller's query does not end the wait. while (rt.recovery_in_progress) { if (token && token->stopping()) throw Exception(ErrorCodes::ABORTED, "CAS ref recovery: teardown began while waiting for a concurrent recovery"); + Cas::throwIfBackgroundStopped(); ++rt.recovery_waiters_for_test; - rt.recovery_cv.wait_for(lock, std::chrono::milliseconds(200)); + rt.recovery_cv.wait_for(lock, Cas::kOwnerStopSlice); --rt.recovery_waiters_for_test; } if (rt.recovered && !needs_rerecovery()) @@ -1682,6 +1715,60 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( uint32_t walks_started = 0; bool vanish_brake_tripped = false; bool cancelled = false; + /// Only a walk that threw lets a stopped owner end recovery: a restart after a successful walk and the + /// structural exits keep their answers. + bool walk_failed = false; + std::exception_ptr unresolved_error; + /// After a failed walk a stopped background owner ends recovery with its verdict, an unresolved write's error first. + const auto rethrowIfBackgroundStoppedAfterFailedWalk = [&] + { + if (!walk_failed) + return; + if (std::exception_ptr stop = Cas::backgroundStopRequested()) + std::rethrow_exception(unresolved_error ? unresolved_error : stop); + }; + /// The same, then a stopped query ends recovery with `failure`, the error recovery already has. + const auto rethrowIfOwnerStoppedAfterFailedWalk = [&](const std::exception_ptr & failure) + { + rethrowIfBackgroundStoppedAfterFailedWalk(); + if (walk_failed && Cas::queryStopRequested()) + std::rethrow_exception(unresolved_error ? unresolved_error : failure); + }; + /// Whether the catalog still names the recovering life. A failed catalog read is a third answer. + struct LifeCheck + { + enum class Answer : uint8_t { Exists, Removed, Unknown }; + Answer answer; + std::exception_ptr failure; + }; + const auto checkLifeStillCataloged = [&]() -> LifeCheck + { + try + { + if (confirmRecoveredLifeOrDetach(rt, admitted_generation)) + return {LifeCheck::Answer::Exists, nullptr}; + return {LifeCheck::Answer::Removed, nullptr}; + } + catch (...) + { + return {LifeCheck::Answer::Unknown, std::current_exception()}; + } + }; + const auto throwIfTeardown = [&token] + { + if (token && token->stopping()) + throw Exception(ErrorCodes::ABORTED, "CAS ref recovery: teardown began during recovery"); + }; + /// Throws `ABORTED` on teardown. False when the mount fence is lost, this runtime is retired or superseded by a + /// self-remount, or the admitting generation has moved: retrying under a stale generation can only be refused at the install. + const auto mayRetry = [&] + { + throwIfTeardown(); + return fence_ok_fn() + && !rt.catalog_life_invalidated.load(std::memory_order_acquire) + && !rt.superseded_by_remount.load(std::memory_order_acquire) + && fence_generation_fn() == admitted_generation; + }; for (;;) { try @@ -1715,6 +1802,10 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// selected-base vanish after the next attempt takes a different path. hole_detail.reset(); + if (walk_failed) + Cas::throwIfBackgroundStopped(); + walk_failed = false; + /// The whole walk runs UNLOCKED. Nothing it touches is shared: the candidate is private /// and `rt` is read only through atomics the poll consults. Unlocking is what keeps a /// recovery's full I/O envelope from stalling every reader of this table -- and what lets @@ -1722,10 +1813,14 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( ++walks_started; lock.unlock(); std::optional walked; + bool unresolved_sent = false; try { + /// Owed so that CAS's own checks do not cut a started walk. On S3 a stopped query's walk still + /// fails at its first error answer, the `404` that ends every walk included. + const auto owed = Cas::OwnerScope::owed(); walked = runRecoveryWalkOnce( - ns, rt, admitted_generation, live, retained_attempt, hole_detail, cancelled, token); + ns, rt, admitted_generation, live, retained_attempt, hole_detail, cancelled, unresolved_sent, token); /// The admission's catalog read precedes the walk, and another server's GC may have /// erased the life and deleted its objects under it. if (walked) @@ -1733,6 +1828,9 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( } catch (...) { + walk_failed = true; + if (unresolved_sent) + unresolved_error = std::current_exception(); /// Re-acquire BEFORE letting anything propagate: the SCOPE_EXIT above mutates /// `recovery_in_progress` and notifies `recovery_cv`, and it MUST run with /// `state_mutex` held -- unwinding through it unlocked would be a data race on the @@ -1800,34 +1898,37 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// a `catch (const Exception &)` would not even see. `getCurrentExceptionCode()` normalises /// every exception (DB, Poco, std) to a code so the transient classifier can decide. const int code = getCurrentExceptionCode(); - /// Corruption of a life the catalog no longer names is the janitor's work, not damage. - if (code == ErrorCodes::CORRUPTED_DATA) + /// Corruption of a life the catalog no longer names is the janitor's work, not damage. The confirmation + /// is no retry, so a stopped query reaches it as a live one does; a query's stored cause is no corruption. + const bool confirm_corruption + = code == ErrorCodes::CORRUPTED_DATA && !Cas::isQueryStoredCause(std::current_exception()); + if (!confirm_corruption) + rethrowIfOwnerStoppedAfterFailedWalk(std::current_exception()); + else { + rethrowIfBackgroundStoppedAfterFailedWalk(); lock.unlock(); - bool confirmed = true; - try - { - confirmed = confirmRecoveredLifeOrDetach(rt, admitted_generation); - } - catch (...) // NOLINT(bugprone-empty-catch) - { - /// Without a confirmation the walk's own error is the answer. - } + const LifeCheck life = checkLifeStillCataloged(); lock.lock(); - if (!confirmed) + if (life.answer == LifeCheck::Answer::Removed) { life_removed = true; break; } + /// A stop during the confirmation must not surface as corruption. + rethrowIfOwnerStoppedAfterFailedWalk(life.failure ? life.failure : std::current_exception()); + /// Nor may a failed confirmation: it did not establish that the catalog still names the life. + if (life.answer == LifeCheck::Answer::Unknown) + std::rethrow_exception(unresolved_error ? unresolved_error : life.failure); } /// `cancelled` is latched by the poll itself: a self-remount's cancellation uses the /// retry-later class (the caller should retry, against the FRESH incarnation), so without the /// latch this loop would read it as a transient blip and re-drive the very work the remount /// just stopped. Detached teardown is independently terminal even when the in-flight /// exception happened to carry a transient transport code. - if (vanish_brake_tripped || cancelled || (token && token->stopping()) - || !isTransientRecoveryError(code)) + if (vanish_brake_tripped || cancelled || !isTransientRecoveryError(code)) throw; /// a latched terminal case, or a non-transient failure -- fail fast + throwIfTeardown(); /// A cancellation now ends the walk through the operation's liveness, which refuses /// silently -- so the exception that arrives here carries a transport code and `cancelled` @@ -1866,11 +1967,17 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// `state_mutex`) never runs unlocked -- same obligation as the walk's window above. try { - recovery_retry_sleep_fn(backoff_ms, token); + /// Only a walk that threw makes the next walk a reissue the owner may stop. + std::optional pause_owed; + if (!walk_failed) + pause_owed.emplace(Cas::OwnerScope::owed()); + pauseBeforeRecoveryRetry(backoff_ms, token); } catch (...) { lock.lock(); + if (unresolved_error) + std::rethrow_exception(unresolved_error); throw; } lock.lock(); @@ -5618,6 +5725,9 @@ NamespaceLifeId CasRefLedger::namespaceLife(const RootNamespace & ns) return rt->life; } invalidateRemovedCatalogLife(rt->life); + /// A stopped caller starts no work on a successor life. + if (recovery_error && Cas::ownerStopRequested()) + std::rethrow_exception(recovery_error); } } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h index 0a670278ffa0e..c7e17c29d09cb 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h @@ -417,10 +417,13 @@ class CasRefLedger /// leave it untouched. void setCasRetrySleepForTest(std::function sleep_fn); - /// Replaces only ref-table recovery's token-aware retry delay seam for deterministic tests. + /// Replaces the sleep of a whole recovery retry pause; the pause's stop checks still run before it. void setRefRecoveryRetrySleepForTest( std::function &)> sleep_fn); + /// Replaces the sleep of one slice of a recovery retry pause, keeping its slicing and stop checks. + void setRefRecoveryRetrySliceSleepForTest(std::function sleep_fn); + /// Test-only observability and fault-injection seams for recovery, wedges, cleanup, and publication. /// The counters expose recovery and publication progress; wedge methods create and inspect the /// unresolved-`PUT` state; cleanup methods expose sweep eligibility; publication methods expose @@ -860,10 +863,14 @@ class CasRefLedger std::function cancel_inflight_builds; std::function recovery_pre_first_request_hook_for_test; - /// Backoff sleep used by `ensureRefTableRecovered`'s transient-retry loop. Default is an - /// interruptible slice-sleep (bails early if `fence_ok_fn` drops or detached teardown starts); - /// `setCasRetrySleepForTest` overrides it (a unit test injects a clock-advancing no-op). - std::function &)> recovery_retry_sleep_fn; + /// The sleep of one slice of `pauseBeforeRecoveryRetry`. + std::function recovery_retry_slice_sleep_fn; + /// When set, `pauseBeforeRecoveryRetry` sleeps the whole pause through it, after the same checks. + std::function &)> recovery_retry_pause_sleep_for_test; + + /// The backoff of `ensureRefTableRecovered`'s retry loop, in `kOwnerStopSlice` slices. Returns early on fence + /// loss, teardown, or a stopped query outside `owed`; throws a stopped background owner's verdict. + void pauseBeforeRecoveryRetry(uint64_t total_ms, const std::optional & token); /// One queued append caller. `build_ops` is invoked at most once by the flush leader and returns the /// caller's operations rather than mutating storage directly. Completion fields are synchronized by @@ -1322,10 +1329,12 @@ class CasRefLedger /// reported through the retry-later class (the caller should retry, against the FRESH incarnation), /// so without it the transient loop reads the stop as a blip and re-drives the very work the remount /// just stopped -- while the barrier blocks waiting for that recovery to finish. + /// `unresolved_sent` is set when the walk throws because its stamp or tombstone was sent and stays + /// unresolved, so the caller can keep that exit after its owner stops. std::optional runRecoveryWalkOnce( const RootNamespace & ns, RefTableRuntime & rt, uint64_t admitted_generation, const LiveEpochPair & live, const std::optional & retained_attempt, std::optional & hole_detail, - bool & cancelled, const std::optional & token = std::nullopt); + bool & cancelled, bool & unresolved_sent, const std::optional & token = std::nullopt); /// The I/O-boundary poll of the walk: is this recovery still entitled to continue? Detached /// teardown, self-remount cancellation, and a runtime already detached by self-remount each diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.cpp index ef4288fc22c72..0ccaad782a09a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -139,7 +140,9 @@ bool failureJudgedAgainstCkpt(int error_code) bool restartsOnMovedBase(int error_code, CasOperation & op, const Layout & layout, const NamespaceLifeId & life, const Etag & token) { - return failureJudgedAgainstCkpt(error_code) && ckptTokenMoved(op, layout, life, token); + /// A query's stored cause says nothing about the chain, whatever its code. + return failureJudgedAgainstCkpt(error_code) && !isQueryStoredCause(std::current_exception()) + && ckptTokenMoved(op, layout, life, token); } RefTxnId RefTableState::chainNextId(uint64_t life_epoch) const diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.h index 1c3f496ea542a..7a774aa783664 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.h @@ -78,8 +78,9 @@ bool ckptTokenMoved(CasOperation & op, const Layout & layout, const NamespaceLif /// Whether a failure with this code is judged against `_ckpt` at all: only `CORRUPTED_DATA` is. bool failureJudgedAgainstCkpt(int error_code); -/// For a failure caught while reading a chain grounded on `_ckpt` `token`: true asks the reader to restart, -/// false to rethrow. Only `CORRUPTED_DATA` restarts, and only when `_ckpt` moved or is absent, because +/// For a failure caught while reading a chain grounded on `_ckpt` `token`, called inside its handler: true asks the +/// reader to restart, false to rethrow. Only `CORRUPTED_DATA` restarts, never a query's stored cause, and only when +/// `_ckpt` moved or is absent, because /// cleanup may then have emptied keys the reader relied on; any other code returns false without a /// request. When the `_ckpt` re-read itself throws, its store error replaces the caught exception: the /// caller fails closed as retry-later and this attempt reports no corruption verdict. diff --git a/src/Disks/tests/gtest_cas_detached_work.cpp b/src/Disks/tests/gtest_cas_detached_work.cpp index dc81efb83fbb2..cb78a0881b9d0 100644 --- a/src/Disks/tests/gtest_cas_detached_work.cpp +++ b/src/Disks/tests/gtest_cas_detached_work.cpp @@ -17,6 +17,7 @@ #include #include #include +#include using namespace DB::Cas; @@ -25,6 +26,11 @@ namespace ProfileEvents extern const Event CASDetachedWorkDrainTimeouts; } +namespace DB::ErrorCodes +{ +extern const int ABORTED; +} + namespace { @@ -1029,3 +1035,89 @@ TEST(CASDetachedWork, StopAfterRecoveryMaterializationPreventsFinalInstall) << "recovery installed a materialized result after detached stop was latched"; EXPECT_EQ(fixture.ledger.laneStateForTest(ns), RefLaneState::NeedsRecovery); } + +namespace +{ + +/// Parks the first read of the armed key, then loses its reply, so the read's reissue meets whatever +/// was latched while it was parked. +class ParkThenLoseReadBackend : public DB::Cas::tests::OrderedFaultBackend +{ +public: + void arm(String key_, std::shared_ptr parked_, std::shared_ptr release_) + { + key = std::move(key_); + parked = std::move(parked_); + release = std::move(release_); + armed.store(true); + } + + std::optional read(const String & read_key, TransportAccess & access) override + { + if (read_key == key && armed.exchange(false)) + { + parked->open(); + release->wait("release_parked_read"); + throw Poco::TimeoutException("test: the read's reply is lost"); + } + return DB::Cas::tests::OrderedFaultBackend::read(read_key, access); + } + +private: + String key; + std::shared_ptr parked; + std::shared_ptr release; + std::atomic armed{false}; +}; + +struct PublishErrorCodes +{ + std::mutex mutex; + std::vector codes; +}; + +} + +/// Teardown during a detached recovery walk ends the recovery with `ABORTED`, not with the error of the +/// request that teardown refused. +TEST(CASRefWriterRecoveryRetry, TeardownDuringWalkThrowsAborted) +{ + auto backend = std::make_shared(); + auto errors = std::make_shared(); + PoolConfig config; + config.snapshot_publish_backoff_initial_ms = 0; + config.snapshot_publish_backoff_max_ms = 0; + config.publish_error_hook_for_test = [errors] + { + std::lock_guard lock(errors->mutex); + errors->codes.push_back(DB::getCurrentExceptionCode()); + }; + auto store = openPublishingPool(backend, config); + const RootNamespace ns{"srv1/teardown_during_walk"}; + + auto first_publisher_captured = std::make_shared(); + auto release_first_publisher = std::make_shared(); + String ckpt_key; + preparePendingRecoveryPublisher( + store, backend, ns, first_publisher_captured, release_first_publisher, ckpt_key); + + auto read_parked = std::make_shared(); + auto release_read = std::make_shared(); + backend->arm(ckpt_key, read_parked, release_read); + { + std::lock_guard lock(errors->mutex); + errors->codes.clear(); + } + release_first_publisher->open(); + GateOpenedOnExit read_released{*release_read}; + read_parked->wait("read_parked"); + + auto drain = std::async(std::launch::async, [&store] { return store->stopAndDrainDetachedWork(/*deadline_ms=*/5000); }); + awaitStopLatched(store); + release_read->open(); + EXPECT_TRUE(drain.get()); + store->waitForSnapshotPublishSettleForTest(ns); + + std::lock_guard lock(errors->mutex); + EXPECT_EQ(errors->codes, std::vector{DB::ErrorCodes::ABORTED}); +} diff --git a/src/Disks/tests/gtest_cas_recovery_streaming.cpp b/src/Disks/tests/gtest_cas_recovery_streaming.cpp index 5b087b7385328..96b6f76584e1c 100644 --- a/src/Disks/tests/gtest_cas_recovery_streaming.cpp +++ b/src/Disks/tests/gtest_cas_recovery_streaming.cpp @@ -6,6 +6,8 @@ #include #include #include "cas_test_helpers.h" +#include "cas_killable_query.h" +#include #include #include @@ -18,6 +20,7 @@ namespace DB::ErrorCodes { +extern const int ABORTED; extern const int CORRUPTED_DATA; extern const int S3_ERROR; } @@ -399,6 +402,106 @@ TEST(CASRecoveryStreaming, CorruptObjectFailsFast) EXPECT_EQ(backend->refs_list_count.load(), 0) << "durable corruption must not trigger recovery LIST"; } +/// A removal under a background owner, parked behind another caller's recovery, leaves at its owner's stop while that +/// recovery is still running; a killed query parked beside it keeps waiting and then reads the recovered table. +TEST(CASRecoveryStreaming, AStoppedBackgroundOwnerLeavesTheWaitForAnotherRecovery) +{ + auto backend = std::make_shared(); + seedPoolMetaForRestart(*backend); + const Layout layout("p"); + const RootNamespace ns{"00/aa@cas@"}; + publishCommittedTransition(*backend, layout, ns, "x", std::nullopt, mref(1)); + + auto store = openPoolForTest(backend); + backend->refs_prefix = layout.namespaceStreamPrefix(fixture::fixtureLife(ns)); + std::promise entered_promise; + std::atomic get_entered{false}; + std::promise release_promise; + std::shared_future release_future = release_promise.get_future().share(); + backend->target_log_key = layout.refLogKey(fixture::fixtureLife(ns), RefTxnId{1, 1}); + backend->on_first_target_get = [&] + { + if (!get_entered.exchange(true)) + entered_promise.set_value(); + release_future.wait(); + }; + backend->armed = true; + + std::exception_ptr recovering_error; + std::thread recovering([&] + { + try + { + store->listRefs(ns); + } + catch (...) + { + recovering_error = std::current_exception(); + } + }); + entered_promise.get_future().wait(); + + std::atomic stop{false}; + std::atomic removal_code{-1}; + std::thread removal([&] + { + const auto owner = OwnerScope::background([&] + { + if (stop.load()) + throw DB::Exception(DB::ErrorCodes::ABORTED, "server shutdown"); + }); + try + { + (void)store->dropNamespace(ns); + removal_code = 0; + } + catch (const DB::Exception & e) + { + removal_code = e.code(); + } + }); + const bool removal_parked = pollUntil([&] { return store->refRecoveryWaitersForTest(ns) >= 1; }); + + std::atomic query_done{false}; + std::atomic query_code{-1}; + std::thread query_reader([&] + { + onKillableQueryThread([&](CasKillableQuery & query) + { + query.kill(); + try + { + store->listRefs(ns); + query_code = 0; + } + catch (const DB::Exception & e) + { + query_code = e.code(); + } + }); + query_done = true; + }); + const bool query_parked = pollUntil([&] { return store->refRecoveryWaitersForTest(ns) >= 2; }); + + stop = true; + const bool removal_left = pollUntil([&] { return removal_code.load() != -1; }); + const bool query_still_waiting = !query_done.load(); + + release_promise.set_value(); + recovering.join(); + removal.join(); + query_reader.join(); + + ASSERT_TRUE(removal_parked) << "the removal never reached the wait"; + ASSERT_TRUE(query_parked) << "the killed query never reached the wait"; + EXPECT_TRUE(removal_left) << "the stopped removal waited for the other recovery"; + EXPECT_EQ(removal_code.load(), DB::ErrorCodes::ABORTED); + EXPECT_TRUE(query_still_waiting) << "a killed query is not a stop for this wait"; + EXPECT_EQ(query_code.load(), 0); + EXPECT_FALSE(recovering_error); + EXPECT_TRUE(store->resolveRef(ns, "x").has_value()); +} + /// Test 14 (concurrent-waiter leg): while one caller is blocked in recovery's unlocked exact-log GET, /// a second caller for the same table parks on `recovery_cv` and is woken exactly once when recovery /// completes. Neither caller may race an independent stream LIST. diff --git a/src/Disks/tests/gtest_cas_ref_recovery_cas_walk.cpp b/src/Disks/tests/gtest_cas_ref_recovery_cas_walk.cpp index 44e3ac2222979..662d399932e88 100644 --- a/src/Disks/tests/gtest_cas_ref_recovery_cas_walk.cpp +++ b/src/Disks/tests/gtest_cas_ref_recovery_cas_walk.cpp @@ -5,6 +5,7 @@ #include "config.h" #include +#include #include #include #include @@ -14,8 +15,11 @@ #include #include #include +#include #include #include +#include +#include #include #include @@ -57,9 +61,12 @@ namespace DB::ErrorCodes { +extern const int ABORTED; extern const int CORRUPTED_DATA; extern const int INVALID_STATE; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; +extern const int READONLY; } namespace ProfileEvents @@ -72,10 +79,12 @@ extern const Event CASRefRecoveryCancelled; extern const Event CASRefCheckpointPublished; extern const Event CASRefCheckpointStamped; extern const Event CASRefAppendTombstoneWritten; +extern const Event CASRefRecoveryRetries; } using namespace DB::Cas; using DB::Cas::tests::VirtualRetryClock; +using DB::Cas::tests::onKillableQueryThread; using DB::Cas::tests::committedRow; using DB::Cas::tests::CountingBackend; using DB::Cas::tests::expectThrowsCode; @@ -1138,7 +1147,6 @@ TEST(CASRefRecoveryCasWalk, UnresolvedRecoveryStampWritesNoTombstoneAndInstallsN auto fake_now = std::make_shared>(1'000'000); PoolConfig config = walkTestConfig(); config.boot_ms_fn = [fake_now] { return fake_now->load(); }; - config.cas_request_budget.recovery_retry_budget_ms = 1; config.cas_request_budget.recovery_retry_initial_backoff_ms = 1; config.cas_request_budget.recovery_retry_max_backoff_ms = 1; auto store = openWalkPool(backend, config); @@ -1162,6 +1170,119 @@ TEST(CASRefRecoveryCasWalk, UnresolvedRecoveryStampWritesNoTombstoneAndInstallsN EXPECT_FALSE(store->refTableRecoveredForTest(ns)) << "nothing is installed"; } +namespace +{ + +/// Runs `on_settle` once, in the first read of `watched_key` after a write of it was refused. +class SettleHookBackend : public HidingListBackend +{ +public: + String watched_key; + uint64_t writes_at_arm = 0; + std::function on_settle; + + std::optional read(const String & key, DB::Cas::TransportAccess & access) override + { + if (key == watched_key && on_settle && writeCount(key) > writes_at_arm) + std::exchange(on_settle, nullptr)(); + return HidingListBackend::read(key, access); + } +}; + +struct StoppedConflictRun +{ + int code = 0; + String message; + uint64_t stamp_writes = 0; + uint64_t tombstone_writes = 0; +}; + +/// A recovery that seals dead epoch 1, run by a query; the write of `refused` (the stamp or the tombstone) is refused +/// with 412, and with `kill` the query is killed in the read that settles that refusal, which then fails. +StoppedConflictRun runRecoveryWithARefusedWrite(bool refuse_stamp, bool kill) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + const RootNamespace ns{refuse_stamp ? "srv1/stamp_conflict" : "srv1/tombstone_conflict"}; + burnEpochsUpTo(backend, layout, 2); + seedTxn(*backend, layout, ns, RefTxnId{1, 1}, "a", /*birth=*/true); + seedCkpt(*backend, layout, ns, lifeEpochCkpt(1, RefTxnId{1, 1})); + const NamespaceLifeId life = catalogLife(backend, layout, ns); + const String ckpt_key = layout.refCkptKey(life); + const String tombstone_key = layout.refLogKey(life, RefTxnId{1, 2}); + auto store = openWalkPool(backend); + store->setCasRetrySleepForTest([](uint64_t) {}); + + backend->watched_key = refuse_stamp ? ckpt_key : tombstone_key; + backend->writes_at_arm = backend->writeCount(backend->watched_key); + backend->refuseNextWrite(backend->watched_key); + const uint64_t stamp_writes_before = backend->writeCount(ckpt_key); + const uint64_t tombstone_writes_before = backend->writeCount(tombstone_key); + + StoppedConflictRun run; + std::thread caller([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + if (kill) + backend->on_settle = [&query] + { + query.kill(); + throw Poco::TimeoutException("SettleHookBackend: the settling read timed out"); + }; + try + { + (void)store->listRefs(ns); + } + catch (const DB::Exception & e) + { + run.code = e.code(); + run.message = e.message(); + } + backend->on_settle = nullptr; + }); + caller.join(); + run.stamp_writes = backend->writeCount(ckpt_key) - stamp_writes_before; + run.tombstone_writes = backend->writeCount(tombstone_key) - tombstone_writes_before; + return run; +} + +} + +/// A refused stamp whose settling read the query's stop cut short ends that walk: the 412 proves the stamp did not +/// land, so the error is a retry-later naming the stop, and no second walk sends a second stamp. A clean refusal +/// restarts the walk, whose second stamp lands. +TEST(CASRefRecoveryCasWalk, RefusedStampSettledUnderAStoppedQueryEndsTheWalk) +{ + { + SCOPED_TRACE("killed in the settling read"); + const auto run = runRecoveryWithARefusedWrite(/*refuse_stamp=*/true, /*kill=*/true); + EXPECT_EQ(run.code, DB::ErrorCodes::NETWORK_ERROR) << run.message; + EXPECT_NE(run.message.find("stopped after its refused generation 3 stamp"), String::npos) << run.message; + EXPECT_EQ(run.stamp_writes, 1u) << "one walk, one stamp"; + EXPECT_EQ(run.tombstone_writes, 0u); + } + { + SCOPED_TRACE("live"); + const auto run = runRecoveryWithARefusedWrite(/*refuse_stamp=*/true, /*kill=*/false); + EXPECT_EQ(run.code, 0) << run.message; + EXPECT_EQ(run.stamp_writes, 2u) << "the refused stamp, then the restarted walk's stamp"; + EXPECT_EQ(run.tombstone_writes, 1u); + } +} + +/// The same for the tombstone: its settling read observed nothing, so the walk ends with a retry-later and chases no +/// successor. +TEST(CASRefRecoveryCasWalk, RefusedTombstoneSettledUnderAStoppedQueryEndsTheWalk) +{ + const auto run = runRecoveryWithARefusedWrite(/*refuse_stamp=*/false, /*kill=*/true); + EXPECT_EQ(run.code, DB::ErrorCodes::NETWORK_ERROR) << run.message; + EXPECT_NE(run.message.find("could not observe"), String::npos) << run.message; + EXPECT_EQ(run.stamp_writes, 1u); + EXPECT_EQ(run.tombstone_writes, 1u) << "one walk, one tombstone"; +} + /// GENESIS. A namespace born at epoch 5 has no epochs 1-4 of its own: they are not "empty epochs it /// failed to close", they are epochs before it existed. The walk starts at the namespace's `life_epoch` /// and writes no phantom seals below it, and with no transition ever having happened it installs NO @@ -1992,6 +2113,43 @@ TEST(CASRefRecoveryCasWalk, RecoveryRequestSequenceStampsThenWritesOneTombstone) EXPECT_EQ(store->refRecoveryRestartsForTest(ns), 0u); } +/// A cold read by a stopped query still recovers the table: the one recovery walk, its stamp and its +/// tombstone included, is owed, so a healthy store answers with every committed ref. +TEST(CASRefRecoveryCasWalk, KilledColdReaderStillRecoversWithStampOrTombstone) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + const RootNamespace ns{"srv1/killed_cold_reader"}; + + burnEpochsUpTo(backend, layout, /*target_live_epoch=*/4); + seedCkpt(*backend, layout, ns, lifeEpochCkpt(1, RefTxnId{1, 2})); + seedTxn(*backend, layout, ns, RefTxnId{1, 1}, "a", /*birth=*/true); + seedTxn(*backend, layout, ns, RefTxnId{1, 2}, "b", /*birth=*/false); + seedTxn(*backend, layout, ns, RefTxnId{1, 3}, "c", /*birth=*/false); + + auto store = openWalkPool(backend); + ASSERT_TRUE(store); + const uint64_t stamped_before = ProfileEvents::global_counters[ProfileEvents::CASRefCheckpointStamped]; + const uint64_t sealed_before = ProfileEvents::global_counters[ProfileEvents::CASRefRecoveryEpochSealed]; + + size_t refs = 0; + std::thread reader([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + EXPECT_NO_THROW(refs = store->listRefs(ns).size()); + }); + reader.join(); + + EXPECT_EQ(refs, 3u) << "every committed ref stays visible"; + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRefCheckpointStamped] - stamped_before, 1u) + << "the walk stamped the checkpoint"; + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRefRecoveryEpochSealed] - sealed_before, 1u) + << "the walk sealed the dead epoch with a tombstone"; +} + /// --------------------------------------------------------------------------------------------- /// Generation 3: one-request append, forward-linked tombstones, uniform genesis /// --------------------------------------------------------------------------------------------- @@ -3408,3 +3566,259 @@ TEST(CASRefWriterTombstone, TombstoneInstallRefusedAfterItsCreateNeedsRecoveryAn << "no second tombstone"; EXPECT_TRUE(store->listRefs(ns).contains("c")); } + +/// --------------------------------------------------------------------------------------------- +/// A stopped owner and the stamp and tombstone writes of recovery +/// --------------------------------------------------------------------------------------------- + +namespace +{ + +/// Loses the reply of the next `lost_replies` writes of `watched_key` before they apply, after `on_lost` +/// runs, so the settling read finds the old state, which proves neither way. `refused_writes` refuses +/// the next writes of the key instead. Counts every write of the key. +class LostWriteReplyBackend : public JournalingBackend +{ +public: + String watched_key; + std::atomic lost_replies{0}; + std::atomic refused_writes{0}; + std::atomic writes_of_watched_key{0}; + std::function on_lost; + + std::expected write( + const String & key, const String & bytes, const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (key == watched_key) + { + ++writes_of_watched_key; + if (refused_writes.fetch_sub(1) > 0) + throw DB::Exception(DB::ErrorCodes::READONLY, "test: the store refuses the write"); + if (lost_replies.fetch_sub(1) > 0) + { + if (on_lost) + on_lost(); + throw Poco::TimeoutException("test: the write's reply is lost"); + } + } + return JournalingBackend::write(key, bytes, expected_value, access); + } +}; + +struct ResidentStampRecovery +{ + std::shared_ptr backend; + PoolPtr store; + RootNamespace ns; + NamespaceLifeId life; + String ckpt_key; + String tombstone_key; +}; + +/// A namespace whose recovery stamps its generation 1 `_ckpt`, then closes the dead epoch 1 with a +/// tombstone at {1,4}. Its runtime is resident and unrecovered: a first recovery failed before its first +/// request, so the next `namespaceLife` recovers it in place. +ResidentStampRecovery openResidentStampRecovery(const String & name, uint64_t backoff_ms = 1) +{ + auto backend = std::make_shared(); + const RootNamespace ns{"srv1/" + name}; + const Layout layout("p"); + burnEpochsUpTo(backend, layout, /*target_live_epoch=*/4); + seedCkpt(*backend, layout, ns, lifeEpochCkpt(1, RefTxnId{1, 2})); + seedTxn(*backend, layout, ns, RefTxnId{1, 1}, "a", /*birth=*/true); + seedTxn(*backend, layout, ns, RefTxnId{1, 2}, "b", /*birth=*/false); + seedTxn(*backend, layout, ns, RefTxnId{1, 3}, "c", /*birth=*/false); + + auto fail_first = std::make_shared>(true); + PoolConfig config = walkTestConfig(); + config.cas_request_budget.recovery_retry_initial_backoff_ms = backoff_ms; + config.cas_request_budget.recovery_retry_max_backoff_ms = backoff_ms; + config.recovery_pre_first_request_hook_for_test = [fail_first] + { + if (fail_first->exchange(false)) + throw DB::Exception(DB::ErrorCodes::ABORTED, "test: the first recovery fails before its first request"); + }; + PoolPtr store = openWalkPool(backend, config); + const NamespaceLifeId life = catalogLife(backend, layout, ns); + expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { (void)store->namespaceLife(ns); }); + EXPECT_NE(store->refTableRuntimeIdentityForTest(ns), 0u) << "the runtime stays resident"; + EXPECT_FALSE(store->refTableRecoveredForTest(ns)); + return ResidentStampRecovery{ + .backend = backend, + .store = store, + .ns = ns, + .life = life, + .ckpt_key = layout.refCkptKey(life), + .tombstone_key = layout.refLogKey(life, RefTxnId{1, 4})}; +} + +/// The owner stops while the reply of the recovery's write at `key` is lost: the caller of `namespaceLife` +/// sees the unresolved 210 after one send, nothing is installed and the catalog row is unchanged. Control: +/// a live owner retries and recovers. +void expectStoppedOwnerKeepsUnresolvedRecoveryWrite(bool tombstone) +{ + const String unresolved_message = tombstone + ? "the tombstone at 1-4 is UNRESOLVED" + : "the generation 3 stamp of its `_ckpt` is unresolved"; + for (const bool stop : {true, false}) + { + SCOPED_TRACE(stop ? "stopped owner" : "control: live owner"); + auto fx = openResidentStampRecovery(fmt::format("unresolved_{}_{}", tombstone ? "tombstone" : "stamp", stop ? "stopped" : "live")); + const uint64_t installs_before = fx.store->recoveryInstallCountForTest(); + fx.backend->watched_key = tombstone ? fx.tombstone_key : fx.ckpt_key; + fx.backend->lost_replies = 1; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + if (stop) + { + fx.backend->on_lost = [&query] { query.kill(); }; + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, unresolved_message, + [&] { (void)fx.store->namespaceLife(fx.ns); }); + } + else + { + EXPECT_NO_THROW((void)fx.store->namespaceLife(fx.ns)); + } + fx.backend->on_lost = {}; + }); + if (stop) + { + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 1) << "the lost write is not sent again"; + EXPECT_EQ(fx.store->recoveryInstallCountForTest(), installs_before); + EXPECT_FALSE(fx.store->refTableRecoveredForTest(fx.ns)); + EXPECT_EQ(catalogLife(fx.backend, Layout("p"), fx.ns), fx.life) << "the catalog row is unchanged"; + } + else + { + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 2); + EXPECT_EQ(fx.store->recoveryInstallCountForTest(), installs_before + 1); + } + } +} + +} + +TEST(CASRefWriterRecoveryRetry, UnresolvedStampThenStopKeepsUnresolvedExitThroughNamespaceLife) +{ + expectStoppedOwnerKeepsUnresolvedRecoveryWrite(/*tombstone=*/false); +} + +TEST(CASRefWriterRecoveryRetry, UnresolvedTombstoneThenStopKeepsUnresolvedExitThroughNamespaceLife) +{ + expectStoppedOwnerKeepsUnresolvedRecoveryWrite(/*tombstone=*/true); +} + +/// The catalog row is removed and replaced while the stamp's reply is lost: the stopped caller sees the +/// unresolved 210 and starts no work on the successor life. +TEST(CASRefWriterRecoveryRetry, UnresolvedStampThenStopThroughNamespaceLifeWithRowGone) +{ + auto fx = openResidentStampRecovery("unresolved_stamp_row_gone"); + const Layout layout("p"); + const CatalogEntry predecessor{.ns = fx.life.ns, .state = NsState::Live, .incarnation = fx.life.incarnation, .creator = std::nullopt}; + std::optional successor; + size_t journal_at_loss = 0; + fx.backend->watched_key = fx.ckpt_key; + fx.backend->lost_replies = 1; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + fx.backend->on_lost = [&] + { + successor = replaceCatalogLifeForTest(fx.backend, layout, predecessor, DB::UInt128(0x5eed)); + query.kill(); + journal_at_loss = fx.backend->journal().size(); + }; + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + "the generation 3 stamp of its `_ckpt` is unresolved", [&] { (void)fx.store->namespaceLife(fx.ns); }); + fx.backend->on_lost = {}; + }); + ASSERT_TRUE(successor); + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 1); + const NamespaceLifeId successor_life = NamespaceLifeId::fromCatalogEntry(successor->ns, successor->incarnation); + const auto journal = fx.backend->journal(); + for (size_t i = journal_at_loss; i < journal.size(); ++i) + { + const auto & [method, key] = journal[i]; + EXPECT_TRUE(method == "GET" || method == "HEAD") << method << " " << key << ": no write after the stop"; + EXPECT_FALSE(key.starts_with(layout.namespaceStreamPrefix(successor_life)) + || key.starts_with(layout.namespaceStatePrefix(successor_life))) + << method << " " << key << ": no request for the successor life"; + } + EXPECT_EQ(fx.store->refTableLifeForTest(fx.ns), std::nullopt) << "the removed life is detached"; +} + +/// The owner stops during the pool's own backoff after a walk whose stamp stayed unresolved: the +/// unresolved 210, not the owner's verdict. +TEST(CASRefWriterRecoveryRetry, StopInBackoffAfterUnresolvedStampKeeps210) +{ + auto fx = openResidentStampRecovery("unresolved_stamp_stop_in_backoff", /*backoff_ms=*/10'000); + fx.backend->watched_key = fx.ckpt_key; + fx.backend->lost_replies = 1; + const uint64_t retries_before = counterOf(ProfileEvents::CASRefRecoveryRetries); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + /// The counter moves right before the backoff starts. + std::thread killer([&] + { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (counterOf(ProfileEvents::CASRefRecoveryRetries) == retries_before && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + query.kill(); + }); + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + "the generation 3 stamp of its `_ckpt` is unresolved", [&] { (void)fx.store->namespaceLife(fx.ns); }); + killer.join(); + }); + EXPECT_GT(counterOf(ProfileEvents::CASRefRecoveryRetries), retries_before) << "the backoff started"; + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 1); + EXPECT_FALSE(fx.store->refTableRecoveredForTest(fx.ns)); +} + +namespace +{ + +/// Runs `namespaceLife` under a background owner that the recovery's backoff stops, so the gate before the next walk +/// is the first check to observe the stop, and expects `code` with `message` after one write of the watched key. +void expectBackgroundStopInBackoff(ResidentStampRecovery & fx, int code, const String & message) +{ + std::atomic stopped{false}; + fx.store->setRefRecoveryRetrySleepForTest([&stopped](uint64_t, const auto &) { stopped = true; }); + { + const auto owner = DB::Cas::OwnerScope::background([&stopped] + { + if (stopped.load()) + throw DB::Exception(DB::ErrorCodes::ABORTED, "test: the background owner stopped"); + }); + DB::Cas::tests::expectThrowsCodeWithMessage(code, message, [&] { (void)fx.store->namespaceLife(fx.ns); }); + } + fx.store->setRefRecoveryRetrySleepForTest([](uint64_t, const auto &) {}); + EXPECT_TRUE(stopped.load()) << "the recovery paused after its failed walk"; + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 1) << "no walk after the stop"; + EXPECT_FALSE(fx.store->refTableRecoveredForTest(fx.ns)); +} + +} + +/// A background owner stopped after a walk whose stamp or tombstone stayed unresolved gets the unresolved 210, +/// not its own verdict: the write may still land. +TEST(CASRefWriterRecoveryRetry, BackgroundStopAfterUnresolvedWriteKeeps210) +{ + for (const bool tombstone : {false, true}) + { + SCOPED_TRACE(tombstone ? "tombstone" : "stamp"); + auto fx = openResidentStampRecovery(tombstone ? "background_unresolved_tombstone" : "background_unresolved_stamp"); + fx.backend->watched_key = tombstone ? fx.tombstone_key : fx.ckpt_key; + fx.backend->lost_replies = 1; + expectBackgroundStopInBackoff(fx, DB::ErrorCodes::NETWORK_ERROR, + tombstone ? "the tombstone at 1-4 is UNRESOLVED" : "the generation 3 stamp of its `_ckpt` is unresolved"); + } +} + +/// A refused stamp sent nothing that may land, so a background owner stopped after it gets its own verdict. +TEST(CASRefWriterRecoveryRetry, StampRefusalIsNotUnresolved) +{ + auto fx = openResidentStampRecovery("stamp_refusal"); + fx.backend->watched_key = fx.ckpt_key; + fx.backend->refused_writes = 1; + expectBackgroundStopInBackoff(fx, DB::ErrorCodes::ABORTED, "the background owner stopped"); +} diff --git a/src/Disks/tests/gtest_cas_ref_writer.cpp b/src/Disks/tests/gtest_cas_ref_writer.cpp index ce4df2b2bc342..71ccc60d8e246 100644 --- a/src/Disks/tests/gtest_cas_ref_writer.cpp +++ b/src/Disks/tests/gtest_cas_ref_writer.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -13,9 +14,13 @@ #include #include #include +#include +#include #include #include #include +#include +#include #include #include @@ -47,7 +52,10 @@ extern const int CORRUPTED_DATA; extern const int INVALID_STATE; extern const int LOGICAL_ERROR; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; +extern const int READONLY; extern const int S3_ERROR; +extern const int TIMEOUT_EXCEEDED; } namespace ProfileEvents @@ -68,6 +76,9 @@ extern const Event CASGCStuckRemovals; using namespace DB::Cas; using DB::Cas::tests::CountingBackend; +using DB::Cas::tests::exceptionCodeOf; +using DB::Cas::tests::onKillableQueryThread; +using DB::Cas::tests::StoppedBy; using DB::Cas::tests::committedRow; using DB::Cas::tests::expectThrowsCode; using DB::Cas::tests::expectThrowsCodeWithMessage; @@ -5348,6 +5359,159 @@ TEST(CASRefWriterNamespaceRemoval, ThrowDuringRemovalSetupCannotStrandLiveLane) EXPECT_NO_THROW(store->dropNamespace(ns)); } +namespace +{ + +struct StoppedRemovalRun +{ + int failed_catalog_reads = 0; + int catalog_reads_after_failure = 0; +}; + +/// A removal that fails before it sends anything, whose reopen proof's first catalog read fails. The owner +/// stops in the backoff after that failure, where `in_backoff` runs as well. +StoppedRemovalRun runStoppedRemovalBeforeSend(const std::shared_ptr & backend, const PoolPtr & store, + const RootNamespace & ns, const std::function & in_backoff = {}) +{ + const String catalog_key = store->layout().refCatalogKey(); + std::atomic fail_next_catalog_read{false}; + std::atomic failed_catalog_reads{0}; + std::atomic catalog_reads_after_failure{0}; + backend->read_observer = [&](const String & key) + { + if (key != catalog_key) + return; + if (fail_next_catalog_read.exchange(false)) + { + ++failed_catalog_reads; + throw Poco::TimeoutException("the reopen proof's first catalog read is lost"); + } + if (failed_catalog_reads.load() > 0) + ++catalog_reads_after_failure; + }; + SCOPE_EXIT({ backend->read_observer = {}; }); + + std::thread owner_thread([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + store->setCasRetrySleepForTest([&](uint64_t) + { + if (failed_catalog_reads.load() > 0 && !query.status->isKilled()) + { + query.kill(); + if (in_backoff) + in_backoff(); + } + }); + store->setRemovalAttemptHookForTest([&] + { + fail_next_catalog_read = true; + throw std::runtime_error("removal setup failed before any send"); + }); + EXPECT_THROW(store->dropNamespace(ns), std::runtime_error); + EXPECT_TRUE(query.status->isKilled()) << "the owner stopped during the reopen proof"; + store->setRemovalAttemptHookForTest({}); + store->setCasRetrySleepForTest({}); + }); + owner_thread.join(); + return {failed_catalog_reads.load(), catalog_reads_after_failure.load()}; +} + +} + +/// The guard's reopen proof is owed to the closed lane: a removal that fails before it sends anything +/// reopens a proven `Live` lane even when its owner stops during the backoff after a failed first read. +/// Owed work does not widen the reopen: a possible late write or a lost lease still keeps the lane closed. +TEST(CASRefWriterNamespaceRemoval, StoppedRemovalBeforeSendReopensProvenLiveLane) +{ + { + SCOPED_TRACE("exact Live"); + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + const RootNamespace ns{"srv1/stopped_removal_before_send"}; + publishEmptyPart(store, ns, "owned"); + + const StoppedRemovalRun run = runStoppedRemovalBeforeSend(backend, store, ns); + + EXPECT_EQ(run.failed_catalog_reads, 1); + EXPECT_EQ(run.catalog_reads_after_failure, 1) << "the failed proof read was reissued once"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + EXPECT_NO_THROW(updatePublishedAt(store, ns)) << "the proven Live lane must be open again"; + } + { + SCOPED_TRACE("possible late write"); + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/stopped_removal_after_ambiguous_write"}; + publishEmptyPart(store, ns, "owned"); + dropWithAmbiguousCatalogWrite(backend, store, ns); + + const StoppedRemovalRun run = runStoppedRemovalBeforeSend(backend, store, ns); + + EXPECT_EQ(run.failed_catalog_reads, 1); + EXPECT_EQ(run.catalog_reads_after_failure, 1) << "the owed proof read was reissued"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + expectPositiveLaneClosed(store, ns); + } + { + SCOPED_TRACE("lease loss"); + auto backend = std::make_shared(); + /// Moves the mount's clock past its lease deadline and back, so the lane stays observable afterwards. + auto lease_clock_offset = std::make_shared>(0); + PoolConfig config; + config.cas_request_budget = wedgeTestBudget(); + config.boot_ms_fn = [lease_clock_offset] { return Pool::bootMs() + lease_clock_offset->load(); }; + auto store = openPoolWithConfig(backend, config); + const RootNamespace ns{"srv1/stopped_removal_lease_loss"}; + publishEmptyPart(store, ns, "owned"); + const uint64_t past_the_lease = 10 * static_cast(store->poolConfig().mount_lease_ttl_ms.count()); + + const StoppedRemovalRun run = runStoppedRemovalBeforeSend(backend, store, ns, [&] + { + lease_clock_offset->store(past_the_lease); + }); + lease_clock_offset->store(0); + + EXPECT_EQ(run.failed_catalog_reads, 1); + EXPECT_EQ(run.catalog_reads_after_failure, 0) << "the expired lease refused the reissue"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + /// The refusal of a closed lane with no possible late write and no observed `Removing` row. + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "is Removing: creation waits", + [&] { updatePublishedAt(store, ns); }); + } +} + +/// Warm `namespaceLife` checks admission first: with an expired generation it reports the fence verdict +/// and leaves the lane unchanged, also when its owner stopped. +TEST(CASRefWriter, WarmNamespaceLifeExpiredGenerationReturnsFenceVerdict) +{ + auto backend = std::make_shared(); + auto store = openPool(backend); + const RootNamespace ns{"srv1/warm_life_expired_generation"}; + publishEmptyPart(store, ns, "owned"); + const uint64_t runtime = store->refTableRuntimeIdentityForTest(ns); + const RefLaneState lane = store->laneStateForTest(ns); + DB::Cas::tests::rearmMountFenceAfterAnomalyForTest(store); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "no longer admitted", [&] { (void)store->namespaceLife(ns); }); + + std::thread stopped_owner([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "no longer admitted", [&] { (void)store->namespaceLife(ns); }); + }); + stopped_owner.join(); + + EXPECT_EQ(store->refTableRuntimeIdentityForTest(ns), runtime); + EXPECT_EQ(store->laneStateForTest(ns), lane); +} + /// The guard must not reopen after an earlier ambiguous `Live -> Removing` send: that write may still land. TEST(CASRefWriterNamespaceRemoval, ThrowDuringRemovalSetupAfterAmbiguousWriteKeepsTheLaneClosed) { @@ -5468,8 +5632,9 @@ TEST(CASRefWriterNamespaceRemoval, ResolveReadProvingRemovingLeavesNoUnresolvedW ASSERT_TRUE(applied_by_resolve_read) << "the kept write was never applied before the resolve read"; ASSERT_TRUE(released_at_ms.has_value()); - /// The loop gives up once the next pause plus the room `CasOperation::pauseBeforeRedecide` reserves for the - /// next decision's read and write no longer fits in the window. An earlier release came from a read inside the loop. + /// The loop keeps deciding until its window is nearly spent: the last decision's read and write each need an + /// envelope, so the release lands no earlier than that much before the window's end. An earlier release came + /// from a read inside the loop. const uint64_t next_decision_reservation_ms = 2 * store->mountRequests().attemptReservationMs(); EXPECT_GE(*released_at_ms - drop_started_ms, kDefaultRequestWindowMs - kMaxBackoffDrawMs - next_decision_reservation_ms) @@ -5600,6 +5765,316 @@ TEST(CASRefWriterNamespaceRemoval, ConcurrentRemovalAttemptsDoNotOverlapAndKeepT EXPECT_NO_THROW(store->dropNamespace(ns)); } +namespace +{ + +constexpr auto STOP_WATCHDOG = std::chrono::seconds(30); + +/// Keeps a blocker parked until the stopped caller has returned, or until the watchdog fires. +struct StoppedCallerSync +{ + void parkBlocker() + { + std::unique_lock lock(mutex); + blocker_parked = true; + cv.notify_all(); + cv.wait_for(lock, STOP_WATCHDOG, [&] { return stopped_returned; }); + blocker_left = true; + } + + bool waitBlockerParked() + { + std::unique_lock lock(mutex); + return cv.wait_for(lock, STOP_WATCHDOG, [&] { return blocker_parked; }); + } + + /// True when the blocker was still parked. + bool stoppedCallerReturned() + { + std::lock_guard lock(mutex); + stopped_returned = true; + cv.notify_all(); + return !blocker_left; + } + + std::mutex mutex; + std::condition_variable cv; + bool blocker_parked = false; + bool stopped_returned = false; + bool blocker_left = false; +}; + +template +bool spinUntil(Ready ready) +{ + const auto deadline = std::chrono::steady_clock::now() + STOP_WATCHDOG; + while (!ready() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + return ready(); +} + +} + +namespace +{ + +/// A removal's owner stops while it waits for another removal's attempt. +void runRemovalFollowerStoppedWhileWaiting(StoppedBy owner) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/stopped_removal_follower"}; + publishEmptyPart(store, ns, "owned"); + + StoppedCallerSync sync; + std::atomic holder_entered{false}; + store->setRemovalAttemptHookForTest([&] + { + if (!holder_entered.exchange(true)) + sync.parkBlocker(); + }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + + std::future holder = std::async(std::launch::async, [&] { return exceptionCodeOf([&] { store->dropNamespace(ns); }); }); + ASSERT_TRUE(sync.waitBlockerParked()); + + int follower_code = 0; + bool returned_while_holder_parked = false; + CasRefLedger::RemovalFlagsForTest flags_on_return; + std::thread follower([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + auto background_stopped = std::make_shared>(false); + const auto background = DB::Cas::tests::backgroundOwnerStoppedBy(background_stopped); + const auto stop = DB::Cas::tests::stopperOf(owner, query, background_stopped); + /// The holder passed this hook before it parked, so only the follower stops here. A killed query + /// keeps waiting, so the holder is released from here; the follower has not claimed the attempt yet. + store->setRemovalRuntimeAcquiredHookForTest([&] + { + stop(); + if (owner == StoppedBy::Query) + sync.stoppedCallerReturned(); + }); + follower_code = exceptionCodeOf([&] { store->dropNamespace(ns); }); + store->setRemovalRuntimeAcquiredHookForTest(nullptr); + flags_on_return = store->removalFlagsForTest(ns); + returned_while_holder_parked = sync.stoppedCallerReturned(); + }); + follower.join(); + ASSERT_EQ(holder.wait_for(STOP_WATCHDOG), std::future_status::ready); + + if (owner == StoppedBy::Background) + { + EXPECT_EQ(follower_code, DB::ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_holder_parked) << "the stopped follower waited for the holder's attempt"; + EXPECT_TRUE(flags_on_return.attempt_active) << "the holder's attempt must stay claimed"; + EXPECT_TRUE(flags_on_return.admission_closed) << "the holder's closed lane must stay closed"; + } + else + { + EXPECT_EQ(follower_code, 0) << "a killed query's removal completes after the holder's"; + EXPECT_FALSE(returned_while_holder_parked); + EXPECT_FALSE(flags_on_return.attempt_active); + } + EXPECT_EQ(holder.get(), 0); + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} + +} + +/// A removal whose background owner stops leaves; the attempt stays claimed by the removal that holds it, which then +/// completes. +TEST(CASRefWriterNamespaceRemoval, BackgroundStoppedRemovalFollowerLeavesOwnerClaimed) +{ + runRemovalFollowerStoppedWhileWaiting(StoppedBy::Background); +} + +/// A removal whose query is killed keeps waiting and completes after the holder. +TEST(CASRefWriterNamespaceRemoval, KilledRemovalFollowerCompletesAfterTheHolder) +{ + runRemovalFollowerStoppedWhileWaiting(StoppedBy::Query); +} + +/// A namespace removal run by a killed query on a healthy store completes: every request it needs is sent. +TEST(CASRefWriterNamespaceRemoval, KilledQuerysRemovalCompletesOnAHealthyStore) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + const RootNamespace ns{"srv1/killed_removal"}; + publishEmptyPart(store, ns, "owned"); + + int code = -1; + std::thread killed([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + code = exceptionCodeOf([&] { store->dropNamespace(ns); }); + }); + killed.join(); + + EXPECT_EQ(code, 0); + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} + +namespace +{ + +/// A removal's owner stops while it waits for appends admitted before its closure, with the catalog row left +/// `Live` or turned `Removing` meanwhile. +void runRemovalStoppedDuringPositiveDrain(StoppedBy owner) +{ + for (const bool row_turns_removing : {false, true}) + { + SCOPED_TRACE(row_turns_removing ? "row turned Removing" : "exact Live"); + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{row_turns_removing ? "srv1/stopped_drain_removing" : "srv1/stopped_drain_live"}; + publishEmptyPart(store, ns, "owned"); + const NamespaceLifeId life = *lifeIfCatalogedForTest(backend, store->layout(), ns); + + StoppedCallerSync sync; + std::atomic leader_entered{false}; + store->setRefPreCarveHookForTest([&] + { + if (!leader_entered.exchange(true)) + sync.parkBlocker(); + }); + SCOPE_EXIT({ store->setRefPreCarveHookForTest(nullptr); }); + + std::future leader = std::async(std::launch::async, [&] { return exceptionCodeOf([&] { updatePublishedAt(store, ns); }); }); + ASSERT_TRUE(sync.waitBlockerParked()); + + int removal_code = 0; + bool returned_while_leader_parked = false; + CasRefLedger::RemovalFlagsForTest flags_on_return; + std::function stop_removal; + std::atomic removal_query_ready{false}; + std::thread removal([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + auto background_stopped = std::make_shared>(false); + const auto background = DB::Cas::tests::backgroundOwnerStoppedBy(background_stopped); + stop_removal = DB::Cas::tests::stopperOf(owner, query, background_stopped); + removal_query_ready = true; + removal_code = exceptionCodeOf([&] { store->dropNamespace(ns); }); + flags_on_return = store->removalFlagsForTest(ns); + returned_while_leader_parked = sync.stoppedCallerReturned(); + }); + /// Only the drain wait follows the closure, so a closed lane means the removal is in, or entering, that wait. + const bool closed = spinUntil([&] { return store->removalFlagsForTest(ns).admission_closed; }); + EXPECT_TRUE(closed); + if (row_turns_removing) + rewriteCatalogRow(backend, store->layout(), ns, CatalogEntry{ + .ns = ns, .state = NsState::Removing, .incarnation = life.incarnation, .removal_started_round = 0}); + ASSERT_TRUE(removal_query_ready.load()); + stop_removal(); + /// A killed query keeps waiting, so the parked leader is released independently. + if (owner == StoppedBy::Query) + sync.stoppedCallerReturned(); + removal.join(); + ASSERT_EQ(leader.wait_for(STOP_WATCHDOG), std::future_status::ready); + + EXPECT_EQ(leader.get(), 0) << "the append admitted before the closure commits"; + if (owner == StoppedBy::Query) + { + EXPECT_EQ(removal_code, 0) << "a killed query's removal completes once the admitted append committed"; + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); + continue; + } + EXPECT_EQ(removal_code, DB::ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_leader_parked) << "the stopped removal waited for the admitted append"; + EXPECT_FALSE(flags_on_return.attempt_active); + EXPECT_EQ(flags_on_return.admission_closed, row_turns_removing); + if (row_turns_removing) + { + expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { updatePublishedAt(store, ns); }); + } + else + { + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + EXPECT_NO_THROW(updatePublishedAt(store, ns)) << "the proven Live lane must be open again"; + } + } +} + +} + +/// A removal whose background owner stops while it waits for appends admitted before its closure sent nothing. +/// It reopens the lane only when a fresh read proves the exact `Live` row; a row turned `Removing` meanwhile keeps +/// it closed. The admitted append commits either way. +TEST(CASRefWriterNamespaceRemoval, BackgroundStoppedPositiveDrainReopensOnlyItsProvenLiveLane) +{ + runRemovalStoppedDuringPositiveDrain(StoppedBy::Background); +} + +/// A removal whose query is killed while it waits for an admitted append keeps waiting and removes the namespace +/// once the append has committed. +TEST(CASRefWriterNamespaceRemoval, KilledQuerysRemovalWaitsForTheAdmittedAppendAndCompletes) +{ + runRemovalStoppedDuringPositiveDrain(StoppedBy::Query); +} + +/// The `Live -> Removing` reply is lost and the owner stops while the write's settling read is in flight. The +/// read is owed and cannot prove the outcome, so the write is not resent, the caller gets the unresolved +/// retry-later exit, and the lane stays closed against the write that may still land. +TEST(CASRefWriterNamespaceRemoval, StopDuringRemovingSettlementKeepsUnresolvedExit) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/stop_during_removing_settlement"}; + publishEmptyPart(store, ns, "owned"); + const String catalog_key = store->layout().refCatalogKey(); + const size_t catalog_writes_before = catalogWritesInJournal(backend, store->layout()); + + StoppedCallerSync sync; + std::atomic parked_once{false}; + backend->read_observer = [&](const String & key) + { + if (key == catalog_key && backend->catalog_cas_fault_fired && !parked_once.exchange(true)) + sync.parkBlocker(); + }; + SCOPE_EXIT({ backend->read_observer = {}; }); + backend->catalog_fault_key = catalog_key; + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::ThrowUncommitted; + + int removal_code = 0; + std::function kill_removal; + std::thread removal([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + kill_removal = [&query] { query.kill(); }; + removal_code = exceptionCodeOf([&] { store->dropNamespace(ns); }); + sync.stoppedCallerReturned(); + }); + const bool parked = sync.waitBlockerParked(); + EXPECT_TRUE(parked) << "the lost write was never settled by a read"; + if (parked) + kill_removal(); + { + std::lock_guard lock(sync.mutex); + sync.stopped_returned = true; + } + sync.cv.notify_all(); + removal.join(); + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::None; + + EXPECT_EQ(removal_code, DB::ErrorCodes::NETWORK_ERROR); + EXPECT_EQ(catalogWritesInJournal(backend, store->layout()) - catalog_writes_before, 1u) << "a stopped owner resends nothing"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + expectPositiveLaneClosed(store, ns); +} + /// A refusal at the admission check inside `beginRemoving` comes before any write is sent, so nothing can /// land and a fresh `Live` row reopens the lane. The boot clock reads past the lease deadline exactly once, /// at that check. @@ -5957,7 +6432,6 @@ TEST(CASRefWriterNamespaceRemoval, DropSendsItsCreatorFenceReadAfterASlowFirstRe }; SCOPE_EXIT({ backend->read_observer = nullptr; }); - const uint64_t now_before = clock->nowMs(); EXPECT_THROW(store->dropNamespace(ns), DB::Exception); ASSERT_TRUE(first_read_ended_ms.has_value()); EXPECT_GT(fence_reads, 0U) << "the creator fence was never read"; @@ -5993,7 +6467,6 @@ TEST(CASRefWriterNamespaceRemoval, DropSendsItsGcStateReadAfterASlowFirstRead) }; SCOPE_EXIT({ backend->read_observer = nullptr; }); - const uint64_t now_before = clock->nowMs(); EXPECT_THROW(store->dropNamespace(ns), DB::Exception); ASSERT_TRUE(first_read_ended_ms.has_value()); EXPECT_GT(gc_state_reads, 0U) << "the gc/state read was never sent"; @@ -6025,7 +6498,6 @@ TEST(CASRefWriterNamespaceRemoval, DropSendsItsCatalogUpdateAfterASlowFirstRead) }; SCOPE_EXIT({ backend->read_observer = nullptr; }); - const uint64_t now_before = clock->nowMs(); EXPECT_THROW(store->dropNamespace(ns), DB::Exception); backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::None; ASSERT_TRUE(first_read_ended_ms.has_value()); @@ -6077,6 +6549,132 @@ TEST(CASRefWriterNamespaceRemoval, AReadFailingAfterAGapLongerThanTheWindowLeave EXPECT_NO_THROW(updatePublishedAt(store, ns)); } +/// Another server lands an unrelated catalog row inside every `Live -> Removing` write, so each write is +/// refused and the update ends at its submission cap. A write was sent, so the lane stays closed even +/// though the row still reads `Live`. An insert is refused before it sends anything, so it leaves no cleanup +/// duty and does not pin the build floor, and a retried removal completes. +TEST(CASRefWriterNamespaceRemoval, ACapExitAfterSendsLeavesTheLaneClosedAndARetriedDropCompletes) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + /// Pauses take no time, so the submission cap and not a window ends the update. + store->setCasRetrySleepForTest([](uint64_t) {}); + const Layout & layout = store->layout(); + const RootNamespace ns{"srv1/cap_exit_after_sends"}; + publishEmptyPart(store, ns, "owned"); + + backend->catalog_fault_key = layout.refCatalogKey(); + bool racing = false; + bool in_observer = false; + size_t rival_rows = 0; + store->setRemovalAttemptHookForTest([&] { racing = true; }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + backend->read_observer = [&](const String & key) + { + if (!racing || in_observer || key != layout.refCatalogKey()) + return; + in_observer = true; + SCOPE_EXIT({ in_observer = false; }); + /// Zero-padded, so each appended row sorts after the ones before it. + RefCatalog rival = readCatalogForTest(backend, layout).catalog; + rival.entries.push_back(CatalogEntry{ + .ns = RootNamespace{fmt::format("srv2/rival_{:03}", rival_rows)}, .state = NsState::Live, + .incarnation = UInt128(0xa000 + rival_rows)}); + ++rival_rows; + backend->catalog_replacement_bytes = encodeRefCatalog(rival); + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::OtherWriterReplacement; + }; + SCOPE_EXIT({ backend->read_observer = nullptr; }); + const size_t catalog_writes_before = catalogWritesInJournal(backend, layout); + + expectThrowsCodeWithMessage( + DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 submissions", [&] { store->dropNamespace(ns); }); + store->setRemovalAttemptHookForTest({}); + racing = false; + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::None; + EXPECT_EQ(catalogWritesInJournal(backend, layout) - catalog_writes_before, 100U); + EXPECT_EQ(catalogEntryOrThrow(backend, layout, ns).state, NsState::Live); + expectPositiveLaneClosed(store, ns); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "retry the `DROP TABLE`", + [&] { (void)publishEmptyPart(store, ns, "inserted_after_the_failed_drop"); }); + EXPECT_FALSE(store->writerCleanupDutiesPendingForTest()) << "the refused insert left a cleanup duty"; + EXPECT_EQ(store->minActive(), store->peekNextBuildSeq()) << "the refused insert pins the build floor"; + + EXPECT_NO_THROW(store->dropNamespace(ns)) << "a retried removal completes"; + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} + +/// A transaction whose precommit landed calls `precommitAdd` again after the lane closed. The refusal of +/// that second call must keep the first call's duty, so `abandon` neither forgets the binding nor deletes +/// the manifest body it names. +TEST(CASRefWriterNamespaceRemoval, ARefusedSecondPrecommitKeepsTheDurableDuty) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + store->setCasRetrySleepForTest([](uint64_t) {}); + const Layout & layout = store->layout(); + const RootNamespace ns{"srv1/refused_second_precommit"}; + publishEmptyPart(store, ns, "owned"); + + auto build = startBuildFor(store, ns, "held"); + const ManifestId id = build->stageManifest({}); + build->precommitAdd(ns, "held", id); + ASSERT_EQ(build->precommitState(), PartWriteTxn::PrecommitState::Durable); + + backend->catalog_fault_key = layout.refCatalogKey(); + bool racing = false; + bool in_observer = false; + size_t rival_rows = 0; + store->setRemovalAttemptHookForTest([&] { racing = true; }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + backend->read_observer = [&](const String & key) + { + if (!racing || in_observer || key != layout.refCatalogKey()) + return; + in_observer = true; + SCOPE_EXIT({ in_observer = false; }); + RefCatalog rival = readCatalogForTest(backend, layout).catalog; + rival.entries.push_back(CatalogEntry{ + .ns = RootNamespace{fmt::format("srv2/rival_{:03}", rival_rows)}, .state = NsState::Live, + .incarnation = UInt128(0xb000 + rival_rows)}); + ++rival_rows; + backend->catalog_replacement_bytes = encodeRefCatalog(rival); + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::OtherWriterReplacement; + }; + SCOPE_EXIT({ backend->read_observer = nullptr; }); + + expectThrowsCodeWithMessage( + DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 submissions", [&] { store->dropNamespace(ns); }); + store->setRemovalAttemptHookForTest({}); + racing = false; + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::None; + expectPositiveLaneClosed(store, ns); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "retry the `DROP TABLE`", + [&] { build->precommitAdd(ns, "held", id); }); + EXPECT_EQ(build->precommitState(), PartWriteTxn::PrecommitState::Durable) + << "the refused second call erased the first call's duty"; + + bool abandoned = false; + try + { + build->abandon(); + abandoned = true; + } + catch (const DB::Exception &) // NOLINT(bugprone-empty-catch) + { + } + build.reset(); + const bool bound = independentFullReplayForTest(*backend, layout, ns).getPrecommits().contains({"held", id.ref}); + if (abandoned) + EXPECT_FALSE(bound) << "abandon returned without removing the binding"; + else + EXPECT_TRUE(store->writerCleanupDutiesPendingForTest()) << "a failed abandon left the binding without a cleanup duty"; + if (bound) + EXPECT_TRUE(readOf(backend, layout.manifestKey(id))) << "the body a precommit binding names was deleted"; +} + /// A remount replaces the runtime, and the new one starts with the lane open. TEST(CASRefWriterNamespaceRemoval, RemountReopensTheLaneAfterAnAmbiguousBeginRemoving) { @@ -7839,7 +8437,6 @@ TEST(CASRefWriterRecoveryRetry, TransientSealFailureIsRetriedThenSucceeds) config.server_id = UInt128(1); config.mount_lease_ttl_ms = std::chrono::milliseconds(500); config.cas_request_budget = sealTestTinyBudget(); - config.cas_request_budget.recovery_retry_budget_ms = 120000; config.cas_request_budget.recovery_retry_initial_backoff_ms = 1000; config.cas_request_budget.recovery_retry_max_backoff_ms = 30000; /// Captured by value: `fake_now` stays frozen for the whole test (see below), and the Pool can @@ -7895,7 +8492,6 @@ TEST(CASRefWriterRecoveryRetry, RecoveryDoesNotEnumerateItsStream) config.server_id = UInt128(1); config.mount_lease_ttl_ms = std::chrono::milliseconds(500); config.cas_request_budget = sealTestTinyBudget(); - config.cas_request_budget.recovery_retry_budget_ms = 120000; /// Captured by value: `fake_now` is never mutated in this test, and the Pool can outlive this /// stack frame (a background publish holds `shared_from_this()`), so a by-reference capture would /// dangle. @@ -8065,7 +8661,6 @@ TEST(CASRefWriterRecoveryRetry, ThrowingBackoffSleepDoesNotWedgeRecovery) config.server_id = UInt128(1); config.mount_lease_ttl_ms = std::chrono::milliseconds(500); config.cas_request_budget = sealTestTinyBudget(); - config.cas_request_budget.recovery_retry_budget_ms = 120000; config.wait_sleep_fn = [](uint64_t) {}; auto store = openPoolWithConfig(backend, config); ASSERT_TRUE(store); @@ -8282,6 +8877,413 @@ TEST(CASRefWriterRecoveryRetry, TheStructuralBrakeEndsBeforeEightWalks) EXPECT_EQ(scripted.script->walks.load(), 4u); } +/// =================================================================================== +/// A stopped owner: no new walk after a failed walk; a restart after a successful walk, a structural exit +/// and a follower keep their plain answers. +/// =================================================================================== + +namespace +{ + +std::exception_ptr queryTimeout() +{ + return std::make_exception_ptr(DB::Exception(DB::ErrorCodes::TIMEOUT_EXCEEDED, "test: the query timed out")); +} + +} + +TEST(CASRefWriterRecoveryRetry, OwnerTimeoutEndsAfterFailedWalkTransportTimeoutCanRecover) +{ + { + SCOPED_TRACE("the owner timed out during a failed walk"); + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + scripted.script->before_walk = [&query](uint32_t) { query.kill(queryTimeout()); }; + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + scripted.script->before_walk = {}; + }); + EXPECT_EQ(scripted.script->walks.load(), 1u) << "no walk after the owner's timeout"; + EXPECT_EQ(scripted.script->pauses.load(), 0u); + } + { + SCOPED_TRACE("control: a transport timeout under a live owner"); + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}); + scripted.script->transient_code = DB::ErrorCodes::TIMEOUT_EXCEEDED; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery &) + { + size_t refs = 0; + EXPECT_NO_THROW(refs = scripted.store->listRefs(scripted.ns).size()); + EXPECT_EQ(refs, 2u); + }); + EXPECT_EQ(scripted.script->walks.load(), 2u); + } +} + +TEST(CASRefWriterRecoveryRetry, StopAfterTransientFailureStartsNoNewWalk) +{ + for (const bool stop_in_backoff : {false, true}) + { + SCOPED_TRACE(stop_in_backoff ? "stop in the backoff" : "stop during the failed walk"); + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + if (stop_in_backoff) + scripted.script->on_pause = [&query] { query.kill(); }; + else + scripted.script->before_walk = [&query](uint32_t) { query.kill(); }; + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + scripted.script->on_pause = {}; + scripted.script->before_walk = {}; + }); + EXPECT_EQ(scripted.script->walks.load(), 1u); + EXPECT_EQ(scripted.script->pauses.load(), stop_in_backoff ? 1u : 0u); + } +} + +/// The pool's own backoff, ten seconds long, sleeps in owner-stop slices: a kill during a slice ends recovery when that +/// slice ends, with no further slice and no new walk. +TEST(CASRefWriterRecoveryRetry, StopDuringBackoffEndsWithinASlice) +{ + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}, /*production_backoff_ms=*/10'000); + std::mutex mutex; + std::condition_variable cv; + bool sleeping = false; + bool killed = false; + std::vector slices; + scripted.store->setRefRecoveryRetrySliceSleepForTest([&](uint64_t ms) + { + std::unique_lock lock(mutex); + slices.push_back(ms); + sleeping = true; + cv.notify_all(); + cv.wait_for(lock, STOP_WATCHDOG, [&] { return killed; }); + }); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + std::thread killer([&] + { + std::unique_lock lock(mutex); + cv.wait_for(lock, STOP_WATCHDOG, [&] { return sleeping; }); + query.kill(); + killed = true; + cv.notify_all(); + }); + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + killer.join(); + }); + ASSERT_EQ(slices.size(), 1u) << "a slice started after the kill"; + EXPECT_EQ(*std::max_element(slices.begin(), slices.end()), static_cast(DB::Cas::kOwnerStopSlice.count())) + << "the backoff is not sliced at the owner-stop slice"; + EXPECT_EQ(scripted.script->walks.load(), 1u); +} + +TEST(CASRefWriterRecoveryRetry, StopDuringCorruptionConfirmationIsNotCorruption) +{ + auto scripted = openScriptedRecovery({WalkFate::Corrupt}); + const String catalog_key = scripted.store->layout().refCatalogKey(); + /// The walk fails before its first request, so the next catalog read is the confirmation's. + std::atomic walk_failed{false}; + std::atomic confirmation_read_lost{false}; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + scripted.script->before_walk = [&](uint32_t) { walk_failed = true; }; + scripted.script->on_read = [&](const String & key) + { + if (key != catalog_key || !walk_failed.exchange(false)) + return; + confirmation_read_lost = true; + query.kill(); + throw Poco::TimeoutException("test: the confirmation's catalog read is lost"); + }; + String error; + try + { + scripted.store->listRefs(scripted.ns); + } + catch (const Poco::TimeoutException & e) + { + error = e.message(); + } + catch (...) + { + error = "unexpected: " + DB::getCurrentExceptionMessage(false); + } + EXPECT_EQ(error, "test: the confirmation's catalog read is lost") << "the confirmation's own failure"; + scripted.script->before_walk = {}; + scripted.script->on_read = {}; + }); + EXPECT_TRUE(confirmation_read_lost.load()) << "the owner stopped during the corruption confirmation"; + EXPECT_EQ(scripted.script->walks.load(), 1u); + + /// The failure released the recovery and `state_mutex`, so the next recovery of the table proceeds. A wedged one + /// keeps its own references to the pool, so its thread is left behind. + auto next_recovery = std::make_shared>(); + auto recovered = next_recovery->get_future(); + std::thread next([store = scripted.store, ns = scripted.ns, next_recovery] + { + try + { + next_recovery->set_value(store->listRefs(ns).size()); + } + catch (...) + { + next_recovery->set_exception(std::current_exception()); + } + }); + if (recovered.wait_for(STOP_WATCHDOG) != std::future_status::ready) + { + next.detach(); + FAIL() << "the next recovery of the table did not return"; + } + next.join(); + EXPECT_EQ(recovered.get(), 2u); + EXPECT_EQ(scripted.script->walks.load(), 2u); +} + +/// A confirmation that fails under a live owner did not establish that the catalog still names the life, so its own +/// failure is the answer, never the walk's corruption. +TEST(CASRefWriterRecoveryRetry, FailedCorruptionConfirmationUnderALiveOwnerIsNotCorruption) +{ + auto scripted = openScriptedRecovery({WalkFate::Corrupt}); + const String catalog_key = scripted.store->layout().refCatalogKey(); + /// The walk fails before its first request, so the next catalog read is the confirmation's. + std::atomic walk_failed{false}; + std::atomic confirmation_read_refused{false}; + int code = 0; + String message; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery &) + { + scripted.script->before_walk = [&](uint32_t) { walk_failed = true; }; + scripted.script->on_read = [&](const String & key) + { + if (key != catalog_key || !walk_failed.exchange(false)) + return; + confirmation_read_refused = true; + throw DB::Exception(DB::ErrorCodes::READONLY, "test: the confirmation's catalog read is refused"); + }; + try + { + scripted.store->listRefs(scripted.ns); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + scripted.script->before_walk = {}; + scripted.script->on_read = {}; + }); + EXPECT_TRUE(confirmation_read_refused.load()); + EXPECT_EQ(code, DB::ErrorCodes::READONLY) << message; + EXPECT_NE(message.find("the confirmation's catalog read is refused"), String::npos) << message; + EXPECT_EQ(scripted.script->walks.load(), 1u); +} + +/// A kill in the backoff after a network failure vetoes the next walk and keeps the network error, which the part +/// loader's classifier reads as retryable rather than as damage. +TEST(CASRefWriterRecoveryRetry, KillInBackoffAfterNetworkFailureKeepsTheNetworkError) +{ + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}); + scripted.script->transient_code = DB::ErrorCodes::NETWORK_ERROR; + std::exception_ptr error; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + scripted.script->on_pause = [&query] { query.kill(); }; + try + { + scripted.store->listRefs(scripted.ns); + } + catch (...) + { + error = std::current_exception(); + } + scripted.script->on_pause = {}; + }); + ASSERT_TRUE(error); + EXPECT_EQ(DB::getExceptionMessage(error, false).find("scripted walk failure") != String::npos, true) + << DB::getExceptionMessage(error, false); + EXPECT_TRUE(DB::isRetryableException(error)) << "a vetoed retry must not read as part damage"; + EXPECT_EQ(scripted.script->walks.load(), 1u); + EXPECT_EQ(scripted.script->pauses.load(), 1u); +} + +/// A walk that fails with real corruption of a life the catalog no longer names ends the same for a killed query as +/// for a live one: the confirmation is no retry, so it runs and finds the life removed. +TEST(CASRefWriterRecoveryRetry, KilledQuerysCorruptionOfARemovedLifeIsConfirmed) +{ + const auto run = [](bool kill) + { + auto scripted = openScriptedRecovery({WalkFate::Corrupt}); + const Layout layout("p"); + const NamespaceLifeId life = lifeIfCatalogedForTest(scripted.backend, layout, scripted.ns).value(); + std::pair outcome{0, ""}; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + scripted.script->before_walk = [&](uint32_t) + { + eraseLifeForTest(scripted.backend, layout, life); + if (kill) + query.kill(); + }; + try + { + outcome.second = std::to_string(scripted.store->listRefs(scripted.ns).size()); + } + catch (const DB::Exception & e) + { + outcome = {e.code(), e.message()}; + } + scripted.script->before_walk = {}; + }); + EXPECT_EQ(scripted.script->walks.load(), 1u); + return outcome; + }; + const auto live = run(false); + const auto killed = run(true); + EXPECT_NE(live.first, DB::ErrorCodes::CORRUPTED_DATA) << live.second; + EXPECT_EQ(killed.first, live.first) << killed.second; + EXPECT_EQ(killed.second, live.second); +} + +/// A query's stored cause with the `CORRUPTED_DATA` code says nothing about the checkpoint: the failed base read +/// starts no checkpoint reread and no restart, and the stored cause propagates. +TEST(CASRefWriterRecoveryRetry, StoredCorruptedDataStartsNoCheckpointReread) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + const RootNamespace ns{"srv1/stored_corruption"}; + const ManifestRef ma = manifestRef(1, 1, 1); + DB::Cas::tests::fixture::admitLive(*backend, layout, ns); + const NamespaceLifeId life = *lifeIfCatalogedForTest(backend, layout, ns); + const RefTxnId snap{1, 10}; + DB::Cas::tests::fixture::writeRefLogRaw(*backend, layout, RefLogTxn{ + .ns = ns.string(), + .txn_id = snap, + .ops = publishCommittedOps("a", ma), + .prev_epoch_seal = std::nullopt}); + writeRefSnapshotRaw(*backend, layout, minimalLiveSnapshot(ns.string(), snap, {committedRow("a", ma)})); + ASSERT_TRUE(createRaw(backend, layout.refCkptKey(life), encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = 1, + .committed_through = snap, + .checkpoint_snapshot_id = snap, + .last_epoch_seal = std::nullopt}, 1))); + auto store = openPool(backend); + const String snapshot_key = layout.refSnapshotKey(life, snap); + const String ckpt_key = layout.refCkptKey(life); + uint64_t ckpt_reads_before = 0; + std::exception_ptr error; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + /// The store fails the base read the way the S3 client does for a killed query: with the query's cause. + backend->read_observer = [&](const String & key) + { + if (key != snapshot_key) + return; + query.kill(std::make_exception_ptr(DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "the query's stored cause"))); + DB::CurrentThread::checkIfNotCancelled(); + }; + ckpt_reads_before = backend->getCount(ckpt_key); + try + { + (void)store->resolveRef(ns, "a"); + } + catch (...) + { + error = std::current_exception(); + } + backend->read_observer = {}; + }); + ASSERT_TRUE(error); + EXPECT_NE(DB::getExceptionMessage(error, false).find("the query's stored cause"), String::npos) + << DB::getExceptionMessage(error, false); + EXPECT_EQ(backend->getCount(ckpt_key) - ckpt_reads_before, 1u) << "the walk's own checkpoint read, no reread"; + EXPECT_EQ(store->refRecoveryRestartsForTest(ns), 0u); +} + +/// Guard: a follower waits read-only, so a killed follower takes the leader's successful recovery. +TEST(CASRefWriterRecoveryRetry, KilledFollowerConsumesSuccessfulRecovery) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + const NamespaceLifeId life = seedRecoverablePart(backend, layout, RootNamespace{"srv1/killed_follower"}); + const auto park = std::make_shared(); + auto store = openPoolWithConfig(backend, ParkedRecovery::config(park)); + const uint64_t installs_before = store->recoveryInstallCountForTest(); + + std::atomic calls{0}; + auto [leader, follower] = runWithAWaiter(park, store, life.ns, + [&]() -> std::optional + { + if (calls.fetch_add(1) == 0) + return store->resolveRef(life.ns, "part_1"); + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + return store->resolveRef(life.ns, "part_1"); + }, + [] {}); + EXPECT_TRUE(leader.get().has_value()); + std::optional follower_answer; + EXPECT_NO_THROW(follower_answer = follower.get()); + EXPECT_TRUE(follower_answer.has_value()); + EXPECT_EQ(store->recoveryInstallCountForTest(), installs_before + 1) << "the follower ran no walk of its own"; +} + +/// Guard: a walk that succeeds but finds the checkpoint moved restarts for a stopped reader too. +TEST(CASRefWriterRecoveryRetry, CheckpointMovedRestartRunsForStoppedReader) +{ + auto scripted = openScriptedRecovery({WalkFate::Restart}); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + query.kill(); + size_t refs = 0; + EXPECT_NO_THROW(refs = scripted.store->listRefs(scripted.ns).size()); + EXPECT_EQ(refs, 2u); + }); + EXPECT_EQ(scripted.script->walks.load(), 2u) << "the restart walk ran"; + EXPECT_TRUE(scripted.store->refTableRecoveredForTest(scripted.ns)); +} + +/// Guard: the structural brake and the walk cap answer a stopped reader with their retryable error. +TEST(CASRefWriterRecoveryRetry, StoppedReaderAtStructuralBrakeAndWalkCapGets210) +{ + { + SCOPED_TRACE("the structural brake"); + auto scripted = openScriptedRecovery(std::vector(20, WalkFate::Restart)); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + query.kill(); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "restarted 3 times", + [&] { scripted.store->listRefs(scripted.ns); }); + }); + EXPECT_EQ(scripted.script->walks.load(), 4u); + } + { + SCOPED_TRACE("the walk cap"); + std::vector fates(5, WalkFate::FailTransiently); + fates.insert(fates.end(), 3, WalkFate::Restart); + auto scripted = openScriptedRecovery(std::move(fates)); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + /// The owner stops once the failed walks are behind it: walks 6 to 8 follow successful walks. + scripted.script->before_walk = [&query](uint32_t walk) + { + if (walk == 6) + query.kill(); + }; + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "the last walk restarted because the checkpoint or its base moved", + [&] { scripted.store->listRefs(scripted.ns); }); + scripted.script->before_walk = {}; + }); + EXPECT_EQ(scripted.script->walks.load(), 8u); + } +} + /// =================================================================================== /// Task 16: `hasAnyRefWithPrefix` -- pure existence probe, same recovery preamble as `listRefs` but /// without materializing the full ref map (an early-exit scan). From f2a0adff117e9baa23af407ffffa840517322e59 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:28:04 +0100 Subject: [PATCH 10/47] Stop CAS part writes and blob uploads at the owner's request A stop before a blob publication ends the upload with the previous publication's error; a stopped owner's failure is not retried, and a landed body stays debris. A refused precommit owes no cleanup of its own and keeps an earlier call's duty. The commit compensation and the rename undo are owed. Upload workers check they run in the submitter's thread group. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressedTransaction.cpp | 11 +- .../Parts/PartFolderAccess.cpp | 3 + .../ContentAddressed/Pool/CasPartWriteTxn.cpp | 175 +++-- .../ContentAddressed/Pool/CasPartWriteTxn.h | 21 +- .../ContentAddressed/Pool/CasPool.cpp | 12 +- .../ContentAddressed/Pool/CasRefLedger.cpp | 34 +- src/Disks/tests/gtest_cas_forget.cpp | 40 + .../tests/gtest_cas_part_folder_access.cpp | 693 +++++++++++++++++- src/Disks/tests/gtest_cas_part_write.cpp | 357 +++++++++ src/Disks/tests/gtest_cas_upload_detached.cpp | 2 +- src/Disks/tests/gtest_cas_upload_fanout.cpp | 260 +++++++ 11 files changed, 1514 insertions(+), 94 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 130c3222ee058..4667e69bba3f0 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -707,6 +708,8 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & /// dropped. `dropRefIfMatches` additionally guards against a concurrent repoint of the SAME ref /// since this call's own publish: it removes the ref only if it still names the exact /// `manifest_ref` this commit bound, leaving a newer binding untouched. + /// Owed to the failed commit: a stopped owner must not leave a ref of that commit live. + const auto owed = Cas::OwnerScope::owed(); for (const auto & oc : part_outcomes) if (oc && oc->created) metadata_storage.partAccess()->dropRefIfMatches({oc->ns, oc->ref}, oc->manifest_ref); @@ -1768,6 +1771,8 @@ void ContentAddressedTransaction::moveFile(const std::string & path_from, const /// attach via moveFile): delegate to moveDirectory, which owns directory shapes. if (src && dst && !src->ref.empty() && src->file.empty() && !dst->ref.empty() && dst->file.empty()) { + /// Owed to the reserved name: only the undo reaches here, and SQL rejects a part left under it. + const auto owed = Cas::OwnerScope::owed(); moveDirectory(path_from, path_to); return; } @@ -2044,6 +2049,8 @@ void fanOutBlobUploads( size_t idx = 0; for (const auto & [ref, req] : grouped) { + /// The drain guard still joins the tasks already dispatched. + throwIfBackgroundStopped(); std::optional * slot = &result_slots[idx++]; BlobUploadRequest task_req = req; const BlobUploadFanoutHooksForTest * task_hooks = hooks; @@ -2052,8 +2059,10 @@ void fanOutBlobUploads( /// Schedule and track in ONE no-throw step: `enqueueAndGiveOwnership` returns the handle (the /// task is now runnable) and the pre-reserved `emplace_back` records it without allocating, so /// there is no window in which a scheduled task is untracked. - handles.emplace_back(runner.enqueueAndGiveOwnership([slot, txn, req_by_value = std::move(task_req), task_hooks] + handles.emplace_back(runner.enqueueAndGiveOwnership([slot, txn, req_by_value = std::move(task_req), task_hooks, + group = CurrentThread::getGroup()] { + throwUnlessInThreadGroup(group, "CAS blob upload worker"); if (task_hooks && task_hooks->in_task) task_hooks->in_task(req_by_value.ref); *slot = txn->uploadBlobDetached(req_by_value); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp index 6eea08da074c5..a4497837b0b86 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp @@ -257,6 +257,9 @@ std::shared_ptr CachedPartFolderAccess::buildView( if (freshness != Freshness::CachedForLoad) return PartFolderView::make(key, resolved, store->readManifestShared(resolved.manifest_id)); + /// A cold build's leader stopped: its followers build again rather than share the leader's verdict. + struct LeaderStopped {}; + const String cache_key = key.cacheKey(); /// Readers that resolved different manifests of one ref must not share a build. const String build_key = cache_key + '\0' + resolved.manifest_id.root_namespace.string() + '\0' diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index 27a822fde859e..8f0f4ec4f87ca 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -80,8 +81,8 @@ bool readBlobIntent(CasOperation & op, const Layout & layout, const BlobRef & re } catch (Exception & e) { - e.addMessage("while reading the deletion intent `{}`; a writer needs GET and LIST on `{}`, and a store that denies " - "LIST answers 403 for an absent intent", key, layout.blobIntentsPrefix()); + addMessageUnlessQueryStoredCause(e, fmt::format("while reading the deletion intent `{}`; a writer needs GET and LIST on `{}`, " + "and a store that denies LIST answers 403 for an absent intent", key, layout.blobIntentsPrefix())); throw; } } @@ -255,6 +256,16 @@ void PartWriteTxn::requireAlive() const "the mount was fenced out and self-remounted; restart the build", epoch, live)); } +void PartWriteTxn::requireAdoptable(std::string_view where) const +{ + requireAlive(); + throwIfBackgroundStopped(); + if (!store->mountRequests().resume(txn_generation).admitted()) + throwCasTransientUnavailable( + fmt::format("PartWriteTxn::{}", where), + "the mount no longer admits the generation this build began under, so its upload results are not adopted"); +} + PutBlobResult PartWriteTxn::putBlob(const BlobRef & ref, BlobSource source) { /// Serial API preserved for existing callers: run the transaction-detached primitive, then fold its @@ -264,6 +275,9 @@ PutBlobResult PartWriteTxn::putBlob(const BlobRef & ref, BlobSource source) /// the request's `declared_size` mirrors it. const uint64_t declared_size = source.size; const BlobUploadResult r = uploadBlobDetached(BlobUploadRequest{ref, std::move(source), declared_size}); + if (adoption_hook_for_test) + adoption_hook_for_test(1); + requireAdoptable("putBlob"); deps.insert_or_assign(r.ref, r.dep); return PutBlobResult{r.ref, r.dep.size}; } @@ -300,7 +314,7 @@ void PartWriteTxn::mergeBlobUploadResults(std::span resu /// Build-and-swap: apply every result into a COPY of the live `deps`. The live member is touched /// ONLY by the final `swap` below, which runs after every result has applied -- so a mid-loop - /// exception (a `bad_alloc` from map-node allocation, or one injected by `setMergeHookForTest`'s + /// exception (a `bad_alloc` from map-node allocation, or one injected by `setAdoptionHookForTest`'s /// hook) leaves `deps` byte-for-byte as it was before this call. Applying an already-validated /// duplicate a second time is idempotent (identical value, same key). std::map candidate = deps; @@ -309,9 +323,10 @@ void PartWriteTxn::mergeBlobUploadResults(std::span resu { candidate.insert_or_assign(r.ref, r.dep); ++applied; - if (merge_hook_for_test) - merge_hook_for_test(applied); + if (adoption_hook_for_test) + adoption_hook_for_test(applied); } + requireAdoptable("mergeBlobUploadResults"); deps.swap(candidate); } @@ -373,6 +388,8 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) constexpr int max_publication_attempts = 8; /// Every exit by exception after a failed attempt gave up on the blob. int failed_attempts = 0; + /// The latest failed publication: what a query stopped before the next one ends with. + std::exception_ptr last_failure; const int exceptions_at_entry = std::uncaught_exceptions(); SCOPE_EXIT({ if (failed_attempts > 0 && std::uncaught_exceptions() > exceptions_at_entry) @@ -384,10 +401,11 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// Pace the reissues the way the request engine paces its own, and through the engine's own /// clock: an ambiguous publication is most often a store under load, and a large body /// republished eight times back to back is what makes that worse. After `requireAlive`, so a - /// cancelled or superseded build fails closed instead of spending a backoff first. - if (attempt > 0) - op.pause(Retry::backoff(attempt)); - const std::optional present = op.head(key, policy); + /// cancelled or superseded build fails closed instead of spending a backoff first. A query stopped in the + /// pause ends the upload with the failed publication's own error. + if (attempt > 0 && !sleepUnlessQueryStops(Retry::backoff(attempt), [&op](uint64_t ms) { op.sleepFor(ms); })) + rethrowVetoedPublicationFailure(key, last_failure); + const std::optional present = op.head(key, Retry::standard()); BlobPublicationReason reason = BlobPublicationReason::Absent; if (present) @@ -460,6 +478,11 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) } } + /// A stop before a publication ends the upload: with the previous publication's failure if there is one. + if (!last_failure) + throwIfQueryStopped(); + else if (queryStopRequested()) + rethrowVetoedPublicationFailure(key, last_failure); const bool first_publication = source.beginPublication(); BlobPublicationTransport transport; @@ -494,11 +517,18 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// among every source over that object. op.publish(BlobPublishRequest{key, std::move(publication)}, Retry::once()); } - catch (const std::exception & error) + catch (...) { + /// A stopped owner's failure is no store answer and is not retried: a landed body stays debris, never adopted. + /// The background verdict first; a query's veto converts a credential refusal as the pause does. + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(std::move(stop)); + if (queryStopRequested()) + rethrowVetoedPublicationFailure(key, std::current_exception()); /// A publication this build is no longer admitted to make is not an ambiguity to retry: /// every further request of this operation refuses the same way. - if (isDeterministicBlobPublicationFailure(error) || !op.admitted()) + if (const auto * error = current_exception_cast(); + error && (isDeterministicBlobPublicationFailure(*error) || !op.admitted())) throw; ++failed_attempts; last_failure = std::current_exception(); @@ -597,10 +627,14 @@ String describeManifestPutGiveUp(const GaveUp & gave_up) case GaveUp::Why::Attempts: throw Exception(ErrorCodes::LOGICAL_ERROR, "A single part write is never capped by a decision count"); case GaveUp::Why::Unresolved: - if (gave_up.sent_any) + if (gave_up.sent_any && std::holds_alternative(gave_up.last_seen)) return fmt::format( "is UNCERTAIN: {} attempt(s) sent and the resolving read did not complete ({}); the body may have landed", gave_up.attempts_sent, detail::renderObservation(gave_up.last_seen)); + if (gave_up.sent_any) + return fmt::format( + "is UNCERTAIN: {} attempt(s) sent and not sent again after the resolving read found {}; the body may " + "have landed", gave_up.attempts_sent, detail::renderObservation(gave_up.last_seen)); return fmt::format( "was not sent: a read of the current object did not complete ({})", detail::renderObservation(gave_up.last_seen)); @@ -777,62 +811,79 @@ void PartWriteTxn::precommitAdd(const RootNamespace & target_ns, const String & /// live precommit with no cleanup owner and no body. Same discipline, and same reason, as the ref /// lane's preconstructed wedge. The three fields are plain assignments of already-materialized /// values, so this cannot throw between the record and the append. + /// A refusal restores what an earlier invocation of this transaction recorded, including its duty. + RootNamespace previous_target_ns = precommit_target_ns; + String previous_final_ref = precommit_final_ref; + const ManifestRef previous_manifest = precommit_manifest; + const PrecommitState previous_state = precommit_state; precommit_target_ns = target_ns; precommit_final_ref = final_ref_name; precommit_manifest = id.ref; precommit_state = PrecommitState::Uncertain; - store->appendRefOps(target_ns, MutationScope::ref(final_ref_name), - /// Capture everything the closure reads BY VALUE (the `store` handle, target namespace, ref name, - /// and manifest id) rather than `[&]`: defense-in-depth so a closure that ever outlives this - /// stack frame (e.g. if the append lane stranded its item) never dereferences a dead stack. The - /// ref-lane leadership guard is the real fix; this makes the closure self-contained regardless. - [pool = store, target_ns, final_ref_name, id, id_staged_by_this_txn, txn_build_id = build_id](const RefTableState & state) -> std::vector - { - /// Idempotent re-add: the target ref is ALREADY committed to this EXACT manifest_ref (a - /// legitimate re-drive calling precommitAdd+promote again for content that is already - /// live -- see `promote`'s matching no-op guard). Nothing to append: re-adding a precommit - /// for an already-owned manifest would violate "no conflicting owner may name the same - /// manifest", which the state machine enforces for every OTHER case. - /// - /// A3 mint-tightening's enforcement lives HERE, gated on this SAME live-state read, rather - /// than unconditionally before the closure: a legitimate re-drive can be handed an id that - /// this exact `PartWriteTxn` object never staged (e.g. a fresh build re-precommitting - /// content a PRIOR, since-destroyed build already promoted -- `CasPromoteRepublish. - /// PromoteSameManifestIsIdempotent`). That case is not a fresh ownership grant: the manifest - /// is already `final_ref_name`'s live, currently-protected binding, so re-affirming it - /// creates no new ABA surface. Checking membership-or-committed-match atomically under the - /// SAME state read (rather than a separate pre-check against a possibly-stale resolve) is - /// what keeps this race-free: a snapshot taken before the closure could see "already - /// committed to id.ref" and let a later closure invocation append a fresh owner_transition - /// after a concurrent repoint moved the ref away from id.ref in between -- exactly the - /// re-ownership of a dropped identity this check exists to prevent. - if (const auto it = state.getCommitted().find(final_ref_name); - it != state.getCommitted().end() && it->second.manifest_ref == id.ref) - return {}; - if (!id_staged_by_this_txn) - throw Exception(ErrorCodes::LOGICAL_ERROR, - "precommitAdd: manifest '{}' was not staged by this transaction (build {}) and is not the current " - "committed manifest of ref '{}' in namespace '{}' -- refusing to re-own a foreign or previously-dropped identity", - manifestRefDebugString(id.ref), u128ToHex(txn_build_id), final_ref_name, target_ns.string()); - - std::vector ops; - if (state.getLifecycle() != RefLifecycle::Live) + try + { + store->appendRefOps(target_ns, MutationScope::ref(final_ref_name), + /// Capture everything the closure reads BY VALUE (the `store` handle, target namespace, ref name, + /// and manifest id) rather than `[&]`: defense-in-depth so a closure that ever outlives this + /// stack frame (e.g. if the append lane stranded its item) never dereferences a dead stack. The + /// ref-lane leadership guard is the real fix; this makes the closure self-contained regardless. + [pool = store, target_ns, final_ref_name, id, id_staged_by_this_txn, txn_build_id = build_id](const RefTableState & state) -> std::vector { - /// Reaching an empty runtime here means catalog resolution admitted a new life. A - /// predecessor still `Removing` was refused before recovery, so rebirth needs no - /// physical marker or empty-prefix proof. - RefOp birth; - birth.kind = RefOpKind::NamespaceBirth; - ops.push_back(birth); - } - RefOp add; - add.kind = RefOpKind::OwnerTransition; - add.new_binding = RefOwnerBinding{RefOwnerKind::Precommit, final_ref_name, id.ref}; - ops.push_back(add); - return ops; - }, - RootMutationOrigin::Writer, RootMutationKind::Precommit); + /// Idempotent re-add: the target ref is ALREADY committed to this EXACT manifest_ref (a + /// legitimate re-drive calling precommitAdd+promote again for content that is already + /// live -- see `promote`'s matching no-op guard). Nothing to append: re-adding a precommit + /// for an already-owned manifest would violate "no conflicting owner may name the same + /// manifest", which the state machine enforces for every OTHER case. + /// + /// A3 mint-tightening's enforcement lives HERE, gated on this SAME live-state read, rather + /// than unconditionally before the closure: a legitimate re-drive can be handed an id that + /// this exact `PartWriteTxn` object never staged (e.g. a fresh build re-precommitting + /// content a PRIOR, since-destroyed build already promoted -- `CasPromoteRepublish. + /// PromoteSameManifestIsIdempotent`). That case is not a fresh ownership grant: the manifest + /// is already `final_ref_name`'s live, currently-protected binding, so re-affirming it + /// creates no new ABA surface. Checking membership-or-committed-match atomically under the + /// SAME state read (rather than a separate pre-check against a possibly-stale resolve) is + /// what keeps this race-free: a snapshot taken before the closure could see "already + /// committed to id.ref" and let a later closure invocation append a fresh owner_transition + /// after a concurrent repoint moved the ref away from id.ref in between -- exactly the + /// re-ownership of a dropped identity this check exists to prevent. + if (const auto it = state.getCommitted().find(final_ref_name); + it != state.getCommitted().end() && it->second.manifest_ref == id.ref) + return {}; + if (!id_staged_by_this_txn) + throw Exception(ErrorCodes::LOGICAL_ERROR, + "precommitAdd: manifest '{}' was not staged by this transaction (build {}) and is not the current " + "committed manifest of ref '{}' in namespace '{}' -- refusing to re-own a foreign or previously-dropped identity", + manifestRefDebugString(id.ref), u128ToHex(txn_build_id), final_ref_name, target_ns.string()); + + std::vector ops; + if (state.getLifecycle() != RefLifecycle::Live) + { + /// Reaching an empty runtime here means catalog resolution admitted a new life. A + /// predecessor still `Removing` was refused before recovery, so rebirth needs no + /// physical marker or empty-prefix proof. + RefOp birth; + birth.kind = RefOpKind::NamespaceBirth; + ops.push_back(birth); + } + RefOp add; + add.kind = RefOpKind::OwnerTransition; + add.new_binding = RefOwnerBinding{RefOwnerKind::Precommit, final_ref_name, id.ref}; + ops.push_back(add); + return ops; + }, + RootMutationOrigin::Writer, RootMutationKind::Precommit); + } + catch (const RefAdmissionRefusedException &) + { + /// Refused before the lane queued the append: this invocation created no binding and owes no duty. + precommit_target_ns = std::move(previous_target_ns); + precommit_final_ref = std::move(previous_final_ref); + precommit_manifest = previous_manifest; + precommit_state = previous_state; + throw; + } /// The append returned: the precommit binding is durably this build's, so the duty settles from /// `Uncertain` to `Durable` and `ensureBlobPresent`'s materialization gate opens. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h index c6b0aeb75609d..2e026a87048c6 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h @@ -177,18 +177,18 @@ class PartWriteTxn /// `BlobRef` must carry an identical dep record; a conflict -- most /// commonly a conflicting size -- means the fan-out's one-task-per-unique-ref invariant was /// violated) -- BEFORE any result is applied. Application then runs against a COPY of `deps` (a - /// "build"), so a mid-application exception (including one raised by `setMergeHookForTest`'s hook, or + /// "build"), so a mid-application exception (including one raised by `setAdoptionHookForTest`'s hook, or /// a `bad_alloc` from map-node allocation) never touches the live `deps`; the copy is committed by a /// single no-throw `swap` only after every result has applied. The build is therefore either fully /// merged or byte-for-byte untouched -- never partially merged. void mergeBlobUploadResults(std::span results); - /// Test-only fault-injection seam (inert in production): invoked after each result has applied to - /// the in-progress merge copy, with the count of results applied so far (1-based). A hook that - /// throws (e.g. to model a `bad_alloc` mid-merge) aborts `mergeBlobUploadResults` before its final - /// swap, so the live `deps` stays untouched -- the seam exists to prove that all-or-nothing property - /// under injected failure at every application point, not just the first or the last. - void setMergeHookForTest(std::function hook) { merge_hook_for_test = std::move(hook); } + /// Test-only fault-injection seam (inert in production), run before results are adopted into `deps` + /// with the count prepared so far (1-based): in `mergeBlobUploadResults` after each result has applied + /// to the merge copy, and in `putBlob` once after the upload. A hook that throws mid-merge aborts + /// `mergeBlobUploadResults` before its final swap, so the live `deps` stays untouched -- the seam + /// exists to prove that all-or-nothing property at every application point. + void setAdoptionHookForTest(std::function hook) { adoption_hook_for_test = std::move(hook); } /// Test-only: runs in `promote` after its liveness checks and before its append. Set before `promote`. void setPromoteBeforeAppendHookForTest(std::function hook) { promote_before_append_hook_for_test = std::move(hook); } @@ -362,6 +362,9 @@ class PartWriteTxn /// Reject operations after `abandon`, namespace cancellation, or writer-epoch fencing. These checks happen /// before backend work so a stale transaction cannot publish a new owner or stage more debris. void requireAlive() const; + /// Before an upload result enters `deps`: the build is alive, its owner has not stopped, and the mount + /// still admits the generation the build began under. + void requireAdoptable(std::string_view where) const; /// Best-effort exact-token delete of THIS build's staged `_manifests` debris; the precommit body (if /// any) is SKIPPED -- left for GC's delete-after-sealed-decrements. Never throws (the namespace-scoped orphan /// sweep is the durable backstop). Shared by the normal and the namespace-removal-cancelled `abandon` @@ -409,8 +412,8 @@ class PartWriteTxn std::map deps; /// dependencies recorded by this build (blobs only) - /// Backing state for `setMergeHookForTest`; empty (no-op) in production. - std::function merge_hook_for_test; + /// Backing state for `setAdoptionHookForTest`; empty (no-op) in production. + std::function adoption_hook_for_test; /// Backing state for `setPromoteBeforeAppendHookForTest`; empty in production. std::function promote_before_append_hook_for_test; }; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp index 0b6e60b669def..134ebb4773e51 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp @@ -2285,8 +2285,12 @@ ConfirmAnswer Pool::confirmPinnedRef(const CasRefLedger::TablePin & table, const const ConfirmVerdict verdict = confirmUnderSlot( ns, ref_name, [&] { return ref_ledger.confirmPinnedRef(table, ns, ref_name, manifest_ref, deadline_ms); }, slot_read_policy); - if (verdict.answer != ConfirmAnswer::Unknown || verdict.refusal == ConfirmVerdict::Refusal::OneWay - || ref_ledger.pinnedTableRetired(table, ns)) + if (verdict.answer != ConfirmAnswer::Unknown) + return verdict.answer; + /// A stopped background owner gets its own verdict instead of any `Unknown`, so `republishRef` never reads the + /// destination for it. + Cas::throwIfBackgroundStopped(); + if (verdict.refusal == ConfirmVerdict::Refusal::OneWay || ref_ledger.pinnedTableRetired(table, ns)) return verdict.answer; const uint64_t now_ms = bootMsNow(); if (now_ms >= deadline_ms) @@ -2334,7 +2338,9 @@ ConfirmVerdict Pool::confirmUnderSlot(const RootNamespace & ns, const String & r catch (...) { throwIfConfirmTornDown(ns, ref_name); - ProfileEvents::increment(ProfileEvents::CASRelinkConfirmRefusedSlotUnreadable); + /// The owner's verdict is not a slot that could not be read; the counter is diagnostic, so a race here goes uncounted. + if (!Cas::ownerStopRequested()) + ProfileEvents::increment(ProfileEvents::CASRelinkConfirmRefusedSlotUnreadable); throw; } /// A read that finished after teardown began answers for a mount that is going away. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index 0099e2f13e268..46aea490fe22b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -2430,31 +2430,37 @@ namespace { /// The row may still be `Live` here, so the text must not claim `Removing`. -[[noreturn]] void throwRemovalWriteMayLand(const RootNamespace & ns) +String removalWriteMayLandReason(const RootNamespace & ns) { - throwCasWriteRetryLater(fmt::format( - "CAS namespace '{}': a removal write may still land, so positive ref mutation admission is " - "closed until a retried removal completes or the disk is remounted; retry later", ns.string())); + return fmt::format( + "CAS namespace '{}': a removal write may still land, so writes are refused until a retried removal " + "completes or the disk is remounted; retry the `DROP TABLE` or other operation that removed it", ns.string()); } /// True whether the removal is still running, done and waiting for GC to erase the row, or stuck; the /// remedy for a stuck one depends on the operation that started it, so the text names none. -[[noreturn]] void throwRemovingObserved(const RootNamespace & ns) +String removingObservedReason(const RootNamespace & ns) { - throwCasWriteRetryLater(fmt::format( + return fmt::format( "CAS namespace '{}' is Removing in the catalog: writes are refused and reads see no data until its removal " "completes and GC erases the row; retry later, and if it stays Removing see the CAS troubleshooting page", - ns.string())); + ns.string()); +} + +/// Only for a caller that has not queued its mutation yet. +[[noreturn]] void throwAdmissionRefused(const String & reason) +{ + throw RefAdmissionRefusedException(makeCasWriteRetryLaterException(reason)); } /// Flags read under `ref_queue_mutex`. [[noreturn]] void throwPositiveAdmissionClosed(const RootNamespace & ns, bool removing_observed, bool write_may_land) { if (write_may_land) - throwRemovalWriteMayLand(ns); + throwAdmissionRefused(removalWriteMayLandReason(ns)); if (removing_observed) - throwRemovingObserved(ns); - throwCasWriteRetryLater(fmt::format( + throwAdmissionRefused(removingObservedReason(ns)); + throwAdmissionRefused(fmt::format( "CAS namespace '{}' is Removing: positive ref mutation admission is closed while its " "terminal fold and catalog removal complete; retry later", ns.string())); } @@ -5666,10 +5672,10 @@ NamespaceLifeId CasRefLedger::namespaceLife(const RootNamespace & ns) write_may_land = rt->removal_write_may_land; } if (write_may_land) - throwRemovalWriteMayLand(ns); + throwAdmissionRefused(removalWriteMayLandReason(ns)); if (removing_observed) - throwRemovingObserved(ns); - throwCasWriteRetryLater(fmt::format( + throwAdmissionRefused(removingObservedReason(ns)); + throwAdmissionRefused(fmt::format( "CAS namespace '{}' is Removing: creation waits for its terminal fold and catalog " "removal to complete; retry later", ns.string())); } @@ -5741,7 +5747,7 @@ NamespaceLifeId CasRefLedger::namespaceLife(const RootNamespace & ns) const auto entry_it = std::find_if(catalog.catalog.entries.begin(), catalog.catalog.entries.end(), [&](const CatalogEntry & entry) { return entry.ns == ns; }); if (entry_it != catalog.catalog.entries.end() && entry_it->state == NsState::Removing) - throwRemovingObserved(ns); + throwAdmissionRefused(removingObservedReason(ns)); const NamespaceLifeId life = entry_it != catalog.catalog.entries.end() && entry_it->state == NsState::Live diff --git a/src/Disks/tests/gtest_cas_forget.cpp b/src/Disks/tests/gtest_cas_forget.cpp index 1e04789d2a259..2a181586d0fad 100644 --- a/src/Disks/tests/gtest_cas_forget.cpp +++ b/src/Disks/tests/gtest_cas_forget.cpp @@ -7,8 +7,11 @@ #include #include #include +#include #include #include +#include +#include #include #include @@ -19,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -359,6 +363,42 @@ TEST(CASForget, ForgetCleanFarewellGatedOnDrain) } } +/// FORGET run by a killed query on a healthy store still drains and writes its clean farewell: every request it +/// sends succeeds, so the kill stops none of them. +TEST(CASForget, KilledQuerysForgetLandsTheFarewell) +{ + using DB::Cas::decodeMountLease; + constexpr uint64_t kTerminated = std::numeric_limits::max(); + auto backend = std::make_shared(); + auto store = DB::Cas::tests::openPoolForTest(backend); + const String mount_key = store->layout().mountKey(kSrid); + + String failure; + std::thread killed([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + try + { + store->forgetDisk([] {}, kForgetReason); + } + catch (...) + { + failure = getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + }); + killed.join(); + + EXPECT_TRUE(failure.empty()) << failure; + EXPECT_EQ(store->lifecycle(), PoolLifecycle::VanishedForgotten); + DB::Cas::tests::OperationForTest op(*backend); + const auto got = (*op).read(mount_key, DB::Cas::Retry::once()); + ASSERT_TRUE(got.has_value()); + EXPECT_EQ(decodeMountLease(got->bytes).min_active_build_sequence, kTerminated) << "the clean farewell did not land"; +} + /// (b1) BOUNDED COMPLETION: FORGET racing an ACTIVE persistent remount worker joins it without deadlock. Here the /// faulting backend keeps every attempt at `StayTransient` (it never reaches `armMountFence`), so this /// isolates the join/no-deadlock property; the fence re-arm path is covered by (b2) below. Uses a diff --git a/src/Disks/tests/gtest_cas_part_folder_access.cpp b/src/Disks/tests/gtest_cas_part_folder_access.cpp index 9fe2eed96eb75..13f2240105f53 100644 --- a/src/Disks/tests/gtest_cas_part_folder_access.cpp +++ b/src/Disks/tests/gtest_cas_part_folder_access.cpp @@ -1,10 +1,15 @@ #include +#include #include #include #include +#include #include +#include #include #include +#include +#include #include #include #include @@ -13,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +37,8 @@ namespace DB::ErrorCodes extern const int MEMORY_LIMIT_EXCEEDED; extern const int NETWORK_ERROR; extern const int NO_REPLICA_HAS_PART; + extern const int QUERY_WAS_CANCELLED; + extern const int TIMEOUT_EXCEEDED; } namespace ProfileEvents @@ -39,6 +47,7 @@ extern const Event CASRefRollbackBestEffortDropFailed; extern const Event CASOwnershipConflict; extern const Event CASRefMove; extern const Event CASRelinkConfirmRefusedStateLockBusy; +extern const Event CASRelinkConfirmRefusedSlotUnreadable; } using namespace DB; @@ -1345,6 +1354,32 @@ TEST(CASPartFolderAccess, PrepareThenAbortAppendsThePrecommitRemoval) } } +/// A killed query's abort on a healthy store does its whole cleanup on its own thread: when the call returns, the +/// precommit binding is gone, the build floor has advanced and no cleanup duty is left for another caller. +TEST(CASPartFolderAccess, KilledQueryAbandonOnSameThreadRemovesPrecommit) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Cas::RootNamespace ns{"srv/t1"}; + Cas::CachedPartFolderAccess access(store, cacheOn()); + + std::thread killed([&] + { + ThreadStatus thread_status; + Cas::tests::CasKillableQuery query(getContext().context); + auto prepared = access.prepareEntries({ns, "part_1"}, {inlineEntry("f", "one")}, Cas::ProvenanceOp::Insert); + ASSERT_TRUE(store->livePrecommitsForTest(ns).contains({"part_1", prepared.manifestId().ref})); + const uint64_t floor_before = store->minActive(); + query.kill(); + + EXPECT_NO_THROW(prepared.abort()); + EXPECT_FALSE(store->writerCleanupDutiesPendingForTest()) << "the abort left its removal to a later caller"; + EXPECT_GT(store->minActive(), floor_before) << "the aborted build still holds the floor"; + EXPECT_TRUE(store->livePrecommitsForTest(ns).empty()) << "the precommit binding stayed live"; + }); + killed.join(); +} + /// A forgotten terminal must be impossible, not merely discouraged: `~PartWriteTxn` only retires the /// build sequence, so the handle's own destructor is the last-resort owner of the precommit removal. TEST(CASPartFolderAccess, DestroyingAnUnfinishedPreparedPartWriteAborts) @@ -1775,7 +1810,7 @@ namespace { /// A pool whose manifest decode cache is off, so every view build reaches the manifest GET. -Cas::PoolPtr openPoolWithoutDecodeCache(const std::shared_ptr & backend) +Cas::PoolPtr openPoolWithoutDecodeCache(Cas::BackendPtr backend) { return Cas::Pool::open(backend, Cas::PoolConfig{.pool_prefix = "p", .server_root_id = "test", .manifest_decode_cache_bytes = 0}); @@ -1906,11 +1941,32 @@ struct LeaderAndFollower bool follower_joined = false; }; +/// Readers that run inside a registered query. An empty function leaves that reader outside any query. +struct ReaderQueries +{ + /// Runs while the leader is parked, with the leader's query. + std::function leader_parked; + /// Runs on the follower's thread, with the follower's query, before it reads. + std::function follower_before_read; +}; + +/// Runs `read` on the current raw thread, inside a registered query when `in_query` is set. +ReaderOutcome readInQuery(bool in_query, const std::function & with_query, + const std::function & read) +{ + if (!in_query) + return read(); + ThreadStatus thread_status; + Cas::tests::CasKillableQuery query(getContext().context); + with_query(query); + return read(); +} + /// One reader leads the cold build of `key` and is held in its manifest GET; `while_parked` runs, then a /// second reader starts and the GET is released once that reader has joined the build or returned. LeaderAndFollower leaderAndFollower( ParkFirstReadBackend & backend, Cas::CachedPartFolderAccess & access, const Cas::PartRefKey & key, - const std::function & while_parked = {}) + const std::function & while_parked = {}, const ReaderQueries & queries = {}) { std::promise release; backend.release = release.get_future().share(); @@ -1946,15 +2002,24 @@ LeaderAndFollower leaderAndFollower( }; SCOPE_EXIT({ finish(); }); - leader_thread.emplace([&] { run.leader = readColdView(access, key); }); + /// Published by the leader's thread before its read parks; used only while it is parked. + Cas::tests::CasKillableQuery * leader_query = nullptr; + leader_thread.emplace([&] + { + run.leader = readInQuery(bool(queries.leader_parked), [&](Cas::tests::CasKillableQuery & query) { leader_query = &query; }, + [&] { return readColdView(access, key); }); + }); run.leader_parked = backend.parked.get_future().wait_for(kRendezvousTimeout) == std::future_status::ready; if (run.leader_parked) { if (while_parked) while_parked(); + if (queries.leader_parked) + queries.leader_parked(*leader_query); follower_thread.emplace([&] { - run.follower = readColdView(access, key); + run.follower = readInQuery(bool(queries.follower_before_read), queries.follower_before_read, + [&] { return readColdView(access, key); }); arrive(); }); run.follower_arrived = arrived.get_future().wait_for(kRendezvousTimeout) == std::future_status::ready; @@ -2044,6 +2109,154 @@ TEST(CASPartFolderAccess, AFollowersOwnMemoryLimitIsFinal) EXPECT_EQ(backend->getCount(manifest_key), 2u); } +namespace +{ + +struct ColdBuildFixture +{ + std::shared_ptr backend = std::make_shared(); + Cas::PoolPtr store = openPoolWithoutDecodeCache(std::make_shared(backend)); + const Cas::RootNamespace ns{"srv/t1"}; + Cas::CachedPartFolderAccess access{store, cacheOn()}; + const Cas::ManifestId id = publishPart(store, ns, "part_1", {inlineEntry("f", "x")}); + const Cas::PartRefKey key{ns, "part_1"}; + const String manifest_key = Cas::Layout("p").manifestKey(id); + + ColdBuildFixture() + { + backend->resetCounts(); + backend->park_key = manifest_key; + } +}; + +} + +/// A leader whose query stopped hands its followers no verdict of its own: a live follower rebuilds the +/// same manifest, and the leader reports its own stop. +TEST(CASPartFolderAccess, StoppedLeaderLetsLiveFollowerRebuild) +{ + struct Arm + { + const char * name; + std::exception_ptr cause; + int code; + }; + for (const auto & arm : {Arm{"kill", nullptr, ErrorCodes::QUERY_WAS_CANCELLED}, + Arm{"timeout", std::make_exception_ptr(Exception(ErrorCodes::TIMEOUT_EXCEEDED, "the query timed out")), + ErrorCodes::TIMEOUT_EXCEEDED}}) + { + SCOPED_TRACE(arm.name); + ColdBuildFixture fx; + fx.backend->failNextReadWith(fx.manifest_key, std::make_exception_ptr(Poco::TimeoutException("the manifest read timed out"))); + + ReaderQueries queries; + queries.leader_parked = [&](Cas::tests::CasKillableQuery & query) { query.kill(arm.cause); }; + const auto run = leaderAndFollower(*fx.backend, fx.access, fx.key, {}, queries); + ASSERT_TRUE(run.leader_parked && run.follower_arrived && run.follower_joined); + + EXPECT_EQ(run.leader.code, arm.code) << run.leader.message; + EXPECT_EQ(run.leader.view, nullptr); + EXPECT_EQ(run.follower.code, 0) << run.follower.message; + ASSERT_NE(run.follower.view, nullptr); + EXPECT_EQ(run.follower.view->manifestId(), fx.id) << "the follower rebuilt the same manifest"; + EXPECT_EQ(fx.backend->getCount(fx.manifest_key), 2u) << "the leader's failed read and the follower's rebuild"; + } +} + +/// A follower takes a successful shared build even when its own query was killed: a read-only follower +/// has no owner check. +TEST(CASPartFolderAccess, KilledReaderConsumesSuccessfulSharedBuild) +{ + ColdBuildFixture fx; + + ReaderQueries queries; + queries.follower_before_read = [](Cas::tests::CasKillableQuery & query) { query.kill(); }; + const auto run = leaderAndFollower(*fx.backend, fx.access, fx.key, {}, queries); + ASSERT_TRUE(run.leader_parked && run.follower_arrived && run.follower_joined); + + EXPECT_EQ(run.leader.code, 0) << run.leader.message; + EXPECT_EQ(run.follower.code, 0) << run.follower.message; + ASSERT_NE(run.follower.view, nullptr); + EXPECT_EQ(run.follower.view, run.leader.view) << "the follower consumed the leader's build"; + EXPECT_EQ(fx.backend->getCount(fx.manifest_key), 1u); +} + +/// A live leader's transport timeout is the leader's to reissue; its follower does not take the build over. +TEST(CASPartFolderAccess, LiveLeadersTransportTimeoutIsNotFollowerTakeover) +{ + ColdBuildFixture fx; + fx.backend->failNextReadWith(fx.manifest_key, std::make_exception_ptr( + Exception(ErrorCodes::TIMEOUT_EXCEEDED, "the manifest read timed out"))); + + const auto run = leaderAndFollower(*fx.backend, fx.access, fx.key); + ASSERT_TRUE(run.leader_parked && run.follower_arrived && run.follower_joined); + + EXPECT_EQ(run.leader.code, 0) << run.leader.message; + ASSERT_NE(run.leader.view, nullptr); + EXPECT_EQ(run.follower.view, run.leader.view) << "the follower consumed the leader's reissued build"; + EXPECT_EQ(fx.backend->getCount(fx.manifest_key), 2u) << "both reads were the leader's"; +} + +namespace +{ + +/// `dropRefIfPresent` on a raw thread whose query was killed with a stored `FILE_DOESNT_EXIST`. +int dropRefIfPresentWithStoredMiss(Cas::CachedPartFolderAccess & access, const Cas::PartRefKey & key) +{ + int code = 0; + std::thread dropper([&] + { + ThreadStatus thread_status; + Cas::tests::CasKillableQuery query(getContext().context); + query.kill(std::make_exception_ptr(Exception(ErrorCodes::FILE_DOESNT_EXIST, "the query's stored cause"))); + try + { + access.dropRefIfPresent(key); + } + catch (const Exception & e) + { + code = e.code(); + } + }); + dropper.join(); + return code; +} + +} + +/// A stopped owner's stored `FILE_DOESNT_EXIST` is not "the ref raced away": on an unsuccessful read of a cold +/// table, which the client-like backend answers with the stored cause, `dropRefIfPresent` throws it and the ref +/// stays live. +TEST(CASPartFolderAccess, StoppedOwnersStoredMissOnAColdTableKeepsTheRefLive) +{ + const Cas::RootNamespace ns{"srv/t1"}; + const Cas::PartRefKey key{ns, "part_1"}; + auto backend = std::make_shared(); + auto client_like = std::make_shared(backend); + publishPart(openPoolForTest(client_like), ns, "part_1", {inlineEntry("f", "x")}); + auto store = openPoolForTest(client_like); + Cas::CachedPartFolderAccess access(store); + ASSERT_FALSE(store->refTableRecoveredForTest(ns)); + + EXPECT_EQ(dropRefIfPresentWithStoredMiss(access, key), ErrorCodes::FILE_DOESNT_EXIST); + EXPECT_FALSE(store->refTableRecoveredForTest(ns)) << "the verdict came from the cold table's read"; + EXPECT_TRUE(access.existsRef(key, Cas::Freshness::ForceFresh)) << "the ref stays live"; +} + +/// On a warm table every request succeeds, so a killed query's drop is sent and lands. +TEST(CASPartFolderAccess, KilledQuerysDropOnAWarmTableLands) +{ + const Cas::RootNamespace ns{"srv/t1"}; + const Cas::PartRefKey key{ns, "part_1"}; + auto backend = std::make_shared(); + auto store = openPoolForTest(std::make_shared(backend)); + Cas::CachedPartFolderAccess access(store); + publishPart(store, ns, "part_1", {inlineEntry("f", "x")}); + + EXPECT_EQ(dropRefIfPresentWithStoredMiss(access, key), 0) << "a healthy drop of a killed query is sent"; + EXPECT_FALSE(access.existsRef(key, Cas::Freshness::ForceFresh)) << "the drop landed"; +} + /// A reader that resolved a newer manifest of the same ref must not receive the build of the older one. TEST(CASPartFolderAccess, ReadersOfDifferentManifestsOfOneRefDoNotShareABuild) { @@ -2136,6 +2349,93 @@ TEST(CASPartFolderAccess, ALateFollowerTakesTheViewAnotherFollowerRebuilt) EXPECT_EQ(second.view, first.view); } +/// Followers of one failed cold build each rethrow their own copy of the leader's failure, of the same type, code and +/// message: callers annotate what they catch, and two query threads must not append to one message. +TEST(CASPartFolderAccess, FollowersOfAFailedBuildRethrowTheirOwnCopy) +{ + auto backend = std::make_shared(); + auto store = openPoolWithoutDecodeCache(backend); + const Cas::Layout layout("p"); + const Cas::RootNamespace ns{"srv/t1"}; + Cas::CachedPartFolderAccess access(store, cacheOn()); + const auto id = publishPart(store, ns, "part_1", {inlineEntry("f", "x")}); + const Cas::PartRefKey key{ns, "part_1"}; + const String manifest_key = layout.manifestKey(id); + backend->park_key = manifest_key; + backend->failNextReadWith(manifest_key, std::make_exception_ptr( + Exception(ErrorCodes::CORRUPTED_DATA, "the leader's read failed"))); + std::promise release; + backend->release = release.get_future().share(); + + std::atomic joins{0}; + std::promise both_joined; + access.setHookForTest(Cas::CachedPartFolderAccess::TestHook::FollowerJoined, [&] + { + if (++joins == 2) + both_joined.set_value(); + }); + SCOPE_EXIT({ access.setHookForTest(Cas::CachedPartFolderAccess::TestHook::FollowerJoined, nullptr); }); + + const auto cold_read = [&](std::exception_ptr & failure) + { + try + { + (void)access.getView(key, Cas::Freshness::CachedForLoad); + } + catch (...) + { + failure = std::current_exception(); + } + }; + std::exception_ptr leader_failure; + std::exception_ptr first_failure; + std::exception_ptr second_failure; + std::thread leader_thread([&] { cold_read(leader_failure); }); + const bool leader_parked = backend->parked.get_future().wait_for(kRendezvousTimeout) == std::future_status::ready; + std::thread first_thread([&] { cold_read(first_failure); }); + std::thread second_thread([&] { cold_read(second_failure); }); + const bool followers_joined = both_joined.get_future().wait_for(kRendezvousTimeout) == std::future_status::ready; + release.set_value(); + leader_thread.join(); + first_thread.join(); + second_thread.join(); + ASSERT_TRUE(leader_parked && followers_joined); + + const auto object_of = [](const std::exception_ptr & failure) -> Exception * + { + if (!failure) + return nullptr; + try + { + std::rethrow_exception(failure); + } + catch (Exception & e) + { + return &e; + } + catch (...) + { + return nullptr; + } + }; + Exception * leader = object_of(leader_failure); + Exception * first = object_of(first_failure); + Exception * second = object_of(second_failure); + ASSERT_TRUE(leader && first && second); + EXPECT_NE(first, second) << "two followers hold one exception object"; + EXPECT_NE(first, leader); + EXPECT_NE(second, leader); + for (const Exception * follower : {first, second}) + { + EXPECT_EQ(follower->code(), ErrorCodes::CORRUPTED_DATA); + EXPECT_EQ(follower->message(), leader->message()); + } + const String second_before = second->message(); + first->addMessage("annotated by the first follower"); + EXPECT_EQ(second->message(), second_before); + EXPECT_EQ(leader->message().find("annotated"), String::npos); +} + TEST(CASPartFolderAccess, DropNamespaceErasesAllViews) { auto backend = std::make_shared(); @@ -2561,3 +2861,388 @@ TEST(CASPartFolderAccess, MoveRetryAfterAmbiguousAppendIsIdempotent) EXPECT_FALSE(access.existsRef({ns, "tmp_a"}, Cas::Freshness::ForceFresh)); EXPECT_EQ(access.resolve({ns, "a"}, Cas::Freshness::ForceFresh)->manifest_id, expected); } + +namespace +{ + +/// A pool whose copy-confirm poll runs on a virtual clock. `moveSlot` makes a pass answer `Unknown`: the mount +/// slot then shows a lease that is not this mount's. `on_snapshot` runs once, after the first ledger snapshot. +/// Every pause runs `on_pause`, then advances the clock. +struct CopyConfirmPollFixture +{ + std::shared_ptr backend = std::make_shared(); + std::shared_ptr> boot_ms = std::make_shared>(1'000'000); + std::shared_ptr store; + Cas::RootNamespace ns{"srv/t1"}; + std::unique_ptr access; + std::optional source; + uint64_t window_ms = 0; + std::atomic pauses{0}; + std::atomic pause_advance_ms{0}; + std::function on_pause; + std::function on_snapshot; + + CopyConfirmPollFixture() + { + Cas::PoolConfig config{.pool_prefix = "p", .server_root_id = "test"}; + config.boot_ms_fn = [clock = boot_ms] { return clock->load(); }; + config.mount_lease_ttl_ms = std::chrono::milliseconds(600'000); + store = Cas::Pool::open(std::make_shared(backend), std::move(config)); + access = std::make_unique(store); + publishPart(store, ns, "src", {inlineEntry("f", "live")}); + source = access->resolveCopySource({ns, "src"}); + window_ms = store->poolConfig().cas_request_budget.request_window_ms; + store->setCasRetrySleepForTest([this](uint64_t ms) + { + ++pauses; + if (on_pause) + on_pause(); + boot_ms->fetch_add(ms + pause_advance_ms); + }); + store->setConfirmAfterLedgerSnapshotHookForTest([this] + { + auto once = std::move(on_snapshot); + on_snapshot = nullptr; + if (once) + once(); + }); + } + + ~CopyConfirmPollFixture() + { + store->setConfirmAfterLedgerSnapshotHookForTest(nullptr); + store->setCasRetrySleepForTest(nullptr); + } + + String slotKey() const { return store->layout().mountKey("test"); } + + void moveSlot() + { + rewriteSlot([](Cas::MountLease & lease) { lease.server_uuid += 1; }); + } + + void rewriteSlot(const std::function & change) + { + Cas::CasRequests requests = DB::Cas::tests::openRequestsForTest(*backend); + Cas::CasOperation op = requests.admit(); + const auto current = op.read(slotKey(), Cas::Retry::standard()); + ASSERT_TRUE(current.has_value()); + Cas::MountLease lease = Cas::decodeMountLease(current->bytes); + change(lease); + ASSERT_TRUE(std::holds_alternative( + op.replace(slotKey(), Cas::encodeMountLease(lease), current->etag, Cas::Retry::standard()))); + } + + void moveSlotOnce() + { + on_snapshot = [this] { moveSlot(); }; + } +}; + +/// Runs `body` on a raw thread inside a registered query and returns the error code it threw (0 for none). +int inQueryThrownCode(const std::function & body) +{ + int code = 0; + std::thread worker([&] + { + ThreadStatus thread_status; + Cas::tests::CasKillableQuery query(getContext().context); + try + { + body(query); + } + catch (const Exception & e) + { + code = e.code(); + } + }); + worker.join(); + return code; +} + +struct StopArm +{ + const char * name; + /// No stop at all: the outcome a stopped query must also get. + bool live = false; + bool background = false; + std::exception_ptr cause; +}; + +std::vector backgroundStopArms() +{ + return {StopArm{.name = "background", .live = false, .background = true, .cause = nullptr}}; +} + +/// The live arm comes first: the stopped query arms compare against its outcome. +std::vector queryStopArms() +{ + return {StopArm{.name = "live", .live = true, .background = false, .cause = nullptr}, + StopArm{.name = "kill", .live = false, .background = false, .cause = nullptr}, + StopArm{.name = "timeout", .live = false, .background = false, + .cause = std::make_exception_ptr(Exception(ErrorCodes::TIMEOUT_EXCEEDED, "the query timed out"))}}; +} + +/// Runs `body` inside a registered query with a background owner; the `stop` it gets stops the arm's owner. +int inQueryStoppedBy(const StopArm & arm, const std::function & stop)> & body) +{ + return inQueryThrownCode([&](Cas::tests::CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = backgroundOwnerStoppedBy(background_stopped); + body([&arm, &query, background_stopped] + { + if (arm.live) + return; + if (arm.background) + *background_stopped = true; + else + query.kill(arm.cause); + }); + }); +} + +/// Stops each arm's owner before the first confirm pause, during it with the deadline reached, or during it with time +/// left for another pass. +void expectStopDuringConfirmPause(const std::vector & arms) +{ + enum class Where { BeforePause, InPauseAtDeadline, InPauseWithTimeLeft }; + for (const Where where : {Where::BeforePause, Where::InPauseAtDeadline, Where::InPauseWithTimeLeft}) + { + std::optional live_answer; + for (const auto & arm : arms) + { + SCOPED_TRACE(String(arm.name) + "/" + std::to_string(static_cast(where))); + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + std::function stop; + if (where == Where::BeforePause) + { + fx.on_snapshot = [&] + { + fx.moveSlot(); + stop(); + }; + fx.pause_advance_ms = fx.window_ms; + } + else + { + fx.moveSlotOnce(); + fx.on_pause = [&] + { + if (auto once = std::exchange(stop, nullptr)) + once(); + }; + fx.pause_advance_ms = where == Where::InPauseAtDeadline ? fx.window_ms : 0; + } + + std::optional answer; + const int code = inQueryStoppedBy(arm, [&](const std::function & stop_owner) + { + stop = stop_owner; + answer = fx.access->confirmCopySource(*fx.source); + }); + + if (arm.background) + { + EXPECT_EQ(code, ErrorCodes::ABORTED) << "the poll answered a stopped background owner"; + EXPECT_EQ(fx.pauses.load(), where == Where::BeforePause ? 0u : 1u); + continue; + } + EXPECT_EQ(code, 0); + ASSERT_TRUE(answer.has_value()); + if (arm.live) + { + EXPECT_NE(*answer, Cas::ConfirmAnswer::Yes) << "positive control: the slot moved"; + live_answer = answer; + continue; + } + EXPECT_EQ(answer, live_answer) << "a stopped query gets the live owner's answer"; + EXPECT_GE(fx.pauses.load(), 1u) << "the poll went on past the stop"; + } + } +} + +} + +/// A stopped background owner never receives `Unknown` from the poll, wherever the stop lands. +TEST(CASPartFolderAccess, BackgroundStopDuringConfirmPauseThrowsNotUnknown) +{ + expectStopDuringConfirmPause(backgroundStopArms()); +} + +/// The confirm poll is no safe point for a query: a killed or timed-out query gets what a live owner gets. +TEST(CASPartFolderAccess, KilledQuerysConfirmPollGetsTheLiveAnswer) +{ + expectStopDuringConfirmPause(queryStopArms()); +} + +namespace +{ + +/// A source pinned to a table a remount replaced: its `Unknown` is one-way. +void expectOneWayUnknownForStoppedOwner(const std::vector & arms) +{ + for (const auto & arm : arms) + { + SCOPED_TRACE(arm.name); + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + fx.rewriteSlot([](Cas::MountLease & lease) + { + lease.gc_fenced = true; + lease.seq += 1; + }); + ASSERT_TRUE(fx.store->tryRemountOnce()); + Cas::ConfirmAnswer answer = Cas::ConfirmAnswer::Yes; + + const int code = inQueryStoppedBy(arm, [&](const std::function & stop) + { + stop(); + answer = fx.access->confirmCopySource(*fx.source); + }); + + EXPECT_EQ(code, arm.background ? ErrorCodes::ABORTED : 0); + if (!arm.background) + EXPECT_EQ(answer, Cas::ConfirmAnswer::Unknown) << "the pinned table is retired"; + EXPECT_EQ(fx.pauses.load(), 0u); + } +} + +} + +/// A one-way `Unknown` is not handed to a stopped background owner. +TEST(CASPartFolderAccess, BackgroundStoppedOwnerIsNotHandedAOneWayUnknown) +{ + expectOneWayUnknownForStoppedOwner(backgroundStopArms()); +} + +/// A live owner and a killed or timed-out query get the one-way `Unknown`. +TEST(CASPartFolderAccess, KilledQueryIsHandedTheOneWayUnknown) +{ + expectOneWayUnknownForStoppedOwner(queryStopArms()); +} + +namespace +{ + +/// A rename whose copy confirm meets a moved slot; each arm's owner stops in the confirm pause. +void expectStoppedRenameOutcome(const std::vector & arms) +{ + std::optional live_code; + std::optional live_source_kept; + for (const auto & arm : arms) + { + SCOPED_TRACE(arm.name); + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + const Cas::RootNamespace to{"srv/t2"}; + fx.access->setHookForTest(Cas::CachedPartFolderAccess::TestHook::BeforeDestinationPublish, [&] + { + publishPart(fx.store, to, "dst", {inlineEntry("f", "live")}); + }); + SCOPE_EXIT({ fx.access->setHookForTest(Cas::CachedPartFolderAccess::TestHook::BeforeDestinationPublish, nullptr); }); + fx.moveSlotOnce(); + fx.pause_advance_ms = fx.window_ms; + std::function stop; + size_t journal_at_stop = 0; + fx.on_pause = [&] + { + journal_at_stop = fx.backend->journal().size(); + if (auto once = std::exchange(stop, nullptr)) + once(); + }; + + const int code = inQueryStoppedBy(arm, [&](const std::function & stop_owner) + { + stop = stop_owner; + fx.access->republishRef({fx.ns, "src"}, {to, "dst"}); + }); + const auto journal = fx.backend->journal(); + size_t destination_reads_after_stop = 0; + for (size_t i = journal_at_stop; i < journal.size(); ++i) + for (const String & key : journal[i].keys) + destination_reads_after_stop += journal[i].verb == JournalVerb::Read && key.contains("/manifests/" + to.string() + "/"); + const bool source_kept = fx.access->existsRef({fx.ns, "src"}, Cas::Freshness::ForceFresh); + + if (arm.background) + { + EXPECT_EQ(code, ErrorCodes::ABORTED) << "the rename was settled for a stopped background owner"; + EXPECT_EQ(destination_reads_after_stop, 0u) << "the destination was read again after the stop"; + EXPECT_TRUE(source_kept) << "the source was dropped"; + continue; + } + if (arm.live) + { + EXPECT_GT(destination_reads_after_stop, 0u) << "positive control: the live owner reads the destination again"; + EXPECT_EQ(code, 0) << "positive control: the live owner takes the equal committed destination"; + EXPECT_FALSE(source_kept) << "positive control: the live owner's rename drops the source"; + live_code = code; + live_source_kept = source_kept; + continue; + } + ASSERT_TRUE(live_code.has_value()) << "the live arm runs first"; + EXPECT_EQ(code, *live_code) << "a stopped query's rename ends as a live owner's"; + EXPECT_EQ(source_kept, *live_source_kept); + EXPECT_GT(destination_reads_after_stop, 0u); + } +} + +} + +/// A stopped background owner leaves the destination unread and the source in place: an `Unknown` answer would +/// send `republishRef` to read the destination again and take an equal committed one as the result. +TEST(CASPartFolderAccess, BackgroundStoppedRenameDoesNotReadDestinationAgainOrDropSource) +{ + expectStoppedRenameOutcome(backgroundStopArms()); +} + +/// A killed or timed-out query's rename reads the destination again and ends as a live owner's does. +TEST(CASPartFolderAccess, KilledQuerysRenameEndsAsALiveOwnersDoes) +{ + expectStoppedRenameOutcome(queryStopArms()); +} + +/// A stopped owner's first pass still sends its slot read: only a pass after the first is refused. +TEST(CASPartFolderAccess, StoppedOwnersFirstConfirmPassStillReadsTheSlot) +{ + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + const uint64_t reads_before = fx.backend->getCount(fx.slotKey()); + Cas::ConfirmAnswer answer = Cas::ConfirmAnswer::Unknown; + + const int code = inQueryThrownCode([&](Cas::tests::CasKillableQuery & query) + { + query.kill(); + answer = fx.access->confirmCopySource(*fx.source); + }); + + EXPECT_EQ(code, 0); + EXPECT_EQ(answer, Cas::ConfirmAnswer::Yes); + EXPECT_EQ(fx.backend->getCount(fx.slotKey()) - reads_before, 1u) << "the first pass did not read the slot"; +} + +/// A slot read that fails with the owner's verdict is not an unreadable slot: it is not counted as a refusal. +TEST(CASPartFolderAccess, StoppedOwnersFailedSlotReadIsNotCountedAsUnreadable) +{ + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + Cas::tests::CasKillableQuery * running = nullptr; + fx.on_snapshot = [&] + { + Cas::CasRequests requests = DB::Cas::tests::openRequestsForTest(*fx.backend); + Cas::CasOperation op = requests.admit(); + ASSERT_EQ(op.removeCurrent(fx.slotKey(), Cas::Retry::standard()), Cas::Removal::Removed); + running->kill(); + }; + const uint64_t before = ProfileEvents::global_counters[ProfileEvents::CASRelinkConfirmRefusedSlotUnreadable]; + + const int code = inQueryThrownCode([&](Cas::tests::CasKillableQuery & query) + { + running = &query; + fx.access->confirmCopySource(*fx.source); + }); + + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRelinkConfirmRefusedSlotUnreadable] - before, 0u); +} diff --git a/src/Disks/tests/gtest_cas_part_write.cpp b/src/Disks/tests/gtest_cas_part_write.cpp index 9c36c9cacf3fb..03a010b2b0111 100644 --- a/src/Disks/tests/gtest_cas_part_write.cpp +++ b/src/Disks/tests/gtest_cas_part_write.cpp @@ -1,11 +1,15 @@ #include #include +#include #include #include #include +#include #include +#include #include #include +#include #include #include #include @@ -16,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -25,6 +30,8 @@ #include #include #include +#include +#include #include #include #include "config.h" @@ -46,6 +53,8 @@ extern const int ABORTED; extern const int CORRUPTED_DATA; extern const int LIMIT_EXCEEDED; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; +extern const int TIMEOUT_EXCEEDED; extern const int UNKNOWN_EXCEPTION; } @@ -3081,6 +3090,9 @@ TEST(CASPartWriteTxn, StageManifestGiveUpTextCoversEveryOutcome) {{.why = Why::Unresolved, .deadline_source = Source::Policy, .sent_any = true, .last_seen = NotObserved{}, .attempts_sent = 5}, "5 attempt(s) sent and the resolving read did not complete (nothing observed)", true}, + {{.why = Why::Unresolved, .deadline_source = Source::Policy, .sent_any = true, .last_seen = ProvenAbsent{}, + .attempts_sent = 1}, + "1 attempt(s) sent and not sent again after the resolving read found absent", true}, {{.why = Why::Unresolved, .deadline_source = Source::Policy, .sent_any = false, .last_seen = ProvenAbsent{}}, "was not sent: a read of the current object did not complete (absent)", false}, }; @@ -3131,3 +3143,348 @@ TEST(CASPartWriteTxn, StageManifestSentThenGaveUpSaysUncertain) EXPECT_NE(text.find("UNCERTAIN"), String::npos) << text; EXPECT_NE(text.find(fmt::format("{} attempt(s) sent", b->put_attempts)), String::npos) << text; } + +namespace +{ + +/// Runs `body` on a fresh thread with a `ThreadStatus` and a killable query attached, and returns the +/// code `body` threw, or 0. +int codeOnQueryThread(const std::function & body) +{ + int code = 0; + std::thread worker([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + try + { + body(query); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + catch (...) + { + code = -1; + } + }); + worker.join(); + return code; +} + +enum class StopBeforeSwap : uint8_t { Query, Background, LeaseLoss }; + +/// Stops the owner after the upload and before its result is recorded, on the fan-out merge and on the serial path. +void expectStopBeforeDependencySwap(std::initializer_list stop_kinds) +{ + using Stop = StopBeforeSwap; + for (const bool fanout : {true, false}) + { + for (const Stop stop_kind : stop_kinds) + { + const char * stop_name = stop_kind == Stop::Query ? "query kill" + : stop_kind == Stop::Background ? "background stop" + : "lease loss"; + SCOPED_TRACE(fmt::format("{} path, {}", fanout ? "fan-out" : "serial", stop_name)); + auto b = std::make_shared(); + auto s = openPool(b); + const String payload = "stop-before-dependency-swap"; + const BlobRef ref = idOf(payload); + auto build = precommittedBuildForPayload(s, RootNamespace{"srv1/stop-before-swap"}, "part", payload); + const auto deps_before = build->depsSnapshotForTest(); + + const int code = codeOnQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + std::atomic background_stopped{false}; + const auto background = DB::Cas::OwnerScope::background([&] + { + if (background_stopped.load()) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + const auto stop = [&] + { + switch (stop_kind) + { + case Stop::Query: + query.kill(); + return; + case Stop::Background: + background_stopped = true; + return; + case Stop::LeaseLoss: + s->tripMountLost(); + DB::Cas::tests::rearmMountFenceAfterAnomalyForTest(s); + return; + } + }; + if (fanout) + { + const BlobUploadResult result + = build->uploadBlobDetached(BlobUploadRequest{ref, BlobSource::fromString(payload), payload.size()}); + build->setAdoptionHookForTest([&](size_t) { stop(); }); + build->mergeBlobUploadResults(std::span(&result, 1)); + } + else + { + build->setAdoptionHookForTest([&](size_t) { stop(); }); + (void)build->putBlob(ref, BlobSource::fromString(payload)); + } + }); + + switch (stop_kind) + { + case Stop::Query: + EXPECT_EQ(code, 0) << "a killed query's adoption proceeds"; + EXPECT_NE(build->depsSnapshotForTest(), deps_before) << "the uploaded body was not adopted"; + EXPECT_NE(build->dependencyProof(ref), std::nullopt); + break; + case Stop::Background: + case Stop::LeaseLoss: + EXPECT_EQ(code, stop_kind == Stop::Background ? DB::ErrorCodes::ABORTED : DB::ErrorCodes::NETWORK_ERROR); + EXPECT_EQ(build->depsSnapshotForTest(), deps_before) << "the dependency was adopted after the stop"; + EXPECT_EQ(build->dependencyProof(ref), std::nullopt); + break; + } + } + } +} + +} + +/// A background stop or a lease loss that lands before the dependency swap leaves the build without the dependency. +TEST(CASPartWrite, BackgroundStopOrLeaseLossBeforeDependencySwapSkipsAdoption) +{ + expectStopBeforeDependencySwap({StopBeforeSwap::Background, StopBeforeSwap::LeaseLoss}); +} + +/// Adoption sends nothing and is no safe point, so a killed query adopts the body it uploaded. +TEST(CASPartWrite, KilledQueryAdoptsTheUploadedBody) +{ + expectStopBeforeDependencySwap({StopBeforeSwap::Query}); +} + +/// The body landed and its reply was lost while the query timed out. The stop ends the upload with the +/// publication's own failure: no further publication, and no observation that would adopt the landed body. A +/// failure that is not a `std::exception` passes the request engine unclassified, so both exception types are +/// covered. +TEST(CASPartWrite, OwnerTimeoutAfterLandedBodyIsNotAdopted) +{ + for (const bool std_exception : {true, false}) + { + SCOPED_TRACE(std_exception ? "std::exception" : "not a std::exception"); + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-owner-timeout"; + auto build = startBuildFor(s, ns, "part_owner_timeout"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload)}); + build->precommitAdd(ns, "part_owner_timeout", id); + + b->fault_count = 1; + b->land_despite_fault = true; + b->fault_is_not_std_exception = !std_exception; + const int code = codeOnQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + b->on_publish = [&] + { + query.kill(std::make_exception_ptr(DB::Exception(DB::ErrorCodes::TIMEOUT_EXCEEDED, "the query's timeout"))); + }; + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + }); + b->on_publish = {}; + + EXPECT_EQ(code, -1) << "the lost reply's own exception, which is not a DB::Exception, not the query's timeout"; + EXPECT_EQ(b->publish_stream_attempts, 1) << "no further publication"; + EXPECT_EQ(b->blob_head_attempts, 1) << "the landed body was observed again"; + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt) << "the landed body was adopted"; + OperationForTest op(*b); + EXPECT_TRUE((*op).head(s->layout().blobKey(idOf(payload)), Retry::once()).has_value()) + << "the landed body stays as debris"; + } +} + +/// A publication that failed while the query was live, then a kill in the pause before the retry: the retry's +/// `HEAD` is not sent, and the upload ends with the failed publication's own error, not the query's. +TEST(CASPartWrite, KillInPublicationRetryPauseKeepsThePublicationFailure) +{ + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-kill-in-retry-pause"; + auto build = startBuildFor(s, ns, "part_kill_in_pause"); + build->precommitAdd(ns, "part_kill_in_pause", build->stageManifest({blobManifestEntry("a.bin", payload)})); + b->fault_count = 1; + + String failure; + std::thread killed([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + s->mountRequests().setSleepFnForTest([&](uint64_t) + { + if (b->publish_stream_attempts > 0) + query.kill(); + }); + try + { + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + } + catch (...) + { + failure = DB::getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + s->mountRequests().setSleepFnForTest([](uint64_t) {}); + }); + killed.join(); + + EXPECT_NE(failure.find("simulated ambiguous publication"), String::npos) << failure; + EXPECT_EQ(b->blob_head_attempts, 1) << "the retry's HEAD was sent after the kill"; + EXPECT_EQ(b->publish_stream_attempts, 1); + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt); +} + +#if USE_AWS_S3 +/// A credential refusal of a publication, then a kill in the pause before the retry: the upload ends as retry-later +/// carrying the refusal, not with the raw refusal, which would read as damage. +TEST(CASPartWrite, KillBeforeAPublicationsCredentialRetryEndsAsRetryLater) +{ + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-kill-before-credential-retry"; + auto build = startBuildFor(s, ns, "part_kill_before_credential_retry"); + build->precommitAdd(ns, "part_kill_before_credential_retry", + build->stageManifest({blobManifestEntry("a.bin", payload)})); + b->fault_count = 1; + b->fault = std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); + + int code = 0; + String failure; + std::thread killed([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + s->mountRequests().setSleepFnForTest([&](uint64_t) + { + if (b->publish_stream_attempts > 0) + query.kill(); + }); + try + { + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + } + catch (const DB::Exception & e) + { + code = e.code(); + failure = e.message(); + } + s->mountRequests().setSleepFnForTest([](uint64_t) {}); + }); + killed.join(); + + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << failure; + EXPECT_NE(failure.find("the store answered AccessDenied"), String::npos) << failure; + EXPECT_NE(failure.find("credential retry"), String::npos) << failure; + EXPECT_EQ(b->publish_stream_attempts, 1); + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt); +} + +/// A credential refusal of a publication whose query was killed during it ends as retry-later carrying the refusal, +/// as a kill in the pause does. A query's stored cause stays the same object, even a credential-class one. +TEST(CASPartWrite, KillDuringAPublicationsCredentialRefusalEndsAsRetryLater) +{ + for (const bool stored_cause : {false, true}) + { + SCOPED_TRACE(stored_cause ? "the query's stored cause" : "the store's refusal"); + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-kill-during-credential-refusal"; + auto build = startBuildFor(s, ns, "part_kill_during_credential_refusal"); + build->precommitAdd(ns, "part_kill_during_credential_refusal", + build->stageManifest({blobManifestEntry("a.bin", payload)})); + b->fault_count = 1; + b->fault = std::make_exception_ptr(DB::S3Exception( + stored_cause ? "the query's stored cause" : "the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, + "AccessDenied")); + + int code = 0; + String failure; + std::exception_ptr caught; + std::thread killed([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + b->on_publish = [&] { query.kill(stored_cause ? b->fault : nullptr); }; + try + { + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + } + catch (const DB::Exception & e) + { + code = e.code(); + failure = e.message(); + caught = std::current_exception(); + } + }); + killed.join(); + + EXPECT_EQ(b->publish_stream_attempts, 1); + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt); + if (stored_cause) + { + EXPECT_EQ(caught, b->fault) << "the stored cause was replaced: " << failure; + continue; + } + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << failure; + EXPECT_NE(failure.find("the store answered AccessDenied"), String::npos) << failure; + EXPECT_NE(failure.find("credential retry"), String::npos) << failure; + } +} +#endif + +/// The serial upload of a killed query sends its `HEAD`. When it finds no reusable body, the upload ends with the +/// query's error before the publication starts; a reusable body is adopted, since adoption starts no new work. +TEST(CASPartWrite, KilledQuerysUploadStartsNoPublication) +{ + for (const bool body_present : {false, true}) + { + SCOPED_TRACE(body_present ? "a reusable body is present" : "no body"); + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-killed-before-publication"; + if (body_present) + { + auto earlier = startBuildFor(s, ns, "part_earlier"); + earlier->precommitAdd(ns, "part_earlier", earlier->stageManifest({blobManifestEntry("a.bin", payload)})); + (void)earlier->putBlob(idOf(payload), BlobSource::fromString(payload)); + } + auto build = startBuildFor(s, ns, "part_killed"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload)}); + build->precommitAdd(ns, "part_killed", id); + const int publications_before = b->publish_stream_attempts; + const int heads_before = b->blob_head_attempts; + + const int code = codeOnQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + query.kill(); + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + }); + + EXPECT_EQ(b->blob_head_attempts - heads_before, 1) << "the HEAD is a first attempt, sent for a killed query"; + EXPECT_EQ(b->publish_stream_attempts, publications_before) << "a publication started after the kill"; + if (body_present) + { + EXPECT_EQ(code, 0); + EXPECT_NE(build->dependencyProof(idOf(payload)), std::nullopt) << "the reusable body was not adopted"; + } + else + { + EXPECT_EQ(code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt); + } + } +} diff --git a/src/Disks/tests/gtest_cas_upload_detached.cpp b/src/Disks/tests/gtest_cas_upload_detached.cpp index 83d67b17f282f..976b67b7b9c02 100644 --- a/src/Disks/tests/gtest_cas_upload_detached.cpp +++ b/src/Disks/tests/gtest_cas_upload_detached.cpp @@ -444,7 +444,7 @@ TEST(CASUploadDetached, MergeFailureLeavesBuildUntouched) const auto pre_merge_snapshot = build->depsSnapshotForTest(); ASSERT_EQ(pre_merge_snapshot.size(), 1u); /// only the pre-existing dep; the detached uploads folded nothing - build->setMergeHookForTest([](size_t applied_so_far) + build->setAdoptionHookForTest([](size_t applied_so_far) { if (applied_so_far == 1) throw std::bad_alloc(); diff --git a/src/Disks/tests/gtest_cas_upload_fanout.cpp b/src/Disks/tests/gtest_cas_upload_fanout.cpp index cdc8e1393d872..958364b4639b8 100644 --- a/src/Disks/tests/gtest_cas_upload_fanout.cpp +++ b/src/Disks/tests/gtest_cas_upload_fanout.cpp @@ -12,10 +12,14 @@ #include #include #include +#include #include #include #include +#include #include +#include +#include #include #include @@ -46,9 +50,17 @@ using DB::Cas::tests::OperationForTest; namespace DB::ErrorCodes { +extern const int CANNOT_SCHEDULE_TASK; extern const int LOGICAL_ERROR; extern const int INCORRECT_DATA; +extern const int NETWORK_ERROR; extern const int NOT_IMPLEMENTED; +extern const int QUERY_WAS_CANCELLED; +} + +namespace DB::FailPoints +{ +extern const char thread_group_switcher_post_attach_failure[]; } namespace CurrentMetrics @@ -1010,6 +1022,164 @@ TEST(CASUploadFanout, TrackingSeamThrowStillDrains) EXPECT_EQ(build->depsSnapshotForTest().size(), 0u) << "merge-nothing on a tracking-seam throw"; } +namespace +{ + +/// Counts blob publications and the blob `HEAD`s per key. +class PublicationCountingBackend final : public InMemoryBackend +{ +public: + std::optional head(const String & key, TransportAccess & access) override + { + { + std::lock_guard lock(mutex); + ++heads[key]; + } + return InMemoryBackend::head(key, access); + } + + void publish(const BlobPublishRequest & request, TransportAccess & access) override + { + ++publications; + InMemoryBackend::publish(request, access); + } + + int headsOf(const String & key) + { + std::lock_guard lock(mutex); + return heads[key]; + } + + std::atomic publications{0}; + +private: + std::mutex mutex; + std::map heads; +}; + +} + +/// A query killed while one upload task is parked still dispatches the sibling and lets it send its `HEAD`: a +/// dispatch and a first attempt are not safe points. No worker starts a publication after the kill, the caller +/// returns only after the parked task finished, and the build records no dependency. +TEST(CASUploadFanout, StoppedWorkerStartsNoPublicationAndParentJoinsSibling) +{ + auto b = std::make_shared(); + auto s = openPool(b); + auto build = precommitBuildFor(s, RootNamespace{"srv1/nsStoppedFanout"}, "part"); + const auto deps_before = stableDeps(*build); + + const String one = "stopped-fanout-one"; + const String two = "stopped-fanout-two"; + /// Dispatch runs in ascending-ref order. + const String parked = (idOf(one) < idOf(two)) ? one : two; + const String later = (parked == one) ? two : one; + + constexpr auto watchdog = std::chrono::seconds(30); + BoundedEvent parked_running; + BoundedEvent killed; + BoundedEvent release_parked; + BoundedEvent parent_returned; + std::mutex dispatched_mutex; + std::vector dispatched; + std::atomic query_ptr{nullptr}; + + BlobUploadFanoutHooksForTest hooks; + hooks.in_task = [&](const BlobRef & ref) + { + { + std::lock_guard lock(dispatched_mutex); + dispatched.push_back(ref); + } + if (ref == idOf(parked)) + { + parked_running.fire(); + EXPECT_TRUE(release_parked.wait(watchdog)); + } + }; + hooks.after_enqueue = [&](const BlobRef & ref) + { + if (ref != idOf(parked)) + return; + /// Running, so the unwind cannot cancel it before it starts. + EXPECT_TRUE(parked_running.wait(watchdog)); + query_ptr.load()->kill(); + killed.fire(); + }; + + int code = 0; + int parked_heads_at_return = -1; + std::thread parent([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + query_ptr = &query; + std::vector reqs{localRequest(one), localRequest(two)}; + auto pool = makePool(2); + try + { + fanOutBlobUploads(*build, reqs, *pool, &hooks); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + parked_heads_at_return = b->headsOf(s->layout().blobKey(idOf(parked))); + parent_returned.fire(); + }); + + EXPECT_TRUE(killed.wait(watchdog)); + EXPECT_FALSE(parent_returned.wait(std::chrono::milliseconds(300))) + << "the caller returned while a dispatched upload task was still parked"; + release_parked.fire(); + EXPECT_TRUE(parent_returned.wait(watchdog)); + parent.join(); + + EXPECT_EQ(code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(parked_heads_at_return, 1) << "the parked task's upload ran before the caller returned"; + EXPECT_EQ(dispatched.size(), 2u) << "the sibling was not dispatched after the kill"; + EXPECT_EQ(b->headsOf(s->layout().blobKey(idOf(later))), 1) << "the sibling did not send its HEAD"; + EXPECT_EQ(b->publications.load(), 0) << "a worker started a publication after the kill"; + EXPECT_EQ(stableDeps(*build), deps_before) << "the build recorded a dependency of the stopped fan-out"; +} + +/// An upload worker that fails to join the inserting query's thread group sends nothing: outside the query a missing +/// `HEAD` would not see the query's stop and the worker would publish. The fan-out fails and records no dependency. +TEST(CASUploadFanout, WorkerOutsideTheQuerySendsNothing) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + auto b = std::make_shared(); + auto s = openPool(b); + auto build = precommitBuildFor(s, RootNamespace{"srv1/nsDetachedWorker"}, "part"); + const auto deps_before = stableDeps(*build); + const String one = "detached-worker-one"; + + int code = 0; + String failure; + DB::Cas::tests::onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery &) + { + /// Armed after the query's own attach, so the worker's switch is the one that fails; it fails one switch only. + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + std::vector reqs{localRequest(one)}; + auto pool = makePool(2); + try + { + fanOutBlobUploads(*build, reqs, *pool); + } + catch (const DB::Exception & e) + { + code = e.code(); + failure = e.message(); + } + }); + + EXPECT_EQ(code, DB::ErrorCodes::CANNOT_SCHEDULE_TASK) << failure; + EXPECT_EQ(b->publications.load(), 0) << "a worker outside the query published a blob"; + EXPECT_EQ(b->headsOf(s->layout().blobKey(idOf(one))), 0) << "a worker outside the query sent a HEAD"; + EXPECT_EQ(stableDeps(*build), deps_before); +} + /// A part's uploads run concurrently and each holds its payload reader until it finishes, so a small /// staged payload must not pin a full default-sized read buffer. TEST(CASUploadFanout, LocalStagedPayloadReaderIsSizedToThePayload) @@ -1043,3 +1213,93 @@ TEST(CASUploadFanout, LocalStagedPayloadReaderIsSizedToThePayload) DB::readStringUntilEOF(large_read, *large_reader); EXPECT_EQ(large_read, large); } + +namespace +{ + +/// Holds every intent `GET` until `expected` of them are in flight, runs `on_all_arrived` once, then answers as the S3 +/// client does: a miss checks the query, which throws the query's stored exception once it is killed. +class IntentReadRendezvousBackend final : public InMemoryBackend +{ +public: + std::optional read(const String & key, TransportAccess & access) override + { + if (intents_prefix.empty() || !key.starts_with(intents_prefix)) + return InMemoryBackend::read(key, access); + { + std::unique_lock lock(mutex); + if (++arrived == expected) + { + on_all_arrived(); + cv.notify_all(); + } + else if (!cv.wait_for(lock, std::chrono::seconds(30), [&] { return arrived >= expected; })) + timed_out = true; + } + auto answer = InMemoryBackend::read(key, access); + if (!answer) + DB::CurrentThread::checkIfNotCancelled(); + return answer; + } + + /// Empty until the pool is open: the pool's own reads are not intent reads. + String intents_prefix; + int expected = 2; + std::function on_all_arrived; + bool timed_out = false; + +private: + std::mutex mutex; + std::condition_variable cv; + int arrived = 0; +}; + +} + +/// Two upload tasks whose intent reads fail with the query's stored exception receive the same object, so neither +/// may annotate it. The stored message must stay as the query set it; with an annotating catch it changes on every +/// run, and TSan or ASan also sees the two unsynchronized writes to one string. +TEST(CASUploadFanout, ConcurrentIntentReadsLeaveTheStoredQueryExceptionUnchanged) +{ + const String stored_text = "the query's stored network failure"; + for (int iteration = 0; iteration < 50; ++iteration) + { + SCOPED_TRACE(iteration); + auto b = std::make_shared(); + auto s = openPool(b); + b->intents_prefix = s->layout().blobIntentsPrefix(); + auto build = precommitBuildFor(s, RootNamespace{"srv1/nsStoredVerdict"}, "part"); + const String one = "stored-verdict-one"; + const String two = "stored-verdict-two"; + seedPresentBody(*b, s->layout(), s->poolMeta(), one); + seedPresentBody(*b, s->layout(), s->poolMeta(), two); + + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "{}", stored_text)); + int code = 0; + DB::Cas::tests::onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + b->on_all_arrived = [&] { query.kill(cause); }; + std::vector reqs{localRequest(one), localRequest(two)}; + auto pool = makePool(2); + try + { + fanOutBlobUploads(*build, reqs, *pool); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_FALSE(b->timed_out) << "the two intent reads never overlapped"; + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR); + try + { + std::rethrow_exception(cause); + } + catch (const DB::Exception & e) + { + ASSERT_EQ(e.message(), stored_text) << "an intent read annotated the query's stored exception"; + } + } +} From 5338a57049d2135c09cde21496addc8457943dbe Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:28:06 +0100 Subject: [PATCH 11/47] Let server shutdown stop an `Atomic` table's CAS namespace removal Only the catalog's drop worker removes an `Atomic` table directory without a query, and it retries after a restart, so shutdown may stop it. The removal lane stays closed after any sent removal write, and its reopen proof is owed. Waits for the lane and for writer cleanup duties use `waitStoppable`. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressedTransaction.cpp | 22 ++ .../ContentAddressed/Pool/CasPool.cpp | 17 +- .../ContentAddressed/Pool/CasPool.h | 8 + .../ContentAddressed/Pool/CasRefLedger.cpp | 59 ++-- .../ContentAddressed/Pool/CasRefLedger.h | 6 + src/Disks/tests/gtest_cas_operation_gate.cpp | 272 +++++++++++++++++- .../gtest_cas_ref_lane_exception_safety.cpp | 116 ++++++++ src/Disks/tests/gtest_cas_writer_duties.cpp | 229 +++++++++++++++ 8 files changed, 700 insertions(+), 29 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 4667e69bba3f0..f5d8324765240 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include #include #include @@ -30,6 +32,7 @@ #include #include #include +#include #include #include @@ -39,6 +42,11 @@ namespace ProfileEvents extern const Event CASBlobUploadFanoutTasks; } +namespace CurrentMetrics +{ + extern const Metric IsServerShuttingDown; +} + namespace fs = std::filesystem; namespace DB @@ -64,6 +72,13 @@ bool hasSuffix(std::string_view s, std::string_view suffix) return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix; } +/// True when the removal is retried after a restart, so server shutdown may stop it: today only the catalog's drop +/// worker removes an `Atomic` table directory without a query. A new such caller must requeue a failed removal. +bool tableRemovalResumesAfterRestart(const std::string & path) +{ + return endsWithTableUuidPair(path) && !CurrentThread::tryGetQueryContext(); +} + } std::unique_ptr openLocalStagedBlobPayload(const std::string & path, uint64_t payload_size) @@ -1320,6 +1335,13 @@ void ContentAddressedTransaction::removeRecursive(const std::string & path, cons /// file go in one dropNamespace. if (auto uuid = Cas::parseTableUuid(path)) { + std::optional shutdown_owner; + if (Cas::tableRemovalResumesAfterRestart(path)) + shutdown_owner.emplace(Cas::OwnerScope::background([] + { + if (CurrentMetrics::get(CurrentMetrics::IsServerShuttingDown)) + throw Exception(ErrorCodes::ABORTED, "CAS table namespace removal stopped by server shutdown"); + })); metadata_storage.partAccess()->dropNamespace(metadata_storage.liveNamespace(*uuid)); return; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp index 134ebb4773e51..e4cb097f195de 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -1872,14 +1873,24 @@ bool Pool::writerCleanupDutiesPending() const [](const auto & item) { return !item.second.pending.empty(); }); } +bool Pool::writerCleanupDrainingForTest(const RootNamespace & ns) const +{ + std::lock_guard lock(writer_cleanup_mutex); + const auto it = writer_cleanup_queues.find(ns); + return it != writer_cleanup_queues.end() && it->second.draining; +} + void Pool::drainWriterCleanupDuties(const RootNamespace & ns) { { std::unique_lock lock(writer_cleanup_mutex); - writer_cleanup_cv.wait(lock, [&] + Cas::waitStoppable(writer_cleanup_cv, lock, [&] { const auto it = writer_cleanup_queues.find(ns); - return it == writer_cleanup_queues.end() || !it->second.draining; + const bool ready = it == writer_cleanup_queues.end() || !it->second.draining; + if (!ready && writer_cleanup_wait_hook_for_test) + writer_cleanup_wait_hook_for_test(); + return ready; }); const auto it = writer_cleanup_queues.find(ns); @@ -1905,6 +1916,8 @@ void Pool::drainWriterCleanupDuties(const RootNamespace & ns) } duty = it->second.pending.front(); } + /// Before each duty, so a stop never falls between a settled duty and its retirement. + Cas::throwIfBackgroundStopped(); ref_ledger.appendRefOps( ns, diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h index 40dea0b2ea08f..3dfe1ec1e4dd4 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h @@ -1035,6 +1035,7 @@ class Pool : public std::enable_shared_from_this std::optional lastEpochSealForTest(const RootNamespace & ns); /// Test seam: this table's append lane state. RefLaneState laneStateForTest(const RootNamespace & ns); + CasRefLedger::RemovalFlagsForTest removalFlagsForTest(const RootNamespace & ns) { return ref_ledger.removalFlagsForTest(ns); } /// Whether this resident table still owes a stale-precommit sweep (armed by recovery; re-armed by a /// failed attempt; cleared permanently only by a verified-clean sweep). @@ -1083,6 +1084,11 @@ class Pool : public std::enable_shared_from_this /// the direct signal that a settlement failure retained its duty for retry, independent of any /// build-floor side effect that could have the same shape for an unrelated reason. bool writerCleanupDutiesPendingForTest() const { return writerCleanupDutiesPending(); } + /// Test seam: whether a caller is draining the writer cleanup duties of `ns`. + bool writerCleanupDrainingForTest(const RootNamespace & ns) const; + /// TEST SEAM: runs under the cleanup-duty mutex each time a caller finds another drainer and waits for it. + /// Must not take that mutex. Set only while no drain runs. + void setWriterCleanupWaitHookForTest(std::function hook) { writer_cleanup_wait_hook_for_test = std::move(hook); } /// Test-only hook: called by `flushRefBatch` /// right before it carves a batch, i.e. AFTER the table is already recovered -- the one otherwise @@ -1385,6 +1391,8 @@ class Pool : public std::enable_shared_from_this /// pool_layout so it is constructed after every dependency it is injected with. CasMountRuntime mount_runtime; + /// TEST SEAM for `setWriterCleanupWaitHookForTest`. + std::function writer_cleanup_wait_hook_for_test = {}; /// TEST SEAM for `setConfirmAfterOwnershipCaptureHookForTest`; set only while no confirm runs. std::function confirm_after_ownership_capture_hook_for_test = {}; /// TEST SEAM for `setConfirmAfterLedgerSnapshotHookForTest`; set only while no confirm runs. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index 46aea490fe22b..8b5d4df0c8cc8 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -2315,6 +2315,15 @@ RefLaneState CasRefLedger::laneStateForTest(const RootNamespace & ns) return rt->lane_state; } +CasRefLedger::RemovalFlagsForTest CasRefLedger::removalFlagsForTest(const RootNamespace & ns) +{ + const auto rt = lookupRefTableRuntime(ns); + if (!rt) + return {}; + std::lock_guard lock(ref_queue_mutex); + return {.attempt_active = rt->removal_attempt_active, .admission_closed = rt->removal_admission_closed}; +} + bool CasRefLedger::needsStalePrecommitSweepForTest(const RootNamespace & ns) { const auto rt = lookupRefTableRuntime(ns); @@ -5975,7 +5984,7 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( return {}; /// as for a name without a row { std::unique_lock queue_lock(ref_queue_mutex); - rt->cv.wait(queue_lock, [&] + Cas::waitStoppable(rt->cv, queue_lock, [&] { return !rt->removal_attempt_active; }); @@ -5996,22 +6005,6 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( return {}; } - /// Close the local positive lane BEFORE publishing `Removing`. Calls already admitted ahead of - /// this point drain first; later positive callers observe the flag in the same queue critical - /// section as enqueue and receive the typed retry-later refusal. The terminal item below is the one - /// deliberate exception. - { - std::unique_lock queue_lock(ref_queue_mutex); - rt->removal_admission_closed = true; - rt->cv.wait(queue_lock, [&] - { - return !rt->leader_active && rt->pending.empty(); - }); - } - - if (removal_attempt_hook_for_test) - removal_attempt_hook_for_test(); - /// Admitted under the runtime this drop closed and drained, not under the current generation: after a /// remount another runtime of this name may be open, and `Removing` must not land under it. const auto runtime_live = [&rt] @@ -6019,7 +6012,6 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( return !rt->catalog_life_invalidated.load(std::memory_order_acquire) && !rt->superseded_by_remount.load(std::memory_order_acquire); }; - CasOperation removal_op = mount_requests.resume(rt->admitted_fence_generation, runtime_live); std::optional observed_live; if (initial_it->state == NsState::Live) observed_live = *initial_it; @@ -6063,8 +6055,25 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( std::optional removal_op; try { - refuseUnlessAdmitted(removal_op, "beginning removal"); - const CasRefCatalog::Snapshot snapshot = CasRefCatalog::read(removal_op, layout, policy); + /// Close the local positive lane BEFORE publishing `Removing`. Calls already admitted ahead of + /// this point drain first; later positive callers observe the flag in the same queue critical + /// section as enqueue and receive the typed retry-later refusal. The terminal item below is the one + /// deliberate exception. + { + std::unique_lock queue_lock(ref_queue_mutex); + rt->removal_admission_closed = true; + Cas::waitStoppable(rt->cv, queue_lock, [&] + { + return !rt->leader_active && rt->pending.empty(); + }); + } + + if (removal_attempt_hook_for_test) + removal_attempt_hook_for_test(); + + removal_op.emplace(mount_requests.resume(rt->admitted_fence_generation, runtime_live)); + refuseUnlessAdmitted(*removal_op, "beginning removal"); + const CasRefCatalog::Snapshot snapshot = CasRefCatalog::read(*removal_op, layout, policy); const auto entry_it = std::find_if(snapshot.catalog.entries.begin(), snapshot.catalog.entries.end(), [&](const CatalogEntry & entry) { return entry.ns == ns; }); if (entry_it == snapshot.catalog.entries.end()) @@ -6086,18 +6095,20 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( { observed_live = *entry_it; uint64_t removal_started_round = 0; - if (const auto got = removal_op.read(layout.gcStateKey(), policy)) + if (const auto got = removal_op->read(layout.gcStateKey(), policy)) removal_started_round = decodeGcState(got->bytes).round; /// The flag turns on at the first sent attempt of the `Live -> Removing` write. Before it nothing /// can land, so a failure may reopen the lane. After it every exception, `FencedOut` and - /// `EntryChanged` may follow an attempt that can still land. - removal_op.observeRequests(RequestObserver{ + /// `EntryChanged` may follow an attempt that can still land: a later refusal does not prove + /// that an earlier send cannot land, because the row has no revision field and, on a store + /// with content-derived ETags, unrelated churn can restore that send's precondition. + removal_op->observeRequests(RequestObserver{ .on_write_attempt = [&removal_write_outcome_unknown](uint32_t) { removal_write_outcome_unknown = true; }, .on_failure = {}, }); switch (CasRefCatalog::beginRemoving( - removal_op, layout, *observed_live, removal_started_round, policy)) + *removal_op, layout, *observed_live, removal_started_round, policy)) { case CasRefCatalog::BeginRemovingOutcome::Transitioned: case CasRefCatalog::BeginRemovingOutcome::AlreadyRemoving: diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h index c7e17c29d09cb..8c4c04cc1e4a4 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h @@ -461,6 +461,12 @@ class CasRefLedger std::optional lastEpochSealForTest(const RootNamespace & ns); /// Returns the append lane state of `ns` without forcing recovery. RefLaneState laneStateForTest(const RootNamespace & ns); + struct RemovalFlagsForTest + { + bool attempt_active = false; + bool admission_closed = false; + }; + RemovalFlagsForTest removalFlagsForTest(const RootNamespace & ns); /// Reports whether recovery or a prior incomplete sweep requires stale-precommit cleanup. bool needsStalePrecommitSweepForTest(const RootNamespace & ns); /// Waits until all background snapshot publications for `ns` have completed. diff --git a/src/Disks/tests/gtest_cas_operation_gate.cpp b/src/Disks/tests/gtest_cas_operation_gate.cpp index 2dbddf6c5f54a..5e9f84a74bc4b 100644 --- a/src/Disks/tests/gtest_cas_operation_gate.cpp +++ b/src/Disks/tests/gtest_cas_operation_gate.cpp @@ -4,17 +4,32 @@ #include #include #include +#include #include +#include #include #include +#include #include +#include +#include +#include +#include + +#include #include +#include #include #include +#include #include +#include +#include #include #include +#include +#include /// Task 8 (rev.7 spec §1): the central six-class operation gate (`checkOpAdmitted`), the `Vanished` truth /// semantics, and the [D5] per-reason typed messages. These tests build a real @@ -28,8 +43,14 @@ /// captured handle -- the SAME object the metadata storage's `cas_store` points at -- rather than calling /// `store()` again after forcing a terminal state. +namespace CurrentMetrics +{ +extern const Metric IsServerShuttingDown; +} + namespace DB::ErrorCodes { +extern const int ABORTED; extern const int INVALID_STATE; extern const int NETWORK_ERROR; extern const int FILE_DOESNT_EXIST; @@ -58,15 +79,15 @@ std::shared_ptr openGateStorage() /// Commit one real part (tmp -> final rename -> commit), leaving `kPartFile` durable and `kPartDir`/ /// `kTableDir` non-empty. Every op below runs against this committed state. -void commitOnePart(ContentAddressedMetadataStorage & storage) +void commitOnePart(ContentAddressedMetadataStorage & storage, const std::string & table_dir = kTableDir) { auto tx = storage.createTransaction(); auto & ca_tx = dynamic_cast(*tx); - auto buf = ca_tx.writeFile(kTableDir + "/tmp_insert_all_1_1_0/data.bin", 65536, WriteMode::Rewrite, {}); + auto buf = ca_tx.writeFile(table_dir + "/tmp_insert_all_1_1_0/data.bin", 65536, WriteMode::Rewrite, {}); const std::string bytes = "content-of-the-part"; buf->write(bytes.data(), bytes.size()); buf->finalize(); - tx->moveDirectory(kTableDir + "/tmp_insert_all_1_1_0", kPartDir); + tx->moveDirectory(table_dir + "/tmp_insert_all_1_1_0", table_dir + "/all_1_1_0"); tx->commit(NoCommitOptions{}); } @@ -435,3 +456,248 @@ TEST(CASOperationGate, RemoveThrowsDuringTransientAndDrainsAfterRecovery) << "the re-queued removal must drain (really remove the part) once the disk recovers to Live"; EXPECT_FALSE(storage->existsFile(kPartFile)); } + +namespace +{ + +constexpr auto SHUTDOWN_WATCHDOG = std::chrono::seconds(30); + +/// The table dir shape of an `Atomic` database, which the catalog's drop worker removes. +const std::string kAtomicTableDir = "store/a80/a80a80a8-0808-4808-8808-080808080808"; +const std::string kAtomicPartDir = kAtomicTableDir + "/all_1_1_0"; + +/// Server shutdown as the drop worker sees it; restored when the test ends, also on a failed assertion. +struct ServerShuttingDown +{ + ServerShuttingDown() = default; + ServerShuttingDown(const ServerShuttingDown &) = delete; + ServerShuttingDown & operator=(const ServerShuttingDown &) = delete; + ~ServerShuttingDown() { CurrentMetrics::set(CurrentMetrics::IsServerShuttingDown, 0); } + static void begin() { CurrentMetrics::set(CurrentMetrics::IsServerShuttingDown, 1); } +}; + +/// The code of removing `table_dir` in one committed transaction on the calling thread, 0 on success. +int removeTableDir(ContentAddressedMetadataStorage & storage, const std::string & table_dir) +{ + return DB::Cas::tests::exceptionCodeOf([&] + { + auto tx = storage.createTransaction(); + tx->removeRecursive(table_dir, /*should_remove_objects=*/nullptr); + tx->commit(NoCommitOptions{}); + }); +} + +/// Local object storage whose next catalog write is lost before it lands, as a timed-out PUT. The first +/// catalog probe after that loss runs `on_settlement_probe`. +class LosingCatalogWriteObjectStorage : public LocalObjectStorage +{ +public: + using LocalObjectStorage::LocalObjectStorage; + + std::unique_ptr writeObject( + const StoredObject & object, WriteMode mode, std::optional attributes, + size_t buf_size, const WriteSettings & write_settings) override + { + if (object.remote_path.ends_with(catalog_key)) + { + ++catalog_writes; + if (lose_next_catalog_write.exchange(false)) + { + lost = true; + throw Poco::TimeoutException("catalog write lost before it landed"); + } + } + return LocalObjectStorage::writeObject(object, mode, attributes, buf_size, write_settings); + } + + bool exists(const StoredObject & object) const override + { + if (lost && object.remote_path.ends_with(catalog_key) && on_settlement_probe) + std::exchange(on_settlement_probe, nullptr)(); + return LocalObjectStorage::exists(object); + } + + String catalog_key; + std::atomic lose_next_catalog_write{false}; + std::atomic lost{false}; + std::atomic catalog_writes{0}; + mutable std::function on_settlement_probe; +}; + +} + +/// A drop worker's table removal waiting for another removal's attempt leaves at server shutdown with 236. +/// The holder, a query, keeps its claim and completes. +TEST(CASOperationGate, ServerShutdownStopsTableRemovalFollowerWithoutTouchingOwner) +{ + auto storage = openGateStorage(); + commitOnePart(*storage, kAtomicTableDir); + auto pool = storage->store(); + const Cas::RootNamespace ns = storage->liveNamespace(*Cas::parseTableUuid(kAtomicTableDir)); + ServerShuttingDown shutdown; + + std::mutex mutex; + std::condition_variable cv; + bool holder_parked = false; + bool follower_returned = false; + bool holder_left = false; + std::atomic holder_entered{false}; + pool->setRemovalAttemptHookForTest([&] + { + if (holder_entered.exchange(true)) + return; + std::unique_lock lock(mutex); + holder_parked = true; + cv.notify_all(); + cv.wait_for(lock, SHUTDOWN_WATCHDOG, [&] { return follower_returned; }); + holder_left = true; + }); + SCOPE_EXIT({ pool->setRemovalAttemptHookForTest({}); }); + + std::future holder = std::async(std::launch::async, [&] + { + std::optional thread_status; + thread_status.emplace(); + Cas::tests::CasKillableQuery query(getContext().context); + return removeTableDir(*storage, kAtomicTableDir); + }); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, SHUTDOWN_WATCHDOG, [&] { return holder_parked; })); + } + + int follower_code = 0; + bool returned_while_holder_parked = false; + Cas::CasRefLedger::RemovalFlagsForTest flags_on_return; + std::thread follower([&] + { + std::optional thread_status; + thread_status.emplace(); + /// The holder passed this hook before it parked, so shutdown begins while only the follower is in it. + pool->setRemovalRuntimeAcquiredHookForTest([] { ServerShuttingDown::begin(); }); + follower_code = removeTableDir(*storage, kAtomicTableDir); + pool->setRemovalRuntimeAcquiredHookForTest(nullptr); + flags_on_return = pool->removalFlagsForTest(ns); + std::lock_guard lock(mutex); + follower_returned = true; + returned_while_holder_parked = !holder_left; + cv.notify_all(); + }); + follower.join(); + ASSERT_EQ(holder.wait_for(SHUTDOWN_WATCHDOG), std::future_status::ready); + + EXPECT_EQ(follower_code, ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_holder_parked) << "the stopped follower waited for the holder's attempt"; + EXPECT_TRUE(flags_on_return.attempt_active) << "the holder's attempt must stay claimed"; + EXPECT_TRUE(flags_on_return.admission_closed) << "the holder's closed lane must stay closed"; + EXPECT_EQ(holder.get(), 0) << "a removal with a query attached is not stopped by server shutdown"; + EXPECT_FALSE(storage->existsDirectory(kAtomicPartDir)); +} + +/// Shutdown begins while the drop worker settles a lost `Live -> Removing` write. The write is not resent, +/// the worker gets the unresolved retry-later exit, and the lane stays closed against the write that may land. +/// A retry without shutdown completes the removal. +TEST(CASOperationGate, ServerShutdownAfterPossibleRemovingWriteRetainsClosure) +{ + static std::atomic counter{0}; + const std::string unique = std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)); + const auto root = (std::filesystem::temp_directory_path() / ("ca_op_gate_lost_write_" + unique)).string(); + std::filesystem::remove_all(root); + std::filesystem::create_directories(root); + auto object_storage = Cas::tests::ownedByDirectory( + std::make_shared(LocalObjectStorageSettings("test", root, /*read_only_=*/false)), root); + const auto scratch = std::filesystem::temp_directory_path() / ("ca_op_gate_lost_write_scratch_" + unique); + auto storage = Cas::tests::ownedByDirectory(std::make_shared( + object_storage, "pool", "srv1", "", nullptr, Cas::tests::makeSettingsForTest("test", scratch)), scratch); + storage->startup(); + commitOnePart(*storage, kAtomicTableDir); + auto pool = storage->store(); + ServerShuttingDown shutdown; + + object_storage->catalog_key = pool->layout().refCatalogKey(); + object_storage->on_settlement_probe = [] { ServerShuttingDown::begin(); }; + object_storage->lose_next_catalog_write = true; + const int catalog_writes_before = object_storage->catalog_writes; + + std::thread worker([&] + { + std::optional thread_status; + thread_status.emplace(); + EXPECT_EQ(removeTableDir(*storage, kAtomicTableDir), ErrorCodes::NETWORK_ERROR); + }); + worker.join(); + + EXPECT_TRUE(object_storage->lost) << "the Removing write was never sent"; + EXPECT_FALSE(object_storage->on_settlement_probe) << "the lost write was never settled by a read"; + EXPECT_EQ(object_storage->catalog_writes - catalog_writes_before, 1) << "a stopped worker resends nothing"; + const auto flags = pool->removalFlagsForTest(storage->liveNamespace(*Cas::parseTableUuid(kAtomicTableDir))); + EXPECT_FALSE(flags.attempt_active); + EXPECT_TRUE(flags.admission_closed) << "the lane must stay closed against the write that may land"; + + CurrentMetrics::set(CurrentMetrics::IsServerShuttingDown, 0); + EXPECT_EQ(removeTableDir(*storage, kAtomicTableDir), 0) << "the retried removal must complete"; + EXPECT_FALSE(storage->existsDirectory(kAtomicPartDir)); +} + +/// Shutdown that begins after the terminal record does not stop the removal: no owner check runs between +/// that record and the return. Does not hold a publisher in flight. +TEST(CASOperationGate, ShutdownAfterTerminalRecordDoesNotStopRemoval) +{ + auto storage = openGateStorage(); + commitOnePart(*storage, kAtomicTableDir); + auto pool = storage->store(); + ServerShuttingDown shutdown; + + std::atomic removing{false}; + std::atomic shutdown_after_terminal{false}; + pool->setCarveHookForTest([&](Cas::CasRefLedger::CarvePhaseForTest phase) + { + if (phase == Cas::CasRefLedger::CarvePhaseForTest::PostDurableInstall && removing && !shutdown_after_terminal.exchange(true)) + ServerShuttingDown::begin(); + }); + SCOPE_EXIT({ pool->setCarveHookForTest({}); }); + + int code = -1; + std::thread worker([&] + { + std::optional thread_status; + thread_status.emplace(); + removing = true; + code = removeTableDir(*storage, kAtomicTableDir); + }); + worker.join(); + + EXPECT_TRUE(shutdown_after_terminal) << "the terminal record was never appended"; + EXPECT_EQ(code, 0); + EXPECT_FALSE(storage->existsDirectory(kAtomicPartDir)); +} + +/// A non-Atomic table directory, such as a temporary table's, is removed by a caller that never retries it, +/// so server shutdown does not stop its removal. +TEST(CASOperationGate, ShutdownDoesNotStopNonAtomicTableRemoval) +{ + const std::string table_dir = "data/_temporary_and_external_tables/_tmp_0a1b2c3d-0a1b-4c2d-8e3f-0a1b2c3d4e5f"; + auto storage = openGateStorage(); + commitOnePart(*storage, table_dir); + auto pool = storage->store(); + const auto table_id = Cas::parseTableUuid(table_dir); + ASSERT_TRUE(table_id); + ASSERT_FALSE(Cas::endsWithTableUuidPair(table_dir)); + const Cas::RootNamespace ns = storage->liveNamespace(*table_id); + ASSERT_TRUE(pool->namespaceStillLogicallyPresent(ns)); + ServerShuttingDown shutdown; + ServerShuttingDown::begin(); + + int code = -1; + std::thread remover([&] + { + std::optional thread_status; + thread_status.emplace(); + code = removeTableDir(*storage, table_dir); + }); + remover.join(); + + EXPECT_EQ(code, 0); + EXPECT_FALSE(storage->existsDirectory(table_dir + "/all_1_1_0")); + EXPECT_FALSE(pool->namespaceStillLogicallyPresent(ns)); +} diff --git a/src/Disks/tests/gtest_cas_ref_lane_exception_safety.cpp b/src/Disks/tests/gtest_cas_ref_lane_exception_safety.cpp index a88838dd70493..965e45452c1d4 100644 --- a/src/Disks/tests/gtest_cas_ref_lane_exception_safety.cpp +++ b/src/Disks/tests/gtest_cas_ref_lane_exception_safety.cpp @@ -2,11 +2,14 @@ #include #include +#include #include #include #include +#include #include +#include #include #include #include @@ -215,3 +218,116 @@ TEST(CASRefWriterLaneExceptionSafety, PreTenureAllocFailureReleasesBaton) EXPECT_FALSE(store->refLeaderActiveForTest(ns)) << "a pre-tenure allocation failure left the append-lane baton held with no live leader"; } + +/// A removal waits, untimed, until the lane drains. When the last queued writer withdraws at the pre-tenure point, +/// that withdrawal is the drain, so it must wake the removal: no other writer is admitted to do it. +TEST(CASRefWriterLaneExceptionSafety, PreTenureFailureOfTheLastQueuedWriterWakesAWaitingRemoval) +{ + auto backend = std::make_shared(); + auto store = openPoolForRefLane(backend); + const RootNamespace ns{"srv1/reflane_pretenure_removal"}; + /// One ref for every writer: the leader never carves a second item of the same ref into its batch. + const auto append = [&] + { + store->appendRefOps(ns, MutationScope::ref("ref"), + [](const RefTableState &) -> std::vector { return {}; }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + }; + append(); + + std::mutex m; + std::condition_variable cv; + bool leader_parked = false; + bool release_leader = false; + bool park_follower = false; + bool follower_parked = false; + bool release_follower = false; + + std::atomic park_leader{1}; + store->setRefPreCarveHookForTest([&] + { + if (park_leader.exchange(0) != 1) + return; + std::unique_lock lock(m); + leader_parked = true; + cv.notify_all(); + cv.wait(lock, [&] { return release_leader; }); + }); + std::thread leader(append); + { + std::unique_lock lock(m); + cv.wait(lock, [&] { return leader_parked; }); + } + + /// A background owner is polled outside the queue mutex while the follower waits, which is where it is held. + std::thread follower([&] + { + const auto owner = OwnerScope::background([&] + { + std::unique_lock lock(m); + if (!park_follower) + return; + follower_parked = true; + cv.notify_all(); + cv.wait(lock, [&] { return release_follower; }); + }); + EXPECT_THROW(append(), DB::Exception) << "the follower must see its own pre-tenure failure"; + }); + while (store->refQueuePendingForTest(ns) < 2) + std::this_thread::yield(); + { + std::unique_lock lock(m); + park_follower = true; + cv.wait(lock, [&] { return follower_parked; }); + release_leader = true; + } + cv.notify_all(); + leader.join(); + ASSERT_EQ(store->refQueuePendingForTest(ns), 1u) << "the follower's item must still be queued"; + ASSERT_FALSE(store->refLeaderActiveForTest(ns)); + + std::atomic tenure_fault{1}; + store->setRefPreTenureHookForTest([&] + { + if (tenure_fault.exchange(0) == 1) + throw DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "injected pre-tenure fault"); + }); + auto removal = std::make_shared>(); + std::future removal_done = removal->get_future(); + std::thread remover([store, ns, removal] + { + try + { + (void)store->dropNamespace(ns); + removal->set_value(nullptr); + } + catch (...) + { + removal->set_value(std::current_exception()); + } + }); + /// The removal closes admission and checks the drain in one critical section, so from here it is waiting. + while (!store->removalFlagsForTest(ns).admission_closed) + std::this_thread::yield(); + { + std::lock_guard lock(m); + release_follower = true; + } + cv.notify_all(); + follower.join(); + + const bool woke = removal_done.wait_for(std::chrono::seconds(10)) == std::future_status::ready; + EXPECT_TRUE(woke) << "the removal still waits for a lane that is already drained"; + if (!woke) + { + /// Nothing can wake it now; leave it parked rather than hang the binary. + remover.detach(); + return; + } + remover.join(); + store->setRefPreTenureHookForTest(nullptr); + store->setRefPreCarveHookForTest(nullptr); + const std::exception_ptr error = removal_done.get(); + EXPECT_FALSE(error) << "the removal must complete"; + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} diff --git a/src/Disks/tests/gtest_cas_writer_duties.cpp b/src/Disks/tests/gtest_cas_writer_duties.cpp index 19c42a59922b1..b15f7d41f9026 100644 --- a/src/Disks/tests/gtest_cas_writer_duties.cpp +++ b/src/Disks/tests/gtest_cas_writer_duties.cpp @@ -1,27 +1,41 @@ #include +#include #include #include #include #include #include +#include #include +#include +#include +#include #include #include #include +#include +#include +#include #include #include +#include +#include +#include #include namespace DB::ErrorCodes { +extern const int ABORTED; extern const int NETWORK_ERROR; } using namespace DB::Cas; using DB::Cas::tests::SharedWaitLog; +using DB::Cas::tests::StoppedBy; +using DB::Cas::tests::exceptionCodeOf; namespace { @@ -276,6 +290,18 @@ TEST(CASWriterDuties, WedgeResolvedAsRejectDrainsTheDutyAsNoOp) /// Removing `mutateRefsAfterWriterCleanup` from the `dropRef` delegate leaves the rejected build at /// `minActive` even though the ref removal succeeds. The observable floor proves the direct API /// serviced the inherited cleanup duty before performing its own mutation. +/// A precommit append refused after admission may already be on its way, so it keeps its cleanup duty and the build +/// floor. Only a closed removal lane refuses before the append is queued, and that refusal owes nothing. +TEST(CASWriterDuties, PrecommitRefusedAfterAdmissionKeepsItsDuty) +{ + auto backend = std::make_shared(); + auto store = openFrozenSingleAttemptPool(backend); + const RootNamespace ns{"srv1/writer_duty_refused_after_admission"}; + publishEmptyRef(store, ns, "target"); + leaveRejectedCleanupDuty(store, ns); + EXPECT_TRUE(store->writerCleanupDutiesPendingForTest()); +} + TEST(CASWriterDuties, DropRefServicesPendingDutyBeforeRemovingTheRef) { auto backend = std::make_shared(); @@ -644,3 +670,206 @@ TEST(CASWriterDuties, DutySurvivesSettlementFailureForRetry) EXPECT_EQ(store->minActive(), store->peekNextBuildSeq()) << "the retried drain settles the retained duty and lets the mutation proceed"; } + +namespace +{ + +constexpr auto STOP_WATCHDOG = std::chrono::seconds(30); + +/// Leaves one duty per ref, each owing a real `OwnerTransition` removal: durable precommits destroyed +/// unsettled. Every precommit lands before the first destruction, since a precommit drains pending duties. +std::vector leaveDurableCleanupDuties(const PoolPtr & store, const RootNamespace & ns, const std::vector & ref_names) +{ + std::vector builds; + std::vector seqs; + for (const auto & ref_name : ref_names) + { + ManifestId id; + builds.push_back(stageEmptyManifest(store, ns, ref_name, id)); + seqs.push_back(builds.back()->buildSeq()); + builds.back()->precommitAdd(ns, ref_name, id); + } + for (auto & build : builds) + build.reset(); + return seqs; +} + +/// Runs `call` on a thread with a killable query and a background owner; `arm` gets the stop of `owner` before +/// `call` runs. +int runAsStoppable(StoppedBy owner, const std::function &)> & arm, const std::function & call) +{ + int code = 0; + DB::Cas::tests::onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = DB::Cas::tests::backgroundOwnerStoppedBy(background_stopped); + arm(DB::Cas::tests::stopperOf(owner, query, background_stopped)); + code = exceptionCodeOf(call); + }); + return code; +} + +void updateLater(const PoolPtr & store, const RootNamespace & ns) +{ + store->updateRefPublishedAt(ns, "later", [](RefPublishedAtUpdate & update) { update.published_at_ms = 17; }); +} + +} + +namespace +{ + +/// A caller's owner stops in the cleanup-duty drain: once while it waits behind another drainer, once while it drains +/// itself between two duties. +void runCleanupDrainWithStoppedCaller(StoppedBy owner) +{ + { + SCOPED_TRACE("waiting behind another drainer"); + auto backend = std::make_shared(); + auto store = openFrozenSingleAttemptPool(backend); + const RootNamespace ns{"srv1/writer_duty_stopped_waiter"}; + publishEmptyRef(store, ns, "target"); + publishEmptyRef(store, ns, "later"); + const uint64_t duty_seq = leaveDurableCleanupDuties(store, ns, {"durable"}).front(); + ASSERT_TRUE(store->writerCleanupDutiesPendingForTest()); + + std::mutex mutex; + std::condition_variable cv; + bool drainer_parked = false; + bool release_drainer = false; + bool drainer_left = false; + std::atomic entered{false}; + store->setRefPreCarveHookForTest([&] + { + if (entered.exchange(true)) + return; + std::unique_lock lock(mutex); + drainer_parked = true; + cv.notify_all(); + cv.wait_for(lock, STOP_WATCHDOG, [&] { return release_drainer; }); + drainer_left = true; + }); + SCOPE_EXIT({ store->setRefPreCarveHookForTest(nullptr); }); + /// A killed query keeps waiting, so the parked drainer is released once that caller is seen waiting. + store->setWriterCleanupWaitHookForTest([&] + { + if (owner != StoppedBy::Query) + return; + std::lock_guard lock(mutex); + release_drainer = true; + cv.notify_all(); + }); + SCOPE_EXIT({ store->setWriterCleanupWaitHookForTest(nullptr); }); + std::future drainer + = std::async(std::launch::async, [&] { return exceptionCodeOf([&] { store->dropRef(ns, "target"); }); }); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, STOP_WATCHDOG, [&] { return drainer_parked; })); + } + + bool returned_while_drainer_parked = false; + bool draining_on_return = false; + bool pending_on_return = false; + uint64_t floor_on_return = 0; + const int code = runAsStoppable(owner, [](const std::function & stop) { stop(); }, [&] + { + SCOPE_EXIT({ + draining_on_return = store->writerCleanupDrainingForTest(ns); + pending_on_return = store->writerCleanupDutiesPendingForTest(); + floor_on_return = store->minActive(); + std::lock_guard lock(mutex); + returned_while_drainer_parked = !drainer_left; + release_drainer = true; + cv.notify_all(); + }); + updateLater(store, ns); + }); + ASSERT_EQ(drainer.wait_for(STOP_WATCHDOG), std::future_status::ready); + + if (owner == StoppedBy::Background) + { + EXPECT_EQ(code, DB::ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_drainer_parked) << "the stopped caller waited for the other drainer"; + EXPECT_TRUE(draining_on_return) << "the other drainer's claim must stay"; + EXPECT_TRUE(pending_on_return); + EXPECT_EQ(floor_on_return, duty_seq); + } + else + { + EXPECT_EQ(code, 0) << "a killed query waits for the other drainer and proceeds"; + EXPECT_FALSE(returned_while_drainer_parked) << "the killed query returned before the drainer was released"; + EXPECT_FALSE(draining_on_return); + EXPECT_FALSE(pending_on_return); + } + EXPECT_EQ(drainer.get(), 0); + EXPECT_FALSE(store->writerCleanupDutiesPendingForTest()); + EXPECT_EQ(store->minActive(), store->peekNextBuildSeq()); + EXPECT_NO_THROW(updateLater(store, ns)) << "a later caller is admitted"; + } + + { + SCOPED_TRACE("draining, stopped between duties"); + auto backend = std::make_shared(); + auto store = openFrozenSingleAttemptPool(backend); + const RootNamespace ns{"srv1/writer_duty_stopped_drainer"}; + publishEmptyRef(store, ns, "later"); + const uint64_t next_seq = leaveDurableCleanupDuties(store, ns, {"settled", "next"}).back(); + + std::atomic stopped{false}; + std::atomic tenures_after_stop{0}; + const int code = runAsStoppable(owner, [&](const std::function & stop) + { + /// The first duty's append is installed when the owner stops; it completes as shared work. + store->setCarveHookForTest([&, stop](CasRefLedger::CarvePhaseForTest phase) + { + if (phase == CasRefLedger::CarvePhaseForTest::PostInstallPreAck && !stopped.exchange(true)) + stop(); + }); + store->setRefPreTenureHookForTest([&] + { + if (stopped.load()) + ++tenures_after_stop; + }); + }, [&] { updateLater(store, ns); }); + store->setCarveHookForTest(nullptr); + store->setRefPreTenureHookForTest(nullptr); + + EXPECT_TRUE(stopped.load()); + EXPECT_FALSE(store->writerCleanupDrainingForTest(ns)); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(code, DB::ErrorCodes::ABORTED); + EXPECT_EQ(tenures_after_stop.load(), 0) << "a stopped drainer starts no append for the next duty"; + EXPECT_TRUE(store->writerCleanupDutiesPendingForTest()); + EXPECT_EQ(store->minActive(), next_seq) << "the settled duty is retired, the next one is not"; + const auto live = store->livePrecommitsForTest(ns); + ASSERT_EQ(live.size(), 1u); + EXPECT_EQ(live.begin()->first, "next"); + EXPECT_NO_THROW(updateLater(store, ns)) << "a later caller drains the next duty"; + } + else + { + EXPECT_EQ(code, 0) << "a killed query drains every duty and runs its own mutation"; + EXPECT_GT(tenures_after_stop.load(), 0) << "the next duty's append ran after the kill"; + EXPECT_TRUE(store->livePrecommitsForTest(ns).empty()); + } + EXPECT_FALSE(store->writerCleanupDutiesPendingForTest()); + EXPECT_EQ(store->minActive(), store->peekNextBuildSeq()); + } +} + +} + +/// A caller whose background owner stops leaves the cleanup-duty drain without changing it: waiting behind another +/// drainer, it leaves that drainer's claim, the queued duty and the build floor; draining itself, it stops between +/// duties only after the settled one is retired and popped, and starts no append for the next one. +TEST(CASWriterDuties, BackgroundStoppedCleanupDrainerLeavesDutyAndFloor) +{ + runCleanupDrainWithStoppedCaller(StoppedBy::Background); +} + +/// A killed query is not a background owner: it waits for the other drainer, and drains every duty itself. +TEST(CASWriterDuties, KilledQueryWaitsForTheDrainerAndDrainsEveryDuty) +{ + runCleanupDrainWithStoppedCaller(StoppedBy::Query); +} From 3c2396f0aac7f9b9fe4910370f99f4d077ea3072 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:28:08 +0100 Subject: [PATCH 12/47] Stop CAS GC rounds at the scheduler's or the query's request A round stopped by `SYSTEM CAS GC STOP` or by its query is recorded as `Stopped`. A manual round checks its query at scan heads, and its read-ahead and delete workers run in the round's thread group. Committed orphan nominations are deleted before the janitor runs, and the post-commit phases are one owed scope. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressed/Gc/CasBlobInDegree.cpp | 7 +- .../ContentAddressed/Gc/CasGc.cpp | 387 ++--- .../ContentAddressed/Gc/CasGc.h | 14 +- .../ContentAddressed/Gc/CasGcReadAhead.cpp | 52 +- .../ContentAddressed/Gc/CasGcScheduler.cpp | 43 +- .../ContentAddressed/Gc/CasGcScheduler.h | 10 +- .../Gc/CasNamespaceJanitor.cpp | 53 +- .../Gc/CasOrphanManifestSweep.cpp | 8 +- .../Gc/CasOrphanManifestSweep.h | 3 +- .../Gc/CatalogLifecycleReconciler.cpp | 6 + .../ContentAddressed/Pool/CasPool.h | 2 +- .../ContentAddressed/Pool/CasRefLedger.cpp | 8 + .../ContentAddressed/Pool/CasRefLedger.h | 3 +- src/Disks/tests/gtest_cas_blob_indegree.cpp | 92 ++ .../tests/gtest_cas_gc_frontier_gate.cpp | 1265 +++++++++++++++++ src/Disks/tests/gtest_cas_gc_intents.cpp | 117 ++ src/Disks/tests/gtest_cas_gc_log.cpp | 2 +- src/Disks/tests/gtest_cas_gc_read_ahead.cpp | 152 ++ src/Disks/tests/gtest_cas_gc_rebuild.cpp | 103 ++ .../gtest_cas_gc_redelete_concurrency.cpp | 62 + src/Disks/tests/gtest_cas_gc_stop_start.cpp | 2 + .../tests/gtest_cas_gc_teardown_stop.cpp | 4 +- .../tests/gtest_cas_namespace_janitor.cpp | 242 ++++ .../tests/gtest_cas_own_creating_cleanup.cpp | 46 + .../gtest_cas_sweep_deletion_premise.cpp | 236 +++ 25 files changed, 2713 insertions(+), 206 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasBlobInDegree.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasBlobInDegree.cpp index c97c7dad14322..6367f70a28a3d 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasBlobInDegree.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasBlobInDegree.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -213,7 +214,8 @@ bool AdoptedRunReader::reportingRefusal(Read && read) } catch (const Exception & e) { - if (e.code() != ErrorCodes::CORRUPTED_DATA) + /// A query's stored cause is no finding about the run, whatever its code. + if (e.code() != ErrorCodes::CORRUPTED_DATA || isQueryStoredCause(std::current_exception())) throw; refused = Refusal{.run_key = next_run > 0 ? currentRun().key : String{}, .message = e.message()}; view.reset(); @@ -242,8 +244,9 @@ bool AdoptedRunReader::nextInRunChecked(SourceEdgeRecord & rec) } catch (Exception & e) { + /// The row read refills from the store, so this can be a stopped query's shared exception. if (e.code() == ErrorCodes::CORRUPTED_DATA) - e.addMessage(fmt::format("in CAS source-edge run `{}` of GC shard {}", currentRun().key, shard)); + addMessageUnlessQueryStoredCause(e, fmt::format("in CAS source-edge run `{}` of GC shard {}", currentRun().key, shard)); throw; } if (!got) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp index 39c2b289ad513..7cb416f41cfad 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -19,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -150,6 +152,8 @@ struct WriteOnceJobResult uint64_t leaked = 0; uint64_t requests = 0; String error; + /// The failure of a job whose query had stopped: the caller propagates it rather than publishing the page. + std::exception_ptr stopped_query_failure; }; /// Deletes `chunk` as one request. A storage that refuses the batch gets one request per key, each @@ -165,7 +169,8 @@ void removeChunkWriteOnceCountingKeys(CasOperation & op, const std::vectoropenRequests().resume(admitted_generation, [this] { return authority_held; }); @@ -558,6 +570,8 @@ void Gc::removeWriteOnceOnIoPool(CasOperation & op, const std::vectorleaked = chunk->size() - result->deleted; result->error = getCurrentExceptionMessage(false); + if (queryStopRequested()) + result->stopped_query_failure = std::current_exception(); } })); } @@ -580,6 +594,9 @@ void Gc::removeWriteOnceOnIoPool(CasOperation & op, const std::vector & catch (Exception & e) { /// A refusal carries the store's text only; the round's error must name what it failed to delete. - e.addMessage("while deleting {} blob intents starting at '{}'", chunk.size(), chunk.front().str()); + addMessageUnlessQueryStoredCause(e, fmt::format("while deleting {} blob intents starting at '{}'", chunk.size(), + chunk.front().str())); throw; } } @@ -762,8 +781,10 @@ void Gc::redeleteBlobs( body_delete = entries[scheduled], layout_ptr = &layout, pool_store = store, - admitted_generation] + admitted_generation, + group = CurrentThread::getGroup()] { + throwUnlessInThreadGroup(group, "CAS GC re-delete worker"); CasOperation job_op = pool_store->openRequests().resume(admitted_generation); *slot = performRedeleteIo(body_delete, *layout_ptr, job_op); })); @@ -825,6 +846,7 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al RoundReport local_report; RoundReport & report = progress ? *progress : local_report; report = RoundReport{}; + round_stop_observed = false; GcState state; std::optional state_etag; @@ -880,8 +902,19 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al /// The helping barrier precedes heartbeat work, DEFER, the hot stream LIST, and every successor /// artifact. A deferred invocation therefore cannot leave a row the adopted parent already proved /// complete, and a folding invocation takes its catalog cut only after the deletion settles. + const auto throw_if_round_stopped = [this] + { + if (!stop_signal || !stop_signal()) + return; + round_stop_observed = true; + throw Exception(ErrorCodes::ABORTED, "CAS GC round stopped by its scheduler"); + }; { GcPhaseTimer t(phase_sink, "pre_fold_ref_drain"); + /// The scheduler owns the drain as a background owner: every background check in the drain throws on its stop. + std::optional scheduler_owner; + if (stop_signal) + scheduler_owner.emplace(OwnerScope::background(throw_if_round_stopped)); uint64_t completed_erases = 0; uint64_t cancelled_creating = 0; /// Declared after `t`, so it runs before the timer emits its record, on a throw too. @@ -973,6 +1006,7 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al store->poolConfig().manifest_sweep_list_budget_keys, orphan_manifest_sweep_decision_at_ms); const bool run_orphan_manifest_sweep = orphan_manifest_sweep_decision == OrphanManifestSweepDecision::StartSweep || orphan_manifest_sweep_decision == OrphanManifestSweepDecision::ContinueSweep; + throw_if_round_stopped(); { GcPhaseTimer t(phase_sink, "defer_decision"); const bool row_decision_due = rowDecisionDue(state, new_round); @@ -1466,176 +1500,156 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al /// a crash between the CAS and here leaks the prefix to fsck (single-crash window, no permanent leak — /// but note the cursor already advanced, so a plain retry will NOT re-attempt it; fsck is the backstop). /// - /// Phase `handoff_reclaim`. - { - GcPhaseTimer t(phase_sink, "handoff_reclaim"); - uint64_t objects_reclaimed = 0; - std::set new_referenced_generations; - for (const RunRef & r : folded.fold_seal.blob_target_runs) - new_referenced_generations.insert(r.key_generation); - - std::set handed_off; /// dedupe: multiple parent refs can share one generation - /// GATED like every other destructive site, and it is also the FIRST destructive site of the - /// post-CAS tail -- which is why the gate is read before the tail begins rather than partway - /// down it. - /// - /// UNLIKE EVERY OTHER GATED SITE, SUPPRESSION HERE LOSES THE WORK RATHER THAN POSTPONING IT. - /// The hand-off is a one-shot DIFFERENCE between the parent seal's runs and the new seal's, and - /// a suppressed round still FOLDS -- only the irreversible half stops -- so the ref moves off - /// the old generation on this very round and the next round's parent seal no longer names it. - /// Nothing revisits it: `snap_pruned_through` is already past that generation and the wholesale - /// prune only walks forward. The prefix is left to `fsck`, which is the same outcome this site - /// already documents for a crash in this window (see the `handoff_reclaim` comment above). Bounded -- - /// one small run per shard per occurrence of a suppressed round that also folded a delta -- and - /// not a correctness problem, but it is the one place where the gate costs something permanent, - /// so it is asserted rather than left to be discovered. - static const std::vector kNoRuns; - const std::vector & handoff_candidates = - suppress_destructive ? kNoRuns : parent_seal_runs; - for (const RunRef & old_ref : handoff_candidates) + /// Phase `handoff_reclaim`, then phase `manifest_deletes`, both owed: the round committed, and nothing revisits + /// what it handed off. A stop that skipped the manifest deletes would leave them to the orphan sweep, the only + /// backstop. + { + const auto owed = OwnerScope::owed(); { - /// Only generations the wholesale prune already passed AND that no live ref still pins. - if (old_ref.key_generation > state.snap_pruned_through) - continue; /// not yet pruned-through: the normal prune will reclaim it when it ages out - if (new_referenced_generations.contains(old_ref.key_generation)) - continue; /// still referenced by a (possibly different-shard) live ref: keep it - if (!handed_off.insert(old_ref.key_generation).second) - continue; /// already reclaimed this round via another shard's ref - /// `bounded_remaining` draws from the hand-off's OWN reserve, never `UINT64_MAX` and never - /// `pruneSupersededGenerations`' shared remainder: this hand-off is a ONE-SHOT event (see the - /// `handoff_reclaim` comment above) -- a generation this call reclaims only PARTIALLY is left - /// exactly like a crash in this window already is -- to `fsck`, never revisited by a later - /// round's hand-off (the parent-seal difference that triggers it does not recur once the ref - /// has moved). The prune, by contrast, safely retries an under-served generation next round - /// via its cursor, so sharing one pool would let a prune-heavy round strand this one-shot - /// reclaim at zero every time; the separate reserve makes that impossible. - const uint64_t remaining = round_work_budget.handoffPrefixWholesaleRemaining(); - if (remaining == 0) - break; - const uint64_t reclaimed = deletePrefixWholesale( - op, layout.gcGenPrefix(old_ref.key_generation), remaining); - round_work_budget.handoff_prefix_wholesale_objects_used += reclaimed; - objects_reclaimed += reclaimed; - LOG_TRACE(logger, - "CAS GC hand-off: generation {} moved out of the live seal below the retention cursor " - "({} objects) — post-CAS wholesale reclaim (the prune had skipped it while referenced)", - old_ref.key_generation, reclaimed); + GcPhaseTimer t(phase_sink, "handoff_reclaim"); + uint64_t objects_reclaimed = 0; + std::set new_referenced_generations; + for (const RunRef & r : folded.fold_seal.blob_target_runs) + new_referenced_generations.insert(r.key_generation); + + std::set handed_off; /// dedupe: multiple parent refs can share one generation + /// GATED like every other destructive site, and it is also the FIRST destructive site of the + /// post-CAS tail -- which is why the gate is read before the tail begins rather than partway + /// down it. + /// + /// UNLIKE EVERY OTHER GATED SITE, SUPPRESSION HERE LOSES THE WORK RATHER THAN POSTPONING IT. + /// The hand-off is a one-shot DIFFERENCE between the parent seal's runs and the new seal's, and + /// a suppressed round still FOLDS -- only the irreversible half stops -- so the ref moves off + /// the old generation on this very round and the next round's parent seal no longer names it. + /// Nothing revisits it: `snap_pruned_through` is already past that generation and the wholesale + /// prune only walks forward. The prefix is left to `fsck`, which is the same outcome this site + /// already documents for a crash in this window (see the `handoff_reclaim` comment above). Bounded -- + /// one small run per shard per occurrence of a suppressed round that also folded a delta -- and + /// not a correctness problem, but it is the one place where the gate costs something permanent, + /// so it is asserted rather than left to be discovered. + static const std::vector kNoRuns; + const std::vector & handoff_candidates = + suppress_destructive ? kNoRuns : parent_seal_runs; + for (const RunRef & old_ref : handoff_candidates) + { + /// Only generations the wholesale prune already passed AND that no live ref still pins. + if (old_ref.key_generation > state.snap_pruned_through) + continue; /// not yet pruned-through: the normal prune will reclaim it when it ages out + if (new_referenced_generations.contains(old_ref.key_generation)) + continue; /// still referenced by a (possibly different-shard) live ref: keep it + if (!handed_off.insert(old_ref.key_generation).second) + continue; /// already reclaimed this round via another shard's ref + /// `bounded_remaining` draws from the hand-off's OWN reserve, never `UINT64_MAX` and never + /// `pruneSupersededGenerations`' shared remainder: this hand-off is a ONE-SHOT event (see the + /// `handoff_reclaim` comment above) -- a generation this call reclaims only PARTIALLY is left + /// exactly like a crash in this window already is -- to `fsck`, never revisited by a later + /// round's hand-off (the parent-seal difference that triggers it does not recur once the ref + /// has moved). The prune, by contrast, safely retries an under-served generation next round + /// via its cursor, so sharing one pool would let a prune-heavy round strand this one-shot + /// reclaim at zero every time; the separate reserve makes that impossible. + const uint64_t remaining = round_work_budget.handoffPrefixWholesaleRemaining(); + if (remaining == 0) + break; + const uint64_t reclaimed = deletePrefixWholesale( + op, layout.gcGenPrefix(old_ref.key_generation), remaining); + round_work_budget.handoff_prefix_wholesale_objects_used += reclaimed; + objects_reclaimed += reclaimed; + LOG_TRACE(logger, + "CAS GC hand-off: generation {} moved out of the live seal below the retention cursor " + "({} objects) — post-CAS wholesale reclaim (the prune had skipped it while referenced)", + old_ref.key_generation, reclaimed); + } + t.metric("generations_reclaimed", handed_off.size()); + t.metric("objects_reclaimed", objects_reclaimed); + t.metric("suppressed", suppress_destructive ? 1 : 0); } - t.metric("generations_reclaimed", handed_off.size()); - t.metric("objects_reclaimed", objects_reclaimed); - t.metric("suppressed", suppress_destructive ? 1 : 0); - } - /// Post-CAS: owner-removed manifest bodies — deleted ONLY now, after their decrements were - /// ADOPTED by the round CAS (delete-after-sealed-decrements). NOT durable across rounds: the - /// ref-log intake cursor that discovered each `-1` edge is committed by THIS round's CAS above, - /// so a log already folded is never re-visited and never re-populates `mf_cleanup`. This phase is - /// deliberately unbudgeted: a cap would leave a declined entry unreachable from any live ref AND - /// never re-derived by this pipeline, converting a bounded burst into a permanent leak. It drains - /// the whole of `folded.mf_cleanup` every round it runs; only a crash (or the destructive-suppression - /// gate below) leaves an entry for the orphan-manifest sweep to reclaim later. - /// The bodies go in batch requests of write-once keys; see the block. - /// - /// Phase `manifest_deletes`. - { - GcPhaseTimer t(phase_sink, "manifest_deletes"); - const uint64_t manifests_deleted_before = report.manifests_deleted; - /// GATED. A manifest body is content the ref graph still describes until its decrements are both - /// sealed AND taken on a round that could prove its frontier -- an unprovable round's `-1` may - /// itself be the observation that is missing an owner elsewhere, so deleting the body on it is - /// exactly the irreversible step the gate exists to withhold. - static const std::map kNoManifestCleanup; - const std::map & mf_cleanup_now = - suppress_destructive ? kNoManifestCleanup : folded.mf_cleanup; - - /// Chunks of write-once keys, one request each, with no per-key precondition: a manifest key is - /// never written twice, so the body at it is the one the fold observed or nothing. The engine - /// reissues a failed chunk whole; a chunk that exhausts its policy throws here, and the chunks - /// before it are already recorded below. A key that one of the exhausted chunk's own attempts - /// did delete is not recorded either: deletion and recording are all-or-nothing per request, - /// never per key, so the next round's fold sees that key as already gone. The etag the fold - /// observed rides the event as information only. - const size_t chunk_keys = std::clamp(store->poolConfig().gc_bulk_delete_chunk_keys, 1, kBulkDeleteMaxKeys); - const size_t request_keys = bulkDeleteChunkKeys(); - uint64_t attempted = 0; - uint64_t requests = 0; - std::vector chunk; - std::vector *> chunk_entries; - const auto flush = [&] + /// Post-CAS: owner-removed manifest bodies — deleted ONLY now, after their decrements were + /// ADOPTED by the round CAS (delete-after-sealed-decrements). NOT durable across rounds: the + /// ref-log intake cursor that discovered each `-1` edge is committed by THIS round's CAS above, + /// so a log already folded is never re-visited and never re-populates `mf_cleanup`. This phase is + /// deliberately unbudgeted: a cap would leave a declined entry unreachable from any live ref AND + /// never re-derived by this pipeline, converting a bounded burst into a permanent leak. It drains + /// the whole of `folded.mf_cleanup` every round it runs; only a crash (or the destructive-suppression + /// gate below) leaves an entry for the orphan-manifest sweep to reclaim later. + /// The bodies go in batch requests of write-once keys; see the block. + /// + /// Phase `manifest_deletes`. { - if (chunk.empty()) - return; - /// A backend without `DeleteObjects` (GCS) falls back to one admitted delete per key here; - /// `chunk_entries`' per-key bookkeeping below is unaffected either way -- it counts objects - /// that are gone after this call returns, not how many requests it took to get them there. - requests += removeCohortWriteOnce(op, chunk, request_keys, Retry::standard()); - for (const auto * entry : chunk_entries) + GcPhaseTimer t(phase_sink, "manifest_deletes"); + const uint64_t manifests_deleted_before = report.manifests_deleted; + /// GATED. A manifest body is content the ref graph still describes until its decrements are both + /// sealed AND taken on a round that could prove its frontier -- an unprovable round's `-1` may + /// itself be the observation that is missing an owner elsewhere, so deleting the body on it is + /// exactly the irreversible step the gate exists to withhold. + static const std::map kNoManifestCleanup; + const std::map & mf_cleanup_now = + suppress_destructive ? kNoManifestCleanup : folded.mf_cleanup; + + /// Chunks of write-once keys, one request each, with no per-key precondition: a manifest key is + /// never written twice, so the body at it is the one the fold observed or nothing. The engine + /// reissues a failed chunk whole; a chunk that exhausts its policy throws here, and the chunks + /// before it are already recorded below. A key that one of the exhausted chunk's own attempts + /// did delete is not recorded either: deletion and recording are all-or-nothing per request, + /// never per key, so the next round's fold sees that key as already gone. The etag the fold + /// observed rides the event as information only. + const size_t chunk_keys = std::clamp(store->poolConfig().gc_bulk_delete_chunk_keys, 1, kBulkDeleteMaxKeys); + const size_t request_keys = bulkDeleteChunkKeys(); + uint64_t attempted = 0; + uint64_t requests = 0; + std::vector chunk; + std::vector *> chunk_entries; + const auto flush = [&] { - ++report.manifests_deleted; - EventEmitter{*store}.emit([&](CasEvent & e) + if (chunk.empty()) + return; + /// A backend without `DeleteObjects` (GCS) falls back to one admitted delete per key here; + /// `chunk_entries`' per-key bookkeeping below is unaffected either way -- it counts objects + /// that are gone after this call returns, not how many requests it took to get them there. + requests += removeCohortWriteOnce(op, chunk, request_keys, Retry::standard()); + for (const auto * entry : chunk_entries) { - e.type = CasEventType::ManifestDelete; - e.namespace_ = entry->first.root_namespace.string(); - e.object_kind = CasEventObjectKind::Manifest; - e.object_hash = manifestRefDebugString(entry->first.ref); - e.token = entry->second.render(); - e.round = new_round; - e.gen = generation; - e.outcome = "deleted_or_absent"; - e.reason = "owner-removed manifest body; batch delete of a write-once key after decrements adopted"; - }); + ++report.manifests_deleted; + EventEmitter{*store}.emit([&](CasEvent & e) + { + e.type = CasEventType::ManifestDelete; + e.namespace_ = entry->first.root_namespace.string(); + e.object_kind = CasEventObjectKind::Manifest; + e.object_hash = manifestRefDebugString(entry->first.ref); + e.token = entry->second.render(); + e.round = new_round; + e.gen = generation; + e.outcome = "deleted_or_absent"; + e.reason = "owner-removed manifest body; batch delete of a write-once key after decrements adopted"; + }); + } + chunk.clear(); + chunk_entries.clear(); + }; + for (const auto & entry : mf_cleanup_now) + { + ++attempted; + chunk.push_back(layout.writeOnceManifestKey(entry.first)); + chunk_entries.push_back(&entry); + if (chunk.size() >= chunk_keys) + flush(); } - chunk.clear(); - chunk_entries.clear(); - }; - for (const auto & entry : mf_cleanup_now) - { - ++attempted; - chunk.push_back(layout.writeOnceManifestKey(entry.first)); - chunk_entries.push_back(&entry); - if (chunk.size() >= chunk_keys) - flush(); + flush(); + t.metric("attempted", attempted); + t.metric("accepted", report.manifests_deleted - manifests_deleted_before); + t.metric("requests", requests); + t.metric("suppressed", suppress_destructive ? 1 : 0); } - flush(); - t.metric("attempted", attempted); - t.metric("accepted", report.manifests_deleted - manifests_deleted_before); - t.metric("requests", requests); - t.metric("suppressed", suppress_destructive ? 1 : 0); } /// Removal completion has no physical pass. The terminal fold placed positive evidence in the /// life row; a later invocation's catalog-only pre-fold drain owns lifecycle deletion, while the /// perpetual janitor owns dead-life bytes. - uint64_t cleanup_evidence_rows = 0; - for (const auto & [life_id, ref_life_state] : folded.fold_seal.ref_lives) - cleanup_evidence_rows += ref_life_state.cleanup_evidence ? 1 : 0; - runNamespaceJanitor(state, suppress_destructive, cleanup_evidence_rows); - /// Phase `ref_object_cleanup`. Emitted even when the whole pass is skipped (`trim_enabled` is - /// a test seam, `suppressed` gates the deletes), because "this phase did nothing and why" is exactly - /// what a reader of a round that reclaimed nothing needs to see. - { - GcPhaseTimer t(phase_sink, "ref_object_cleanup"); - RefCleanupPassStats cleanup_stats; - /// Runs before `t` emits its row, also when a delete chunk throws: the pass has then already - /// deleted objects that the row must account for. - SCOPE_EXIT_SAFE({ - t.metric("suppressed", suppress_destructive ? 1 : 0); - t.metric("trim_enabled", trim_enabled ? 1 : 0); - t.metric("namespaces_planned", folded.ref_tables.size()); - t.metric("objects_planned", cleanup_stats.objects_planned); - t.metric("objects_deleted", cleanup_stats.objects_deleted); - t.metric("namespaces_skipped", cleanup_stats.namespaces_skipped); - t.metric("stopped_lease_moved", cleanup_stats.stopped_lease_moved ? 1 : 0); - t.metric("stopped_authority_unverified", cleanup_stats.stopped_authority_unverified ? 1 : 0); - t.metric("chunks_under_catalog_change", cleanup_stats.chunks_under_catalog_change); - }); - if (trim_enabled) - cleanupRefObjects(folded, state.lease, suppress_destructive, round_work_budget, cleanup_stats); - } /// Bounded orphan-manifest backstop. The fold already exact-read each candidate, retired its exact /// source edges into the adopted runs and placed cursor progress in the SAME `gc/state` CAS above. - /// Only this post-CAS tail may delete candidate bodies. + /// Only this post-CAS tail may delete candidate bodies. It runs before the janitor and the ref cleanup: + /// those resume next round, while the commit moved the sweep cursor past these nominations. /// Phase `orphan_sweep`. { GcPhaseTimer t(phase_sink, "orphan_sweep"); @@ -1695,6 +1709,33 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al t.metric("retained_work_budget", sweep.retained_work_budget); } + uint64_t cleanup_evidence_rows = 0; + for (const auto & [life_id, ref_life_state] : folded.fold_seal.ref_lives) + cleanup_evidence_rows += ref_life_state.cleanup_evidence ? 1 : 0; + runNamespaceJanitor(state, suppress_destructive, cleanup_evidence_rows); + /// Phase `ref_object_cleanup`. Emitted even when the whole pass is skipped (`trim_enabled` is + /// a test seam, `suppressed` gates the deletes), because "this phase did nothing and why" is exactly + /// what a reader of a round that reclaimed nothing needs to see. + { + GcPhaseTimer t(phase_sink, "ref_object_cleanup"); + RefCleanupPassStats cleanup_stats; + /// Runs before `t` emits its row, also when a delete chunk throws: the pass has then already + /// deleted objects that the row must account for. + SCOPE_EXIT_SAFE({ + t.metric("suppressed", suppress_destructive ? 1 : 0); + t.metric("trim_enabled", trim_enabled ? 1 : 0); + t.metric("namespaces_planned", folded.ref_tables.size()); + t.metric("objects_planned", cleanup_stats.objects_planned); + t.metric("objects_deleted", cleanup_stats.objects_deleted); + t.metric("namespaces_skipped", cleanup_stats.namespaces_skipped); + t.metric("stopped_lease_moved", cleanup_stats.stopped_lease_moved ? 1 : 0); + t.metric("stopped_authority_unverified", cleanup_stats.stopped_authority_unverified ? 1 : 0); + t.metric("chunks_under_catalog_change", cleanup_stats.chunks_under_catalog_change); + }); + if (trim_enabled) + cleanupRefObjects(folded, state.lease, suppress_destructive, round_work_budget, cleanup_stats); + } + return report; } @@ -4267,9 +4308,11 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, catch (const Exception & e) { /// A read verb that gives up throws `NETWORK_ERROR`; any other failure fails the round, as elsewhere. - /// A lost fence or a spent lease budget throws the same code. + /// A lost fence or a spent lease budget throws the same code. A stopped owner's failure was not retried, + /// so it says nothing about the leased version. if (e.code() != ErrorCodes::NETWORK_ERROR) throw; + rethrowIfStoppedOwnersFailure(); seen = "no answer (" + e.message() + ")"; } result.parent_unconfirmed = !seen.empty(); @@ -4604,7 +4647,7 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, { /// The parent runs this merge streams are what a newer leader's retention removes. An absent run was /// classified by its own probe; a second probe could contradict it. - if (e.code() == ErrorCodes::CORRUPTED_DATA && !absence_classified) + if (e.code() == ErrorCodes::CORRUPTED_DATA && !absence_classified && !isQueryStoredCause(std::current_exception())) throwIfStateMoved(op, state_etag, e.message()); throw; } @@ -5251,17 +5294,30 @@ bool Gc::rowDecisionDue(const GcState & state, uint64_t current_round) /// FAIL-CLOSED: a missing / undecodable seal, or a summary that is not TOTAL over gc_shards, is /// corrupt GC bookkeeping — force a FOLD so the round's own fail-closed path surfaces it, never a /// silent defer (matching the fold's throw-on-missing-adopted-seal treatment). + std::optional seal_bytes; + try + { + CasOperation op = store->openRequests().admit(); + seal_bytes = op.read(store->layout().foldSealKey(state.snap_generation, state.snap_attempt), Retry::standard()); + } + catch (...) + { + /// A read that failed for a killed query says nothing about the seal. + if (queryStopRequested()) + throw; + return true; + } + if (!seal_bytes) + return true; std::optional seal; try { - seal = readFoldSeal(state.snap_generation, state.snap_attempt); + seal = decodeFoldSeal(seal_bytes->bytes, store->layout(), store->poolConfig().gc_shards, state.snap_generation); } catch (...) { return true; /// undecodable seal => fail-closed force-fold } - if (!seal) - return true; for (uint64_t shard = 0; shard < state.gc_shards; ++shard) { const auto it = seal->condemned_summary.find(shard); @@ -5440,6 +5496,7 @@ RebuildReport Gc::rebuildBaseline(bool force) } catch (const Exception & e) { + rethrowIfStoppedOwnersFailure(); throw Exception(ErrorCodes::CORRUPTED_DATA, "CAS GC rebuild: the prior fold seal (generation {}, attempt {}) is UNDECODABLE " "({}), so the holds it carries cannot be read. A rebuild that dropped them would " @@ -5498,6 +5555,7 @@ RebuildReport Gc::rebuildBaseline(bool force) } catch (const Exception & e) { + rethrowIfStoppedOwnersFailure(); throw Exception(ErrorCodes::CORRUPTED_DATA, "CAS GC rebuild: gc/state names no adopted baseline and the newest fold seal " "(generation {}, attempt {}) is UNDECODABLE ({}), so the holds this pool carries " @@ -6040,6 +6098,7 @@ void Gc::refreshAuthority(uint64_t admitted_generation, const Retry & policy) } catch (...) { + rethrowIfStoppedOwnersFailure(); tryLogCurrentException(logger, "CAS gc: the leader-authority probe failed; this round's destructive operations treat the " "lease as lost"); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h index b1bc1a2db24ec..35c85aaddf9fa 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h @@ -535,14 +535,15 @@ class Gc /// instance, and the scheduler holds `gc_round_mutex` across both the install and the round. void setPhaseSink(GcPhaseSink sink) { phase_sink = std::move(sink); } - /// Install (or clear) the stop signal of the rounds that follow. Planning asks it before each read, the walk - /// before each step, and the intake once more after its last walk. Once it answers true, the intake reads no - /// further ref log, every namespace it has not finished stays unproven, and the round deletes nothing; the - /// reduce and the commit still run. A stop after the final intake poll does not affect the round. Not asked: - /// the pre-fold drain of catalog rows, the checkpoint reads before planning, and a cold cursor's resolution, - /// which may follow one backlink per epoch. Installed and cleared like `setPhaseSink`. + /// Install (or clear) the stop signal of the rounds that follow, like `setPhaseSink`. The drain and pre-listing + /// poll throw `ABORTED` and set `roundStopObserved`. During intake, a stop ends reads and suppresses deletion. + /// Reduce and commit still run. Checkpoint reads and cold cursor resolution do not poll. The callback may run + /// under a CAS mutex, so it must be lock-free or take only a leaf lock. void setStopSignal(std::function signal) { stop_signal = std::move(signal); } + /// Whether the current or last `runRegularRound` found the stop signal true before its hot listing. + bool roundStopObserved() const { return round_stop_observed; } + /// Keys per GC write-once delete request: `gc_bulk_delete_chunk_keys` capped by the storage's batch /// limit, clamped to [1, `kBulkDeleteMaxKeys`] because an empty request would never advance. size_t bulkDeleteChunkKeys() const; @@ -1091,6 +1092,7 @@ class Gc GcPhaseSink phase_sink; /// See `setStopSignal`. Empty: the intake is never stopped. std::function stop_signal; + bool round_stop_observed = false; UInt128 gc_id{}; /// this leader's identity (random u128, never 0) /// Every round-engine log line goes through this logger (see the constructor's `log_` doc /// comment) so multi-disk processes can attribute GC logs to the disk/srid that produced them. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp index 857acd6ad131a..c3faf732d4515 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp @@ -1,7 +1,11 @@ #include +#include #include +#include +#include #include +#include #include #include @@ -17,6 +21,21 @@ namespace ProfileEvents namespace DB::Cas { +namespace +{ + +/// Runs `fn` in `group` and leaves it on return or unwind, before the caller publishes the answer: the round may end its +/// query once it takes the answer. +template +auto runInGroup(const ThreadGroupPtr & group, Fn && fn) +{ + ThreadGroupSwitcher switcher(group, ThreadName::UNKNOWN); + throwUnlessInThreadGroup(group, "CAS GC read-ahead worker"); + return fn(); +} + +} + GcReadAhead::GcReadAhead(CasOperation & op_, CasRequests & requests_, ThreadPool & pool_, size_t concurrency_) : op(op_), requests(requests_), pool(pool_), concurrency(concurrency_), generation(op_.generation()) { @@ -54,18 +73,25 @@ void GcReadAhead::hint(Slots & slots, const String & key, Request request, Re slots.emplace(key, slot); try { - pool.scheduleOrThrowOnError([slot, key, requests_ptr = &requests, gen = generation, request] + /// The worker joins a manual round's query, so the query's stop vetoes the worker's retry of a failed request. + /// A scheduled round has no query group, and the switch does nothing. + pool.scheduleOrThrowOnError([slot, key, requests_ptr = &requests, gen = generation, request, + group = CurrentThread::getGroup()] { try { - CasOperation worker = requests_ptr->resume(gen); - slot->result = request(worker, key); - slot->promise.set_value(); + slot->result = runInGroup(group, [&] + { + CasOperation worker = requests_ptr->resume(gen); + return request(worker, key); + }); } catch (...) { slot->promise.set_exception(std::current_exception()); + return; } + slot->promise.set_value(); }); } catch (...) @@ -193,7 +219,8 @@ std::function GcReadAhead::startCreate(std::function>(); - auto job = [promise, fn = std::move(request), requests_ptr = &requests, gen = generation, failure = create_failure] + auto job = [promise, fn = std::move(request), requests_ptr = &requests, gen = generation, failure = create_failure, + group = CurrentThread::getGroup()] { if (failure->failed.load()) { @@ -201,21 +228,28 @@ std::function GcReadAhead::startCreate(std::functionset_exception(failure->first); return; } + IntentCreateResult answer; try { - CasOperation worker = requests_ptr->resume(gen); - promise->set_value(fn(worker)); + answer = runInGroup(group, [&] + { + CasOperation worker = requests_ptr->resume(gen); + return fn(worker); + }); } catch (...) { + const auto error = std::current_exception(); { std::lock_guard lock(failure->mutex); if (!failure->first) - failure->first = std::current_exception(); + failure->first = error; } failure->failed.store(true); - promise->set_exception(std::current_exception()); + promise->set_exception(error); + return; } + promise->set_value(std::move(answer)); }; const uint64_t id = next_create++; /// Registered before the worker exists, so the destructor waits for every worker that was scheduled. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp index 6a057b0156f63..a618e257fcac2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -20,6 +21,7 @@ namespace DB::ErrorCodes extern const int NETWORK_ERROR; extern const int ABORTED; extern const int TIMEOUT_EXCEEDED; + extern const int QUERY_WAS_CANCELLED; extern const int SOCKET_TIMEOUT; extern const int MEMORY_LIMIT_EXCEEDED; extern const int FAULT_INJECTED; @@ -344,11 +346,16 @@ Cas::RoundReport CasGcScheduler::runRoundLogged(Cas::Gc & round_gc, GcRoundLogRe catch (...) { fin.error_code = getCurrentExceptionCode(); - /// Non-transient first, so a bug that coincides with a restart is never masked; then the - /// teardown flag, the only witness of a refused teardown fence (see `Outcome::Stopped`). - fin.outcome = !isTransientGcRoundError(fin.error_code) ? Rec::Outcome::Failed - : store->teardownBegun() ? Rec::Outcome::Stopped - : Rec::Outcome::Aborted; + /// A stopped query ends a manual round with its verdict or with a transient code it caused, such as a + /// sent write left unresolved. Scheduler stops use the round's recorded observation. Non-transient before + /// the stop and teardown flags, so a bug that coincides with a stop or restart is never masked; the + /// teardown flag is the only witness of a refused teardown fence (see `Outcome::Stopped`). + const bool query_stopped = fin.error_code == ErrorCodes::QUERY_WAS_CANCELLED + || (isTransientGcRoundError(fin.error_code) && Cas::queryStopRequested()); + fin.outcome = query_stopped ? Rec::Outcome::Stopped + : !isTransientGcRoundError(fin.error_code) ? Rec::Outcome::Failed + : store->teardownBegun() || round_gc.roundStopObserved() ? Rec::Outcome::Stopped + : Rec::Outcome::Aborted; fin.error = getCurrentExceptionMessage(false); fill_counters(rep); fin.duration_ms = std::chrono::duration_cast( @@ -415,6 +422,8 @@ void CasGcScheduler::loop() return; if (before_tick_lock_hook_for_test) before_tick_lock_hook_for_test(); + /// Read under the round mutex: a manual round resets the observation as soon as the mutex is free. + bool round_stopped_by_scheduler = false; try { /// LOW/benign: if stop() flips `scheduler_state` while we're blocked here (a concurrent manual @@ -445,6 +454,9 @@ void CasGcScheduler::loop() if (store->teardownBegun() && isTransientGcRoundError(getCurrentExceptionCode())) LOG_INFO(log, "CA GC cleanup of this mount's own `Creating` rows stopped by the disk's teardown: {}", getCurrentExceptionMessage(false)); + else if (stopRequested() && isTransientGcRoundError(getCurrentExceptionCode())) + LOG_INFO(log, "CA GC cleanup of this mount's own `Creating` rows stopped by the scheduler's stop: {}", + getCurrentExceptionMessage(false)); else tryLogCurrentException(log, "CA GC cleanup of this mount's own `Creating` rows failed (will retry next tick)"); } @@ -467,7 +479,18 @@ void CasGcScheduler::loop() /// Only the background round: a manual round runs on a stopped scheduler too. gc.setStopSignal(stop_requested); SCOPE_EXIT({ gc.setStopSignal({}); }); - const Cas::RoundReport report = runRoundLogged(gc, GcRoundLogRecord::Trigger::Scheduled, [this] { onLeaseAcquired(); }); + const Cas::RoundReport report = [&] + { + try + { + return runRoundLogged(gc, GcRoundLogRecord::Trigger::Scheduled, [this] { onLeaseAcquired(); }); + } + catch (...) + { + round_stopped_by_scheduler = gc.roundStopObserved(); + throw; + } + }(); i_am_leader.store(report.acquired_lease, std::memory_order_relaxed); if (report.acquired_lease) { @@ -503,6 +526,8 @@ void CasGcScheduler::loop() } catch (...) { + if (tick_failure_hook_for_test) + tick_failure_hook_for_test(); if (store->teardownBegun() && isTransientGcRoundError(getCurrentExceptionCode())) { /// The disk is being torn down and the round was cut at its next request: expected, @@ -510,6 +535,12 @@ void CasGcScheduler::loop() LOG_INFO(log, "CA GC round stopped by the disk's teardown: {}", getCurrentExceptionMessage(false)); continue; } + if (round_stopped_by_scheduler && isTransientGcRoundError(getCurrentExceptionCode())) + { + /// `SYSTEM CAS GC STOP` ended the round, as asked; `runRoundLogged` recorded it as `Stopped`. + LOG_INFO(log, "CA GC round stopped by the scheduler's stop: {}", getCurrentExceptionMessage(false)); + continue; + } /// Idempotent round - the next tick retries; failures must never kill the pacing thread. /// runRoundLogged already emitted the classified (Aborted/Failed) Finish row before rethrowing. /// diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h index 4eb8381146f7f..b788e6ffb6aa8 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h @@ -33,7 +33,9 @@ struct GcRoundLogRecord /// nothing durable is wrong. `Stopped`: the same transient class, observed after the pool's /// teardown began -- a correlation, not a cause: the engine reports a refused teardown fence /// exactly like a lost mount fence, so the flag is the only witness, and the row says so honestly - /// rather than reading a clean restart as a backend incident. `Failed` is reserved for everything + /// rather than reading a clean restart as a backend incident. `Stopped` also names a round that ended + /// at a scheduler stop it observed itself (`Gc::roundStopObserved`), and a manual round that ended with + /// `QUERY_WAS_CANCELLED` or with a transient code while its query was stopped. `Failed` is reserved for everything /// else (a logic error, corrupted data, an unclassified code): fail-closed, an unrecognised /// failure reads as real -- during a teardown too. enum class Outcome { Unknown, Success, NotALeader, Failed, Deferred, Aborted, Stopped }; @@ -181,6 +183,10 @@ class CasGcScheduler /// Set it before `start`. void setBeforeTickLockHookForTest(std::function hook) { before_tick_lock_hook_for_test = std::move(hook); } + /// Runs `hook` on the round worker when a tick fails, after the round mutex is released and before the + /// failure is logged. Set it before `start`. + void setTickFailureHookForTest(std::function hook) { tick_failure_hook_for_test = std::move(hook); } + private: enum class SchedulerState { @@ -259,6 +265,8 @@ class CasGcScheduler std::condition_variable terminal_exit_cv; /// See `setBeforeTickLockHookForTest`. Empty in production. std::function before_tick_lock_hook_for_test; + /// See `setTickFailureHookForTest`. Empty in production. + std::function tick_failure_hook_for_test; /// Cumulative condemned entries minus exact-token deletes completed by this scheduler while it /// led. It is an approximate health gauge, not durable GC state. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp index 0a8857f714799..a8fd3d48f0241 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -76,9 +77,16 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven } catch (...) { - if (first_page_of_pass) - (void)casGcMaintenanceState(op, layout, progress.etag, GcMaintenanceState{}, Retry::once()); - throw; + /// A stopped query's failed `LIST` keeps the scan's progress: the reset is optional, and the stop vetoed + /// every further request. + if (!first_page_of_pass || queryStopRequested()) + throw; + const std::exception_ptr list_failure = std::current_exception(); + WriteResult reset = casGcMaintenanceState(op, layout, progress.etag, GcMaintenanceState{}, Retry::once()); + /// A reset that may still land outranks the listing error. + if (const auto * gave_up = std::get_if(&reset); gave_up && gave_up->why == GaveUp::Why::Unresolved && gave_up->sent_any) + (void)orThrow(std::move(reset), "CAS GC janitor cursor reset after a failed LIST"); + std::rethrow_exception(list_failure); } result.pages = 1; result.keys = page.keys.size(); @@ -105,6 +113,8 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven /// themselves prevent progress. bool page_decided = !ambiguous && !suppress_deletes; std::vector dead_stream_keys; + /// A request that failed for a stopped query ends the page with that failure, unpublished. + std::exception_ptr stopped_query_failure; for (const ListedKey & listed : page.keys) { @@ -164,6 +174,11 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven ++result.leaked; result.anomalies.push_back( "leaked dead-life object '" + listed.key + "': exact HEAD failed: " + e.what()); + if (queryStopRequested()) + { + stopped_query_failure = std::current_exception(); + break; + } continue; } } @@ -183,8 +198,15 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven ++result.leaked; result.anomalies.push_back( "leaked dead-life object '" + listed.key + "': exact delete failed: " + e.what()); + if (queryStopRequested()) + { + stopped_query_failure = std::current_exception(); + break; + } } } + if (stopped_query_failure) + std::rethrow_exception(stopped_query_failure); if (page_decided && !dead_stream_keys.empty() && op.admitted()) remove_write_once_keys(op, dead_stream_keys, result); @@ -199,21 +221,30 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven if (page_decided) { const GcMaintenanceState next{.janitor_cursor = page.next_cursor}; + std::optional outcome; try { - const WriteResult outcome = casGcMaintenanceState(op, layout, progress.etag, next, Retry::standard()); - if (std::holds_alternative(outcome) || std::holds_alternative(outcome)) - result.anomalies.push_back("cursor publication did not commit"); - else if (std::holds_alternative(outcome)) - { - published = true; - result.more = result.deleted > 0 && !(cursor.empty() && page.next_cursor.empty()); - } + outcome = casGcMaintenanceState(op, layout, progress.etag, next, Retry::standard()); } catch (const std::exception & e) { + if (queryStopRequested()) + throw; result.anomalies.push_back("cursor publication failed: " + String(e.what())); } + /// A stopped query's caller must learn that the cursor write may still land, or that the store refused it. + const auto * gave_up = outcome ? std::get_if(&*outcome) : nullptr; + const bool unresolved = gave_up && gave_up->why == GaveUp::Why::Unresolved && gave_up->sent_any; + const bool refused = outcome && std::holds_alternative(*outcome); + if ((unresolved || refused) && queryStopRequested()) + (void)orThrow(std::move(*outcome), "CAS GC janitor cursor publication"); + if (outcome && (std::holds_alternative(*outcome) || std::holds_alternative(*outcome))) + result.anomalies.push_back("cursor publication did not commit"); + else if (outcome && std::holds_alternative(*outcome)) + { + published = true; + result.more = result.deleted > 0 && !(cursor.empty() && page.next_cursor.empty()); + } } /// An unpublished page is listed again, so its failed keys are not leaked yet. if (!published) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp index 0611bd15ad43e..525ee36411b26 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -636,6 +637,8 @@ uint64_t sweepNamespace(Pool & store, const RootNamespace & ns, const BuildPrefi } catch (const Exception & e) { + /// Skipped with a warning, a stopped owner's failure would let the drain go on after the stop. + rethrowIfStoppedOwnersFailure(); LOG_WARNING(getLogger("CasOrphanManifestSweep"), "CAS orphan sweep: namespace {} protection view unavailable ({}); skipping its deletions", ns.string(), e.message()); @@ -653,6 +656,8 @@ uint64_t sweepNamespace(Pool & store, const RootNamespace & ns, const BuildPrefi uint64_t deleted = 0; op.forEachListedKey(prefix_key, [&](const ListedKey & listed) { + throwIfQueryStopped(); + throwIfBackgroundStopped(); if (protection.active.contains(listed.key)) return true; /// owned by a committed or precommit owner — never sweep @@ -676,7 +681,7 @@ uint64_t sweepNamespace(Pool & store, const RootNamespace & ns, const BuildPrefi /// already reclaimed it" race, not a failure. A THROWN exception (a transient backend hiccup) /// is the one thing `warnings` changes: opted-in (non-null), it is recorded and the sweep moves /// to the next key; opted-out (nullptr, every pre-existing caller), it propagates exactly as - /// before (fail-close). + /// before (fail-close). A failure after an owner stopped propagates either way. try { const std::optional head = op.head(listed.key, Retry::standard()); @@ -687,6 +692,7 @@ uint64_t sweepNamespace(Pool & store, const RootNamespace & ns, const BuildPrefi } catch (...) { + rethrowIfStoppedOwnersFailure(); if (!warnings) throw; warnings->push_back("CAS orphan sweep: " + listed.key + " delete failed: " diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h index a6b12402eb416..aea312ffb55f3 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h @@ -189,7 +189,8 @@ struct ManifestSweepResult /// below) also pushes a "cannot confirm emptiness" warning, not just a `LOG_WARNING`. `warnings == /// nullptr` (the default, every pre-existing caller) preserves the original behaviour exactly: a /// per-key failure propagates as an exception (fail-close default), and the protection-view skip is -/// log-only. `Gone`/`Mismatch` delete outcomes stay silently spared either way — those are the +/// log-only. A stopped owner ends the sweep at the next key with its verdict, and a failure after the stop propagates +/// either way. `Gone`/`Mismatch` delete outcomes stay silently spared either way — those are the /// normal "a fresh owner reclaimed it" race the periodic sweep expects, not a failure to warn about. /// This direct decommission path relies on the caller's held server-root claim/fence: while that claim /// is held, a same-server-root rebirth cannot become live between its catalog cut and exact-token delete. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.cpp index 090650a1a68bf..95fea3f15ee2f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -39,6 +40,7 @@ bool CatalogLifecycleReconciler::isCreatorTerminal(const CreatorFence & creator) const auto [it, inserted] = creator_slots.try_emplace({creator.server_root_id, creator.writer_epoch}); if (!inserted) return it->second == CreatorSlotStatus::Terminal; + throwIfBackgroundStopped(); try { it->second = probe_creator_slot(creator); @@ -47,6 +49,7 @@ bool CatalogLifecycleReconciler::isCreatorTerminal(const CreatorFence & creator) { if (e.code() == ErrorCodes::LOGICAL_ERROR) throw; + rethrowIfStoppedOwnersFailure(); /// A deposed leader's read fails too; the drain's own verdict reports that, not this creator. if (op.admitted()) LOG_WARNING(getLogger("CatalogLifecycleReconciler"), @@ -91,6 +94,7 @@ std::optional CatalogLifecycleReconciler::selectEligible( { for (const CatalogEntry & entry : catalog.catalog.entries) { + throwIfQueryStopped(); if (entry.state == NsState::Creating) { /// The probe reads the creator's mount slot, which a deposed leader may not do; the verdict @@ -141,6 +145,8 @@ CatalogLifecycleReconcileResult CatalogLifecycleReconciler::reconcile( for (;;) { + throwIfQueryStopped(); + throwIfBackgroundStopped(); const std::optional eligible = selectEligible(catalog); if (!eligible) { diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h index 3dfe1ec1e4dd4..0a326138d792f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h @@ -469,7 +469,7 @@ class Pool : public std::enable_shared_from_this void beginTeardown() noexcept; bool teardownBegun() const noexcept; /// The GC scheduler's per-tick cleanup of this mount's own idle `Creating` catalog rows; stops at teardown - /// or once `stop_requested` returns true. + /// or once `stop_requested` returns true, with `ABORTED` when that happens inside a cancel. void cancelIdleOwnCreatingRows(const std::function & stop_requested = {}); bool stopAndDrainDetachedWork(uint64_t deadline_ms); uint64_t detachedWorkInFlight() const; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index 8b5d4df0c8cc8..181974bd7ac4b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -772,6 +772,14 @@ void CasRefLedger::cancelIdleOwnCreatingRows( const auto stopped = [&] { return stop_requested && stop_requested(); }; if (stopped()) return; + /// The stop also ends a cancel that keeps losing the catalog, at its next submission. + std::optional stop_owner; + if (stop_requested) + stop_owner.emplace(Cas::OwnerScope::background([&] + { + if (stopped()) + throw Exception(ErrorCodes::ABORTED, "CAS cleanup of this mount's own `Creating` rows stopped by its scheduler"); + })); /// The order `Pool::captureMountIncarnation` uses: a generation that holds across the epoch read dates it. const uint64_t generation = fence_generation_fn(); const uint64_t epoch = live_epoch_fn(); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h index 8c4c04cc1e4a4..70f38f82d8606 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h @@ -348,7 +348,8 @@ class CasRefLedger /// name has no cold admission in flight here; the check is repeated inside the catalog lane. One scan /// read per call; each cancel may add its own catalog reads and conditional writes. `pause` replaces /// the mount plane's retry sleep. `stop_requested` is checked before the read and before each cancel, and - /// ends the call when true. An absent catalog is logged and ends the call; other failures throw. + /// returns when true; inside a cancel it is the owner check, which throws `ABORTED`. An absent catalog is + /// logged and ends the call; other failures throw. void cancelIdleOwnCreatingRows(const Liveness & alive, std::function pause, const std::function & stop_requested = {}); diff --git a/src/Disks/tests/gtest_cas_blob_indegree.cpp b/src/Disks/tests/gtest_cas_blob_indegree.cpp index 29f3dcf8450dd..8ba90b78f60b6 100644 --- a/src/Disks/tests/gtest_cas_blob_indegree.cpp +++ b/src/Disks/tests/gtest_cas_blob_indegree.cpp @@ -10,9 +10,11 @@ #if USE_AWS_S3 #include #endif +#include #include #include #include +#include #include #include #include @@ -1145,6 +1147,96 @@ TEST(CASSourceEdgeRun, OnlyAnAbsentRunReachesTheHook) } } +namespace +{ + +/// Serves the run's header line, then on the next refill calls `on_refill` and throws the query's stored +/// exception, as an S3 body whose next `GET` fails after a kill does. +class HeaderThenStoppedReadBuffer : public DB::ReadBuffer +{ +public: + HeaderThenStoppedReadBuffer(String header_, std::function on_refill_) + : DB::ReadBuffer(nullptr, 0), header(std::move(header_)), on_refill(std::move(on_refill_)) + { + } + +private: + bool nextImpl() override + { + if (!served) + { + served = true; + BufferBase::set(header.data(), header.size(), 0); + return true; + } + on_refill(); + DB::CurrentThread::checkIfNotCancelled(); + return false; + } + + String header; + std::function on_refill; + bool served = false; +}; + +class HeaderThenStoppedBackend : public InMemoryBackend +{ +public: + std::unique_ptr stream(const String & key, TransportAccess & access) override + { + auto raw = InMemoryBackend::read(key, access); + if (!raw) + return nullptr; + return std::make_unique(raw->bytes.substr(0, raw->bytes.find('\n') + 1), on_refill); + } + + std::function on_refill; +}; + +} + +/// A run row read whose stream refill fails with the query's stored exception must not annotate it: the query +/// rethrows that one object to every thread it stops. The stored code is `CORRUPTED_DATA`, the code the row catch +/// annotates. +TEST(CASSourceEdgeRun, RowReadLeavesTheStoredQueryExceptionUnchanged) +{ + const String stored_text = "the query's stored corruption"; + for (const auto mode : {AdoptedRunReader::OnRefusal::Throw, AdoptedRunReader::OnRefusal::Report}) + { + SCOPED_TRACE(mode == AdoptedRunReader::OnRefusal::Report ? "Report" : "Throw"); + HeaderThenStoppedBackend backend; + const Layout layout{"pool"}; + const RunRef run = writeSourceEdgeRun(backend, layout, 1, 0, 0, {}, {{b(1), s(1)}}); + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "{}", stored_text)); + int code = 0; + DB::Cas::tests::onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + backend.on_refill = [&] { query.kill(cause); }; + DB::Cas::tests::OperationForTest op(backend); + const std::vector runs{run}; + AdoptedRunReader reader(*op, runs, 0, AdoptedRunContext{.gc_shards = 1, .parent_round = 1, .summary = {}}, mode); + SourceEdgeRecord rec; + try + { + reader.next(rec); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + EXPECT_EQ(code, DB::ErrorCodes::CORRUPTED_DATA) << "the refill failure did not reach the caller"; + try + { + std::rethrow_exception(cause); + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.message(), stored_text) << "the row read annotated the query's stored exception"; + } + } +} + /// ==== schema 3 key codec (Phase 3 T3, mixed-algo pools) ==== TEST(CASSourceEdgeKeySchema3, MixedWidthKeysOrderAlgoFirst) diff --git a/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp b/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp index 6950be2aa8d0a..29f3846b26711 100644 --- a/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp +++ b/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp @@ -1,18 +1,25 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include #include #include +#include #include +#include "cas_killable_query.h" #include "cas_test_helpers.h" +#include +#include +#include #include #include @@ -35,8 +42,19 @@ namespace DB::ErrorCodes { + extern const int ABORTED; extern const int NETWORK_ERROR; + extern const int NOT_IMPLEMENTED; + extern const int TIMEOUT_EXCEEDED; extern const int CORRUPTED_DATA; + extern const int QUERY_WAS_CANCELLED; + extern const int READONLY; + extern const int CANNOT_SCHEDULE_TASK; +} + +namespace DB::FailPoints +{ + extern const char thread_group_switcher_post_attach_failure[]; } /// THE DESTRUCTIVE-ROUND FRONTIER PROOF (spec 2026-07-27 "ref chain complete cut" §5). @@ -5834,3 +5852,1250 @@ TEST(CASGCFrontierGate, ACreatingOnlyCatalogRegainsAProvenFrontier) EXPECT_TRUE(after.frontier_complete); EXPECT_FALSE(after.suppress_destructive); } + +namespace +{ + +/// Kills `kill` once a conditional write moves `gc/state` to `generation` or beyond: the round has just +/// committed, and the post-commit tail has not started. +class KillAtRoundCommitBackend final : public CountingBackend +{ +public: + String gc_state_key; + uint64_t generation = 0; + std::function kill; + std::atomic fired{false}; + + std::expected write( + const String & key, const String & bytes, const std::optional & expected_value, + TransportAccess & access) override + { + std::expected result = CountingBackend::write(key, bytes, expected_value, access); + if (kill && result.has_value() && expected_value && key == gc_state_key + && decodeGcState(bytes).snap_generation >= generation && !fired.exchange(true)) + kill(); + return result; + } +}; + +} + +/// A manual round whose query is killed right after the round commit still reclaims the hand-off +/// prefix: the hand-off is one-shot, so the stop must not cost it. +TEST(CASGCFrontierGate, StoppedManualRoundStillReclaimsHandoffPrefix) +{ + auto backend = std::make_shared(); + auto store = Pool::open(backend, + PoolConfig{.pool_prefix = "p", .server_root_id = "test", + .gc_snapshot_generations_to_keep = 2, .gc_fold_max_defer_rounds = 0}); + const Layout & layout = store->layout(); + const RootNamespace ns{"00/aa@cas@"}; + const ManifestRef r1 = publish(*backend, layout, ns, "tbl", 1, DB::UInt128(0xa1)); + + Gc gc(store, kGc); + runRegularRoundReclaiming(gc); + store->renewWatermarkOnce(); + OperationForTest raw_op(*backend); + const uint64_t old_gen = decodeGcState((*raw_op).read(layout.gcStateKey(), Retry::once())->bytes).snap_generation; + const String old_prefix = layout.gcGenPrefix(old_gen); + for (int i = 0; i < 6; ++i) + { + runRegularRoundReclaiming(gc); + store->renewWatermarkOnce(); + } + const GcState before = decodeGcState((*raw_op).read(layout.gcStateKey(), Retry::once())->bytes); + ASSERT_GT(before.snap_pruned_through, old_gen) << "the generation must be behind the retention cursor"; + ASSERT_FALSE((*raw_op).list(old_prefix, "", 1000, Retry::once()).keys.empty()) << "a live ref still pins it"; + + const ManifestRef r2{.writer_epoch = 1, .build_sequence = 2, .manifest_ordinal = 1}; + writeBlobBody(*backend, layout, DB::UInt128(0xb2)); + writeManifestRaw(*backend, layout, ns, r2, {blobEntryFor("data.bin", DB::UInt128(0xb2))}); + publishCommittedTransition(*backend, layout, ns, "tbl", r1, r2); + + backend->gc_state_key = layout.gcStateKey(); + backend->generation = before.snap_generation + 1; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->kill = [&query] { query.kill(); }; + try + { + runRegularRoundReclaiming(gc); + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::QUERY_WAS_CANCELLED) << e.message(); + } + backend->kill = {}; + }); + + ASSERT_TRUE(backend->fired) << "the query was not killed at the round commit"; + EXPECT_TRUE((*raw_op).list(old_prefix, "", 1000, Retry::once()).keys.empty()) + << "the hand-off prefix is reclaimed by the stopped round"; +} + +/// The catalog reconciler of a stopped manual round (driven directly, not through a full round) resolves +/// its attempted erase of a completed `Removing` row by a complete catalog read, even when its owner stops +/// during the backoff after that read's first attempt failed. The drain then stops before its next selection. +TEST(CASGCFrontierGate, StoppedDrainReconcilerStillResolvesAttemptedErase) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + const Layout & layout = store->layout(); + CasRequests seed_requests = openRequestsForTest(backend); + CasOperation seed_op = seed_requests.admit(); + const CompletedRemovingFixture fixture = seedCompletedRemoving(seed_op, store, kGc); + + size_t catalog_reads = 0; + std::atomic resolution_read_failed{false}; + backend->afterReadOf(layout.refCatalogKey(), [&] + { + if (++catalog_reads == 2) + { + resolution_read_failed = true; + throw Poco::TimeoutException("the erase's resolution read is lost"); + } + }); + + uint64_t completed_erases = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + if (resolution_read_failed) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + CasOperation op = requests.admit(); + const auto parent_object = op.read(layout.foldSealKey(1, 1), Retry::once()); + ASSERT_TRUE(parent_object); + const CasFoldSeal parent = decodeFoldSeal(parent_object->bytes); + CatalogLifecycleReconciler reconciler(op, layout, parent, noCreatorProvedTerminal); + expectThrowsCode(DB::ErrorCodes::QUERY_WAS_CANCELLED, + [&] { reconciler.reconcile(noAuthorityRefresh, noRetirementRecord); }); + completed_erases = reconciler.completedErases(); + EXPECT_TRUE(query.status->isKilled()) << "the owner stopped before the reissue"; + }); + backend->afterReadOf(layout.refCatalogKey(), {}); + + ASSERT_TRUE(resolution_read_failed); + EXPECT_EQ(catalog_reads, 3u) << "selection, the failed resolution read and its reissue"; + EXPECT_EQ(completed_erases, 1u); + EXPECT_FALSE(CasRefCatalog::lifeIfCataloged(seed_op, layout, fixture.ns)) << "the erase landed and was observed"; +} + +namespace +{ + +/// A gate the test opens on every exit, so a failed assertion cannot strand a parked round thread. +class OpenOnExitGate +{ +public: + ~OpenOnExitGate() { open(); } + + void open() + { + std::lock_guard lock(mutex); + opened = true; + cv.notify_all(); + } + + bool wait() + { + std::unique_lock lock(mutex); + return cv.wait_for(lock, std::chrono::seconds(30), [&] { return opened; }); + } + +private: + std::mutex mutex; + std::condition_variable cv; + bool opened = false; +}; + +/// A lease nobody holds, so a scheduler with its own random identity claims it on its first round. +void freeGcLease(Backend & backend, const Layout & layout) +{ + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + const auto got = op.read(layout.gcStateKey(), Retry::once()); + ASSERT_TRUE(got); + GcState state = decodeGcState(got->bytes); + state.lease = GcLease{.owner = UInt128(0), .seq = 0}; + ASSERT_TRUE(std::holds_alternative( + op.replace(layout.gcStateKey(), encodeGcState(state), got->etag, Retry::once()))); +} + +/// Calls `stop` from another thread, because it joins the round thread that asks for it, and returns once +/// the stop is visible to the round. +std::future requestSchedulerStop(CasGcScheduler & scheduler) +{ + auto stopping = std::async(std::launch::async, [&scheduler] { scheduler.stop(); }); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (!scheduler.stopRequested() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + EXPECT_TRUE(scheduler.stopRequested()); + return stopping; +} + +std::vector journalAfter(const std::vector & journal, size_t from, const String & except_key) +{ + std::vector tail; + for (size_t i = from; i < journal.size(); ++i) + if (!journal[i].ends_with(" " + except_key)) + tail.push_back(journal[i]); + return tail; +} + +} + +/// A scheduled round stopped between two erases of its pre-fold drain: the first erase and its resolution +/// read complete, nothing follows them, and the round ends `Stopped` without its listing or commit. The +/// next activation drains the row left. +TEST(CASGCFrontierGate, StopBetweenErasesSkipsSecondAndFold) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemovingBatch(op, store, kGc, /*count=*/2); + freeGcLease(*backend, layout); + const std::vector seeded{ + RootNamespace{"00/drain-batch-0@cas@"}, RootNamespace{"00/drain-batch-1@cas@"}}; + const uint64_t catalog_writes_before = backend->putOverwriteCount(layout.refCatalogKey()); + + OwnerRoundSink sink; + ScopedCasGcLogCapture scheduler_log("test::gc"); + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + OpenOnExitGate parked; + OpenOnExitGate release; + std::atomic fired = false; + size_t journal_at_stop = 0; + uint64_t state_writes_at_stop = 0; + /// The first catalog read with an erase behind it is that erase's resolution read. + backend->afterReadOf(layout.refCatalogKey(), [&] + { + if (backend->putOverwriteCount(layout.refCatalogKey()) == catalog_writes_before || fired.exchange(true)) + return; + journal_at_stop = backend->journalSnapshot().size(); + state_writes_at_stop = backend->putOverwriteCount(layout.gcStateKey()); + parked.open(); + release.wait(); + }); + scheduler.start(); + scheduler.requestRoundSoon(); + ASSERT_TRUE(parked.wait()) << "the round never resolved its first erase"; + std::future stopping = requestSchedulerStop(scheduler); + release.open(); + const std::optional finish = sink.waitForFinish(); + ASSERT_EQ(stopping.wait_for(std::chrono::seconds(30)), std::future_status::ready); + backend->afterReadOf(layout.refCatalogKey(), {}); + + ASSERT_TRUE(finish); + EXPECT_EQ(finish->outcome, GcRoundLogRecord::Outcome::Stopped) << finish->error; + EXPECT_EQ(finish->error_code, DB::ErrorCodes::ABORTED) << finish->error; + EXPECT_EQ(scheduler_log.captured().find("round failed"), String::npos) << scheduler_log.captured(); + EXPECT_EQ(backend->putOverwriteCount(layout.refCatalogKey()), catalog_writes_before + 1); + const std::vector tail = journalAfter(backend->journalSnapshot(), journal_at_stop, layout.gcHbKey()); + EXPECT_TRUE(tail.empty()) << "first request after the resolution read: " << tail.front(); + EXPECT_EQ(backend->putOverwriteCount(layout.gcStateKey()), state_writes_at_stop) << "the round committed"; + size_t still_cataloged = 0; + for (const RootNamespace & ns : seeded) + if (CasRefCatalog::lifeIfCataloged(op, layout, ns)) + ++still_cataloged; + EXPECT_EQ(still_cataloged, 1u); + + const auto finishes = [&] + { + std::vector rows; + for (const GcRoundLogRecord & r : sink.all()) + if (r.event_type == GcRoundLogRecord::EventType::Finish) + rows.push_back(r); + return rows; + }; + scheduler.start(); + scheduler.requestRoundSoon(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (finishes().size() < 2 && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + scheduler.stop(); + ASSERT_EQ(finishes().size(), 2u) << "the next activation ran no round"; + EXPECT_EQ(finishes()[1].outcome, GcRoundLogRecord::Outcome::Success) << finishes()[1].error; + for (const RootNamespace & ns : seeded) + EXPECT_FALSE(CasRefCatalog::lifeIfCataloged(op, layout, ns)) << ns.string(); +} + +/// A scheduled round stopped after its erase's reply was lost settles that erase by a read and sends it +/// once; the drain then stops before anything else. +TEST(CASGCFrontierGate, StopAfterLostEraseSettlesWithoutResend) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemovingBatch(op, store, kGc, /*count=*/2); + const String catalog_key = layout.refCatalogKey(); + const uint64_t catalog_writes_before = backend->putOverwriteCount(catalog_key); + backend->clearJournal(); + backend->loseNextCatalogCasResponse(catalog_key); + + Gc gc(store, kGc); + gc.setStopSignal([&] + { + const std::vector journal = backend->journalSnapshot(); + return std::find(journal.begin(), journal.end(), "cas_response_lost " + catalog_key) != journal.end(); + }); + expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { gc.runRegularRound(); }); + gc.setStopSignal({}); + + const std::vector journal = backend->journalSnapshot(); + EXPECT_EQ(std::count(journal.begin(), journal.end(), "cas_begin " + catalog_key), 1) << "the lost erase was resent"; + EXPECT_EQ(std::count(journal.begin(), journal.end(), "cas_response_lost " + catalog_key), 1); + EXPECT_EQ(backend->putOverwriteCount(catalog_key), catalog_writes_before + 1); + ASSERT_FALSE(journal.empty()); + EXPECT_EQ(journal.back(), "get " + catalog_key) << "the drain sent more after resolving the lost erase"; + const auto row_count = CasRefCatalog::read(op, layout).catalog.entries.size(); + EXPECT_EQ(row_count, 1u) << "the settled erase landed; the second row stays"; +} + +/// A drain whose owner stopped during the first of several creator probes probes no other creator. A +/// failed probe of a stopped owner is not reported as an unreadable creator slot. +TEST(CASGCFrontierGate, StopAfterFirstOfSeveralCreatorProbesProbesNoMore) +{ + for (const bool probe_fails : {false, true}) + { + SCOPED_TRACE(probe_fails ? "the probe fails" : "the probe answers"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + std::vector rows; + for (size_t i = 0; i < 3; ++i) + rows.push_back(seedStalledCreating(op, store, fmt::format("00/probe-{}@cas@", i), UInt128{0xc0 + i}, + CreatorFence{.server_root_id = fmt::format("creator-{}", i), .writer_epoch = 1, .fence_generation = 1})); + + bool stopped = false; + size_t probes = 0; + const CasFoldSeal parent; + CatalogLifecycleReconciler reconciler(op, layout, parent, [&](const CreatorFence &) + { + ++probes; + stopped = true; + if (probe_fails) + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected mount slot read failure"); + return CreatorSlotStatus::Live; + }); + ScopedCasGcLogCapture capture("CatalogLifecycleReconciler"); + { + const auto owner = OwnerScope::background([&] + { + if (stopped) + throw DB::Exception(DB::ErrorCodes::ABORTED, "test owner stopped"); + }); + expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { reconciler.reconcile(noAuthorityRefresh, noRetirementRecord); }); + } + + EXPECT_EQ(probes, 1u); + EXPECT_EQ(capture.captured().find("could not be read"), String::npos) << capture.captured(); + for (const CatalogEntry & row : rows) + EXPECT_EQ(catalogRow(op, layout, row.ns), std::optional{row}) << row.ns.string(); + } +} + +/// A manual round's drain whose query is killed while the first of several creator probes answers ends at the next +/// row with the query's own error: nothing failed, so there is no failure to keep, and no other creator is probed. +TEST(CASGCFrontierGate, KilledQueryEndsTheDrainAtTheNextRow) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + std::vector rows; + for (size_t i = 0; i < 3; ++i) + rows.push_back(seedStalledCreating(op, store, fmt::format("00/killed-probe-{}@cas@", i), UInt128{0xd0 + i}, + CreatorFence{.server_root_id = fmt::format("killed-creator-{}", i), .writer_epoch = 1, .fence_generation = 1})); + + size_t probes = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + const CasFoldSeal parent; + CatalogLifecycleReconciler reconciler(op, layout, parent, [&](const CreatorFence &) + { + ++probes; + query.kill(); + return CreatorSlotStatus::Live; + }); + expectThrowsCode(DB::ErrorCodes::QUERY_WAS_CANCELLED, + [&] { reconciler.reconcile(noAuthorityRefresh, noRetirementRecord); }); + }); + + EXPECT_EQ(probes, 1u); + for (const CatalogEntry & row : rows) + EXPECT_EQ(catalogRow(op, layout, row.ns), std::optional{row}) << row.ns.string(); +} + +/// A scheduled round deposed inside its drain, with the stop requested only after the drain's last owner +/// check, ends `Aborted`: the scheduler reports a stop the round observed, never one it samples afterwards. +TEST(CASGCFrontierGate, DepositionDuringStopIsNotStopped) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + const CompletedRemovingFixture fixture = seedCompletedRemoving(op, store, kGc); + freeGcLease(*backend, layout); + const String seal_key = layout.foldSealKey(1, 1); + const uint64_t seal_reads_before = backend->getCount(seal_key); + + OwnerRoundSink sink; + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + /// The drain reads its parent seal, then `gc/state` for its authority, then `gc/state` again before the + /// erase. The first of these deposes the leader; the second, which reads the deposition, requests the stop. + bool in_hook = false; + bool deposed = false; + std::optional> stopping; + backend->afterReadOf(layout.gcStateKey(), [&] + { + if (in_hook || stopping || backend->getCount(seal_key) == seal_reads_before) + return; + in_hook = true; + if (!deposed) + { + transferGcLease(*backend, layout, hexToU128("00000000000000000000000000000099")); + deposed = true; + } + else + { + stopping = requestSchedulerStop(scheduler); + } + in_hook = false; + }); + scheduler.start(); + scheduler.requestRoundSoon(); + const std::optional finish = sink.waitForFinish(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (!scheduler.stopRequested() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + scheduler.stop(); + backend->afterReadOf(layout.gcStateKey(), {}); + + ASSERT_TRUE(finish); + ASSERT_TRUE(stopping) << "the round never reached the erase's authority read"; + EXPECT_EQ(finish->outcome, GcRoundLogRecord::Outcome::Aborted) << finish->error; + EXPECT_NE(finish->error_code, DB::ErrorCodes::ABORTED) << finish->error; + EXPECT_TRUE(CasRefCatalog::lifeIfCataloged(op, layout, fixture.ns)); +} + +/// A manual round on a stopped scheduler that meets corruption is `Failed`: a stopped scheduler names no +/// stop of a round it did not run. +TEST(CASGCFrontierGate, CorruptionOnStoppedSchedulerManualRoundIsFailed) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + GcState state; + state.round = 1; + state.gc_shards = store->poolConfig().gc_shards; + state.snap_generation = 1; + state.snap_attempt = 1; + ASSERT_TRUE(std::holds_alternative(op.create(layout.gcStateKey(), encodeGcState(state), Retry::once()))); + + OwnerRoundSink sink; + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + scheduler.start(); + scheduler.stop(); + ASSERT_TRUE(scheduler.stopRequested()); + expectThrowsCode(DB::ErrorCodes::CORRUPTED_DATA, + [&] { (void)scheduler.runOneRoundNow(GcRoundLogRecord::Trigger::Manual); }); + + const std::optional finish = sink.waitForFinish(); + ASSERT_TRUE(finish); + EXPECT_EQ(finish->outcome, GcRoundLogRecord::Outcome::Failed) << finish->error; + EXPECT_EQ(finish->error_code, DB::ErrorCodes::CORRUPTED_DATA); +} + +/// A scheduled round whose drain saw no stop still stops before the hot listing: on a fresh pool the drain +/// reads nothing, and the round lists nothing. +TEST(CASGCFrontierGate, StopBeforeTheHotListingListsNothing) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + Gc gc(store, kGc); + gc.setStopSignal([] { return true; }); + expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { gc.runRegularRound(); }); + gc.setStopSignal({}); + EXPECT_EQ(backend->listCount(store->layout().casRefsPrefix()), 0u); +} + +namespace +{ + +/// Runs `fail` once, in place of the answer to the first read or listing whose name `matches` accepts. +class FailOneRequestBackend final : public CountingBackend +{ +public: + using CountingBackend::list; + + void failFirst(std::function matches_, std::function fail_) + { + std::lock_guard lock(mutex); + matches = std::move(matches_); + fail = std::move(fail_); + } + + bool fired() const + { + std::lock_guard lock(mutex); + return did_fire; + } + + std::optional read(const String & key, TransportAccess & access) override + { + failIfArmed(key); + return CountingBackend::read(key, access); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + failIfArmed(prefix); + return CountingBackend::list(prefix, cursor, limit, access); + } + +private: + void failIfArmed(const String & name) + { + std::function now; + { + std::lock_guard lock(mutex); + if (fail && matches(name)) + { + now = std::move(fail); + fail = {}; + did_fire = true; + } + } + if (now) + now(); + } + + mutable std::mutex mutex; + std::function matches; + std::function fail; + bool did_fire = false; +}; + +} + +/// A killed manual round whose authority read fails reports that failure, not a lost lease. +TEST(CASGCFrontierGate, StoppedOwnersFailedAuthorityReadIsNotALostLease) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + const String seal_key = layout.foldSealKey(1, 1); + const uint64_t seal_reads_before = backend->getCount(seal_key); + + ScopedCasGcLogCapture capture; + onKillableQueryThread([&](CasKillableQuery & query) + { + /// The drain reads its parent seal, then `gc/state` for its authority. + backend->failFirst( + [&](const String & name) { return name == layout.gcStateKey() && backend->getCount(seal_key) > seal_reads_before; }, + [&] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected gc/state read failure"); + }); + Gc gc(store, kGc); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "injected gc/state read failure", [&] { gc.runRegularRound(); }); + }); + + ASSERT_TRUE(backend->fired()); + EXPECT_EQ(capture.captured().find("leader-authority probe failed"), String::npos) << capture.captured(); +} + +/// A manual round killed while the namespace janitor lists fails with the listing's failure; the janitor does not +/// report it as a stopped page of a successful round. +TEST(CASGCFrontierGate, KilledManualRoundIsNotSwallowedByTheJanitor) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + + ScopedCasGcLogCapture capture; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->failFirst( + [&](const String & name) { return name == layout.namespaceRootPrefix(); }, + [&] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected janitor listing failure"); + }); + Gc gc(store, kGc); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "injected janitor listing failure", [&] { gc.runRegularRound(); }); + }); + + ASSERT_TRUE(backend->fired()) << "the round never ran its janitor"; + EXPECT_EQ(capture.captured().find("janitor stopped this round"), String::npos) << capture.captured(); +} + +/// The deferral decision reads the adopted fold seal. A read that fails for a killed manual round ends the round with +/// its failure, reading the seal no more; under a live query the same failure forces a fold instead of a deferral. +TEST(CASGCFrontierGate, KilledRoundsFailedDeferralSealReadEndsTheRound) +{ + struct Run + { + int code = 0; + String message; + std::optional report; + uint64_t seal_reads_at_decision = 0; + uint64_t seal_reads = 0; + }; + enum class Arm { Control, Live, Killed }; + const auto run = [](Arm arm, uint64_t fail_after_reads) + { + Run out; + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + const String seal_key = layout.foldSealKey(1, 1); + onKillableQueryThread([&](CasKillableQuery & query) + { + Gc gc(store, kGc); + /// The decision's read is the last seal read before the hot scan's catalog read. + gc.setRoundPointHookForTest([&](const Gc::RoundPointSiteForTest & site) + { + if (site.point == Gc::RoundPointForTest::AfterCatalogRead && out.seal_reads_at_decision == 0) + out.seal_reads_at_decision = backend->getCount(seal_key); + }); + if (arm != Arm::Control) + backend->failFirst( + [&](const String & name) { return name == seal_key && backend->getCount(seal_key) == fail_after_reads; }, + [&, arm] + { + if (arm == Arm::Killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected seal read refusal"); + }); + try + { + out.report = gc.runRegularRound(); + } + catch (const DB::Exception & e) + { + out.code = e.code(); + out.message = e.message(); + } + }); + out.seal_reads = backend->getCount(seal_key); + return out; + }; + + const Run control = run(Arm::Control, 0); + ASSERT_TRUE(control.report) << control.message; + ASSERT_TRUE(control.report->deferred) << "the fixture's round must be eligible for deferral"; + ASSERT_GE(control.seal_reads_at_decision, 1u); + const uint64_t reads_before_decision = control.seal_reads_at_decision - 1; + + const Run live = run(Arm::Live, reads_before_decision); + ASSERT_TRUE(live.report) << live.message; + EXPECT_FALSE(live.report->deferred) << "a live query's failed seal read forces the fold"; + + const Run killed = run(Arm::Killed, reads_before_decision); + EXPECT_FALSE(killed.report.has_value()); + EXPECT_EQ(killed.code, DB::ErrorCodes::READONLY) << killed.message; + EXPECT_NE(killed.message.find("injected seal read refusal"), String::npos) << killed.message; + EXPECT_EQ(killed.seal_reads, reads_before_decision) << "the killed round read the seal again"; +} + +/// A killed manual round whose janitor batch delete fails ends with that failure and leaves the janitor's cursor +/// where it was; under a live query the same failure is a recorded leak and the round succeeds. +TEST(CASGCFrontierGate, KilledRoundsFailedJanitorBatchDeletePublishesNoPage) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + /// An authoritative universe must not be empty for the destructive gate to open. + const RootNamespace live_namespace{"live/janitor-kill@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + ASSERT_TRUE(std::holds_alternative(op.create( + layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, + .last_epoch_seal = std::nullopt}, 1), + Retry::once()))); + const String dead_log = layout.refLogKey( + NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-kill"}, UInt128{0xDB}), RefTxnId{1, 1}); + ASSERT_TRUE(std::holds_alternative(op.create(dead_log, "dead residue", Retry::once()))); + const GcMaintenanceReadResult progress_before = readGcMaintenanceState(op, layout); + + std::map namespace_cleanup; + int code = 0; + String message; + std::atomic fired{false}; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->onBeforeBulkRemove([&] + { + if (fired.exchange(true)) + return; + if (killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected batch delete refusal"); + }); + Gc gc(store, kGc); + gc.setPhaseSink([&](const GcPhaseRecord & record) + { + if (record.phase == "namespace_cleanup") + namespace_cleanup = record.metrics; + }); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + backend->onBeforeBulkRemove({}); + }); + + ASSERT_TRUE(fired.load()) << "the round sent no janitor batch delete"; + EXPECT_TRUE(op.head(dead_log, Retry::once()).has_value()); + if (killed) + { + EXPECT_EQ(code, DB::ErrorCodes::READONLY) << message; + EXPECT_NE(message.find("injected batch delete refusal"), String::npos) << message; + const GcMaintenanceReadResult progress_after = readGcMaintenanceState(op, layout); + EXPECT_EQ(progress_after.etag.has_value(), progress_before.etag.has_value()); + if (progress_after.etag && progress_before.etag) + EXPECT_TRUE(sameVersion(*progress_after.etag, *progress_before.etag)) << "the janitor published the page"; + } + else + { + EXPECT_EQ(code, 0) << message; + ASSERT_FALSE(namespace_cleanup.empty()); + EXPECT_EQ(namespace_cleanup["leaked"], 1u); + } + } +} + +/// A store without batch delete makes the janitor delete one key at a time. A killed manual round whose first such +/// delete fails sends no further delete and leaves the janitor's cursor where it was; under a live query the failure is +/// a recorded leak and the next key is still deleted. +TEST(CASGCFrontierGate, KilledRoundsFailedJanitorSingleKeyFallbackPublishesNoPage) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + /// An authoritative universe must not be empty for the destructive gate to open. + const RootNamespace live_namespace{"live/janitor-fallback-kill@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + ASSERT_TRUE(std::holds_alternative(op.create( + layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, + .last_epoch_seal = std::nullopt}, 1), + Retry::once()))); + const NamespaceLifeId dead_life + = NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-fallback-kill"}, UInt128{0xDD}); + const std::vector dead_logs{layout.refLogKey(dead_life, RefTxnId{1, 1}), layout.refLogKey(dead_life, RefTxnId{1, 2})}; + for (const String & key : dead_logs) + ASSERT_TRUE(std::holds_alternative(op.create(key, "dead residue", Retry::once()))); + const GcMaintenanceReadResult progress_before = readGcMaintenanceState(op, layout); + + std::map namespace_cleanup; + int code = 0; + String message; + std::atomic janitor_deletes{0}; + std::atomic calls_at_failure{0}; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->onBeforeBulkRemove([&] + { + const int n = ++janitor_deletes; + if (n == 1) + throw DB::Exception(DB::ErrorCodes::NOT_IMPLEMENTED, "injected: no batch delete"); + if (n != 2) + return; + calls_at_failure = backend->bulkRemoveCalls(); + if (killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected single-key delete refusal"); + }); + Gc gc(store, kGc); + gc.setPhaseSink([&](const GcPhaseRecord & record) + { + if (record.phase == "namespace_cleanup") + namespace_cleanup = record.metrics; + }); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + backend->onBeforeBulkRemove({}); + }); + + ASSERT_GE(janitor_deletes.load(), 2) << "the round never fell back to single-key deletes"; + size_t remaining = 0; + for (const String & key : dead_logs) + remaining += op.head(key, Retry::once()).has_value() ? 1 : 0; + if (killed) + { + EXPECT_EQ(code, DB::ErrorCodes::READONLY) << message; + EXPECT_NE(message.find("injected single-key delete refusal"), String::npos) << message; + EXPECT_EQ(backend->bulkRemoveCalls(), calls_at_failure.load()) << "a delete was sent after the failed one"; + EXPECT_EQ(remaining, 2u); + const GcMaintenanceReadResult progress_after = readGcMaintenanceState(op, layout); + EXPECT_EQ(progress_after.etag.has_value(), progress_before.etag.has_value()) << "the janitor published the page"; + if (progress_after.etag && progress_before.etag) + EXPECT_TRUE(sameVersion(*progress_after.etag, *progress_before.etag)) << "the janitor published the page"; + } + else + { + EXPECT_EQ(code, 0) << message; + EXPECT_EQ(remaining, 1u) << "the key after the failed one is still deleted"; + ASSERT_FALSE(namespace_cleanup.empty()); + EXPECT_EQ(namespace_cleanup["leaked"], 1u); + } + } +} + +/// A janitor delete worker that fails to join the manual round's query sends nothing: outside the query its request +/// would not see the query's stop. The janitor stops with that failure and its cursor stays where it was; a janitor +/// failure under a live query does not fail the round. +TEST(CASGCFrontierGate, JanitorWorkerOutsideTheRoundsQueryDeletesNothing) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + for (const bool attach_fails : {false, true}) + { + SCOPED_TRACE(attach_fails ? "worker attach fails" : "control"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + /// An authoritative universe must not be empty for the destructive gate to open. + const RootNamespace live_namespace{"live/janitor-group@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + ASSERT_TRUE(std::holds_alternative(op.create( + layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, + .last_epoch_seal = std::nullopt}, 1), + Retry::once()))); + const String dead_log = layout.refLogKey( + NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-group"}, UInt128{0xDE}), RefTxnId{1, 1}); + ASSERT_TRUE(std::holds_alternative(op.create(dead_log, "dead residue", Retry::once()))); + const GcMaintenanceReadResult progress_before = readGcMaintenanceState(op, layout); + + int code = 0; + String message; + std::optional deletes_at_arming; + ScopedCasGcLogCapture capture; + onKillableQueryThread([&](CasKillableQuery &) + { + /// Armed at the janitor's listing, after the round's own attach, so a janitor worker's switch fails. + backend->failFirst( + [&](const String & name) { return attach_fails && name == layout.namespaceRootPrefix(); }, + [&] + { + deletes_at_arming = backend->bulkRemoveCalls(); + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + }); + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + Gc gc(store, kGc); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + + if (!attach_fails) + { + EXPECT_EQ(code, 0) << message; + EXPECT_FALSE(op.head(dead_log, Retry::once()).has_value()) << "positive control: the janitor deletes the residue"; + continue; + } + ASSERT_TRUE(deletes_at_arming.has_value()) << "the round never listed the namespace roots"; + EXPECT_EQ(code, 0) << message; + EXPECT_NE(capture.captured().find("janitor delete worker could not join"), String::npos) << capture.captured(); + EXPECT_EQ(backend->bulkRemoveCalls(), *deletes_at_arming) << "a janitor worker outside the query sent a delete"; + EXPECT_TRUE(op.head(dead_log, Retry::once()).has_value()); + const GcMaintenanceReadResult progress_after = readGcMaintenanceState(op, layout); + EXPECT_EQ(progress_after.etag.has_value(), progress_before.etag.has_value()) << "the janitor published the page"; + if (progress_after.etag && progress_before.etag) + EXPECT_TRUE(sameVersion(*progress_after.etag, *progress_before.etag)) << "the janitor published the page"; + } +} + +namespace +{ + +/// Runs `on_remove` once, before the first `DELETE` of `target` reaches the store. +class RemoveHookBackend final : public CountingBackend +{ +public: + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + std::function hook; + if (key == target) + hook = std::exchange(on_remove, {}); + if (hook) + hook(); + return CountingBackend::remove(key, expected_value, access); + } + + String target; + std::function on_remove; +}; + +} + +/// A killed manual round whose janitor exact delete of one key fails ends with that failure and leaves the janitor's +/// cursor where it was; under a live query the same failure is a recorded leak and the round succeeds. +TEST(CASGCFrontierGate, KilledRoundsFailedJanitorExactDeletePublishesNoPage) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + /// An authoritative universe must not be empty for the destructive gate to open. + const RootNamespace live_namespace{"live/janitor-exact-kill@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + ASSERT_TRUE(std::holds_alternative(op.create( + layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, + .last_epoch_seal = std::nullopt}, 1), + Retry::once()))); + /// A dead life's checkpoint is mutable, so the janitor deletes it exactly, one key at a time. + const String dead_ckpt = layout.refCkptKey( + NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-exact-kill"}, UInt128{0xDC})); + ASSERT_TRUE(std::holds_alternative(op.create(dead_ckpt, "dead checkpoint", Retry::once()))); + const GcMaintenanceReadResult progress_before = readGcMaintenanceState(op, layout); + + std::map namespace_cleanup; + int code = 0; + String message; + bool fired = false; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->target = dead_ckpt; + backend->on_remove = [&] + { + fired = true; + if (killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected exact delete refusal"); + }; + Gc gc(store, kGc); + gc.setPhaseSink([&](const GcPhaseRecord & record) + { + if (record.phase == "namespace_cleanup") + namespace_cleanup = record.metrics; + }); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + + ASSERT_TRUE(fired) << "the round sent no janitor delete of the dead checkpoint"; + EXPECT_TRUE(op.head(dead_ckpt, Retry::once()).has_value()); + if (killed) + { + EXPECT_EQ(code, DB::ErrorCodes::READONLY) << message; + EXPECT_NE(message.find("injected exact delete refusal"), String::npos) << message; + const GcMaintenanceReadResult progress_after = readGcMaintenanceState(op, layout); + EXPECT_EQ(progress_after.etag.has_value(), progress_before.etag.has_value()) << "the janitor published the page"; + if (progress_after.etag && progress_before.etag) + EXPECT_TRUE(sameVersion(*progress_after.etag, *progress_before.etag)) << "the janitor published the page"; + } + else + { + EXPECT_EQ(code, 0) << message; + ASSERT_FALSE(namespace_cleanup.empty()); + EXPECT_EQ(namespace_cleanup["leaked"], 1u); + } + } +} + +/// A manual round stopped by its query is `Stopped`, for a kill and for `max_execution_time`, and ends with the +/// failure that observed the stop. A 159 while the query is live is not a query stop, so that round stays `Aborted`. +TEST(CASGCFrontierGate, QueryStopOfAManualRoundIsStopped) +{ + enum class Stop { Kill, QueryTimeout, LiveQueryTimeout }; + for (const Stop how : {Stop::Kill, Stop::QueryTimeout, Stop::LiveQueryTimeout}) + { + SCOPED_TRACE(how == Stop::Kill ? "kill" : how == Stop::QueryTimeout ? "query timeout" : "159 under a live query"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + freeGcLease(*backend, layout); + + OwnerRoundSink sink; + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + /// A 159 that is not the query's: the query stays live while another owner reports a timeout. + std::atomic timed_out{false}; + const auto other_owner = OwnerScope::background([&] + { + if (timed_out) + throw DB::Exception(DB::ErrorCodes::TIMEOUT_EXCEEDED, "Timeout exceeded"); + }); + backend->failFirst( + [&](const String & name) { return name == layout.foldSealKey(1, 1); }, + [&] + { + if (how == Stop::LiveQueryTimeout) + timed_out = true; + else if (how == Stop::QueryTimeout) + query.kill(std::make_exception_ptr(DB::Exception(DB::ErrorCodes::TIMEOUT_EXCEEDED, "Timeout exceeded"))); + else + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected seal read failure"); + }); + try + { + (void)scheduler.runOneRoundNow(GcRoundLogRecord::Trigger::Manual); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_TRUE(backend->fired()); + EXPECT_EQ(code, how == Stop::LiveQueryTimeout ? DB::ErrorCodes::TIMEOUT_EXCEEDED : DB::ErrorCodes::NETWORK_ERROR); + const std::optional finish = sink.waitForFinish(); + ASSERT_TRUE(finish); + EXPECT_EQ(finish->error_code, code) << finish->error; + EXPECT_EQ(finish->outcome, how == Stop::LiveQueryTimeout ? GcRoundLogRecord::Outcome::Aborted : GcRoundLogRecord::Outcome::Stopped) + << finish->error; + } +} + +/// A manual round that runs after a scheduled round ended at `SYSTEM CAS GC STOP`, but before the scheduler +/// classified that failure, does not turn the stop into a failed round in the log. +TEST(CASGCFrontierGate, ManualRoundBeforeTheStopIsClassifiedKeepsTheStop) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + + OwnerRoundSink sink; + ScopedCasGcLogCapture scheduler_log("test::gc", "information"); + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + std::future stopping; + std::promise stop_issued; + std::atomic tick_seen = false; + /// The stop is visible before the round starts, so the round's pre-listing poll ends it. + scheduler.setBeforeTickLockHookForTest([&] + { + if (tick_seen.exchange(true)) + return; + stopping = requestSchedulerStop(scheduler); + stop_issued.set_value(); + }); + std::atomic manual_ran = false; + scheduler.setTickFailureHookForTest([&] + { + if (manual_ran.exchange(true)) + return; + try + { + (void)scheduler.runOneRoundNow(GcRoundLogRecord::Trigger::Manual); + } + catch (...) + { + ADD_FAILURE() << "the manual round failed: " << DB::getCurrentExceptionMessage(false); + } + }); + scheduler.start(); + scheduler.requestRoundSoon(); + ASSERT_EQ(stop_issued.get_future().wait_for(std::chrono::seconds(60)), std::future_status::ready) << "no tick ran"; + ASSERT_EQ(stopping.wait_for(std::chrono::seconds(60)), std::future_status::ready); + + ASSERT_TRUE(manual_ran) << "the scheduled round did not fail"; + std::vector finishes; + for (const GcRoundLogRecord & r : sink.all()) + if (r.event_type == GcRoundLogRecord::EventType::Finish) + finishes.push_back(r); + ASSERT_EQ(finishes.size(), 2u); + EXPECT_EQ(finishes[0].trigger, GcRoundLogRecord::Trigger::Scheduled); + EXPECT_EQ(finishes[0].outcome, GcRoundLogRecord::Outcome::Stopped) << finishes[0].error; + EXPECT_EQ(finishes[1].trigger, GcRoundLogRecord::Trigger::Manual); + EXPECT_NE(finishes[1].outcome, GcRoundLogRecord::Outcome::Stopped) << finishes[1].error; + const String captured = scheduler_log.captured(); + EXPECT_NE(captured.find("stopped by the scheduler's stop"), String::npos) << captured; + EXPECT_EQ(captured.find("round failed"), String::npos) << captured; +} + +namespace +{ + +/// Fails the round's `gc/state` commit on a killable query thread: the query is killed inside the commit's +/// write, which then either loses to a competing `gc/state` write or loses its reply with a failed settling read. +class KilledCommitBackend final : public CountingBackend +{ +public: + enum class Fault : uint8_t { CompetingWrite, LostReplyUnreadable }; + + void arm(const Layout & layout_, uint64_t round_before_, Fault fault_, std::function kill_) + { + layout.emplace(layout_); + round_before = round_before_; + fault = fault_; + kill = std::move(kill_); + } + + bool fired() const { return did_fire; } + + std::optional read(const String & key, TransportAccess & access) override + { + if (fail_state_reads && layout && key == layout->gcStateKey()) + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected gc/state read failure"); + return CountingBackend::read(key, access); + } + + std::expected write( + const String & key, const String & bytes, const std::optional & expected_value, + TransportAccess & access) override + { + if (!kill || in_hook || !layout || key != layout->gcStateKey() || !expected_value + || decodeGcState(bytes).round <= round_before) + return CountingBackend::write(key, bytes, expected_value, access); + did_fire = true; + const std::function kill_now = std::exchange(kill, {}); + if (fault == Fault::CompetingWrite) + moveLeaseAway(); + kill_now(); + if (fault == Fault::CompetingWrite) + return CountingBackend::write(key, bytes, expected_value, access); + fail_state_reads = true; + throw Poco::TimeoutException("injected lost gc/state commit reply"); + } + +private: + /// Through this backend, so the commit write that follows is conditioned on a moved incarnation. + void moveLeaseAway() + { + in_hook = true; + SCOPE_EXIT({ in_hook = false; }); + auto requests = openRequestsForTest(*this); + auto op = requests.admit(); + const auto got = op.read(layout->gcStateKey(), Retry::once()); + ASSERT_TRUE(got); + GcState state = decodeGcState(got->bytes); + state.lease.owner = hexToU128("00000000000000000000000000000099"); + ++state.lease.seq; + ASSERT_TRUE(std::holds_alternative( + op.replace(layout->gcStateKey(), encodeGcState(state), got->etag, Retry::once()))); + } + + std::optional layout; + uint64_t round_before = 0; + Fault fault = Fault::CompetingWrite; + std::function kill; + bool in_hook = false; + bool did_fire = false; + bool fail_state_reads = false; +}; + +} + +/// A manual round whose query is stopped is `Stopped` also when the stop surfaces as another transient code: +/// `ABORTED` from a commit that lost to a competing write after the kill, or the unresolved commit's 210. +TEST(CASGCFrontierGate, KilledManualRoundIsStoppedWhateverTransientCodeEndsIt) +{ + using Fault = KilledCommitBackend::Fault; + for (const Fault fault : {Fault::CompetingWrite, Fault::LostReplyUnreadable}) + { + SCOPED_TRACE(fault == Fault::CompetingWrite ? "competing write" : "lost reply, unreadable settlement"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + freeGcLease(*backend, layout); + const auto state = op.read(layout.gcStateKey(), Retry::once()); + ASSERT_TRUE(state); + + OwnerRoundSink sink; + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->arm(layout, decodeGcState(state->bytes).round, fault, [&query] { query.kill(); }); + try + { + (void)scheduler.runOneRoundNow(GcRoundLogRecord::Trigger::Manual); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_TRUE(backend->fired()) << "the round never sent its commit"; + EXPECT_EQ(code, fault == Fault::CompetingWrite ? DB::ErrorCodes::ABORTED : DB::ErrorCodes::NETWORK_ERROR); + const std::optional finish = sink.waitForFinish(); + ASSERT_TRUE(finish); + EXPECT_EQ(finish->error_code, code) << finish->error; + EXPECT_EQ(finish->outcome, GcRoundLogRecord::Outcome::Stopped) << finish->error; + } +} diff --git a/src/Disks/tests/gtest_cas_gc_intents.cpp b/src/Disks/tests/gtest_cas_gc_intents.cpp index 683f37243523e..396ac94959b6a 100644 --- a/src/Disks/tests/gtest_cas_gc_intents.cpp +++ b/src/Disks/tests/gtest_cas_gc_intents.cpp @@ -1,6 +1,7 @@ #include #include "cas_test_helpers.h" +#include "cas_killable_query.h" #include #include @@ -4652,9 +4653,13 @@ class PausedLeaderBackend : public GetHookBackend Absent, Unanswered, Refused, + /// A retryable store answer, as the S3 client gives for a failed connection. + NetworkError, }; std::atomic state_head{StateHead::Store}; + /// Runs at every `HEAD` of `gc/state`, before its answer. + std::function on_state_head; /// Every token of `gc/state` is a weak ETag: a valid precondition with no canonical identity. std::atomic weak_state_tokens{false}; @@ -4697,6 +4702,8 @@ class PausedLeaderBackend : public GetHookBackend return meta; if (meta && weakened(key)) meta->value = weak(meta->value); + if (on_state_head) + on_state_head(); switch (state_head.load()) { case StateHead::Store: @@ -4707,6 +4714,8 @@ class PausedLeaderBackend : public GetHookBackend throw Poco::TimeoutException("the gc/state HEAD was never answered"); case StateHead::Refused: throw std::runtime_error("the store refused the gc/state HEAD"); + case StateHead::NetworkError: + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "the gc/state HEAD failed"); } return meta; } @@ -5277,6 +5286,114 @@ TEST(CASGcIntents, UnconfirmedLeasedStateSuppressesTheRound) } } +/// A killed round's intent delete that fails with the query's stored cause propagates it unannotated: the query +/// rethrows that one object to every thread it stops. +TEST(CASGcIntents, IntentDeleteLeavesTheStoredQueryExceptionUnchanged) +{ + IntentPool<> pool(std::make_shared()); + ASSERT_NO_FATAL_FAILURE(pool.makePending({1})); + pool.round(); + ASSERT_TRUE(pool.row(1) && pool.row(1)->standing) << "the body is deleted, its intent is next"; + const String stored_text = "the query's stored network failure"; + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "{}", stored_text)); + bool fired = false; + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + pool.backend->onBeforeBulkRemove([&] + { + if (std::exchange(fired, true)) + return; + query.kill(cause); + std::rethrow_exception(cause); + }); + try + { + pool.gc->runRegularRound({}, /*allow_steal*/ true, UniversePolicy::Authoritative); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + pool.backend->onBeforeBulkRemove({}); + }); + + ASSERT_TRUE(fired) << "the round sent no intent delete"; + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR); + try + { + std::rethrow_exception(cause); + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.message(), stored_text) << "the intent delete annotated the query's stored exception"; + } +} + +/// The validation read of `gc/state` fails with a retryable error. A live round retries, gives up, records +/// `parent_unconfirmed` and commits; a killed round's retry is vetoed, so it ends with that failure and writes nothing +/// after the read. +TEST(CASGcIntents, AKilledRoundsFailedValidationReadEndsTheRoundBeforeItsWrites) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + IntentPool pool(std::make_shared()); + ASSERT_NO_FATAL_FAILURE(pool.makePending({1})); + std::map reduce; + pool.gc->setPhaseSink([&reduce](const GcPhaseRecord & record) + { + if (record.phase == "fold_reduce") + reduce = record.metrics; + }); + + pool.backend->state_head = StateHead::NetworkError; + pool.backend->clearJournal(); + int code = 0; + String message; + onKillableQueryThread([&](CasKillableQuery & query) + { + pool.backend->on_state_head = [&] + { + if (killed) + query.kill(); + }; + try + { + pool.gc->runRegularRound({}, /*allow_steal*/ true, UniversePolicy::Authoritative); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + pool.backend->on_state_head = {}; + }); + pool.backend->state_head = StateHead::Store; + + const auto journal = pool.backend->journal(); + const std::vector heads = stateHeadIndices(journal); + ASSERT_FALSE(heads.empty()) << "positive control: the round sent its validation read"; + const size_t writes_after = static_cast(std::count_if(journal.begin() + heads.back(), journal.end(), + [](const JournalEntry & entry) { return entry.verb == JournalVerb::Write; })); + if (killed) + { + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << message; + EXPECT_NE(message.find("the gc/state HEAD failed"), String::npos) << message; + EXPECT_EQ(heads.size(), 1u) << "the killed round retried the read"; + EXPECT_EQ(writes_after, 0u) << "the killed round wrote after its failed validation read"; + } + else + { + EXPECT_EQ(code, 0) << message; + EXPECT_GT(heads.size(), 1u) << "the live round retried the read"; + EXPECT_EQ(metricOr(reduce, "parent_unconfirmed"), 1u); + EXPECT_GT(writes_after, 0u) << "the live round committed"; + } + EXPECT_TRUE(pool.bodyMeta(1).has_value()); + } +} + /// A round whose destructive work is suppressed takes no redelete slot, so it keeps the position the previous round /// left: the round after it still starts behind the carried row. TEST(CASGcIntents, ASuppressedRoundKeepsTheRedeletePosition) diff --git a/src/Disks/tests/gtest_cas_gc_log.cpp b/src/Disks/tests/gtest_cas_gc_log.cpp index 75667566f0566..34bdc9b97f58f 100644 --- a/src/Disks/tests/gtest_cas_gc_log.cpp +++ b/src/Disks/tests/gtest_cas_gc_log.cpp @@ -942,7 +942,7 @@ TEST(CASGCLog, FoldingRoundEmitsEveryPhaseInOrder) "fold_ref_group", "fold_seal_read", "fold_ref_intake", "intent_sweep_list", "fold_reduce", "fold_seal_write", "pending_deletes", "round_commit", "handoff_reclaim", - "manifest_deletes", "namespace_cleanup", "ref_object_cleanup", "orphan_sweep"}; + "manifest_deletes", "orphan_sweep", "namespace_cleanup", "ref_object_cleanup"}; EXPECT_EQ(phaseNames(rows, 0), expected); /// Every phase row is a Phase row of THIS round and carries a duration field (0 is a legitimate diff --git a/src/Disks/tests/gtest_cas_gc_read_ahead.cpp b/src/Disks/tests/gtest_cas_gc_read_ahead.cpp index 542dcde870025..39e3846ee61b7 100644 --- a/src/Disks/tests/gtest_cas_gc_read_ahead.cpp +++ b/src/Disks/tests/gtest_cas_gc_read_ahead.cpp @@ -11,10 +11,17 @@ #include #include #include +#include #include #include +#include +#include #include +#include +#include +#include +#include #include #include @@ -27,11 +34,17 @@ #include #include #include +#include #include #include #include #include +namespace DB::FailPoints +{ + extern const char thread_group_switcher_post_attach_failure[]; +} + namespace DB::ErrorCodes { extern const int CANNOT_SCHEDULE_TASK; @@ -199,6 +212,145 @@ TEST(CASGCReadAhead, WindowIsFourTimesConcurrency) EXPECT_EQ(reads.window(), 32u); } +/// A manual round's workers run in its query: a worker whose first request fails after the kill sends no second +/// one, and the take gets that request's own failure. Under a live query the same worker retries and answers. +TEST(CASGCReadAhead, KilledRoundsWorkerDoesNotReissueAFailedRequest) +{ + enum class Worker : uint8_t { Read, Head, Create }; + for (const Worker worker : {Worker::Read, Worker::Head, Worker::Create}) + { + for (const bool killed : {true, false}) + { + SCOPED_TRACE(fmt::format("worker {}, {}", static_cast(worker), killed ? "killed query" : "live query")); + ReadAheadRig rig; + rig.put("k", "v"); + rig.backend->resetCounts(); + bool answered = false; + String failure; + std::thread round([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + if (killed) + query.kill(); + const auto timeout = std::make_exception_ptr(Poco::TimeoutException("injected request timeout")); + if (worker == Worker::Head) + rig.backend->failNextHeadWith("k", timeout); + else + rig.backend->failNextReadWith("k", timeout); + GcReadAhead reads(rig.op, rig.requests, rig.pool, 4); + try + { + switch (worker) + { + case Worker::Read: + reads.hintRead("k"); + answered = reads.takeRead("k").has_value(); + break; + case Worker::Head: + reads.hintHead("k"); + answered = reads.takeHead("k").has_value(); + break; + case Worker::Create: + { + auto take = reads.startCreate([](CasOperation & op) + { + EXPECT_TRUE(op.read("k", Retry::standard()).has_value()); + return IntentCreateResult{}; + }); + (void)take(); + answered = true; + break; + } + } + } + catch (...) + { + failure = DB::getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + }); + round.join(); + + const size_t requests = worker == Worker::Head ? rig.backend->headCount("k") : rig.backend->getCount("k"); + if (killed) + { + EXPECT_FALSE(answered); + EXPECT_NE(failure.find("injected request timeout"), String::npos) << failure; + EXPECT_EQ(requests, 1u) << "the failed request was reissued after the kill"; + } + else + { + EXPECT_TRUE(answered) << failure; + EXPECT_EQ(requests, 2u) << "positive control: a live query's worker retries"; + } + } + } +} + +/// A manual round's worker that fails to join the round's query sends nothing: outside the query its request would +/// not see the query's stop. The take gets the worker's failure. +TEST(CASGCReadAhead, WorkerOutsideTheRoundsQuerySendsNothing) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + enum class Worker : uint8_t { Read, Head, Create }; + for (const Worker worker : {Worker::Read, Worker::Head, Worker::Create}) + { + SCOPED_TRACE(fmt::format("worker {}", static_cast(worker))); + ReadAheadRig rig; + rig.put("k", "v"); + rig.backend->resetCounts(); + bool answered = false; + int code = 0; + String failure; + std::thread round([&] + { + DB::ThreadStatus thread_status; + CasKillableQuery query(getContext().context); + GcReadAhead reads(rig.op, rig.requests, rig.pool, 4); + /// Armed after the round's own attach, so the worker's switch is the one that fails. + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + try + { + switch (worker) + { + case Worker::Read: + reads.hintRead("k"); + answered = reads.takeRead("k").has_value(); + break; + case Worker::Head: + reads.hintHead("k"); + answered = reads.takeHead("k").has_value(); + break; + case Worker::Create: + { + auto take = reads.startCreate([](CasOperation & op) + { + EXPECT_TRUE(op.read("k", Retry::standard()).has_value()); + return IntentCreateResult{}; + }); + (void)take(); + answered = true; + break; + } + } + } + catch (const DB::Exception & e) + { + code = e.code(); + failure = e.message(); + } + }); + round.join(); + + EXPECT_FALSE(answered); + EXPECT_EQ(code, DB::ErrorCodes::CANNOT_SCHEDULE_TASK) << failure; + const size_t requests = worker == Worker::Head ? rig.backend->headCount("k") : rig.backend->getCount("k"); + EXPECT_EQ(requests, 0u) << "a worker outside the round's query sent a request"; + } +} + /// A create's state is released when its answer is taken, so a site that keeps a window of creates in flight holds /// at most that window, however many creates it sends. TEST(CASGCReadAhead, TakenCreateIsReleased) diff --git a/src/Disks/tests/gtest_cas_gc_rebuild.cpp b/src/Disks/tests/gtest_cas_gc_rebuild.cpp index fa8cae8ded6b1..c580bcca69ad1 100644 --- a/src/Disks/tests/gtest_cas_gc_rebuild.cpp +++ b/src/Disks/tests/gtest_cas_gc_rebuild.cpp @@ -13,8 +13,12 @@ #include #include #include +#include "cas_killable_query.h" #include "cas_sweep_test_support.h" #include "cas_test_helpers.h" +#include +#include +#include using namespace DB::Cas; using namespace DB::Cas::tests; @@ -28,6 +32,7 @@ namespace DB::ErrorCodes { extern const int CORRUPTED_DATA; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; } namespace @@ -1081,6 +1086,104 @@ TEST(CASGCRebuild, FailingLeaseGiveBackLeavesTheRefusalToTheCaller) << "a failed give-back leaves the claim in place"; } +/// A rebuild whose query is killed after its lease claim still gives the claim back: the give-back is owed +/// to the claimed resource, so the next rebuild is not refused as a competing leader. +TEST(CASGCRebuild, KilledRebuildGivesBackClaimedLease) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Layout & layout = store->layout(); + const ManifestId missing = seedLostStateWithMissingCommittedManifest(*backend, store); + ASSERT_FALSE(readObj(*backend, layout.gcStateKey()).has_value()); + + std::thread rebuild_thread([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + backend->arm(layout.manifestKey(missing), 1, [&] { query.kill(); }); + Gc killed(store, hexToU128("00000000000000000000000000000026")); + try + { + const RebuildReport refused = killed.rebuildBaseline(/*force*/ false); + EXPECT_FALSE(refused.performed); + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::QUERY_WAS_CANCELLED) << e.message(); + } + }); + rebuild_thread.join(); + + ASSERT_TRUE(backend->didFire()) << "the query was not killed after the lease claim"; + const auto given_back = readObj(*backend, layout.gcStateKey()); + ASSERT_TRUE(given_back.has_value()) << "the claim created gc/state"; + EXPECT_EQ(decodeGcState(given_back->bytes).lease.owner, DB::UInt128(0)) << "the claim was given back"; + + Gc next(store, hexToU128("00000000000000000000000000000027")); + const RebuildReport rep = next.rebuildBaseline(/*force*/ true); + EXPECT_EQ(rep.refusal.find("another GC leader holds the lease"), String::npos) << rep.refusal; +} + +/// A rebuild whose query is killed while it reads a fold seal reports the read's own failure, not an undecodable +/// seal that tells the operator to recreate the pool: for the adopted seal, and for the newest one found by +/// listing when `gc/state` is gone. +TEST(CASGCRebuild, KilledRebuildIsNotUndecodableSeal) +{ + for (const bool state_lost : {false, true}) + { + SCOPED_TRACE(state_lost ? "newest listed seal" : "adopted seal"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Layout & layout = store->layout(); + const RootNamespace ns{"00/aa@cas@"}; + writeBlobBody(*backend, layout, DB::UInt128(1)); + writeManifestRaw(*backend, layout, ns, ref(1, 0xAA), {blobEntryFor("a", DB::UInt128(1))}); + publishCommittedTransition(*backend, layout, ns, "tbl", std::nullopt, ref(1, 0xAA)); + Gc gc(store, kGc); + gc.runRegularRound(); + const GcState st = decodeGcState(readObj(*backend, layout.gcStateKey())->bytes); + ASSERT_GT(st.snap_generation, 0u); + if (state_lost) + { + const auto state_meta = headObj(*backend, layout.gcStateKey()); + ASSERT_TRUE(state_meta); + ASSERT_EQ(removeExact(*backend, layout.gcStateKey(), state_meta->etag), Removal::Removed); + } + + std::optional code; + String message; + std::thread rebuild_thread([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + backend->arm(layout.foldSealKey(st.snap_generation, st.snap_attempt), 1, [&] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected fold seal read failure"); + }); + try + { + Gc rebuild(store, hexToU128("00000000000000000000000000000028")); + (void)rebuild.rebuildBaseline(/*force*/ true); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + rebuild_thread.join(); + + ASSERT_TRUE(backend->didFire()) << "the rebuild never read the fold seal"; + ASSERT_TRUE(code) << "the killed rebuild returned normally"; + EXPECT_EQ(*code, DB::ErrorCodes::NETWORK_ERROR) << message; + EXPECT_NE(message.find("injected fold seal read failure"), String::npos) << message; + EXPECT_EQ(message.find("UNDECODABLE"), String::npos) << message; + } +} + /// The refusal is a wait, not a verdict: once the manifest is readable, a rebuild with a fresh GC identity, /// as each run of `clickhouse-disks cas-gc-rebuild` takes, counts the precommit. TEST(CASGCRebuild, RebuildRefusedForAnUnreadableManifestSucceedsOnceItIsReadable) diff --git a/src/Disks/tests/gtest_cas_gc_redelete_concurrency.cpp b/src/Disks/tests/gtest_cas_gc_redelete_concurrency.cpp index a4f03fb3c12b8..04facd6e733af 100644 --- a/src/Disks/tests/gtest_cas_gc_redelete_concurrency.cpp +++ b/src/Disks/tests/gtest_cas_gc_redelete_concurrency.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -25,6 +26,7 @@ #include #include #include +#include "cas_killable_query.h" #include "cas_test_helpers.h" namespace ProfileEvents @@ -37,6 +39,11 @@ namespace DB::ErrorCodes extern const int CANNOT_SCHEDULE_TASK; } +namespace DB::FailPoints +{ +extern const char thread_group_switcher_post_attach_failure[]; +} + using namespace DB::Cas; using namespace DB::Cas::tests; @@ -855,6 +862,61 @@ TEST(CASGCRedeleteConcurrency, SchedulingFailureAttemptsNothingAndTheNextRoundRe EXPECT_TRUE(allBlobsAbsent(*backend, *store)); } +/// A re-delete worker that fails to join the manual round's query deletes nothing: outside the query its request would +/// not see the query's stop. Its job fails and the round fails before its commit. The failpoint fails one switch only, +/// so the other jobs run in the query and delete. +TEST(CASGCRedeleteConcurrency, WorkerOutsideTheRoundsQueryDeletesNothing) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + auto backend = std::make_shared(); + auto store = openPoolWithIoConcurrency(backend, 4); + Gc gc(store, kGc); + publishThenDrop(*backend, store, gc); + ASSERT_NO_FATAL_FAILURE(driveUntilAllGraduated(*backend, gc, store, kFaultedBlob)); + + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + std::atomic armed{false}; + gc.setPhaseSink([&](const GcPhaseRecord & rec) + { + /// Armed after the round's own attach and its read-ahead, so a re-delete worker's switch is the one that fails. + if (rec.phase == "fold_seal_write") + { + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + armed = true; + } + else if (rec.phase == "pending_deletes") + { + DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + } + }); + + RoundReport progress; + int code = 0; + String message; + onKillableQueryThread([&](CasKillableQuery &) + { + try + { + gc.runRegularRound({}, /*allow_steal*/ true, UniversePolicy::Authoritative, &progress); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + gc.setPhaseSink({}); + + ASSERT_TRUE(armed.load()) << "the round never reached its fold seal"; + EXPECT_EQ(code, DB::ErrorCodes::CANNOT_SCHEDULE_TASK) << message; + EXPECT_EQ(progress.body_delete_failed, 1u); + EXPECT_EQ(progress.bodies_deleted, kBlobs - 1); + size_t present = 0; + for (uint64_t blob = 1; blob <= kBlobs; ++blob) + present += blobAbsent(*backend, store->layout(), numberedBlobHash(blob)) ? 0 : 1; + EXPECT_EQ(present, 1u) << "the worker outside the query deleted its blob"; +} + TEST(CASGCRedeleteConcurrency, EnqueueRefusalYieldsToLowerIndexWorkerFailure) { auto backend = std::make_shared(); diff --git a/src/Disks/tests/gtest_cas_gc_stop_start.cpp b/src/Disks/tests/gtest_cas_gc_stop_start.cpp index daad78bcdfca0..62652c7bdbee1 100644 --- a/src/Disks/tests/gtest_cas_gc_stop_start.cpp +++ b/src/Disks/tests/gtest_cas_gc_stop_start.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -373,6 +374,7 @@ TEST(CASGCStopStart, StopClearsLeadershipAfterManualRoundWithoutStart) TEST(CASGCStopStart, StartFailureRollsBackAndCanBeRetried) { + CAS_SKIP_WITHOUT_FAILPOINTS(); for (const char * failpoint : {FailPoints::cas_gc_scheduler_fail_before_heartbeat_worker_start, FailPoints::cas_gc_scheduler_fail_before_worker_start}) diff --git a/src/Disks/tests/gtest_cas_gc_teardown_stop.cpp b/src/Disks/tests/gtest_cas_gc_teardown_stop.cpp index 421cdb9764e7c..35c0a2178fb7f 100644 --- a/src/Disks/tests/gtest_cas_gc_teardown_stop.cpp +++ b/src/Disks/tests/gtest_cas_gc_teardown_stop.cpp @@ -278,14 +278,14 @@ TEST(CASGCTeardownStop, OpenPlaneSleepReturnsAtOnceOnceTeardownBegan) auto store = openPlainPool(backend); store->beginTeardown(); - auto paused = std::async(std::launch::async, [&store] { store->openRequests().pause(60'000); }); + auto paused = std::async(std::launch::async, [&store] { store->openRequests().sleepFor(60'000); }); ASSERT_EQ(paused.wait_for(std::chrono::seconds(10)), std::future_status::ready) << "the open plane's sleep must observe the arm; a plain sleep holds for the full minute"; /// Clearing the seam must put the interruptible sleep back, not the engine's plain one. store->setCasRetrySleepForTest([](uint64_t) {}); store->setCasRetrySleepForTest({}); - auto paused_again = std::async(std::launch::async, [&store] { store->openRequests().pause(60'000); }); + auto paused_again = std::async(std::launch::async, [&store] { store->openRequests().sleepFor(60'000); }); EXPECT_EQ(paused_again.wait_for(std::chrono::seconds(10)), std::future_status::ready) << "resetting the retry-sleep seam left the open plane on the plain sleep"; } diff --git a/src/Disks/tests/gtest_cas_namespace_janitor.cpp b/src/Disks/tests/gtest_cas_namespace_janitor.cpp index 5ce77394a95d0..5df4369eafe26 100644 --- a/src/Disks/tests/gtest_cas_namespace_janitor.cpp +++ b/src/Disks/tests/gtest_cas_namespace_janitor.cpp @@ -2,6 +2,12 @@ #include #include #include +#include +#include +#include + +#include +#include using namespace DB::Cas; using namespace DB::Cas::tests; @@ -9,6 +15,7 @@ using namespace DB::Cas::tests; namespace DB::ErrorCodes { extern const int NETWORK_ERROR; + extern const int READONLY; } namespace @@ -698,6 +705,94 @@ TEST(CASNamespaceJanitor, CursorPublicationFailureIsLeakOnly) EXPECT_FALSE(readObj(*backend, dead).has_value()); } +namespace +{ + +/// The first cursor write loses its reply without landing; `on_settle` runs in the read that settles it. +class LostCursorWriteBackend : public CountingBackend +{ +public: + std::function on_settle; + bool write_failed = false; + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (key.ends_with("/gc/maintenance_state") && !write_failed) + { + write_failed = true; + throw Poco::TimeoutException("LostCursorWriteBackend: the cursor write timed out"); + } + return CountingBackend::write(key, bytes, expected_value, access); + } + + std::optional read(const String & key, DB::Cas::TransportAccess & access) override + { + if (key.ends_with("/gc/maintenance_state") && write_failed && on_settle) + std::exchange(on_settle, nullptr)(); + return CountingBackend::read(key, access); + } +}; + +} + +/// A cursor write whose outcome stays unknown because the query stopped in its settling read ends the page with the +/// unresolved 210 instead of an anomaly. A live owner resends the cursor and publishes it. +TEST(CASNamespaceJanitor, UnresolvedCursorWriteOfAStoppedQueryPropagates) +{ + for (const bool kill : {true, false}) + { + SCOPED_TRACE(kill ? "killed in the settling read" : "live"); + auto backend = std::make_shared(); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, DB::Cas::kDefaultRequestWindowMs); + const Layout layout("p"); + seedCatalog(*backend, layout); + const String dead = layout.refCkptKey(life("dead", 145)); + createObj(*backend, dead, "bytes"); + + int code = 0; + String message; + std::optional result; + std::thread caller([&] + { + DB::ThreadStatus thread_status; + CasKillableQuery query(::getContext().context); + if (kill) + backend->on_settle = [&query] + { + query.kill(); + throw Poco::TimeoutException("LostCursorWriteBackend: the settling read timed out"); + }; + try + { + result = NamespaceJanitor(requests, layout, 100).runOnePage(false, [] { return true; }); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + caller.join(); + + EXPECT_FALSE(readObj(*backend, dead).has_value()); + if (kill) + { + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << message; + EXPECT_NE(message.find("unresolved"), String::npos) << message; + EXPECT_FALSE(result.has_value()); + } + else + { + EXPECT_EQ(code, 0) << message; + ASSERT_TRUE(result.has_value()); + EXPECT_TRUE(result->anomalies.empty()); + EXPECT_TRUE(readState(requests, layout).state.has_value()) << "the resent cursor was published"; + } + } +} + /// The write inside `catch (...)` (the reset after a LIST failure) is admitted `once`: an unmodeled, /// unresolvable write attempt must give up after its one exact resolve read rather than looping through /// `Retry::standard()`'s backoff. `write_attempts == 1` is the discriminator: under `standard`, the same @@ -719,6 +814,153 @@ TEST(CASGcMaintenanceState, CatchPathWriteIsOnce) << "the catch-path reset settles by its one resolve read and gives up rather than reissuing"; } +namespace +{ + +/// Every `LIST` runs `on_list`, then fails with a transport error. +class FailingListBackend : public CountingBackend +{ +public: + std::function on_list; + + DB::Cas::Backend::RawListPage list(const String &, const String &, size_t, DB::Cas::TransportAccess &) override + { + if (on_list) + on_list(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "list failed"); + } +}; + +} + +/// A stopped query's failed first `LIST` ends the page with that failure and keeps the scan's cursor: the stop vetoed +/// the optional reset. A live owner's failed first `LIST` resets the cursor. +TEST(CASNamespaceJanitor, StoppedQuerysFailedListKeepsTheCursor) +{ + for (const bool kill : {true, false}) + { + SCOPED_TRACE(kill ? "killed in the LIST" : "live"); + auto backend = std::make_shared(); + FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + const Layout layout("p"); + createObj(*backend, layout.gcMaintenanceStateKey(), encodeGcMaintenanceState({.janitor_cursor = "kept"})); + const uint64_t writes_before = backend->writeCount(layout.gcMaintenanceStateKey()); + + int code = 0; + String message; + onKillableQueryThread([&](CasKillableQuery & query) + { + if (kill) + backend->on_list = [&query] { query.kill(); }; + try + { + (void)NamespaceJanitor(requests, layout, 100).runOnePage(false, [] { return true; }, /*first_page_of_pass=*/true); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + + EXPECT_NE(code, 0); + if (kill) + { + EXPECT_EQ(backend->writeCount(layout.gcMaintenanceStateKey()), writes_before) << "a reset was sent: " << message; + EXPECT_EQ(readState(requests, layout).state->janitor_cursor, "kept"); + } + else + { + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << message; + EXPECT_TRUE(readState(requests, layout).state->janitor_cursor.empty()) << "the live owner reset the cursor"; + } + } +} + +/// A cursor reset after a failed `LIST` that may still land is what the caller learns, not the listing error. +TEST(CASNamespaceJanitor, AnUnresolvedResetAfterAFailedListIsReported) +{ + auto backend = std::make_shared(); + FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + const Layout layout("p"); + + const String message = DB::Cas::tests::messageOf(DB::ErrorCodes::NETWORK_ERROR, + [&] { (void)NamespaceJanitor(requests, layout, 100).runOnePage(false, [] { return true; }, /*first_page_of_pass=*/true); }); + EXPECT_NE(message.find("cursor reset after a failed LIST: the write is unresolved"), String::npos) << message; +} + +namespace +{ + +/// The janitor's cursor write: refused as `READONLY`, after killing the query when `kill`. +struct RefusedCursorRound +{ + int code = 0; + String message; + std::set phases; +}; + +RefusedCursorRound runRoundWithARefusedCursorWrite(bool kill) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + const Layout & layout = store->layout(); + const RootNamespace live_namespace{"00/live@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + createObj(*backend, layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{.life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, .last_epoch_seal = std::nullopt}, 1)); + createObj(*backend, layout.refCkptKey(life("dead", 153)), "checkpoint"); + + RefusedCursorRound out; + Gc gc(store, UInt128{154}); + gc.setPhaseSink([&](const GcPhaseRecord & record) { out.phases.insert(record.phase); }); + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->onBeforeWrite(layout.gcMaintenanceStateKey(), [&query, kill] + { + if (kill) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "the store is read-only"); + }); + try + { + (void)runRegularRoundReclaiming(gc); + } + catch (const DB::Exception & e) + { + out.code = e.code(); + out.message = e.message(); + } + }); + gc.setPhaseSink({}); + return out; +} + +} + +/// A stopped query's refused cursor write ends the round with the refusal, before ref cleanup starts. A live owner +/// records an anomaly and goes on to ref cleanup. +TEST(CASNamespaceJanitorIntegration, RefusedCursorWriteOfAStoppedQueryEndsTheRound) +{ + { + SCOPED_TRACE("killed in the cursor write"); + const auto out = runRoundWithARefusedCursorWrite(/*kill=*/true); + EXPECT_EQ(out.code, DB::ErrorCodes::READONLY) << out.message; + EXPECT_NE(out.message.find("the store is read-only"), String::npos) << out.message; + EXPECT_TRUE(out.phases.contains("namespace_cleanup")); + EXPECT_FALSE(out.phases.contains("ref_object_cleanup")) << "ref cleanup started"; + } + { + SCOPED_TRACE("live"); + const auto out = runRoundWithARefusedCursorWrite(/*kill=*/false); + EXPECT_EQ(out.code, 0) << out.message; + EXPECT_TRUE(out.phases.contains("ref_object_cleanup")); + } +} + TEST(CASNamespaceJanitorIntegration, RegularGcRoundDeletesDeadNamespaceBytes) { auto backend = std::make_shared(); diff --git a/src/Disks/tests/gtest_cas_own_creating_cleanup.cpp b/src/Disks/tests/gtest_cas_own_creating_cleanup.cpp index 369ed5cbf831a..371b16faa731e 100644 --- a/src/Disks/tests/gtest_cas_own_creating_cleanup.cpp +++ b/src/Disks/tests/gtest_cas_own_creating_cleanup.cpp @@ -7,9 +7,15 @@ #include +#include #include #include +namespace DB::ErrorCodes +{ +extern const int ABORTED; +} + namespace ProfileEvents { extern const Event CASOwnCreatingCancelled; @@ -109,3 +115,43 @@ TEST(CASOwnCreatingCleanup, AStopRequestBeforeThePassSendsNothing) EXPECT_EQ(requestTotal(*backend) - before, 0u); EXPECT_EQ(ownCreatingRows(op, store), 3u); } + +/// A stop request that lands while the first row's cancel loses the catalog to another writer ends the pass at +/// that cancel's next submission, before any further catalog write. +TEST(CASOwnCreatingCleanup, AStopRequestDuringARowsConflictEndsThePass) +{ + auto backend = std::make_shared(); + PoolConfig config{.pool_prefix = "p", .server_root_id = "test", .gc_fold_max_defer_rounds = 0}; + config.mount_renew_period = std::chrono::milliseconds{3'600'000}; + config.retry_sleep_fn = [](uint64_t) {}; + PoolPtr store = Pool::open(backend, config); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + seedThreeOwnRows(op, store); + const String key = store->layout().refCatalogKey(); + + std::atomic stop = false; + size_t catalog_writes = 0; + bool in_hook = false; + /// Every catalog write of the pass meets an incarnation another writer just moved, as on a hot catalog. + backend->onBeforeWrite(key, [&] + { + if (in_hook) + return; + in_hook = true; + ++catalog_writes; + CasRequests other_requests = openRequestsForTest(backend); + CasOperation other = other_requests.admit(); + const auto current = other.read(key, Retry::once()); + EXPECT_TRUE(current && std::holds_alternative(other.replace(key, current->bytes, current->etag, Retry::once()))); + in_hook = false; + stop = true; + }); + + const uint64_t cancels = ownCancels(); + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { store->cancelIdleOwnCreatingRows([&] { return stop.load(); }); }); + backend->onBeforeWrite(key, {}); + EXPECT_EQ(catalog_writes, 1u) << "the stopped cancel submitted again"; + EXPECT_EQ(ownCancels() - cancels, 0u); + EXPECT_EQ(ownCreatingRows(op, store), 3u); +} diff --git a/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp b/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp index 8117cb7e1db96..09bcba8b31d14 100644 --- a/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp +++ b/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp @@ -4,12 +4,26 @@ #include #include #include +#include "cas_killable_query.h" #include "cas_sweep_test_support.h" #include "cas_test_helpers.h" +#include +#include +#include #include +#include +#include +#include #include +namespace DB::ErrorCodes +{ + extern const int NETWORK_ERROR; + extern const int QUERY_WAS_CANCELLED; + extern const int READONLY; +} + using namespace DB::Cas; using namespace DB::Cas::tests; @@ -144,6 +158,63 @@ TEST(CASSweepDeletionPremise, AConsumedEpochSealWithACleanTailDeletes) EXPECT_TRUE(warnings.empty()) << "nothing was retained, so nothing is warned about"; } +/// The round commits its orphan cursor before the namespace janitor runs, so the bodies that commit nominated are +/// deleted even when the janitor then ends a killed round with its failure; a live round treats the same janitor +/// failure as a leak and succeeds. +TEST(CASSweepDeletionPremise, AKilledJanitorAfterTheCommitLeavesNoNominatedBody) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + OrphanFixture f(/*gc_fold_max_defer_rounds*/0); + const Layout & layout = f.store->layout(); + seedCursorAt(*f.backend, layout, f.ns, RefTxnId{kBuildEpoch + 1, 1}); + const String dead_log = layout.refLogKey( + NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-kill"}, UInt128{0xDB}), RefTxnId{1, 1}); + { + OperationForTest op(*f.backend); + ASSERT_TRUE(std::holds_alternative((*op).create(dead_log, "dead residue", Retry::once()))); + } + + int code = 0; + String message; + uint64_t nominations_deleted = 0; + std::atomic fired{false}; + onKillableQueryThread([&](CasKillableQuery & query) + { + f.backend->onBeforeBulkRemove([&] + { + if (fired.exchange(true)) + return; + if (killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected janitor batch delete refusal"); + }); + Gc gc(f.store, hexToU128("00000000000000000000000000000001")); + gc.setPhaseSink([&](const GcPhaseRecord & phase) + { + if (phase.phase == "orphan_sweep") + nominations_deleted = phase.metrics.at("deleted"); + }); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + f.backend->onBeforeBulkRemove({}); + }); + + ASSERT_TRUE(fired.load()) << "the round sent no janitor batch delete"; + EXPECT_EQ(code, killed ? DB::ErrorCodes::READONLY : 0) << message; + EXPECT_EQ(nominations_deleted, 1u); + EXPECT_FALSE(f.orphanExists()) << "the nominated body outlived the commit that nominated it"; + } +} + /// Uncertainty rule, hold arm. The cursor HAS consumed epoch 1's seal, so rule (1) alone would let the /// body go -- but the namespace is held, which means the fold could not account for everything at or /// above the held position. A held namespace retains everything under it. @@ -761,3 +832,168 @@ TEST(CASSweepDeletionPremise, NamespaceWorkBudgetCapsDistinctViewsPerPage) ++surviving; EXPECT_EQ(surviving, 1u) << "exactly one candidate remains -- the one whose namespace had no budget left"; } + +namespace +{ + +/// Runs `on_read` once, before the first read of a key containing `read_substring`, and `on_remove` once, before +/// the remove of `remove_key`. A hook that throws replaces that request's answer. +class SweepFaultBackend final : public InMemoryBackend +{ +public: + String read_substring; + std::function on_read; + String remove_key; + std::function on_remove; + + std::optional read(const String & key, TransportAccess & access) override + { + if (on_read && key.find(read_substring) != String::npos) + std::exchange(on_read, {})(); + return InMemoryBackend::read(key, access); + } + + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + if (on_remove && key == remove_key) + std::exchange(on_remove, {})(); + return InMemoryBackend::remove(key, expected_value, access); + } +}; + +/// `OrphanFixture` with three eligible, unowned manifests in build 5 and a cursor past their epoch's seal, so a live +/// sweep deletes all three. +struct KilledSweepFixture +{ + std::shared_ptr backend = std::make_shared(); + PoolPtr store; + RootNamespace ns{"00/aa@cas@"}; + std::vector orphan_keys; + + KilledSweepFixture() + { + store = openPoolForTest(backend); + casAdmitRecoverableEntry(*backend, store->layout(), ns); + for (const uint64_t ordinal : {0xABu, 0xACu, 0xADu}) + { + const ManifestRef orphan = ref(5, ordinal); + writeManifestRaw(*backend, store->layout(), ns, orphan, {blobEntryFor("a", DB::UInt128(ordinal))}); + orphan_keys.push_back(store->layout().manifestKey(ManifestId{ns, orphan})); + } + std::sort(orphan_keys.begin(), orphan_keys.end()); + setWatermarkMinActive(*backend, store->layout(), kServerRoot, kBuildEpoch, /*min_active_build_sequence*/6); + seedCursorAt(*backend, store->layout(), ns, RefTxnId{kBuildEpoch + 1, 1}); + } + + bool exists(const String & key) const + { + OperationForTest op(*backend); + return (*op).head(key, Retry::once()).has_value(); + } +}; + +struct SweepRun +{ + int code = 0; + uint64_t deleted = 0; + std::vector warnings; +}; + +/// The decommission drain's call, on a thread of a query; `arm` runs on that thread first. +SweepRun sweepOnQueryThread(KilledSweepFixture & f, const std::function & arm) +{ + SweepRun out; + std::thread caller([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + arm(query); + try + { + out.deleted = sweepNamespace(*f.store, f.ns, buildPrefix(5), &out.warnings); + } + catch (const DB::Exception & e) + { + out.code = e.code(); + } + }); + caller.join(); + return out; +} + +} + +/// A killed query's sweep stops at the next key with the query's own error, also inside one build prefix: no key of +/// the prefix is deleted after the kill. +TEST(CASSweepDeletionPremise, KilledQueryEndsTheSweepAtTheNextKey) +{ + KilledSweepFixture f; + const SweepRun run = sweepOnQueryThread(f, [](CasKillableQuery & query) { query.kill(); }); + + EXPECT_EQ(run.code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + for (const String & key : f.orphan_keys) + EXPECT_TRUE(f.exists(key)) << key; + + const SweepRun live = sweepOnQueryThread(f, [](CasKillableQuery &) {}); + EXPECT_EQ(live.code, 0); + EXPECT_EQ(live.deleted, f.orphan_keys.size()) << "positive control: a live sweep deletes every key"; +} + +/// A query killed while the first key's delete is in flight: that delete lands, and the sweep ends at the next key +/// with the query's error, so the other keys of the prefix stay. +TEST(CASSweepDeletionPremise, KilledQueryEndsTheSweepAtTheKeyAfterTheKill) +{ + KilledSweepFixture f; + const SweepRun run = sweepOnQueryThread(f, [&](CasKillableQuery & query) + { + f.backend->remove_key = f.orphan_keys.front(); + f.backend->on_remove = [&query] { query.kill(); }; + }); + + EXPECT_EQ(run.code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_FALSE(f.exists(f.orphan_keys.front())) << "the delete in flight at the kill"; + for (size_t i = 1; i < f.orphan_keys.size(); ++i) + EXPECT_TRUE(f.exists(f.orphan_keys[i])) << "a key after the kill was deleted: " << f.orphan_keys[i]; +} + +/// A delete of the last key that fails after the kill ends the sweep with that failure, not with a warning. +TEST(CASSweepDeletionPremise, KilledQuerysFailedDeleteOfTheLastKeyPropagates) +{ + KilledSweepFixture f; + const SweepRun run = sweepOnQueryThread(f, [&](CasKillableQuery & query) + { + f.backend->remove_key = f.orphan_keys.back(); + f.backend->on_remove = [&query] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected delete failure"); + }; + }); + + EXPECT_EQ(run.code, DB::ErrorCodes::NETWORK_ERROR); + EXPECT_TRUE(f.exists(f.orphan_keys.back())); + for (size_t i = 0; i + 1 < f.orphan_keys.size(); ++i) + EXPECT_FALSE(f.exists(f.orphan_keys[i])) << "the keys before the kill were deleted: " << f.orphan_keys[i]; + EXPECT_TRUE(run.warnings.empty()) << fmt::format("{}", fmt::join(run.warnings, "; ")); +} + +/// A protection-view read that fails after the kill ends the sweep with that failure, not with a skipped namespace. +TEST(CASSweepDeletionPremise, KilledQuerysFailedProtectionReadPropagates) +{ + KilledSweepFixture f; + const SweepRun run = sweepOnQueryThread(f, [&](CasKillableQuery & query) + { + f.backend->read_substring = "_ckpt"; + f.backend->on_read = [&query] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected checkpoint read failure"); + }; + }); + + EXPECT_EQ(run.code, DB::ErrorCodes::NETWORK_ERROR); + for (const String & key : f.orphan_keys) + EXPECT_TRUE(f.exists(key)) << key; + EXPECT_TRUE(run.warnings.empty()) << fmt::format("{}", fmt::join(run.warnings, "; ")); +} From b2f32fdd16b716b374d3c89f42752339474ce544 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:28:10 +0100 Subject: [PATCH 13/47] Handle a stopped owner in CAS decommission, fsck and pool migration The decommission drain checks a killed query per page of the manifest listing and per key. `runBounded` workers check their thread group before any request. Catches in the tools leave a query's stored exception unannotated. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../Primitives/CasBoundedRun.h | 5 +- .../Tools/CasDecommission.cpp | 30 ++- .../ContentAddressed/Tools/CasFsck.cpp | 7 +- .../ContentAddressed/Tools/CasMigratePool.cpp | 17 +- src/Disks/tests/gtest_cas_decommission.cpp | 250 ++++++++++++++++++ src/Disks/tests/gtest_cas_fsck.cpp | 68 +++++ src/Disks/tests/gtest_cas_migrate_pool.cpp | 185 +++++++++++++ 7 files changed, 544 insertions(+), 18 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasBoundedRun.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasBoundedRun.h index af193e425faad..9414c3a036953 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasBoundedRun.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasBoundedRun.h @@ -1,5 +1,7 @@ #pragma once +#include #include +#include #include #include #include @@ -57,12 +59,13 @@ void runBounded(ThreadPool & pool, ThreadName thread_name, size_t count, const J { if constexpr (HasBeforeSubmit) job.beforeSubmit(i); - handles.emplace_back(runner.enqueueAndGiveOwnership([&job, &failed, i] + handles.emplace_back(runner.enqueueAndGiveOwnership([&job, &failed, i, group = CurrentThread::getGroup()] { if (failed.load()) return; try { + throwUnlessInThreadGroup(group, "CAS tool worker"); job(i); } catch (...) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasDecommission.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasDecommission.cpp index 973d6de56c331..b13f3c5f50e5c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasDecommission.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasDecommission.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -54,13 +55,16 @@ std::string_view removalName(Removal r) /// /// A per-object failure — a backend exception, a `Mismatch` or `Gone` outcome, or an object /// disappearing between `LIST` and `HEAD` — is recorded as a warning and does not prevent the remaining -/// objects from being attempted while `op` is still admitted. Returns only the objects whose -/// exact-incarnation delete was reported as `Removed`. +/// objects from being attempted while `op` is still admitted. A stopped owner ends the drain at the next object with +/// its verdict; a delete that failed after its query stopped ends it with that failure. +/// Returns only the objects whose exact-incarnation delete was reported as `Removed`. uint64_t deleteListedPrefix(CasOperation & op, const String & prefix, std::vector & warnings) { uint64_t deleted = 0; op.forEachListedKey(prefix, [&](const ListedKey & listed) { + throwIfQueryStopped(); + throwIfBackgroundStopped(); try { std::optional etag = listed.etag; @@ -84,6 +88,7 @@ uint64_t deleteListedPrefix(CasOperation & op, const String & prefix, std::vecto } catch (...) { + rethrowIfStoppedOwnersFailure(); warnings.push_back("decommission drain: " + listed.key + " delete failed: " + getCurrentExceptionMessage(/*with_stacktrace=*/false)); return op.admitted(); @@ -350,6 +355,7 @@ void drainVictim(Pool & admin, const CasRefCatalog::Snapshot & catalog_cut, cons std::vector> owned_lives; for (const CatalogEntry & entry : catalog_cut.catalog.entries) { + throwIfQueryStopped(); if (entry.ns.string() != victim_srid && !entry.ns.string().starts_with(victim_namespace_prefix)) continue; const auto life = catalog_cut.life_index.resolve(entry.incarnation); @@ -361,6 +367,7 @@ void drainVictim(Pool & admin, const CasRefCatalog::Snapshot & catalog_cut, cons for (const auto & [selected_entry, life] : owned_lives) { + throwIfQueryStopped(); const RootNamespace & ns = life.ns; const String & ns_str = ns.string(); @@ -428,15 +435,24 @@ void drainVictim(Pool & admin, const CasRefCatalog::Snapshot & catalog_cut, cons { const String debris_prefix = admin.layout().casManifestsServerPrefix(victim_srid); std::set> groups; /// (namespace, writer epoch, build sequence) - op.forEachListedKey(debris_prefix, [&](const ListedKey & listed) + /// Checked before each page is requested and again once it arrives, for a kill that landed during the fetch. + String cursor; + do { - if (const auto parsed = admin.layout().parseManifestKey(listed.key)) - groups.emplace(parsed->root_namespace.string(), parsed->ref.writer_epoch, parsed->ref.build_sequence); - return true; - }, Retry::standard()); + throwIfQueryStopped(); + ListPage page = op.list(debris_prefix, cursor, CasOperation::kCasListPageKeys, Retry::standard()); + throwIfQueryStopped(); + for (const ListedKey & listed : page.keys) + if (const auto parsed = admin.layout().parseManifestKey(listed.key)) + groups.emplace(parsed->root_namespace.string(), parsed->ref.writer_epoch, parsed->ref.build_sequence); + cursor = std::move(page.next_cursor); + } while (!cursor.empty()); for (const auto & [ns_str, writer_epoch, build_sequence] : groups) + { + throwIfQueryStopped(); report.manifest_debris_removed += sweepNamespace( admin, RootNamespace(ns_str), BuildPrefix{writer_epoch, build_sequence}, &report.warnings); + } } /// Drain the victim's own `/staging//` area. The live-mount staging helper uses diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasFsck.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasFsck.cpp index e47d61b8e1c1f..352e831528260 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasFsck.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasFsck.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -490,7 +491,8 @@ std::optional walkRefStream( } catch (const Exception & e) { - if (e.code() == ErrorCodes::TIMEOUT_EXCEEDED) + /// A query's stored cause is no finding about the chain, whatever its code. + if (e.code() == ErrorCodes::TIMEOUT_EXCEEDED || isQueryStoredCause(std::current_exception())) throw; deadline.rethrowIfOutOfTime(op, e, kWalkingRefs); record_failure(e.code() == ErrorCodes::CORRUPTED_DATA, e.message()); @@ -2041,7 +2043,8 @@ LegacyMarkerRemoval removeLegacyMarkers(Pool & pool, const std::vector & { if (on_progress) on_progress(deleted.load()); - e.addMessage(fmt::format("{} legacy marker(s) deleted before the stop; run again to continue", deleted.load())); + addMessageUnlessQueryStoredCause(e, fmt::format("{} legacy marker(s) deleted before the stop; run again to continue", + deleted.load())); throw; } return {deleted.load(), changed.load()}; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasMigratePool.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasMigratePool.cpp index bd4493b87ffb7..14ee8473bd902 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasMigratePool.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasMigratePool.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -544,7 +545,7 @@ class Migration uint64_t last_progress_ms = pool.bootMsNow(); while (!watched.empty()) { - op.pause(options.poll_step_ms); + op.sleepFor(options.poll_step_ms); /// Taken before the reads: it can confirm that a token held, never date a sighting. const uint64_t sample_ms = pool.bootMsNow(); if (sample_ms >= last_progress_ms + kProgressEveryMs) @@ -577,7 +578,7 @@ class Migration } say(fmt::format("M2: waiting {} ms in which no mount slot and no GC lease may move", grace_ms)); - op.pause(grace_ms); + op.sleepFor(grace_ms); checkUnchanged(tokens, pairs, Window::BeforeFloor); say(fmt::format("M2: {} mount slot(s), {} fenced; no slot and no GC lease moved in {} ms", slot_keys.size(), fenced, grace_ms)); @@ -705,8 +706,8 @@ class Migration { if (e.code() != ErrorCodes::CORRUPTED_DATA) throw; - e.addMessage("M3: GC of this build refuses a source-edge run of the fold seal that gc/state adopts. The run " - "stopped before the floor was raised to 4"); + addMessageUnlessQueryStoredCause(e, "M3: GC of this build refuses a source-edge run of the fold seal that " + "gc/state adopts. The run stopped before the floor was raised to 4"); throw; } } @@ -836,8 +837,8 @@ class Migration } catch (Exception & e) { - e.addMessage("an intent create failed; nothing was written after the intents, and a rerun passes only once the " - "store accepts the create"); + addMessageUnlessQueryStoredCause(e, "an intent create failed; nothing was written after the intents, and a rerun " + "passes only once the store accepts the create"); throw; } if (!result.confirmed()) @@ -965,8 +966,8 @@ class Migration } catch (Exception & e) { - e.addMessage("M9: {} marker(s) removed in earlier pages; the pool is migrated, and a rerun or `cas-fsck --fix " - "legacy-markers` removes the rest", report.legacy_markers_deleted); + addMessageUnlessQueryStoredCause(e, fmt::format("M9: {} marker(s) removed in earlier pages; the pool is migrated, and " + "a rerun or `cas-fsck --fix legacy-markers` removes the rest", report.legacy_markers_deleted)); throw; } meter.add(page.size()); diff --git a/src/Disks/tests/gtest_cas_decommission.cpp b/src/Disks/tests/gtest_cas_decommission.cpp index 66c9aa395142b..0b6605847b9fa 100644 --- a/src/Disks/tests/gtest_cas_decommission.cpp +++ b/src/Disks/tests/gtest_cas_decommission.cpp @@ -1,12 +1,16 @@ #include "cas_test_helpers.h" #include +#include #include #include #include #include +#include #include #include #include +#include +#include #include #include #include @@ -14,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +36,8 @@ namespace DB::ErrorCodes extern const int ABORTED; extern const int BAD_ARGUMENTS; extern const int CORRUPTED_DATA; + extern const int NETWORK_ERROR; + extern const int QUERY_WAS_CANCELLED; } using namespace DB; @@ -1613,6 +1620,249 @@ TEST_F(CASDecommission, ResumesOverItsOwnTombstone) namespace { +/// Runs `on_first_staging_delete` before the first delete under the victim's staging prefix, and counts the +/// listings of each prefix. +class StopOnFirstStagingDeleteBackend : public InMemoryBackend +{ +public: + using InMemoryBackend::list; + + std::function on_first_staging_delete; + + size_t listingsOf(const String & prefix) const + { + std::lock_guard lock(mutex); + return static_cast(std::count(listed_prefixes.begin(), listed_prefixes.end(), prefix)); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + { + std::lock_guard lock(mutex); + listed_prefixes.push_back(prefix); + } + return InMemoryBackend::list(prefix, cursor, limit, access); + } + + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + if (on_first_staging_delete && key.starts_with("p/staging/victim/")) + std::exchange(on_first_staging_delete, {})(); + return InMemoryBackend::remove(key, expected_value, access); + } + +private: + mutable std::mutex mutex; + std::vector listed_prefixes; +}; + +} + +/// A decommission whose owner stops during the staging drain deletes nothing more and lists no further prefix: +/// the stop ends the run instead of becoming a warning per remaining object. +TEST_F(CASDecommission, OwnerStopDuringTheDrainEndsTheRun) +{ + auto backend = startVictim(std::make_shared()); + seed("p/staging/victim/a_first.tmp"); + seed("p/staging/victim/b_second.tmp"); + seed("p/roots/victim/c_third"); + std::atomic stopped = false; + size_t roots_listings_at_stop = 0; + backend->on_first_staging_delete = [&] + { + roots_listings_at_stop = backend->listingsOf("p/roots/victim/"); + stopped = true; + }; + + { + const auto owner = OwnerScope::background([&stopped] + { + if (stopped) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); + expectThrowsCode(ErrorCodes::ABORTED, [&] { (void)run("admin"); }); + } + + ASSERT_TRUE(stopped) << "premise: the drain reached the staging prefix"; + EXPECT_FALSE(exists("p/staging/victim/a_first.tmp")) << "the delete the stop landed in"; + EXPECT_TRUE(exists("p/staging/victim/b_second.tmp")); + EXPECT_TRUE(exists("p/roots/victim/c_third")); + EXPECT_EQ(backend->listingsOf("p/roots/victim/"), roots_listings_at_stop) << "the stopped drain listed the roots"; +} + +/// A killed query ends the key drain at the next key with its own error, and a delete that failed after the kill ends +/// it with that delete's error, not with a warning: the next staging key and the roots stay. +TEST_F(CASDecommission, KilledQueryEndsTheKeyDrainAtTheNextKey) +{ + for (const bool delete_fails : {false, true}) + { + SCOPED_TRACE(delete_fails ? "the delete fails after the kill" : "the delete succeeds after the kill"); + auto backend = startVictim(std::make_shared()); + seed("p/staging/victim/a_first.tmp"); + seed("p/staging/victim/b_second.tmp"); + seed("p/roots/victim/c_third"); + size_t roots_listings_at_kill = 0; + int code = 0; + String message; + std::thread killed([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + backend->on_first_staging_delete = [&] + { + roots_listings_at_kill = backend->listingsOf("p/roots/victim/"); + query.kill(); + if (delete_fails) + throw Exception(ErrorCodes::NETWORK_ERROR, "injected staging delete failure"); + }; + try + { + (void)run("admin"); + } + catch (const Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + killed.join(); + + EXPECT_EQ(code, delete_fails ? ErrorCodes::NETWORK_ERROR : ErrorCodes::QUERY_WAS_CANCELLED) << message; + EXPECT_EQ(exists("p/staging/victim/a_first.tmp"), delete_fails) << "the delete the kill landed in"; + EXPECT_TRUE(exists("p/staging/victim/b_second.tmp")) << "the drain deleted a key after the kill"; + EXPECT_TRUE(exists("p/roots/victim/c_third")); + EXPECT_EQ(backend->listingsOf("p/roots/victim/"), roots_listings_at_kill) << "the killed drain listed the roots"; + } +} + +namespace +{ + +/// Runs `on_list` once, before the first listing whose prefix `matches` accepts, and records every listed prefix. +class HookFirstListingBackend : public InMemoryBackend +{ +public: + using InMemoryBackend::list; + + std::function matches; + std::function on_list; + /// When set, a page holds at most this many keys, as a store with a small `list_object_keys_size` answers. + size_t page_cap = 0; + + size_t listingsOf(const String & prefix) const + { + std::lock_guard lock(mutex); + return static_cast(std::count(listed_prefixes.begin(), listed_prefixes.end(), prefix)); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + std::function hook; + { + std::lock_guard lock(mutex); + listed_prefixes.push_back(prefix); + if (on_list && matches && matches(prefix)) + hook = std::exchange(on_list, {}); + } + if (hook) + hook(); + return InMemoryBackend::list(prefix, cursor, page_cap ? std::min(limit, page_cap) : limit, access); + } + +private: + mutable std::mutex mutex; + std::vector listed_prefixes; +}; + +/// Staged manifests of one build no ref names: several keys in one manifest group of `ns_str`. Returns their keys. +std::vector seedOrphanManifestGroup(Pool & victim, const String & ns_str, uint32_t keys) +{ + std::vector out; + for (uint32_t ordinal = 1; ordinal <= keys; ++ordinal) + { + const ManifestRef ref{.writer_epoch = victim.writerEpoch(), .build_sequence = 99, .manifest_ordinal = ordinal}; + const ManifestId id = writeManifestRaw(*victim.poolBackendPtr(), victim.layout(), RootNamespace(ns_str), ref, {}); + out.push_back(victim.layout().manifestKey(id)); + } + return out; +} + +} + +/// A killed query ends the drain at the next scan head with its own error: before the first namespace, at the +/// next page of the manifest listing, or at the next key of a group that holds several. The tombstone stays, and a rerun resumes. +TEST_F(CASDecommission, KilledQueryEndsTheDrainAtTheNextScanHead) +{ + enum class KillAt : uint8_t { BeforeTheRun, DebrisListing, GroupListing }; + for (const KillAt kill_at : {KillAt::BeforeTheRun, KillAt::DebrisListing, KillAt::GroupListing}) + { + SCOPED_TRACE(kill_at == KillAt::BeforeTheRun ? "before the run" + : kill_at == KillAt::DebrisListing ? "at the debris listing" : "at the group's key listing"); + std::vector group_keys; + auto backend = startVictim(std::make_shared(), [&](Pool & victim) + { + oneTable(victim); + group_keys = seedOrphanManifestGroup(victim, "victim/db/t1", 3); + }); + const String group_prefix = group_keys.front().substr(0, group_keys.front().rfind('/') + 1); + const String debris_prefix = layout.casManifestsServerPrefix("victim"); + + int code = 0; + size_t listings_at_kill = 0; + std::thread killed([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + if (kill_at == KillAt::BeforeTheRun) + query.kill(); + else + { + if (kill_at == KillAt::DebrisListing) + backend->page_cap = 1; + const String watched = kill_at == KillAt::DebrisListing ? debris_prefix : group_prefix; + backend->matches = [watched](const String & prefix) { return prefix == watched; }; + backend->on_list = [&query, &listings_at_kill, watched, &backend] + { + listings_at_kill = backend->listingsOf(watched); + query.kill(); + }; + } + try + { + (void)run("admin"); + } + catch (const Exception & e) + { + code = e.code(); + } + }); + killed.join(); + + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(backend->listingsOf("p/staging/victim/"), 0u) << "the stopped drain went on to the staging area"; + OperationForTest op(*victim_backend); + const CasRefCatalog::Snapshot catalog = CasRefCatalog::read(*op, layout); + ASSERT_EQ(catalog.catalog.entries.size(), 1u); + EXPECT_EQ(catalog.catalog.entries.front().state, kill_at == KillAt::BeforeTheRun ? NsState::Live : NsState::Removing); + EXPECT_EQ(backend->listingsOf(group_prefix), kill_at == KillAt::GroupListing ? 1u : 0u); + if (kill_at == KillAt::DebrisListing) + { + ASSERT_GT(listings_at_kill, 0u) << "premise: the kill landed in the debris listing"; + EXPECT_EQ(backend->listingsOf(debris_prefix), listings_at_kill) << "the killed listing requested another page"; + } + expectOwner(2, true, false); + + const auto rerun = run("admin"); + EXPECT_EQ(rerun.namespaces_removed + rerun.namespaces_already_removed, 1u); + EXPECT_GT(backend->listingsOf("p/staging/victim/"), 0u) << "the rerun drained the staging area"; + } +} + +namespace +{ + /// The first roots delete under the victim lets the admin's local lease deadline pass (the fake clock jumps a /// TTL); every delete admitted on the mount plane after it is refused. Optionally also GC-fences the body. class ExpireLeaseOnFirstRootsDeleteBackend : public InMemoryBackend diff --git a/src/Disks/tests/gtest_cas_fsck.cpp b/src/Disks/tests/gtest_cas_fsck.cpp index 9941a729dde24..c5b73f503c8b0 100644 --- a/src/Disks/tests/gtest_cas_fsck.cpp +++ b/src/Disks/tests/gtest_cas_fsck.cpp @@ -13,12 +13,15 @@ #include #include #include +#include "cas_killable_query.h" #include "cas_test_helpers.h" #include "config.h" #if USE_AWS_S3 #include #endif +#include +#include #include #include #include @@ -1208,6 +1211,71 @@ TEST(CASFsckAuthority, CheckpointBaseTransportFailureIsUnchecked) } #endif +/// A query's stored cause with the `CORRUPTED_DATA` code is no finding about the chain: a killed `SYSTEM CAS FSCK` +/// whose base read fails with it leaves the namespace unchecked instead of reporting `ChainBroken`. +TEST(CASFsckAuthority, StoredCorruptedDataIsNotChainBroken) +{ + class StoredCauseOnGetBackend final : public InMemoryBackend + { + public: + String key; + std::function on_get; + + std::optional read(const String & requested_key, TransportAccess & access) override + { + if (requested_key == key && on_get) + on_get(); + return InMemoryBackend::read(requested_key, access); + } + }; + + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Layout & layout = store->layout(); + const RootNamespace ns{"00/stored_corruption@cas@"}; + fixture::admitLive(*backend, layout, ns); + + const RefTxnId base{1, 1}; + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + CasOperation op = requests.admit(); + const NamespaceLifeId life = *CasRefCatalog::lifeIfCataloged(op, layout, ns); + fixture::writeRefLogRaw(*backend, layout, RefLogTxn{ + .ns = ns.string(), .txn_id = base, .ops = {namespaceBirthOp()}, .prev_epoch_seal = std::nullopt}); + RefTableState state; + applyRefLogTxn(state, RefLogTxn{ + .ns = ns.string(), .txn_id = base, .ops = {namespaceBirthOp()}, .prev_epoch_seal = std::nullopt}); + writeRefSnapshotRaw(*backend, layout, snapshotOf(state, ns.string())); + writeFsckCheckpointWithBase(*backend, layout, ns, base); + backend->key = layout.refSnapshotKey(life, base); + + std::optional report; + std::exception_ptr error; + std::thread worker([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + /// The store fails the base read the way the S3 client does for a killed query: with the query's cause. + backend->on_get = [&] + { + query.kill(std::make_exception_ptr(DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "the query's stored cause"))); + DB::CurrentThread::checkIfNotCancelled(); + }; + try + { + report = runFsck(*store, /*detail=*/true); + } + catch (...) + { + error = std::current_exception(); + } + backend->on_get = {}; + }); + worker.join(); + ASSERT_TRUE(report.has_value()) << DB::getExceptionMessage(error, false); + EXPECT_EQ(report->chain_broken, 0u); + EXPECT_EQ(report->unchecked, 1u); +} + /// Cleanup may advance `_ckpt` after fsck sampled it and retire the old base before fsck exact-reads it. /// The miss is authority instability, so fsck walks again from the new `_ckpt`, which here names no base. /// Mutation caught: classifying `CORRUPTED_DATA` without rechecking the sampled checkpoint token. diff --git a/src/Disks/tests/gtest_cas_migrate_pool.cpp b/src/Disks/tests/gtest_cas_migrate_pool.cpp index 2ca32c91f094a..40e1dca74081f 100644 --- a/src/Disks/tests/gtest_cas_migrate_pool.cpp +++ b/src/Disks/tests/gtest_cas_migrate_pool.cpp @@ -27,7 +27,9 @@ #include #include #include +#include #include +#include "cas_killable_query.h" #include "cas_test_helpers.h" #include @@ -42,11 +44,17 @@ extern const int BAD_ARGUMENTS; extern const int CANNOT_SCHEDULE_TASK; extern const int CORRUPTED_DATA; extern const int INVALID_STATE; +extern const int NETWORK_ERROR; extern const int NOT_IMPLEMENTED; extern const int READONLY; extern const int UNKNOWN_FORMAT_VERSION; } +namespace DB::FailPoints +{ +extern const char thread_group_switcher_post_attach_failure[]; +} + namespace ProfileEvents { extern const Event CASGCIntentConfirmedExisting; @@ -60,6 +68,34 @@ namespace /// The in-memory store with a switchable dialect, `HEAD`s that answer a weak token, injected write and delete /// refusals, and hooks after a write lands and before a `HEAD`. +/// Serves `header`, then on the next refill runs `on_refill` and the cancellation check a store client makes. +class HeaderThenStoppedReadBuffer : public DB::ReadBuffer +{ +public: + HeaderThenStoppedReadBuffer(String header_, std::function on_refill_) + : DB::ReadBuffer(nullptr, 0), header(std::move(header_)), on_refill(std::move(on_refill_)) + { + } + +private: + bool nextImpl() override + { + if (!served) + { + served = true; + BufferBase::set(header.data(), header.size(), 0); + return true; + } + on_refill(); + DB::CurrentThread::checkIfNotCancelled(); + return false; + } + + String header; + std::function on_refill; + bool served = false; +}; + class MigrationBackend : public CountingBackend { public: @@ -117,6 +153,30 @@ class MigrationBackend : public CountingBackend after_write = std::move(hook); } + /// The stream of `key` serves its first line, then runs `hook` and fails as a stopped query's read does. + void stopStreamAfterHeader(const String & key, std::function hook) + { + std::lock_guard lock(mutex); + stopped_stream_key = key; + stopped_stream_hook = std::move(hook); + } + + std::unique_ptr stream(const String & key, TransportAccess & access) override + { + std::function hook; + { + std::lock_guard lock(mutex); + if (key == stopped_stream_key) + hook = stopped_stream_hook; + } + if (!hook) + return CountingBackend::stream(key, access); + const auto raw = CountingBackend::read(key, access); + if (!raw) + return nullptr; + return std::make_unique(raw->bytes.substr(0, raw->bytes.find('\n') + 1), hook); + } + /// Runs `hook` once, before the first `HEAD` of `key` is served. void beforeHead(const String & key, std::function hook) { @@ -259,6 +319,8 @@ class MigrationBackend : public CountingBackend std::function before_head; String after_head_key; std::function after_head; + String stopped_stream_key; + std::function stopped_stream_hook; }; /// A live holder's slot body declaring a 30 s lease. @@ -2893,3 +2955,126 @@ TEST(CASBoundedRun, FailedSubmissionJoinsTheQueuedJobs) ASSERT_EQ(finished.load(), 3u) << "a submitted job was not joined before the failure left the run"; } } + +/// A job whose thread fails to join the submitting query's thread group does not run: outside the query its requests +/// would not see the query's stop. The failpoint fails one switch only, so the other job may run in the query. +TEST(CASBoundedRun, JobOutsideTheQueryDoesNotRun) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + std::mutex mutex; + std::vector ran_in_query; + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + /// Armed after the query's own attach, so a job's switch is the one that fails. + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + try + { + runBounded(*makeBoundedPool(2), DB::ThreadName::UNKNOWN, 2, [&](size_t) + { + const bool in_query = DB::CurrentThread::getGroup() == query.group; + std::lock_guard lock(mutex); + ran_in_query.push_back(in_query); + }); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + EXPECT_EQ(code, DB::ErrorCodes::CANNOT_SCHEDULE_TASK); + EXPECT_LE(ran_in_query.size(), 1u) << "both jobs ran although one could not join the query"; + for (const bool in_query : ran_in_query) + EXPECT_TRUE(in_query) << "a job ran outside the query"; +} + +namespace +{ + +/// The message of the stored cause after `run` killed its query with it. +String storedMessageAfter(const std::exception_ptr & cause) +{ + try + { + std::rethrow_exception(cause); + } + catch (const DB::Exception & e) + { + return e.message(); + } +} + +} + +/// A marker removal that fails with a killed query's stored cause reaches the caller unannotated, through the +/// removal's own catch and the M9 page's: the query rethrows that one object to every thread it stops. +TEST(CASMigratePool, MarkerRemovalLeavesTheStoredQueryExceptionUnchanged) +{ + Fixture f(3); + seedMixedPool(f); + const String stored_text = "the query's stored network failure"; + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "{}", stored_text)); + bool fired = false; + int code = 0; + std::vector lines; + onKillableQueryThread([&](CasKillableQuery & query) + { + f.backend->beforeHead(*f.markers().begin(), [&] + { + fired = true; + query.kill(cause); + std::rethrow_exception(cause); + }); + MigratePoolOptions one_at_a_time; + one_at_a_time.concurrency = 1; + try + { + f.run(one_at_a_time, &lines); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_TRUE(fired) << "the run never removed a marker"; + EXPECT_TRUE(contains(lines, "M8")) << "the kill landed before the marker removal"; + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR); + EXPECT_EQ(storedMessageAfter(cause), stored_text) << "a marker removal annotated the query's stored exception"; +} + +/// An inherited run whose refill fails with a killed query's stored `CORRUPTED_DATA` reaches the caller unannotated +/// through M3's catch, which annotates that code otherwise. +TEST(CASMigratePool, InheritedRunReadLeavesTheStoredQueryExceptionUnchanged) +{ + Fixture f(3); + f.body(1); + f.rows({f.row(1, /*pending*/ true)}); + const std::vector run_keys = adoptedRunKeysOf(f); + ASSERT_FALSE(run_keys.empty()); + const String stored_text = "the query's stored corruption"; + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "{}", stored_text)); + bool fired = false; + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + f.backend->stopStreamAfterHeader(run_keys.front(), [&] + { + fired = true; + query.kill(cause); + }); + try + { + f.run(); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_TRUE(fired) << "the run never refilled the inherited run"; + EXPECT_EQ(code, DB::ErrorCodes::CORRUPTED_DATA); + EXPECT_EQ(storedMessageAfter(cause), stored_text) << "M3 annotated the query's stored exception"; +} From bbb0c413878e8f0223ceb887484808796c151c84 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:28:12 +0100 Subject: [PATCH 14/47] Describe `Stopped` GC rounds in the `cas_gc_log` column comments Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- src/Interpreters/ContentAddressedGarbageCollectionLog.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Interpreters/ContentAddressedGarbageCollectionLog.cpp b/src/Interpreters/ContentAddressedGarbageCollectionLog.cpp index 5052577f85a55..de407e028c547 100644 --- a/src/Interpreters/ContentAddressedGarbageCollectionLog.cpp +++ b/src/Interpreters/ContentAddressedGarbageCollectionLog.cpp @@ -39,7 +39,7 @@ ColumnsDescription ContentAddressedGarbageCollectionLogElement::getColumnsDescri {"gc_id", std::make_shared(), "GC scheduler instance id (which mounter)."}, {"trigger", trigger_enum, "Scheduled (background tick) or Manual (SYSTEM command)."}, {"round", std::make_shared(), "GC round number (0 on Start)."}, - {"outcome", outcome_enum, "Unknown (Start) / Success (led, folded, and completed) / NotALeader (another replica holds the GC lease) / Deferred (led but took the skip-unchanged fast path -- no fold ran) / Aborted (the round threw a transient error -- backend unavailability, a lost lease, a concurrent leader -- and the next scheduled round retries) / Stopped (a transient error observed after the disk\'s teardown began: the round was cut short by a server shutdown or the storage\'s destructor, so neither waited for it; a correlation, not a cause -- a transient incident that started before the teardown is recorded the same way, and decommission does not arm the flag at all) / Error (the round threw a non-transient error -- during a teardown too)."}, + {"outcome", outcome_enum, "Unknown (Start) / Success (led, folded, and completed) / NotALeader (another replica holds the GC lease) / Deferred (led but took the skip-unchanged fast path -- no fold ran) / Aborted (the round threw a transient error -- backend unavailability, a lost lease, a concurrent leader -- and the next scheduled round retries) / Stopped (the round was cut short on request: a transient error after the disk\'s teardown began, a stop by `SYSTEM CAS GC STOP`, or a manual round whose query was killed or timed out; for a teardown this is a correlation, not a cause -- a transient incident that started before the teardown is recorded the same way, and decommission does not arm the flag at all) / Error (the round threw a non-transient error -- during a teardown too)."}, {"candidates_marked", std::make_shared(), "Objects retired (marked) this round."}, {"objects_deleted", std::make_shared(), "Objects physically deleted this round."}, {"objects_absent", std::make_shared(), "Retire candidates found already absent."}, @@ -53,14 +53,14 @@ ColumnsDescription ContentAddressedGarbageCollectionLogElement::getColumnsDescri {"fence_outs", std::make_shared(), "Expired mounts fenced out by this round's heartbeat floor."}, {"anomalies", std::make_shared(), "Fold clamps surfaced (and survived) this round; steady >0 warrants a look at the round log details."}, {"duration_ms", std::make_shared(), "Round wall-clock duration (Finish)."}, - {"error", std::make_shared(), "Exception text when outcome = Aborted, Stopped or Error. On a Stopped row it names the engine\'s refusal, not the teardown."}, - {"error_code", std::make_shared(), "Exception code when outcome = Aborted, Stopped or Error; 0 otherwise. The structured twin of `error`: key monitoring on this column, not on message text."}, + {"error", std::make_shared(), "Exception text when outcome = Aborted, Stopped or Error. On a Stopped row it is the message of the exception that ended the round: for example `CAS GC round stopped by its scheduler` or the killed query\'s own message; after a teardown it names the engine\'s refusal, not the teardown."}, + {"error_code", std::make_shared(), "Exception code when outcome = Aborted, Stopped or Error; 0 otherwise. The structured twin of `error`: key monitoring on this column, not on message text. On a Stopped row it is the code the round ended with: usually ABORTED for SYSTEM CAS GC STOP and QUERY_WAS_CANCELLED or TIMEOUT_EXCEEDED for a manual round, but any transient code can appear, such as NETWORK_ERROR after a write whose outcome is unknown."}, {"ProfileEvents", std::make_shared(lc_string, std::make_shared()), "On a Start/Finish row: the per-round ProfileEvents delta (the Cas* counters and S3 events for this round). On a Phase row: THAT PHASE's delta, so `GROUP BY phase` over `ProfileEvents['S3ListObjects']` attributes the round's LIST budget to the phase that spent it. Requests issued by GC I/O pool workers (the `pending_deletes` fan-out and the fold read-ahead) are missing from their phase rows; they still count in `system.events`."}, {"round_id", std::make_shared(), "Correlator for every row of one round attempt (its Start, each Phase, and its Finish). Minted per attempt; unlike `round` it exists even for a round that never committed and for a round that never led. Group by this column to reconstruct one round."}, {"phase", lc_string, - "The GC phase this row describes (empty on Start/Finish), in execution order: lease, pre_fold_ref_drain, heartbeat_floor, defer_decision, parent_seal_read, fold_ref_group, fold_seal_read, fold_ref_intake, intent_sweep_list, fold_reduce, fold_seal_write, pending_deletes, round_commit, handoff_reclaim, manifest_deletes, namespace_cleanup, ref_object_cleanup, orphan_sweep. A round that defers, or that never acquires the lease, emits only the phases it reached."}, + "The GC phase this row describes (empty on Start/Finish), in execution order: lease, pre_fold_ref_drain, heartbeat_floor, defer_decision, parent_seal_read, fold_ref_group, fold_seal_read, fold_ref_intake, intent_sweep_list, fold_reduce, fold_seal_write, pending_deletes, round_commit, handoff_reclaim, manifest_deletes, orphan_sweep, namespace_cleanup, ref_object_cleanup. A round that defers, or that never acquires the lease, emits only the phases it reached."}, {"phase_duration_microseconds", std::make_shared(), "Wall-clock duration of this phase in microseconds (Phase rows only). Microseconds because several phases are routinely sub-millisecond and the point is to see when they are not. Phase durations do not sum to the round's `duration_ms`: the round also does untimed bookkeeping between phases."}, {"phase_metrics", std::make_shared(lc_string, std::make_shared()), From e77514d85d6a4c82685050a0cf3570ac900903c1 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:28:14 +0100 Subject: [PATCH 15/47] Test CAS request windows and owner stops through an S3 fault proxy `s3_fault_proxy.py` moves to `helpers/s3_mocks` and can hold a request until the test releases it. `test_cas_request_window` covers per-request windows, kills and query timeouts end to end. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../s3_mocks}/s3_fault_proxy.py | 197 +++- .../docker_compose_proxy.yml | 6 +- .../test_cas_request_window/__init__.py | 0 .../configs/blob_upload_serial.xml | 4 + .../configs/drop_cooldown.xml | 5 + .../configs/drop_delay.xml | 4 + .../configs/storage_conf.xml | 35 + .../configs/storage_conf_gc.xml | 37 + .../configs/storage_conf_stop.xml | 38 + .../configs/transactions.xml | 3 + .../docker_compose_proxy.yml | 40 + .../test_cas_request_window/test.py | 970 ++++++++++++++++++ 12 files changed, 1321 insertions(+), 18 deletions(-) rename tests/integration/{test_cas_mount_renewal_retry => helpers/s3_mocks}/s3_fault_proxy.py (62%) create mode 100644 tests/integration/test_cas_request_window/__init__.py create mode 100644 tests/integration/test_cas_request_window/configs/blob_upload_serial.xml create mode 100644 tests/integration/test_cas_request_window/configs/drop_cooldown.xml create mode 100644 tests/integration/test_cas_request_window/configs/drop_delay.xml create mode 100644 tests/integration/test_cas_request_window/configs/storage_conf.xml create mode 100644 tests/integration/test_cas_request_window/configs/storage_conf_gc.xml create mode 100644 tests/integration/test_cas_request_window/configs/storage_conf_stop.xml create mode 100644 tests/integration/test_cas_request_window/configs/transactions.xml create mode 100644 tests/integration/test_cas_request_window/docker_compose_proxy.yml create mode 100644 tests/integration/test_cas_request_window/test.py diff --git a/tests/integration/test_cas_mount_renewal_retry/s3_fault_proxy.py b/tests/integration/helpers/s3_mocks/s3_fault_proxy.py similarity index 62% rename from tests/integration/test_cas_mount_renewal_retry/s3_fault_proxy.py rename to tests/integration/helpers/s3_mocks/s3_fault_proxy.py index cf3102611a192..641599683a30b 100644 --- a/tests/integration/test_cas_mount_renewal_retry/s3_fault_proxy.py +++ b/tests/integration/helpers/s3_mocks/s3_fault_proxy.py @@ -22,6 +22,23 @@ `remaining_faults` budget. The `drop_after_forward` mode records the upstream result and request body digest, then closes the downstream connection so retry recovery can prove response-loss cases. +`slow_then_drop` waits `slow_ms`, forwards, then closes without the response. `trickle` forwards, then +sends the response in pieces spread over `slow_ms`. `trace: true` records every request at ingress +(optionally scoped by `trace_path_substring`) and `/stats` returns it as `trace`, with the proxy's +monotonic clock as `now_mono_ms`. A record names the fault it got; after a trickle, `outcome` is +`delivered` once the last piece is flushed or `disconnected` when a write fails, and +`t_last_piece_mono_ms` is when the last piece started to be written. With `trace_bodies: true` a record +also carries the request body as Latin-1 text when it is at most `TRACE_BODY_MAX_BYTES`, else None. + +`rules` is an ordered script of `{method, path_substring, action, count}` with an optional +`body_substring`. Only the first rule with `count > 0` is consulted: a request it matches consumes one +count and gets its action, any other request gets the random decision above. `path_substring`, +`trace_path_substring` and `body_substring` are each a string or a list of strings that must all occur. +Actions: `forward`; `412`, an S3 `PreconditionFailed` without forwarding; `503`, a `SlowDown` without +forwarding; `hold`, which parks the request until `POST /release {id, respond: forward|503}`. A traced +parked request gets `t_release_mono_ms` when it is released. `GET /parked` lists the parked requests; +`/stats` returns the rules with their remaining counts. + Control plane (separate port): POST /config {json}, GET /stats, GET /healthz. Deterministic: fault decisions are driven by a seeded PRNG keyed per-request-index, so a given (seed, rate) is reproducible. """ @@ -29,6 +46,7 @@ import hashlib import http.client import http.server +import io import json import os import random @@ -41,20 +59,29 @@ UPSTREAM = os.environ.get("RUSTFS_UPSTREAM", "rustfs1:11121") # host:port of the real store S3_PORT = int(os.environ.get("S3_PROXY_PORT", "11121")) CTL_PORT = int(os.environ.get("S3_PROXY_CTL_PORT", "8474")) +TRICKLE_INTERVAL_MS = 250 +TRACE_BODY_MAX_BYTES = 64 * 1024 # Runtime-mutable fault config (guarded by _cfg_lock). rate=0 => pure pass-through. _cfg_lock = threading.Lock() _DEFAULT_CFG = { "rate": 0.0, # fraction of matched requests that get a fault - "modes": ["503"], # subset of {503,429,slow,reset,drop_after_forward} + # subset of {503,429,slow,reset,drop_after_forward,slow_then_drop,trickle}: + # slow_then_drop waits slow_ms, forwards, then closes without the response; + # trickle forwards, then sends the response in pieces spread over slow_ms. + "modes": ["503"], "methods": ["GET", "PUT", "HEAD", "POST"], # HTTP methods eligible for S22 faults "slow_ms": 1500, # latency for the "slow" mode "seed": 1, "path_substring": None, # optional request-path scope + "trace": False, # record every request at ingress; returned by /stats + "trace_path_substring": None, # optional scope of the trace + "trace_bodies": False, # record small request bodies in the trace "remaining_faults": None, # optional exact finite fault budget; None = legacy unlimited # S27 list-anomaly config (independent of the S22 fault rate): "list_anomaly": None, # None | "duplicate" | "drop_token" "list_prefix": "roots/", # only LIST calls whose prefix contains this are perturbed + "rules": [], # ordered script; see the module docstring } _DEFAULT_STATS = { "forwarded": 0, @@ -62,13 +89,18 @@ "list_perturbed": 0, "by_mode": {}, "drop_after_forward": [], + "trace": [], } _cfg = dict(_DEFAULT_CFG) _stats = dict(_DEFAULT_STATS) _stats["by_mode"] = {} _stats["drop_after_forward"] = [] +_stats["trace"] = [] _req_index = [0] _idx_lock = threading.Lock() +# id -> {"id", "method", "path", "t_mono_ms", "event", "respond", "trace"}; guarded by _cfg_lock. +_parked = {} +_parked_ids = [0] def _get_cfg(): @@ -104,14 +136,26 @@ def _record_drop_after_forward(method, path, body, upstream_status, upstream_eta del records[:-64] +def _release(record, respond): + record["respond"] = respond + if record["trace"] is not None: + record["trace"]["t_release_mono_ms"] = time.monotonic() * 1000.0 + record["event"].set() + + def _reset(): with _cfg_lock: + # A parked handler thread must not outlive the test that parked it. + for record in _parked.values(): + _release(record, "503") + _parked.clear() _cfg.clear() _cfg.update(_DEFAULT_CFG) _stats.clear() _stats.update(_DEFAULT_STATS) _stats["by_mode"] = {} _stats["drop_after_forward"] = [] + _stats["trace"] = [] with _idx_lock: _req_index[0] = 0 @@ -119,6 +163,21 @@ def _reset(): _SLOWDOWN_BODY = (b'' b'SlowDownPlease reduce your request rate.' b'/fault-proxy') +_PRECONDITION_FAILED_BODY = (b'' + b'PreconditionFailed' + b'At least one of the pre-conditions you specified did not hold' + b'/fault-proxy') + + +def _path_matches(path, substring): + if substring is None: + return True + substrings = [substring] if isinstance(substring, str) else substring + return all(s in (path or "") for s in substrings) + + +def _body_matches(body, substring): + return _path_matches(body.decode("latin-1"), substring) class Handler(http.server.BaseHTTPRequestHandler): @@ -128,6 +187,34 @@ def log_message(self, *a): pass # quiet # --- fault decision ----------------------------------------------------- + def _admit(self, ingress_mono_ms): + """Consumes the head rule, publishes the trace record and parks a held request in one critical section, so + a concurrent `/config` reset or `/release` sees all three or none of them. Returns the rule's action and the + parked record.""" + with _cfg_lock: + action = None + head = next((r for r in _cfg["rules"] if r["count"] > 0), None) + if (head is not None and head["method"] == self.command and _path_matches(self.path, head["path_substring"]) + and _body_matches(self._cached_body, head.get("body_substring"))): + head["count"] -= 1 + action = head["action"] + if _cfg["trace"] and _path_matches(self.path, _cfg.get("trace_path_substring")): + body = None + if _cfg.get("trace_bodies") and len(self._cached_body) <= TRACE_BODY_MAX_BYTES: + body = self._cached_body.decode("latin-1") + # Every key exists before the record is published; later fields start as None. + self._trace_record = {"t_mono_ms": ingress_mono_ms, "method": self.command, "path": self.path, + "fault": None, "rule": action, "status": None, "outcome": None, + "t_last_piece_mono_ms": None, "t_release_mono_ms": None, "body": body} + _stats["trace"].append(self._trace_record) + parked = None + if action == "hold": + _parked_ids[0] += 1 + parked = {"id": _parked_ids[0], "method": self.command, "path": self.path, "t_mono_ms": ingress_mono_ms, + "event": threading.Event(), "respond": None, "trace": self._trace_record} + _parked[parked["id"]] = parked + return action, parked + def _should_fault(self, cfg): # Keep the original unscoped decision path byte-for-byte: existing scenario configs omit # both new fields and therefore retain their request-index/seed behavior. @@ -146,8 +233,7 @@ def _should_fault(self, cfg): current = _cfg if current["rate"] <= 0 or self.command not in current["methods"]: return None - path_substring = current.get("path_substring") - if path_substring is not None and path_substring not in (self.path or ""): + if not _path_matches(self.path, current.get("path_substring")): return None remaining = current.get("remaining_faults") if remaining is not None and remaining <= 0: @@ -161,17 +247,40 @@ def _should_fault(self, cfg): current["remaining_faults"] = remaining - 1 return mode + def _send_error(self, code, body): + self._trace_status(code) + self.send_response(code) + self.send_header("Content-Type", "application/xml") + self.send_header("Content-Length", str(len(body))) + self.send_header("Connection", "keep-alive") + self.end_headers() + self.wfile.write(body) + + def _hold(self, parked): + parked["event"].wait() + if parked["respond"] == "forward": + self._forward() + else: + self._send_error(503, _SLOWDOWN_BODY) + + def _apply_rule(self, action, parked): + _bump("by_mode", "rule_" + action) + if action == "forward": + self._forward() + elif action == "412": + self._send_error(412, _PRECONDITION_FAILED_BODY) + elif action == "503": + self._send_error(503, _SLOWDOWN_BODY) + elif action == "hold": + self._hold(parked) + else: + raise ValueError(f"unknown rule action {action}") + def _emit_fault(self, mode): _bump("faults") _bump("by_mode", mode) if mode in ("503", "429"): - code = 503 if mode == "503" else 429 - self.send_response(code) - self.send_header("Content-Type", "application/xml") - self.send_header("Content-Length", str(len(_SLOWDOWN_BODY))) - self.send_header("Connection", "keep-alive") - self.end_headers() - self.wfile.write(_SLOWDOWN_BODY) + self._send_error(503 if mode == "503" else 429, _SLOWDOWN_BODY) elif mode == "slow": time.sleep(_get_cfg()["slow_ms"] / 1000.0) self._forward() # after the delay, serve the real response @@ -184,6 +293,11 @@ def _emit_fault(self, mode): pass elif mode == "drop_after_forward": self._forward(drop_after_forward=True) + elif mode == "slow_then_drop": + time.sleep(_get_cfg()["slow_ms"] / 1000.0) + self._forward(drop_after_forward=True) + elif mode == "trickle": + self._forward(trickle=True) # --- request body ------------------------------------------------------- def _read_body(self): @@ -207,7 +321,7 @@ def _read_body(self): return b"" # --- forward to upstream ------------------------------------------------ - def _forward(self, drop_after_forward=False): + def _forward(self, drop_after_forward=False, trickle=False): body = getattr(self, "_cached_body", None) if body is None: body = self._read_body() @@ -265,6 +379,10 @@ def _forward(self, drop_after_forward=False): pass self.connection.close() return + self._trace_status(resp.status) + real_wfile = self.wfile + if trickle: + self.wfile = io.BytesIO() self.send_response(resp.status) is_head = (self.command == "HEAD") for k, v in resp.getheaders(): @@ -281,10 +399,34 @@ def _forward(self, drop_after_forward=False): self.end_headers() if not is_head: self.wfile.write(data) + if trickle: + # Keeps the socket active, so only a total-time bound ends the attempt. + raw = self.wfile.getvalue() + self.wfile = real_wfile + pieces = max(1, int(cfg["slow_ms"] // TRICKLE_INTERVAL_MS)) + step = max(1, -(-len(raw) // pieces)) + outcome = "disconnected" + try: + for i in range(0, len(raw), step): + time.sleep(TRICKLE_INTERVAL_MS / 1000.0) + if i + step >= len(raw) and self._trace_record is not None: + self._trace_record["t_last_piece_mono_ms"] = time.monotonic() * 1000.0 + self.wfile.write(raw[i:i + step]) + self.wfile.flush() + outcome = "delivered" + finally: + if self._trace_record is not None: + self._trace_record["outcome"] = outcome conn.close() + def _trace_status(self, status): + if self._trace_record is not None: + self._trace_record["status"] = status + def _handle(self): cfg = _get_cfg() + self._trace_record = None + ingress_mono_ms = time.monotonic() * 1000.0 # Cache body once (fault paths + forward both may need it). try: self._cached_body = self._read_body() @@ -294,8 +436,13 @@ def _handle(self): print(f"[dbg] {self.command} {self.path[:60]} CL={self.headers.get('Content-Length')} " f"TE={self.headers.get('Transfer-Encoding')} CE={self.headers.get('Content-Encoding')} " f"Expect={self.headers.get('Expect')} read={len(self._cached_body)}", flush=True) - mode = self._should_fault(cfg) - if mode is None: + action, parked = self._admit(ingress_mono_ms) + mode = self._should_fault(cfg) if action is None else None + if self._trace_record is not None: + self._trace_record["fault"] = mode + if action is not None: + self._apply_rule(action, parked) + elif mode is None: self._forward() else: self._emit_fault(mode) @@ -365,21 +512,41 @@ def do_GET(self): snapshot = dict(_stats) snapshot["by_mode"] = dict(_stats["by_mode"]) snapshot["drop_after_forward"] = list(_stats["drop_after_forward"]) + snapshot["trace"] = [dict(r) for r in _stats["trace"]] + snapshot["rules"] = [dict(r) for r in _cfg["rules"]] + snapshot["now_mono_ms"] = time.monotonic() * 1000.0 return self._json(200, snapshot) + if self.path.startswith("/parked"): + with _cfg_lock: + parked = [{k: r[k] for k in ("id", "method", "path", "t_mono_ms")} + for r in _parked.values() if r["respond"] is None] + return self._json(200, {"parked": parked}) self._json(404, {"error": "not found"}) def do_POST(self): - if not self.path.startswith("/config"): - return self._json(404, {"error": "not found"}) length = int(self.headers.get("Content-Length", "0")) try: patch = json.loads(self.rfile.read(length) or b"{}") except Exception as e: return self._json(400, {"error": f"bad json: {e}"}) + if self.path.startswith("/release"): + respond = patch.get("respond", "forward") + if respond not in ("forward", "503"): + return self._json(400, {"error": f"bad respond {respond}"}) + with _cfg_lock: + record = _parked.pop(patch.get("id"), None) + if record is None: + return self._json(404, {"error": "not parked"}) + _release(record, respond) + return self._json(200, {"ok": True}) + if not self.path.startswith("/config"): + return self._json(404, {"error": "not found"}) reset = bool(patch.pop("reset", False)) if reset: _reset() with _cfg_lock: + if "rules" in patch: + patch["rules"] = [dict(r) for r in patch["rules"]] _cfg.update(patch) snap = dict(_cfg) self._json(200, {"ok": True, "config": snap}) diff --git a/tests/integration/test_cas_mount_renewal_retry/docker_compose_proxy.yml b/tests/integration/test_cas_mount_renewal_retry/docker_compose_proxy.yml index 67f39af36922b..d83488f9ea4c7 100644 --- a/tests/integration/test_cas_mount_renewal_retry/docker_compose_proxy.yml +++ b/tests/integration/test_cas_mount_renewal_retry/docker_compose_proxy.yml @@ -11,9 +11,9 @@ services: condition: service_started volumes: # Compose resolves relative binds against the generated first compose file in - # `/_instances-*/node`, not against this appended file, so `../..` is the - # directory holding this file. - - ../../s3_fault_proxy.py:/proxy/s3_fault_proxy.py:ro + # `/_instances-*/node`, not against this appended file, so `../../..` is + # `tests/integration`. + - ../../../helpers/s3_mocks/s3_fault_proxy.py:/proxy/s3_fault_proxy.py:ro expose: - "11121" ports: diff --git a/tests/integration/test_cas_request_window/__init__.py b/tests/integration/test_cas_request_window/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/integration/test_cas_request_window/configs/blob_upload_serial.xml b/tests/integration/test_cas_request_window/configs/blob_upload_serial.xml new file mode 100644 index 0000000000000..62a192ac8f339 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/blob_upload_serial.xml @@ -0,0 +1,4 @@ + + + 1 + diff --git a/tests/integration/test_cas_request_window/configs/drop_cooldown.xml b/tests/integration/test_cas_request_window/configs/drop_cooldown.xml new file mode 100644 index 0000000000000..42988c699315a --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/drop_cooldown.xml @@ -0,0 +1,5 @@ + + + 600 + diff --git a/tests/integration/test_cas_request_window/configs/drop_delay.xml b/tests/integration/test_cas_request_window/configs/drop_delay.xml new file mode 100644 index 0000000000000..3b6211126770a --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/drop_delay.xml @@ -0,0 +1,4 @@ + + + 0 + diff --git a/tests/integration/test_cas_request_window/configs/storage_conf.xml b/tests/integration/test_cas_request_window/configs/storage_conf.xml new file mode 100644 index 0000000000000..ec44b710170a0 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/storage_conf.xml @@ -0,0 +1,35 @@ + + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-window + http://s3proxy:11121/test/cas_request_window/ + clickhouse + clickhouse + false + + 500 + 1000 + 5000 + 10000 + 2000 + 500 + + + + + +
+ disk_cas_window +
+
+
+
+
+
diff --git a/tests/integration/test_cas_request_window/configs/storage_conf_gc.xml b/tests/integration/test_cas_request_window/configs/storage_conf_gc.xml new file mode 100644 index 0000000000000..8ab3bc3ef4027 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/storage_conf_gc.xml @@ -0,0 +1,37 @@ + + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-gc + http://s3proxy:11121/test/cas_request_gc/ + clickhouse + clickhouse + + true + 3600 + + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + + +
+ disk_cas_gc +
+
+
+
+
+
diff --git a/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml b/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml new file mode 100644 index 0000000000000..1e57ebc461a5f --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml @@ -0,0 +1,38 @@ + + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-stop + http://s3proxy:11121/test/cas_request_stop/ + clickhouse + clickhouse + false + + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + + +
+ disk_cas_stop +
+
+
+
+
+
diff --git a/tests/integration/test_cas_request_window/configs/transactions.xml b/tests/integration/test_cas_request_window/configs/transactions.xml new file mode 100644 index 0000000000000..f2a01989fdf20 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/transactions.xml @@ -0,0 +1,3 @@ + + 42 + diff --git a/tests/integration/test_cas_request_window/docker_compose_proxy.yml b/tests/integration/test_cas_request_window/docker_compose_proxy.yml new file mode 100644 index 0000000000000..210d732547b7c --- /dev/null +++ b/tests/integration/test_cas_request_window/docker_compose_proxy.yml @@ -0,0 +1,40 @@ +services: + s3proxy: + image: python:3.12-slim + command: ["python3", "/proxy/s3_fault_proxy.py"] + environment: + RUSTFS_UPSTREAM: "rustfs1:11121" + S3_PROXY_PORT: "11121" + S3_PROXY_CTL_PORT: "8474" + depends_on: + rustfs1: + condition: service_started + volumes: + # Compose resolves relative binds against the generated first compose file in + # `/_instances-*/node`, not against this appended file, so `../../..` is + # `tests/integration`. + - ../../../helpers/s3_mocks/s3_fault_proxy.py:/proxy/s3_fault_proxy.py:ro + expose: + - "11121" + ports: + - "127.0.0.1::8474" + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8474/healthz', timeout=2)"] + interval: 1s + timeout: 3s + retries: 30 + + node: + depends_on: + s3proxy: + condition: service_healthy + + node_stop: + depends_on: + s3proxy: + condition: service_healthy + + node_gc: + depends_on: + s3proxy: + condition: service_healthy diff --git a/tests/integration/test_cas_request_window/test.py b/tests/integration/test_cas_request_window/test.py new file mode 100644 index 0000000000000..3e0af0d6f042b --- /dev/null +++ b/tests/integration/test_cas_request_window/test.py @@ -0,0 +1,970 @@ +"""One CAS metadata request gets its own window, not a deadline shared with the previous one. + +Pinned values (configs/storage_conf.xml, configs/drop_cooldown.xml): + attempt envelope 2000 ms, cas_request_window_ms 5000 (more than two envelopes), + slow_ms 7000 (more than the window), trickle interval 250 ms (shorter than the 500 ms + connect_timeout_ms, so the socket never idles that long), + database_catalog_drop_error_cooldown_sec 600 (a failed removal is not requeued while a test + checks it). + +The kill tests run on `node_stop` (configs/storage_conf_stop.xml): attempt timeout 8000 ms, so a +request parked for the kill handshake is not abandoned by its attempt timeout first. A plain `DROP TABLE` +there is removed at once (configs/drop_delay.xml). It runs with Keeper and transactions enabled +(configs/transactions.xml), and uploads a part's blobs one at a time (configs/blob_upload_serial.xml). + +The GC test runs on `node_gc` (configs/storage_conf_gc.xml): the same timing and a one-hour GC interval. +A manual round never takes the GC lease from another process, and a restart leaves the lease with the +previous one, so this server is never restarted. + +Each test drops the tables it leaves and scopes its fault rules and trace to its own pool, so the module +passes in any order and when repeated. +""" + +import json +import os +import re +import subprocess +import threading +import time +import urllib.request + +import pytest + +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) + +POLICY = "cas_window" +SLOW_MS = 7000 +WINDOW_S = 5 +WINDOW_PREFIX = "/test/cas_request_window/" +CATALOG = WINDOW_PREFIX + "cas/ref_catalog" +STOP_POLICY = "cas_stop" +STOP_PREFIX = "/test/cas_request_stop/" +STOP_CATALOG = STOP_PREFIX + "cas/ref_catalog" +# `cas_attempt_timeout_ms` of `configs/storage_conf_stop.xml`: a parked request's socket gives up after it. +STOP_ATTEMPT_TIMEOUT_S = 8 +# The store behind the proxy, which the servers can read directly. +STORE_URL = "http://rustfs1:11121" +GC_DISK = "disk_cas_gc" +# Without slashes, so it also matches a listing's URL-encoded `prefix` parameter. +GC_POOL = "cas_request_gc" + + +def _control(url, path, patch=None): + data = None if patch is None else json.dumps(patch).encode() + request = urllib.request.Request( + url + path, data=data, headers={"Content-Type": "application/json"}, method="GET" if data is None else "POST" + ) + with urllib.request.urlopen(request, timeout=10) as response: + return json.loads(response.read().decode()) + + +def _wait_until(probe, timeout): + end = time.monotonic() + timeout + while time.monotonic() < end: + result = probe() + if result: + return result + time.sleep(0.2) + raise AssertionError("condition did not become true within {}s".format(timeout)) + + +@pytest.fixture(scope="module") +def node(): + cluster.add_instance( + "node", + main_configs=["configs/storage_conf.xml", "configs/drop_cooldown.xml"], + with_rustfs=True, + ) + # `stay_alive` lets a test restart the server, which drops its cached ref tables. + cluster.add_instance("node_stop", main_configs=["configs/storage_conf_stop.xml", "configs/drop_delay.xml", + "configs/transactions.xml", "configs/blob_upload_serial.xml"], + with_rustfs=True, with_zookeeper=True, stay_alive=True) + cluster.add_instance("node_gc", main_configs=["configs/storage_conf_gc.xml"], with_rustfs=True) + cluster.base_cmd.extend(["--file", os.path.join(os.path.dirname(__file__), "docker_compose_proxy.yml")]) + try: + cluster.start() + binding = subprocess.check_output(cluster.base_cmd + ["port", "s3proxy", "8474"], text=True).strip() + cluster.proxy_url = "http://{}".format(binding) + _wait_until(lambda: _control(cluster.proxy_url, "/healthz"), timeout=30) + yield cluster.instances["node"] + finally: + cluster.shutdown() + + +@pytest.fixture(scope="module") +def node_stop(node): + return cluster.instances["node_stop"] + + +@pytest.fixture(scope="module") +def node_gc(node): + return cluster.instances["node_gc"] + + +def _drop_all_tables(instance): + for name in instance.query("SELECT table FROM system.detached_tables WHERE database = 'default'").split(): + instance.query("ATTACH TABLE default.`{}`".format(name)) + for name in instance.query("SELECT name FROM system.tables WHERE database = 'default'").split(): + instance.query("DROP TABLE default.`{}` SYNC".format(name)) + + +@pytest.fixture(autouse=True) +def clean_state(node, node_stop, node_gc): + _control(cluster.proxy_url, "/config", {"reset": True}) + yield + _control(cluster.proxy_url, "/config", {"reset": True}) + for instance in (node, node_stop, node_gc): + _drop_all_tables(instance) + + +def _arm(**config): + _control(cluster.proxy_url, "/config", dict(rate=1.0, trace=True, **config)) + + +def _stats(): + return _control(cluster.proxy_url, "/stats") + + +def _create(node, name): + node.query( + "CREATE TABLE {} (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(name, POLICY) + ) + + +def test_long_body_with_a_lost_response_commits(node): + _create(node, "long_body") + _arm( + modes=["slow_then_drop"], methods=["PUT"], path_substring=[WINDOW_PREFIX, "/blobs/"], remaining_faults=1, + slow_ms=SLOW_MS, trace_path_substring=[WINDOW_PREFIX, "/blobs/"], + ) + # A random body, so no earlier run stored it and the `PUT` is not skipped. + node.query("INSERT INTO long_body SELECT number, randomPrintableASCII(16) FROM numbers(1000)", timeout=60) + + stats = _stats() + dropped = stats["drop_after_forward"] + assert len(dropped) == 1, dropped + key = dropped[0]["path"] + assert dropped[0]["upstream_status"] == 200, dropped + trace = stats["trace"] + puts = [i for i, r in enumerate(trace) if r["method"] == "PUT" and r["path"] == key] + # The HEAD proves the landed body, so it is never sent again. + assert len(puts) == 1, trace + assert any(r["method"] == "HEAD" and r["path"] == key and r["status"] == 200 for r in trace[puts[0] + 1:]), trace + assert node.query("SELECT count() FROM long_body").strip() == "1000" + + +def _remount_attempts(node): + return int(node.query("SELECT sum(value) FROM system.events WHERE event = 'CASRemountAttempts'").strip()) + + +def test_slow_catalog_read_then_drop(node): + # GC is off for this disk. A remount also reads the catalog, so the test checks that none started. + _create(node, "slow_catalog") + node.query("INSERT INTO slow_catalog VALUES (1, 'x')") + remounts_before = _remount_attempts(node) + retries_before = node.count_in_log("Will retry later").strip() + _arm( + modes=["trickle"], methods=["GET"], path_substring=CATALOG, remaining_faults=1, + slow_ms=SLOW_MS, trace_path_substring=CATALOG, + ) + drop_started_ms = time.monotonic() * 1000.0 + drop = node.get_query_request("DROP TABLE slow_catalog SYNC", timeout=90) + + def settled(): + trace = _stats()["trace"] + return all(r["status"] is not None for r in trace) and all( + r["outcome"] is not None for r in trace if r["fault"] == "trickle") + + # A failed removal is requeued only after the 600 s cooldown and logs "Will retry later". + _wait_until(lambda: (drop.process.poll() is not None + or node.count_in_log("Will retry later").strip() != retries_before) and settled(), timeout=60) + trace = sorted(_stats()["trace"], key=lambda r: r["t_mono_ms"]) + assert _remount_attempts(node) == remounts_before + + slowed = trace[0] + assert slowed["fault"] == "trickle" and slowed["method"] == "GET" and slowed["status"] == 200, trace + first_put = next((i for i, r in enumerate(trace) if r["method"] == "PUT" and r["status"] == 200), None) + assert first_put is not None, trace + assert slowed["outcome"] == "delivered", trace + assert slowed["t_last_piece_mono_ms"] - slowed["t_mono_ms"] > WINDOW_S * 1000, trace + assert slowed["t_mono_ms"] >= drop_started_ms, (drop_started_ms, trace) + # The removal reads the catalog twice before its write; another attempt of the slowed read would + # add a GET here. + prefix = trace[:first_put + 1] + assert len(prefix) == 3, trace + assert prefix[1]["method"] == "GET" and prefix[1]["status"] == 200, trace + assert prefix[1]["t_mono_ms"] > slowed["t_last_piece_mono_ms"], trace + assert node.count_in_log("Will retry later").strip() == retries_before + drop.get_answer() + + +def test_failing_catalog_read_gives_up_at_its_window(node): + """Every catalog request answers 503. The `CREATE TABLE` fails in its first catalog read, which gives up at its + request window: every attempt of that read is a `GET` sent within the window from the first one, and nothing is + sent after it. One operation only, so this does not show that a later operation gets a window of its own.""" + _arm(modes=["503"], methods=["GET", "PUT", "HEAD"], path_substring=CATALOG, trace_path_substring=CATALOG) + error = node.query_and_get_error("CREATE TABLE failing (id UInt64) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(POLICY)) + assert re.search(r"read of '[^']*ref_catalog': gave up at the policy deadline after (\d+|zero|one or more) " + r"attempt\(s\)", error), error + + # The slack covers scheduling only. Waiting it out on the proxy's clock lets a late attempt show up. + first_ms = _stats()["trace"][0]["t_mono_ms"] + window_end_ms = first_ms + WINDOW_S * 1000 + 500 + _wait_until(lambda: _stats()["now_mono_ms"] > window_end_ms, timeout=2 * WINDOW_S) + trace = _stats()["trace"] + assert len(trace) > 1 and all(r["method"] == "GET" and r["status"] == 503 for r in trace), trace + assert not [r for r in trace if r["t_mono_ms"] > window_end_ms], trace + + +def _rule(method, path_substring, action, count=1, body_substring=None): + return {"method": method, "path_substring": path_substring, "action": action, "count": count, + "body_substring": body_substring} + + +def _arm_rules(rules): + _control(cluster.proxy_url, "/config", + {"rules": rules, "trace": True, "trace_path_substring": STOP_PREFIX, "trace_bodies": True}) + + +def _create_sql(name): + return "CREATE TABLE {} (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " \ + "SETTINGS storage_policy = '{}'".format(name, STOP_POLICY) + + +def _stop_and_release(node, query_id, path_substring, respond="forward", kill=True): + """Parked request, stop, `is_cancelled`, release: nothing the stopped query does after the release + can predate the stop. Returns the release time on the proxy's clock.""" + parked = _wait_until( + lambda: [p for p in _control(cluster.proxy_url, "/parked")["parked"] if path_substring in p["path"]], timeout=60) + assert len(parked) == 1, parked + # The release must reach the parked request before its socket times out, or the stopped query sees a timeout + # instead of the released answer. Killed and polled over HTTP: a client start per query is slow in a sanitizer + # build. + if kill: + node.http_query("KILL QUERY WHERE query_id = '{}' ASYNC".format(query_id)) + # `ASYNC` returns before the query is marked cancelled. + _wait_until(lambda: node.http_query( + "SELECT is_cancelled FROM system.processes WHERE query_id = '{}'".format(query_id)).strip() == "1", + timeout=STOP_ATTEMPT_TIMEOUT_S - 1) + _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": respond}) + released = [r for r in _stats()["trace"] if r["t_release_mono_ms"] is not None] + assert len(released) == 1, released + return released[0]["t_release_mono_ms"] + + +def _catalog_puts(trace): + return [r for r in trace if r["method"] == "PUT" and r["path"].startswith(STOP_CATALOG)] + + +def _remaining_counts(): + return [r["count"] for r in _stats()["rules"]] + + +def _events(node, event): + return int(node.query("SELECT sum(value) FROM system.events WHERE event = '{}'".format(event)).strip()) + + +def _stop_settings(stop): + return {"max_execution_time": 3, "timeout_overflow_mode": "throw"} if stop == "timeout" else None + + +def _catalog_entries(record): + """The namespace entries of a traced catalog `PUT`, parsed from its body.""" + entries = (json.loads(line) for line in (record["body"] or "").splitlines()) + return [e for e in entries if e.get("kind") == "entry"] + + +def _namespace_of(trace, life): + namespaces = {e["ns"] for r in _catalog_puts(trace) for e in _catalog_entries(r) if e["life"] == life} + assert len(namespaces) == 1, (life, namespaces) + return namespaces.pop() + + +def _life_of(trace, uuid): + """The namespace life that the catalog writes in `trace` give the table with `uuid`. A temporary table's + namespace carries the UUID URL-encoded.""" + forms = (uuid, uuid.replace("-", "%2D")) + lives = {e["life"] for r in _catalog_puts(trace) for e in _catalog_entries(r) if any(f in e["ns"] for f in forms)} + assert len(lives) == 1, (uuid, lives) + return lives.pop() + + +def _table_uuid(node, name): + return node.query("SELECT uuid FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).strip() + + +def _create_with_life(node, name): + """Creates `name` on `STOP_POLICY` and returns its namespace life.""" + _arm_rules([]) + seen = len(_stats()["trace"]) + node.query(_create_sql(name)) + return _life_of(_stats()["trace"][seen:], _table_uuid(node, name)) + + +def _stored_lines(node, path): + """The text lines of the compressed object at `path`, read from the store past the proxy.""" + return node.http_query( + "SELECT line FROM s3('{}{}', 'clickhouse', 'clickhouse', 'LineAsString', 'line String', 'zstd') " + "FORMAT TSVRaw".format(STORE_URL, path.split("?")[0])).splitlines() + + +def _landed_log_records(trace, life): + return [r for r in trace if r["method"] == "PUT" and r["status"] == 200 + and "cas/ns/stream/{}/_log/".format(life) in r["path"]] + + +def _log_ops(node, record): + """The operations of a landed ref-log record.""" + return [json.loads(line) for line in _stored_lines(node, record["path"]) if line.startswith('{"op"')] + + +def _removal_records(node, trace, life): + """The landed ref-log records of `life` in `trace` that carry the terminal `remove_namespace` operation and + follow a landed catalog write that moved `life` to `Removing`.""" + marked = [r["t_mono_ms"] for r in _catalog_puts(trace) + if r["status"] == 200 and _removing_body(life) in (r["body"] or "")] + if not marked: + return [] + return [r for r in _landed_log_records(trace, life) if r["t_mono_ms"] > marked[0] + and any(op["op"] == "remove_namespace" for op in _log_ops(node, r))] + + +def _brief(trace): + """`trace` without request bodies, for an assertion message.""" + return [(r["method"], r["path"], r["status"], r["rule"]) for r in trace] + + +def _removing_body(life): + """A substring of exactly the catalog writes that name `life` as `Removing`.""" + return '"state":"removing","life":"{}"'.format(life) + + +@pytest.mark.parametrize("stop", ["kill", "timeout"]) +def test_stop_after_accepted_conflicts_permits_next_put(node_stop, stop): + """Three `PUT`s of a catalog write meet 412; the read that settles the third is parked while the query stops and + then succeeds. An accepted conflict is an answer, not a failure, so the fourth `PUT` is sent and lands.""" + rules = [] + for action in ("forward", "forward", "hold"): + rules += [_rule("PUT", STOP_CATALOG, "412"), _rule("GET", STOP_CATALOG, action)] + _arm_rules(rules) + query_id = "accepted_conflicts_" + stop + request = node_stop.get_query_request( + _create_sql(query_id), query_id=query_id, settings=_stop_settings(stop), timeout=120) + released_ms = _stop_and_release(node_stop, query_id, STOP_CATALOG, kill=(stop == "kill")) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + puts = _catalog_puts(trace) + assert [r["status"] for r in puts[:4]] == [412, 412, 412, 200], trace + assert puts[3]["t_mono_ms"] > released_ms, trace + assert _remaining_counts() == [0] * 6 + # Whether the stopped `CREATE` still reports its stop after the catalog write is outside CAS. + _, error = request.get_answer_and_error() + if request.process.returncode != 0: + assert re.search(r"Code: {}\b".format(394 if stop == "kill" else 159), error), error + + +@pytest.mark.parametrize("stop", ["kill", "timeout"]) +def test_failed_settlement_after_stop_starts_no_further_put(node_stop, stop): + """A catalog write meets 412 and its settling read is parked while the query stops, then answered with 503. That + read failed after the stop, so the write ends with its conflict and no further `PUT` is sent.""" + _arm_rules([_rule("PUT", STOP_CATALOG, "412"), _rule("GET", STOP_CATALOG, "hold"), + _rule("PUT", STOP_CATALOG, "412", count=1000)]) + query_id = "failed_settlement_" + stop + request = node_stop.get_query_request( + _create_sql(query_id), query_id=query_id, settings=_stop_settings(stop), timeout=120) + released_ms = _stop_and_release(node_stop, query_id, STOP_CATALOG, respond="503", kill=(stop == "kill")) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + assert [r["status"] for r in _catalog_puts(trace)] == [412], trace + assert not [r for r in _catalog_puts(trace) if r["t_mono_ms"] > released_ms], trace + error = request.get_error() + # `ABORTED`: the conflict the settling read could not resolve. + assert re.search(r"Code: 236\b", error) and "conflict" in error, error + assert _remaining_counts() == [0, 0, 1000] + + +def test_kill_after_ambiguous_create_keeps_unresolved_exit(node_stop): + _arm_rules([_rule("PUT", STOP_CATALOG, "503"), _rule("GET", STOP_CATALOG, "hold")]) + query_id = "ambiguous_create" + request = node_stop.get_query_request(_create_sql("ambiguous_create"), query_id=query_id, timeout=120) + _stop_and_release(node_stop, query_id, STOP_CATALOG) + _wait_until(lambda: request.process.poll() is not None or len(_catalog_puts(_stats()["trace"])) > 1, timeout=60) + trace = _stats()["trace"] + assert [r["status"] for r in _catalog_puts(trace)] == [503], trace + error = request.get_error() + # The pause before the next decision vetoes it and returns the unresolved send. + assert re.search(r"Code: 210\b", error) and "the write is unresolved (sent" in error, error + assert _remaining_counts() == [0, 0] + + # Control: a live owner decides again after each ambiguous attempt until one lands. + _control(cluster.proxy_url, "/config", {"reset": True}) + _arm_rules([_rule("PUT", STOP_CATALOG, "503", count=8)]) + node_stop.query(_create_sql("ambiguous_create_live"), timeout=120) + statuses = [r["status"] for r in _catalog_puts(_stats()["trace"])] + assert statuses[:9] == [503] * 8 + [200], statuses + assert _remaining_counts() == [0] + assert node_stop.query("EXISTS TABLE ambiguous_create_live").strip() == "1" + + +def test_killed_leader_with_chunk_in_flight_leaves_a_usable_lane(node_stop): + """A killed ref-log leader whose chunk `PUT` fails settles it by a read that meets a 404. The S3 client + reports that 404 as the leader's stop, so the lane may need one recovery; a concurrent insert into the + table still commits and later inserts work. Whether the concurrent insert shares the leader's chunk is + not observable here.""" + life = _create_with_life(node_stop, "ref_batch") + wedged_before = _events(node_stop, "CASRefAppendWedged") + _arm_rules([_rule("PUT", [STOP_PREFIX, "cas/ns/stream/{}/_log/".format(life)], "hold")]) + # A synchronous insert appends from the query's own thread, so the kill reaches the chunk's leader. + sync = {"async_insert": 0} + leader = node_stop.get_query_request("INSERT INTO ref_batch VALUES (1, 'leader')", query_id="ref_batch_leader", + settings=sync, timeout=120) + _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + neighbor = node_stop.get_query_request("INSERT INTO ref_batch VALUES (2, 'neighbor')", settings=sync, timeout=120) + # The release answers 503 without forwarding, so the chunk's settling read meets a 404. + released_ms = _stop_and_release(node_stop, "ref_batch_leader", "/_log/", respond="503") + neighbor.get_answer() + _wait_until(lambda: leader.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + held = next(r for r in trace if r["rule"] == "hold") + assert held["status"] == 503, trace + assert [r for r in trace if r["method"] == "GET" and r["path"] == held["path"] and r["status"] == 404 + and r["t_mono_ms"] > released_ms], trace + assert _events(node_stop, "CASRefAppendWedged") <= wedged_before + 1, trace + assert _remaining_counts() == [0] + assert node_stop.query("SELECT count() FROM ref_batch WHERE id = 2").strip() == "1" + node_stop.query("INSERT INTO ref_batch VALUES (3, 'after')", settings=sync) + assert node_stop.query("SELECT count() FROM ref_batch WHERE id = 3").strip() == "1" + + +def test_atomic_sync_drop_kill_releases_only_waiter(node_stop): + """Killing `DROP TABLE ... SYNC` in an `Atomic` database stops only the waiting query. The background + removal keeps its parked catalog request and completes in the same attempt.""" + life = _create_with_life(node_stop, "atomic_sync_drop") + node_stop.query("INSERT INTO atomic_sync_drop VALUES (1, 'x')") + uuid = _table_uuid(node_stop, "atomic_sync_drop") + retries_before = node_stop.count_in_log("Will retry later").strip() + _arm_rules([_rule("PUT", STOP_CATALOG, "hold", body_substring=_removing_body(life))]) + seen = len(_stats()["trace"]) + query_id = "atomic_sync_drop" + request = node_stop.get_query_request("DROP TABLE atomic_sync_drop SYNC", query_id=query_id, timeout=120) + parked = _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + assert len(parked) == 1, parked + # Over HTTP: the parked write must still be parked when the kill returns. + node_stop.http_query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) + _wait_until(lambda: request.process.poll() is not None, timeout=30) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + assert _control(cluster.proxy_url, "/parked")["parked"] == parked + + _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) + _wait_until(lambda: node_stop.query( + "SELECT count() FROM system.dropped_tables WHERE uuid = '{}'".format(uuid)).strip() == "0", timeout=60) + _wait_until(lambda: _removal_records(node_stop, _stats()["trace"][seen:], life), timeout=60) + trace = _stats()["trace"][seen:] + assert [r["status"] for r in _catalog_puts(trace)] == [200], _brief(trace) + assert _remaining_counts() == [0] + assert node_stop.count_in_log("Will retry later").strip() == retries_before + + +def _active_parts(node, name): + return node.query("SELECT name FROM system.parts WHERE table = '{}' AND active ORDER BY name".format(name)) + + +def _detach_cold(node, name): + """Creates a one-part table of two rows, detaches it permanently and restarts the server so its ref table is not + cached. Returns the table's namespace life and its active parts before the detach.""" + life = _create_with_life(node, name) + node.query("INSERT INTO {} VALUES (1, 'a'), (2, 'b')".format(name)) + parts = _active_parts(node, name) + node.query("DETACH TABLE {} PERMANENTLY".format(name)) + node.restart_clickhouse() + _control(cluster.proxy_url, "/config", {"reset": True}) + return life, parts + + +def _assert_reattached(node, name, parts): + """Every part of `_detach_cold`'s table is active again, and none was detached as broken.""" + assert _active_parts(node, name) == parts + assert node.query("SELECT count() FROM {}".format(name)).strip() == "2" + assert _broken_on_start(node, name) == "0" + + +def _cold_attach_with_parked_walk(node, name, respond, settings=None): + """Runs `ATTACH TABLE` on `_detach_cold`'s table with the first `_log/` GET of its namespace life parked, stops + the query and releases the GET with `respond`. Returns the request, the life's id, the release time and the + active parts before the detach.""" + life, parts = _detach_cold(node, name) + _arm_rules([_rule("GET", [STOP_PREFIX, "cas/ns/stream/{}/_log/".format(life)], "hold")]) + request = node.get_query_request("ATTACH TABLE {}".format(name), query_id=name, settings=settings, timeout=120) + released_ms = _stop_and_release(node, name, "/_log/", respond=respond, kill=settings is None) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + return request, life, released_ms, parts + + +def _broken_on_start(node, name): + return node.query( + "SELECT count() FROM system.detached_parts WHERE table = '{}' AND reason = 'broken-on-start'".format(name)).strip() + + +def test_killed_cold_attach_keeps_parts_active(node_stop): + """A stopped `ATTACH TABLE` whose cold ref walk reads a healthy store, then a second `ATTACH` if the + stop ended the first one: every part is active. When the first `ATTACH` fails, it fails in the ref walk + before any part loads, so the `broken-on-start` check then covers only the second `ATTACH`.""" + request, _, _, parts = _cold_attach_with_parked_walk(node_stop, "cold_attach", respond="forward") + _, error = request.get_answer_and_error() + if request.process.returncode != 0: + assert re.search(r"Code: 394\b", error), error + node_stop.query("ATTACH TABLE cold_attach") + _assert_reattached(node_stop, "cold_attach", parts) + assert _remaining_counts() == [0] + + +def test_kill_during_cold_ref_walk(node_stop): + """An `ATTACH TABLE` whose query timed out while its cold ref walk failed ends without another walk; a + second query recovers the data. The timeout's 159 is a transient code, so only the owner check keeps + recovery from walking again.""" + request, life, released_ms, parts = _cold_attach_with_parked_walk( + node_stop, "cold_walk", respond="503", settings={"max_execution_time": 3, "timeout_overflow_mode": "throw"}) + error = request.get_error() + assert re.search(r"Code: 159\b", error), error + trace = _stats()["trace"] + assert not [r for r in trace if life in r["path"] and r["t_mono_ms"] > released_ms], trace + node_stop.query("ATTACH TABLE cold_walk") + _assert_reattached(node_stop, "cold_walk", parts) + + +def test_kill_in_recovery_backoff_keeps_the_store_error(node_stop): + """A cold `ATTACH TABLE` whose ref walk failed on store errors while the query was live, killed in the backoff + before the next walk: no other walk starts, and the query ends with the walk's own retryable `NETWORK_ERROR`, not + with its stop. A second `ATTACH` loads every part, and none is detached as broken.""" + name = "backoff_kill" + life, parts = _detach_cold(node_stop, name) + # Every read of the life's log fails, so the walk fails once its request window passes. + _arm_rules([_rule("GET", [STOP_PREFIX, "cas/ns/stream/{}/_log/".format(life)], "503", count=1000)]) + + def recovery_retries(): + return int(node_stop.http_query( + "SELECT sum(value) FROM system.events WHERE event = 'CASRefRecoveryRetries'").strip() or 0) + + retries_before = recovery_retries() + request = node_stop.get_query_request("ATTACH TABLE {}".format(name), query_id=name, timeout=120) + # Counted right before the backoff, which lasts a second before the next walk. Polled and killed over HTTP: + # starting a client per poll or for the kill can take most of that second in a sanitizer build. + end = time.monotonic() + 60 + while recovery_retries() == retries_before: + assert time.monotonic() < end and request.process.poll() is None, "the walk did not fail" + time.sleep(0.02) + life_gets_at_kill = len([r for r in _stats()["trace"] if life in r["path"]]) + node_stop.http_query("KILL QUERY WHERE query_id = '{}' ASYNC".format(name)) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + error = request.get_error() + # The walk's own give-up on the life's log, not a retry-later of another request. + assert re.search(r"Code: 210\b", error) and re.search(r"_log/.*gave up at the \w+ deadline", error, re.DOTALL), error + assert len([r for r in _stats()["trace"] if life in r["path"]]) == life_gets_at_kill, "another walk started" + + _control(cluster.proxy_url, "/config", {"reset": True}) + node_stop.query("ATTACH TABLE {}".format(name)) + _assert_reattached(node_stop, name, parts) + + +def _blob_puts_after(trace, released_ms): + return [r for r in trace if r["method"] == "PUT" and "/blobs/" in r["path"] and r["t_mono_ms"] > released_ms] + + +def test_kill_while_blob_head_is_parked_publishes_nothing(node_stop): + """A query killed while the `HEAD` of its part's only blob, a new body, is parked: the `HEAD` is released and + answers 404, which the S3 client reports as the query's stop, so the upload ends with 394 before any publication + of that blob. No blob publication starts after the release, no part is committed, and the next insert succeeds. + An outcome test: the check before a publication is not reached here; the unit tests cover it.""" + node_stop.query("CREATE TABLE blob_head_kill {}".format(ONE_BLOB_TABLE)) + _arm_rules([_rule("HEAD", [STOP_PREFIX, "/blobs/"], "hold")]) + request, query_id = _blob_fixture_insert(node_stop, "blob_head_kill", ONE_BLOB_INSERT) + released_ms = _stop_and_release(node_stop, query_id, "/blobs/") + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + held = next(r for r in trace if r["rule"] == "hold") + assert held["status"] == 404, trace + assert not [r for r in trace if r["method"] == "PUT" and r["path"] == held["path"]], trace + assert not _blob_puts_after(trace, released_ms), trace + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + assert _remaining_counts() == [0] + assert node_stop.query("SELECT count() FROM blob_head_kill").strip() == "0" + + node_stop.query("INSERT INTO blob_head_kill VALUES (1, 'next')") + assert node_stop.query("SELECT count() FROM blob_head_kill").strip() == "1" + + +def _blob_requests(trace, method): + return [r for r in trace if r["method"] == method and "/blobs/" in r["path"]] + + +# One blob per part: a packed part keeps every file in `data.packed`. +ONE_BLOB_TABLE = "(id UInt64, payload String) ENGINE = MergeTree ORDER BY id " \ + "SETTINGS storage_policy = '{}', min_bytes_for_full_part_storage = '1G'".format(STOP_POLICY) +ONE_BLOB_INSERT = "INSERT INTO {} SELECT number, randomPrintableASCII(100) FROM numbers(10000)" +# Two new blobs per part: the `Wide` column bodies are random. Uncompressed fixed-length values make the marks and +# the index the same in every part, so after the first part they are reused and only answer a `HEAD`. The second +# argument of `randomPrintableASCII` keeps the two calls distinct: one call would give both columns one body. +TWO_BLOB_TABLE = "(a String CODEC(NONE), b String CODEC(NONE)) ENGINE = MergeTree ORDER BY tuple() " \ + "SETTINGS storage_policy = '{}', min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, " \ + "min_bytes_for_full_part_storage = 0".format(STOP_POLICY) +TWO_BLOB_INSERT = "INSERT INTO {} SELECT randomPrintableASCII(100, 1), randomPrintableASCII(100, 2) FROM numbers(10000)" + + +def _checked_blob_fixture(node, name, table, insert, new_blobs): + """Creates `name`, after checking on two other tables of the same shape that an insert of `insert` publishes + exactly `new_blobs` blobs and reuses every other one. The first of them stores the reusable bodies.""" + for suffix in ("_warm", "_control"): + node.query("CREATE TABLE {}{} {}".format(name, suffix, table)) + _arm_rules([]) + node.query(insert.format(name + "_warm"), settings={"async_insert": 0}) + seen = len(_stats()["trace"]) + node.query(insert.format(name + "_control"), settings={"async_insert": 0}) + trace = _stats()["trace"][seen:] + puts = sorted({r["path"] for r in _blob_requests(trace, "PUT")}) + missing = sorted({r["path"] for r in _blob_requests(trace, "HEAD") if r["status"] == 404}) + assert len(puts) == new_blobs and puts == missing, \ + "the fixture of {} publishes {} blob(s), not {}: PUT {}, HEAD 404 {}".format(name, len(puts), new_blobs, puts, missing) + node.query("CREATE TABLE {} {}".format(name, table)) + _control(cluster.proxy_url, "/config", {"reset": True}) + + +def _blob_fixture_insert(node, name, insert): + query_id = name + "_insert" + request = node.get_query_request(insert.format(name), query_id=query_id, settings={"async_insert": 0}, timeout=120) + return request, query_id + + +def test_kill_during_last_blob_upload_commits_the_part(node_stop): + """The insert's part has one blob. A query killed while its `PUT` is parked: the `PUT` is released and lands, and + adoption, promotion and the part rename are no safe points and meet no failure, so the part is committed. No blob + publication starts after the release.""" + name = "blob_last_put_kill" + _checked_blob_fixture(node_stop, name, ONE_BLOB_TABLE, ONE_BLOB_INSERT, new_blobs=1) + _arm_rules([_rule("PUT", [STOP_PREFIX, "/blobs/"], "hold")]) + request, query_id = _blob_fixture_insert(node_stop, name, ONE_BLOB_INSERT) + released_ms = _stop_and_release(node_stop, query_id, "/blobs/") + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + puts = _blob_requests(trace, "PUT") + assert [(r["rule"], r["status"]) for r in puts] == [("hold", 200)], trace + assert not _blob_puts_after(trace, released_ms), trace + _, error = request.get_answer_and_error() + # The query may still report its kill once the part is committed. + if request.process.returncode != 0: + assert re.search(r"Code: 394\b", error), error + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "10000" + assert _remaining_counts() == [0] + + node_stop.query("INSERT INTO {} VALUES (100000, 'next')".format(name)) + assert node_stop.query("SELECT count() FROM {} WHERE id = 100000".format(name)).strip() == "1" + + +def test_kill_during_first_blob_upload_publishes_no_later_blob(node_stop): + """The insert's part has two new blobs, published one after another. A query killed while the first `PUT` is + parked: the `PUT` is released and lands, then the second blob's `HEAD` answers 404, which the S3 client reports as + the query's stop. The second blob is not published, the insert ends with 394 and commits nothing.""" + name = "blob_first_put_kill" + _checked_blob_fixture(node_stop, name, TWO_BLOB_TABLE, TWO_BLOB_INSERT, new_blobs=2) + _arm_rules([_rule("PUT", [STOP_PREFIX, "/blobs/"], "hold")]) + request, query_id = _blob_fixture_insert(node_stop, name, TWO_BLOB_INSERT) + released_ms = _stop_and_release(node_stop, query_id, "/blobs/") + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + held = next(r for r in trace if r["rule"] == "hold") + assert held["status"] == 200, trace + later_misses = [r for r in _blob_requests(trace, "HEAD") + if r["t_mono_ms"] > released_ms and r["path"] != held["path"] and r["status"] == 404] + assert len(later_misses) == 1, trace + assert not [r for r in _blob_requests(trace, "PUT") if r["path"] == later_misses[0]["path"]], trace + assert not _blob_puts_after(trace, released_ms), trace + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "0" + assert _remaining_counts() == [0] + + node_stop.query("INSERT INTO {} VALUES ('next', 'next')".format(name)) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "1" + + +LIFE_LOG = re.compile(r"cas/ns/stream/([0-9a-f]+)/_log/") + + +def _landed_log_puts(trace): + """The lives of the ref-log `PUT`s in `trace` that landed.""" + return [m.group(1) for r in trace if r["method"] == "PUT" and r["status"] == 200 + for m in [LIFE_LOG.search(r["path"])] if m] + + +def _killed_after_first_ref_append(node, query_id, sql, settings): + """Runs `sql`, which creates a table and writes one part per second into it, and kills it once a ref-log append + has landed, so the query owns committed CAS work when it stops. Merges are stopped meanwhile. Returns the request + after the query ended, the life of the first append, which the caller attributes, and the length of the proxy + trace when the kill was sent.""" + node.query("SYSTEM STOP MERGES") + try: + _arm_rules([]) + seen = len(_stats()["trace"]) + request = node.get_query_request(sql, query_id=query_id, settings=settings, timeout=120) + appended = _wait_until(lambda: _landed_log_puts(_stats()["trace"][seen:]), timeout=60) + killed_at = len(_stats()["trace"]) + node.query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + finally: + node.query("SYSTEM START MERGES") + return request, appended[0], killed_at + + +ONE_PART_PER_SECOND = {"max_block_size": 1, "max_insert_block_size": 1, "min_insert_block_size_rows": 0, + "min_insert_block_size_bytes": 0, "async_insert": 0} + + +ROLLED_BACK_CSN = 2**64 - 1 + + +def _rolled_back_installs(node, trace, life, part): + """The landed ref-log records of `life` in `trace` that install `part` with a manifest, also written in + `trace`, whose `txn_version.txt` carries the rolled-back creation CSN.""" + namespace = _namespace_of(_stats()["trace"], life) + rolled_back = set() + for r in trace: + if r["method"] == "PUT" and r["status"] == 200 and "/cas/manifests/" in r["path"]: + lines = _stored_lines(node, r["path"]) + header = json.loads(lines[1]) + if header["namespace"] == namespace and "creation_csn: {}".format(ROLLED_BACK_CSN) in lines: + rolled_back.add((header["epoch"], header["build"])) + return [r for r in _landed_log_records(trace, life) for op in _log_ops(node, r) + if op.get("new_ref") == part and (op["new_epoch"], op["new_build"]) in rolled_back] + + +def test_killed_implicit_transaction_insert_rolls_back(node_stop): + """An `INSERT` in an implicit transaction killed after the transaction registered a part it created: the + transaction rolls back and persists that part's rolled-back version. A ref-log record that lands after the kill + and before the query ends installs the registered part with a manifest whose `txn_version.txt` carries the + rolled-back creation CSN. Only the row inserted before remains, the server keeps running, and the next + transactional insert succeeds.""" + name = "txn_kill" + life = _create_with_life(node_stop, name) + try: + node_stop.query("SYSTEM STOP MERGES") + node_stop.query("INSERT INTO {} VALUES (1000, 'first')".format(name)) + fatal_before = int(node_stop.count_in_log("").strip()) + query_id = "txn_kill_insert" + request = node_stop.get_query_request( + "INSERT INTO {} SELECT number, 'x' FROM numbers(30) WHERE sleepEachRow(1) = 0".format(name), + query_id=query_id, settings=dict(ONE_PART_PER_SECOND, implicit_transaction=1), timeout=120) + # A part of an uncommitted transaction is active with an unknown CSN once the transaction registered it. + registered = _wait_until(lambda: node_stop.query( + "SELECT name FROM system.parts WHERE table = '{}' AND active AND creation_csn = 0 LIMIT 1".format(name)).strip(), + timeout=60) + killed_at = len(_stats()["trace"]) + node_stop.query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + ended_at = len(_stats()["trace"]) + # A merge of transactional parts is not supported on a CAS disk. + node_stop.query("SYSTEM STOP MERGES {}".format(name)) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + window = _stats()["trace"][killed_at:ended_at] + assert _rolled_back_installs(node_stop, window, life, registered), (registered, window) + # The cleanup may already have removed the rolled-back part. + csn = node_stop.query( + "SELECT creation_csn FROM system.parts WHERE table = '{}' AND name = '{}'".format(name, registered)).strip() + assert csn in ("", str(ROLLED_BACK_CSN)), (registered, csn) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "1" + assert int(node_stop.count_in_log("").strip()) == fatal_before + + node_stop.query("INSERT INTO {} VALUES (100, 'next')".format(name), + settings={"implicit_transaction": 1, "async_insert": 0}) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "2" + finally: + # Its transactional parts must not meet a merge in a later test, and a server-wide `START MERGES` lifts + # the table's own stop. + try: + node_stop.query("DROP TABLE IF EXISTS {} SYNC".format(name)) + finally: + node_stop.query("SYSTEM START MERGES") + + +def _holder_errors(node): + return int(node.count_in_log(" TemporaryTableHolder").strip()) + + +def _temporary_table_dropped(node, uuid): + """The storage of the temporary table with `uuid` finished dropping its data.""" + return node.count_in_log("({}): dropAllData: done.".format(uuid)).strip() == "1" + + +def test_killed_temporary_table_query_is_dropped_at_disconnect(node_stop): + """A `CREATE TEMPORARY TABLE ... AS SELECT` on a CAS disk killed after it committed a part fails with 394 and + leaves the table in its session. The table is dropped when the client disconnects: its namespace moves to + `Removing` in the catalog, its ref log ends with the terminal record, its storage finishes dropping, and the + server keeps running.""" + fatal_before = int(node_stop.count_in_log("").strip()) + holder_errors_before = _holder_errors(node_stop) + request, life, killed_at = _killed_after_first_ref_append( + node_stop, "temporary_kill", + "CREATE TEMPORARY TABLE temporary_kill (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}' AS SELECT number, 'x' FROM numbers(30) WHERE sleepEachRow(1) = 0".format(STOP_POLICY), + ONE_PART_PER_SECOND) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + namespace = _namespace_of(_stats()["trace"], life) + temporary = re.search(r"/_temporary_and_external_tables/_tmp_([0-9a-f%D]+)@cas@$", namespace) + assert temporary, namespace + uuid = temporary.group(1).replace("%2D", "-") + _wait_until(lambda: _removal_records(node_stop, _stats()["trace"][killed_at:], life), timeout=60) + _wait_until(lambda: _temporary_table_dropped(node_stop, uuid), timeout=60) + # A failed drop is logged by the holder and leaves the table attached. + assert _holder_errors(node_stop) == holder_errors_before + assert int(node_stop.count_in_log("").strip()) == fatal_before + assert node_stop.query("SELECT 1").strip() == "1" + + +def test_killed_replace_of_a_temporary_table_drops_the_replaced_table(node_stop): + """`REPLACE TEMPORARY TABLE` on a CAS disk killed while it fills the new table, after it committed a part. The + query ends with 394 and the session keeps the new table. The replaced table is dropped: its namespace moves to + `Removing` in the catalog, its ref log ends with the terminal record, its storage finishes dropping, and the + server keeps running. GC erases the catalog row later; it is off on this disk.""" + session = {"session_id": "replace_temporary_kill"} + table = "(id UInt64, payload String) ENGINE = MergeTree ORDER BY id SETTINGS storage_policy = '{}'".format(STOP_POLICY) + + def session_query(sql, **params): + return node_stop.http_query(sql, params=dict(session, **params), method="POST") + + def table_uuid(): + return session_query("SELECT uuid FROM system.tables WHERE is_temporary AND name = 'replace_kill'").strip() + + try: + _arm_rules([]) + session_query("CREATE TEMPORARY TABLE replace_kill {}".format(table)) + node_stop.query("SYSTEM STOP MERGES") + session_query("INSERT INTO replace_kill VALUES (1, 'x')") + replaced_uuid = table_uuid() + replaced_life = _life_of(_stats()["trace"], replaced_uuid) + fatal_before = int(node_stop.count_in_log("").strip()) + holder_errors_before = _holder_errors(node_stop) + + query_id = "replace_temporary_kill" + seen = len(_stats()["trace"]) + outcome = {} + + def replace(): + outcome["answer"], outcome["error"] = node_stop.http_query_and_get_answer_with_error( + "REPLACE TEMPORARY TABLE replace_kill {} AS SELECT number, 'y' FROM numbers(30) WHERE sleepEachRow(1) = 0" + .format(table), params=dict(session, query_id=query_id, wait_end_of_query=1, **ONE_PART_PER_SECOND), + method="POST", timeout=120) + + thread = threading.Thread(target=replace) + thread.start() + try: + # The fill starts after the session swapped in the new table, so a part of another life is the fill's. + _wait_until(lambda: [life for life in _landed_log_puts(_stats()["trace"][seen:]) if life != replaced_life], + timeout=60) + killed_at = len(_stats()["trace"]) + node_stop.query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) + finally: + thread.join(timeout=120) + assert not thread.is_alive(), "the killed REPLACE did not return" + assert re.search(r"Code: 394\b", outcome["error"] or ""), outcome + + _wait_until(lambda: _removal_records(node_stop, _stats()["trace"][killed_at:], replaced_life), timeout=60) + _wait_until(lambda: _temporary_table_dropped(node_stop, replaced_uuid), timeout=60) + assert _holder_errors(node_stop) == holder_errors_before + new_uuid = table_uuid() + assert new_uuid and new_uuid != replaced_uuid, (replaced_uuid, new_uuid) + assert int(node_stop.count_in_log("").strip()) == fatal_before + assert node_stop.query("SELECT 1").strip() == "1" + finally: + node_stop.query("SYSTEM START MERGES") + # Dropped now rather than when the session expires or the server stops, during a later test. + session_query("DROP TEMPORARY TABLE IF EXISTS replace_kill") + + +def test_manual_gc_kill_preserves_owner_code(node_gc): + """A killed `SYSTEM CAS GC RUN` whose drain's first catalog `GET` is parked returns 394 and sends no + request of that round after the release. Mount renewals and `gc/hb` pulses continue and are not counted.""" + node_gc.query("CREATE TABLE gc_kill (id UInt64) ENGINE = MergeTree ORDER BY id SETTINGS storage_policy = 'cas_gc'") + node_gc.query("INSERT INTO gc_kill VALUES (1)") + # The first round adopts a generation; only then does a round's drain read the catalog. + first = json.loads(node_gc.http_query("SYSTEM CAS GC RUN {}".format(GC_DISK), + params={"default_format": "JSONEachRow"}, method="POST")) + assert first["acquired_lease"] in (1, True), first + catalog = GC_POOL + "/cas/ref_catalog" + _control(cluster.proxy_url, "/config", + {"rules": [_rule("GET", catalog, "hold")], "trace": True, "trace_path_substring": GC_POOL}) + query_id = "manual_gc_kill" + request = node_gc.get_query_request("SYSTEM CAS GC RUN {}".format(GC_DISK), query_id=query_id, timeout=120) + released_ms = _stop_and_release(node_gc, query_id, catalog) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + late = [r for r in _stats()["trace"] if r["t_mono_ms"] > released_ms + and not r["path"].endswith("/mount") and "/gc/hb" not in r["path"]] + assert not late, late + assert _remaining_counts() == [0] + + +def test_shutdown_hands_atomic_drop_to_restart(node_stop): + """Server shutdown stops the background removal of a dropped table after its `Live -> Removing` write and + before the terminal ref-log record, so the dropped metadata survives the exit and the removal finishes + after restart. One SIGTERM to the exact server PID: a second one, or SIGKILL, would end the process + without the orderly shutdown under test.""" + name = "shutdown_drop" + life = _create_with_life(node_stop, name) + node_stop.query("INSERT INTO {} VALUES (1, 'x')".format(name)) + life_log = "cas/ns/stream/{}/_log/".format(life) + uuid = _table_uuid(node_stop, name) + dropped_metadata = "ls /var/lib/clickhouse/metadata_dropped/ | grep -c {} || true".format(uuid) + stopped_before = int(node_stop.count_in_log("removal stopped by server shutdown").strip()) + shutting_down_before = int(node_stop.count_in_log("Waiting for current connections to close").strip()) + fatal_before = int(node_stop.count_in_log("").strip()) + # Taken before the hold, so only the kill and the log poll run before the parked `PUT`'s attempt timeout. + pid = node_stop.get_process_pid("clickhouse") + assert pid is not None + + _control(cluster.proxy_url, "/config", {"reset": True}) + # Only this table's `Live -> Removing` write names its life as `Removing`. + _arm_rules([_rule("PUT", STOP_CATALOG, "hold", body_substring=_removing_body(life))]) + node_stop.query("DROP TABLE {}".format(name)) + parked = _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + assert len(parked) == 1, parked + node_stop.exec_in_container(["bash", "-c", "kill -15 {}".format(pid)], user="root") + # Logged right after `IsServerShuttingDown` is set, so the removal resumes under shutdown. + _wait_until(lambda: int(node_stop.count_in_log("Waiting for current connections to close").strip()) + > shutting_down_before, timeout=30) + _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) + released_ms = [r for r in _stats()["trace"] if r["t_release_mono_ms"] is not None][0]["t_release_mono_ms"] + _wait_until(lambda: node_stop.get_process_pid("clickhouse") is None, timeout=60) + + trace = _stats()["trace"] + held = next(r for r in trace if r["rule"] == "hold") + assert held["path"].startswith(STOP_CATALOG) and held["status"] == 200, trace + assert _removing_body(life) in held["body"], held + assert [r for r in trace if r["method"] == "PUT" and life_log in r["path"] and r["status"] == 200 + and r["t_mono_ms"] < held["t_mono_ms"]], trace + assert not [r for r in trace if r["method"] == "PUT" and life_log in r["path"] and r["t_mono_ms"] > released_ms], trace + assert node_stop.exec_in_container(["bash", "-c", dropped_metadata]).strip() == "1" + assert int(node_stop.count_in_log("removal stopped by server shutdown").strip()) > stopped_before + # A crash during shutdown also ends the process; an orderly exit logs nothing fatal. + assert int(node_stop.count_in_log("").strip()) == fatal_before + + restarted_ms = _stats()["trace"][-1]["t_mono_ms"] + node_stop.start_clickhouse() + _wait_until(lambda: node_stop.exec_in_container(["bash", "-c", dropped_metadata]).strip() == "0", timeout=60) + assert node_stop.query("SELECT count() FROM system.dropped_tables WHERE uuid = '{}'".format(uuid)).strip() == "0" + + def appended_through_terminal(): + appended = [r for r in _stats()["trace"] + if r["t_mono_ms"] > restarted_ms and r["method"] == "PUT" and life_log in r["path"]] + terminal = [r for r in appended if r["status"] == 200 and _log_ops(node_stop, r)[-1]["op"] == "remove_namespace"] + return appended if terminal else None + + # The retried removal may seal the previous writer epoch first. + appended = _wait_until(appended_through_terminal, timeout=60) + assert all(r["status"] == 200 for r in appended), _brief(appended) From d42bd3d271cdf293f9fec5bf61bfe4ea079ff6fc Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 04:28:16 +0100 Subject: [PATCH 16/47] Document CAS request windows and stopping CAS work Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../antalya/cas/architecture/blob-protocol.md | 9 +++-- .../cas/architecture/garbage-collection.md | 39 +++++++++++-------- docs/en/antalya/cas/configuration.md | 22 +++++++++-- .../antalya/cas/operations/troubleshooting.md | 36 ++++++++++++++++- .../en/operations/system-tables/cas_gc_log.md | 14 +++---- 5 files changed, 89 insertions(+), 31 deletions(-) diff --git a/docs/en/antalya/cas/architecture/blob-protocol.md b/docs/en/antalya/cas/architecture/blob-protocol.md index abf9c644159ea..eefb18431ef73 100644 --- a/docs/en/antalya/cas/architecture/blob-protocol.md +++ b/docs/en/antalya/cas/architecture/blob-protocol.md @@ -96,10 +96,11 @@ Ordered steps in `PartWriteTxn::ensureBlobPresent`: 7. `BlobSource::beginPublication` consumes the shared, monotonic `publication_attempted` state before backend I/O. A lost response cannot re-enable verbatim copy on a later attempt. 8. Retryable or ambiguous failures restart at `HEAD`: up to 8 attempts, each with a fresh envelope. - The engine starts no new attempt after the configured request window (`cas_request_window_ms`, - default 120 s), but an attempt already started can run longer: each creating request waits up to - the disk's `request_timeout_ms`, and multipart part uploads keep their own retries. A write can - therefore take longer than the request window before it fails with a retryable error. No + Each `HEAD` and intent `GET` has its own request window (`cas_request_window_ms`, default 120 s); + the loop has no time limit of its own; 8 attempts are its count. An attempt already started can run longer: each creating + request waits up to the disk's `request_timeout_ms`, and multipart part uploads keep their own + retries. A write can therefore take longer than one request window before it fails with a + retryable error. No dependency proof is recorded until the body was adopted or the publication completed. **Reads go to the store.** The `HEAD` is sent after the precommit edge is durable, and the intent diff --git a/docs/en/antalya/cas/architecture/garbage-collection.md b/docs/en/antalya/cas/architecture/garbage-collection.md index c7a76e8ae8444..eed248b17f949 100644 --- a/docs/en/antalya/cas/architecture/garbage-collection.md +++ b/docs/en/antalya/cas/architecture/garbage-collection.md @@ -59,11 +59,11 @@ follower or a deferred round execution returns before that commit. | 15 | `manifest_deletes` | post-`CAS` | Delete manifest bodies whose owner-removal minus-one edge the `CAS` in phase 13 just adopted | | 16 | `namespace_cleanup` | leader; suppressed on `DEFER` | Pages of the perpetual namespace janitor under a 20 s soft budget, reclaiming dead-life debris | | 17 | `ref_object_cleanup` | post-`CAS` | Prune ref logs and snapshots once both fold coverage and a live snapshot make them safe to delete | -| 18 | `orphan_sweep` | post-`CAS` | Exact-token deletion for the [orphan-manifest sweep](/antalya/cas/architecture/manifests-and-refs#orphan-sweep), after phase 13 adopted each candidate's blob-source retirements and the cursor | +| 18 | `orphan_sweep` | post-`CAS`, right after phase 15 | Exact-token deletion for the [orphan-manifest sweep](/antalya/cas/architecture/manifests-and-refs#orphan-sweep), after phase 13 adopted each candidate's blob-source retirements and the cursor | Phases 2 through 4 run on every leader round; a follower returns after phase 1. Phases 5–15 and -17–18 run only when phase 4 decides to fold (phase 9 only when the round does not suppress destruction); phase 16 runs after phase 15 on a fold and right after -phase 4 on a `DEFER`. A `DEFER` verdict is therefore not a bare no-op: it still runs one bounded +17–18 run only when phase 4 decides to fold (phase 9 only when the round does not suppress destruction). On a fold, phase 18 runs +right after phase 15, then phases 16 and 17; on a `DEFER`, phase 16 runs right after phase 4. A `DEFER` verdict is therefore not a bare no-op: it still runs one bounded namespace-janitor page with `suppress_destructive = true` — listing and classification only, no deletes and no cursor advance — and then returns, publishing no fold artifact and no commit `CAS`. Its lease `CAS` may already have created or renewed the lease in phase 1: @@ -109,7 +109,7 @@ that object. - **Runs on:** always — the only phase a `NotALeader` round emits - **Reads:** `gc/state`; `gc/hb` (only when another GC owns the lease) - **Writes / deletes:** one successful `CAS` on `gc/state` (acquire, renew or steal); a conflict is - re-observed and re-decided by the request engine within the configured request window (`cas_request_window_ms`, default 120 s); no + re-observed and re-decided by the request engine, at most 100 times, each request within its own window (`cas_request_window_ms`, default 120 s); no deletes - **Safety:** the lease is *work de-duplication, not mutual exclusion* — see below - **Fails the round if:** this `Gc` instance saw `gc/state` before and it has since disappeared, or @@ -186,9 +186,8 @@ evidence from the fold running now. - **Retry order:** when an erase is refused because the catalog changed, the drain pauses first (full-jitter backoff, growing to 5 s), then re-reads the catalog, then sends the next erase against that fresh read. A catalog write that lands during the pause therefore cannot refuse the next erase. - A permanently contended catalog ends the drain with `NETWORK_ERROR` at the request deadline or after - 100 erase attempts on one row, whichever comes first; the deadline is one frozen window shared by - every attempt on that row. + A permanently contended catalog ends the drain with `NETWORK_ERROR` after + 100 erases on one row, with no pause after the last. Each erase request has its own window. - **Observability:** phase row `pre_fold_ref_drain`; metric `deleted` (erases the store acknowledged, counted before the resolution read so a drain that throws still reports them, plus erases a resolution read proved); metric `cancelled_creating` (the `Creating` rows the drain cancelled; @@ -625,10 +624,13 @@ role as the coverage record. ### Post-commit failures {#post-commit-failures} After a `Committed` result the round is committed — an exception in phases 14–18 does not un-commit -it. Those phases tolerate the object outcomes they name (`NotFound`, `TokenMismatch`), but only -phase 16 is wrapped in a catch-all; a backend or decode exception in phases 14, 15, 17 or 18 -propagates, and `system.cas_gc_log` then records an `Aborted` or `Error` finish (see -[round outcomes](#round-outcomes)) for a round whose new `gc/state` is already durable. Read such a +it. Those phases tolerate the object outcomes they name (`NotFound`, `TokenMismatch`). Phase 16 logs +any other failure and goes on, unless the round was asked to stop. A backend or decode exception in +phases 14, 15, 17 or 18 propagates. Phase 18 runs before phases 16 and 17, so its exception also skips +them for that round. A propagated exception makes `system.cas_gc_log` record an +`Aborted`, `Stopped` or `Error` finish (see +[round outcomes](#round-outcomes)) for a round whose new `gc/state` is already durable. A manual round +whose query is killed or timed out in these phases is recorded as `Stopped`. Read such a row as "committed round, failed tail": the next round starts from the committed state, and what the tail did not delete is picked up later — by the orphan sweep for phase 15's leftovers, by phase 17's recomputed plan, and for phase 18 only once the sweep cursor (already advanced by phase @@ -702,8 +704,9 @@ nothing ends the pass. A pool without debris costs one `LIST` per round. page and checked again before the cursor is published; the incarnation segment in every key makes an old life's objects structurally unreachable from a reborn same-name namespace, so a missed key can only leak storage, never expose it -- **Fails the round if:** nothing — the whole phase is wrapped in a catch-all ("namespace janitor - stopped this round"). A failed batch `DELETE` leaks its keys and the cursor still advances. A failed +- **Fails the round if:** the round was asked to stop and a request of the phase fails or leaves its + cursor write's outcome unknown. Any other failure is logged ("namespace janitor stopped this round") + and the round goes on. A failed batch `DELETE` leaks its keys and the cursor still advances. A failed `LIST` resets the cursor to the stream start only on the first page of the phase; on a later page the cursor the previous page published stays - **Observability:** phase row `namespace_cleanup`; metrics `janitor_pages`, `janitor_keys`, @@ -761,7 +764,8 @@ from the catalog. ## Phase 18 — orphan sweep {#phase-18-orphan-sweep} -The last phase: executes the [orphan-manifest sweep](/antalya/cas/architecture/manifests-and-refs#orphan-sweep) +Runs right after phase 15, before the janitor and the ref object cleanup, because the committed cursor +has already moved past its nominations. Executes the [orphan-manifest sweep](/antalya/cas/architecture/manifests-and-refs#orphan-sweep) planned in phase 10 and adopted by phase 13's `CAS`. Planning runs only when the schedule requests it and the destructive gate permits it. The default wait before starting another traversal is one hour, subject to the clock-skew rule below. Successful pages of an active traversal continue @@ -1296,8 +1300,11 @@ A `Finish` row of `system.cas_gc_log` carries one of: `Success` (folded and comm (phase 4 chose not to fold), `NotALeader` (returned after phase 1), `Aborted` (the round threw a *transient* error — `S3_ERROR`, `NETWORK_ERROR`, `TIMEOUT_EXCEEDED`, `SOCKET_TIMEOUT`, `ABORTED`, `MEMORY_LIMIT_EXCEEDED` — and this `Gc` keeps its leadership and heartbeat, so the next round simply -retries), `Stopped` (a transient error while the disk was being torn down), or `Error` (any other -error code, notably `CORRUPTED_DATA` and `LOGICAL_ERROR`; leadership is dropped). The `error_code` +retries), `Stopped` (the round was stopped: a manual round whose query was killed or timed out ended +with `QUERY_WAS_CANCELLED` or a transient error, or a round ended with a transient error after the disk +began tearing down or after it saw `SYSTEM CAS GC STOP`), or `Error` (any other +error code, notably `CORRUPTED_DATA` and `LOGICAL_ERROR`; leadership is dropped). A `Stopped` round +may already have committed its `gc/state`: see [post-commit failures](#post-commit-failures). The `error_code` column carries the code on `Aborted`, `Stopped` and `Error` and is `0` otherwise; every unrecognised code is `Error` by omission, never silently transient. diff --git a/docs/en/antalya/cas/configuration.md b/docs/en/antalya/cas/configuration.md index 0e0ec0aa4f66c..7432bb2a5b8cd 100644 --- a/docs/en/antalya/cas/configuration.md +++ b/docs/en/antalya/cas/configuration.md @@ -108,7 +108,7 @@ entirely before release. Treat this table as a snapshot of the current build, no | `cas_manifest_decode_cache_bytes` | 128 MiB | Manifest decode cache byte budget (`0` disables) | | `cas_gc_io_concurrency` | `16` | Bounded pool size for GC object-storage requests that run in parallel: the fold's read-ahead (checkpoints, ref logs, manifests, zero-candidate HEADs), the fold's deletion-intent creates, the orphan-manifest sweep planning reads, the `SYSTEM CAS GC REBUILD` read-ahead, the `pending_deletes` conditional blob `DELETE` fan-out, and the namespace janitor's batch deletes of dead ref logs and snapshots. Not covered: all other GC requests, which run on the round thread. `1` runs the covered requests sequentially. `cas_gc_read_concurrency` is rejected without an alias; use `cas_gc_io_concurrency` instead | | `cas_attempt_timeout_ms` | `5000` | Budget for one HTTP attempt of a writable Native mount's control-plane requests (read, head, list, remove, conditional write, the mount-time bucket-versioning probe), at least 1. Together with the connect cap it forms the attempt envelope (`cas_attempt_timeout_ms + 2 × cap`; the cap is `cas_attempt_timeout_ms` itself when the disk's `connect_timeout_ms` is `0`, else `min(connect_timeout_ms, cas_attempt_timeout_ms)`) that the lease arithmetic reserves: one TCP connect and one TLS handshake under the cap each, send/receive bounded per socket operation by `cas_attempt_timeout_ms`. With background renewal the cadence check requires `cas_mount_renew_period_ms + 2 × envelope + cas_lease_safety_margin_ms < cas_mount_lease_ttl_ms`, which puts an effective ceiling on the frozen connect cap: under the defaults (TTL 40000, period 10000, margin 2000) the envelope must stay under 14000, so with the default attempt timeout a disk `connect_timeout_ms` of `0` or of 4500 ms or more refuses to open writable — lower the connect timeout or raise the TTL if you hit this. Blob body publication does not use this budget: its object-creating request is sent once under the disk's `request_timeout_ms`, with the connect timeout under the same cap | -| `cas_request_window_ms` | `120000` | How long a failing request keeps retrying before it gives up, measured from the start of the call. It applies to control-plane requests and to the blob publication loop. At the limit the request gives up with a retryable `NETWORK_ERROR`. When a query loads a part's metadata and neither cache holds it, a `MEMORY_LIMIT_EXCEEDED` from the manifest read is not retried: the query fails at once with its own code. Another query waiting for the same part is not failed by that error: it reads the manifest again under its own memory limit. Every other manifest read, including the fresh read a write makes of a part it changes, still retries that error for the whole window. A writable disk refuses to open unless the window is larger than twice the attempt envelope (a write reserves its attempt and the read that settles it); a read-only disk, unless it is larger than the envelope. On a writable disk every attempt also needs room left in the mount lease, so while renewals fail a request stops when the lease runs out, even inside a longer window. The ref-table recovery retry budget is derived as twice this value: 240 s by default, so a recovery attempt that spends one whole window inside a single write still has room for a second try. `90000` gives a 90 s window and a 180 s recovery budget | +| `cas_request_window_ms` | `120000` | How long one failing request keeps starting attempts, measured from the start of that request. Every request has its own window, so a series of requests is not bounded by it; the deadlines that successive requests share are the mount lease and the `--timeout` of an offline tool. The same value bounds, on its own, the wait in the catalog queue and the time after which a copy-source confirm starts no new poll pass (a pass already started, and its wait for the table's lock, finish). The read that settles an unclear write has its own window. A conditional update is decided at most 100 times, and a catalog update is submitted at most 100 times: see [updates that keep losing races](#contention-bound). A blob publication is tried at most 8 times, and its upload is under no window. Recovery of a table walks at most 8 times. At the limit the request gives up with a retryable `NETWORK_ERROR`, except when the eighth recovery walk fails: the table load then fails with that walk's own error. When a query loads a part's metadata and neither cache holds it, a `MEMORY_LIMIT_EXCEEDED` from the manifest read is not retried: the query fails at once with its own code. Another query waiting for the same part is not failed by that error: it reads the manifest again under its own memory limit. Every other manifest read, including the fresh read a write makes of a part it changes, still retries that error for the whole window. A writable disk refuses to open unless the window is larger than twice the attempt envelope (a write reserves its attempt and the read that settles it); a read-only disk, unless it is larger than the envelope. On a writable disk, the requests that tables make run under this server's mount lease, and each of their attempts also needs room left in it, so while renewals fail such a request stops when the lease runs out, even inside a longer window. Background lease renewal does not need that room. `90000` gives a 90 s window. `SYSTEM CAS GC STOP` prevents the next attempt of the catalog drain that a scheduled `GC` round runs before its fold, server shutdown that of the namespace removal of an `Atomic` table, and a killed or timed-out query prevents the next retry of a failed attempt, so a stopped request can end before its window does; an attempt in flight runs to its end: see [stopping CAS work](/antalya/cas/operations/troubleshooting#stopping-cas-work) | | `cas_lease_safety_margin_ms` | `2000` | Startup-only margin validated against the mount lease TTL: the attempt envelope + `cas_lease_safety_margin_ms` must be strictly less than the mount lease TTL, and `cas_mount_renew_period_ms` + 2 × envelope + `cas_lease_safety_margin_ms` too, or the disk refuses to open writable | | `cas_unsafe_remount_no_delay` | `0` | Reclaim a mount slot that carries this server's own uuid at once after a hard restart, without observing the slot's token for the lease TTL. Unsafe whenever two processes can hold the same `server_uuid` (a copied uuid file, a stalled predecessor). After such a reclaim the predecessor can still start conditional writes until its own cutoff (`confirmed deadline − cas_lease_safety_margin_ms − 2 × envelope`) or until its next renewal meets the token guard, and a request it already sent may still materialize later. That is not a data hazard: ref-log keys carry `(writer_epoch, sequence)` and creates are conditional, so two writers can never commit different bodies to one key, and recovery's tombstone settles any straggler (recovery fails closed after 64 successive tombstone-create attempts in one epoch displaced by newly materializing old-epoch transactions). The exposure is availability, not data. Intended for test stands and deployments that guarantee one process per uuid | | `cas_staging_backend` | `local` | Blob staging backend (`local` \| `s3`); `s3` is opt-in and requires native same-store copy on writable mount. A transaction deletes its staging objects on commit and on abort; mount start removes leftovers of the same `server_root_id`. Neither can see a multipart upload that was never completed, so add an `AbortIncompleteMultipartUpload` lifecycle rule on the bucket to reclaim those | @@ -139,6 +139,22 @@ The `expires_at_ms` stamped into the mount object is a writer-stamped diagnostic authorizes a reclaim or a GC fence-out. Local fencing is derived instead from the confirmed request's pre-I/O `CLOCK_BOOTTIME` anchor plus the TTL. +### Updates that keep losing races {#contention-bound} + +An update of a shared object that keeps losing races to other writers is retried at most 100 times, then fails with +`NETWORK_ERROR` and a message containing `did not converge`. Examples are the ref catalog under many concurrent +`CREATE` and `DROP` statements, and a hot ref. There is no total time budget for this loop: each attempt has its own +request window. + +- **One lost race** on a healthy store costs one conditional write, the read that settles it when one is needed, and + a pause drawn uniformly from 0 to 200 ms. +- **Typical total:** 100 lost races cost 100 conditional writes, up to 100 reads, and about 10 s of pauses (at most + 20 s). On a store that answers in tens of milliseconds the whole loop takes about 10 to 20 s. +- **Worst case:** 100 slow answers, each inside its own window: about 100 request windows, more than 3 hours at the + default `cas_request_window_ms`. +- **Earlier exits:** `KILL QUERY` or `max_execution_time` ends the loop at the next failed answer from the store. + `SYSTEM CAS GC STOP` ends `GC`'s own catalog updates at their next attempt. + ### Lease TTL: 30 s, 40 s and 120 s {#mount-lease-costs} The write reserve is `2 × envelope + cas_lease_safety_margin_ms` (16 s with defaults, `envelope` as @@ -360,8 +376,8 @@ Builds that include this change move these defaults: - `cas_mount_lease_ttl_ms` moves from `30000` to `40000`. The wait after a hard restart grows with it, from about 43 s to 47 s plus the start time (see [the lease costs](#mount-lease-costs)). -- The request window moves from a fixed 90 s to `cas_request_window_ms`, default `120000`. The ref-table - recovery budget moves from a fixed 120 s to twice the window, 240 s. +- The request window moves from a fixed 90 s to `cas_request_window_ms`, default `120000`. Recovery of a + ref table no longer has a time budget: it walks at most 8 times. - The four `cas_gc_round_redelete_budget`, `cas_gc_round_ref_cleanup_budget`, `cas_gc_round_handoff_prefix_wholesale_budget` and `cas_gc_round_outcome_entry_budget` caps move from `5000` to `0` (unbounded). The first rounds of an diff --git a/docs/en/antalya/cas/operations/troubleshooting.md b/docs/en/antalya/cas/operations/troubleshooting.md index 240eb16591c77..6be7fb9697a4e 100644 --- a/docs/en/antalya/cas/operations/troubleshooting.md +++ b/docs/en/antalya/cas/operations/troubleshooting.md @@ -17,7 +17,7 @@ tools. | Symptom | Diagnosis | Action | |---|---|---| | A server keeps losing its mount lease and self-remounting | Check `system.cas_mounts` for the server's own `state`/`expires_at`, then correlate `watermark_renew` and `mount_remount` in `system.cas_log`; losing the lease trips a local fence and latches a remount generation | Read the failed renewal's `classification` before changing anything — it alone now says why (see [the decision flow](#mount-renewal-remount-flow)). Look for object-store latency consuming the confirmed lease or BOOTTIME advancement; see [the mount lease](/antalya/cas/architecture/mounts-and-leases#mount-lease) | -| Writes slow down or stall under load, with no exception reaching the client | S3 `SlowDown`/`ServiceUnavailable`/`RequestTimeout`/`InternalError` (5xx) responses are not on the request engine's `isDefinitelyRefusedWrite` definite-failure list (only malformed-request, entity-too-large, and access-denied that no credential refresh can fix are), so they classify as ambiguous and are retried automatically. Confirm with `sum(ProfileEvents['CASConditionalWriteUnresolved'])` rising alongside `sum(ProfileEvents['CASConditionalWriteAttempts'])` over `system.query_log` for the affected window (or `ProfileEvent_CASConditionalWriteUnresolved` in `system.metric_log` for a cumulative view across queries), and check `system.blob_storage_log` for `disk_name = ''` rows with a nonzero `error_code` around the same window | Nothing to configure per-request: the request engine retries the same `(key, bytes)` with capped-exponential backoff (200ms initial, capped at 5s, full jitter) until the configured request window (`cas_request_window_ms`, default 120 s) ends — for these conditional writes there is no separate attempts ceiling, only the deadline. A blob body upload is different: it is never resent as is after an ambiguous outcome, and each retry publishes a fresh envelope, up to 8 attempts, and no new attempt starts after the request window ends. An attempt already started can run longer: each creating request waits up to the disk's `request_timeout_ms`, and multipart part uploads keep their own retries. `CASBlobPublishAttemptFailed` counts failed attempts; `CASBlobPublishGaveUp` counts uploads that failed at least once and then ended with an exception, at the attempt cap or the deadline. Meanwhile the mount-lease renewer keeps extending the fence across the disruption — this is the "blips, throttling, partial outages" case the write path is built to survive. Confirm the mount lease itself is still renewing (`system.cas_mounts.expires_at` moving forward, `last_success_age_seconds` not climbing; it is `NULL` until this server's GC completes its first round as leader) — if it is, this is expected and self-resolving. If `SlowDown` responses are sustained rather than transient, check the bucket's request-rate limits against the pool's actual PUT/GET rate (see [bucket requirements](/antalya/cas/bucket-requirements)) and consider lowering `cas_blob_upload_pool_size` to reduce concurrent upload traffic; a write only surfaces a client-visible `NETWORK_ERROR` if the request window passes before the store recovers (an attempt started before the deadline can finish after it), and that error is retried by the ordinary merge/insert backoff, not silently dropped | +| Writes slow down or stall under load, with no exception reaching the client | S3 `SlowDown`/`ServiceUnavailable`/`RequestTimeout`/`InternalError` (5xx) responses are not on the request engine's `isDefinitelyRefusedWrite` definite-failure list (only malformed-request, entity-too-large, and access-denied that no credential refresh can fix are), so they classify as ambiguous and are retried automatically. Confirm with `sum(ProfileEvents['CASConditionalWriteUnresolved'])` rising alongside `sum(ProfileEvents['CASConditionalWriteAttempts'])` over `system.query_log` for the affected window (or `ProfileEvent_CASConditionalWriteUnresolved` in `system.metric_log` for a cumulative view across queries), and check `system.blob_storage_log` for `disk_name = ''` rows with a nonzero `error_code` around the same window | Nothing to configure per-request: the request engine retries the same `(key, bytes)` with capped-exponential backoff (200ms initial, capped at 5s, full jitter) while attempts keep starting inside the request's window (`cas_request_window_ms`, default 120 s, measured from the start of the request) — for one conditional write there is no separate attempts ceiling, only that window. An update that a busy table keeps refusing is decided at most 100 times, then fails with `NETWORK_ERROR` and a message containing `did not converge after 100 decisions`. A blob body upload is different: it is never resent as is after an ambiguous outcome, and each retry publishes a fresh envelope, up to 8 attempts in total; the request window bounds each `HEAD` and intent `GET`. An attempt already started can run longer: each creating request waits up to the disk's `request_timeout_ms`, and multipart part uploads keep their own retries. `CASBlobPublishAttemptFailed` counts each failed attempt that counts toward the 8, the eighth included, although no attempt follows it; a failure after the query stopped, and a failure that no retry can cure, are not counted. `CASBlobPublishGaveUp` counts uploads with at least one such failed attempt that then ended with an exception, at the attempt cap, or when a `HEAD` or intent `GET` gave up at its own request window. Meanwhile the mount-lease renewer keeps extending the fence across the disruption — this is the "blips, throttling, partial outages" case the write path is built to survive. Confirm the mount lease itself is still renewing (`system.cas_mounts.expires_at` moving forward) — if it is, this is expected and self-resolving. If `SlowDown` responses are sustained rather than transient, check the bucket's request-rate limits against the pool's actual PUT/GET rate (see [bucket requirements](/antalya/cas/bucket-requirements)) and consider lowering `cas_blob_upload_pool_size` to reduce concurrent upload traffic; a write surfaces a client-visible `NETWORK_ERROR` when a request's window passes before the store recovers, after 8 failed blob publication attempts, or when an update has not converged after 100 decisions or 100 catalog submissions, however fast each failure was; the ordinary merge/insert backoff retries that error, it is not silently dropped | | A write fails with a message containing `CAS ref-log txn`, `is durable but was not acknowledged`, `outcome is unknown`, `nothing is durable` or `CLOSED by a successor's` | The phrase says whether the write can still take effect. A write blocked behind an earlier unresolved transaction (a wedged or needs-recovery lane) was never attempted, and its message names the earlier transaction's outcome with the same phrase. Errors that name no earlier transaction carry no phrase, for example an admission refusal before the write is queued (`the operation is no longer admitted`), a failed ref-table recovery, a lost mount lease, a table superseded by a self-remount, and a lane in a terminal state (`INVALID_STATE`, "terminal lane state") | Read [CAS commit errors](#cas-commit-errors) before retrying: some outcomes can duplicate on retry | | `GC` never seems to reclaim space after tables are dropped | `SELECT * FROM system.cas_gc_log WHERE event_type='Finish' ORDER BY event_time DESC LIMIT 5` — check `outcome`; also `SELECT is_leader FROM system.cas_mounts` on this node | If `outcome != 'Success'`/`'Deferred'`, see [reading GC health](/antalya/cas/operations/monitoring#gc-health); if this node is not the leader (`is_leader = 0`), it never reclaims for this disk — check the peer holding leadership. Reclamation also needs at least two full rounds past condemnation by design (the grace period is rounds, not acks) — a single manual `SYSTEM CAS GC RUN` will not finish it, and it does nothing on a node that is not the leader | | A dangling-access exception or `CORRUPTED_DATA` on read | Run `clickhouse-disks cas-fsck --detail` and check `dangling` specifically — it is the one class that means data loss, distinct from `unreachable`/`awaiting-gc`, which are just waiting for the rounds that delete them | A nonzero `dangling` count is a real incident: collect the `--detail` output (see [what to collect before filing a bug](/antalya/cas/operations/debugging#filing-a-bug)) before taking any destructive action | @@ -33,6 +33,7 @@ tools. | `SYSTEM CAS DROP POOL MEMBER` returns `member_retired = 0` or a non-empty `warnings` column | The run stopped before its verified mark: a drain step failed, the admin lost its claim, or the farewell could not be confirmed; the owner keeps an unverified tombstone as the resume anchor. Only a claim lost before the drain started rolls the tombstone back, with the warning `the tombstone was rolled back`; nothing was removed then. After `the admin claim was lost during the drain` part of the member's data may be gone: the tombstone stays and the member does not start until a rerun verifies the retirement. A warning `the owner moved on to life N` means the owner was un-retired after this run's tombstone, by a rejoin or by another run's rollback | Rerun the same command only under the [rerun rule](/antalya/cas/operations/migration#rejoin-rerun-rule); it resumes over its own tombstone. A rerun refused as alive or contended waits until GC fences the previous run's slot: about one `cas_mount_lease_ttl_ms` plus 5 % plus one `cas_mount_renew_period_ms` (about 52 s with the defaults), plus up to two GC intervals, with a GC leader running. `namespaces_pending_gc` alone is not a reason to rerun | | `SYSTEM CAS DROP POOL MEMBER` refuses with `alive or contended` although the member is down | The claim trusts no wall clock: `expired` in `system.cas_mounts` is not a certificate of death; only a terminal slot (`terminated` or `fenced`) is reclaimable | Wait until the member's row shows `state = 'terminated'` (clean stop) or `state = 'fenced'` (the disk's GC leader fences the stale lease at the start of a GC round, once it has seen it unchanged for about one `cas_mount_lease_ttl_ms` plus one `cas_mount_renew_period_ms`, about 52 s with the default 40 s lease (40 s + 2 s for the 5 % term + 10 s for one renewal period, from the formula, not measured), so the wait can be up to two GC intervals longer; `SYSTEM CAS GC RUN` on the leader, `is_leader = 1` in `system.cas_mounts`, can trigger the fence, but the run that fences must come at least that long after the first run that saw the lease), then rerun | | The log repeats `CAS GC namespace removal is stuck … cleanup evidence is absent because terminal has not folded` and `CASGCStuckRemovals` grows | A removal turned the namespace's catalog row `Removing` and did not write its terminal record. Four operations remove a namespace: `DROP TABLE`, the source side of a table rename that moves the data, `SYSTEM UNFREEZE` and `SYSTEM CAS DROP POOL MEMBER`. While the row is `Removing`, writes to the table are refused and reads see no data after a restart or a remount, after a retried `DROP`, and on the GC leader after its next GC round; until then a server that kept the table open can still serve it. A server that closes such a table logs `its catalog row is Removing, so this server closes it`; that line alone also follows a table dropped on another server or before a restart, until GC erases its row. The data stays on the store, and the namespace's objects are reclaimed only after its removal completes. The warning starts after 10 GC rounds, a built-in value and not a setting, and repeats every GC round | The remedy depends on the operation, and no tool returns the row to `Live`. `DROP TABLE` in an `Atomic` database: the server retries the drop and logs `Cannot drop table … Will retry later.`; a retry that succeeds finishes the removal, and a warning that persists means the retry keeps failing, so read its error. `DROP TABLE` in an `Ordinary` database: the failed drop re-attaches the table under its name, and running `DROP TABLE` again finishes the removal. `SYSTEM CAS DROP POOL MEMBER`: rerunning it under the [rerun rule](/antalya/cas/operations/migration#rejoin-rerun-rule) finishes the removal. A table rename that moved the data (the log has `RENAME TABLE move was only partially applied`): the table stays attached under its old name, its parts are already in the new name's namespace, and no statement finishes the removal and keeps those parts reachable. A retried `RENAME TABLE` is refused with `DIRECTORY_ALREADY_EXISTS`; a retried rename from an `Ordinary` to an `Atomic` database targets a new uuid, completes with an empty table and leaves the moved parts in a namespace no table references. Do not retry the rename or drop the table; [file a bug](/antalya/cas/operations/debugging#filing-a-bug). `SYSTEM UNFREEZE WITH NAME`: a rerun finishes the removal only while another namespace under that backup name still has a part. Once every namespace left under it is `Removing`, the backup directory reads as absent and the rerun does nothing; no statement finishes the removal then, so file a bug | +| Writes to a table fail with `a removal write may still land` after a `DROP TABLE` failed | The `DROP` sent its `Live -> Removing` catalog write and failed before it learned whether that write applied. The write can still land, so the table stays closed for writes until the `DROP` is retried, even while its catalog row reads `Live`. The server logs `the outcome of its Live -> Removing catalog write is unknown` | Retry the `DROP TABLE`; a retry that succeeds finishes the removal. If the retry fails with the same error, restart the server, then retry the `DROP TABLE`. A restart reopens the table for writes but does not cancel the removal write; see [removal](/antalya/cas/architecture/namespaces#removal) | | `clickhouse-disks cas-migrate-pool` refuses with `changed during the migration` or `moved during the migration` | A server of the pool renewed its mount slot or its GC lease while the tool ran | Stop the server the message names and run the tool again; see [the refusals](/antalya/cas/operations/migration#migrate-generation-4-refusals) | | `clickhouse-disks cas-migrate-pool` refuses with `identities are not comparable`, `leaves no room for blob intent keys` or `cannot serve as a blob identity` | The disk's token dialect differs from the pool's, the pool prefix is too long, or the store's tokens cannot name a body | See [the refusals](/antalya/cas/operations/migration#migrate-generation-4-refusals) | | `clickhouse-disks cas-migrate-pool` fails with `could not be confirmed` | An intent create got no usable answer; the tool wrote nothing after the intents | Run the tool again | @@ -132,3 +133,36 @@ The default-level log policy is intentionally bounded: one warning on the first then one recovery info or terminal fence warning, plus one final line per whole-chain remount attempt. Use `system.cas_log` and counter deltas to reconstruct the incident; `DEBUG` contains individual physical retries when that extra transport detail is necessary. + +## Stopping CAS work {#stopping-cas-work} + +A query that is killed with `KILL QUERY` or hits its time limit stops `CAS` work only where stopping leaves the state a storage failure there would leave: + +- A retry after a failed request. The retry is not sent. When a read or a blob upload failed before the stop, the query fails with that request's error, or with a retry-later `NETWORK_ERROR` (210) that names a credential refusal, not with the stop's own error. That request's error can itself be `TIMEOUT_EXCEEDED` (159), when the failed attempt timed out. When a metadata write failed before the stop, the query fails with a retry-later `NETWORK_ERROR` (210) that says the write is unresolved and what a read of the key found; it does not carry the store's error. A metadata write that the store refused, with no earlier attempt left unanswered, keeps the store's error. When such a write was refused for its credentials and the stop cancels its resend with fresh credentials, it fails with a retry-later `NETWORK_ERROR` (210) that names the refusal. When the request fails after the stop, the S3 client reports the stop itself (see below). The pause before a retry notices the stop within 200 ms. A pause inside cleanup that the operation owes after a send runs to its end, and the request is sent once more unless the mount fence, the mount lease or a deadline stops it; if that attempt fails after the stop, it is not retried. +- The next step of work that `CAS` can resume later: the catalog cleanup of a manual `SYSTEM CAS GC RUN`, the drain of `SYSTEM CAS DROP POOL MEMBER`, and the upload of a blob body the writer has to publish, because the store does not hold the blob or holds one the writer cannot reuse. The query fails with `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED`. When an earlier upload attempt of the same blob failed, the check before the next upload fails the query with that attempt's error instead. The drain checks the stop before each of the member's namespaces, before the listing of its manifests and after each page of that listing arrives, before each group of its manifests and before each key it deletes. A `SYSTEM CAS DROP POOL MEMBER` stopped after its drain began leaves the member retired; rerun it to finish. Stopped before that, it can leave the member as it was. + +Everywhere else the `CAS` requests of a stopped query run as on a plain S3 disk. This covers the first attempt of every request, a new decision after another writer won a race before the stop, waits for other callers, cleanup after a failed write, transaction rollback, dropping a table or a temporary table, `SYSTEM CAS FORGET`, and the scan of `SYSTEM CAS FSCK`. + +The S3 client reports a stopped query's error in place of any failed answer from the store, as on a plain S3 disk. This includes an expected answer of a healthy store, such as `404` for a key that does not exist. So the query can still fail with `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED` when the store answers with an error after the stop. A bulk delete that the store answers successfully, with an error for one of its keys, keeps that key's error. Writes of several queries to one table's metadata can be sent together by one of them. When that query is stopped, such a failed answer can fail the other queries' writes in the same request too. + +A metadata write that loses a race to another writer after the stop fails the query with `ABORTED` (236) and a message that says "conflict": the S3 client reports the stop in place of the store's refusal, and a read of the key shows the other writer's object. + +Two background owners stop `CAS` work at its next step, with their own error: + +- `SYSTEM CAS GC STOP`, for the catalog drain that a scheduled `GC` round runs before its fold. +- Server shutdown, for the namespace removal of an `Atomic` table. The removal is requeued and finishes after the restart. + +A `GC` round that `SYSTEM CAS GC STOP` ends is recorded as `Stopped` in `system.cas_gc_log`. A manual round whose query is killed or timed out is recorded as `Stopped` when it ends with `QUERY_WAS_CANCELLED`, or with one of the transient errors `S3_ERROR`, `NETWORK_ERROR`, `SOCKET_TIMEOUT`, `TIMEOUT_EXCEEDED`, `ABORTED` or `MEMORY_LIMIT_EXCEEDED`. It is recorded as `Error` when it ends with any other error, for example `READONLY`. A stop that comes after the round's last check leaves the round's own outcome. + +No stop interrupts: + +- A request already in flight. +- The first attempt of a read, and a read that only waits for another reader's result. +- A recovery walk that is already running. On S3 the walk of a stopped query still fails at the first error answer. A walk that looks for a record after its last one ends with such an answer, the `404` for that key; a walk that ends at the table's final removal record looks for none. The failed read is not retried. When the stop cuts short the read that follows a refused write of the walk, the walk ends with a retry-later `NETWORK_ERROR` (210) instead of starting again. +- Cleanup that the operation owes after a send, and merges. + +If the stop lands after a metadata write whose outcome is unknown, the error is the retry-later `NETWORK_ERROR` (210), and its message says the write is unresolved or its outcome is unknown. Check the table before you repeat the write. + +A stop does not mean that no further request is sent. It ends the retries of a failed request and the scans listed above at their next check. Other work in progress can still send requests up to its own limits, for example another recovery walk up to the limit on walks. When a stop comes together with a lost mount lease or a refused credential, the error can name the less specific of the two causes. + +There is no bound on how long the call takes to return after a stop. diff --git a/docs/en/operations/system-tables/cas_gc_log.md b/docs/en/operations/system-tables/cas_gc_log.md index 5427b8c1fe9db..68e76dbb294a5 100644 --- a/docs/en/operations/system-tables/cas_gc_log.md +++ b/docs/en/operations/system-tables/cas_gc_log.md @@ -38,7 +38,7 @@ specified (it is enabled by default in the shipped `config.xml`). - `gc_id` ([String](/sql-reference/data-types/string)) — The GC scheduler instance id (which mounter ran the round). - `trigger` ([Enum8](/sql-reference/data-types/enum)) — `Scheduled` (background tick) or `Manual` (`SYSTEM` command). - `round` ([UInt64](/sql-reference/data-types/int-uint)) — The GC round number (`0` on a `Start` row). -- `outcome` ([Enum8](/sql-reference/data-types/enum)) — `Unknown` (on a `Start` row), `Success` (led, folded, and completed), `NotALeader` (another replica holds the GC lease), `Deferred` (led but took the skip-unchanged fast path — no fold ran, because no changed shard reached the fold threshold and no deletion was due), `Aborted` (the round threw a transient error — backend unavailability, a lost lease, a concurrent leader; the next scheduled round retries it), `Stopped` (a transient error observed after the disk began shutting down: the round was cut short so the shutdown need not wait for it, and the next start re-derives its work), or `Error` (the round threw a non-transient error — investigate). +- `outcome` ([Enum8](/sql-reference/data-types/enum)) — `Unknown` (on a `Start` row), `Success` (led, folded, and completed), `NotALeader` (another replica holds the GC lease), `Deferred` (led but took the skip-unchanged fast path — no fold ran, because no changed shard reached the fold threshold and no deletion was due), `Aborted` (the round threw a transient error — backend unavailability, a lost lease, a concurrent leader; the next scheduled round retries it), `Stopped` (the round was cut short on request: the disk began shutting down, `SYSTEM CAS GC STOP` was issued, or the query of a manual round was killed or timed out), or `Error` (the round threw a non-transient error — investigate). A round stopped before its closing compare-and-swap adopted nothing, and the next round re-derives its work. A round stopped after it, for example a manual round killed during its post-commit cleanup, keeps its commit and has `round != 0`. Later rounds pick up most of the cleanup it skipped, but not a generation the hand-off reclaim did not finish: that is left to `cas-fsck`. See [post-commit failures](/antalya/cas/architecture/garbage-collection#post-commit-failures). - `candidates_marked` ([UInt64](/sql-reference/data-types/int-uint)) — Objects retired (marked) this round. - `objects_deleted` ([UInt64](/sql-reference/data-types/int-uint)) — Objects physically deleted this round. - `objects_absent` ([UInt64](/sql-reference/data-types/int-uint)) — Retire candidates found already absent. @@ -52,8 +52,8 @@ specified (it is enabled by default in the shipped `config.xml`). - `fence_outs` ([UInt64](/sql-reference/data-types/int-uint)) — Expired mounts fenced out by this round's heartbeat floor. - `anomalies` ([UInt64](/sql-reference/data-types/int-uint)) — Fold clamps surfaced (and survived) this round. A steady non-zero value warrants a look at the round log details. - `duration_ms` ([UInt64](/sql-reference/data-types/int-uint)) — The round wall-clock duration (on a `Finish` row). -- `error` ([String](/sql-reference/data-types/string)) — The exception text when `outcome = 'Aborted'`, `'Stopped'` or `'Error'`. On a `Stopped` row it names the request the shutdown refused, not the shutdown itself. -- `error_code` ([Int32](/sql-reference/data-types/int-uint)) — The exception code when `outcome = 'Aborted'`, `'Stopped'` or `'Error'`; `0` otherwise. Key monitoring on this column rather than on the `error` text. On an `Aborted`, `Stopped` or `Error` row the counters still report everything the round completed before it threw, and `round != 0` on such a row means the round's closing compare-and-swap committed and the failure hit only post-commit cleanup. +- `error` ([String](/sql-reference/data-types/string)) — The exception text when `outcome = 'Aborted'`, `'Stopped'` or `'Error'`. On a `Stopped` row it is the message of the exception that ended the round: for example `CAS GC round stopped by its scheduler` for `SYSTEM CAS GC STOP`, the query's own message for a killed or timed-out manual round, or an unresolved-write message when the stop landed after a write whose outcome is unknown. After a shutdown it names the request the shutdown refused, not the shutdown itself. +- `error_code` ([Int32](/sql-reference/data-types/int-uint)) — The exception code when `outcome = 'Aborted'`, `'Stopped'` or `'Error'`; `0` otherwise. Key monitoring on this column rather than on the `error` text. On a `Stopped` row it is the code the round ended with. That is usually `ABORTED` for `SYSTEM CAS GC STOP` and `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED` for a killed or timed-out manual round, but any transient code can appear, such as `NETWORK_ERROR` when the stop landed after a write whose outcome is unknown. After a shutdown it is the refused request's code. On an `Aborted`, `Stopped` or `Error` row the counters still report everything the round completed before it threw, and `round != 0` on such a row means the round's closing compare-and-swap committed and the failure hit only post-commit cleanup. - `ProfileEvents` ([Map(LowCardinality(String), UInt64)](/sql-reference/data-types/map)) — On a `Start`/`Finish` row, the per-round `ProfileEvents` delta (the `CAS*` counters and S3/disk events for this round). On a `Phase` row, **that phase's** delta, so `GROUP BY phase` over `ProfileEvents['S3ListObjects']` attributes the round's `LIST` budget to the phase that spent it. - `round_id` ([String](/sql-reference/data-types/string)) — The correlator for every row of one round attempt: its `Start`, each of its `Phase` rows, and its `Finish`. Minted per attempt, so unlike `round` it exists even for a round that never committed and for a round that never led. Group by this column to reconstruct one round. - `phase` ([LowCardinality(String)](/sql-reference/data-types/lowcardinality)) — The GC phase this row describes; empty on `Start`/`Finish`. See [Per-phase rows](#per-phase-rows) for the phase list. @@ -92,15 +92,15 @@ The phases, in execution order: | `fold_seal_read` | The adopted fold seal, read twice at the same generation and attempt. | two fold-seal `GET`s | | `fold_ref_intake` | Read and fold every new ref log and the manifest bodies its edges name. `phase_metrics` carries five keys per source family, with the prefix `ckpt_` (namespace checkpoints), `reflog_` (ref logs) or `manifest_` (manifest bodies): `reads_issued` (reads started, ahead of time or at the moment the fold needs the result; a retry is not counted again), `takes` (results the fold consumed, absent ones included), `awaited` (takes whose result was not ready when the fold asked for it: every read made at that moment, and a read started ahead that had not finished; a sample at one instant), `wait_us` (time the GC thread spent in those takes, from that moment to the result) and `apply_us` (time from a take's result to the next take, or to the end of the checkpoint reads or of one namespace's walk: decoding, folding, and anything else the thread did meanwhile). `cursor_resolves` and `cursor_resolve_us` count and time the namespaces whose next ref log had to be found by reading from the stored fold cursor, because this process does not remember it, for example after a restart. `cursor_resolves` counts calls of the resolver, not reads: a cursor at or above the checkpoint's snapshot reads its own record, one below it in the snapshot's epoch needs no read, and one in an older epoch reads one ref log head per epoch it steps through. Those reads are not made ahead of time and are not in `reflog_reads_issued`; `cursor_resolve_us` is the time of the whole call. | one `GET` per new log, one `GET` per manifest edge | | `intent_sweep_list` | List one page of `blob-intents/` from the stored cursor to find deletion intents that have no row. Absent from a round whose destruction is suppressed. `phase_metrics` carries `listed`, `nominated`, `unparsed`, `wrapped` (`1` when the listing reached its end) and `list_budget_keys`. | one `LIST` page | -| `fold_reduce` | The per-shard in-degree merge: condemn and create intents, spare, decide deletes, adopt orphan intents. `phase_metrics` carries `condemned`, `intents_confirmed` (rows committed `pending`), `spared`, `body_deletes_decided` (body deletes decided), `adopted`, `nominations_waiting` (nominated intents left for a later fold: see [orphan intents](/antalya/cas/architecture/garbage-collection#orphan-intents)), `read_ahead_blobs` (blobs the fold holds in memory to read the `HEAD`s of `pending` and `standing` rows ahead; 0 when no parent row is `pending` or `standing`), `suppress_destructive` (`1` when the round deleted no body or intent: an anomaly, a held namespace, an incomplete reference frontier, a stop request seen before the end of the ref intake, or `parent_unconfirmed`), `frontier_complete` (`0` when the round could not prove its reference frontier complete, which suppresses deletes), `parent_unconfirmed` (`1` when the `HEAD` of `gc/state` after the intake did not show the leased version, so the round deleted nothing), `condemned_rows` (rows the round leaves on file: `candidate`, `pending` and `standing`) and `pending_rows` (the `pending` and `standing` rows among them). | prior-run streaming `GET`s, one `HEAD` per blob that needs a decision, one intent `PUT` per intent created, run `PUT`s | +| `fold_reduce` | The per-shard in-degree merge: condemn and create intents, spare, decide deletes, adopt orphan intents. `phase_metrics` carries `condemned`, `intents_confirmed` (rows committed `pending`), `spared`, `body_deletes_decided` (body deletes decided), `adopted`, `nominations_waiting` (nominated intents left for a later fold: see [orphan intents](/antalya/cas/architecture/garbage-collection#orphan-intents)), `read_ahead_blobs` (blobs the fold holds in memory to read the `HEAD`s of `pending` and `standing` rows ahead; 0 when no parent row is `pending` or `standing`), `suppress_destructive` (`1` when the round deleted no body or intent: an anomaly, a held namespace, an incomplete reference frontier, a stop request seen before the end of the ref intake, or `parent_unconfirmed`), `frontier_complete` (`0` when the round could not prove its reference frontier complete, which suppresses deletes), `parent_unconfirmed` (`1` when the `HEAD` of `gc/state` after the intake did not show the leased version, so the round deleted nothing), `condemned_rows` (rows the round leaves on file: `candidate`, `pending` and `standing`) and `pending_rows` (the `pending` and `standing` rows among them). | prior-run streaming `GET`s, one `HEAD` per blob that needs a decision, one intent `PUT` per intent created, run `PUT`s; when the orphan-manifest sweep is planned, its manifest `LIST` page and the `GET`s that decide its nominations | | `fold_seal_write` | Publish the new fold seal. | one `PUT` | | `pending_deletes` | The single content-delete site: exact-token deletes of bodies whose rows were `pending` in the adopted state, then the deletion-intent deletes, plus the outcome logs. `phase_metrics` carries `bodies_deleted` (body deletes answered this round), `jobs_scheduled` (bodies sent to the GC I/O pool; `0` for no candidates, sequential execution, singleton batches, or refusal before the first submission), `jobs_failed` and `intents_deleted`. | one `DELETE` per body, intent deletes in batch requests, one outcome-log `PUT` per shard with rows | | `round_commit` | The generation-retention prune and the round's single `gc/state` compare-and-swap. | prune `LIST`s and deletes, one compare-and-swap | | `handoff_reclaim` | Wholesale-reclaim generations a moved run ref stranded below the retention cursor. | prefix `LIST`s and deletes | -| `manifest_deletes` | Exact-token deletes of owner-removed manifest bodies, after their decrements were adopted. | one `DELETE` per body | +| `manifest_deletes` | Deletes of owner-removed manifest bodies, after their decrements were adopted. The keys are write-once, so the deletes carry no token. | batch `DELETE` requests of up to `cas_gc_bulk_delete_chunk_keys` keys; one `DELETE` per key on a storage without a batch delete | +| `orphan_sweep` | Deletes the orphan part manifests that `fold_reduce` nominated and the round's commit adopted. | one `HEAD` per nomination, one exact-token `DELETE` per nomination still present at its token | | `namespace_cleanup` | Run `cas/ns/` pages across the stream and state subtrees for the perpetual dead-life janitor, under a 20 s soft budget; `budget_exhausted` is 1 when the budget stopped the phase, `delete_requests` counts the phase's delete calls, which run on the GC I/O pool and are missing from this row's `ProfileEvents`. This phase is physical reclamation, not a lifecycle gate. | per page: one namespace-root page `LIST`, catalog cut, batch deletes of dead ref logs and snapshots, exact-token deletes of the rest | -| `ref_object_cleanup` | Delete ref logs covered by both the durable fold cursor and a durable snapshot, plus superseded snapshots. | one `HEAD` + one `DELETE` per deletable object | -| `orphan_sweep` | The budgeted, cursor-paced orphan part-manifest backstop. | budgeted `LIST` and deletes | +| `ref_object_cleanup` | Delete ref logs covered by both the durable fold cursor and a durable snapshot, plus superseded snapshots. | per planned namespace, the `GET`s that validate its recovery base; per chunk, up to one ref catalog and one `gc/state` `GET` and one batch `DELETE` of up to `cas_gc_bulk_delete_chunk_keys` write-once keys (one `DELETE` per key on a storage without a batch delete) | Which phase dominates a round: From 989b0f1536fb25889c71d2c7e8505ec74293ddd5 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Fri, 27 Nov 2026 11:26:00 +0100 Subject: [PATCH 17/47] Follow dropped metadata through the log in the shutdown drop test `test_shutdown_hands_atomic_drop_to_restart` listed the local `metadata_dropped` directory. On the "db disk" lanes the database disk is remote, the directory is empty, and the test failed although the server stopped the removal as expected ("Cannot drop table ... Will retry later: ... CAS table namespace removal stopped by server shutdown"). The test now checks that `DatabaseCatalog` logs no removal of the table's metadata before the exit and logs it after the restart. https://altinity-build-artifacts.s3.amazonaws.com/json.html?PR=2970&sha=d42bd3d271cdf293f9fec5bf61bfe4ea079ff6fc&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%208%2F8%29 https://github.com/Altinity/ClickHouse/pull/2970 Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Fable 5.2 --- tests/integration/test_cas_request_window/test.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/integration/test_cas_request_window/test.py b/tests/integration/test_cas_request_window/test.py index 3e0af0d6f042b..eeed10dbdac1d 100644 --- a/tests/integration/test_cas_request_window/test.py +++ b/tests/integration/test_cas_request_window/test.py @@ -920,7 +920,9 @@ def test_shutdown_hands_atomic_drop_to_restart(node_stop): node_stop.query("INSERT INTO {} VALUES (1, 'x')".format(name)) life_log = "cas/ns/stream/{}/_log/".format(life) uuid = _table_uuid(node_stop, name) - dropped_metadata = "ls /var/lib/clickhouse/metadata_dropped/ | grep -c {} || true".format(uuid) + # The database disk may be remote, so the dropped metadata is followed through the log, not the local filesystem. + metadata_removed = "Removing metadata .*{}.sql of dropped table".format(uuid) + removed_before = int(node_stop.count_in_log(metadata_removed).strip()) stopped_before = int(node_stop.count_in_log("removal stopped by server shutdown").strip()) shutting_down_before = int(node_stop.count_in_log("Waiting for current connections to close").strip()) fatal_before = int(node_stop.count_in_log("").strip()) @@ -949,14 +951,15 @@ def test_shutdown_hands_atomic_drop_to_restart(node_stop): assert [r for r in trace if r["method"] == "PUT" and life_log in r["path"] and r["status"] == 200 and r["t_mono_ms"] < held["t_mono_ms"]], trace assert not [r for r in trace if r["method"] == "PUT" and life_log in r["path"] and r["t_mono_ms"] > released_ms], trace - assert node_stop.exec_in_container(["bash", "-c", dropped_metadata]).strip() == "1" + assert int(node_stop.count_in_log(metadata_removed).strip()) == removed_before assert int(node_stop.count_in_log("removal stopped by server shutdown").strip()) > stopped_before # A crash during shutdown also ends the process; an orderly exit logs nothing fatal. assert int(node_stop.count_in_log("").strip()) == fatal_before restarted_ms = _stats()["trace"][-1]["t_mono_ms"] node_stop.start_clickhouse() - _wait_until(lambda: node_stop.exec_in_container(["bash", "-c", dropped_metadata]).strip() == "0", timeout=60) + # Only metadata that survived the exit can be found and removed by the restarted server. + _wait_until(lambda: int(node_stop.count_in_log(metadata_removed).strip()) > removed_before, timeout=60) assert node_stop.query("SELECT count() FROM system.dropped_tables WHERE uuid = '{}'".format(uuid)).strip() == "0" def appended_through_terminal(): From cd519b16cde8f7ab6f2edae766b36e3279a8167e Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 19:51:22 +0100 Subject: [PATCH 18/47] Read right before a CAS write that retries a lost race After a conditional write lost a race, the engine read the object, paused, and then wrote on the body it had read before the pause. With other writers committing more often than once per pause every retry was refused: a `CREATE TABLE ... ON CLUSTER` lost 100 submissions of the ref catalog in 11 s and failed with "did not converge after 100 submissions". A read and the write conditioned on it are now one probe with nothing between them; pauses come only between probes: - a write from the cached catalog that loses is decided again at once on the read that settled it; - a write decided on a fresh read that loses is followed by a pause, a new read and a write. A clean 412 on that path is no longer settled by a read of its own, and a submission after a pause never starts from the cache; - the pause after the n-th consecutive clean loss is min(750 ms, 40 ms * (n - 1)) plus up to a quarter: the first retry comes at once. A conflict that settled a transport fault keeps the fault schedule and restarts the count; - `readModifyWrite` and `readModifyWriteOnPresence` share one loop; - the catalog erase loop refreshes GC authority before its catalog read on a retry, and `resolveNamespaceLife` paces by its collisions. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../ContentAddressed/Backend/CasHotKeys.cpp | 57 ++++- .../ContentAddressed/Backend/CasHotKeys.h | 34 ++- .../ContentAddressed/Backend/CasRequests.cpp | 201 +++++++++--------- .../ContentAddressed/Backend/CasRequests.h | 45 ++-- .../ContentAddressed/Backend/CasRetry.cpp | 7 + .../ContentAddressed/Backend/CasRetry.h | 18 +- .../ContentAddressed/Backend/CasWriteResult.h | 4 +- .../ContentAddressed/Gc/CasGc.cpp | 6 +- .../ContentAddressed/Pool/CasRefCatalog.cpp | 57 +++-- .../ContentAddressed/Pool/CasRefCatalog.h | 5 +- .../ContentAddressed/Pool/CasRefLedger.cpp | 14 +- 11 files changed, 276 insertions(+), 172 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp index 42441d332388e..9720672200643 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp @@ -56,7 +56,8 @@ CasHotKeys::~CasHotKeys() chassert(lanes.empty()); } -WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide) +WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide, Start start, + OnLoss on_loss) { /// The wait has its own end, taken here; each request after it binds its own window. const Retry::Bound wait_end = op.owner.bindPolicy(policy); @@ -138,7 +139,7 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr lane.cv.wait_for(lock, kOwnerStopSlice); } ProfileEvents::increment(ProfileEvents::CASHotKeyQueueWaitMicroseconds, (op.owner.now_ms() - entered_ms) * 1000); - return hold(key, op, policy, decide); + return hold(key, op, policy, decide, start, on_loss); } void CasHotKeys::leave(const String & key, Item & item, bool entered_hold, uint64_t entered_ms, CasOperation & op) noexcept @@ -193,14 +194,16 @@ void CasHotKeys::leave(const String & key, Item & item, bool entered_hold, uint6 } } -WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry & policy, const Decide & decide) +WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry & policy, const Decide & decide, Start start, + OnLoss on_loss) { + /// Every write of this hold, and its base read, are one submission's: they share one record of what was sent. CasOperation::WriteState state; std::optional base; bool from_cache = false; /// A single-attempt submission never starts from a hint: its one attempt is on fresh state, as /// the engine's own verb reads before it. - if (!policy.single_attempt) + if (!policy.single_attempt && start == Start::CacheOrRead) { if (auto remembered = cached(key)) { @@ -258,30 +261,62 @@ WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry throwIfBackgroundStopped(); candidate = decide(base); } - if (!candidate) + const auto declined = [&] { if (base) remember(key, *base); return Declined{state.last_seen}; - } - - WriteResult result = [&] + }; + const bool retried_after_a_pause = on_loss == OnLoss::SubmitAgain && !policy.single_attempt; + const auto write = [&] { + /// A loss on a hint is settled: the retry below decides on that read. A loss on a fresh read that the + /// caller retries is repaid by its pause and a read after it, so a settling read would go unused. + const auto on_clean_refusal = from_cache || !retried_after_a_pause + ? CasOperation::OnCleanRefusal::Settle : CasOperation::OnCleanRefusal::ReturnUnobserved; try { - return base ? op.replace(key, *candidate, base->etag, policy) : op.create(key, *candidate, policy); + return op.writeLoop(key, *candidate, base ? std::optional(base->etag) : std::nullopt, policy, + state, CasOperation::ResolveWith::Body, on_clean_refusal); } catch (...) { forget(key); throw; } - }(); + }; + if (!candidate) + return declined(); + WriteResult result = write(); + + /// A clean loss on a hint says only that the hint was old, not that the key is contended: decide + /// again on the resolve read and write at once, so nothing waits between that read and the write. + if (const auto * conflict = std::get_if(&result); from_cache && conflict && !conflict->any_ambiguous + && !conflict->observed_stop + && (std::holds_alternative(conflict->seen) || std::holds_alternative(conflict->seen))) + { + forget(key); + state.last_seen = conflict->seen; + base.reset(); + if (const auto * object = std::get_if(&state.last_seen)) + base = *object; + from_cache = false; + throwIfBackgroundStopped(); + candidate = decide(base); + if (!candidate) + return declined(); + result = write(); + } + std::visit(detail::Overload{ [&](const Committed & committed) { remember(key, Object{*candidate, committed.etag}); }, [&](const Conflict & conflict) { - if (const auto * object = std::get_if(&conflict.seen)) + /// A caller that retries a `Conflict` pauses first, and a body read before that pause would + /// refuse its next write once anyone commits during it: the next hold reads instead. + const bool retried = retried_after_a_pause && !conflict.observed_stop; + const auto * object = std::get_if(&conflict.seen); + if (object && !retried) remember(key, *object); else forget(key); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h index cda89bc1b80b2..3adef679851e1 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h @@ -26,16 +26,18 @@ class CasOperation; /// growing sleep. `submit` takes a FIFO ticket for the key, waits its turn re-checking the caller's /// own fence, lease and deadline, obtains a base (the cache's object, else the engine's own read), /// runs the caller's `decide` on it, lands the candidate through the engine's `replace` or `create` -/// on the caller's own operation and thread, and returns the engine's result unchanged. The caller -/// keeps the retry loop: a `Conflict` is a lost race against another server, and the caller submits -/// again after `Retry::conflictBackoff`. +/// on the caller's own operation and thread, and returns the engine's result. The caller keeps the +/// retry loop: a `Conflict` is a lost race against another server, and the caller submits again after +/// `Retry::conflictBackoff` with `Start::Read`. Such a `Conflict` on a fresh read is returned unsettled +/// (`NotObserved`) and leaves no cached body, since the read after the pause replaces both. /// /// The cache is a hint and never a source of truth: every write against it is conditional on its -/// etag, so a stale entry costs one 412 and one resolve read; and a verdict a `decide` renders on it +/// etag, so a stale entry costs one 412 and one resolve read, on which the hold decides and writes +/// again at once (unless the 412 settled a transport fault); and a verdict a `decide` renders on it /// (a refusal by exception, or "nothing to write") is never delivered, because a refusal without a /// write is the one thing a 412 cannot correct -- the entry is dropped, the key is read, and the -/// `decide` runs again on the read. The store's answer to a write decided on a hint is delivered -/// whatever it is: it is a fact about the store, and the caller's ordinary retry learns the rest. +/// `decide` runs again on the read. Any other answer to a write decided on a hint is delivered as it +/// is: it is a fact about the store, and the caller's ordinary retry learns the rest. /// /// One instance per pool, shared by its three request planes; a `CasRequests` built without one owns /// a private instance with no cache. Every callback (`decide`, a `Liveness` closure, a backend hook) @@ -56,11 +58,21 @@ class CasHotKeys /// its reads go through `op`; it reads `base->bytes` and never `base->etag`. using Decide = std::function(const std::optional &)>; - /// One hold on `key`: wait for the turn, obtain a base, run `decide`, one engine write, remember. + /// One hold on `key`: wait for the turn, obtain a base, run `decide`, one engine write, remember; a + /// clean `Conflict` on a cached base adds one more `decide` and write on the resolve read. /// The wait ends at the window of `policy`, or its earlier lease, taken at entry; the base read and - /// the write each bind their own. Returns the engine's own result for that write, in class and - /// content, and propagates a `decide`'s exception as `readModifyWrite` does, never from a cached base. - WriteResult submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide); + /// the write each bind their own. Returns the engine's own result for that write, except that a clean + /// `Conflict` on a fresh read that the caller retries (`OnLoss::SubmitAgain`, not a single attempt) is not + /// settled and carries `NotObserved`; it + /// propagates a `decide`'s exception as `readModifyWrite` does, never from a cached base. + /// `Start::Read` skips the cache: a caller that paused since its last submission must not write on a + /// body another holder remembered during that pause. + enum class Start : uint8_t { CacheOrRead, Read }; + /// `OnLoss::End`: the caller will not submit again after a lost race, so a refusal is settled, as under a + /// single attempt, and the caller learns what won. + enum class OnLoss : uint8_t { SubmitAgain, End }; + WriteResult submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide, + Start start = Start::CacheOrRead, OnLoss on_loss = OnLoss::SubmitAgain); /// Items in the key's queue, the holder included; 0 for a key with no lane. size_t queueDepthForTest(const String & key) const; @@ -104,7 +116,7 @@ class CasHotKeys }; using Cache = CacheBase, RememberedWeight>; - WriteResult hold(const String & key, CasOperation & op, const Retry & policy, const Decide & decide); + WriteResult hold(const String & key, CasOperation & op, const Retry & policy, const Decide & decide, Start start, OnLoss on_loss); void leave(const String & key, Item & item, bool entered_hold, uint64_t entered_ms, CasOperation & op) noexcept; std::optional cached(const String & key) const; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp index 7fe86a9a660b3..7456d4824ceb2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include namespace ProfileEvents @@ -519,6 +520,20 @@ CasOperation::Gate CasOperation::gate(uint64_t needed_ms) const return Gate::Ok; } +std::optional CasOperation::refusedReadAttempt(const Retry::Bound & bound) const +{ + const uint64_t reservation = reservedFor(0, 1); + switch (gate(reservation)) + { + case Gate::FenceLost: return ReadStop::FenceLost; + case Gate::NoBudget: return ReadStop::NoBudgetLease; + case Gate::Ok: break; + } + if (!fits(reservation, bound)) + return ReadStop::PolicyExhausted; + return std::nullopt; +} + uint64_t CasOperation::reservedFor(uint64_t sleep_ms, uint32_t envelopes) const { uint64_t total = sleep_ms; @@ -547,7 +562,7 @@ std::optional CasOperation::pauseAfterUnresolvedWrite(uint64_t ms, const } std::optional CasOperation::pauseUnderPolicy(uint64_t ms, const Retry & policy, PauseAfter after, - void (*record)()) + void (*record)(), bool zero_is_no_pause) { /// Admission for `needed_ms` of pause, so a pause never outlives the mount lease. A window belongs to /// one request and the next request binds its own when it is sent, so only the policy's absolute limits @@ -571,6 +586,8 @@ std::optional CasOperation::pauseUnderPolicy(uint64_t m }; if (auto stop = check_pause(ms)) return stop; + if (ms == 0 && zero_is_no_pause) + return std::nullopt; record(); /// A query cut short here is reported by the check below, after the typed bounds. if (after == PauseAfter::Failure) @@ -582,9 +599,9 @@ std::optional CasOperation::pauseUnderPolicy(uint64_t m } std::optional CasOperation::pauseBetweenDecisions(uint64_t ms, WriteState & state, const Retry & policy, - PauseAfter after, void (*record)()) + PauseAfter after, void (*record)(), bool zero_is_no_pause) { - const std::optional stop = pauseUnderPolicy(ms, policy, after, record); + const std::optional stop = pauseUnderPolicy(ms, policy, after, record, zero_is_no_pause); if (!stop) return std::nullopt; switch (*stop) @@ -802,10 +819,11 @@ Removal CasOperation::removeCurrent(const String & key, const Retry & policy) throwDidNotConverge(fmt::format("CAS remove of '{}'", key), kCasMaxDecisions, "decisions"); } - /// Another incarnation became current between the observation and the delete. Re-observe, paced - /// like every other reissue; the next `head` and `remove` bind their own windows. + /// Another incarnation became current between the observation and the delete: a lost race. Re-observe + /// after the conflict pause; the next `head` and `remove` bind their own windows. if (const std::optional stop - = pauseUnderPolicy(Retry::backoff(attempt), policy, PauseAfter::Conflict, detail::recordReissue)) + = pauseUnderPolicy(Retry::conflictBackoff(attempt), policy, PauseAfter::Conflict, detail::recordReissue, + /*zero_is_no_pause=*/true)) { switch (*stop) { @@ -1032,17 +1050,27 @@ WriteResult CasOperation::gaveUpAfterDecisionCap(WriteState & state, const Retry return gaveUp(GaveUp::Why::Attempts, GaveUp::Source::Policy, state); } +CasOperation::OnCleanRefusal CasOperation::onCleanRefusalBefore(uint32_t decisions, const Retry & policy) +{ + /// A decision that another follows after a conflict pause reads again after that pause; the last + /// one, and a single attempt, report what the settling read saw. + return policy.single_attempt || decisions == kCasMaxDecisions ? OnCleanRefusal::Settle : OnCleanRefusal::ReturnUnobserved; +} + std::optional CasOperation::pauseAfterConflict(uint32_t decisions, WriteState & state, const Retry & policy) { if (decisions == kCasMaxDecisions) return gaveUpAfterDecisionCap(state, policy); - /// A clean lost race is settled: the resolve read holds the fresh object and the next - /// iteration decides on it. Only a conflict that settled a transport fault is paced by the - /// growing schedule. Either way the conflict is an answer, so the pause does not consult the query. - return state.any_ambiguous - ? pauseBetweenDecisions(reissuePause(state, Retry::backoff(++state.reissues)), state, policy, PauseAfter::Conflict) - : pauseBetweenDecisions(reissuePause(state, Retry::conflictBackoff()), state, policy, PauseAfter::Conflict, - detail::recordConflictPause); + /// A clean conflict is paced by the call's run of consecutive clean ones, which a conflict that settled a + /// transport fault ends; that one is paced by the fault schedule. Either way the conflict is an answer, so the + /// pause does not consult the query. The first clean conflict of a run is retried at once, after the same checks. + if (state.any_ambiguous) + { + state.clean_conflicts = 0; + return pauseBetweenDecisions(reissuePause(state, Retry::backoff(++state.reissues)), state, policy, PauseAfter::Conflict); + } + return pauseBetweenDecisions(reissuePause(state, Retry::conflictBackoff(++state.clean_conflicts)), state, policy, + PauseAfter::Conflict, detail::recordConflictPause, /*zero_is_no_pause=*/true); } WriteResult CasOperation::postCommit(Etag inc, bool resolved_by_read, WriteState & state, const Retry::Bound & bound) @@ -1256,7 +1284,8 @@ void reportWriteFailure(const RequestObserver & observer, const String & key, co } WriteResult CasOperation::writeLoop(const String & key, const String & bytes, const std::optional & expected, - const Retry & policy, WriteState & state, ResolveWith resolve_refusal_with) + const Retry & policy, WriteState & state, ResolveWith resolve_refusal_with, + OnCleanRefusal on_clean_refusal) { const Retry::Bound bound = owner.bindPolicy(policy); std::optional expected_value; @@ -1407,8 +1436,20 @@ WriteResult CasOperation::writeLoop(const String & key, const String & bytes, co continue; } - /// One exact read settles every refused precondition and every ambiguity, under every policy: a refused - /// precondition does not say WHO holds the key. A presence-only caller settles a refusal with a HEAD; proving + if (attempt.kind == AttemptKind::Conflict && !earlier_attempt_unanswered + && on_clean_refusal == OnCleanRefusal::ReturnUnobserved) + { + state.last_seen = NotObserved{}; + /// The skipped read would have bound its own window and been refused by these, before any pause the + /// caller takes; they are reported as that read reports them. + const Retry::Bound read_bound = owner.bindPolicy(policy); + if (const std::optional read_refused = refusedReadAttempt(read_bound)) + return gaveUpForReadStop(*read_refused, sourceFor(read_bound), state); + return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous, state.observed_stop}; + } + + /// One exact read settles every other refused precondition and every ambiguity: a refused precondition does + /// not say WHO holds the key. A presence-only caller settles a refusal with a HEAD; proving /// an ambiguous attempt landed needs the bytes. if (auto settled = adjudicate(settlingRead(key, policy, state, resolve_refusal_with), bytes, expected, state, bound)) return *settled; @@ -1442,20 +1483,38 @@ WriteResult CasOperation::replace(const String & key, const String & bytes, cons return writeLoop(key, bytes, seen, policy, state, ResolveWith::Body); } -WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObject & decide, const Retry & policy) +template +WriteResult CasOperation::readModifyWriteImpl( + const String & key, const std::function(const std::optional &)> & decide, const Retry & policy) { - WriteState state; - - Resolved resolved = observe(key, policy); - state.last_seen = resolved.seen; - std::optional current; - if (const auto * obj = std::get_if(&state.last_seen)) - current = *obj; - else if (!std::holds_alternative(state.last_seen)) - return gaveUpAfterFailedObservation(resolved, state); + constexpr bool presence_only = std::is_same_v; + constexpr ResolveWith observe_with = presence_only ? ResolveWith::Presence : ResolveWith::Body; + /// Proving an ambiguous attempt landed needs the bytes even here; a presence-only verb reports metadata only. + const auto reported = [](auto value) + { + if constexpr (presence_only) + return withoutBody(std::move(value)); + else + return value; + }; + WriteState state; for (uint32_t decisions = 1;; ++decisions) { + /// A decision after the first is reached only through the conflict pause, and reads after it: a write + /// landing during the pause would refuse a decision taken on any read before it. + if (decisions > 1) + if (const std::optional given_up = pauseAfterConflict(decisions - 1, state, policy)) + return *given_up; + + const Resolved resolved = observe(key, policy, observe_with); + state.last_seen = resolved.seen; + std::optional current; + if (const auto * seen = std::get_if(&state.last_seen)) + current = *seen; + else if (!std::holds_alternative(state.last_seen)) + return gaveUpAfterFailedObservation(resolved, state); + throwIfBackgroundStopped(); /// Outside every classification: `decide` is the caller's own control flow, and an exception /// from it is theirs to see unchanged. @@ -1463,90 +1522,22 @@ WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObje if (!next) return Declined{state.last_seen}; - WriteResult result = writeLoop(key, *next, - current ? std::optional(current->etag) : std::nullopt, policy, state, - ResolveWith::Body); - if (!std::holds_alternative(result)) - return result; - - /// The write's own resolve read IS this iteration's read: a hot key never costs a second GET - /// per conflict. - if (const auto * obj = std::get_if(&state.last_seen)) - current = *obj; - else if (std::holds_alternative(state.last_seen)) - current.reset(); - - if (policy.single_attempt || state.observed_stop) - return result; - if (const std::optional given_up = pauseAfterConflict(decisions, state, policy)) - return *given_up; - - /// Only when the resolve settled nothing is a fresh read owed; otherwise `current` already is - /// what the store held. - if (std::holds_alternative(state.last_seen)) - { - resolved = observe(key, policy); - state.last_seen = resolved.seen; - if (const auto * obj = std::get_if(&state.last_seen)) - current = *obj; - else if (std::holds_alternative(state.last_seen)) - current.reset(); - else - return gaveUpAfterFailedObservation(resolved, state); - } + WriteResult result = writeLoop(key, *next, current ? std::optional(current->etag) : std::nullopt, policy, state, + observe_with, onCleanRefusalBefore(decisions, policy)); + state.last_seen = reported(std::move(state.last_seen)); + if (!std::holds_alternative(result) || policy.single_attempt || state.observed_stop) + return reported(std::move(result)); } } -WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const DecideOnMeta & decide, const Retry & policy) +WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObject & decide, const Retry & policy) { - WriteState state; - - Resolved resolved = observe(key, policy, ResolveWith::Presence); - state.last_seen = resolved.seen; - std::optional current; - if (const auto * meta = std::get_if(&state.last_seen)) - current = *meta; - else if (!std::holds_alternative(state.last_seen)) - return gaveUpAfterFailedObservation(resolved, state); - - for (uint32_t decisions = 1;; ++decisions) - { - throwIfBackgroundStopped(); - const std::optional next = decide(current); - if (!next) - return Declined{state.last_seen}; - - WriteResult result = writeLoop(key, *next, - current ? std::optional(current->etag) : std::nullopt, policy, state, - ResolveWith::Presence); - /// A refused precondition was settled by a HEAD, but proving an ambiguous attempt landed needs - /// the bytes; this loop is presence-only by contract, so that body stops here. - state.last_seen = withoutBody(std::move(state.last_seen)); - if (!std::holds_alternative(result)) - return withoutBody(std::move(result)); - - if (const auto * meta = std::get_if(&state.last_seen)) - current = *meta; - else if (std::holds_alternative(state.last_seen)) - current.reset(); - - if (policy.single_attempt || state.observed_stop) - return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous, state.observed_stop}; - if (const std::optional given_up = pauseAfterConflict(decisions, state, policy)) - return *given_up; + return readModifyWriteImpl(key, decide, policy); +} - if (std::holds_alternative(state.last_seen)) - { - resolved = observe(key, policy, ResolveWith::Presence); - state.last_seen = resolved.seen; - if (const auto * meta = std::get_if(&state.last_seen)) - current = *meta; - else if (std::holds_alternative(state.last_seen)) - current.reset(); - else - return gaveUpAfterFailedObservation(resolved, state); - } - } +WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const DecideOnMeta & decide, const Retry & policy) +{ + return readModifyWriteImpl(key, decide, policy); } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h index e122f2b6084b0..998878396c3d2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h @@ -404,8 +404,8 @@ class CasOperation WriteResult create(const String & key, const String & bytes, const Retry & policy); WriteResult replace(const String & key, const String & bytes, const Etag & seen, const Retry & policy); - /// Read, decide, write, and re-decide on conflict against what the write's own resolve read - /// already observed. `decide` returning nullopt is `Declined`. + /// Read, decide, write; on a conflict, pause, read again and re-decide on that read. `decide` + /// returning nullopt is `Declined`. WriteResult readModifyWrite(const String & key, const DecideOnObject & decide, const Retry & policy); /// The same loop over `head`, settling a refused precondition with a `head` too. Proving that an /// ambiguous attempt landed needs the bytes, so that one path does read a body; either way the verb @@ -447,6 +447,8 @@ class CasOperation bool any_ambiguous = false; Observation last_seen = NotObserved{}; uint32_t reissues = 0; + /// The current run of consecutive clean lost races, which sets the length of the conflict pause. + uint32_t clean_conflicts = 0; bool refresh_attempted = false; /// An operation of this call failed and saw its query stopped: a write attempt, its settling read, or the /// pause before a reissue. The call starts no further discretionary request, also after a settled conflict. @@ -466,6 +468,9 @@ class CasOperation /// confusion `GaveUp::Source` exists to prevent. `PolicyExhausted` names the `Retry` bound, whose /// own source is `Bound::source`. enum class ReadStop : uint8_t { FenceLost, NoBudgetLease, PolicyExhausted }; + /// What refuses the next attempt of a read-class request bound to `bound`, if anything: the fence, the lease + /// budget for one request envelope, then the bound itself. + std::optional refusedReadAttempt(const Retry::Bound & bound) const; /// What the resolve read saw, and why it stopped when it saw nothing. `stop` is set ONLY when a /// bound refused; a read that failed at the transport leaves it empty, and that is the one case @@ -502,8 +507,14 @@ class CasOperation /// failed connection is reissued before its read. `Refused`, `Declined` and `GaveUp` report what /// the store or the bounds said. The window bound at entry governs every send of these bytes; the /// read that settles an attempt is a request of its own and binds its own window from `policy`. + /// What a clean refused precondition (no attempt of this call left unanswered) returns. `ReturnUnobserved` + /// skips the settling read and returns `Conflict{NotObserved}`, for a caller that pauses and reads again + /// before its next decision, which would overwrite that read unused. + enum class OnCleanRefusal : uint8_t { Settle, ReturnUnobserved }; + WriteResult writeLoop(const String & key, const String & bytes, const std::optional & expected, - const Retry & policy, WriteState & state, ResolveWith resolve_refusal_with); + const Retry & policy, WriteState & state, ResolveWith resolve_refusal_with, + OnCleanRefusal on_clean_refusal = OnCleanRefusal::Settle); /// The resolve read: an exact read (a `HEAD` for `Presence`) under its own window from `policy`, reporting /// what it saw and, when it saw nothing, which of its bounds stopped it. A stopped owner's failure is /// `NotObserved` only when a bound refused the read or inside `owed`; otherwise it propagates. @@ -533,15 +544,23 @@ class CasOperation enum class PauseAfter : uint8_t { Conflict, Failure }; /// The pause between two decisions: admission for the pause, then the policy's explicit lease and outside cap, /// then the sleep, then admission, lease and cap again so no `decide` runs past them. It consults - /// no window: the next decision's requests bind their own when they are sent. - std::optional pauseUnderPolicy(uint64_t ms, const Retry & policy, PauseAfter after, void (*record)()); + /// no window: the next decision's requests bind their own when they are sent. With `zero_is_no_pause`, a + /// pause of 0 ms runs the checks once and neither records nor sleeps. + std::optional pauseUnderPolicy(uint64_t ms, const Retry & policy, PauseAfter after, void (*record)(), + bool zero_is_no_pause = false); /// `pauseUnderPolicy` reported as a give-up. A value means the call ended; nullopt means /// `decide` may run again. std::optional pauseBetweenDecisions(uint64_t ms, WriteState & state, const Retry & policy, PauseAfter after, - void (*record)() = detail::recordReissue); + void (*record)() = detail::recordReissue, bool zero_is_no_pause = false); /// The read-modify-write loops' step after a lost decision: the decision cap, else the pause before the next /// decision. A value means the call ended. std::optional pauseAfterConflict(uint32_t decisions, WriteState & state, const Retry & policy); + /// The loop behind `readModifyWrite` (`Seen = Object`, GET) and `readModifyWriteOnPresence` (`Seen = Meta`, HEAD). + template + WriteResult readModifyWriteImpl(const String & key, const std::function(const std::optional &)> & decide, + const Retry & policy); + /// How the read-modify-write loops' write of decision number `decisions` answers a clean refusal. + static OnCleanRefusal onCleanRefusalBefore(uint32_t decisions, const Retry & policy); /// The caller may send another attempt. struct ResumeAfterPause {}; /// A query stopped in the pause and vetoes the next attempt; the pause also set `state.observed_stop`. @@ -618,15 +637,15 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const /// Not before the first attempt: a healthy read is never refused, as on a plain S3 disk. if (attempt_no > 1) throwIfBackgroundStopped(); - const uint64_t reservation = reservedFor(0, 1); - switch (gate(reservation)) + if (const std::optional refused = refusedReadAttempt(bound)) { - case Gate::FenceLost: giveUpReadFenceLost(verb, subject, "before the request"); - case Gate::NoBudget: giveUpReadNoBudget(verb, subject, "for one more request"); - case Gate::Ok: break; + switch (*refused) + { + case ReadStop::FenceLost: giveUpReadFenceLost(verb, subject, "before the request"); + case ReadStop::NoBudgetLease: giveUpReadNoBudget(verb, subject, "for one more request"); + case ReadStop::PolicyExhausted: giveUpReadDeadline(verb, subject, source, attempt_no - 1); + } } - if (!fits(reservation, bound)) - giveUpReadDeadline(verb, subject, source, attempt_no - 1); if (policy.attempt_spacing_ms) attempt_started_ms = owner.now_ms(); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp index 86f680da7ea60..62fd37252a572 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp @@ -17,6 +17,13 @@ uint64_t Retry::backoff(uint32_t attempt) return thread_local_rng() % (ceiling + 1); /// full jitter: uniform(0, ceiling) } +uint64_t Retry::conflictBackoff(uint32_t loss) +{ + const uint64_t steps = loss > 0 ? loss - 1 : 0; + const uint64_t base = std::min(kCasConflictPauseCeilingMs, kCasConflictPauseStepMs * steps); + return base + thread_local_rng() % (base / 4 + 1); +} + uint64_t Retry::spacedPause(uint64_t spacing_draw_ms, uint64_t attempt_started_ms, uint64_t now_ms) { const uint64_t taken_ms = now_ms > attempt_started_ms ? now_ms - attempt_started_ms : 0; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h index 591dfeb97044d..73fd6514854f2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h @@ -11,6 +11,12 @@ namespace DB::Cas /// An update of a shared object that keeps losing races fails at this count with `NETWORK_ERROR` "did not converge"; /// there is no total time budget, and each request has its own window. inline constexpr uint32_t kCasMaxDecisions = 100; +/// How much the pause grows with each further consecutive clean lost race of one call: enough to desynchronise competitors, +/// short enough not to wait long when a race is brief. +inline constexpr uint64_t kCasConflictPauseStepMs = 40; +/// The ceiling of the pause's base: 100 lost races cost about 67 to 84 s of pauses, under the waits other parts of +/// the server put on these loops. A pause adds up to a quarter of its base. +inline constexpr uint64_t kCasConflictPauseCeilingMs = 750; /// The walk that fails at this count propagates its own error; a restart at it fails as "did not converge". inline constexpr uint32_t kCasMaxRecoveryWalks = 8; @@ -65,12 +71,12 @@ struct Retry /// `attempt == 0` returns 0. static uint64_t backoff(uint32_t attempt); - /// The flat pause after a clean lost race: `backoff(1)`, uniform over [0, 200] ms. It does not grow - /// with the writer's loss count, because a settled conflict has nothing to wait for but - /// desynchronisation from its competitors, and growing it with the loss count made the oldest - /// loser the slowest and the likeliest to lose again. A conflict that settled a transport fault - /// keeps `backoff(attempt)`: the fault is what must pace the loop. - static uint64_t conflictBackoff() { return backoff(1); } + /// The pause after the `loss`-th consecutive clean lost race of one call (1-based): `base` plus uniform(0, base / 4), + /// `base = min(kCasConflictPauseCeilingMs, kCasConflictPauseStepMs * (loss - 1))`, so the first is 0. The next decision + /// reads after the pause, so its length does not change that decision's chance; it grows only to + /// lower the contention a repeated loss shows, and the jitter keeps competitors from retrying in step. + /// A conflict that settled a transport fault keeps `backoff(attempt)`: the fault is what must pace it. + static uint64_t conflictBackoff(uint32_t loss); /// A policy with `ms` milliseconds of its own budget and no lease bound. static Retry within(uint64_t ms) { return {.window_ms = ms, .lease_deadline_ms = std::nullopt, .single_attempt = false}; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h index 73a391abdeb37..65eeb8bcabbca 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h @@ -49,8 +49,8 @@ struct Declined { Observation seen; }; /// carry: an operator's attempt counters sum over ALL the endings of a write, and losing the key is /// one an operator wants counted rather than dropped. `any_ambiguous` is true when an attempt of the /// inner write ended without proof of whether it applied before the resolve read settled the race: a -/// caller outside the engine paces such a conflict on the growing schedule, as the engine's own -/// loops do, and a clean lost race on the flat one. `attempts_sent` cannot stand in for it: a +/// caller outside the engine paces such a conflict on the fault schedule (`Retry::backoff`), as the +/// engine's own loops do, and a clean lost race on `Retry::conflictBackoff`. `attempts_sent` cannot stand in for it: a /// throttled first attempt whose resolve read finds the key moved is one attempt, ambiguous. /// `observed_stop` is true when an operation of the call failed and saw its query stopped: a loop takes the /// conflict as the answer and starts no further decision. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp index 7cb416f41cfad..61e50cc27e750 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp @@ -6130,9 +6130,9 @@ bool Gc::acquireOrRenewLease(GcState & state, std::optional & state_etag, CasOperation op = store->openRequests().admit(); const String key = store->layout().gcStateKey(); - /// What the decision that actually landed wrote. `readModifyWrite` re-decides on every conflict - /// against what the losing write's own resolve read observed, so the last decision is the committed - /// one, and a competing leader's write makes the next decision see a moved lease tuple. + /// What the decision that actually landed wrote. `readModifyWrite` re-decides after every conflict + /// on a read taken after its pause, so the last decision is the committed one, and a competing + /// leader's write makes the next decision see a moved lease tuple. GcState decided; bool decided_never_held = false; const std::optional committed = orThrow(op.readModifyWrite(key, diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp index 259e6c5d81373..5b64c56596c2f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp @@ -151,8 +151,7 @@ struct CatalogDecisionFailure : std::exception /// Shared body of `casUpdate`/`casAdmitEntry`. `encode` turns a freshly `mutate`d candidate into the /// bytes to write: the plain path just grammar-checks (`encodeRefCatalog`), the admitting path also /// runs both admission predicates (`checkCatalogAdmission`) first. A refused precondition re-runs -/// `mutate` against the resolve read's fresh body -- the one the pool's hot-key lane remembers and -/// the next hold starts from -- never re-encoding the stale candidate. +/// `mutate` against a fresh read, never re-encoding the stale candidate. RefCatalog casUpdateImpl( CasOperation & op, const Layout & layout, const std::function & mutate, @@ -196,23 +195,29 @@ RefCatalog casUpdateImpl( try { /// One hold at a time per pool on this key, from the pool's last known catalog when the lane holds - /// one. The loop is this function's: a `Conflict` is a lost race against another server (the lane - /// never conflicts with itself), repaid after the flat jitter, or after the growing schedule when - /// the conflict settled a transport fault. Under a single-attempt policy the first `Conflict` is - /// the answer, as the engine's own verb answers it. Each request binds its own window, so the - /// count of submissions is what ends a loop that keeps losing; one submission may run `decide` - /// twice on a cached catalog, so `decide` calls are not counted. + /// one; the lane itself retries a clean loss on that cached catalog at once. The loop is this + /// function's: a `Conflict` is a lost race against another server (the lane never conflicts with + /// itself), repaid after `Retry::conflictBackoff` of the run of consecutive clean losses, or after the fault + /// schedule when the conflict settled a transport fault; the next submission reads after the pause. + /// Under a single-attempt policy the first `Conflict` is the answer, as the engine's own verb answers + /// it. Each request binds its own window, so the count of submissions is what ends a loop that keeps + /// losing; one submission may run `decide` twice on a cached catalog, so `decide` calls are not counted. /// /// Under `resend_unresolved = false` the engine returns an attempt whose fate is unknown instead of /// resending its bytes, and this loop decides again on a fresh read. Attempt numbering continues, /// so the next write is not a first attempt with the adaptive timeout again. Retry attempt_policy = policy; uint32_t settled_faults = 0; + uint32_t clean_losses = 0; for (uint32_t submissions = 1;; ++submissions) { + /// Every submission after the first follows a pause, so it reads rather than start from a body + /// another holder of this pool remembered during that pause. if (submissions > 1) throwIfBackgroundStopped(); - WriteResult result = op.hotKeys().submit(key, op, attempt_policy, decide); + WriteResult result = op.hotKeys().submit(key, op, attempt_policy, decide, + submissions > 1 ? CasHotKeys::Start::Read : CasHotKeys::Start::CacheOrRead, + submissions < kCasMaxDecisions ? CasHotKeys::OnLoss::SubmitAgain : CasHotKeys::OnLoss::End); if (std::holds_alternative(result)) return std::move(*written); @@ -249,9 +254,17 @@ RefCatalog casUpdateImpl( } if (lost_race) { - op.sleepFor(conflict->any_ambiguous ? Retry::backoff(++settled_faults) : Retry::conflictBackoff()); + /// The pause follows the run of consecutive clean losses; a settled fault ends that run. + if (conflict->any_ambiguous) + { + clean_losses = 0; + op.sleepFor(Retry::backoff(++settled_faults)); + } + else if (const uint64_t pause_ms = Retry::conflictBackoff(++clean_losses); pause_ms > 0) + op.sleepFor(pause_ms); continue; } + clean_losses = 0; attempt_policy.attempts_already_sent += gave_up->attempts_sent; std::optional stopped = op.pauseAfterUnresolvedWrite(Retry::backoff(++settled_faults), *gave_up, policy); if (!stopped) @@ -562,11 +575,13 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov const Retry policy = Retry::standard(); bool retirement_announced = false; + uint32_t clean_losses = 0; /// Each request binds its own window, so only the count ends a loop that keeps losing the catalog. for (uint32_t attempt = 0; attempt < kCasMaxDecisions; ++attempt) { - /// So the admission consulted below is not one reading taken before the first attempt. - if (refresh_authority) + /// So the admission consulted below is not one reading taken before the first attempt. A later + /// attempt refreshes right after its pause, below. + if (refresh_authority && attempt == 0) refresh_authority(); catalog_snapshot.life_index.throwIfAmbiguous("CAS completed-removal deletion"); @@ -600,10 +615,22 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov const bool erase_again = conflict && !conflict->observed_stop; /// Pause before the read: that read is the snapshot the next erase is conditioned on, and a /// write landing during a pause taken after it would refuse that erase every time. - /// The argument counts reissues so far: `backoff(0)` is no wait at all. No erase follows the - /// last attempt, so nothing waits for it. + /// A clean refusal is paced by the run of consecutive clean ones, which a refusal that settled a transport + /// fault ends; that one is paced by the fault schedule. No erase follows the last attempt, so nothing waits for it. + /// The next attempt's refresh follows the pause and precedes the read, so no request sits between + /// that read and the erase on it. A stopped background owner makes no next attempt, so it skips it. if (erase_again && attempt + 1 < kCasMaxDecisions) - op.sleepFor(Retry::backoff(attempt + 1)); + { + if (conflict->any_ambiguous) + { + clean_losses = 0; + op.sleepFor(Retry::backoff(attempt + 1)); + } + else if (const uint64_t pause_ms = Retry::conflictBackoff(++clean_losses); pause_ms > 0) + op.sleepFor(pause_ms); + if (refresh_authority && !backgroundStopRequested()) + refresh_authority(); + } /// An operation whose admission is gone cannot issue the resolution read either, so the call /// ends HERE and reports the cut it was given rather than a fresh one. There is nothing further diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h index 5a4c00759d176..6e15435ca72f7 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h @@ -155,8 +155,9 @@ class CasRefCatalog /// `catalog_snapshot`, and the mandatory resolution snapshot is returned in the result so a /// catalog-only drain can select the next row without an intervening read. /// - /// `refresh_authority` runs at the top of every attempt, before the checks that decide whether to - /// send one. It is not a verdict -- the verdict stays `op.admitted()` -- but that liveness may be + /// `refresh_authority` runs once before every attempt: before the first one's checks, and for each + /// later one right after its pause, before the catalog read that attempt is conditioned on, unless + /// a background owner stopped during that pause. It is not a verdict -- the verdict stays `op.admitted()` -- but that liveness may be /// a cached flag its holder refreshes from a fact this loop cannot see, and one reading taken /// before the first erase must not authorise the rest. A caller whose liveness needs no refresh /// passes a no-op and says so. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index 181974bd7ac4b..b7b9374a85725 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -1532,12 +1532,18 @@ NamespaceLifeId CasRefLedger::resolveNamespaceLife( CasOperation op = mount_requests.resume(admitted_generation); const Retry policy = Retry::standard(); + uint32_t collisions = 0; for (size_t attempt = 0; attempt < kMaxResolveAttempts; ++attempt) { - /// Paces ONLY the re-reads a competing actor forced. A `Live` outcome is this open's own - /// success and its single confirming re-read is not contention, so it is never delayed. The - /// argument is the number of collisions so far, so the first one waits the shortest draw. - const auto paceReRead = [&] { op.sleepFor(Retry::backoff(static_cast(attempt) + 1)); }; + /// Paces ONLY the re-reads a competing actor forced, by the count of those collisions. A `Live` + /// outcome is this open's own success and its single confirming re-read is not contention, so it + /// is never delayed. The last attempt is followed by no re-read, so nothing waits for it. + const auto paceReRead = [&] + { + ++collisions; + if (const uint64_t pause_ms = Retry::conflictBackoff(collisions); pause_ms > 0 && attempt + 1 < kMaxResolveAttempts) + op.sleepFor(pause_ms); + }; const CasRefCatalog::Snapshot snap = CasRefCatalog::read(op, layout, policy); const auto it = std::find_if(snap.catalog.entries.begin(), snap.catalog.entries.end(), From dd66035fe904a67a24b8c01ca632b4433b8e35f6 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 19:51:22 +0100 Subject: [PATCH 19/47] Test the probe order and the pause schedule of CAS retries Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- src/Disks/tests/cas_test_helpers.h | 43 ++ src/Disks/tests/gtest_cas_hot_keys.cpp | 192 +++++++- src/Disks/tests/gtest_cas_owner_stop.cpp | 176 +++++-- src/Disks/tests/gtest_cas_ref_catalog.cpp | 446 ++++++++++++++++-- .../gtest_cas_ref_catalog_birth_wiring.cpp | 95 +++- src/Disks/tests/gtest_cas_requests.cpp | 313 ++++++++++-- src/Disks/tests/gtest_cas_shared_deadline.cpp | 78 ++- 7 files changed, 1190 insertions(+), 153 deletions(-) diff --git a/src/Disks/tests/cas_test_helpers.h b/src/Disks/tests/cas_test_helpers.h index 4038ea9fe8366..d2afab191288c 100644 --- a/src/Disks/tests/cas_test_helpers.h +++ b/src/Disks/tests/cas_test_helpers.h @@ -2405,6 +2405,49 @@ class CountingBackend : public DB::Cas::InMemoryBackend uint64_t publish_total = 0; }; +/// Whether `ms` is a pause after the `n`-th clean lost race of one call: `base <= ms <= base + base / 4`, with +/// `base = min(750, 40 * (n - 1))`, so the first is exactly 0. +inline ::testing::AssertionResult isConflictPause(uint64_t ms, uint32_t n) +{ + const uint64_t base = std::min(750, 40ull * (n - 1)); + if (ms >= base && ms <= base + base / 4) + return ::testing::AssertionSuccess(); + return ::testing::AssertionFailure() << ms << " ms is not the pause after clean loss " << n << ": expected [" + << base << ", " << base + base / 4 << "]"; +} + +/// The requests on `key` as one letter each (`R` read, `H` head, `W` write), with a mark labelled +/// `pause` as `P`. Requests between a `rival{` mark and the next `}rival` mark are left out, so a test +/// sees only its own caller's requests and where a competitor's commits fell among them. +inline String renderOwnRequests(const CountingBackend & backend, const String & key) +{ + String out; + bool in_rival = false; + for (const JournalEntry & entry : backend.journal()) + { + if (entry.verb == JournalVerb::Mark) + { + if (entry.detail == "rival{") + in_rival = true; + else if (entry.detail == "}rival") + in_rival = false; + else if (entry.detail == "pause" && !in_rival) + out += 'P'; + continue; + } + if (in_rival || entry.keys != std::vector{key}) + continue; + switch (entry.verb) + { + case JournalVerb::Read: out += 'R'; break; + case JournalVerb::Head: out += 'H'; break; + case JournalVerb::Write: out += 'W'; break; + default: out += '?'; break; + } + } + return out; +} + /// Runs a hook once, on the first HEAD of one key after `armOnHead`, before that HEAD is served and with no /// backend lock held. A writer that commits there lands after the round's cut and before the redelete /// observes the blob. diff --git a/src/Disks/tests/gtest_cas_hot_keys.cpp b/src/Disks/tests/gtest_cas_hot_keys.cpp index 39cec4c7bd0d6..437b161486665 100644 --- a/src/Disks/tests/gtest_cas_hot_keys.cpp +++ b/src/Disks/tests/gtest_cas_hot_keys.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -223,15 +224,25 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) ASSERT_TRUE(std::holds_alternative(result)); } #endif - /// A clean refused precondition with the store unchanged: `Conflict` carrying the occupant. + /// A clean refused precondition with the store unchanged, under a single attempt: `Conflict` carrying the occupant. backend->refuseNextWrite("k"); { - WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(3)); + WriteResult result = hot_keys.submit("k", op, Retry::once(), appendTicket(3)); const auto * conflict = std::get_if(&result); ASSERT_NE(conflict, nullptr); EXPECT_TRUE(std::holds_alternative(conflict->seen)); EXPECT_FALSE(conflict->any_ambiguous); } + /// The same refusal of a write decided on a fresh read, for a caller that retries: it pauses and reads before its + /// next decision, so the refusal is returned unsettled. + backend->refuseNextWrite("k"); + { + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(3), CasHotKeys::Start::Read); + const auto * conflict = std::get_if(&result); + ASSERT_NE(conflict, nullptr); + EXPECT_TRUE(std::holds_alternative(conflict->seen)); + EXPECT_FALSE(conflict->any_ambiguous); + } /// The resolve read fails at the transport under `once`: nothing observed. The failure is armed /// from a one-shot write hook, not up front, so it lands on the write's own resolve read rather /// than on the hold's base read, which must succeed for this sub-case to reach the write at all. @@ -515,13 +526,13 @@ TEST(CASHotKeys, AnExternalWriterCostsOneResolveReadAndOneRetry) const uint64_t gets_before = backend->getCount("k"); const uint64_t writes_before = backend->writeCount("k"); - /// The caller's loop: submit, and on a conflict submit again after the flat pause. + /// The caller's loop: submit, and on a conflict submit again after the conflict pause. std::optional result; - for (int i = 0; i < 3 && !result; ++i) + for (uint32_t i = 0; i < 3 && !result; ++i) { WriteResult attempt = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); if (std::holds_alternative(attempt)) - op.sleepFor(Retry::conflictBackoff()); + op.sleepFor(Retry::conflictBackoff(i + 1)); else result = std::move(attempt); } @@ -535,6 +546,153 @@ TEST(CASHotKeys, AnExternalWriterCostsOneResolveReadAndOneRetry) DB::Cas::tests::expectBytes(*backend, "k", "E,2,3"); } +namespace +{ + +/// Records the physical attempt number the engine hands the transport for each write of `key`. +struct AttemptNumberingBackend : CountingBackend +{ + std::vector write_attempts; + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (key == "k") + write_attempts.push_back(access.attemptNo()); + return CountingBackend::write(key, bytes, expected_value, access); + } +}; + +} + +/// The refused write on a hint and the write on its resolve read are attempts of one submission: they are +/// counted and numbered together, and a give-up between them reports the first. +TEST(CASHotKeys, BothWritesOfOneHoldAreAttemptsOfOneSubmission) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + auto op = requests.admit(); + CasRequests external_requests = DB::Cas::tests::openRequestsForTest(backend); + auto external = external_requests.admit(); + const auto move_externally = [&](const String & bytes) + { + const auto current = external.read("k", Retry::standard()); + (void)orThrow(external.replace("k", bytes, current->etag, Retry::standard()), "external"); + }; + + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); + move_externally("E"); + backend->write_attempts.clear(); + { + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); + const auto * committed = std::get_if(&result); + ASSERT_NE(committed, nullptr); + EXPECT_EQ(committed->attempts_sent, 2u); + EXPECT_EQ(backend->write_attempts, (std::vector{1, 2})); + } + + /// The fence trips in the decision on the resolve read, so the second write is never sent. + move_externally("F"); + bool alive = true; + auto fenced = requests.admit([&] { return alive; }); + int decisions = 0; + WriteResult result = hot_keys.submit("k", fenced, Retry::standard(), + [&](const std::optional & current) -> std::optional + { + if (++decisions == 2) + alive = false; + return current->bytes + ",3"; + }); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(gave_up->attempts_sent, 1u); + const auto * seen = std::get_if(&gave_up->last_seen); + ASSERT_NE(seen, nullptr) << "the resolve read of the refused write"; + EXPECT_EQ(seen->bytes, "F"); +} + +/// A retrying caller's refusal on a fresh read is returned unsettled, but only when the read it skips would +/// have been admitted: the same lease budget and the same bounds decide, and report what that read would. +TEST(CASHotKeys, AnUnsettledRefusalStillMeetsTheBoundsOfTheReadItSkips) +{ + { + SCOPED_TRACE("the lease has room for less than one more request"); + SyncClock clock; + auto backend = std::make_shared(); + uint64_t lease_left_ms = 10'000; + Fence fence = Fence::open(); + fence.admit = [&lease_left_ms](uint64_t, uint64_t needed_ms) + { + return needed_ms <= lease_left_ms ? Fence::Admit::Ok : Fence::Admit::NoBudget; + }; + CasHotKeys hot_keys(0); + CasRequests requests(backend, fence, clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + requests.setAttemptReservationForTest(1'000); + auto op = requests.admit(); + (void)orThrow(op.create("k", "1", Retry::standard()), "seed"); + backend->refuseNextWrite("k"); + backend->onBeforeWrite("k", [&] { lease_left_ms = 500; }); + + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2), CasHotKeys::Start::Read); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << "index " << result.index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Lease); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(clock.sleepCount(), 0u); + } + { + SCOPED_TRACE("an absolute cap leaves less than one request envelope once the write returns"); + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(0); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + requests.setAttemptReservationForTest(1'000); + auto op = requests.admit(); + (void)orThrow(op.create("k", "1", Retry::standard()), "seed"); + const Retry capped = Retry::standard().cappedAt(clock.nowFn()() + 10'000); + backend->refuseNextWrite("k"); + backend->onBeforeWrite("k", [&] { clock.advance(9'500); }); + + WriteResult result = hot_keys.submit("k", op, capped, appendTicket(2), CasHotKeys::Start::Read); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << "index " << result.index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(clock.sleepCount(), 0u); + } +} + +/// A loss on a cached body says only that the cache was old: the hold decides again on the resolve +/// read and writes at once, with no pause, in the same submission. +TEST(CASHotKeys, ALossOnACachedBodyRetriesAtOnce) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + auto op = requests.admit(); + CasRequests external_requests = DB::Cas::tests::openRequestsForTest(backend); + auto external = external_requests.admit(); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); + const auto current = external.read("k", Retry::standard()); + (void)orThrow(external.replace("k", "E", current->etag, Retry::standard()), "external"); + backend->clearJournal(); + + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); + + ASSERT_TRUE(std::holds_alternative(result)); + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*backend, "k"), "WRW") << "refused on the cache, the resolve read, the write on it"; + EXPECT_EQ(clock.sleepCount(), 0u); + DB::Cas::tests::expectBytes(*backend, "k", "E,2"); +} + TEST(CASHotKeys, MalformedBytesRepairedExternallyRaiseNoCorruptionVerdict) { SyncClock clock; @@ -553,23 +711,29 @@ TEST(CASHotKeys, MalformedBytesRepairedExternallyRaiseNoCorruptionVerdict) }; ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), strict))); - auto current = external.read("k", Retry::standard()); - const Etag garbage = *orThrow(external.replace("k", "garbage", current->etag, Retry::standard()), "break"); - /// The lane's next hold starts from its cache, loses to the garbage, and remembers the garbage - /// its resolve read saw; the caller pauses and submits again. - WriteResult first = hot_keys.submit("k", op, Retry::standard(), strict); + /// A single-attempt hold reads, and the garbage lands between that read and its write: the write + /// loses, and the lane remembers the garbage its resolve read saw, as nobody retries that conflict. + std::optional garbage; + backend->onBeforeWrite("k", [&] + { + backend->onBeforeWrite("k", [] {}); + auto current = external.read("k", Retry::standard()); + garbage = *orThrow(external.replace("k", "garbage", current->etag, Retry::standard()), "break"); + }); + WriteResult first = hot_keys.submit("k", op, Retry::once(), strict); ASSERT_TRUE(std::holds_alternative(first)); - (void)orThrow(external.replace("k", "9", garbage, Retry::standard()), "repair"); + ASSERT_TRUE(garbage.has_value()); + (void)orThrow(external.replace("k", "9", *garbage, Retry::standard()), "repair"); const auto reread_before = counter(ProfileEvents::CASHotKeyCacheVerdictsReread); /// The verdict on the cached garbage is not delivered: one read, and the decide lands on the repair. WriteResult second = hot_keys.submit("k", op, Retry::standard(), strict); ASSERT_TRUE(std::holds_alternative(second)); EXPECT_EQ(counter(ProfileEvents::CASHotKeyCacheVerdictsReread) - reread_before, 1u); DB::Cas::tests::expectBytes(*backend, "k", "9,9"); - /// And when the read is garbage too, that is the real corruption. - current = external.read("k", Retry::standard()); + /// And when the read is garbage too, that is the real corruption: the hold loses on its cache and + /// decides again on a resolve read that is garbage. + const auto current = external.read("k", Retry::standard()); (void)orThrow(external.replace("k", "garbage", current->etag, Retry::standard()), "break again"); - (void)hot_keys.submit("k", op, Retry::standard(), strict); /// conflict: the cache now holds garbage DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::CORRUPTED_DATA, [&] { (void)hot_keys.submit("k", op, Retry::standard(), strict); }); } diff --git a/src/Disks/tests/gtest_cas_owner_stop.cpp b/src/Disks/tests/gtest_cas_owner_stop.cpp index a09e62b603bee..9b338ad82da04 100644 --- a/src/Disks/tests/gtest_cas_owner_stop.cpp +++ b/src/Disks/tests/gtest_cas_owner_stop.cpp @@ -1469,6 +1469,14 @@ ConflictPauseRun runConflictPause(const ConflictPauseArm & arm, PauseOwner who) return run; } +/// Decisions before the stopping pause: one per lost race, plus the first lost race, which is retried at once +/// without a pause, plus, for the catalog, the first decision on the lane's cached catalog, whose loss is retried at +/// once on its resolve read. +int decisionsBeforeStop(const ConflictPauseArm & arm) +{ + return (arm.slow ? 3 : 1) + 1 + (arm.loop == DecisionLoop::Catalog ? 1 : 0); +} + } /// A stop during the pause after a lost race ends the loop: no decision and no write after it. @@ -1477,7 +1485,7 @@ TEST_P(CASOwnerStopLoop, StopDuringConflictPauseSkipsNextDecision) const ConflictPauseArm arm = GetParam(); const ConflictPauseRun run = runConflictPause(arm, PauseOwner::Background); EXPECT_EQ(codeOf(run.error), ErrorCodes::ABORTED); - EXPECT_EQ(run.decisions_at_stop, arm.slow ? 3 : 1) << "one pause after each lost race"; + EXPECT_EQ(run.decisions_at_stop, decisionsBeforeStop(arm)) << "one pause after each lost race"; EXPECT_EQ(run.decisions, run.decisions_at_stop) << "no decision after the stop"; EXPECT_EQ(run.writes, run.writes_at_stop) << "no write after the stop"; } @@ -1491,7 +1499,7 @@ TEST_P(CASOwnerStopLoop, KilledQueryDecidesAgainAfterConflictPause) EXPECT_EQ(codeOf(run.error), 0) << messageOf(run.error); if (run.result) EXPECT_TRUE(std::holds_alternative(*run.result)); - EXPECT_EQ(run.decisions_at_stop, arm.slow ? 3 : 1) << "one pause after each lost race"; + EXPECT_EQ(run.decisions_at_stop, decisionsBeforeStop(arm)) << "one pause after each lost race"; EXPECT_EQ(run.decisions, run.decisions_at_stop + 1) << "one decision after the kill"; EXPECT_EQ(run.writes, run.writes_at_stop + 1) << "one write after the kill"; } @@ -1559,10 +1567,14 @@ enum class UnresolvedStop : uint8_t /// Another server admits the namespace during the redecide pause; the owner stops between the check /// before `decide` and the marker that `decide` then throws. DecisionMarkerWhileStopping, - /// The second decision's write is refused with 412, and the query is killed in the read that settles the refusal. + /// The second decision's write is refused with 412, and the query is killed in the first read after that refusal: + /// the next submission's base read, as a retried refusal is not settled. KillSettlingSecondWrite, - /// As `KillSettlingSecondWrite`, but every write after the lost one is refused and the kill comes in the read - /// that settles the last submission the cap allows. + /// As `KillSettlingSecondWrite`, but every write after the lost one is refused and the kill comes in the base read + /// of the last submission the cap allows. + KillReadingForLastAllowedWrite, + /// As `KillReadingForLastAllowedWrite`, but the kill comes in the read that settles the last allowed write: no + /// submission follows that write, so its refusal is settled. KillSettlingLastAllowedWrite, /// The second decision's write is refused as `READONLY` by the store while the owner stops, so the engine returns /// that refusal. @@ -1602,7 +1614,7 @@ UnresolvedCreateOutcome runUnresolvedCreate(std::optional stop_a } std::optional query; if (stop_at == UnresolvedStop::UnrecordedClientVerdict || stop_at == UnresolvedStop::KillSettlingSecondWrite - || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) + || stop_at == UnresolvedStop::KillReadingForLastAllowedWrite || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) query.emplace(getContext().context); BackendPtr backend = query ? BackendPtr(std::make_shared(inner)) : BackendPtr(inner); @@ -1704,9 +1716,11 @@ UnresolvedCreateOutcome runUnresolvedCreate(std::optional stop_a query->kill(); throw Poco::TimeoutException("ReadAfterWriteHookBackend: the settling read timed out"); } - if (stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) + if (stop_at == UnresolvedStop::KillReadingForLastAllowedWrite || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) { - if (inner->writesSinceArm() == kCasMaxDecisions) + const uint64_t kill_after_write + = stop_at == UnresolvedStop::KillSettlingLastAllowedWrite ? kCasMaxDecisions : kCasMaxDecisions - 1; + if (inner->writesSinceArm() == kill_after_write) { query->kill(); throw Poco::TimeoutException("ReadAfterWriteHookBackend: the settling read timed out"); @@ -1719,7 +1733,8 @@ UnresolvedCreateOutcome runUnresolvedCreate(std::optional stop_a auto op = requests.admit(); inner->arm(); inner->injectAmbiguousWrite(key); - if (stop_at == UnresolvedStop::KillSettlingSecondWrite || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) + if (stop_at == UnresolvedStop::KillSettlingSecondWrite || stop_at == UnresolvedStop::KillReadingForLastAllowedWrite + || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) inner->refuseNextWrite(key); if (stop_at == UnresolvedStop::RefusedSecondWriteWhileStopping) inner->onBeforeWrite(key, [&] @@ -1818,11 +1833,13 @@ TEST(CASOwnerStop, StoppedNamespaceCreateKeepsUnresolvedExit) } } -/// A refused write whose settling read fails after a kill does not answer the first write, whose outcome is still -/// unknown: the call keeps the unresolved exit and sends nothing more, also at the last submission the cap allows. +/// A refused write followed by a read that fails after a kill does not answer the first write, whose outcome is still +/// unknown: the call keeps the unresolved exit and sends nothing more, also in the last submission the cap allows, +/// whether the kill comes in that submission's read or in the read that settles its refused write. TEST(CASOwnerStop, ObservedStopConflictKeepsAnEarlierUnresolvedExit) { for (const auto & [stop_at, writes] : {std::pair{UnresolvedStop::KillSettlingSecondWrite, uint64_t{2}}, + std::pair{UnresolvedStop::KillReadingForLastAllowedWrite, uint64_t{kCasMaxDecisions - 1}}, std::pair{UnresolvedStop::KillSettlingLastAllowedWrite, uint64_t{kCasMaxDecisions}}}) { SCOPED_TRACE(writes); @@ -1859,8 +1876,9 @@ TEST(CASOwnerStop, LocalFaultAfterAnUnresolvedWriteIsNotReplaced) EXPECT_EQ(out.catalog_writes, 2u) << "the lost write and the failed one, nothing after"; } -/// A catalog update that lost a race to another server stops before its next submission starts when the -/// owner stops in the conflict pause. A lost fence the settling read observed stays the typed fence outcome. +/// A catalog update that lost two races to another server stops before its next submission starts when the owner +/// stops in the conflict pause after the second; the first is retried at once. A fence lost while the first write +/// is in flight stays the typed fence outcome. TEST(CASOwnerStop, ConflictedCatalogUpdateStopsAtTheNextSubmission) { for (const bool fence_lost_in_flight : {false, true}) @@ -1897,11 +1915,12 @@ TEST(CASOwnerStop, ConflictedCatalogUpdateStopsAtTheNextSubmission) int competitor_writes = 0; backend->onBeforeWrite(key, [&] { - if (competing || competitor_writes > 0) + if (competing || competitor_writes > 1) return; competing = true; CasRefCatalog::casAdmitEntry(competitor, layout, 1, - CatalogEntry{.ns = RootNamespace{"b"}, .state = NsState::Live, .incarnation = UInt128(2)}); + CatalogEntry{.ns = RootNamespace{competitor_writes == 0 ? "b" : "c"}, .state = NsState::Live, + .incarnation = UInt128(2 + competitor_writes)}); ++competitor_writes; competing = false; if (fence_lost_in_flight) @@ -1923,7 +1942,8 @@ TEST(CASOwnerStop, ConflictedCatalogUpdateStopsAtTheNextSubmission) { error = std::current_exception(); } - EXPECT_EQ(backend->writeCount(key) - writes_before, 2u) << "the competitor's write and one of the caller's"; + EXPECT_EQ(backend->writeCount(key) - writes_before, fence_lost_in_flight ? 2u : 4u) + << "each of the caller's writes and the competitor's write before it"; if (fence_lost_in_flight) { EXPECT_EQ(codeOf(error), 0) << messageOf(error); @@ -1938,7 +1958,7 @@ TEST(CASOwnerStop, ConflictedCatalogUpdateStopsAtTheNextSubmission) EXPECT_EQ(backend->getCount(key), reads_at_pause) << "no base read for a next submission"; } const auto snap = CasRefCatalog::read(competitor, layout); - ASSERT_EQ(snap.catalog.entries.size(), 2u); + ASSERT_EQ(snap.catalog.entries.size(), fence_lost_in_flight ? 2u : 3u); EXPECT_EQ(snap.catalog.entries.at(0).state, NsState::Live) << "the next submission never started"; }); } @@ -1951,13 +1971,13 @@ namespace class ReplacedBeforeFirstRemoveBackend final : public CountingBackend { public: - explicit ReplacedBeforeFirstRemoveBackend(String key_) : key(std::move(key_)) {} + explicit ReplacedBeforeFirstRemoveBackend(String key_, int replacements_ = 1) : key(std::move(key_)), replacements(replacements_) {} std::function on_replaced; RawRemoval remove(const String & k, const String & expected_value, TransportAccess & access) override { - if (k == key && !replaced.exchange(true)) + if (k == key && replaced.fetch_add(1) < replacements) { const auto current = InMemoryBackend::head(k, access); (void)InMemoryBackend::write(k, "replaced", current->value, access); @@ -1969,13 +1989,15 @@ class ReplacedBeforeFirstRemoveBackend final : public CountingBackend private: const String key; - std::atomic replaced{false}; + const int replacements; + std::atomic replaced{0}; }; } -/// A stop around the reissue pause of `removeCurrent` sends no second HEAD: before the pause the call -/// ends without sleeping, during the pause it ends before the HEAD. +/// A stop around the reissue pause of `removeCurrent` sends no further HEAD. A stop at the first mismatch ends the +/// call at the checks of its zero pause, without sleeping; a stop during the pause after the second mismatch ends it +/// before the third HEAD. TEST(CASOwnerStop, StopAroundRemoveReissuePauseSendsNoHead) { for (const bool during_sleep : {false, true}) @@ -1983,7 +2005,7 @@ TEST(CASOwnerStop, StopAroundRemoveReissuePauseSendsNoHead) SCOPED_TRACE(during_sleep ? "stop during the sleep" : "stop before the pause"); onThread(false, [&] { - auto backend = std::make_shared("k"); + auto backend = std::make_shared("k", /*replacements=*/2); std::atomic stop{false}; int sleeps = 0; CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) @@ -2008,8 +2030,8 @@ TEST(CASOwnerStop, StopAroundRemoveReissuePauseSendsNoHead) code = codeOf(std::current_exception()); } EXPECT_EQ(code, ErrorCodes::ABORTED); - EXPECT_EQ(backend->headCount("k"), 1u); - EXPECT_EQ(backend->deleteCount("k"), 1u); + EXPECT_EQ(backend->headCount("k"), during_sleep ? 2u : 1u); + EXPECT_EQ(backend->deleteCount("k"), during_sleep ? 2u : 1u); EXPECT_EQ(sleeps, during_sleep ? 1 : 0); }); } @@ -2750,8 +2772,9 @@ TEST(CASOwnerStop, ConflictThenStopUnderStandardRmwDecidesOnce) } } -/// A clean 412 whose settling read fails after the kill: a one-shot caller gets the `Conflict`, and a loop starts no -/// reread, decision or write after it. +/// A clean 412 followed by a read that fails after the kill. A one-shot caller settles the 412 with that read and gets +/// the `Conflict`. A loop does not settle it: the failed read is the one after its pause, which ends the call with the +/// read's error. Neither starts a decision or a write after it. TEST(CASOwnerStop, KilledQuerysConflictWithFailedSettlementEndsTheLoop) { for (const bool once : {true, false}) @@ -2796,14 +2819,22 @@ TEST(CASOwnerStop, KilledQuerysConflictWithFailedSettlementEndsTheLoop) writes = inner->writes.load(); reads = inner->reads.load(); }); - EXPECT_EQ(code, 0) << "the conflict is the answer, not the kill"; - ASSERT_TRUE(written.has_value()); - const auto * conflict = std::get_if(&*written); - ASSERT_NE(conflict, nullptr) << "index " << written->index(); - EXPECT_TRUE(std::holds_alternative(conflict->seen)); + if (once) + { + EXPECT_EQ(code, 0) << "the conflict is the answer, not the kill"; + ASSERT_TRUE(written.has_value()); + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "index " << written->index(); + EXPECT_TRUE(std::holds_alternative(conflict->seen)); + } + else + { + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED) << "the failed read after the pause ends the call with the kill"; + EXPECT_FALSE(written.has_value()); + } EXPECT_EQ(decisions, 1); EXPECT_EQ(writes, 1) << "the refused PUT only"; - EXPECT_EQ(reads, 2) << "the base read and the failed settling read, no reread"; + EXPECT_EQ(reads, 2) << "the base read and the one failed read after the refusal, not retried"; } } @@ -3038,7 +3069,84 @@ TEST(CASOwnerStop, SettledConflictAfterAFaultPermitsTheNextDecisionAfterAKill) EXPECT_EQ(pauses, 2); EXPECT_EQ(decisions, 2); EXPECT_EQ(writes, 3) << "the timed-out PUT, its refused resend, and the PUT of the next decision"; - EXPECT_EQ(reads, 3) << "the base read and two settling reads"; + EXPECT_EQ(reads, 4) << "the base read, two settling reads and the read after the conflict pause"; +} + +/// A clean 412 inside a retrying read-modify-write is not settled: the read after the pause replaces it. The first one +/// is retried at once; a query killed during the pause after the second is consulted when the read after that pause +/// fails, before it is retried, and nothing is written after. +TEST(CASOwnerStop, AKillDuringTheConflictPauseIsObservedByTheFailedReadAfterIt) +{ + std::optional written; + int code = 0; + int writes = 0; + int reads_after_write = 0; + int pauses = 0; + int pauses_at_first_read_after_write = -1; + bool settled_before_pause = false; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + inner->failure = nullptr; + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [&](uint64_t) + { + if (++pauses == 1) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + const auto created = competitor.create(STOPPABLE_KEY, "v0", Retry::once()); + ASSERT_TRUE(std::holds_alternative(created)); + const Etag base = std::get(created).etag; + inner->writes = 0; + bool competing = false; + int moves = 0; + Etag competitor_etag = base; + /// The competitor wins the first two races: the first loss is retried at once, the second one pauses. + inner->on_write = [&] + { + if (competing || moves >= 2) + return; + competing = true; + const auto moved = competitor.replace(STOPPABLE_KEY, "competitor" + std::to_string(moves), competitor_etag, Retry::once()); + ASSERT_TRUE(std::holds_alternative(moved)); + competitor_etag = std::get(moved).etag; + ++moves; + competing = false; + }; + inner->on_read = [&] + { + if (inner->writes.load() - moves >= 2 && pauses == 0) + settled_before_pause = true; + if (pauses == 0) + return; + if (++reads_after_write == 1) + pauses_at_first_read_after_write = pauses; + throw Poco::TimeoutException("FirstWriteFailsBackend: the read timed out"); + }; + auto op = requests.admit(); + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [&](const std::optional & current) + { + return std::optional(current->bytes + "+"); + }, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + /// The competitor's writes pass through the same backend. + writes = inner->writes.load() - moves; + }); + EXPECT_FALSE(written.has_value()) << "index " << (written ? written->index() : 0); + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED) << "the failed read ends the call with the kill"; + EXPECT_EQ(writes, 2) << "no write after the kill"; + EXPECT_FALSE(settled_before_pause) << "the second 412 was not settled before the pause"; + EXPECT_EQ(pauses_at_first_read_after_write, 1); + EXPECT_EQ(reads_after_write, 1) << "the stop is consulted after the failed read, which is not retried"; + EXPECT_EQ(pauses, 1); } /// A genuine refused precondition stays a conflict when the owner stops while its settling read is in diff --git a/src/Disks/tests/gtest_cas_ref_catalog.cpp b/src/Disks/tests/gtest_cas_ref_catalog.cpp index 1f2fb0146386f..259f803e4e7d7 100644 --- a/src/Disks/tests/gtest_cas_ref_catalog.cpp +++ b/src/Disks/tests/gtest_cas_ref_catalog.cpp @@ -190,6 +190,20 @@ String renderJournal(const std::vector & journal) return rendered; } +/// The next `count` writes of `key` are refused as lost races, with the store unchanged. The first lost race of a call +/// is retried at once, so a test that needs a pause refuses two. +void refuseNextWrites(InMemoryBackend & backend, const String & key, int count) +{ + auto left = std::make_shared(count); + backend.onBeforeWrite(key, [&backend, key, left] + { + if (*left == 0) + return; + --*left; + backend.refuseNextWrite(key); + }); +} + /// Lands a competing catalog body under the erase's own attempt and withdraws this actor's admission /// with it -- the concurrent winner an erase has to be resolved against, driven deterministically and /// without a second thread. @@ -1143,7 +1157,7 @@ TEST(CASRefCatalog, CasUpdateEndsAfterAHundredPacedSubmissions) }); }); EXPECT_EQ(backend->writes(layout.refCatalogKey()) - writes_before, 100u); - EXPECT_EQ(clock.sleeps.size(), 99u) << "every refusal but the last is paced"; + EXPECT_EQ(clock.sleeps.size(), 98u) << "every refusal but the first, retried at once, and the last is paced"; } TEST(CASRefCatalog, CasAdmitEntryAcceptsAnOrdinaryCreation) @@ -1484,14 +1498,14 @@ TEST(CASRefCatalogRemoval, AConflictingEraseBacksOffBeforeItsRetry) .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); - backend->refuseNextWrite(layout.refCatalogKey()); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); EXPECT_EQ(deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh), CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); - ASSERT_EQ(clock.sleeps.size(), 1u) << "one refusal, so exactly one paced retry"; - EXPECT_LE(clock.sleeps.front(), 200u) << "the first reissue's full-jitter ceiling"; - EXPECT_EQ(backend->writes(layout.refCatalogKey()), 3u) - << "the seed, the refused erase, and the retry that landed"; + ASSERT_EQ(clock.sleeps.size(), 1u) << "the first refusal is retried at once, the second after a pause"; + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps.front(), 2)) << "the pause after the second lost race"; + EXPECT_EQ(backend->writes(layout.refCatalogKey()), 4u) + << "the seed, the two refused erases, and the retry that landed"; } /// A writer that lands during every backoff must not starve the erase: the next erase write is @@ -1530,10 +1544,10 @@ TEST(CASRefCatalogRemoval, AWriterLandingDuringEveryBackoffCannotStarveTheErase) ++external_writes; }); - backend->refuseNextWrite(layout.refCatalogKey()); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); EXPECT_EQ(deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh), CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); - EXPECT_EQ(clock.sleeps.size(), 1u) << "one refusal, one pause, and the erase after it lands"; + EXPECT_EQ(clock.sleeps.size(), 1u) << "two refusals, the first retried at once, one pause, and the erase after it lands"; EXPECT_EQ(external_writes, 1u); const RefCatalog current = CasRefCatalog::read(op, layout).catalog; @@ -1554,12 +1568,12 @@ TEST(CASRefCatalogRemoval, AWriterLandingDuringEveryBackoffCannotStarveTheErase) seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); const uint64_t writes_after_seed = backend->writes(layout.refCatalogKey()); - backend->refuseNextWrite(layout.refCatalogKey()); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); EXPECT_EQ(deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh), CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); EXPECT_EQ(clock.sleeps.size(), 1u); - EXPECT_EQ(backend->writes(layout.refCatalogKey()) - writes_after_seed, 2u) - << "the refused erase and the erase after the pause"; + EXPECT_EQ(backend->writes(layout.refCatalogKey()) - writes_after_seed, 3u) + << "the two refused erases and the erase after the pause"; EXPECT_TRUE(CasRefCatalog::read(op, layout).catalog.entries.empty()); } } @@ -1595,7 +1609,7 @@ TEST(CASRefCatalogRemoval, AConflictedEraseSendsTheNextWriteFromAReadTakenAfterT const CasRefCatalog::Snapshot snapshot = CasRefCatalog::read(op, layout); const size_t journal_before = backend->journalFor(layout.refCatalogKey()).size(); - backend->refuseNextWrite(layout.refCatalogKey()); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); EXPECT_EQ(CasRefCatalog::deleteCompletedRemovingAtSnapshot( op, layout, snapshot, removing, ready_parent, noAuthorityRefresh, noRetirementRecord, noRetirementRecord).outcome, @@ -1616,10 +1630,76 @@ TEST(CASRefCatalogRemoval, AConflictedEraseSendsTheNextWriteFromAReadTakenAfterT << "and the next erase write comes from that read: " << renderJournal(journal_since); } +/// The authority refresh before a retried erase runs right after the pause (none after the first refusal), before the +/// catalog read the erase is conditioned on, so no request of its own sits between that read and the erase. +TEST(CASRefCatalogRemoval, TheAuthorityRefreshBeforeARetriedEraseComesBeforeItsCatalogRead) +{ + auto backend = std::make_shared(); + DB::Cas::tests::FakeClock clock; + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + requests.setNowFnForTest(clock.nowFn()); + const Layout layout("erase-refresh-before-read"); + std::vector journal_sizes_at_pause; + std::vector journal_sizes_at_refresh; + String timeline; + auto pause = clock.sleepFn(); + requests.setSleepFnForTest([&](uint64_t ms) + { + pause(ms); + timeline += 'P'; + journal_sizes_at_pause.push_back(backend->journalFor(layout.refCatalogKey()).size()); + }); + CasOperation op = requests.admit(); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, + .state = NsState::Removing, + .incarnation = UInt128{7}, + .removal_started_round = 13}; + seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + + const CasRefCatalog::Snapshot snapshot = CasRefCatalog::read(op, layout); + const size_t journal_before = backend->journalFor(layout.refCatalogKey()).size(); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); + + EXPECT_EQ(CasRefCatalog::deleteCompletedRemovingAtSnapshot( + op, layout, snapshot, removing, ready_parent, + [&] + { + timeline += 'F'; + journal_sizes_at_refresh.push_back(backend->journalFor(layout.refCatalogKey()).size()); + }, + noRetirementRecord, noRetirementRecord).outcome, + CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); + + EXPECT_EQ(timeline, "FFPF") + << "a refresh before the first erase, one before the second, retried at once, and one after the pause before the third"; + ASSERT_EQ(journal_sizes_at_pause.size(), 1u); + ASSERT_EQ(journal_sizes_at_refresh.size(), 3u) << "one refresh per attempt"; + EXPECT_EQ(journal_sizes_at_refresh.front(), journal_before) << "before the first erase"; + EXPECT_EQ(journal_sizes_at_refresh.back(), journal_sizes_at_pause.front()) + << "the second refresh follows the pause with no catalog request between them"; + const std::vector journal = backend->journalFor(layout.refCatalogKey()); + const size_t refreshed_at = journal_sizes_at_refresh.back(); + ASSERT_EQ(journal.size(), refreshed_at + 3) << renderJournal(journal); + using Verb = WriteCountingBackend::Verb; + /// The retry after the first refusal is not paced, and its refresh still comes right before its catalog read. + const size_t first_retry_refreshed_at = journal_sizes_at_refresh[1]; + ASSERT_LT(first_retry_refreshed_at + 1, journal.size()) << renderJournal(journal); + EXPECT_EQ(journal[first_retry_refreshed_at], Verb::Read) << "the first retry's catalog read: " << renderJournal(journal); + EXPECT_EQ(journal[first_retry_refreshed_at + 1], Verb::Write) << "and the erase on it: " << renderJournal(journal); + EXPECT_EQ(journal[refreshed_at], Verb::Read) << "the catalog read after the refresh: " << renderJournal(journal); + EXPECT_EQ(journal[refreshed_at + 1], Verb::Write) << "the erase on it: " << renderJournal(journal); + EXPECT_EQ(journal[refreshed_at + 2], Verb::Read) << "the read that resolves the erase: " << renderJournal(journal); +} + /// A caller's liveness need not be a fact this loop can read. The GC drain's is a cached /// leader-authority flag its owner refreshes by re-reading `gc/state`, so a leader deposed while an /// erase is in flight leaves that flag stale -- and on an unrecoverable delete path one reading taken -/// before the first erase must not authorise the rest. Hence the refresh hook, run at the top of every +/// before the first erase must not authorise the rest. Hence the refresh hook, run before every /// attempt. /// /// The winner here writes the SAME row back: the incarnation moves, so the erase is refused, and the @@ -1702,12 +1782,12 @@ TEST(CASRefCatalogRemoval, NonFenceAuthorityExceptionPropagatesBeforeEraseCas) << "nothing changed under an authority failure that reached no attempt"; } -/// The counterpart to the case above: the hook fails AFTER the loop has already sent one erase and -/// resolved it (a refusal, so the row is provably unchanged), on the refresh that would gate the next +/// The counterpart to the case above: the hook fails AFTER the loop has already sent one erase and the +/// store refused it (so the row is provably unchanged), on the refresh that would gate the next /// attempt. The failure must still escape rather than be read as the fenced-out liveness answer this /// class's default `admitted()` would otherwise report, and -- exactly as when it fails up front -- no /// further erase may reach the store on an authority this call could not evaluate. -TEST(CASRefCatalogRemoval, NonFenceAuthorityExceptionPropagatesAfterEraseResolution) +TEST(CASRefCatalogRemoval, NonFenceAuthorityExceptionPropagatesAfterARefusedErase) { auto backend = std::make_shared(); DB::Cas::tests::FakeClock clock; @@ -1736,7 +1816,7 @@ TEST(CASRefCatalogRemoval, NonFenceAuthorityExceptionPropagatesAfterEraseResolut { ++refreshes; if (refreshes > 1) - throw std::runtime_error("injected authority-refresh failure after the erase resolved"); + throw std::runtime_error("injected authority-refresh failure after the erase was refused"); }), std::runtime_error); EXPECT_EQ(refreshes, 2u) << "once before the refused attempt, once before the retry it never sent"; @@ -1911,7 +1991,9 @@ TEST(CASRefCatalogRemoval, PerpetualConflictGivesUpAfterAHundredErases) } EXPECT_NE(message.find("did not converge after 100 attempts"), String::npos) << message; EXPECT_EQ(backend->refusedAttempts(), 100u); - EXPECT_EQ(clock.sleeps.size() - sleeps_before, 99u) << "no pause after the last refusal"; + EXPECT_EQ(clock.sleeps.size() - sleeps_before, 98u) << "no pause after the first refusal, retried at once, nor the last"; + for (size_t i = sleeps_before; i < clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[i], static_cast(i - sleeps_before + 2))); EXPECT_EQ(CasRefCatalog::read(op, layout).catalog.entries, std::vector{removing}); } @@ -2016,7 +2098,8 @@ TEST(CASRefCatalogRemoval, StopDuringAConflictedErasesResolutionStartsNoNextDeci const Layout layout("erase-conflict-stop"); const CatalogEntry removing = removingEntryForStopTests(); seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); - backend->refuseNextWrite(layout.refCatalogKey()); + /// The first refusal is retried at once; the second pauses. + refuseNextWrites(*backend, layout.refCatalogKey(), 2); size_t refreshes = 0; { @@ -2031,8 +2114,8 @@ TEST(CASRefCatalogRemoval, StopDuringAConflictedErasesResolutionStartsNoNextDeci }); } ASSERT_TRUE(stopped) << "premise: the erase conflicted and paused"; - EXPECT_EQ(refreshes, 1u) << "a refresh for a second decision"; - EXPECT_EQ(backend->writes(layout.refCatalogKey()), 2u) << "the seed and the conflicted erase"; + EXPECT_EQ(refreshes, 2u) << "one for each erase sent, none for a third decision"; + EXPECT_EQ(backend->writes(layout.refCatalogKey()), 3u) << "the seed and the two conflicted erases"; EXPECT_EQ(CasRefCatalog::read(op, layout).catalog.entries, std::vector{removing}); } @@ -3261,12 +3344,6 @@ TEST(CASRefCatalog, TheCatalogLoopPacesAConflictByWhetherItSettledAFault) /// are still on the catalog when the second starts, and re-admitting the same namespace would /// duplicate it rather than race it. constexpr int K = 3; - /// The settled-fault scenario draws 8, not 3: an upper-bound-only check on `backoff`'s draws - /// cannot tell the growing schedule from the flat one (both stay under 200 ms plenty often at - /// small K), so that scenario also needs a floor. With `backoff(attempt) = uniform(0, min(5000, - /// 200 << (attempt-1)))`, the flat schedule can NEVER draw over 200 ms, so a single draw over - /// 200 ms is proof by itself that the schedule grew; drawing 8 times keeps the growing schedule's - /// own chance of missing that floor purely by bad luck around 2^-28. constexpr int K2 = 8; int moved = 0; int limit = K; @@ -3293,15 +3370,14 @@ TEST(CASRefCatalog, TheCatalogLoopPacesAConflictByWhetherItSettledAFault) if (e.ns.string() == "a") { e.state = NsState::Removing; e.removal_started_round = 1; } return next; }); - ASSERT_EQ(f.clock.sleeps.size(), static_cast(K)); - for (uint64_t s : f.clock.sleeps) - EXPECT_LE(s, 200u); + /// The first loss is on the lane's cached catalog and is retried at once, without counting; the first counted loss + /// is retried at once too, so only the later ones pause. + ASSERT_EQ(f.clock.sleeps.size(), static_cast(K - 2)); + for (size_t i = 0; i < f.clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(f.clock.sleeps[i], static_cast(i + 2))); EXPECT_EQ(eventCount(ProfileEvents::CASRequestConflictPause) - pauses_before, 0u) << "the lane's caller pauses itself; the engine's counter is for its own loops"; - /// K2 conflicts that each settled a fault: the growing schedule, on the loop's own count. An - /// upper-bound check alone is satisfied by the flat schedule too (its draws are a subset of the - /// growing schedule's early-attempt range), so this also asserts a floor: at least one draw over - /// 200 ms, which the flat schedule can never produce. + /// K2 conflicts that each settled a fault: the fault schedule, on the loop's own count of them. f.clock.sleeps.clear(); moved = 0; limit = K2; @@ -3311,10 +3387,304 @@ TEST(CASRefCatalog, TheCatalogLoopPacesAConflictByWhetherItSettledAFault) CasRefCatalog::casUpdate(pool_op, layout, [](const RefCatalog & cur) { return cur; }); ASSERT_EQ(f.clock.sleeps.size(), static_cast(K2)); for (size_t i = 0; i < f.clock.sleeps.size(); ++i) - EXPECT_LE(f.clock.sleeps[i], std::min(5000, 200ull << i)); - EXPECT_TRUE(std::any_of(f.clock.sleeps.begin(), f.clock.sleeps.end(), [](uint64_t s) { return s > 200u; })) - << "the flat schedule can never draw over 200 ms; a growing schedule almost certainly does " - "somewhere in 8 draws, so this is what tells the two schedules apart"; + EXPECT_LE(f.clock.sleeps[i], std::min(5000, 200ull << i)) << "fault pause " << i + 1; + /// Every clean pause lies in its own step's range. A full-jitter draw lands in that range with probability at + /// most 1/10 at each of these steps, so all 8 do with probability below 1e-9. + size_t outside_clean = 0; + for (size_t i = 0; i < f.clock.sleeps.size(); ++i) + outside_clean += DB::Cas::tests::isConflictPause(f.clock.sleeps[i], static_cast(i + 1)) ? 0 : 1; + EXPECT_GT(outside_clean, 0u) << "a fault paced by the clean schedule"; +} + +namespace +{ + +/// Another server's catalog writer that commits on demand. Its requests are bracketed by marks, so +/// `renderOwnRequests` shows only the pool's own requests. +struct CatalogRival +{ + PoolAndExternal & f; + Layout layout; + CasOperation op; + uint64_t commits = 0; + bool inside = false; + + void commit() + { + inside = true; + f.backend->mark("rival{"); + CasRefCatalog::casAdmitEntry(op, layout, 1, liveEntry(fmt::format("r{:03}", commits), 1000 + commits)); + f.backend->mark("}rival"); + ++commits; + inside = false; + } +}; + +RefCatalog markARemoving(const RefCatalog & cur) +{ + RefCatalog next = cur; + for (auto & e : next.entries) + if (e.ns.string() == "a") + { + e.state = NsState::Removing; + e.removal_started_round = 1; + } + return next; +} + +} + +/// The rival lands right before the pool's first three writes and during every pause. The first loss is on the lane's +/// cached catalog and is retried at once on the resolve read; the second, the first on a fresh read, is retried at once +/// too; the third is paced; the write after the pause is decided on a read taken after it, so it lands. +TEST(CASRefCatalog, ACatalogUpdateIsNotStarvedByAWriterThatCommitsDuringEveryPause) +{ + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation pool_op = f.pool.admit(); + CasRefCatalog::initializeEmptyForNewPool(pool_op, layout); + CasRefCatalog::casAdmitEntry(pool_op, layout, 1, liveEntry("a", 1)); /// the lane caches the catalog + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + int collisions = 0; + f.backend->onBeforeWrite(key, [&] + { + if (rival.inside || collisions >= 3) + return; + ++collisions; + rival.commit(); + }); + auto sleep = f.clock.sleepFn(); + f.pool.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + f.backend->mark("pause"); + rival.commit(); + }); + f.backend->clearJournal(); + + int decided = 0; + CasRefCatalog::casUpdate(pool_op, layout, [&](const RefCatalog & cur) { ++decided; return markARemoving(cur); }); + + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*f.backend, key), "WRWRWPRW") + << "cached write refused, resolve read, write refused, read, write refused, pause, read, the write on it"; + EXPECT_EQ(decided, 4); + EXPECT_EQ(f.clock.sleeps.size(), 1u); + EXPECT_EQ(rival.commits, 4u); + const RefCatalog landed = CasRefCatalog::read(pool_op, layout).catalog; + ASSERT_EQ(landed.entries.size(), 5u); + EXPECT_EQ(landed.entries.front().state, NsState::Removing); +} + +/// A rival that lands right before every write still ends the loop on the submission cap, with a +/// pause between submissions and every write after a pause decided on a read taken after it. +TEST(CASRefCatalog, ACatalogUpdateAgainstAWriterBeforeEveryWriteEndsOnTheCount) +{ + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation pool_op = f.pool.admit(); + CasRefCatalog::initializeEmptyForNewPool(pool_op, layout); + CasRefCatalog::casAdmitEntry(pool_op, layout, 1, liveEntry("a", 1)); /// the lane caches the catalog + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + f.backend->onBeforeWrite(key, [&] + { + if (!rival.inside) + rival.commit(); + }); + auto sleep = f.clock.sleepFn(); + f.pool.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + f.backend->mark("pause"); + }); + f.backend->clearJournal(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 submissions", [&] + { + CasRefCatalog::casUpdate(pool_op, layout, markARemoving); + }); + + EXPECT_EQ(f.clock.sleeps.size(), kCasMaxDecisions - 2) << "no pause after the first lost race, nor the last"; + for (size_t i = 0; i < f.clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(f.clock.sleeps[i], static_cast(i + 2))); + /// The loss on the cached catalog is settled and retried at once. A loss on a fresh read is not settled when a + /// read follows it, at once after the first and after a pause from the second; the last submission's loss, which + /// nothing follows, is. + String expected = "WRW" "RW"; + for (uint32_t i = 2; i < kCasMaxDecisions - 1; ++i) + expected += "PRW"; + expected += "PRWR"; + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*f.backend, key), expected); +} + +/// A conflict that settled a transport fault ends the run of clean losses, in the catalog update and in the erase loop: +/// the clean loss after it starts a new run and is retried at once, so only the fault-settled conflict pauses. +TEST(CASRefCatalog, AFaultSettledConflictRestartsTheCleanLossCount) +{ + { + SCOPED_TRACE("catalog update"); + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation setup = f.external.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + CasRefCatalog::casAdmitEntry(setup, layout, 1, liveEntry("a", 1)); + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + int moves = 0; + f.backend->onBeforeWrite(key, [&] + { + if (rival.inside || moves >= 3) + return; + ++moves; + rival.commit(); + if (moves == 2) + f.backend->injectAmbiguousWrite(key); + }); + CasOperation pool_op = f.pool.admit(); + CasRefCatalog::casUpdate(pool_op, layout, markARemoving); + EXPECT_EQ(moves, 3) << "premise: clean, fault-settled, clean"; + EXPECT_EQ(f.clock.sleeps.size(), 1u); + } + { + SCOPED_TRACE("catalog erase"); + auto backend = std::make_shared(); + DB::Cas::tests::FakeClock clock; + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + requests.setNowFnForTest(clock.nowFn()); + requests.setSleepFnForTest(clock.sleepFn()); + CasOperation op = requests.admit(); + CasOperation writer = requests.admit(); + const Layout layout("erase-fault-between"); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, + .state = NsState::Removing, + .incarnation = UInt128{7}, + .removal_started_round = 13}; + seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + int moves = 0; + bool inside = false; + backend->onBeforeWrite(layout.refCatalogKey(), [&] + { + if (inside || moves >= 3) + return; + inside = true; + ++moves; + CasRefCatalog::casAdmitEntry(writer, layout, 1, liveEntry(fmt::format("w{}", moves), 100 + moves)); + if (moves == 2) + backend->injectAmbiguousWrite(layout.refCatalogKey()); + inside = false; + }); + EXPECT_EQ(deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh), + CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); + EXPECT_EQ(moves, 3) << "premise: clean, fault-settled, clean"; + EXPECT_EQ(clock.sleeps.size(), 1u); + } +} + +/// The catalog disappears between the last submission's read and its write. That write's refusal is settled, +/// as no submission follows it, so the caller that takes absence as an answer gets it rather than the count. +TEST(CASRefCatalog, AnAbsenceAtTheLastSubmissionIsReportedNotTheCount) +{ + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation setup = f.external.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + const CatalogEntry creating{ + .ns = RootNamespace{"a"}, + .state = NsState::Creating, + .incarnation = UInt128{5}, + .creator = CreatorFence{.server_root_id = "gone", .writer_epoch = 1, .fence_generation = 1}}; + CasRefCatalog::casAdmitEntry(setup, layout, 1, creating); + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + CasOperation remover = f.external.admit(); + uint32_t pool_writes = 0; + bool removing = false; + f.backend->onBeforeWrite(key, [&] + { + if (rival.inside || removing) + return; + if (++pool_writes < kCasMaxDecisions) + { + rival.commit(); + return; + } + removing = true; + ASSERT_EQ(remover.removeCurrent(key, Retry::standard()), Removal::Removed); + removing = false; + }); + + CasOperation pool_op = f.pool.admit(); + bool absent = false; + const auto outcome = CasRefCatalog::cancelStalledCreating(pool_op, layout, creating, + [](const CreatorFence &) { return true; }, [](const Retry &) {}, Retry::standard(), &absent); + + EXPECT_EQ(outcome, CasRefCatalog::StalledCreatingCancelOutcome::EntryChanged); + EXPECT_TRUE(absent); + EXPECT_EQ(pool_writes, kCasMaxDecisions); +} + +/// While the caller pauses after a lost race (its second on a fresh read: the first is retried at once), another +/// holder in the same pool commits and the lane caches that commit, then another server moves the catalog on. The submission after the pause reads instead of +/// starting from that cached body, which is older than the pause's end. +TEST(CASRefCatalog, ASubmissionAfterAPauseReadsInsteadOfStartingFromTheCache) +{ + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation pool_op = f.pool.admit(); + CasOperation neighbour = f.pool.admit(); + CasRefCatalog::initializeEmptyForNewPool(pool_op, layout); + CasRefCatalog::casAdmitEntry(pool_op, layout, 1, liveEntry("a", 1)); + CasRefCatalog::casAdmitEntry(pool_op, layout, 1, liveEntry("n", 2)); + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + bool in_pause = false; + int collisions = 0; + f.backend->onBeforeWrite(key, [&] + { + if (rival.inside || in_pause || collisions >= 3) + return; + ++collisions; + rival.commit(); + }); + auto sleep = f.clock.sleepFn(); + f.pool.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + f.backend->mark("pause"); + in_pause = true; + f.backend->mark("rival{"); + CasRefCatalog::casUpdate(neighbour, layout, [](const RefCatalog & cur) + { + RefCatalog next = cur; + for (auto & e : next.entries) + if (e.ns.string() == "n") + { + e.state = NsState::Removing; + e.removal_started_round = 2; + } + return next; + }); + f.backend->mark("}rival"); + rival.commit(); + in_pause = false; + }); + f.backend->clearJournal(); + + CasRefCatalog::casUpdate(pool_op, layout, markARemoving); + + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*f.backend, key), "WRWRWPRW") + << "after the pause: a read, then the write on it, not a write on the neighbour's cached commit"; + EXPECT_EQ(f.clock.sleeps.size(), 1u); + const RefCatalog landed = CasRefCatalog::read(pool_op, layout).catalog; + for (const auto & e : landed.entries) + if (e.ns.string() == "a" || e.ns.string() == "n") + EXPECT_EQ(e.state, NsState::Removing) << e.ns.string(); } TEST(CASRefCatalog, TheGCEraseRacesTheLaneAsItRacesEverything) diff --git a/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp b/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp index b7eeba9ea65a6..1ce327a243be6 100644 --- a/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp +++ b/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp @@ -715,16 +715,89 @@ class ChurningCatalogBackend final : public InMemoryBackend } +namespace +{ + +/// After this server's own birth of `ns` lands, rewrites the catalog under three successive reads: the confirming read +/// sees a foreign `Creating` row, the reconciliation's read sees that row moved on, and the next read sees it `Live`. +class ReplacedAfterBirthBackend final : public InMemoryBackend +{ +public: + ReplacedAfterBirthBackend(String catalog_key_, RootNamespace ns_) + : catalog_key(std::move(catalog_key_)), ns(std::move(ns_)) + { + } + + int stage = 0; + + std::optional read(const String & key, DB::Cas::TransportAccess & access) override + { + if (key == catalog_key && stage < 3) + rewrite(access); + return InMemoryBackend::read(key, access); + } + +private: + void rewrite(DB::Cas::TransportAccess & access) + { + const std::optional got = InMemoryBackend::read(catalog_key, access); + if (!got) + return; + RefCatalog catalog = decodeRefCatalog(got->bytes); + for (CatalogEntry & entry : catalog.entries) + { + if (entry.ns != ns) + continue; + if (stage == 0 && entry.state == NsState::Live) + { + entry.state = NsState::Creating; + entry.creator = CreatorFence{.server_root_id = "foreign-creator", .writer_epoch = 7, .fence_generation = 1}; + } + else if (stage == 1) + ++entry.creator->fence_generation; + else if (stage == 2) + { + entry.state = NsState::Live; + entry.creator.reset(); + } + else + return; + ++stage; + (void)InMemoryBackend::write(catalog_key, encodeRefCatalog(catalog), got->value, access); + return; + } + } + + const String catalog_key; + const RootNamespace ns; +}; + +} + +/// A birth that lands and is then replaced before its confirming read is followed by one collision, the first of this +/// call, so it is retried at once, whatever round it falls in. +TEST(CASRefCatalogBirthWiring, TheFirstCollisionAfterAConfirmedBirthIsRetriedAtOnce) +{ + const RootNamespace ns{"replaced_after_birth"}; + auto backend = std::make_shared(Layout{"p"}.refCatalogKey(), ns); + auto store = openPoolForBirthTest(backend); + std::vector pauses; + store->setCasRetrySleepForTest([&](uint64_t ms) { pauses.push_back(ms); }); + + (void)store->namespaceLife(ns); + + EXPECT_EQ(backend->stage, 3) << "premise: the row was replaced, moved on and completed"; + EXPECT_TRUE(pauses.empty()) << "a pause of " << (pauses.empty() ? 0 : pauses.front()) << " ms after the first collision"; +} + /// A catalog entry that moves under every read drives `resolveNamespaceLife`'s state machine for ever. -/// Every re-read a competing actor forces is paced, and the loop ends after its 32 rounds. The pause -/// before the last round carries the clock past a whole window, so the last round is sent only if each -/// of its requests binds its own window. +/// Every re-read a competing actor forces is paced by the count of collisions, the first collision is retried at once, +/// the last is not paced because no re-read follows it, and the loop ends after its 32 rounds. The pause before the last +/// round carries the clock past a whole window, so the last round is sent only if each of its requests +/// binds its own window. TEST(CASRefCatalogBirthWiring, APerpetuallyChurningCatalogEntryIsPacedAndEndsAfterItsRounds) { constexpr size_t kRounds = 32; - /// One attempt's reservation on a disk with default settings, and the longest `Retry::backoff` draw. - constexpr uint64_t kEnvelopeMs = 7'000; - constexpr uint64_t kMaxBackoffMs = 5'000; auto backend = std::make_shared(Layout{"p"}.refCatalogKey()); CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); @@ -743,13 +816,15 @@ TEST(CASRefCatalogBirthWiring, APerpetuallyChurningCatalogEntryIsPacedAndEndsAft auto now_ms = std::make_shared(0); size_t pauses = 0; + std::vector pause_ms; std::optional last_round_started_ms; size_t reads_before_last_round = 0; store->setCasRequestNowFnForTest([now_ms] { return *now_ms; }); store->setCasRetrySleepForTest([&, now_ms](uint64_t ms) { *now_ms += ms; - if (++pauses == kRounds - 1) + pause_ms.push_back(ms); + if (++pauses == kRounds - 2) { *now_ms += DB::Cas::kDefaultRequestWindowMs; last_round_started_ms = *now_ms; @@ -761,8 +836,10 @@ TEST(CASRefCatalogBirthWiring, APerpetuallyChurningCatalogEntryIsPacedAndEndsAft expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, fmt::format("after {} attempts", kRounds), [&] { store->namespaceLife(ns); }); - EXPECT_GE(pauses, kRounds - 1) << "each re-read a lost round forced is paced"; + EXPECT_EQ(pauses, kRounds - 2) << "each re-read a lost round forced is paced, but the first and the last round are not"; + for (size_t i = 0; i < pause_ms.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(pause_ms[i], static_cast(i + 2))); ASSERT_TRUE(last_round_started_ms.has_value()); EXPECT_EQ(backend->churned_reads - reads_before_last_round, 2u) << "the last round's loop read and its decision read"; - EXPECT_LE(*now_ms - *last_round_started_ms, kEnvelopeMs + kMaxBackoffMs); + EXPECT_EQ(*now_ms, *last_round_started_ms) << "no pause after the last round"; } diff --git a/src/Disks/tests/gtest_cas_requests.cpp b/src/Disks/tests/gtest_cas_requests.cpp index f4cc31db774e3..f8f25a6529eb5 100644 --- a/src/Disks/tests/gtest_cas_requests.cpp +++ b/src/Disks/tests/gtest_cas_requests.cpp @@ -13,6 +13,7 @@ #include #include "cas_test_helpers.h" #include +#include #include #include @@ -115,8 +116,36 @@ TEST(CASIncarnation, GrammarRefusesTheNineWays) EXPECT_FALSE(isIncarnationValue(Dialect::Emulated, "")); } +TEST(CASRetry, TheConflictPauseGrowsToItsCeilingWithUpToAQuarterOfJitter) +{ + thread_local_rng.seed(2026); /// a fixed sequence, so the spread checks below cannot fail on an unlucky draw + EXPECT_EQ(Retry::conflictBackoff(1), 0u) << "the first loss is retried at once"; + const std::vector bases{0, 40, 80, 120, 160, 400, 720, 750, 750, 750}; + const std::vector losses{1, 2, 3, 4, 5, 11, 19, 20, 21, 100}; + for (size_t step = 1; step < losses.size(); ++step) + { + const uint32_t loss = losses[step]; + const uint64_t base = bases[step]; + uint64_t low = std::numeric_limits::max(); + uint64_t high = 0; + for (int i = 0; i < 1000; ++i) + { + const uint64_t pause = Retry::conflictBackoff(loss); + ASSERT_GE(pause, base) << "loss " << loss; + ASSERT_LE(pause, base + base / 4) << "loss " << loss; + low = std::min(low, pause); + high = std::max(high, pause); + } + /// The bounds alone cannot tell jitter from a constant, so the spread is asserted too. + EXPECT_LT(low, base + base / 16) << "loss " << loss; + EXPECT_GT(high, base + base * 3 / 16) << "loss " << loss; + } + EXPECT_LE(Retry::conflictBackoff(std::numeric_limits::max()), 750u + 750u / 4) << "the ceiling holds for any count"; +} + TEST(CASRetry, BackoffIsFullJitterUnderTheCap) { + thread_local_rng.seed(2026); /// a fixed sequence, so the spread checks below cannot fail on an unlucky draw for (uint32_t attempt = 1; attempt <= 12; ++attempt) { const uint64_t ceiling = std::min(5000, 200ull << (attempt - 1)); @@ -481,7 +510,7 @@ TEST(CASRequests, PauseBeforeRedecideEndingOnTheExplicitLeaseEndsTheCall) namespace { -/// One lost race, then a pause that sleeps 10 s past what it asked for. `policy_ending_at` builds the +/// Two lost races, the first retried at once, then a pause that sleeps 10 s past what it asked for. `policy_ending_at` builds the /// policy from the instant the room for one write and one conflict pause ends. Returns the result and /// how many times `decide` ran. std::pair raceThenOversleep(const std::function & policy_ending_at) @@ -492,13 +521,20 @@ std::pair raceThenOversleep(const std::functiononBeforeWrite("k", [&] { - if (staged) + if (staging || staged >= 2) return; - staged = true; - orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + staging = true; + if (const auto current = rival.read("k", Retry::once())) + orThrow(rival.replace("k", "theirs again", current->etag, Retry::once()), "rival"); + else + orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + ++staged; + staging = false; }); int decisions = 0; @@ -519,7 +555,7 @@ std::pair raceThenOversleep(const std::function(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); @@ -529,7 +565,7 @@ TEST(CASRequests, ReadModifyWriteWakingPastTheOutsideCapRunsNoSecondDecide) TEST(CASRequests, ReadModifyWriteWakingPastTheExplicitLeaseRunsNoSecondDecide) { const auto [result, decisions] = raceThenOversleep([](uint64_t end) { return Retry::untilLeaseSafe(end, /*margin=*/0); }); - EXPECT_EQ(decisions, 1); + EXPECT_EQ(decisions, 2); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); @@ -1341,7 +1377,7 @@ TEST(CASRequests, OnPresenceSettlesARefusedPreconditionWithAHead) ASSERT_TRUE(std::holds_alternative(result)); /// A refused precondition needs only to know WHAT is at the key, so this loop never fetches a body. EXPECT_EQ(backend->getTotal(), 0u); - EXPECT_EQ(backend->headTotal(), 2u); + EXPECT_EQ(backend->headTotal(), 2u) << "the base and the read after the pause; the refusal itself is not settled"; EXPECT_EQ(backend->writeTotal(), 2u); } @@ -1388,11 +1424,11 @@ TEST(CASRequests, RemoveCurrentReObservesAMismatchAndRefusesUnderOnce) orThrow(op.create("k", "v", Retry::standard()), "create"); EXPECT_EQ(op.removeCurrent("k", Retry::standard()), Removal::Removed); - /// Another incarnation became current between the observation and the delete: observe again, - /// paced like every other reissue, and delete what the second look saw. + /// Another incarnation became current between the observation and the delete: a lost race, the first of + /// the call, so it observes again at once and deletes what the second look saw. EXPECT_EQ(backend->heads, 2u); EXPECT_EQ(backend->removes, 2u); - EXPECT_EQ(clock.sleeps.size(), 1u); + EXPECT_TRUE(clock.sleeps.empty()); } { FakeClock clock; @@ -1790,13 +1826,20 @@ TEST(CASRequests, AFenceLostDuringThePauseRunsNoSecondDecide) lost = true; }); - bool staged = false; + /// The rival wins the first two races: the first is retried at once, the second pauses. + int staged = 0; + bool staging = false; backend->onBeforeWrite("k", [&] { - if (staged) + if (staging || staged >= 2) return; - staged = true; - orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + staging = true; + if (const auto current = rival.read("k", Retry::once())) + orThrow(rival.replace("k", "theirs again", current->etag, Retry::once()), "rival"); + else + orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + ++staged; + staging = false; }); int decisions = 0; @@ -1809,8 +1852,8 @@ TEST(CASRequests, AFenceLostDuringThePauseRunsNoSecondDecide) }, Retry::standard()); - /// The conflict was informative, so the loop would decide again; the fence moved in the pause. - EXPECT_EQ(decisions, 1); + /// The conflicts were informative, so the loop would decide again; the fence moved in the pause after the second. + EXPECT_EQ(decisions, 2); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); @@ -1834,13 +1877,20 @@ TEST(CASRequests, AFenceLostDuringThePauseRunsNoSecondDecideOnPresence) lost = true; }); - bool staged = false; + /// The rival wins the first two races: the first is retried at once, the second pauses. + int staged = 0; + bool staging = false; backend->onBeforeWrite("k", [&] { - if (staged) + if (staging || staged >= 2) return; - staged = true; - orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + staging = true; + if (const auto current = rival.read("k", Retry::once())) + orThrow(rival.replace("k", "theirs again", current->etag, Retry::once()), "rival"); + else + orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + ++staged; + staging = false; }); int decisions = 0; @@ -1853,8 +1903,8 @@ TEST(CASRequests, AFenceLostDuringThePauseRunsNoSecondDecideOnPresence) }, Retry::standard()); - /// The conflict was informative, so the loop would decide again; the fence moved in the pause. - EXPECT_EQ(decisions, 1); + /// The conflicts were informative, so the loop would decide again; the fence moved in the pause after the second. + EXPECT_EQ(decisions, 2); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); @@ -2255,7 +2305,7 @@ DecideOnObject appendX() } -TEST(CASRequests, CleanConflictsArePacedFlatAndDoNotAdvanceTheReissueCounter) +TEST(CASRequests, CleanConflictsArePacedByTheirLossCountAndDoNotAdvanceTheReissueCounter) { FakeClock clock; auto backend = std::make_shared(); @@ -2270,12 +2320,21 @@ TEST(CASRequests, CleanConflictsArePacedFlatAndDoNotAdvanceTheReissueCounter) WriteResult result = op.readModifyWrite("k", appendX(), Retry::standard()); ASSERT_TRUE(std::holds_alternative(result)); - EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRequestConflictPause] - pauses_before, K); + /// The first loss is retried at once: no pause is slept or counted for it. + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRequestConflictPause] - pauses_before, K - 1); EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRequestReissue] - reissues_before, 0u); - ASSERT_EQ(clock.sleeps.size(), static_cast(K)); - for (uint64_t s : clock.sleeps) - EXPECT_LE(s, 200u); /// flat: every pause is one `backoff(1)` draw, whatever the loss count + ASSERT_EQ(clock.sleeps.size(), static_cast(K - 1)); + for (size_t i = 0; i < clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[i], static_cast(i + 2))); EXPECT_EQ(backend->writeCount("k"), 1u + K + 1u + K); /// seed, K refused, K rival moves, the one that landed + + /// A new call starts its own count. + clock.sleeps.clear(); + RaceMaker again(backend, clock, "k", 3, /*ambiguous=*/false); + ASSERT_TRUE(std::holds_alternative(op.readModifyWrite("k", appendX(), Retry::standard()))); + ASSERT_EQ(clock.sleeps.size(), 2u); + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[0], 2)); + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[1], 3)); } TEST(CASRequests, AConflictThatSettledAFaultKeepsTheGrowingSchedule) @@ -2300,6 +2359,183 @@ TEST(CASRequests, AConflictThatSettledAFaultKeepsTheGrowingSchedule) EXPECT_LE(clock.sleeps[i], std::min(5000, 200ull << i)) << "reissue " << i; } +namespace +{ + +/// Another writer of `key` that commits on demand. Its requests are bracketed by marks, so +/// `renderOwnRequests` shows only the caller's own requests. +struct MarkedRival +{ + MarkedRival(std::shared_ptr backend_, FakeClock & clock, String key_) + : backend(std::move(backend_)), key(std::move(key_)) + , rival_requests(makeRequests(backend, clock)), rival(rival_requests.admit()) + { + } + + void commit() + { + inside = true; + backend->mark("rival{"); + const auto current = rival.read(key, Retry::once()); + (void)orThrow(rival.replace(key, current->bytes + "r", current->etag, Retry::once()), "rival"); + backend->mark("}rival"); + ++commits; + inside = false; + } + + std::shared_ptr backend; + String key; + int commits = 0; + bool inside = false; + CasRequests rival_requests; + CasOperation rival; +}; + +String repeated(std::string_view unit, size_t times) +{ + String out; + for (size_t i = 0; i < times; ++i) + out += unit; + return out; +} + +} + +/// A conflict that settled a transport fault ends the run of clean losses: the clean loss after it starts a new run and +/// is retried at once, so only the fault-settled conflict pauses. +TEST(CASRequests, AFaultSettledConflictRestartsTheCleanLossCount) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + (void)orThrow(op.create("k", "v", Retry::standard()), "seed"); + MarkedRival rival(backend, clock, "k"); + int moves = 0; + backend->onBeforeWrite("k", [&] + { + if (rival.inside || moves >= 3) + return; + ++moves; + rival.commit(); + if (moves == 2) + backend->injectAmbiguousWrite("k"); + }); + + ASSERT_TRUE(std::holds_alternative(op.readModifyWrite("k", appendX(), Retry::standard()))); + EXPECT_EQ(moves, 3) << "premise: clean, fault-settled, clean"; + EXPECT_EQ(clock.sleeps.size(), 1u) << "the clean losses around the fault are each the first of their run"; +} + +/// The rival lands right before the first two writes and during every pause. The first loss is retried at once; the +/// write after the pause that follows the second is decided on a read taken after it, so it lands. +TEST(CASRequests, AReadModifyWriteIsNotStarvedByAWriterThatCommitsDuringEveryPause) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + (void)orThrow(op.create("k", "v", Retry::standard()), "seed"); + MarkedRival rival(backend, clock, "k"); + int collisions = 0; + backend->onBeforeWrite("k", [&] + { + if (rival.inside || collisions >= 2) + return; + ++collisions; + rival.commit(); + }); + auto sleep = clock.sleepFn(); + requests.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + backend->mark("pause"); + rival.commit(); + }); + backend->clearJournal(); + + WriteResult result = op.readModifyWrite("k", appendX(), Retry::standard()); + + ASSERT_TRUE(std::holds_alternative(result)); + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*backend, "k"), "RWRWPRW") + << "read, refused write, read, refused write, pause, read, the write on it"; + EXPECT_EQ(clock.sleeps.size(), 1u); + EXPECT_EQ(rival.commits, 3); + expectBytes(*backend, "k", "vrrrx"); +} + +TEST(CASRequests, AnOnPresenceWriteIsNotStarvedByAWriterThatCommitsDuringEveryPause) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + (void)orThrow(op.create("k", "v", Retry::standard()), "seed"); + MarkedRival rival(backend, clock, "k"); + int collisions = 0; + backend->onBeforeWrite("k", [&] + { + if (rival.inside || collisions >= 2) + return; + ++collisions; + rival.commit(); + }); + auto sleep = clock.sleepFn(); + requests.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + backend->mark("pause"); + rival.commit(); + }); + backend->clearJournal(); + + WriteResult result = op.readModifyWriteOnPresence("k", + [](const std::optional &) -> std::optional { return String("w"); }, Retry::standard()); + + ASSERT_TRUE(std::holds_alternative(result)); + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*backend, "k"), "HWHWPHW"); + EXPECT_EQ(clock.sleeps.size(), 1u); + expectBytes(*backend, "k", "w"); +} + +/// A rival that lands between every read and the write on it still ends the loop on the decision +/// cap, and every write after the first is decided on a read taken after its pause. +TEST(CASRequests, AReadModifyWriteAgainstAWriterBeforeEveryWriteEndsOnTheCount) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + (void)orThrow(op.create("k", "v", Retry::standard()), "seed"); + MarkedRival rival(backend, clock, "k"); + backend->onBeforeWrite("k", [&] + { + if (!rival.inside) + rival.commit(); + }); + auto sleep = clock.sleepFn(); + requests.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + backend->mark("pause"); + }); + backend->clearJournal(); + + WriteResult result = op.readModifyWrite("k", appendX(), Retry::standard()); + + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Attempts); + EXPECT_EQ(clock.sleeps.size(), kCasMaxDecisions - 2) << "no pause after the first refusal, retried at once, nor the last"; + for (size_t i = 0; i < clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[i], static_cast(i + 2))); + /// Only the last refusal is settled: no decision follows it, and its read is what the give-up reports. + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*backend, "k"), "RWRW" + repeated("PRW", kCasMaxDecisions - 3) + "PRWR"); + const auto * seen = std::get_if(&gave_up->last_seen); + ASSERT_NE(seen, nullptr); + expectBytes(*backend, "k", seen->bytes); +} + TEST(CASRequests, ReplaceReportsWhetherAConflictSettledAFault) { FakeClock clock; @@ -2379,8 +2615,9 @@ TEST(CASRequests, CleanConflictsBeforeAFaultDoNotInflateTheFaultsFirstBackoff) WriteResult result = op.readModifyWrite("k", appendX(), Retry::standard()); ASSERT_TRUE(std::holds_alternative(result)); - ASSERT_EQ(clock.sleeps.size(), static_cast(K + 1)); - EXPECT_LE(clock.sleeps[K], 200u) << "the first transport reissue sleeps within backoff(1)"; + /// The first clean loss is retried at once, so K - 1 conflict pauses precede the reissue's. + ASSERT_EQ(clock.sleeps.size(), static_cast(K)); + EXPECT_LE(clock.sleeps[K - 1], 200u) << "the first transport reissue sleeps within backoff(1)"; } TEST(CASRequests, ADeterministicLocalFailureSurfacesUnchangedWithoutAReissue) @@ -2787,7 +3024,7 @@ TEST(CASRequests, ANameOnlyAccessDenialOnAReadPropagatesWhenNoRefreshIsAvailable EXPECT_TRUE(clock.sleeps.empty()); } -TEST(CASRequests, ReadModifyWriteWhoseResolveAndFreshObservationBothFailGivesUpUnresolved) +TEST(CASRequests, ReadModifyWriteWhoseReadAfterTheConflictPauseFailsGivesUpUnresolved) { FakeClock clock; auto backend = std::make_shared(); @@ -2796,9 +3033,10 @@ TEST(CASRequests, ReadModifyWriteWhoseResolveAndFreshObservationBothFailGivesUpU orThrow(op.create("k", "v0", Retry::standard()), "create"); backend->resetCounts(); - /// The store refuses the precondition, and both reads that would settle what happened answer with - /// a store refusal the read loop surfaces at once rather than reissuing. They are armed from inside - /// the write so the loop's OWN first read still succeeds and `decide` sees the object. + /// The store refuses the precondition, and the read after the conflict pause answers with a store + /// refusal the read loop surfaces at once rather than reissuing; the refusal itself is not settled, as + /// that read replaces what settling it would see. Armed from inside the write so the loop's OWN first + /// read still succeeds and `decide` sees the object. backend->refuseNextWrite("k"); bool armed = false; backend->onBeforeWrite("k", [&] @@ -2807,14 +3045,13 @@ TEST(CASRequests, ReadModifyWriteWhoseResolveAndFreshObservationBothFailGivesUpU return; armed = true; backend->failNextReadWith("k", s3Error(Aws::S3::S3Errors::UNKNOWN, "MalformedXML")); - backend->failNextReadWith("k", s3Error(Aws::S3::S3Errors::UNKNOWN, "MalformedXML")); }); WriteResult result = op.readModifyWrite("k", [](const std::optional &) -> std::optional { return String("v1"); }, Retry::standard()); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); - /// No BOUND refused either read -- the reads themselves failed -- so naming a deadline the clock + /// No BOUND refused the read -- the read itself failed -- so naming a deadline the clock /// never reached would send its reader to widen the wrong thing, and nothing was observed to /// report as a conflict. EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); @@ -2822,8 +3059,8 @@ TEST(CASRequests, ReadModifyWriteWhoseResolveAndFreshObservationBothFailGivesUpU EXPECT_TRUE(std::holds_alternative(gave_up->last_seen)); /// The write count is unchanged after the first attempt: nothing ever said another one was safe. EXPECT_EQ(backend->writeTotal(), 1u); - EXPECT_EQ(backend->getTotal(), 3u); - EXPECT_EQ(clock.sleeps.size(), 1u); + EXPECT_EQ(backend->getTotal(), 2u); + EXPECT_TRUE(clock.sleeps.empty()) << "the first conflict is retried at once"; } /// A missing bucket is an ANSWER the store gave, but not an answer about the object: an S3-compatible diff --git a/src/Disks/tests/gtest_cas_shared_deadline.cpp b/src/Disks/tests/gtest_cas_shared_deadline.cpp index 3a0d895b74178..6293458e4692f 100644 --- a/src/Disks/tests/gtest_cas_shared_deadline.cpp +++ b/src/Disks/tests/gtest_cas_shared_deadline.cpp @@ -904,7 +904,7 @@ TEST(CASSharedDeadline, ReadModifyWriteSucceedsOnTheHundredthDecision) ASSERT_TRUE(std::holds_alternative(result)) << outcomeOf(result); EXPECT_EQ(decisions, kCasMaxDecisions); - EXPECT_EQ(pauses, kCasMaxDecisions - 1); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; EXPECT_EQ(rival.moves, kCasMaxDecisions - 1); EXPECT_EQ(std::get(result).attempts_sent, kCasMaxDecisions); } @@ -930,10 +930,12 @@ TEST(CASSharedDeadline, ReadModifyWriteEndsAfterAHundredDecisions) EXPECT_EQ(gave_up->why, GaveUp::Why::Attempts); EXPECT_EQ(gave_up->attempts_sent, kCasMaxDecisions); EXPECT_EQ(decisions, kCasMaxDecisions); - EXPECT_EQ(pauses, kCasMaxDecisions - 1); - /// Every write was settled: the plane's own reads are the first one and one per write. + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; + /// Every loss but the last is followed by a read, after a pause from the second, and only the last refusal, which + /// no decision follows, is settled: the plane's own reads are the first one, one per later decision and the last + /// settlement. EXPECT_EQ(rival.moves, kCasMaxDecisions); - EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Read, "k") - rival.moves, 1 + kCasMaxDecisions); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Read, "k") - rival.moves, 1 + (kCasMaxDecisions - 1) + 1); const auto * seen = std::get_if(&gave_up->last_seen); ASSERT_NE(seen, nullptr); EXPECT_EQ(seen->bytes, plane.bytesOf("k")); @@ -954,7 +956,7 @@ TEST(CASSharedDeadline, RemoveCurrentSucceedsOnTheHundredthDecision) EXPECT_EQ(removed, std::optional(Removal::Removed)) << "error: " << orNone(failure); EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Head, "k"), kCasMaxDecisions); EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Remove, "k"), kCasMaxDecisions); - EXPECT_EQ(pauses, kCasMaxDecisions - 1); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; } TEST(CASSharedDeadline, RemoveCurrentEndsAfterAHundredDecisions) @@ -970,7 +972,7 @@ TEST(CASSharedDeadline, RemoveCurrentEndsAfterAHundredDecisions) [&] { (void)plane.op.removeCurrent("k", Retry::standard()); }); EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Head, "k"), kCasMaxDecisions); EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Remove, "k"), kCasMaxDecisions); - EXPECT_EQ(pauses, kCasMaxDecisions - 1); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; EXPECT_NE(plane.bytesOf("k"), ""); } @@ -1042,7 +1044,40 @@ TEST(CASSharedDeadline, RemoveCurrentReportsAFenceTripDuringItsLastDeleteNotTheC run(TrippableFence::Trip::LeaseExpiry, "no lease budget"); } -/// The fence trips while the read that settles the hundredth refused submission is in flight. +/// The fence trips while the hundredth submission's write is in flight, and that write is refused: the call reports +/// the lost fence, not the count. The first submission writes twice, on the lane's cached catalog and then on its +/// resolve read, so the hundredth submission sends write `kCasMaxDecisions + 1`. +TEST(CASSharedDeadline, CasUpdateReportsAFenceTripDuringItsLastWriteNotTheCount) +{ + TrippableFence mount; + CasHotKeys lane(16ULL << 20); + Plane plane(&lane, mount.fence()); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + CatalogRival rival(plane, layout, 10 * kCasMaxDecisions); + bool tripped = false; + /// The rival's own read, inside the move that refuses write `kCasMaxDecisions + 1`. + plane.backend->armWith(Verb::Read, + [&](const String & k) { return k == key && rival.inside && rival.moves == kCasMaxDecisions; }, + [&] + { + mount.trip(TrippableFence::Trip::Rearm); + tripped = true; + }); + const size_t journal_from = plane.backend->seenCount(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "mount fence tripped", [&] + { + CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) { return current; }); + }); + EXPECT_TRUE(tripped) << "the hundredth submission's write was never sent"; + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions + 1); +} + +/// The fence trips while the read that settles the hundredth submission's refused write is in flight: no +/// submission follows it, so that write is settled, and the call reports the lost fence, not the count. TEST(CASSharedDeadline, CasUpdateReportsAFenceTripDuringItsLastSettlementNotTheCount) { TrippableFence mount; @@ -1054,8 +1089,9 @@ TEST(CASSharedDeadline, CasUpdateReportsAFenceTripDuringItsLastSettlementNotTheC CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); CatalogRival rival(plane, layout, 10 * kCasMaxDecisions); bool tripped = false; + /// The plane's own read after write `kCasMaxDecisions + 1`, the hundredth submission's. plane.backend->armWith(Verb::Read, - [&](const String & k) { return k == key && !rival.inside && rival.moves == kCasMaxDecisions; }, + [&](const String & k) { return k == key && !rival.inside && rival.moves == kCasMaxDecisions + 1; }, [&] { mount.trip(TrippableFence::Trip::Rearm); @@ -1067,12 +1103,14 @@ TEST(CASSharedDeadline, CasUpdateReportsAFenceTripDuringItsLastSettlementNotTheC { CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) { return current; }); }); - EXPECT_TRUE(tripped) << "the hundredth settling read was never sent"; - EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions); + EXPECT_TRUE(tripped) << "the hundredth submission's settling read was never sent"; + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions + 1); } /// `casUpdate` counts submissions to the hot-key lane: one submission can run its `decide` twice on a -/// cached catalog, so the tests count the plane's writes of the catalog, not the calls of `mutate`. +/// cached catalog, so the tests count the plane's writes of the catalog, not the calls of `mutate`. The +/// first submission starts from the cached catalog, loses, and writes again at once on the resolve read, +/// so `kCasMaxDecisions` submissions send one write more than that. TEST(CASSharedDeadline, CasUpdateSucceedsOnTheHundredthSubmission) { CasHotKeys lane(16ULL << 20); @@ -1081,7 +1119,7 @@ TEST(CASSharedDeadline, CasUpdateSucceedsOnTheHundredthSubmission) const String key = layout.refCatalogKey(); CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); - CatalogRival rival(plane, layout, kCasMaxDecisions - 1); + CatalogRival rival(plane, layout, kCasMaxDecisions); size_t pauses = 0; plane.countPauses(pauses); const size_t journal_from = plane.backend->seenCount(); @@ -1098,16 +1136,16 @@ TEST(CASSharedDeadline, CasUpdateSucceedsOnTheHundredthSubmission) }); EXPECT_FALSE(failure.has_value()) << orNone(failure); - EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions); - EXPECT_EQ(rival.moves, kCasMaxDecisions - 1); - EXPECT_EQ(pauses, kCasMaxDecisions - 1); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions + 1); + EXPECT_EQ(rival.moves, kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; const RefCatalog durable = CasRefCatalog::read(plane.op, layout).catalog; EXPECT_EQ(durable.entries.size(), 1 + rival.moves); EXPECT_EQ(durable.entries.front().state, NsState::Removing); } -/// Every write meets a moved precondition. The hundredth refusal ends the call without a pause after -/// it, and the error names a clean conflict. +/// Every write meets a moved precondition. The hundredth refused submission ends the call without a +/// pause after it, and the error names a clean conflict. The first submission writes twice. TEST(CASSharedDeadline, CasUpdateEndsAfterAHundredSubmissionsOnACleanConflict) { CasHotKeys lane(16ULL << 20); @@ -1127,9 +1165,9 @@ TEST(CASSharedDeadline, CasUpdateEndsAfterAHundredSubmissionsOnACleanConflict) { CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) { return current; }); }); - EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions); - EXPECT_EQ(rival.moves, kCasMaxDecisions); - EXPECT_EQ(pauses, kCasMaxDecisions - 1); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions + 1); + EXPECT_EQ(rival.moves, kCasMaxDecisions + 1); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; } /// Namespace-create step 1 decides again after a write whose fate is unknown. When the hundredth From 4ac9ee2c3500018e0a66a8234adb1796ca5e69fa Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 19:51:22 +0100 Subject: [PATCH 20/47] Pin both reads that can fail after a stop following a lost CAS race A stopped query whose catalog write lost a race ends at the next failed read. On the cached path that read settles the refused write and the query ends with its conflict; on the fresh path it is the read before the next attempt and the query ends with its own stop. The test runs both in a fixed order; no further `PUT` follows in either. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../test_cas_request_window/test.py | 49 ++++++++++++------- 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/tests/integration/test_cas_request_window/test.py b/tests/integration/test_cas_request_window/test.py index eeed10dbdac1d..124ce4d0d64db 100644 --- a/tests/integration/test_cas_request_window/test.py +++ b/tests/integration/test_cas_request_window/test.py @@ -345,8 +345,8 @@ def _removing_body(life): @pytest.mark.parametrize("stop", ["kill", "timeout"]) def test_stop_after_accepted_conflicts_permits_next_put(node_stop, stop): - """Three `PUT`s of a catalog write meet 412; the read that settles the third is parked while the query stops and - then succeeds. An accepted conflict is an answer, not a failure, so the fourth `PUT` is sent and lands.""" + """Three `PUT`s of a catalog write meet 412; the read before the fourth is parked while the query stops and then + succeeds. An accepted conflict is an answer, not a failure, so the fourth `PUT` is sent and lands.""" rules = [] for action in ("forward", "forward", "hold"): rules += [_rule("PUT", STOP_CATALOG, "412"), _rule("GET", STOP_CATALOG, action)] @@ -368,23 +368,38 @@ def test_stop_after_accepted_conflicts_permits_next_put(node_stop, stop): @pytest.mark.parametrize("stop", ["kill", "timeout"]) -def test_failed_settlement_after_stop_starts_no_further_put(node_stop, stop): - """A catalog write meets 412 and its settling read is parked while the query stops, then answered with 503. That - read failed after the stop, so the write ends with its conflict and no further `PUT` is sent.""" - _arm_rules([_rule("PUT", STOP_CATALOG, "412"), _rule("GET", STOP_CATALOG, "hold"), - _rule("PUT", STOP_CATALOG, "412", count=1000)]) - query_id = "failed_settlement_" + stop - request = node_stop.get_query_request( - _create_sql(query_id), query_id=query_id, settings=_stop_settings(stop), timeout=120) - released_ms = _stop_and_release(node_stop, query_id, STOP_CATALOG, respond="503", kill=(stop == "kill")) - _wait_until(lambda: request.process.poll() is not None, timeout=60) - trace = _stats()["trace"] - assert [r["status"] for r in _catalog_puts(trace)] == [412], trace - assert not [r for r in _catalog_puts(trace) if r["t_mono_ms"] > released_ms], trace - error = request.get_error() +def test_failed_read_after_a_lost_race_and_stop_starts_no_further_put(node_stop, stop): + """A catalog write meets 412, and the next catalog read is parked while the query stops, then answered with 503. + No further `PUT` is sent. A write decided on the lane's cached catalog has its 412 settled by that read, and the + call ends with the conflict the read could not resolve. A write decided on a fresh read is retried at once without + settling, so the parked read is the one before the next attempt, and the call ends with that read's error: the + query's own stop.""" + + def lose_race_then_fail_the_read(suffix): + _control(cluster.proxy_url, "/config", {"reset": True}) + _arm_rules([_rule("PUT", STOP_CATALOG, "412"), _rule("GET", STOP_CATALOG, "hold"), + _rule("PUT", STOP_CATALOG, "412", count=1000)]) + query_id = "failed_read_{}_{}".format(suffix, stop) + request = node_stop.get_query_request( + _create_sql(query_id), query_id=query_id, settings=_stop_settings(stop), timeout=120) + released_ms = _stop_and_release(node_stop, query_id, STOP_CATALOG, respond="503", kill=(stop == "kill")) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + assert [r["status"] for r in _catalog_puts(trace)] == [412], trace + assert not [r for r in _catalog_puts(trace) if r["t_mono_ms"] > released_ms], trace + assert _remaining_counts() == [0, 0, 1000] + return request.get_error() + + # A table created without faults leaves the lane holding the catalog it wrote. + _control(cluster.proxy_url, "/config", {"reset": True}) + node_stop.query(_create_sql("failed_read_warm_" + stop), timeout=120) + error = lose_race_then_fail_the_read("cached") # `ABORTED`: the conflict the settling read could not resolve. assert re.search(r"Code: 236\b", error) and "conflict" in error, error - assert _remaining_counts() == [0, 0, 1000] + + # That conflict observed nothing, so the lane keeps no catalog and the next write starts from a read. + error = lose_race_then_fail_the_read("fresh") + assert re.search(r"Code: {}\b".format(394 if stop == "kill" else 159), error), error def test_kill_after_ambiguous_create_keeps_unresolved_exit(node_stop): From e0780e20217ec4e20fd430e44fa330ba6935c6a1 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 19:51:22 +0100 Subject: [PATCH 21/47] Document the retry order and pause schedule of CAS conflicts Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- docs/en/antalya/cas/configuration.md | 15 +++++++++++---- docs/en/antalya/cas/operations/troubleshooting.md | 2 +- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/en/antalya/cas/configuration.md b/docs/en/antalya/cas/configuration.md index 7432bb2a5b8cd..2b9bd3ac43700 100644 --- a/docs/en/antalya/cas/configuration.md +++ b/docs/en/antalya/cas/configuration.md @@ -146,10 +146,17 @@ An update of a shared object that keeps losing races to other writers is retried `CREATE` and `DROP` statements, and a hot ref. There is no total time budget for this loop: each attempt has its own request window. -- **One lost race** on a healthy store costs one conditional write, the read that settles it when one is needed, and - a pause drawn uniformly from 0 to 200 ms. -- **Typical total:** 100 lost races cost 100 conditional writes, up to 100 reads, and about 10 s of pauses (at most - 20 s). On a store that answers in tens of milliseconds the whole loop takes about 10 to 20 s. +- **One lost race** on a healthy store costs one conditional write, a pause, and one read before the next attempt. + The first lost race is retried at once. After that the pause grows by 40 ms with each race the same update loses in + a row, up to a base of 750 ms, plus a random addition of up to a quarter of the base, so one pause lasts at most 937 ms. + Five lost races in a row cost 400 to 500 ms of pauses. A race lost on a transport fault is paced like a fault + instead, and the next lost race counts as a first one again. +- **A loss on a cached value:** an update may start from the last catalog this server knows, without a read. When + that value is out of date, its write is refused and the update reads and writes again at once, with no pause and + without counting it as a lost race. So 100 attempts can send 101 conditional writes. +- **Total at the limit:** 100 lost races cost about 100 conditional writes, about 100 reads, and 98 pauses (the first + retry is not paced) of 66.8 s to 83.5 s in all, about 75.2 s on average. While lease renewals succeed, the count of 100 ends the loop, not the + mount lease. - **Worst case:** 100 slow answers, each inside its own window: about 100 request windows, more than 3 hours at the default `cas_request_window_ms`. - **Earlier exits:** `KILL QUERY` or `max_execution_time` ends the loop at the next failed answer from the store. diff --git a/docs/en/antalya/cas/operations/troubleshooting.md b/docs/en/antalya/cas/operations/troubleshooting.md index 6be7fb9697a4e..dc37b19025b8b 100644 --- a/docs/en/antalya/cas/operations/troubleshooting.md +++ b/docs/en/antalya/cas/operations/troubleshooting.md @@ -145,7 +145,7 @@ Everywhere else the `CAS` requests of a stopped query run as on a plain S3 disk. The S3 client reports a stopped query's error in place of any failed answer from the store, as on a plain S3 disk. This includes an expected answer of a healthy store, such as `404` for a key that does not exist. So the query can still fail with `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED` when the store answers with an error after the stop. A bulk delete that the store answers successfully, with an error for one of its keys, keeps that key's error. Writes of several queries to one table's metadata can be sent together by one of them. When that query is stopped, such a failed answer can fail the other queries' writes in the same request too. -A metadata write that loses a race to another writer after the stop fails the query with `ABORTED` (236) and a message that says "conflict": the S3 client reports the stop in place of the store's refusal, and a read of the key shows the other writer's object. +A metadata write that loses a race to another writer after the stop fails the query with `ABORTED` (236) and a message that says "conflict": the S3 client reports the stop in place of the store's refusal, and a read of the key shows the other writer's object. A write that lost its race before the stop reads the key again before its next attempt. When that read fails after the stop, the query fails with the read's error, which the S3 client reports as `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED`. The exception is a write decided on the server's cached copy of the key: that read settles its refusal, and the query fails with `ABORTED` (236) and "conflict". Two background owners stop `CAS` work at its next step, with their own error: From 1f7515462d24d879908c6026b98a9e4e9d542f3d Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 00:14:49 +0100 Subject: [PATCH 22/47] Pace CAS part uploads and stop them in a part being built CAS blob bodies and S3 staging objects were written with default `WriteSettings`, so the remote write bandwidth limits did not reach them, and `KILL QUERY` or `max_execution_time` waited for an upload in flight to finish. Each body now carries the `remote_throttler` of the writer that produced it. For a part that is being built the throttler is wrapped by a guard that throws the query's stop when the socket refills its send budget. Part manifests and other control requests are not touched. A merge or a mutation is paced and not stopped: its thread group's cancellation predicate never throws on this base. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../Backend/CasObjectStorageBackend.cpp | 5 +- .../ContentAddressed/Backend/CasOwner.cpp | 55 +++++++++++++++ .../ContentAddressed/Backend/CasOwner.h | 25 +++++++ .../Backend/CasUploadGuard.cpp | 67 +++++++++++++++++++ .../ContentAddressed/Backend/CasUploadGuard.h | 40 +++++++++++ .../ContentAddressedTransaction.cpp | 42 ++++++++---- .../ContentAddressedTransaction.h | 4 +- .../ContentAddressed/Pool/CasPartWriteTxn.cpp | 4 ++ .../ContentAddressed/Pool/CasPartWriteTxn.h | 3 + 9 files changed, 231 insertions(+), 14 deletions(-) create mode 100644 src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.cpp create mode 100644 src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.h diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp index ad32d87eeda5c..00fc726d7ec47 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -928,12 +929,14 @@ void ObjectStorageBackend::publish(const BlobPublishRequest & request, Transport /// Unconditional rewrite: default request mode and multipart policy, so generation stores are /// not restricted by the conditional single-PUT cap. + WriteSettings write_settings = blobPublicationWriteSettings(); + write_settings.remote_throttler = BodyGuardScope::forKey(request.destination_key); auto out = object_storage->writeObject( StoredObject(request.destination_key), WriteMode::Rewrite, /*attributes=*/std::nullopt, blob_publication_detail::blobWriteBufferSize(streaming->fresh_envelope.size() + streaming->payload_size), - blobPublicationWriteSettings()); + write_settings); out->write(streaming->fresh_envelope.data(), streaming->fresh_envelope.size()); blob_publication_detail::copyVerifiedPayloadAndFinalize(*payload, *out, *streaming, request.destination_key, "ObjectStorageBackend::publish: source yielded {}{} payload bytes for {}, declared {} -- upload aborted, nothing published"); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp index 7fe8fde5bf080..86bc6f0af2416 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp @@ -235,4 +235,59 @@ std::function OwnerScope::effectiveCheck() return current.background; } +namespace +{ + +thread_local std::function upload_stop; + +template +bool cancellationBlocked() +{ + if constexpr (requires { typename Status::QueryCancellationBlocker; }) + return Status::QueryCancellationBlocker::isActive(); + else + return false; +} + +template +inline constexpr bool kGroupHasCancellationSetter = requires(Group & group, std::function is_canceled, std::function throw_if_canceled) +{ + group.setQueryCancellationPredicates(is_canceled, throw_if_canceled); +}; + +static_assert(!kGroupHasCancellationSetter, + "merges are cancellable on this base: add a test that a merge's upload is stopped and correct the user docs on " + "stopping CAS work"); + +} + +std::function uploadStopCheck() +{ + const auto & owner = OwnerScope::current; + if (owner.owed || owner.shared || cancellationBlocked()) + return {}; + ThreadGroupPtr thread_group = CurrentThread::getGroup(); + if (!thread_group) + return {}; + auto predicate = thread_group->getSharedData().throw_if_query_canceled_predicate; + if (!predicate) + return {}; + return [keep_group = std::move(thread_group), stop = std::move(predicate)] { stop(); }; +} + +UploadStopScope::UploadStopScope(std::function stop) + : saved(std::exchange(upload_stop, std::move(stop))) +{ +} + +UploadStopScope::~UploadStopScope() +{ + upload_stop = std::move(saved); +} + +const std::function & UploadStopScope::current() +{ + return upload_stop; +} + } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h index fab5f4478f5f9..125376b27897f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h @@ -164,10 +164,35 @@ class OwnerScope friend void throwIfQueryStopped(); friend std::exception_ptr backgroundStopRequested(); friend bool isQueryStoredCause(const std::exception_ptr & e); + friend std::function uploadStopCheck(); static thread_local State current; State saved; bool active = true; }; +/// The check an upload of a new build runs while it sends, built on the publishing thread; the callable may run on any +/// thread. Empty inside `owed` or `shared` and on a thread with no thread group. Otherwise it runs the group's throwing +/// cancellation predicate, which never throws for a background group such as a merge or a mutation. It holds the thread +/// group, so it may outlive the scope that built it. Background owners are not part of it. +std::function uploadStopCheck(); + +/// Carries the stop check of the build being published from the publishing thread to the code that builds each +/// body's throttler. Scopes nest; destruction restores the enclosing value. +class UploadStopScope +{ +public: + explicit UploadStopScope(std::function stop); + ~UploadStopScope(); + + UploadStopScope(const UploadStopScope &) = delete; + UploadStopScope & operator=(const UploadStopScope &) = delete; + + /// Empty outside a scope. + static const std::function & current(); + +private: + std::function saved; +}; + } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.cpp new file mode 100644 index 0000000000000..854bff8c697c3 --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.cpp @@ -0,0 +1,67 @@ +#include + +#include +#include + +namespace DB::Cas +{ + +namespace +{ + +class UploadGuard final : public IThrottler +{ +public: + UploadGuard(ThrottlerPtr bandwidth_, std::function stop_) + : bandwidth(std::move(bandwidth_)) + , stop(std::move(stop_)) + { + } + + bool throttle(size_t amount, size_t max_block_ns) override + { + stop(); + const bool blocked = bandwidth && bandwidth->throttle(amount, max_block_ns); + stop(); + return blocked; + } + + bool isThrottling() const override { return bandwidth && bandwidth->isThrottling(); } + Int64 getAvailable() override { return bandwidth ? bandwidth->getAvailable() : std::numeric_limits::max(); } + UInt64 getMaxSpeed() const override { return bandwidth ? bandwidth->getMaxSpeed() : 0; } + UInt64 getMaxBurst() const override { return bandwidth ? bandwidth->getMaxBurst() : 0; } + +private: + ThrottlerPtr bandwidth; + std::function stop; +}; + +thread_local String bound_key; +thread_local ThrottlerPtr bound_throttler; + +} + +ThrottlerPtr makeUploadGuard(ThrottlerPtr bandwidth, std::function stop) +{ + if (!stop) + return bandwidth; + return std::make_shared(std::move(bandwidth), std::move(stop)); +} + +BodyGuardScope::BodyGuardScope(String key, ThrottlerPtr throttler) + : saved{std::exchange(bound_key, std::move(key)), std::exchange(bound_throttler, std::move(throttler))} +{ +} + +BodyGuardScope::~BodyGuardScope() +{ + bound_key = std::move(saved.key); + bound_throttler = std::move(saved.throttler); +} + +ThrottlerPtr BodyGuardScope::forKey(const String & key) +{ + return bound_throttler && bound_key == key ? bound_throttler : nullptr; +} + +} diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.h new file mode 100644 index 0000000000000..a9a0ac1796aff --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasUploadGuard.h @@ -0,0 +1,40 @@ +#pragma once +#include +#include + +#include + +namespace DB::Cas +{ + +/// A throttler for one request body that also runs `stop` around every `throttle` call, so the sender notices a +/// stopped owner at each send-budget refill. The amount and `max_block_ns` reach `bandwidth` unchanged. +/// Returns `bandwidth` itself, possibly null, when `stop` is empty. With a stop and no `bandwidth`, `throttle` +/// runs the stop and returns false, and the limits report as absent. +ThrottlerPtr makeUploadGuard(ThrottlerPtr bandwidth, std::function stop); + +/// Binds one object key to the throttler of its body on this thread, for backend code that builds the write settings +/// of that body and has no parameter to receive it. Scopes nest: the innermost binding is the only one visible. +class BodyGuardScope +{ +public: + BodyGuardScope(String key, ThrottlerPtr throttler); + ~BodyGuardScope(); + + BodyGuardScope(const BodyGuardScope &) = delete; + BodyGuardScope & operator=(const BodyGuardScope &) = delete; + + /// The throttler bound to exactly `key` on this thread, null for any other key or outside a scope. + static ThrottlerPtr forKey(const String & key); + +private: + struct Binding + { + String key; + ThrottlerPtr throttler; + }; + + Binding saved; +}; + +} diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index f5d8324765240..7c8643ce190d5 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -458,6 +459,7 @@ void ContentAddressedTransaction::uploadPendingBlobs(PartStaging & st) Cas::BlobSource source; source.size = pb.size; source.publication_attempted = pb.publication_attempted; + source.remote_throttler = pb.remote_throttler; if (pb.backend == Cas::StagingBackend::S3) { source.server_side_copy_from = pb.staging_key; @@ -626,8 +628,13 @@ void ContentAddressedTransaction::publishStaging(const Cas::RootNamespace & ns, throw Exception(ErrorCodes::LOGICAL_ERROR, "ContentAddressedTransaction: staged entries or removal marks for {}/{} without a Build", ns.string(), ref); - /// Promote is an atomic owner move that validates every blob dependency proof. - const Cas::ManifestId id = precommitAndUpload(ns, ref, st, pending_refs); + /// Promote is an atomic owner move that validates every blob dependency proof. Only the uploads of a new build may + /// be stopped: nothing names it yet, and the promote itself must not be cut. + const Cas::ManifestId id = [&] + { + Cas::UploadStopScope upload_stop(Cas::uploadStopCheck()); + return precommitAndUpload(ns, ref, st, pending_refs); + }(); /// Test-only fault seam (Task 3 TDD): simulate a promote-time backend failure for `ref` right /// before the durable promote call. A no-op in production (nothing ever arms it). @@ -924,14 +931,16 @@ void ContentAddressedTransaction::createMetadataFile(const std::string &, const void ContentAddressedTransaction::stageBlobPartFile( const ContentAddressedMetadataStorage::Route & route, - const Cas::BlobRef & ref, size_t size, const std::string & staging_key, Cas::StagingBackend backend) + const Cas::BlobRef & ref, size_t size, const std::string & staging_key, Cas::StagingBackend backend, + ThrottlerPtr remote_throttler) { /// Do not upload here. Record the pending blob for post-precommit publication; dependency state /// remains absent until the upload succeeds and its result is merged. /// The staging bytes are kept (the transaction owns them) — a local temp file for /// `Cas::StagingBackend::Local`, or an S3 staging object for `Cas::StagingBackend::S3`. auto & st = stagingFor(route); - st.pending_blobs.push_back({ref, staging_key, size, backend}); + st.pending_blobs.push_back( + {ref, staging_key, size, backend, std::make_shared>(false), std::move(remote_throttler)}); (void)buildFor(route, st); Cas::ManifestEntry entry; @@ -1133,7 +1142,11 @@ std::unique_ptr ContentAddressedTransaction::writeFile( const Cas::PoolPtr pool = metadata_storage.store(); const Cas::MountIncarnation incarnation = pool->captureMountIncarnation(); const std::string staging_key = metadata_storage.stagingKey(incarnation.writer_epoch, getRandomASCIIString(32) + ".tmp"); - auto object_sink = metadata_storage.objectStorage()->writeObject(StoredObject(staging_key), WriteMode::Rewrite); + /// Only the throttler travels: the caller's other settings describe its own buffer, not this upload. + WriteSettings sink_settings; + sink_settings.remote_throttler = Cas::makeUploadGuard(settings.remote_throttler, Cas::uploadStopCheck()); + auto object_sink = metadata_storage.objectStorage()->writeObject( + StoredObject(staging_key), WriteMode::Rewrite, /*attributes=*/std::nullopt, DBMS_DEFAULT_BUFFER_SIZE, sink_settings); return std::make_unique( std::move(object_sink), staging_key, @@ -1142,10 +1155,11 @@ std::unique_ptr ContentAddressedTransaction::writeFile( buf_size, settings.use_adaptive_write_buffer, settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo](const std::string & hash_hex, size_t size, const std::string & key) + [this, route = *r, hash_algo, throttler = settings.remote_throttler]( + const std::string & hash_hex, size_t size, const std::string & key) { const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; - stageBlobPartFile(route, ref, size, key, Cas::StagingBackend::S3); + stageBlobPartFile(route, ref, size, key, Cas::StagingBackend::S3, throttler); }, [pool, generation = incarnation.fence_generation] { pool->checkFenceOrThrow(generation); }); } @@ -1156,10 +1170,11 @@ std::unique_ptr ContentAddressedTransaction::writeFile( buf_size, settings.use_adaptive_write_buffer, settings.adaptive_write_buffer_initial_size, - [this, route = *r, hash_algo](const std::string & hash_hex, size_t size, const std::string & temp_path) + [this, route = *r, hash_algo, throttler = settings.remote_throttler]( + const std::string & hash_hex, size_t size, const std::string & temp_path) { const Cas::BlobRef ref{hash_algo, Cas::codecFor(hash_algo).fromHex(hash_hex)}; - stageBlobPartFile(route, ref, size, temp_path, Cas::StagingBackend::Local); + stageBlobPartFile(route, ref, size, temp_path, Cas::StagingBackend::Local, throttler); }); } @@ -1167,7 +1182,7 @@ std::unique_ptr ContentAddressedTransaction::writeFile( /// rides the single tree object as an Inline entry (one-GET part open); an oversized /// candidate spills to a blob (the safety net). return std::make_unique( - [this, route = *r](std::string bytes) + [this, route = *r, throttler = settings.remote_throttler](std::string bytes) { /// Mint via the one write hash function, `Cas::poolContentHash` (algorithm, payload) -> BlobRef /// (`CasPartWriteTxn.h`) -- the SAME mint the streaming blob path's callers use, so an inline file @@ -1217,7 +1232,7 @@ std::unique_ptr ContentAddressedTransaction::writeFile( /// enough (a safety net, not a hot path) that S3-staging mode does not cover it. bool staged = false; SCOPE_EXIT({ if (!staged) { std::error_code ec; std::filesystem::remove(temp_path, ec); } }); - stageBlobPartFile(route, ref, bytes.size(), temp_path, Cas::StagingBackend::Local); + stageBlobPartFile(route, ref, bytes.size(), temp_path, Cas::StagingBackend::Local, throttler); staged = true; } }); @@ -2068,6 +2083,8 @@ void fanOutBlobUploads( /// `waitForAllToFinish` only waits (never throws), so it is safe on the unwinding path (the B90 /// lesson, `threadPoolCallbackRunner.h:68`). SCOPE_EXIT_SAFE({ ThreadPoolCallbackRunnerLocal::waitForAllToFinish(handles); }); + /// Read on the publishing thread, so every worker is stopped, or not, as its publisher would be. + const std::function upload_stop = UploadStopScope::current(); size_t idx = 0; for (const auto & [ref, req] : grouped) { @@ -2082,8 +2099,9 @@ void fanOutBlobUploads( /// task is now runnable) and the pre-reserved `emplace_back` records it without allocating, so /// there is no window in which a scheduled task is untracked. handles.emplace_back(runner.enqueueAndGiveOwnership([slot, txn, req_by_value = std::move(task_req), task_hooks, - group = CurrentThread::getGroup()] + group = CurrentThread::getGroup(), upload_stop] { + UploadStopScope adopted_stop(upload_stop); throwUnlessInThreadGroup(group, "CAS blob upload worker"); if (task_hooks && task_hooks->in_task) task_hooks->in_task(req_by_value.ref); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index 84f544b4abd95..bc934ca6ef5fa 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -176,6 +176,8 @@ class ContentAddressedTransaction : public IMetadataTransaction /// record into another part, and the copy shares the flag, so the parts together copy /// the staged envelope at most once. std::shared_ptr> publication_attempted = std::make_shared>(false); + /// The `remote_throttler` of the settings the file was written with; a hardlink or a move keeps it. + ThrottlerPtr remote_throttler; }; std::vector pending_blobs; /// Staged blobs uploaded after the manifest edge is precommitted. }; @@ -202,7 +204,7 @@ class ContentAddressedTransaction : public IMetadataTransaction /// (Local or S3-staging, `backend` says which) and the always-Local inline-cap fallback. void stageBlobPartFile(const ContentAddressedMetadataStorage::Route & route, const Cas::BlobRef & ref, size_t size, const std::string & staging_key, - Cas::StagingBackend backend); + Cas::StagingBackend backend, ThrottlerPtr remote_throttler); /// Builds the fixed-length CABL envelope header for a staging blob, with a fresh `incarnation_tag`, /// so the S3 staging object holds `[header][payload]` and the promote diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index 8f0f4ec4f87ca..fda40d07c108c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -515,6 +516,9 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// each iteration of this loop builds one. The verbatim staged copy is additionally /// once-only per staging object: `beginPublication` spends a flag that the caller shares /// among every source over that object. + std::optional body_guard; + if (transport == BlobPublicationTransport::Streaming) + body_guard.emplace(key, makeUploadGuard(source.remote_throttler, UploadStopScope::current())); op.publish(BlobPublishRequest{key, std::move(publication)}, Retry::once()); } catch (...) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h index 2e026a87048c6..6ab3c33b14e2a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -30,6 +31,8 @@ struct BlobSource std::optional server_side_copy_from; std::shared_ptr> publication_attempted = std::make_shared>(false); + /// The bandwidth limit of the writer that produced the bytes; null for none. + ThrottlerPtr remote_throttler; /// Atomically consume the logical source's first-publication privilege -- the verbatim staged copy /// is available to exactly one physical publication of this source, whichever one gets here first. From 7d5a0b19ff99e2b14b4fb377975c82026e315d23 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 00:14:50 +0100 Subject: [PATCH 23/47] Move the generation fake storage to a header; record write settings The upload guard tests need the fake that `gtest_cas_s3_staging.cpp` defines. It moves to `cas_fake_generation_object_storage.h` and now records the `WriteSettings` of each `writeObject` and `copyObject` and can call a recorded throttler while a body is written. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../cas_fake_generation_object_storage.h | 440 ++++++++++++++++++ src/Disks/tests/gtest_cas_s3_staging.cpp | 348 +------------- 2 files changed, 443 insertions(+), 345 deletions(-) create mode 100644 src/Disks/tests/cas_fake_generation_object_storage.h diff --git a/src/Disks/tests/cas_fake_generation_object_storage.h b/src/Disks/tests/cas_fake_generation_object_storage.h new file mode 100644 index 0000000000000..b7dbb82336928 --- /dev/null +++ b/src/Disks/tests/cas_fake_generation_object_storage.h @@ -0,0 +1,440 @@ +#pragma once + +#include "config.h" + +#if USE_AWS_S3 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace DB::ErrorCodes +{ +extern const int BAD_ARGUMENTS; +} + +namespace DB::Cas::tests +{ + +/// A `LocalObjectStorage` that reports the GCS generation dialect +/// (`conditionalOpsUseGenerationTokens() == true`) and a non-`Local` `getType()`, so +/// `ContentAddressedMetadataStorage::openPoolView` builds its backend in `Mode::Native` with +/// `native_token_type == Dialect::Generation`. The fake also advertises native copy so generation +/// token mode can exercise explicit S3 staging without endpoint/provider heuristics. +/// +/// Holds every object entirely in memory, keyed by the BARE CAS key exactly as `Backend` hands it to +/// `object_storage` (e.g. `"pool/_probe//token"`). Native mode never asks `object_storage` to +/// resolve that key against anything (`ContentAddressedMetadataStorage::physicalKey` is a documented +/// no-op for Native, since a real S3 client resolves a bucket-relative key against its own bucket/prefix +/// configuration internally) -- so this fake never needs a notion of "resolve a key to a location" at +/// all, unlike a real filesystem-backed object storage would. That sidesteps the class of bug a +/// resolve-then-strip round trip through the real `LocalObjectStorage` file/list implementation is prone +/// to (a key is a key, with no round trip to get wrong), and it never touches the real filesystem, so it +/// cannot leak files into the test process's working directory either. +/// +/// A writable Native-mode mount always runs the mandatory capability battery (`CasProbe.cpp`), which +/// requires REAL conditional-write enforcement: the precondition is evaluated when a write completes, +/// signaled by an `S3Exception` carrying the canonical `PreconditionFailed` name (see +/// `ObjectStorageBackend::finalizeConditionalWrite`). `writeObject` therefore buffers bytes in memory and +/// defers both the precondition check and the commit to `finalize`, mirroring how a real object store +/// only commits -- and only then can reject -- on PUT completion. +class FakeGenerationObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + /// Report the S3 ETag dialect instead: a token is a digest of the object's bytes, so the same bytes + /// written or copied again carry the same token, as on S3 without KMS. Set before `startup`. + bool content_derived_etags = false; + + DB::ObjectStorageType getType() const override { return DB::ObjectStorageType::S3; } + bool conditionalOpsUseGenerationTokens() const override { return !content_derived_etags; } + std::optional isBucketVersioningEnabled(const DB::ObjectStorageControlRequest &) const override { return false; } + bool supportsRetryProfile(DB::ObjectStorageRetryProfile) const override { return true; } + bool supportsCopyMode(DB::ObjectStorageCopyMode mode) const override + { + return mode == DB::ObjectStorageCopyMode::Default || mode == DB::ObjectStorageCopyMode::NativeOnly; + } + + /// One `writeObject` or `copyObject` as the store received it. + struct WriteRecord + { + std::string key; + DB::WriteSettings settings; + bool copy = false; + bool throttled = false; + std::exception_ptr throttle_error; + }; + + /// Keys whose write calls its `remote_throttler->throttle(32768, 0)` once before the store takes the bytes, as a + /// socket does at a send-budget refill. What that call throws fails the write. Set before the writes start. + std::function throttle_while_writing; + /// Runs on the writing thread right before that call. + std::function before_throttle; + + /// Every write and copy so far, in the order the store received them. + std::vector> records() const + { + std::lock_guard lock(mutex); + return {recorded.begin(), recorded.end()}; + } + + std::unique_ptr writeObject( + const DB::StoredObject & object, + DB::WriteMode mode, + std::optional /*attributes*/, + size_t /*buf_size*/, + const DB::WriteSettings & write_settings) override + { + if (mode != DB::WriteMode::Rewrite) + throw DB::Exception(DB::ErrorCodes::BAD_ARGUMENTS, "FakeGenerationObjectStorage only supports Rewrite"); + auto record = std::make_shared(); + record->key = object.remote_path; + record->settings = write_settings; + { + std::lock_guard lock(mutex); + recorded.push_back(record); + } + return std::make_unique( + *this, object.remote_path, write_settings.object_storage_write_if_none_match, + write_settings.object_storage_write_if_match, std::move(record)); + } + + bool exists(const DB::StoredObject & object) const override + { + std::lock_guard lock(mutex); + return objects.contains(object.remote_path); + } + + std::unique_ptr readObject( + const DB::StoredObject & object, + const DB::ReadSettings & /*read_settings*/, + std::optional /*read_hint*/, + bool /*use_external_buffer*/, + bool /*restrict_seek*/) const override + { + std::lock_guard lock(mutex); + auto it = objects.find(object.remote_path); + if (it == objects.end()) + /// `RESOURCE_NOT_FOUND`, not a plain `DB::Exception`: `Backend::probeSentinelRaw`'s Native + /// path (`CasObjectStorageBackend.cpp`) classifies absence ONLY from a caught `S3Exception` + /// carrying `NO_SUCH_KEY`/`RESOURCE_NOT_FOUND` (or the matching exception name) -- anything + /// else, including an unrecognized exception TYPE, falls through to `ProbeOutcome:: + /// Indeterminate` (fail-closed). A bodyless HEAD on a real absent S3 key throws exactly this + /// code, since the SDK cannot parse a `` from a body that was never sent. + throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", + Aws::S3::S3Errors::RESOURCE_NOT_FOUND); + /// Copies the bytes, matching a real remote read (no shared ownership with the stored entry, so + /// a later overwrite of this key cannot mutate bytes a caller is still reading). + return std::make_unique(object.remote_path, it->second.bytes); + } + + DB::ObjectMetadata getObjectMetadata(const std::string & path, bool with_tags) const override + { + auto metadata = tryGetObjectMetadata(path, with_tags); + if (!metadata) + throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", + Aws::S3::S3Errors::RESOURCE_NOT_FOUND); + return *metadata; + } + + std::optional tryGetObjectMetadata(const std::string & path, bool /*with_tags*/) const override + { + std::lock_guard lock(mutex); + auto it = objects.find(path); + if (it == objects.end()) + return std::nullopt; + DB::ObjectMetadata metadata; + metadata.size_bytes = it->second.bytes.size(); + metadata.etag = tokenOf(it->second); + return metadata; + } + + std::optional tryGetObjectMetadataWithNativeToken(const std::string & path, bool with_tags) const override + { + return tryGetObjectMetadata(path, with_tags); + } + + /// This fake advertises every retry profile, and an in-memory store has no retry behaviour to + /// vary, so the profile-aware overloads simply forward. A storage that claimed the capability + /// without implementing them would refuse every control-plane request of a writable mount. + std::optional tryGetObjectMetadataWithNativeToken( + const std::string & path, bool with_tags, const DB::ObjectStorageControlRequest &) const override + { + return tryGetObjectMetadata(path, with_tags); + } + + DB::ObjectStorageIteratorPtr iterate( + const std::string & path_prefix, size_t max_keys, bool with_tags, const std::optional & start_after, + const DB::ObjectStorageControlRequest &) const override + { + return DB::LocalObjectStorage::iterate(path_prefix, max_keys, with_tags, start_after); + } + + DB::ConditionalRemoveResult removeObjectIfTokenMatches( + const DB::StoredObject & object, const std::string & etag, const DB::ObjectStorageControlRequest &) override + { + return removeObjectIfTokenMatches(object, etag); + } + using DB::LocalObjectStorage::removeObjectIfTokenMatches; + + /// A real S3 GET answers with the object's incarnation, which is what the backend reads its + /// bytes AND its generation from in one request. Quoted, the way the SDK's ETag field carries a + /// generation across the HTTP boundary. + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( + const DB::StoredObject & object, const DB::ReadSettings &, size_t, std::optional) const override + { + std::lock_guard lock(mutex); + auto it = objects.find(object.remote_path); + if (it == objects.end()) + throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", + Aws::S3::S3Errors::RESOURCE_NOT_FOUND); + DB::SmallObjectDataWithMetadata result; + result.data = it->second.bytes; + result.metadata.size_bytes = it->second.bytes.size(); + result.metadata.etag = transportTokenOf(it->second); + return result; + } + + void removeObjectIfExists(const DB::StoredObject & object) override + { + std::lock_guard lock(mutex); + objects.erase(object.remote_path); + } + + void removeObjectsIfExist(const DB::StoredObjects & objects_to_remove) override + { + std::lock_guard lock(mutex); + for (const auto & object : objects_to_remove) + objects.erase(object.remote_path); + } + + /// S3 sends an unconditional delete under every retry profile; the intent probe and GC use it. + void removeObjectsIfExistUnderProfile(const DB::StoredObjects & objects_to_remove, const DB::ObjectStorageControlRequest &) override + { + removeObjectsIfExist(objects_to_remove); + } + + /// `path` is a bare CAS-relative prefix (e.g. `"pool/"` or `"pool/_probe/"`) -- exactly what + /// `Backend::list`'s Native-mode path passes through unchanged (it applies no prefix stripping of + /// its own there) and expects back on every listed key. A plain string-prefix scan over the + /// in-memory keys already IS that key space, so there is no separate "physical" representation to + /// resolve to or strip back off. + void listObjects(const std::string & path, DB::RelativePathsWithMetadata & children, size_t max_keys) const override + { + std::lock_guard lock(mutex); + for (const auto & [key, entry] : objects) + { + if (!key.starts_with(path)) + continue; + DB::ObjectMetadata metadata; + metadata.size_bytes = entry.bytes.size(); + metadata.etag = tokenOf(entry); + children.push_back(std::make_shared(key, std::move(metadata))); + if (max_keys != 0 && children.size() >= max_keys) + break; + } + } + + DB::ConditionalRemoveResult removeObjectIfTokenMatches(const DB::StoredObject & object, const std::string & etag) override + { + std::lock_guard lock(mutex); + DB::ConditionalRemoveResult result; + auto it = objects.find(object.remote_path); + if (it == objects.end()) + { + result.outcome = DB::ConditionalRemoveOutcome::NotFound; + return result; + } + if (tokenOf(it->second) != etag) + { + result.outcome = DB::ConditionalRemoveOutcome::TokenMismatch; + return result; + } + objects.erase(it); + result.outcome = DB::ConditionalRemoveOutcome::Removed; + return result; + } + + /// Checks the write-once/exact-token precondition against the current generation and, on success, + /// stores `bytes` and mints the next generation. Throws an `S3Exception` naming `PreconditionFailed` + /// on a lost condition -- the one signal `finalizeConditionalWrite` classifies as + /// `ConditionalWriteOutcome::PreconditionLost` rather than an ordinary failure. + /// Returns the new object's token as a real store returns it in the write response: the backend + /// attributes the write to that token and nothing reads it back. + std::string commitConditionalWrite(const std::string & key, const std::string & bytes, + const std::string & if_none_match, const std::string & if_match) + { + std::lock_guard lock(mutex); + auto it = objects.find(key); + const bool exists_now = it != objects.end(); + if (!if_none_match.empty() && exists_now) + throw DB::S3Exception("FakeGenerationObjectStorage: if-none-match precondition failed", + Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); + if (!if_match.empty() && (!exists_now || tokenOf(it->second) != if_match)) + throw DB::S3Exception("FakeGenerationObjectStorage: if-match precondition failed", + Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); + + Entry & entry = objects[key]; + entry = Entry{bytes, next_generation++}; + return transportTokenOf(entry); + } + + /// A same-store copy of the stored bytes, counted per destination key. + void copyObject( /// NOLINT + const DB::StoredObject & object_from, + const DB::StoredObject & object_to, + const DB::ReadSettings & /*read_settings*/, + const DB::WriteSettings & write_settings, + std::optional /*object_to_attributes*/ = {}) override + { + std::lock_guard lock(mutex); + auto record = std::make_shared(); + record->key = object_to.remote_path; + record->settings = write_settings; + record->copy = true; + recorded.push_back(std::move(record)); + auto it = objects.find(object_from.remote_path); + if (it == objects.end()) + throw DB::S3Exception("FakeGenerationObjectStorage: copy source does not exist", + Aws::S3::S3Errors::RESOURCE_NOT_FOUND); + Entry copy{it->second.bytes, next_generation++}; + objects[object_to.remote_path] = std::move(copy); + ++copies_to[object_to.remote_path]; + } + + std::map copiesByDestination() const + { + std::lock_guard lock(mutex); + return copies_to; + } + +private: + struct Entry + { + std::string bytes; + uint64_t generation; + }; + + std::string tokenOf(const Entry & entry) const + { + if (content_derived_etags) + return getHexUIntLowercase(sipHash128(entry.bytes.data(), entry.bytes.size())); + return std::to_string(entry.generation); + } + + /// The token as the SDK's ETag field carries it: quoted for a GCS generation. + std::string transportTokenOf(const Entry & entry) const + { + return content_derived_etags ? tokenOf(entry) : "\"" + tokenOf(entry) + "\""; + } + + /// Buffers the whole body in memory so the entry is committed exactly once, at `finalize`, and only after the + /// precondition has been checked. + class ConditionalWriteBuffer final : public DB::WriteBufferFromFileBase + { + public: + ConditionalWriteBuffer(FakeGenerationObjectStorage & storage_, std::string key_, + std::string if_none_match_, std::string if_match_, std::shared_ptr record_) + : DB::WriteBufferFromFileBase(/*buf_size=*/8192, nullptr, 0) + , storage(storage_), key(std::move(key_)) + , if_none_match(std::move(if_none_match_)), if_match(std::move(if_match_)) + , record(std::move(record_)) + { + } + + void sync() override {} + std::string getFileName() const override { return key; } + + /// The write response's own incarnation, quoted the way the SDK's ETag field carries a GCS + /// generation across the HTTP boundary -- the backend is what strips that transport syntax. + std::optional getResultObjectETag() const override { return committed_generation; } + + protected: + void nextImpl() override + { + if (!offset()) + return; + buffered.append(working_buffer.begin(), offset()); + } + + void finalizeImpl() override + { + next(); + const auto & throttler = record->settings.remote_throttler; + if (throttler && storage.throttle_while_writing && storage.throttle_while_writing(key)) + throttleOnce(*throttler); + committed_generation = storage.commitConditionalWrite(key, buffered, if_none_match, if_match); + } + + void throttleOnce(DB::IThrottler & throttler) + { + if (storage.before_throttle) + storage.before_throttle(key); + record->throttled = true; + try + { + throttler.throttle(32768, 0); + } + catch (...) + { + record->throttle_error = std::current_exception(); + throw; + } + } + + private: + FakeGenerationObjectStorage & storage; + std::string key; + std::string if_none_match; + std::string if_match; + std::string buffered; + std::optional committed_generation; + std::shared_ptr record; + }; + + mutable std::mutex mutex; + std::map objects; + std::map copies_to; + std::vector> recorded; + uint64_t next_generation = 1; +}; + +inline std::shared_ptr makeFakeGenerationObjectStorageForTest() +{ + static std::atomic counter{0}; + const auto unique = std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)); + const auto root = (std::filesystem::temp_directory_path() / ("cas_s3_staging_generation_" + unique)).string(); + + std::error_code ec; + std::filesystem::remove_all(root, ec); + std::filesystem::create_directories(root, ec); + + DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); + return ownedByDirectory(std::make_shared(std::move(settings)), root); +} + +} + +#endif diff --git a/src/Disks/tests/gtest_cas_s3_staging.cpp b/src/Disks/tests/gtest_cas_s3_staging.cpp index e32fc4b55e1e9..b9084ec982609 100644 --- a/src/Disks/tests/gtest_cas_s3_staging.cpp +++ b/src/Disks/tests/gtest_cas_s3_staging.cpp @@ -1,6 +1,7 @@ #include #include "cas_test_helpers.h" #include "cas_publication_test_support.h" +#include "cas_fake_generation_object_storage.h" #include #include #include @@ -1131,351 +1132,8 @@ TEST(CASS3Staging, MountStartSweepsALostAbortDelete) #if USE_AWS_S3 -namespace -{ - -/// A `LocalObjectStorage` that reports the GCS generation dialect -/// (`conditionalOpsUseGenerationTokens() == true`) and a non-`Local` `getType()`, so -/// `ContentAddressedMetadataStorage::openPoolView` builds its backend in `Mode::Native` with -/// `native_token_type == Dialect::Generation`. The fake also advertises native copy so generation -/// token mode can exercise explicit S3 staging without endpoint/provider heuristics. -/// -/// Holds every object entirely in memory, keyed by the BARE CAS key exactly as `Backend` hands it to -/// `object_storage` (e.g. `"pool/_probe//token"`). Native mode never asks `object_storage` to -/// resolve that key against anything (`ContentAddressedMetadataStorage::physicalKey` is a documented -/// no-op for Native, since a real S3 client resolves a bucket-relative key against its own bucket/prefix -/// configuration internally) -- so this fake never needs a notion of "resolve a key to a location" at -/// all, unlike a real filesystem-backed object storage would. That sidesteps the class of bug a -/// resolve-then-strip round trip through the real `LocalObjectStorage` file/list implementation is prone -/// to (a key is a key, with no round trip to get wrong), and it never touches the real filesystem, so it -/// cannot leak files into the test process's working directory either. -/// -/// A writable Native-mode mount always runs the mandatory capability battery (`CasProbe.cpp`), which -/// requires REAL conditional-write enforcement: the precondition is evaluated when a write completes, -/// signaled by an `S3Exception` carrying the canonical `PreconditionFailed` name (see -/// `ObjectStorageBackend::finalizeConditionalWrite`). `writeObject` therefore buffers bytes in memory and -/// defers both the precondition check and the commit to `finalize`, mirroring how a real object store -/// only commits -- and only then can reject -- on PUT completion. -class FakeGenerationObjectStorage final : public DB::LocalObjectStorage -{ -public: - using DB::LocalObjectStorage::LocalObjectStorage; - - /// Report the S3 ETag dialect instead: a token is a digest of the object's bytes, so the same bytes - /// written or copied again carry the same token, as on S3 without KMS. Set before `startup`. - bool content_derived_etags = false; - - DB::ObjectStorageType getType() const override { return DB::ObjectStorageType::S3; } - bool conditionalOpsUseGenerationTokens() const override { return !content_derived_etags; } - std::optional isBucketVersioningEnabled(const DB::ObjectStorageControlRequest &) const override { return false; } - bool supportsRetryProfile(DB::ObjectStorageRetryProfile) const override { return true; } - bool supportsCopyMode(DB::ObjectStorageCopyMode mode) const override - { - return mode == DB::ObjectStorageCopyMode::Default || mode == DB::ObjectStorageCopyMode::NativeOnly; - } - - std::unique_ptr writeObject( - const DB::StoredObject & object, - DB::WriteMode mode, - std::optional /*attributes*/, - size_t /*buf_size*/, - const DB::WriteSettings & write_settings) override - { - if (mode != DB::WriteMode::Rewrite) - throw DB::Exception(DB::ErrorCodes::BAD_ARGUMENTS, "FakeGenerationObjectStorage only supports Rewrite"); - return std::make_unique( - *this, object.remote_path, write_settings.object_storage_write_if_none_match, - write_settings.object_storage_write_if_match); - } - - bool exists(const DB::StoredObject & object) const override - { - std::lock_guard lock(mutex); - return objects.contains(object.remote_path); - } - - std::unique_ptr readObject( - const DB::StoredObject & object, - const DB::ReadSettings & /*read_settings*/, - std::optional /*read_hint*/, - bool /*use_external_buffer*/, - bool /*restrict_seek*/) const override - { - std::lock_guard lock(mutex); - auto it = objects.find(object.remote_path); - if (it == objects.end()) - /// `RESOURCE_NOT_FOUND`, not a plain `DB::Exception`: `Backend::probeSentinelRaw`'s Native - /// path (`CasObjectStorageBackend.cpp`) classifies absence ONLY from a caught `S3Exception` - /// carrying `NO_SUCH_KEY`/`RESOURCE_NOT_FOUND` (or the matching exception name) -- anything - /// else, including an unrecognized exception TYPE, falls through to `ProbeOutcome:: - /// Indeterminate` (fail-closed). A bodyless HEAD on a real absent S3 key throws exactly this - /// code, since the SDK cannot parse a `` from a body that was never sent. - throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", - Aws::S3::S3Errors::RESOURCE_NOT_FOUND); - /// Copies the bytes, matching a real remote read (no shared ownership with the stored entry, so - /// a later overwrite of this key cannot mutate bytes a caller is still reading). - return std::make_unique(object.remote_path, it->second.bytes); - } - - DB::ObjectMetadata getObjectMetadata(const std::string & path, bool with_tags) const override - { - auto metadata = tryGetObjectMetadata(path, with_tags); - if (!metadata) - throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", - Aws::S3::S3Errors::RESOURCE_NOT_FOUND); - return *metadata; - } - - std::optional tryGetObjectMetadata(const std::string & path, bool /*with_tags*/) const override - { - std::lock_guard lock(mutex); - auto it = objects.find(path); - if (it == objects.end()) - return std::nullopt; - DB::ObjectMetadata metadata; - metadata.size_bytes = it->second.bytes.size(); - metadata.etag = tokenOf(it->second); - return metadata; - } - - std::optional tryGetObjectMetadataWithNativeToken(const std::string & path, bool with_tags) const override - { - return tryGetObjectMetadata(path, with_tags); - } - - /// This fake advertises every retry profile, and an in-memory store has no retry behaviour to - /// vary, so the profile-aware overloads simply forward. A storage that claimed the capability - /// without implementing them would refuse every control-plane request of a writable mount. - std::optional tryGetObjectMetadataWithNativeToken( - const std::string & path, bool with_tags, const DB::ObjectStorageControlRequest &) const override - { - return tryGetObjectMetadata(path, with_tags); - } - - DB::ObjectStorageIteratorPtr iterate( - const std::string & path_prefix, size_t max_keys, bool with_tags, const std::optional & start_after, - const DB::ObjectStorageControlRequest &) const override - { - return DB::LocalObjectStorage::iterate(path_prefix, max_keys, with_tags, start_after); - } - - DB::ConditionalRemoveResult removeObjectIfTokenMatches( - const DB::StoredObject & object, const std::string & etag, const DB::ObjectStorageControlRequest &) override - { - return removeObjectIfTokenMatches(object, etag); - } - using DB::LocalObjectStorage::removeObjectIfTokenMatches; - - /// A real S3 GET answers with the object's incarnation, which is what the backend reads its - /// bytes AND its generation from in one request. Quoted, the way the SDK's ETag field carries a - /// generation across the HTTP boundary. - DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( - const DB::StoredObject & object, const DB::ReadSettings &, size_t, std::optional) const override - { - std::lock_guard lock(mutex); - auto it = objects.find(object.remote_path); - if (it == objects.end()) - throw DB::S3Exception("FakeGenerationObjectStorage: object does not exist", - Aws::S3::S3Errors::RESOURCE_NOT_FOUND); - DB::SmallObjectDataWithMetadata result; - result.data = it->second.bytes; - result.metadata.size_bytes = it->second.bytes.size(); - result.metadata.etag = transportTokenOf(it->second); - return result; - } - - void removeObjectIfExists(const DB::StoredObject & object) override - { - std::lock_guard lock(mutex); - objects.erase(object.remote_path); - } - - void removeObjectsIfExist(const DB::StoredObjects & objects_to_remove) override - { - std::lock_guard lock(mutex); - for (const auto & object : objects_to_remove) - objects.erase(object.remote_path); - } - - /// S3 sends an unconditional delete under every retry profile; the intent probe and GC use it. - void removeObjectsIfExistUnderProfile(const DB::StoredObjects & objects_to_remove, const DB::ObjectStorageControlRequest &) override - { - removeObjectsIfExist(objects_to_remove); - } - - /// `path` is a bare CAS-relative prefix (e.g. `"pool/"` or `"pool/_probe/"`) -- exactly what - /// `Backend::list`'s Native-mode path passes through unchanged (it applies no prefix stripping of - /// its own there) and expects back on every listed key. A plain string-prefix scan over the - /// in-memory keys already IS that key space, so there is no separate "physical" representation to - /// resolve to or strip back off. - void listObjects(const std::string & path, DB::RelativePathsWithMetadata & children, size_t max_keys) const override - { - std::lock_guard lock(mutex); - for (const auto & [key, entry] : objects) - { - if (!key.starts_with(path)) - continue; - DB::ObjectMetadata metadata; - metadata.size_bytes = entry.bytes.size(); - metadata.etag = tokenOf(entry); - children.push_back(std::make_shared(key, std::move(metadata))); - if (max_keys != 0 && children.size() >= max_keys) - break; - } - } - - DB::ConditionalRemoveResult removeObjectIfTokenMatches(const DB::StoredObject & object, const std::string & etag) override - { - std::lock_guard lock(mutex); - DB::ConditionalRemoveResult result; - auto it = objects.find(object.remote_path); - if (it == objects.end()) - { - result.outcome = DB::ConditionalRemoveOutcome::NotFound; - return result; - } - if (tokenOf(it->second) != etag) - { - result.outcome = DB::ConditionalRemoveOutcome::TokenMismatch; - return result; - } - objects.erase(it); - result.outcome = DB::ConditionalRemoveOutcome::Removed; - return result; - } - - /// Checks the write-once/exact-token precondition against the current generation and, on success, - /// stores `bytes` and mints the next generation. Throws an `S3Exception` naming `PreconditionFailed` - /// on a lost condition -- the one signal `finalizeConditionalWrite` classifies as - /// `ConditionalWriteOutcome::PreconditionLost` rather than an ordinary failure. - /// Returns the new object's token as a real store returns it in the write response: the backend - /// attributes the write to that token and nothing reads it back. - std::string commitConditionalWrite(const std::string & key, const std::string & bytes, - const std::string & if_none_match, const std::string & if_match) - { - std::lock_guard lock(mutex); - auto it = objects.find(key); - const bool exists_now = it != objects.end(); - if (!if_none_match.empty() && exists_now) - throw DB::S3Exception("FakeGenerationObjectStorage: if-none-match precondition failed", - Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); - if (!if_match.empty() && (!exists_now || tokenOf(it->second) != if_match)) - throw DB::S3Exception("FakeGenerationObjectStorage: if-match precondition failed", - Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); - - Entry & entry = objects[key]; - entry = Entry{bytes, next_generation++}; - return transportTokenOf(entry); - } - - /// A same-store copy of the stored bytes, counted per destination key. - void copyObject( /// NOLINT - const DB::StoredObject & object_from, - const DB::StoredObject & object_to, - const DB::ReadSettings & /*read_settings*/, - const DB::WriteSettings & /*write_settings*/, - std::optional /*object_to_attributes*/ = {}) override - { - std::lock_guard lock(mutex); - auto it = objects.find(object_from.remote_path); - if (it == objects.end()) - throw DB::S3Exception("FakeGenerationObjectStorage: copy source does not exist", - Aws::S3::S3Errors::RESOURCE_NOT_FOUND); - Entry copy{it->second.bytes, next_generation++}; - objects[object_to.remote_path] = std::move(copy); - ++copies_to[object_to.remote_path]; - } - - std::map copiesByDestination() const - { - std::lock_guard lock(mutex); - return copies_to; - } - -private: - struct Entry - { - std::string bytes; - uint64_t generation; - }; - - std::string tokenOf(const Entry & entry) const - { - if (content_derived_etags) - return getHexUIntLowercase(sipHash128(entry.bytes.data(), entry.bytes.size())); - return std::to_string(entry.generation); - } - - /// The token as the SDK's ETag field carries it: quoted for a GCS generation. - std::string transportTokenOf(const Entry & entry) const - { - return content_derived_etags ? tokenOf(entry) : "\"" + tokenOf(entry) + "\""; - } - - /// Buffers the whole body in memory (like `FakeStagingSink` above) so the entry is committed exactly - /// once, at `finalize`, and only after the precondition has been checked. - class ConditionalWriteBuffer final : public DB::WriteBufferFromFileBase - { - public: - ConditionalWriteBuffer(FakeGenerationObjectStorage & storage_, std::string key_, - std::string if_none_match_, std::string if_match_) - : DB::WriteBufferFromFileBase(/*buf_size=*/8192, nullptr, 0) - , storage(storage_), key(std::move(key_)) - , if_none_match(std::move(if_none_match_)), if_match(std::move(if_match_)) - { - } - - void sync() override {} - std::string getFileName() const override { return key; } - - /// The write response's own incarnation, quoted the way the SDK's ETag field carries a GCS - /// generation across the HTTP boundary -- the backend is what strips that transport syntax. - std::optional getResultObjectETag() const override { return committed_generation; } - - protected: - void nextImpl() override - { - if (!offset()) - return; - buffered.append(working_buffer.begin(), offset()); - } - - void finalizeImpl() override - { - next(); - committed_generation = storage.commitConditionalWrite(key, buffered, if_none_match, if_match); - } - - private: - FakeGenerationObjectStorage & storage; - std::string key; - std::string if_none_match; - std::string if_match; - std::string buffered; - std::optional committed_generation; - }; - - mutable std::mutex mutex; - std::map objects; - std::map copies_to; - uint64_t next_generation = 1; -}; - -std::shared_ptr makeFakeGenerationObjectStorageForTest() -{ - static std::atomic counter{0}; - const auto unique = std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)); - const auto root = (std::filesystem::temp_directory_path() / ("cas_s3_staging_generation_" + unique)).string(); - - std::error_code ec; - std::filesystem::remove_all(root, ec); - std::filesystem::create_directories(root, ec); - - DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); - return DB::Cas::tests::ownedByDirectory(std::make_shared(std::move(settings)), root); -} - -} +using DB::Cas::tests::FakeGenerationObjectStorage; +using DB::Cas::tests::makeFakeGenerationObjectStorageForTest; /// A store whose iterator does not page (the fallback `IObjectStorage::iterate` lists `max_keys` keys /// once and ends) must still let a page-sized list report that more keys follow. A page that ended From 88a7ed36173046d6f852c6952fc47800873ed58c Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 00:14:50 +0100 Subject: [PATCH 24/47] Test the CAS upload guard on a recording object storage Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- src/Disks/tests/gtest_cas_upload_guard.cpp | 720 +++++++++++++++++++++ 1 file changed, 720 insertions(+) create mode 100644 src/Disks/tests/gtest_cas_upload_guard.cpp diff --git a/src/Disks/tests/gtest_cas_upload_guard.cpp b/src/Disks/tests/gtest_cas_upload_guard.cpp new file mode 100644 index 0000000000000..714b04d1b15b7 --- /dev/null +++ b/src/Disks/tests/gtest_cas_upload_guard.cpp @@ -0,0 +1,720 @@ +#include + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "config.h" +#if USE_AWS_S3 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#endif + +namespace DB::ErrorCodes +{ + extern const int QUERY_WAS_CANCELLED; +} + +using namespace DB; +using namespace DB::Cas; +using DB::Cas::tests::CasKillableQuery; +using DB::Cas::tests::onKillableQueryThread; +using DB::Cas::tests::onThread; + +namespace +{ + +/// Records what reaches it and reports fixed limits. +class RecordingThrottler final : public IThrottler +{ +public: + bool throttle(size_t amount_, size_t max_block_ns_) override + { + amount += amount_; + max_block_ns = max_block_ns_; + ++calls; + return true; + } + + bool isThrottling() const override { return true; } + Int64 getAvailable() override { return 123; } + UInt64 getMaxSpeed() const override { return 456; } + UInt64 getMaxBurst() const override { return 789; } + + size_t amount = 0; + size_t max_block_ns = 0; + size_t calls = 0; +}; + +int codeOf(const std::function & call) +{ + try + { + call(); + } + catch (const Exception & e) + { + return e.code(); + } + return 0; +} + +} + +TEST(CASUploadGuard, GuardForwardsAndStops) +{ + auto limiter = std::make_shared(); + + EXPECT_EQ(makeUploadGuard(limiter, {}), limiter); + EXPECT_EQ(makeUploadGuard(nullptr, {}), nullptr); + + std::vector inner_calls_at_stop; + auto guard = makeUploadGuard(limiter, [&] { inner_calls_at_stop.push_back(limiter->calls); }); + ASSERT_NE(guard, limiter); + EXPECT_TRUE(guard->throttle(32768, 20'000'000'000)); + EXPECT_EQ(limiter->amount, 32768u); + EXPECT_EQ(limiter->max_block_ns, 20'000'000'000u); + EXPECT_EQ(inner_calls_at_stop, (std::vector{0, 1})); + EXPECT_TRUE(guard->isThrottling()); + EXPECT_EQ(guard->getAvailable(), 123); + EXPECT_EQ(guard->getMaxSpeed(), 456u); + EXPECT_EQ(guard->getMaxBurst(), 789u); + + std::atomic stopped{false}; + auto stopping = makeUploadGuard(limiter, [&] + { + if (stopped) + throw Exception(ErrorCodes::QUERY_WAS_CANCELLED, "stopped"); + }); + stopped = true; + const size_t calls_before = limiter->calls; + EXPECT_EQ(codeOf([&] { stopping->throttle(1, 1); }), ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(limiter->calls, calls_before) << "the stop before the inner call must keep the bytes from the limiter"; + + stopped = false; + auto stop_after = makeUploadGuard(limiter, [&, first = true]() mutable + { + if (!std::exchange(first, false)) + throw Exception(ErrorCodes::QUERY_WAS_CANCELLED, "stopped"); + }); + EXPECT_EQ(codeOf([&] { stop_after->throttle(1, 1); }), ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(limiter->calls, calls_before + 1) << "the stop after the inner call runs once the limiter was charged"; +} + +TEST(CASUploadGuard, AStopOnlyGuardStopsAndReportsNoLimit) +{ + onKillableQueryThread([](CasKillableQuery & query) + { + auto guard = makeUploadGuard(nullptr, uploadStopCheck()); + ASSERT_NE(guard, nullptr); + EXPECT_FALSE(guard->throttle(32768, 1)); + EXPECT_FALSE(guard->isThrottling()); + EXPECT_EQ(guard->getAvailable(), std::numeric_limits::max()); + EXPECT_EQ(guard->getMaxSpeed(), 0u); + EXPECT_EQ(guard->getMaxBurst(), 0u); + + query.kill(); + EXPECT_EQ(codeOf([&] { guard->throttle(32768, 1); }), ErrorCodes::QUERY_WAS_CANCELLED); + }); +} + +TEST(CASUploadGuard, StopCheckIsEmptyWhereWorkMustFinish) +{ + onKillableQueryThread([](CasKillableQuery &) + { + EXPECT_TRUE(uploadStopCheck()); + { + auto owed = OwnerScope::owed(); + EXPECT_FALSE(uploadStopCheck()); + } + { + auto shared = OwnerScope::shared(); + EXPECT_FALSE(uploadStopCheck()); + } + EXPECT_TRUE(uploadStopCheck()); + }); + + onThread(true, [] { EXPECT_FALSE(uploadStopCheck()) << "a thread with no group has no query to stop"; }); + onThread(false, [] { EXPECT_FALSE(uploadStopCheck()); }); +} + +TEST(CASUploadGuard, StopCheckCarriesTheQueryVerdictAndKeepsTheGroup) +{ + std::function check; + std::weak_ptr group; + + onKillableQueryThread([&](CasKillableQuery & query) + { + check = uploadStopCheck(); + ASSERT_TRUE(check); + group = query.group; + + onThread(false, [&] { EXPECT_EQ(codeOf(check), 0); }); + query.kill(); + onThread(false, [&] { EXPECT_EQ(codeOf(check), ErrorCodes::QUERY_WAS_CANCELLED); }); + }); + + EXPECT_FALSE(group.expired()) << "the check keeps the group after the fixture released its references"; + check = nullptr; + EXPECT_TRUE(group.expired()); +} + +TEST(CASUploadGuard, AMergeThreadGroupGetsAStopThatNeverThrows) +{ + onThread(true, [] + { + CurrentThread::attachToGroup(ThreadGroup::createForMergeMutate(getContext().context)); + const std::function stop = uploadStopCheck(); + if (stop) + EXPECT_NO_THROW(stop()); + + auto limiter = std::make_shared(); + auto guard = makeUploadGuard(limiter, stop); + EXPECT_NO_THROW(guard->throttle(32768, 0)); + EXPECT_EQ(limiter->amount, 32768u); + }); +} + +TEST(CASUploadGuard, BodyGuardScopeMatchesTheExactKeyOnly) +{ + auto outer = std::make_shared(); + auto inner = std::make_shared(); + + EXPECT_EQ(BodyGuardScope::forKey("a"), nullptr); + { + BodyGuardScope scope("a", outer); + EXPECT_EQ(BodyGuardScope::forKey("a"), outer); + EXPECT_EQ(BodyGuardScope::forKey("b"), nullptr); + EXPECT_EQ(BodyGuardScope::forKey("a/"), nullptr); + EXPECT_EQ(BodyGuardScope::forKey(""), nullptr); + { + BodyGuardScope nested("b", inner); + EXPECT_EQ(BodyGuardScope::forKey("b"), inner); + EXPECT_EQ(BodyGuardScope::forKey("a"), nullptr); + } + EXPECT_EQ(BodyGuardScope::forKey("a"), outer); + EXPECT_EQ(BodyGuardScope::forKey("b"), nullptr); + } + EXPECT_EQ(BodyGuardScope::forKey("a"), nullptr); + + onThread(false, [&] + { + BodyGuardScope scope("a", outer); + }); + EXPECT_EQ(BodyGuardScope::forKey("a"), nullptr); +} + +TEST(CASUploadGuard, UploadStopScopeRestoresItsPredecessor) +{ + EXPECT_FALSE(UploadStopScope::current()); + int outer_calls = 0; + int inner_calls = 0; + { + UploadStopScope outer([&] { ++outer_calls; }); + UploadStopScope::current()(); + { + UploadStopScope inner([&] { ++inner_calls; }); + UploadStopScope::current()(); + } + UploadStopScope::current()(); + { + UploadStopScope empty({}); + EXPECT_FALSE(UploadStopScope::current()); + } + EXPECT_TRUE(UploadStopScope::current()); + } + EXPECT_FALSE(UploadStopScope::current()); + EXPECT_EQ(outer_calls, 2); + EXPECT_EQ(inner_calls, 1); + + UploadStopScope here([] {}); + onThread(false, [] { EXPECT_FALSE(UploadStopScope::current()) << "the marker is thread-scoped"; }); +} + +#if USE_AWS_S3 + +namespace DB::ContentAddressedSetting +{ + extern const ContentAddressedSettingsString staging_backend; +} + +namespace CurrentMetrics +{ + extern const Metric LocalThread; + extern const Metric LocalThreadActive; + extern const Metric LocalThreadScheduled; +} + +namespace +{ + +using DB::Cas::tests::FakeGenerationObjectStorage; +using DB::Cas::tests::makeFakeGenerationObjectStorageForTest; +using WriteRecords = std::vector>; + +const String kTable = "a11/a11a11a1-1111-4111-8111-111111111111/"; + +/// A mount of `object_storage` that stages blob bodies in local files, so each body is streamed through `writeObject` +/// at publication; with `s3_staging` it stages them in the store and publishes them by a server-side copy. +std::shared_ptr mountOver( + const ObjectStoragePtr & object_storage, const String & server_root_id, bool s3_staging = false) +{ + static std::atomic counter{0}; + const auto scratch = std::filesystem::temp_directory_path() + / ("cas_upload_guard_" + server_root_id + "_" + std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1))); + auto settings = DB::Cas::tests::makeSettingsForTest(server_root_id, scratch); + if (s3_staging) + { + settings[ContentAddressedSetting::staging_backend] = "s3"; + settings.validate(); + } + auto mount = DB::Cas::tests::ownedByDirectory( + std::make_shared(object_storage, "pool", "srv1", /*disk_name_=*/"", /*context_=*/nullptr, settings), + scratch); + mount->startup(); + return mount; +} + +void writeWith(IMetadataTransaction & tx, const String & path, const String & bytes, ThrottlerPtr limiter) +{ + WriteSettings settings; + settings.remote_throttler = std::move(limiter); + auto buf = dynamic_cast(tx).writeFile(path, 65536, WriteMode::Rewrite, settings); + buf->write(bytes.data(), bytes.size()); + buf->finalize(); +} + +String bodyKeyOf(const PoolPtr & pool, const String & payload) +{ + return pool->layout().blobKey(poolContentHash(pool->writeAlgo(), payload)); +} + +/// The streamed writes of `key`, copies excluded. +WriteRecords writesOf(const FakeGenerationObjectStorage & storage, const String & key) +{ + WriteRecords result; + for (const auto & record : storage.records()) + if (record->key == key && !record->copy) + result.push_back(record); + return result; +} + +/// The throttler of the one streamed body of `payload`. +ThrottlerPtr bodyThrottlerOf(const FakeGenerationObjectStorage & storage, const PoolPtr & pool, const String & payload) +{ + const auto writes = writesOf(storage, bodyKeyOf(pool, payload)); + if (writes.size() != 1) + throw std::runtime_error(fmt::format("expected one body write of {}, got {}", bodyKeyOf(pool, payload), writes.size())); + return writes.front()->settings.remote_throttler; +} + +/// Calls `throttler` as a socket does at a refill and checks that `target` alone among `limiters` was charged. +void expectReachesOnly(const ThrottlerPtr & throttler, const RecordingThrottler & target, const std::vector & limiters) +{ + ASSERT_NE(throttler, nullptr) << "the body carries no throttler"; + std::vector before; + for (const auto * limiter : limiters) + before.push_back(limiter->amount); + EXPECT_EQ(codeOf([&] { throttler->throttle(32768, 0); }), 0); + for (size_t i = 0; i < limiters.size(); ++i) + EXPECT_EQ(limiters[i]->amount - before[i], limiters[i] == &target ? 32768u : 0u) << "limiter #" << i; +} + +/// Sets the query's `max_remote_write_network_bandwidth` to one byte per second and returns the limiter that the +/// calling thread's writes get from it. +ThrottlerPtr limitQueryRemoteWrites(CasKillableQuery & query) +{ + query.context->setSetting("max_remote_write_network_bandwidth", Field(UInt64{1})); + return DB::getWriteSettings().remote_throttler; +} + +bool isManifestKey(const PoolPtr & pool, const String & key) +{ + return key.starts_with(pool->layout().casManifestsPrefix()); +} + +struct BoundedEvent +{ + std::mutex mutex; + std::condition_variable cv; + bool fired = false; + + void fire() + { + { + std::lock_guard lock(mutex); + fired = true; + } + cv.notify_all(); + } + + bool wait(std::chrono::seconds bound) + { + std::unique_lock lock(mutex); + return cv.wait_for(lock, bound, [&] { return fired; }); + } +}; + +/// A precommitted build of `part_path`'s part, which every publication of `uploadBlobDetached` requires. +PartWriteTxnPtr precommittedBuild(ContentAddressedMetadataStorage & mount, const String & part_path) +{ + const auto route = mount.route(*parsePartFilePath(part_path + "data.bin")); + PartWriteInfo info; + info.intended_ref = route->ns.string() + "/" + route->ref; + PartWriteTxnPtr build = mount.poolForTest()->beginPartWrite(std::move(info)); + const String seed = "seed-manifest-" + part_path; + const ManifestId id = build->stageManifest({DB::Cas::tests::blobEntryFor("seed.bin", DB::Cas::tests::u128Of(seed), seed.size())}); + build->precommitAdd(route->ns, route->ref, id); + return build; +} + +BlobUploadRequest requestFor(const PoolPtr & pool, const String & payload, ThrottlerPtr limiter) +{ + BlobUploadRequest request{poolContentHash(pool->writeAlgo(), payload), BlobSource::fromString(payload), payload.size()}; + request.source.remote_throttler = std::move(limiter); + return request; +} + +std::unique_ptr makeWorkers(size_t size) +{ + return std::make_unique( + CurrentMetrics::LocalThread, CurrentMetrics::LocalThreadActive, CurrentMetrics::LocalThreadScheduled, size); +} + +} + +TEST(CASUploadGuard, EachBodyCarriesItsOwnLimiterAndTheStopOnlyInANewBuild) +{ + enum class Arm : uint8_t { NewBuild, CommittedPart, Owed, Shared }; + for (const Arm arm : {Arm::NewBuild, Arm::CommittedPart, Arm::Owed, Arm::Shared}) + { + const char * name = arm == Arm::NewBuild ? "new build" + : arm == Arm::CommittedPart ? "write onto a committed part" + : arm == Arm::Owed ? "inside owed" + : "inside shared"; + SCOPED_TRACE(name); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, fmt::format("mountGuardBodies{}", static_cast(arm))); + const String part = kTable + "all_1_1_0/"; + if (arm == Arm::CommittedPart) + { + auto tx = mount->createTransaction(); + writeWith(*tx, part + "count.txt", "1", nullptr); + tx->commit(NoCommitOptions{}); + } + + const String payload_a = fmt::format("guard bodies {}: the first file", name); + const String payload_b = fmt::format("guard bodies {}: the second file", name); + auto limiter_a = std::make_shared(); + auto limiter_b = std::make_shared(); + const std::vector limiters{limiter_a.get(), limiter_b.get()}; + const size_t records_before_query = storage->records().size(); + std::set manifests; + + onKillableQueryThread([&](CasKillableQuery & query) + { + SCOPED_TRACE(name); + ASSERT_NE(limitQueryRemoteWrites(query), nullptr) << "the query has no remote write limiter"; + { + std::optional owner; + if (arm == Arm::Owed) + owner.emplace(OwnerScope::owed()); + if (arm == Arm::Shared) + owner.emplace(OwnerScope::shared()); + auto tx = mount->createTransaction(); + writeWith(*tx, part + "a.bin", payload_a, limiter_a); + writeWith(*tx, part + "b.bin", payload_b, limiter_b); + tx->commit(NoCommitOptions{}); + } + + const ThrottlerPtr body_a = bodyThrottlerOf(*storage, mount->poolForTest(), payload_a); + const ThrottlerPtr body_b = bodyThrottlerOf(*storage, mount->poolForTest(), payload_b); + expectReachesOnly(body_a, *limiter_a, limiters); + expectReachesOnly(body_b, *limiter_b, limiters); + + const auto records = storage->records(); + for (size_t i = records_before_query; i < records.size(); ++i) + if (!records[i]->copy && isManifestKey(mount->poolForTest(), records[i]->key)) + manifests.insert(records[i].get()); + ASSERT_FALSE(manifests.empty()) << "the commit wrote no manifest"; + for (const auto * manifest : manifests) + EXPECT_EQ(manifest->settings.remote_throttler, nullptr) << "the manifest " << manifest->key << " carries a throttler"; + + query.kill(); + const int expected = arm == Arm::NewBuild ? ErrorCodes::QUERY_WAS_CANCELLED : 0; + ASSERT_NE(body_a, nullptr); + ASSERT_NE(body_b, nullptr); + EXPECT_EQ(codeOf([&] { body_a->throttle(32768, 0); }), expected); + EXPECT_EQ(codeOf([&] { body_b->throttle(32768, 0); }), expected); + }); + + const auto pool = mount->poolForTest(); + const std::set bodies{bodyKeyOf(pool, payload_a), bodyKeyOf(pool, payload_b)}; + size_t others = 0; + for (const auto & record : storage->records()) + { + if (record->copy || bodies.contains(record->key) || manifests.contains(record.get())) + continue; + ++others; + EXPECT_EQ(record->settings.remote_throttler, nullptr) << "a write of " << record->key << " carries a throttler"; + } + EXPECT_GT(others, 0u) << "the commit's other writes were not recorded"; + } +} + +TEST(CASUploadGuard, AServerSideCopyOfAStagedBodyCarriesNoThrottler) +{ + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, "mountGuardCopy", /*s3_staging=*/true); + const String payload = "guard copy: a staged body"; + auto limiter = std::make_shared(); + + onKillableQueryThread([&](CasKillableQuery &) + { + auto tx = mount->createTransaction(); + writeWith(*tx, kTable + "all_1_1_0/data.bin", payload, limiter); + tx->commit(NoCommitOptions{}); + }); + + const String body = bodyKeyOf(mount->poolForTest(), payload); + size_t copies = 0; + for (const auto & record : storage->records()) + { + if (!record->copy || record->key != body) + continue; + ++copies; + EXPECT_EQ(record->settings.remote_throttler, nullptr); + } + EXPECT_EQ(copies, 1u) << "the publication of a staged body was not a server-side copy"; +} + +TEST(CASUploadGuard, TheFanOutCarriesTheStopToItsWorkers) +{ + constexpr auto watchdog = std::chrono::seconds(30); + { + SCOPED_TRACE("a query killed while a worker sends a body"); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, "mountGuardFanoutStop"); + const auto pool = mount->poolForTest(); + const std::vector payloads{"guard fan-out stop: one", "guard fan-out stop: two", "guard fan-out stop: three"}; + const String stopped = bodyKeyOf(pool, payloads.front()); + + /// The hooks live in the storage, which the mount's teardown still writes through after this scope's locals + /// are gone, so they hold what they use. + auto in_body = std::make_shared(); + auto killed = std::make_shared(); + storage->throttle_while_writing = [stopped](const String & key) { return key == stopped; }; + storage->before_throttle = [in_body, killed, watchdog](const String &) + { + in_body->fire(); + EXPECT_TRUE(killed->wait(watchdog)); + }; + + std::atomic query_ptr{nullptr}; + int code = 0; + std::exception_ptr setup_error; + std::thread publisher([&] + { + try + { + ThreadStatus thread_status; + CasKillableQuery query(getContext().context); + query_ptr = &query; + auto build = precommittedBuild(*mount, kTable + "all_2_2_0/"); + std::vector requests; + for (const auto & payload : payloads) + requests.push_back(requestFor(pool, payload, std::make_shared())); + auto workers = makeWorkers(requests.size()); + UploadStopScope scope(uploadStopCheck()); + code = codeOf([&] { fanOutBlobUploads(*build, requests, *workers); }); + } + catch (...) + { + setup_error = std::current_exception(); + } + }); + + const bool entered = in_body->wait(watchdog); + EXPECT_TRUE(entered) << "no worker sent the body of the stopped blob"; + if (entered) + query_ptr.load()->kill(); + killed->fire(); + publisher.join(); + ASSERT_FALSE(setup_error) << "the publisher failed: " << getExceptionMessage(setup_error, false); + + const auto writes = writesOf(*storage, stopped); + ASSERT_EQ(writes.size(), 1u) << "the stopped blob was published again"; + ASSERT_TRUE(writes.front()->throttled) << "the stopped body carries no throttler"; + const std::exception_ptr throttle_error = writes.front()->throttle_error; + EXPECT_EQ(codeOf([&] { if (throttle_error) std::rethrow_exception(throttle_error); }), ErrorCodes::QUERY_WAS_CANCELLED) + << "the worker's body did not carry the query's stop"; + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED); + } +} + +TEST(CASUploadGuard, TheLimiterFollowsTheFile) +{ + const String source = kTable + "all_1_1_0/"; + const String destination = kTable + "all_2_2_0/"; + enum class Arm : uint8_t { Hardlink, Move }; + for (const Arm arm : {Arm::Hardlink, Arm::Move}) + { + const char * name = arm == Arm::Hardlink ? "hardlink" : "move"; + SCOPED_TRACE(name); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, fmt::format("mountGuardFollows{}", static_cast(arm))); + const String payload = fmt::format("guard follows the file: {}", name); + auto limiter = std::make_shared(); + + onKillableQueryThread([&](CasKillableQuery &) + { + auto tx = mount->createTransaction(); + writeWith(*tx, source + "data.bin", payload, limiter); + writeWith(*tx, source + "count.txt", "1", nullptr); + if (arm == Arm::Hardlink) + { + tx->createHardLink(source + "data.bin", destination + "data.bin"); + tx->unlinkFile(source + "data.bin", /*if_exists=*/false, /*should_remove_objects=*/false); + } + else + tx->moveFile(source + "data.bin", destination + "data.bin"); + tx->commit(NoCommitOptions{}); + }); + + ASSERT_FALSE(mount->existsFile(source + "data.bin")) << "the source part still names the body"; + ASSERT_TRUE(mount->existsFile(destination + "data.bin")); + expectReachesOnly(bodyThrottlerOf(*storage, mount->poolForTest(), payload), *limiter, {limiter.get()}); + } + + { + SCOPED_TRACE("equal bytes written twice into one part"); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, "mountGuardFollowsTwice"); + const String payload = "guard follows the file: equal bytes"; + auto limiter_a = std::make_shared(); + auto limiter_b = std::make_shared(); + + onKillableQueryThread([&](CasKillableQuery &) + { + auto tx = mount->createTransaction(); + writeWith(*tx, source + "a.bin", payload, limiter_a); + writeWith(*tx, source + "b.bin", payload, limiter_b); + tx->commit(NoCommitOptions{}); + }); + + expectReachesOnly(bodyThrottlerOf(*storage, mount->poolForTest(), payload), *limiter_a, {limiter_a.get(), limiter_b.get()}); + } + + { + SCOPED_TRACE("an inline candidate above the inline cap"); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, "mountGuardFollowsOversizedInline"); + /// One byte above `INLINE_CAP` of `ContentAddressedTransaction.cpp`, so the file spills to a blob. + const String payload(1024 * 1024 + 1, 'c'); + auto limiter = std::make_shared(); + + onKillableQueryThread([&](CasKillableQuery &) + { + auto tx = mount->createTransaction(); + writeWith(*tx, source + "columns.txt", payload, limiter); + tx->commit(NoCommitOptions{}); + }); + + expectReachesOnly(bodyThrottlerOf(*storage, mount->poolForTest(), payload), *limiter, {limiter.get()}); + } +} + +TEST(CASUploadGuard, TheStagingSinkCarriesTheGuardAndKeepsItsDefaults) +{ + enum class Arm : uint8_t { NewBuild, CommittedPart }; + for (const Arm arm : {Arm::NewBuild, Arm::CommittedPart}) + { + const char * name = arm == Arm::NewBuild ? "new build" : "data file written into a committed part"; + SCOPED_TRACE(name); + auto storage = makeFakeGenerationObjectStorageForTest(); + auto mount = mountOver(storage, fmt::format("mountGuardSink{}", static_cast(arm)), /*s3_staging=*/true); + const String part = kTable + "all_1_1_0/"; + if (arm == Arm::CommittedPart) + { + auto tx = mount->createTransaction(); + writeWith(*tx, part + "count.txt", "1", nullptr); + tx->commit(NoCommitOptions{}); + } + const String sink_prefix = mount->stagingKeyPrefix(); + const auto sinksSince = [&](size_t first) + { + WriteRecords sinks; + const auto records = storage->records(); + for (size_t i = first; i < records.size(); ++i) + if (!records[i]->copy && records[i]->key.starts_with(sink_prefix)) + sinks.push_back(records[i]); + return sinks; + }; + + auto limiter = std::make_shared(); + onKillableQueryThread([&](CasKillableQuery & query) + { + SCOPED_TRACE(name); + auto tx = mount->createTransaction(); + + const size_t before_txn_version = storage->records().size(); + writeWith(*tx, part + "txn_version.txt", "version: 1\n", limiter); + EXPECT_TRUE(sinksSince(before_txn_version).empty()) << "txn_version.txt opened a staging sink"; + + WriteSettings settings; + settings.remote_throttler = limiter; + settings.enable_filesystem_cache_log = true; + const size_t before_data = storage->records().size(); + { + auto buf = dynamic_cast(*tx).writeFile( + part + "data.bin", 65536, WriteMode::Rewrite, settings); + const String payload = fmt::format("guard sink: {}", name); + buf->write(payload.data(), payload.size()); + buf->finalize(); + } + const auto sinks = sinksSince(before_data); + ASSERT_EQ(sinks.size(), 1u) << "the data file did not go through one staging sink"; + + WriteSettings stripped = sinks.front()->settings; + stripped.remote_throttler = nullptr; + EXPECT_TRUE(stripped == WriteSettings{}) << "the sink's settings differ from the defaults beyond the throttler"; + const ThrottlerPtr sink_throttler = sinks.front()->settings.remote_throttler; + expectReachesOnly(sink_throttler, *limiter, {limiter.get()}); + tx->commit(NoCommitOptions{}); + + query.kill(); + ASSERT_NE(sink_throttler, nullptr); + EXPECT_EQ(codeOf([&] { sink_throttler->throttle(32768, 0); }), ErrorCodes::QUERY_WAS_CANCELLED); + }); + } +} + +#endif From 45548c66df1ee869870d51367335763605900cf0 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 00:14:50 +0100 Subject: [PATCH 25/47] Test paced and stopped CAS uploads on real servers Four tests in `test_cas_request_window`: a paced upload is stopped in flight by `KILL QUERY` and by `max_execution_time` with local and with S3 staging; a server-wide limit paces uploads while the mount keeps renewing; a killed implicit transaction rolls back during a paced upload; SIGTERM during an upload ends in an orderly shutdown. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- .../test_cas_request_window/configs/guard.xml | 39 +++ .../configs/storage_conf_stop.xml | 28 ++ .../test_cas_request_window/test.py | 268 +++++++++++++++++- 3 files changed, 331 insertions(+), 4 deletions(-) create mode 100644 tests/integration/test_cas_request_window/configs/guard.xml diff --git a/tests/integration/test_cas_request_window/configs/guard.xml b/tests/integration/test_cas_request_window/configs/guard.xml new file mode 100644 index 0000000000000..4590c24737d97 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/guard.xml @@ -0,0 +1,39 @@ + + + 1000000 + + 30 + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-guard + http://rustfs1:11121/test/cas_request_guard/ + clickhouse + clickhouse + false + + 500 + 1000 + 5000 + 10000 + 2000 + 500 + + + + + +
+ disk_cas_guard +
+
+
+
+
+
diff --git a/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml b/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml index 1e57ebc461a5f..ffb893666d4a3 100644 --- a/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml +++ b/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml @@ -24,6 +24,27 @@ 2000 500 + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-stop-s3 + http://s3proxy:11121/test/cas_request_stop_s3/ + clickhouse + clickhouse + s3 + false + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 +
@@ -33,6 +54,13 @@ + + +
+ disk_cas_stop_s3 +
+
+
diff --git a/tests/integration/test_cas_request_window/test.py b/tests/integration/test_cas_request_window/test.py index 124ce4d0d64db..902f8984e9689 100644 --- a/tests/integration/test_cas_request_window/test.py +++ b/tests/integration/test_cas_request_window/test.py @@ -12,6 +12,10 @@ there is removed at once (configs/drop_delay.xml). It runs with Keeper and transactions enabled (configs/transactions.xml), and uploads a part's blobs one at a time (configs/blob_upload_serial.xml). +The upload tests stop a part body that `max_remote_write_network_bandwidth` paces, on `disk_cas_stop` (local +staging) and `disk_cas_stop_s3` (S3 staging). `node_guard` (configs/guard.xml) paces every body by a server-wide +limit, pins its mount lease and waits 30 s for connections at shutdown; only the upload guard tests run there. + The GC test runs on `node_gc` (configs/storage_conf_gc.xml): the same timing and a one-hour GC interval. A manual round never takes the GC lease from another process, and a restart leaves the lease with the previous one, so this server is never restarted. @@ -21,6 +25,7 @@ """ import json +import logging import os import re import subprocess @@ -60,14 +65,16 @@ def _control(url, path, patch=None): return json.loads(response.read().decode()) -def _wait_until(probe, timeout): +def _wait_until(probe, timeout, describe=None): + """Polls `probe` until it returns a true value. On a timeout the error carries `describe()`, when given.""" end = time.monotonic() + timeout while time.monotonic() < end: result = probe() if result: return result time.sleep(0.2) - raise AssertionError("condition did not become true within {}s".format(timeout)) + raise AssertionError("condition did not become true within {}s{}".format( + timeout, "" if describe is None else ": " + str(describe()))) @pytest.fixture(scope="module") @@ -82,6 +89,7 @@ def node(): "configs/transactions.xml", "configs/blob_upload_serial.xml"], with_rustfs=True, with_zookeeper=True, stay_alive=True) cluster.add_instance("node_gc", main_configs=["configs/storage_conf_gc.xml"], with_rustfs=True) + cluster.add_instance("node_guard", main_configs=["configs/guard.xml"], with_rustfs=True, stay_alive=True) cluster.base_cmd.extend(["--file", os.path.join(os.path.dirname(__file__), "docker_compose_proxy.yml")]) try: cluster.start() @@ -103,6 +111,11 @@ def node_gc(node): return cluster.instances["node_gc"] +@pytest.fixture(scope="module") +def node_guard(node): + return cluster.instances["node_guard"] + + def _drop_all_tables(instance): for name in instance.query("SELECT table FROM system.detached_tables WHERE database = 'default'").split(): instance.query("ATTACH TABLE default.`{}`".format(name)) @@ -111,11 +124,11 @@ def _drop_all_tables(instance): @pytest.fixture(autouse=True) -def clean_state(node, node_stop, node_gc): +def clean_state(node, node_stop, node_gc, node_guard): _control(cluster.proxy_url, "/config", {"reset": True}) yield _control(cluster.proxy_url, "/config", {"reset": True}) - for instance in (node, node_stop, node_gc): + for instance in (node, node_stop, node_gc, node_guard): _drop_all_tables(instance) @@ -986,3 +999,250 @@ def appended_through_terminal(): # The retried removal may seal the previous writer epoch first. appended = _wait_until(appended_through_terminal, timeout=60) assert all(r["status"] == 200 for r in appended), _brief(appended) + + +# A fresh incompressible body per insert, so the store holds no copy to reuse. At `PACED_LIMIT` it needs 120 s. +BODY_BYTES = 60_000_000 +PACED_LIMIT = 500_000 +PACED_INSERT = "INSERT INTO {} SELECT 1, randomString(60000000)" +# Above the one-second burst of the throttler and far below half of the body. +PROGRESS_BYTES = 4_000_000 +STOP_BOUND_S = 20 +# A stop that is not honoured waits for the rest of the body, about 100 s at `PACED_LIMIT`. +UNSTOPPED_WAIT_S = 300 +GUARD_POLICY = "cas_guard" +GUARD_DISK = "disk_cas_guard" +# `configs/guard.xml`. +SERVER_LIMIT = 1_000_000 +GUARD_LEASE_TTL_S = 10 +GUARD_RENEW_PERIOD_S = 2 + + +def _paced(settings=None): + return dict({"max_remote_write_network_bandwidth": PACED_LIMIT, "async_insert": 0}, **(settings or {})) + + +def _query_throttled_bytes(node, query_id): + """The bytes that the query's own write limit let through so far. None while the query has no row in + `system.processes`: before the server registered it and after it ended.""" + value = node.http_query("SELECT ProfileEvents['QueryRemoteWriteThrottlerBytes'] FROM system.processes " + "WHERE query_id = '{}'".format(query_id)).strip() + return int(value) if value else None + + +def _wait_body_going_out(node, request, query_id, baseline, timeout=180): + """Waits until the query's limit let `PROGRESS_BYTES` through beyond `baseline`, with most of the body left to + send. Returns the byte count then.""" + end = time.monotonic() + timeout + last = None + while True: + # No row before the server registers the query, and none after it ended. + sent = _query_throttled_bytes(node, query_id) + if sent is not None: + last = sent + if sent >= baseline + PROGRESS_BYTES: + break + assert request.process.poll() is None, \ + "the query ended before its body went out paced: {} bytes over the limit when last seen".format(last) + assert time.monotonic() < end, "{} bytes over the limit after {} s".format(last, timeout) + time.sleep(0.2) + assert sent - baseline <= BODY_BYTES // 2, (baseline, sent) + return sent + + +def _kill_and_time(node, request, query_id): + """Kills the query and returns the seconds from before the kill to the query's end.""" + started = time.monotonic() + node.http_query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id), timeout=UNSTOPPED_WAIT_S) + _wait_until(lambda: request.process.poll() is not None, timeout=UNSTOPPED_WAIT_S) + return time.monotonic() - started + + +@pytest.mark.parametrize("stop", ["kill", "timeout"]) +@pytest.mark.parametrize("staging", ["local", "s3"]) +def test_upload_is_stopped_in_flight(node_stop, staging, stop): + """A query stopped while its part body goes out paced by its write limit ends within `STOP_BOUND_S`: from before + `KILL QUERY`, or from the `max_execution_time` deadline. No part is committed, and the same insert without a limit + then succeeds. With S3 staging the body goes out while the part file is written.""" + name = "paced_{}_{}".format(staging, stop) + node_stop.query("CREATE TABLE {} (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(name, STOP_POLICY if staging == "local" else "cas_stop_s3")) + query_id = name + "_insert" + # The gate passes about 8 s after the upload starts. At the deadline at most 30.5 MB went out, so the rest of + # the body still needs about 59 s. + timeout = {"max_execution_time": 60, "timeout_overflow_mode": "throw"} if stop == "timeout" else {} + submitted = time.monotonic() + request = node_stop.get_query_request(PACED_INSERT.format(name), query_id=query_id, settings=_paced(timeout), + timeout=UNSTOPPED_WAIT_S + 60) + sent = _wait_body_going_out(node_stop, request, query_id, baseline=0) + gated = time.monotonic() - submitted + if stop == "kill": + elapsed = _kill_and_time(node_stop, request, query_id) + code = 394 + else: + deadline = submitted + timeout["max_execution_time"] + assert time.monotonic() < deadline, "the gate passed {:.1f} s after submission, past the {} s deadline".format( + gated, timeout["max_execution_time"]) + _wait_until(lambda: request.process.poll() is not None, timeout=UNSTOPPED_WAIT_S) + elapsed = time.monotonic() - deadline + code = 159 + logging.info("%s: %d bytes paced at the gate %.1f s after submission, ended %.1f s after the stop", + name, sent, gated, elapsed) + assert elapsed <= STOP_BOUND_S, "ended {:.1f} s after the stop".format(elapsed) + error = request.get_error() + assert re.search(r"Code: {}\b".format(code), error), error + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "0" + + node_stop.query(PACED_INSERT.format(name), settings={"async_insert": 0}, timeout=120) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "1" + + +def _server_throttled_bytes(node): + return _events(node, "RemoteWriteThrottlerBytes") + + +def _guard_mount(node): + rows = node.query("SELECT writer_epoch, renewal_sequence FROM system.cas_mounts WHERE disk = '{}' " + "AND server_root_id = 'itest-cas-guard'".format(GUARD_DISK)).strip().splitlines() + assert len(rows) == 1, rows + return tuple(int(v) for v in rows[0].split("\t")) + + +def test_limit_applies_and_the_mount_stays_live(node_guard): + """Mount renewals pass no bytes through the server-wide limit. Concurrent inserts of distinct bodies under that + limit take at least 90% of the time that their bytes, less one second of burst and one send quantum, need at the + limit. While they upload for more than one lease period the mount renews in the same epoch.""" + bodies, body_bytes = 3, 8_000_000 + idle_baseline = _server_throttled_bytes(node_guard) + idle_mount = _guard_mount(node_guard) + # Three renewal periods with no upload: the renewals in them must leave the counter where it was. + time.sleep(3 * GUARD_RENEW_PERIOD_S) + renewed = _guard_mount(node_guard) + assert renewed[0] == idle_mount[0] and renewed[1] > idle_mount[1], (idle_mount, renewed) + # Holds while no other test leaves merging tables on `node_guard`. + assert _server_throttled_bytes(node_guard) == idle_baseline, (idle_baseline, _server_throttled_bytes(node_guard)) + node_guard.query("CREATE TABLE server_limit (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(GUARD_POLICY)) + baseline = _server_throttled_bytes(node_guard) + started = time.monotonic() + requests = [node_guard.get_query_request( + "INSERT INTO server_limit SELECT {}, randomString({})".format(i, body_bytes), + settings={"async_insert": 0}, timeout=300) for i in range(bodies)] + _wait_until(lambda: _server_throttled_bytes(node_guard) >= baseline + PROGRESS_BYTES // 2, timeout=120, + describe=lambda: "{} bytes over the limit".format(_server_throttled_bytes(node_guard) - baseline)) + + samples = [(time.monotonic(), _guard_mount(node_guard))] + while samples[-1][0] - samples[0][0] <= GUARD_LEASE_TTL_S: + # Three renewal periods between samples, so each sample follows at least one renewal even if one is slow. + time.sleep(3 * GUARD_RENEW_PERIOD_S) + mount = _guard_mount(node_guard) + assert any(r.process.poll() is None for r in requests), \ + "the uploads ended {:.1f} s into the sampling".format(time.monotonic() - samples[0][0]) + samples.append((time.monotonic(), mount)) + logging.info("mount samples: %s", samples) + epochs = {mount[0] for _, mount in samples} + assert len(epochs) == 1, samples + sequences = [mount[1] for _, mount in samples] + assert all(later > earlier for earlier, later in zip(sequences, sequences[1:])), samples + + for request in requests: + request.get_answer() + wall = time.monotonic() - started + # The burst cap is applied after a call's amount is taken off, so the first call after an idle spell passes one + # quantum, at least 32 KiB, free. + # 10% slack: a socket charges the larger of the send size and 32 KiB per call, so the free amount varies. + bound = 0.9 * (bodies * body_bytes - SERVER_LIMIT - 32 * 1024) / SERVER_LIMIT + logging.info("%d bytes under %d B/s: %.1f s, bound %.1f s", bodies * body_bytes, SERVER_LIMIT, wall, bound) + assert wall >= bound, (wall, bound) + assert node_guard.query("SELECT count() FROM server_limit").strip() == str(bodies) + + +def test_killed_transaction_rolls_back_during_a_paced_upload(node_stop): + """An `INSERT` in an implicit transaction writes a tiny first part and a large second one, and is killed while the + second part's body goes out paced: it ends within `STOP_BOUND_S`, and the transaction rolls back the first part. + A ref-log record that lands after the kill installs that part with the rolled-back creation CSN.""" + name = "txn_paced_kill" + life = _create_with_life(node_stop, name) + try: + node_stop.query("SYSTEM STOP MERGES") + node_stop.query("INSERT INTO {} VALUES (1000, 'first')".format(name)) + fatal_before = int(node_stop.count_in_log("").strip()) + query_id = "txn_paced_kill_insert" + request = node_stop.get_query_request( + "INSERT INTO {} SELECT number, if(number = 0, 'x', randomString({})) FROM numbers(2)".format(name, BODY_BYTES), + # One thread, so the tiny part is written and committed before the large one is built. + query_id=query_id, settings=_paced(dict(ONE_PART_PER_SECOND, implicit_transaction=1, max_threads=1, + max_insert_threads=1)), + timeout=UNSTOPPED_WAIT_S + 60) + registered = _wait_until(lambda: node_stop.query( + "SELECT name FROM system.parts WHERE table = '{}' AND active AND creation_csn = 0 LIMIT 1".format(name)).strip(), + timeout=60) + baseline = _query_throttled_bytes(node_stop, query_id) + assert baseline is not None, "the query ended with its first part" + sent = _wait_body_going_out(node_stop, request, query_id, baseline) + killed_at = len(_stats()["trace"]) + elapsed = _kill_and_time(node_stop, request, query_id) + ended_at = len(_stats()["trace"]) + logging.info("%s: %d bytes paced past %d at the gate, ended %.1f s after the kill", name, sent, baseline, elapsed) + assert elapsed <= STOP_BOUND_S, "ended {:.1f} s after the kill".format(elapsed) + # A merge of transactional parts is not supported on a CAS disk. + node_stop.query("SYSTEM STOP MERGES {}".format(name)) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + window = _stats()["trace"][killed_at:ended_at] + assert _rolled_back_installs(node_stop, window, life, registered), (registered, _brief(window)) + # The cleanup may already have removed the rolled-back part. + csn = node_stop.query( + "SELECT creation_csn FROM system.parts WHERE table = '{}' AND name = '{}'".format(name, registered)).strip() + assert csn in ("", str(ROLLED_BACK_CSN)), (registered, csn) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "1" + assert int(node_stop.count_in_log("").strip()) == fatal_before + + node_stop.query("INSERT INTO {} VALUES (100, 'next')".format(name), + settings={"implicit_transaction": 1, "async_insert": 0}) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "2" + finally: + try: + node_stop.query("DROP TABLE IF EXISTS {} SYNC".format(name)) + finally: + node_stop.query("SYSTEM START MERGES") + + +def _server_alive(node, pid): + state = node.exec_in_container(["bash", "-c", "ps -o stat= -p {} || true".format(pid)], user="root").strip() + return bool(state) and not state.startswith("Z") + + +def test_sigterm_during_insert_upload_is_orderly(node_guard): + """SIGTERM while a paced body goes out: shutdown kills the query, its upload stops, and the server closes its + connections within `shutdown_wait_unfinished` (30 s, well below the body's remaining time), shuts its storages + down and exits without the forced exit. One SIGTERM to the exact server PID: a second one, or SIGKILL, would end + the process without the orderly shutdown under test.""" + node_guard.query("CREATE TABLE sigterm_upload (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(GUARD_POLICY)) + # The success line only: the warning about remaining connections starts with the same words. + closed = "Application: Closed connections\\.$" + forced = "Will shutdown forcefully" + storages = "Shut down storages\\." + before = {line: int(node_guard.count_in_log(line).strip()) for line in (closed, forced, storages, "")} + pid = node_guard.get_process_pid("clickhouse") + assert pid is not None + query_id = "sigterm_upload_insert" + request = node_guard.get_query_request(PACED_INSERT.format("sigterm_upload"), query_id=query_id, + settings=_paced(), timeout=UNSTOPPED_WAIT_S) + try: + sent = _wait_body_going_out(node_guard, request, query_id, baseline=0) + signalled = time.monotonic() + node_guard.exec_in_container(["bash", "-c", "kill -15 {}".format(pid)], user="root") + _wait_until(lambda: not _server_alive(node_guard, pid), timeout=120, describe=lambda: "{} still alive {:.1f} s " + "after the signal".format(pid, time.monotonic() - signalled)) + logging.info("sigterm: %d bytes paced at the gate, server exited %.1f s after the signal", + sent, time.monotonic() - signalled) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + delta = {line: int(node_guard.count_in_log(line).strip()) - count for line, count in before.items()} + # A forced exit can lose its own log line, so the two success lines carry the check. + assert delta == {closed: 1, forced: 0, storages: 1, "": 0}, delta + finally: + if node_guard.get_process_pid("clickhouse") is None: + node_guard.start_clickhouse() + assert node_guard.query("SELECT 1").strip() == "1" From 8363501c833e62b412ddd89b06991132eb4064e5 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 00:14:50 +0100 Subject: [PATCH 26/47] Document write limits and stopped uploads on CAS disks Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Opus 5.5 --- docs/en/antalya/cas/configuration.md | 19 +++++++++++++++++ .../antalya/cas/operations/troubleshooting.md | 21 +++++++++++++++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/docs/en/antalya/cas/configuration.md b/docs/en/antalya/cas/configuration.md index 2b9bd3ac43700..aa5dfec200df3 100644 --- a/docs/en/antalya/cas/configuration.md +++ b/docs/en/antalya/cas/configuration.md @@ -460,6 +460,25 @@ Source: `ServerSettings.cpp`. This setting is process-wide rather than scoped to |---|---|---| | `cas_blob_upload_pool_size` | `64` | Size of the dedicated server-wide thread pool used to upload blobs in parallel when committing a `CAS` part. Zero is rejected: the pool must have at least one thread | +## Write bandwidth limits {#write-bandwidth-limits} + +These limits pace blob bodies and part files staged in the object store with `cas_staging_backend = s3`: + +| Setting | Paces | +|---|---| +| `max_remote_write_network_bandwidth` | The uploads of the query | +| `max_remote_write_network_bandwidth_for_server` | Every upload of the server, also merges, mutations and moves | +| `max_network_bandwidth_for_user`, `max_network_bandwidth_for_all_users` | Uploads that run under a query, together with the query's other network traffic that these limits count | + +Part manifests, refs, the catalog, the mount lease, the GC state and deletes are never paced by these limits. + +A request that the S3 client sends by itself during an upload may be throttled with the upload. Two such requests +are a token request with `http_client = gcp_oauth` and the bucket region lookup of a client that has not sent a +request yet. + +After an upgrade, a server that already has one of these limits set starts to pace `CAS` uploads. A low server-wide +limit makes merges and mutations hold their queue slots longer, and they are not stopped while they upload. + ## `SYSTEM CAS` commands {#system-commands} `SYSTEM CAS GC RUN`, `SYSTEM CAS GC STOP`, `SYSTEM CAS GC START`, `SYSTEM CAS GC REBUILD`, diff --git a/docs/en/antalya/cas/operations/troubleshooting.md b/docs/en/antalya/cas/operations/troubleshooting.md index dc37b19025b8b..d1aeb0a23b316 100644 --- a/docs/en/antalya/cas/operations/troubleshooting.md +++ b/docs/en/antalya/cas/operations/troubleshooting.md @@ -141,7 +141,7 @@ A query that is killed with `KILL QUERY` or hits its time limit stops `CAS` work - A retry after a failed request. The retry is not sent. When a read or a blob upload failed before the stop, the query fails with that request's error, or with a retry-later `NETWORK_ERROR` (210) that names a credential refusal, not with the stop's own error. That request's error can itself be `TIMEOUT_EXCEEDED` (159), when the failed attempt timed out. When a metadata write failed before the stop, the query fails with a retry-later `NETWORK_ERROR` (210) that says the write is unresolved and what a read of the key found; it does not carry the store's error. A metadata write that the store refused, with no earlier attempt left unanswered, keeps the store's error. When such a write was refused for its credentials and the stop cancels its resend with fresh credentials, it fails with a retry-later `NETWORK_ERROR` (210) that names the refusal. When the request fails after the stop, the S3 client reports the stop itself (see below). The pause before a retry notices the stop within 200 ms. A pause inside cleanup that the operation owes after a send runs to its end, and the request is sent once more unless the mount fence, the mount lease or a deadline stops it; if that attempt fails after the stop, it is not retried. - The next step of work that `CAS` can resume later: the catalog cleanup of a manual `SYSTEM CAS GC RUN`, the drain of `SYSTEM CAS DROP POOL MEMBER`, and the upload of a blob body the writer has to publish, because the store does not hold the blob or holds one the writer cannot reuse. The query fails with `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED`. When an earlier upload attempt of the same blob failed, the check before the next upload fails the query with that attempt's error instead. The drain checks the stop before each of the member's namespaces, before the listing of its manifests and after each page of that listing arrives, before each group of its manifests and before each key it deletes. A `SYSTEM CAS DROP POOL MEMBER` stopped after its drain began leaves the member retired; rerun it to finish. Stopped before that, it can leave the member as it was. -Everywhere else the `CAS` requests of a stopped query run as on a plain S3 disk. This covers the first attempt of every request, a new decision after another writer won a race before the stop, waits for other callers, cleanup after a failed write, transaction rollback, dropping a table or a temporary table, `SYSTEM CAS FORGET`, and the scan of `SYSTEM CAS FSCK`. +Everywhere else the `CAS` requests of a stopped query run as on a plain S3 disk, except the upload of a part that is being built (see below). This covers the first attempt of every other request, a new decision after another writer won a race before the stop, waits for other callers, cleanup after a failed write, transaction rollback, dropping a table or a temporary table, `SYSTEM CAS FORGET`, and the scan of `SYSTEM CAS FSCK`. The S3 client reports a stopped query's error in place of any failed answer from the store, as on a plain S3 disk. This includes an expected answer of a healthy store, such as `404` for a key that does not exist. So the query can still fail with `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED` when the store answers with an error after the stop. A bulk delete that the store answers successfully, with an error for one of its keys, keeps that key's error. Writes of several queries to one table's metadata can be sent together by one of them. When that query is stopped, such a failed answer can fail the other queries' writes in the same request too. @@ -154,9 +154,26 @@ Two background owners stop `CAS` work at its next step, with their own error: A `GC` round that `SYSTEM CAS GC STOP` ends is recorded as `Stopped` in `system.cas_gc_log`. A manual round whose query is killed or timed out is recorded as `Stopped` when it ends with `QUERY_WAS_CANCELLED`, or with one of the transient errors `S3_ERROR`, `NETWORK_ERROR`, `SOCKET_TIMEOUT`, `TIMEOUT_EXCEEDED`, `ABORTED` or `MEMORY_LIMIT_EXCEEDED`. It is recorded as `Error` when it ends with any other error, for example `READONLY`. A stop that comes after the round's last check leaves the round's own outcome. +A stop also ends the upload of a part that is being built: + +- The `INSERT` ends with `QUERY_WAS_CANCELLED` after `KILL QUERY`, or with `TIMEOUT_EXCEEDED` when it reaches + `max_execution_time` with `timeout_overflow_mode = 'throw'`. It may be retried unchanged. +- The stop is noticed while a blob body is being sent, usually within a second. A bandwidth limit can add its own + wait. No time is promised. +- With `cas_staging_backend = s3` the write to the staging object is what is stopped, also for a data file written + into an existing part. +- A blob body that was cut may still have reached the store. Cleanup is best effort, and the rest is left to GC. The + next mount start removes a staging object. +- The server aborts the incomplete multipart upload of a cut body. If the abort fails, the upload stays until the + bucket's lifecycle rule removes it. +- A stopped upload may log an error line for each cancelled request of a multipart upload. +- The upload of a merge, a mutation, a background replication fetch or a background move is not stopped. Server + shutdown waits for it. A fetch or a move that a query runs itself (`ALTER TABLE ... FETCH PARTITION`, + `ALTER TABLE ... MOVE PARTITION`) is stopped with that query. + No stop interrupts: -- A request already in flight. +- Any other request already in flight. - The first attempt of a read, and a read that only waits for another reader's result. - A recovery walk that is already running. On S3 the walk of a stopped query still fails at the first error answer. A walk that looks for a record after its last one ends with such an answer, the `404` for that key; a walk that ends at the table's final removal record looks for none. The failed read is not retried. When the stop cuts short the read that follows a refused write of the walk, the walk ends with a retry-later `NETWORK_ERROR` (210) instead of starting again. - Cleanup that the operation owes after a send, and merges. From 0c581eb779489093ec429deea1840d2f0ef79320 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 22:34:45 +0100 Subject: [PATCH 27/47] test(cas): fetch cleanup after a stop must not publish the part Red on purpose: removeRecursive on a part directory leaves the transaction's staged files, so the commit that follows publishes them. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Disks/tests/gtest_ca_transaction.cpp | 46 ++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/Disks/tests/gtest_ca_transaction.cpp b/src/Disks/tests/gtest_ca_transaction.cpp index c45e8cbf65029..456c73d13a609 100644 --- a/src/Disks/tests/gtest_ca_transaction.cpp +++ b/src/Disks/tests/gtest_ca_transaction.cpp @@ -811,6 +811,52 @@ TEST(CASTransactionRemove, CreateThenDirDropDoesNotPublish) EXPECT_FALSE(storage->existsDirectory("b08/b08b08b0-0808-4808-8808-080808080808/all_1_1_0")); } +/// The stopped-fetch cleanup (`DataPartsExchange`, `ABORTED` branch) removes a half-downloaded +/// `tmp-fetch_*` part with `removeSharedRecursive` and then commits the SAME transaction that staged +/// its files. The removal must leave nothing behind, whichever removal call the storage issues. +namespace +{ + +void stageHalfFetchedPartThenRemoveAndCommit( + DB::ContentAddressedMetadataStorage & storage, + const std::string & table_dir, + const std::function & remove) +{ + const std::string part_dir = table_dir + "/tmp-fetch_all_1_1_0"; + auto tx = storage.createTransaction(); + writeFileTx(*tx, part_dir + "/checksums.txt", "cs-bytes"); + writeFileTx(*tx, part_dir + "/data.bin", "half-downloaded"); + remove(*tx, part_dir); + tx->commit(DB::NoCommitOptions{}); +} + +} + +TEST(CASTransactionRemove, FetchCleanupWithRemoveDirectoryLeavesNothing) +{ + auto storage = openTxStorage(); + const std::string table_dir = "b10/b10b10b0-1010-4010-8010-101010101010"; + stageHalfFetchedPartThenRemoveAndCommit( + *storage, table_dir, [](DB::IMetadataTransaction & tx, const std::string & dir) { tx.removeDirectory(dir); }); + + EXPECT_FALSE(storage->existsDirectory(table_dir + "/tmp-fetch_all_1_1_0")); + EXPECT_FALSE(storage->existsFile(table_dir + "/tmp-fetch_all_1_1_0/data.bin")); +} + +TEST(CASTransactionRemove, FetchCleanupWithRemoveRecursiveLeavesNothing) +{ + auto storage = openTxStorage(); + const std::string table_dir = "b11/b11b11b0-1111-4111-8111-111111111111"; + stageHalfFetchedPartThenRemoveAndCommit( + *storage, + table_dir, + [](DB::IMetadataTransaction & tx, const std::string & dir) { tx.removeRecursive(dir, /*should_remove_objects=*/nullptr); }); + + EXPECT_FALSE(storage->existsDirectory(table_dir + "/tmp-fetch_all_1_1_0")) + << "removeRecursive on a part directory dropped the committed ref only; the staged files were published by commit"; + EXPECT_FALSE(storage->existsFile(table_dir + "/tmp-fetch_all_1_1_0/data.bin")); +} + /// [Task 3] `startup()` publishes `cas_store`/`part_access`/`gc_scheduler` (and sets /// `pool_uuid`) atomically as its LAST action. Everything /// before that point -- opening the pool, building the part-folder facade, the capability probe, From f0920f4ed450713fed5358a9d4b9f35fcf6e6319 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sat, 28 Nov 2026 22:38:25 +0100 Subject: [PATCH 28/47] fix(cas): recursive removal of a part discards what the transaction staged A stopped byte fetch removes the half-downloaded part with a recursive removal and then commits the same transaction. The recursive removal dropped the ref but kept the staged files, so the commit published the part that was just removed. `removeDirectory` already discarded the staging; both now share `discardStagingOf`. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Fable 5.2 --- .../ContentAddressedTransaction.cpp | 33 ++++++++++--------- .../ContentAddressedTransaction.h | 4 +++ 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 7c8643ce190d5..c1814355de631 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -1251,6 +1251,21 @@ void ContentAddressedTransaction::createDirectoryRecursive(const std::string &) metadata_storage.checkOpAdmitted(CasOpClass::Write); } +void ContentAddressedTransaction::discardStagingOf(const ContentAddressedMetadataStorage::Route & r) +{ + auto * st = findStaging(r); + if (!st) + return; + st->content_removed.clear(); + clearEntries(*st); + st->base_manifest_ref.reset(); + if (st->build) + { + st->build->abandon(); + st->build.reset(); + } +} + void ContentAddressedTransaction::removeDirectory(const std::string & path) { /// CONTRACT: `removeDirectory`/`moveDirectory` mutate durable refs at CALL TIME, not at commit — @@ -1273,22 +1288,7 @@ void ContentAddressedTransaction::removeDirectory(const std::string & path) if (auto r = routeOf(path); r && !r->ref.empty() && r->file.empty()) { metadata_storage.partAccess()->dropRefIfPresent(r->refKey()); - /// This transaction's staged removal marks for the same ref (content_removed, populated by - /// unlinkFile's per-file unlinks that the MergeTree fast-removal path issues right before this - /// call) are superseded by the whole-part ref-drop just performed above — discard them so - /// publishStaging's committed-ref repoint branch never chases an already-dropped ref, and the - /// dominant removal path pays zero repoints (one ref-drop only). - if (auto * st = findStaging(*r)) - { - st->content_removed.clear(); - clearEntries(*st); - st->base_manifest_ref.reset(); - if (st->build) - { - st->build->abandon(); - st->build.reset(); - } - } + discardStagingOf(*r); return; } } @@ -1384,6 +1384,7 @@ void ContentAddressedTransaction::removeRecursive(const std::string & path, cons if (r && !r->ref.empty() && r->file.empty()) { metadata_storage.partAccess()->dropRefIfPresent(r->refKey()); + discardStagingOf(*r); return; } /// A projection subdir: virtual (nested in the parent tree) - removal is a no-op; the diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h index bc934ca6ef5fa..fb02b5a96672a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.h @@ -237,6 +237,10 @@ class ContentAddressedTransaction : public IMetadataTransaction PartStaging & stagingFor(const ContentAddressedMetadataStorage::Route & r); /// Finds existing staging state without creating an entry; returns nullptr when untouched. PartStaging * findStaging(const ContentAddressedMetadataStorage::Route & r); + /// A whole-part removal supersedes what this transaction staged for the same ref: files written, + /// per-file removal marks and an open build. Without the discard the commit would publish a part the + /// caller just removed, or chase a ref that is already dropped. + void discardStagingOf(const ContentAddressedMetadataStorage::Route & r); /// Finds the staged manifest entry for a routed file without consulting committed storage. const Cas::ManifestEntry * findStagedEntry(const ContentAddressedMetadataStorage::Route & r) const; /// Returns the pending (staged but not yet uploaded) blob for `ref`, or nullptr when it has From 37f87466755b12090794c3b0f3c1183f5f332e17 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sun, 29 Nov 2026 01:09:54 +0100 Subject: [PATCH 29/47] test(cas): a stopped byte fetch leaves no temporary part Adds the pausable failpoint `replicated_fetch_pause_after_projections` and a test that stops a paused byte fetch of a part with a projection, on local and S3 staging. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Common/FailPoint.cpp | 1 + src/Storages/MergeTree/DataPartsExchange.cpp | 4 + .../configs/storage_conf_other_pool.xml | 47 ++++++++++++ .../test_cas_replicated_relink/test.py | 76 +++++++++++++++++++ 4 files changed, 128 insertions(+) diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index 533218442c58a..c21ec79c9f661 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -405,6 +405,7 @@ static struct InitFiu REGULAR(smt_takeover_fake_hardware_error_after_set) \ REGULAR(cas_relink_receiver_force_mechanism_failure) \ PAUSEABLE_ONCE(cas_relink_receiver_pause_before_confirm) \ + PAUSEABLE_ONCE(replicated_fetch_pause_after_projections) \ REGULAR(cas_relink_sender_omit_pool_cookie) \ REGULAR(cas_relink_receiver_drop_forced_disk) \ ONCE(cas_gc_scheduler_fail_before_heartbeat_worker_start) \ diff --git a/src/Storages/MergeTree/DataPartsExchange.cpp b/src/Storages/MergeTree/DataPartsExchange.cpp index 1285f5152bad3..e7a1a09762156 100644 --- a/src/Storages/MergeTree/DataPartsExchange.cpp +++ b/src/Storages/MergeTree/DataPartsExchange.cpp @@ -56,6 +56,7 @@ namespace FailPoints /// neither is reachable from configuration, so an integration test cannot produce them any other way. extern const char cas_relink_receiver_force_mechanism_failure[]; extern const char cas_relink_receiver_pause_before_confirm[]; + extern const char replicated_fetch_pause_after_projections[]; /// Stands in for a sender that predates the `cas_pool_uuid` response cookie: the offer is made /// without naming the pool, and the receiver has to fall back on "the single advertised pool". extern const char cas_relink_sender_omit_pool_cookie[]; @@ -1287,6 +1288,9 @@ MergeTreeData::MutableDataPartPtr Fetcher::downloadPartToDisk( projection_name + ".proj", projection_checksum.getTotalSizeOnDisk(), projection_checksum.getTotalChecksumUInt128()); } + /// Test-only: lets a test stop the fetch while the projections are finalized and the base part is not started. + FailPointInjection::pauseFailPoint(FailPoints::replicated_fetch_pause_after_projections); + downloadBaseOrProjectionPartToDisk( replica_path, part_storage_for_loading, in, output_buffer_getter, data_checksums, throttler, sync); } diff --git a/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml b/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml index 3134abe489989..0f644f2974b64 100644 --- a/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml +++ b/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml @@ -19,6 +19,46 @@ node2_other 0 + + + object_storage + s3 + cas + 30 + 10000 + http://rustfs1:11121/test/other_pool_s3/ + clickhouse + clickhouse + node2_other_s3 + s3 + 0 + + + + object_storage + s3 + cas + http://rustfs1:11121/test/other_pool/ + clickhouse + clickhouse + node2_other + true + 0 + + + + object_storage + s3 + cas + http://rustfs1:11121/test/other_pool_s3/ + clickhouse + clickhouse + node2_other_s3 + true + 0 +
@@ -28,6 +68,13 @@ + + +
+ disk_cas_other_s3 +
+
+
diff --git a/tests/integration/test_cas_replicated_relink/test.py b/tests/integration/test_cas_replicated_relink/test.py index 8665ac4d9633f..f9e8ba2a10e19 100644 --- a/tests/integration/test_cas_replicated_relink/test.py +++ b/tests/integration/test_cas_replicated_relink/test.py @@ -21,6 +21,8 @@ # must degrade to bytes. OTHER_STORAGE_POLICY = "cas_other" OTHER_CA_DISK = "disk_cas_other" +OTHER_S3_STORAGE_POLICY = "cas_other_s3" +OTHER_S3_CA_DISK = "disk_cas_other_s3" # node2-only policies (configs/storage_conf_tiered.xml). `cas_tiered` = [local `default`] then # [disk_cas_shared]: an ordinary reservation lands on `default`, so a relink onto the pool's disk is a @@ -1233,3 +1235,77 @@ def test_relink_wins_over_ttl_then_mover_converges(): node2.query("SYSTEM START FETCHES {}".format(table)) node2.query("SYSTEM START MOVES {}".format(table)) drop_everywhere(table) + + +def list_disk_dir(node, disk, path): + """Entries of `path` as the disk lists them (a staged part is a ref, not a file in a local directory).""" + out = node.exec_in_container( + [ + "bash", + "-c", + "clickhouse disks -C /etc/clickhouse-server/config.xml --disk {} --save-logs --query {} 2>&1; true".format( + shlex.quote(disk + "_ro"), shlex.quote("list '{}'".format(path)) + ), + ] + ) + assert "Code:" not in out, out + return out.split() + + +@pytest.mark.parametrize( + "policy, disk", + [ + pytest.param(OTHER_STORAGE_POLICY, OTHER_CA_DISK, id="local"), + pytest.param(OTHER_S3_STORAGE_POLICY, OTHER_S3_CA_DISK, id="s3"), + ], +) +def test_stopped_byte_fetch_leaves_no_tmp_fetch_ref(policy, disk): + node1 = cluster.instances["node1"] + node2 = cluster.instances["node2"] + table = "stopped_fetch_" + policy + failpoint = "replicated_fetch_pause_after_projections" + create_sql = ( + "CREATE TABLE " + table + " (id Int64, v UInt64, s String, " + "PROJECTION p_by_s (SELECT s, sum(v) GROUP BY s)) " + "ENGINE = ReplicatedMergeTree('{zk}', '{{replica}}') ORDER BY id " + "SETTINGS storage_policy = '{policy}'" + ) + drop_everywhere(table) + zk = "/clickhouse/tables/" + table + node1.query(create_sql.format(policy=STORAGE_POLICY, zk=zk)) + node2.query(create_sql.format(policy=policy, zk=zk)) + node2.query("SYSTEM STOP FETCHES {}".format(table)) + insert_rows(node1, table, 0) + part = active_part_names(node1, table)[0] + expected_sum = int(node1.query("SELECT sum(v) FROM {}".format(table))) + data_path = node2.query( + "SELECT arrayJoin(data_paths) FROM system.tables WHERE database = 'default' AND name = '{}'".format(table) + ).strip() + table_path = data_path[data_path.index("store/"):] + + node2.query("SYSTEM ENABLE FAILPOINT " + failpoint) + try: + node2.query("SYSTEM START FETCHES {}".format(table)) + node2.query("SYSTEM WAIT FAILPOINT {} PAUSE".format(failpoint), timeout=120) + assert int(node2.query("SELECT count() FROM system.replicated_fetches WHERE table = '{}'".format(table))) == 1 + node2.query("SYSTEM STOP FETCHES {}".format(table)) + finally: + node2.query("SYSTEM DISABLE FAILPOINT " + failpoint) + + wait_until( + lambda: int(node2.query("SELECT count() FROM system.replicated_fetches WHERE table = '{}'".format(table))) == 0, + 60, + "the stopped fetch to leave system.replicated_fetches", + ) + entries = list_disk_dir(node2, disk, table_path) + list_disk_dir(node2, disk, table_path + "detached") + assert not [e for e in entries if e.startswith("tmp-fetch_")], entries + assert fsck(node2, disk)["dangling"] == "0" + assert any_state_part_count(node2, table, part) == 0 + + node2.query("SYSTEM START FETCHES {}".format(table)) + node2.query("SYSTEM SYNC REPLICA {}".format(table), timeout=90) + assert int(node2.query("SELECT count() FROM {}".format(table))) == NUM_ROWS + assert int(node2.query("SELECT sum(v) FROM {}".format(table))) == expected_sum + # Control for the listing helper: it must see the part that arrived. + assert part in list_disk_dir(node2, disk, table_path) + drop_everywhere(table) From d2ffcf21be93c2e41ecef6b8da5cdd502503f24e Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Sat, 29 Aug 2026 14:27:33 +0000 Subject: [PATCH 30/47] Merge pull request #115733 from ClickHouse/shutdown-cancel-merges Cancel in-flight merges and mutations on server shutdown (cherry picked from commit 691db87c896bdd3cd19c15cadb58a631cd1a8ab2) Port notes: one conflict, in `src/Storages/MergeTree/DataPartsExchange.cpp` `Fetcher::fetchSelectedPart`, where upstream registers the fetch entry and this fork has the CAS fetch-by-relink block. The registration and the per-entry `ReplicatedFetchReadCallback` now come first, right after the common header, and the relink block follows. Everything in the relink block is kept as is. Its `fall_back_to_byte_fetch` lambda additionally calls `entry.reset()` before it releases the directory lock, as upstream does before the zero-copy retry. The separate confirmation request in `relinkPartToDisk` keeps its own buffer. No hunk of upstream is left out. The test files are taken unchanged. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Common/FailPoint.cpp | 2 + src/Interpreters/Context.cpp | 48 ++++- src/Storages/MergeTree/DataPartsExchange.cpp | 73 ++++++- src/Storages/MergeTree/MergeList.h | 17 ++ .../MergeTree/MergeTreeBackgroundExecutor.cpp | 15 +- .../MergeTree/MergeTreeBackgroundExecutor.h | 10 + .../MergeTree/MergeTreeSequentialSource.cpp | 11 + src/Storages/MergeTree/ReplicatedFetchList.h | 31 +++ .../test_shutdown_cancels_merges/__init__.py | 0 .../configs/storage_conf.xml | 25 +++ .../configs/users_small_fetch_buffer.xml | 11 + .../test_shutdown_cancels_merges/test.py | 203 ++++++++++++++++++ 12 files changed, 425 insertions(+), 21 deletions(-) create mode 100644 tests/integration/test_shutdown_cancels_merges/__init__.py create mode 100644 tests/integration/test_shutdown_cancels_merges/configs/storage_conf.xml create mode 100644 tests/integration/test_shutdown_cancels_merges/configs/users_small_fetch_buffer.xml create mode 100644 tests/integration/test_shutdown_cancels_merges/test.py diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index c21ec79c9f661..41a57ead6e356 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -43,6 +43,8 @@ static struct InitFiu REGULAR(rmt_dedup_conflict_part_name_missing) \ REGULAR(smt_dedup_conflict_part_name_missing) \ REGULAR(merge_tree_sink_on_start_random_sleep) \ + REGULAR(merge_tree_sequential_source_sleep_before_read) \ + REGULAR(replicated_sends_sleep_before_file_send) \ REGULAR(use_delayed_remote_source) \ ONCE(remote_query_executor_cancel_before_send) \ PAUSEABLE_ONCE(remote_query_executor_receive_packet_pause) \ diff --git a/src/Interpreters/Context.cpp b/src/Interpreters/Context.cpp index fa2901bdc812c..f718b14aad35c 100644 --- a/src/Interpreters/Context.cpp +++ b/src/Interpreters/Context.cpp @@ -1083,12 +1083,50 @@ struct ContextSharedPart : boost::noncopyable LOG_TRACE(log, "Shutting down object storage queue streaming"); StreamingStorageRegistry::instance().shutdown(); - /// Stop all MergeTree background executors before shutting down databases. - /// This ensures no background tasks (merges, mutations, moves, part cleanup) - /// are running when storage objects are shut down or destroyed. - /// Without this, a background task could be accessing a storage's data_parts_indexes - /// while DatabaseCatalog::shutdown is destroying that storage, causing a SIGBUS. + /// Stop all MergeTree background executors and cancel the in-flight merges, + /// mutations and fetches, in this order: + /// + /// 1. Flip every executor into shutdown mode without joining it. From this point on + /// no new task can be scheduled (`trySchedule` rejects them) and no pending task + /// can start (worker threads exit at the next step boundary), so the set of + /// running tasks cannot grow. + /// 2. Cancel everything that is currently running. `cancelAll` also marks entries + /// inserted later as cancelled, so a task that is inside its first step and has + /// not registered itself in the list yet cannot escape the cancellation. + /// 3. Join the executors. + /// + /// The executors' `wait` (step 3) does not interrupt already running tasks, and the + /// per-storage cancellation (`merges_blocker`, `fetcher.blocker`) happens only later, + /// in `DatabaseCatalog::shutdown`. Without step 2, `wait` would block until the + /// current task step completes, and a single slow step (e.g. a merge applying huge + /// patch parts, which can spend minutes inside one block under sanitizers, or a + /// fetch of a large part) would delay shutdown beyond any timeout. The results of + /// these merges and fetches are discarded after the restart anyway, so finishing + /// them is pure waste. Without step 1, the cancellation would be racy: a task + /// scheduled after step 2 would be invisible to `cancelAll` and block `wait` again. + /// + /// Merge and mutate tasks check `MergeListElement::is_cancelled` on every block + /// through `MergeProgressCallback` and abort with the `ABORTED` exception; fetches + /// check `ReplicatedFetchListElement::is_cancelled` on every buffer refill. + /// + /// Waiting for the executors before shutting down databases also ensures no + /// background task is accessing a storage's data (e.g. data_parts_indexes) while + /// `DatabaseCatalog::shutdown` destroys that storage, which used to cause a SIGBUS. /// See https://github.com/ClickHouse/ClickHouse/issues/85433 + LOG_TRACE(log, "Stopping background executors from starting new tasks"); + if (merge_mutate_executor) + merge_mutate_executor->requestShutdown(); + if (fetch_executor) + fetch_executor->requestShutdown(); + if (moves_executor) + moves_executor->requestShutdown(); + if (common_executor) + common_executor->requestShutdown(); + + LOG_TRACE(log, "Cancelling merges, mutations and fetches"); + merge_list.cancelAll(); + replicated_fetch_list.cancelAll(); + SHUTDOWN(log, "merges executor", merge_mutate_executor, wait()); SHUTDOWN(log, "fetches executor", fetch_executor, wait()); SHUTDOWN(log, "moves executor", moves_executor, wait()); diff --git a/src/Storages/MergeTree/DataPartsExchange.cpp b/src/Storages/MergeTree/DataPartsExchange.cpp index e7a1a09762156..fdb0511079343 100644 --- a/src/Storages/MergeTree/DataPartsExchange.cpp +++ b/src/Storages/MergeTree/DataPartsExchange.cpp @@ -37,6 +37,7 @@ #include #include #include +#include namespace fs = std::filesystem; @@ -70,6 +71,11 @@ namespace MergeTreeSetting extern const MergeTreeSettingsUInt64 min_compressed_bytes_to_fsync_after_fetch; } +namespace FailPoints +{ + extern const char replicated_sends_sleep_before_file_send[]; +} + namespace ErrorCodes { extern const int NO_SUCH_DATA_PART; @@ -177,6 +183,12 @@ struct ReplicatedFetchReadCallback void operator() (size_t bytes_count) { + /// The entry is cancelled on server shutdown - there is no point in finishing + /// the download, its result would be discarded anyway. + if (replicated_fetch_entry->is_cancelled) + throw Exception(ErrorCodes::ABORTED, + "Fetching of part {} was cancelled", replicated_fetch_entry->result_part_name); + replicated_fetch_entry->bytes_read_compressed.store(bytes_count, std::memory_order_relaxed); /// It's possible when we fetch part from very old clickhouse version @@ -564,6 +576,15 @@ MergeTreeData::DataPart::Checksums Service::sendPartFromDisk( writeBinary(replicated_description.files.size(), out); for (const auto & [file_name, desc] : replicated_description.files) { + /// The flush makes the send observable by the receiver: without it, small (e.g. zero-copy + /// metadata) files accumulate in `out` and are sent in one piece at the end, and the sleeps + /// would just delay that single send instead of simulating a slow streaming transfer. + fiu_do_on(FailPoints::replicated_sends_sleep_before_file_send, + { + out.next(); + sleepForSeconds(5); + }); + writeStringBinary(file_name, out); writeBinary(desc.file_size, out); @@ -820,9 +841,33 @@ std::pair Fetcher::fetchSelected .withMethod(Poco::Net::HTTPRequest::HTTP_POST) .withTimeouts(timeouts) .withSettings(read_settings) - .withDelayInit(false) + /// The buffer size determines how often `ReplicatedFetchReadCallback` observes the + /// cancellation of the fetch (e.g. on server shutdown): the underlying read blocks + /// until a whole buffer is received, and the callback runs between the refills. + .withBufSize(read_settings.remote_fs_settings.buffer_size) + /// Delay the request until the shutdown cancellation callback below is installed: + /// with eager initialization the constructor would perform the first blocking read + /// before `setNextCallback` can run. + .withDelayInit(true) .create(creds); + /// Make the shutdown cancellation (`ReplicatedFetchList::cancelAll`) effective from the very + /// first read of the response body: the part header (sizes, TTL infos, part type, UUID, + /// projection count) is read below before the fetch is registered in the list, and a sender + /// stalled in that prefix would otherwise pin the fetch worker until the HTTP timeouts fire. + /// The callback is replaced by `ReplicatedFetchReadCallback` after the registration. + auto & replicated_fetch_list = data.getContext()->getReplicatedFetchList(); + in->setNextCallback([&replicated_fetch_list, part_name](size_t) + { + if (replicated_fetch_list.isAllCancelled()) + throw Exception(ErrorCodes::ABORTED, "Fetching of part {} was cancelled", part_name); + }); + + /// Send the request and read the first chunk of the response body. `nextImpl` runs the callback + /// before the connection and each blocking refill, so the whole transfer is cancellable. + /// The response is needed just below for the cookies. + in->next(); + int server_protocol_version = parse(in->getResponseCookie("server_protocol_version", "0")); String remote_fs_metadata = parse(in->getResponseCookie("remote_fs_metadata", "")); @@ -943,6 +988,18 @@ std::pair Fetcher::fetchSelected if (server_protocol_version >= REPLICATION_PROTOCOL_VERSION_WITH_PARTS_PROJECTION) readBinary(projections, *in); + /// Register the fetch before branching on `remote_fs_metadata`, so that both the regular and the + /// zero-copy download participate in the shutdown cancellation (`ReplicatedFetchList::cancelAll`): + /// the callback aborts the fetch with `ABORTED` on the next buffer refill after the entry is cancelled. + auto storage_id = data.getStorageID(); + String new_part_path = fs::path(data.getFullPathOnDisk(disk)) / part_name / ""; + auto entry = replicated_fetch_list.insert( + storage_id.getDatabaseName(), storage_id.getTableName(), + part_info.getPartitionId(), part_name, new_part_path, + replica_path, uri, to_detached, sum_files_size); + + in->setNextCallback(ReplicatedFetchReadCallback(*entry)); + /// CAS replication — fetch-by-relink (`part_manifest_v2`). The sender /// chose to relink: it sent only the part's encoded PartManifest body, no file bytes, and the /// reservation above already went to the offered pool's disk. Build the part by staging this @@ -971,6 +1028,8 @@ std::pair Fetcher::fetchSelected /// one as evidence that the brake is redundant.) auto fall_back_to_byte_fetch = [&] { + /// The recursive call registers its own entry in the `ReplicatedFetchList`. + entry.reset(); temporary_directory_lock = {}; return fetchSelectedPart( metadata_snapshot, context, part_name, zookeeper_name, replica_path, host, port, timeouts, @@ -1062,6 +1121,9 @@ std::pair Fetcher::fetchSelected LOG_WARNING(log, "Will retry fetching part without zero-copy: {}", e.message()); + /// The recursive call registers its own entry in the `ReplicatedFetchList`. + /// `in` still holds a callback referencing this entry, but it is never read after this point. + entry.reset(); temporary_directory_lock = {}; /// Try again but without zero-copy. `allow_ca_relink=false` for the same reason as the relink @@ -1082,15 +1144,6 @@ std::pair Fetcher::fetchSelected } } - auto storage_id = data.getStorageID(); - String new_part_path = fs::path(data.getFullPathOnDisk(disk)) / part_name / ""; - auto entry = data.getContext()->getReplicatedFetchList().insert( - storage_id.getDatabaseName(), storage_id.getTableName(), - part_info.getPartitionId(), part_name, new_part_path, - replica_path, uri, to_detached, sum_files_size); - - in->setNextCallback(ReplicatedFetchReadCallback(*entry)); - auto output_buffer_getter = [](IDataPartStorage & part_storage, const String & file_name, size_t file_size) { return part_storage.writeFile(file_name, std::min(file_size, DBMS_DEFAULT_BUFFER_SIZE), {}); diff --git a/src/Storages/MergeTree/MergeList.h b/src/Storages/MergeTree/MergeList.h index 5ef867c1a4389..cd69827bd4ad8 100644 --- a/src/Storages/MergeTree/MergeList.h +++ b/src/Storages/MergeTree/MergeList.h @@ -159,6 +159,8 @@ class MergeList final : public BackgroundProcessList; std::atomic merges_with_ttl_counter = 0; + /// Set by cancelAll (on server shutdown): entries inserted after it are cancelled at birth. + std::atomic all_cancelled = false; public: MergeList() : Parent(CurrentMetrics::Merge) @@ -183,13 +185,28 @@ class MergeList final : public BackgroundProcessList + EntryPtr insert(Args &&... args) + { + auto entry = Parent::insert(std::forward(args)...); + if (all_cancelled) + (*entry)->is_cancelled = true; + return entry; + } + void cancelInPartition(const StorageID & table_id, const String & partition_id, Int64 delimiting_block_number) { std::lock_guard lock{mutex}; diff --git a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp index 7c3bbfcd41bbd..bddb7e19900ca 100644 --- a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp +++ b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp @@ -98,14 +98,17 @@ MergeTreeBackgroundExecutor::~MergeTreeBackgroundExecutor() } template -void MergeTreeBackgroundExecutor::wait() +void MergeTreeBackgroundExecutor::requestShutdown() { - { - LockGuardWithStopWatch lock(mutex, log, __PRETTY_FUNCTION__); - shutdown = true; - has_tasks.notify_all(); - } + LockGuardWithStopWatch lock(mutex, log, __PRETTY_FUNCTION__); + shutdown = true; + has_tasks.notify_all(); +} +template +void MergeTreeBackgroundExecutor::wait() +{ + requestShutdown(); pool->wait(); } diff --git a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h index 8b93a5d4799e4..8db4844c7e7b9 100644 --- a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h +++ b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h @@ -334,6 +334,16 @@ class MergeTreeBackgroundExecutor final : boost::noncopyable bool trySchedule(ExecutableTaskPtr task); void removeTasksCorrespondingToStorage(StorageID id); + + /// Flip the executor into shutdown mode without joining the worker threads: + /// new tasks are rejected by `trySchedule` and pending tasks are not started + /// (worker threads exit at the next step boundary). Used on server shutdown to + /// stop scheduling before the in-flight tasks are cancelled, so that no freshly + /// scheduled task can slip in after the cancellation and block `wait`. + void requestShutdown(); + + /// Implies `requestShutdown`, then joins the worker threads. Running tasks are + /// not interrupted: each finishes its current step. void wait(); /// Update scheduling policy for pending tasks. It does nothing if `new_policy` is the same or unknown. diff --git a/src/Storages/MergeTree/MergeTreeSequentialSource.cpp b/src/Storages/MergeTree/MergeTreeSequentialSource.cpp index 232c4fac0b1fc..e1f0fa05c687f 100644 --- a/src/Storages/MergeTree/MergeTreeSequentialSource.cpp +++ b/src/Storages/MergeTree/MergeTreeSequentialSource.cpp @@ -22,7 +22,9 @@ #include #include #include +#include #include +#include namespace DB { @@ -32,6 +34,11 @@ namespace ErrorCodes extern const int LOGICAL_ERROR; } +namespace FailPoints +{ + extern const char merge_tree_sequential_source_sleep_before_read[]; +} + namespace Setting { extern const SettingsNonZeroUInt64 merge_tree_min_read_task_size; @@ -239,6 +246,10 @@ try if (isCancelled()) return {}; + /// Used in tests to emulate a merge whose single reading step is very slow + /// (e.g. applying huge patch parts), to check that shutdown does not wait for it. + fiu_do_on(FailPoints::merge_tree_sequential_source_sleep_before_read, { sleepForSeconds(10); }); + auto read_result = readers_chain.read(current_rows_to_read, mark_ranges, patch_ranges); if (!read_result.num_rows) return {}; diff --git a/src/Storages/MergeTree/ReplicatedFetchList.h b/src/Storages/MergeTree/ReplicatedFetchList.h index 321b11e082c78..2fe75e71a9855 100644 --- a/src/Storages/MergeTree/ReplicatedFetchList.h +++ b/src/Storages/MergeTree/ReplicatedFetchList.h @@ -69,6 +69,10 @@ struct ReplicatedFetchListElement : private boost::noncopyable const UInt64 thread_id; + /// Set on server shutdown. Checked in `ReplicatedFetchReadCallback` on every buffer + /// refill of the part download, which aborts with the `ABORTED` exception. + std::atomic is_cancelled{}; + ReplicatedFetchListElement( const std::string & database_, const std::string & table_, const std::string & partition_id_, const std::string & result_part_name_, @@ -86,11 +90,38 @@ class ReplicatedFetchList final : public BackgroundProcessList; + /// Set by cancelAll (on server shutdown): entries inserted after it are cancelled at birth. + std::atomic all_cancelled = false; public: ReplicatedFetchList () : Parent(CurrentMetrics::ReplicatedFetch) {} + + /// Whether `cancelAll` has been called (the server is shutting down). + /// Checked in `fetchSelectedPart` while reading the part header, before the fetch + /// is registered in the list and gets its own per-entry `is_cancelled` flag. + bool isAllCancelled() const { return all_cancelled; } + + /// Cancel all current fetches, and also all inserted later. + /// Used on server shutdown, when their results would be discarded anyway. + void cancelAll() + { + /// See the comment in `MergeList::cancelAll` about the ordering with `insert`. + all_cancelled = true; + std::lock_guard lock{mutex}; + for (auto & fetch_element : entries) + fetch_element.is_cancelled = true; + } + + template + EntryPtr insert(Args &&... args) + { + auto entry = Parent::insert(std::forward(args)...); + if (all_cancelled) + (*entry)->is_cancelled = true; + return entry; + } }; } diff --git a/tests/integration/test_shutdown_cancels_merges/__init__.py b/tests/integration/test_shutdown_cancels_merges/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/integration/test_shutdown_cancels_merges/configs/storage_conf.xml b/tests/integration/test_shutdown_cancels_merges/configs/storage_conf.xml new file mode 100644 index 0000000000000..ed82e47f67b25 --- /dev/null +++ b/tests/integration/test_shutdown_cancels_merges/configs/storage_conf.xml @@ -0,0 +1,25 @@ + + + test + + + + + + s3 + http://minio1:9001/root/data/ + minio + ClickHouse_Minio_P@ssw0rd + + + + + +
+ s3 +
+
+
+
+
+
diff --git a/tests/integration/test_shutdown_cancels_merges/configs/users_small_fetch_buffer.xml b/tests/integration/test_shutdown_cancels_merges/configs/users_small_fetch_buffer.xml new file mode 100644 index 0000000000000..5e4122894604a --- /dev/null +++ b/tests/integration/test_shutdown_cancels_merges/configs/users_small_fetch_buffer.xml @@ -0,0 +1,11 @@ + + + + + 1024 + + + diff --git a/tests/integration/test_shutdown_cancels_merges/test.py b/tests/integration/test_shutdown_cancels_merges/test.py new file mode 100644 index 0000000000000..7dcbfaa04bde6 --- /dev/null +++ b/tests/integration/test_shutdown_cancels_merges/test.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 + +import time + +import pytest + +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) + +node = cluster.add_instance("node", stay_alive=True) +node1 = cluster.add_instance("node1", with_zookeeper=True) +node2 = cluster.add_instance("node2", with_zookeeper=True, stay_alive=True) +node3 = cluster.add_instance( + "node3", + main_configs=["configs/storage_conf.xml"], + with_zookeeper=True, + with_minio=True, +) +node4 = cluster.add_instance( + "node4", + main_configs=["configs/storage_conf.xml"], + user_configs=["configs/users_small_fetch_buffer.xml"], + with_zookeeper=True, + with_minio=True, + stay_alive=True, +) + + +@pytest.fixture(scope="module") +def started_cluster(): + try: + cluster.start() + yield cluster + finally: + cluster.shutdown() + + +def test_shutdown_cancels_running_merge(started_cluster): + """A graceful shutdown must cancel in-flight merges instead of waiting for + them to finish. The `merge_tree_sequential_source_sleep_before_read` + failpoint makes every reading step of the merge sleep for 10 seconds, so + the merge of 16 parts runs for at least 160 seconds. Without cancellation + the server cannot stop before the timeout below (the background executor's + `wait` does not interrupt running tasks, and per-storage cancellation + happens only after that wait). See the `Possible deadlock on shutdown` + stress test failures where a merge applying patch parts blocked shutdown: + https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a013c79d6ac80373b820381527ea85823ab03834&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29 + """ + node.query(""" + CREATE TABLE t_shutdown_merge (k UInt64, v UInt64) + ENGINE = MergeTree ORDER BY k + SETTINGS min_parts_to_merge_at_once = 16 + """) + + node.query("SYSTEM STOP MERGES t_shutdown_merge") + + for i in range(16): + node.query( + f"INSERT INTO t_shutdown_merge SELECT number + {i} * 10000, number FROM numbers(10000)" + ) + + node.query("SYSTEM ENABLE FAILPOINT merge_tree_sequential_source_sleep_before_read") + node.query("SYSTEM START MERGES t_shutdown_merge") + + # Wait until the background merge picks up the parts. With + # min_parts_to_merge_at_once = 16 the only merge the selector can assign + # takes all 16 parts at once. + for _ in range(300): + num_parts = node.query( + "SELECT num_parts FROM system.merges WHERE table = 't_shutdown_merge'" + ).strip() + if num_parts: + assert int(num_parts) == 16 + break + time.sleep(0.2) + else: + raise Exception("The background merge did not start") + + start = time.time() + assert node.stop_clickhouse(stop_wait_sec=90) is True + elapsed = time.time() - start + assert elapsed < 90, f"Shutdown took {elapsed} seconds" + + node.start_clickhouse() + + # The merge was aborted, the source parts and the data are intact. + assert node.query("SELECT count() FROM t_shutdown_merge") == "160000\n" + + node.query("DROP TABLE t_shutdown_merge SYNC") + + +def test_shutdown_cancels_running_fetch(started_cluster): + """A graceful shutdown must also cancel in-flight fetches of parts from + other replicas: a fetch runs inside a single step of a background task, so + the executors' `wait` would otherwise block for the whole download. The + sender is throttled to 1 MiB/s and the part is ~150 MB of incompressible + data, so without cancellation the fetch holds the shutdown for ~150 + seconds. + """ + node1.query(""" + CREATE TABLE t_shutdown_fetch (k UInt64, v String) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_shutdown_fetch', 'r1') + ORDER BY k + SETTINGS max_replicated_sends_network_bandwidth = 1048576 + """) + node1.query( + "INSERT INTO t_shutdown_fetch SELECT number, randomString(1000) FROM numbers(150000)" + ) + + node2.query(""" + CREATE TABLE t_shutdown_fetch (k UInt64, v String) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_shutdown_fetch', 'r2') + ORDER BY k + """) + + for _ in range(300): + fetches = node2.query( + "SELECT count() FROM system.replicated_fetches WHERE table = 't_shutdown_fetch'" + ).strip() + if fetches != "0": + break + time.sleep(0.2) + else: + raise Exception("The fetch did not start") + + start = time.time() + assert node2.stop_clickhouse(stop_wait_sec=90) is True + elapsed = time.time() - start + assert elapsed < 90, f"Shutdown took {elapsed} seconds" + + # The fetch was aborted by the cancellation of the `ReplicatedFetchList` + # entry (the `ABORTED` message includes the part name), not by anything else. + assert node2.contains_in_log("Fetching of part all_.* was cancelled") + + node2.start_clickhouse() + + # After the restart the fetch is retried; dropping the table cancels it + # again, through the per-storage blockers. + node2.query("DROP TABLE t_shutdown_fetch SYNC") + node1.query("DROP TABLE t_shutdown_fetch SYNC") + + +def test_shutdown_cancels_running_zero_copy_fetch(started_cluster): + """The zero-copy fetch branch (`remote_fs_metadata`) must participate in + the shutdown cancellation too: the `ReplicatedFetchList` entry is created + and the read callback is installed before the branch on the fetch mode. + The `replicated_sends_sleep_before_file_send` failpoint makes the sender + flush and then sleep 5 seconds before each metadata file, and the part is + wide with 20 columns (several dozen files), so without cancellation the + metadata transfer holds the shutdown for well over 90 seconds. The + receiver observes the cancellation between the refills of its read + buffer, and the whole metadata stream is a few KB, so node4 shrinks + `max_read_buffer_size_remote_fs` to 1 KiB (see the comment in + `users_small_fetch_buffer.xml`). + """ + columns = ", ".join(f"v{i} String" for i in range(20)) + node3.query(f""" + CREATE TABLE t_shutdown_zc_fetch (k UInt64, {columns}) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_shutdown_zc_fetch', 'r1') + ORDER BY k + SETTINGS storage_policy = 's3', allow_remote_fs_zero_copy_replication = 1, + min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0 + """) + node3.query( + f"INSERT INTO t_shutdown_zc_fetch SELECT * FROM generateRandom('k UInt64, {columns}') LIMIT 100" + ) + + node3.query("SYSTEM ENABLE FAILPOINT replicated_sends_sleep_before_file_send") + + node4.query(f""" + CREATE TABLE t_shutdown_zc_fetch (k UInt64, {columns}) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_shutdown_zc_fetch', 'r2') + ORDER BY k + SETTINGS storage_policy = 's3', allow_remote_fs_zero_copy_replication = 1, + min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0 + """) + + for _ in range(300): + fetches = node4.query( + "SELECT count() FROM system.replicated_fetches WHERE table = 't_shutdown_zc_fetch'" + ).strip() + if fetches != "0": + break + time.sleep(0.2) + else: + raise Exception("The fetch did not start") + + start = time.time() + assert node4.stop_clickhouse(stop_wait_sec=90) is True + elapsed = time.time() - start + assert elapsed < 90, f"Shutdown took {elapsed} seconds" + + # The fetch took the zero-copy branch and was aborted by the cancellation + # of the `ReplicatedFetchList` entry (the `ABORTED` message). + assert node4.contains_in_log("metadata onto disk") + assert node4.contains_in_log("Fetching of part all_.* was cancelled") + + node3.query("SYSTEM DISABLE FAILPOINT replicated_sends_sleep_before_file_send") + node4.start_clickhouse() + + node4.query("DROP TABLE t_shutdown_zc_fetch SYNC") + node3.query("DROP TABLE t_shutdown_zc_fetch SYNC") From 84349480daf204f22f69f08f93582a8cfaabcdaa Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Tue, 22 Sep 2026 22:25:10 +0000 Subject: [PATCH 31/47] Merge pull request #113653 from groeneai/fix-executor-shutdown-drains-pending-tasks Release the tasks left in a MergeTree background executor's queue on shutdown (cherry picked from commit d59f7af75b3151367f6e814614bb9a5d905b2197) Port notes: clean pick. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- .../MergeTree/MergeTreeBackgroundExecutor.cpp | 25 +++++ .../MergeTree/MergeTreeBackgroundExecutor.h | 7 +- .../MergeTree/tests/gtest_executor.cpp | 93 +++++++++++++++++++ 3 files changed, 124 insertions(+), 1 deletion(-) diff --git a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp index bddb7e19900ca..0ffe0d6df9673 100644 --- a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp +++ b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -109,9 +110,33 @@ template void MergeTreeBackgroundExecutor::wait() { requestShutdown(); + + /// `threadFunction` breaks before popping once `shutdown` is set, so a task that `routine` + /// re-pushed keeps what it owns alive forever. Draining after `pool->wait()` is what makes it + /// complete: no worker can push to `pending` past that point. Also runs if `wait()` rethrows. + SCOPE_EXIT({ drainPendingTasks(); }); + pool->wait(); } +template +void MergeTreeBackgroundExecutor::drainPendingTasks() +{ + std::vector tasks_to_cancel; + { + LockGuardWithStopWatch lock(mutex, log, __PRETTY_FUNCTION__); + while (!pending.empty()) + tasks_to_cancel.push_back(pending.pop()); + } + + /// Cancelling and destroying a task can be slow, so do it outside the lock. + for (auto & item : tasks_to_cancel) + { + item->cancel(); + item.reset(); + } +} + template void MergeTreeBackgroundExecutor::increaseThreadsAndMaxTasksCount(size_t new_threads_count, size_t new_max_tasks_count) { diff --git a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h index 8db4844c7e7b9..1a98b4d9dd373 100644 --- a/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h +++ b/src/Storages/MergeTree/MergeTreeBackgroundExecutor.h @@ -343,7 +343,8 @@ class MergeTreeBackgroundExecutor final : boost::noncopyable void requestShutdown(); /// Implies `requestShutdown`, then joins the worker threads. Running tasks are - /// not interrupted: each finishes its current step. + /// not interrupted: each finishes its current step. Tasks still waiting in + /// `pending` are cancelled and destroyed. void wait(); /// Update scheduling policy for pending tasks. It does nothing if `new_policy` is the same or unknown. @@ -362,6 +363,10 @@ class MergeTreeBackgroundExecutor final : boost::noncopyable void routine(TaskRuntimeDataPtr item); + /// Cancel and destroy every task still waiting in `pending`. Only complete once no worker can + /// push there any more, i.e. after `pool->wait()` in `wait()`. + void drainPendingTasks(); + /// libc++ does not provide TSA support for std::unique_lock -> TSA_NO_THREAD_SAFETY_ANALYSIS void threadFunction() TSA_NO_THREAD_SAFETY_ANALYSIS; diff --git a/src/Storages/MergeTree/tests/gtest_executor.cpp b/src/Storages/MergeTree/tests/gtest_executor.cpp index 5bc591f8a78ab..20288f611a659 100644 --- a/src/Storages/MergeTree/tests/gtest_executor.cpp +++ b/src/Storages/MergeTree/tests/gtest_executor.cpp @@ -6,6 +6,8 @@ #include #include +#include +#include #include #include #include @@ -390,3 +392,94 @@ TEST(Executor, SlowTaskDestructionBlocksRemoveTasks) executor->wait(); } + + +/// Task that always asks for another step, so `routine` keeps re-pushing it to the pending queue. +/// It records whether it was cancelled; a real merge task releases most of its resources in +/// `cancel` and keeps its `TableLockHolder` alive for as long as the task object exists. +class NeverFinishingTask : public IExecutableTask +{ +public: + NeverFinishingTask(const String & name_, std::latch & step_executed_, std::atomic & cancelled_) + : name(name_) + , step_executed(step_executed_) + , cancelled(cancelled_) + {} + + bool executeStep() override + { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + if (!step_reported.exchange(true)) + step_executed.count_down(); + return true; + } + + void cancel() noexcept override { cancelled = true; } + StorageID getStorageID() const override { return {"test", name}; } + void onCompleted() override {} + Priority getPriority() const override { return {}; } + String getQueryId() const override { return "test::never_finishing"; } + +private: + String name; + std::latch & step_executed; + std::atomic & cancelled; + std::atomic step_reported{false}; +}; + + +/// A multi-step task waiting in the pending queue must not survive `wait()`. +/// +/// `threadFunction` breaks out of its loop before popping once `shutdown` is set, so a task that +/// `routine` re-pushed for another step is neither resumed nor cancelled. A real merge task holds +/// a `TableLockHolder` (a table share lock) for its whole lifetime, so such an abandoned task +/// blocks every later exclusive lock on its table until the acquisition times out. That is how a +/// `RENAME` rotating an obsolete `system.session_log` during shutdown ends in `DEADLOCK_AVOIDED` +/// once that timeout expires. +TEST(Executor, ShutdownReleasesPendingTasks) +{ + /// More than one task, so that draining a single one is not enough to pass. + static constexpr size_t tasks_count = 3; + + /// Declared before the executor so they outlive it (its destructor calls `wait`). + std::latch step_executed(tasks_count); + std::array, tasks_count> cancelled{}; + std::array, tasks_count> weak_tasks; + + auto executor = std::make_shared> + ( + ThreadName::TEST_SCHEDULER, + 1, // threads + 10, // max_tasks + CurrentMetrics::BackgroundMergesAndMutationsPoolTask, + CurrentMetrics::BackgroundMergesAndMutationsPoolSize, + ProfileEvents::CommonBackgroundExecutorTaskExecuteStepMicroseconds, + ProfileEvents::CommonBackgroundExecutorTaskCancelMicroseconds, + ProfileEvents::CommonBackgroundExecutorTaskResetMicroseconds, + ProfileEvents::CommonBackgroundExecutorWaitMicroseconds + ); + + for (size_t i = 0; i < tasks_count; ++i) + { + auto task = std::make_shared( + "pending_storage_" + std::to_string(i), step_executed, cancelled[i]); + weak_tasks[i] = task; + ASSERT_TRUE(executor->trySchedule(std::move(task))); + } + + /// Wait until every task has run a step, so each is known to be cycling through the pending + /// queue rather than never having been picked up. The single worker pops them in turn, and + /// `routine` re-pushes each one, so all of them are queued again by the time `wait()` runs. + step_executed.wait(); + + executor->wait(); + + for (size_t i = 0; i < tasks_count; ++i) + { + EXPECT_TRUE(weak_tasks[i].expired()) + << "task " << i << " was left in the pending queue and outlived executor shutdown, so " + "the resources it owns (for a merge task, a table share lock) were never released"; + EXPECT_TRUE(cancelled[i].load()) + << "task " << i << " was left in the pending queue and not cancelled on executor shutdown"; + } +} From 2de4145c38ed72d0265ddf4f6a9e335b7b320313 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Mon, 5 Oct 2026 02:01:49 +0000 Subject: [PATCH 32/47] Merge pull request #123870 from jgsogo/fix/121748-mergelist-cancelall fix: OOM-canary, stop only current merges (cherry picked from commit 589d92cfa62921d492b019ee140fecff94547ea4) Port notes: clean pick. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Common/OOMCanary/OOMCanary.cpp | 4 ++-- src/Storages/MergeTree/MergeList.h | 14 ++++++++++---- src/Storages/MergeTree/ReplicatedFetchList.h | 8 +++++++- tests/integration/test_oom_canary/test.py | 4 ++-- 4 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/Common/OOMCanary/OOMCanary.cpp b/src/Common/OOMCanary/OOMCanary.cpp index 69f795a2ba0ea..40087318c04d1 100644 --- a/src/Common/OOMCanary/OOMCanary.cpp +++ b/src/Common/OOMCanary/OOMCanary.cpp @@ -438,8 +438,8 @@ void OOMCanary::onCanaryOOM() /// Cancel all merges and mutations try { - context->getMergeList().cancelAll(); - LOG_INFO(log, "Cancelled all running merges"); + context->getMergeList().cancelCurrent(); + LOG_INFO(log, "Cancelled currently running merges"); } catch (...) { diff --git a/src/Storages/MergeTree/MergeList.h b/src/Storages/MergeTree/MergeList.h index cd69827bd4ad8..6b6f30bfc1a82 100644 --- a/src/Storages/MergeTree/MergeList.h +++ b/src/Storages/MergeTree/MergeList.h @@ -185,14 +185,20 @@ class MergeList final : public BackgroundProcessList Date: Mon, 5 Oct 2026 15:23:17 +0000 Subject: [PATCH 33/47] Do not let query cancellation interrupt transaction finalization `afterCommit` and `rollback` are `noexcept`. With the merge thread group now having a throwing cancellation predicate, a cancelled merge could throw `ABORTED` from a read in `afterCommit` and terminate the server. Block cancellation checks in the transaction finalization and rollback paths. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 66ab027fa0e923ecc2be8bfa2f88660e1bb58c80) Port notes: three conflicts. `src/Common/ThreadStatus.cpp`: upstream's context carries `publishUntrackedMemory`, which this base lacks; only the blocker definition is taken. `src/Interpreters/MergeTreeTransaction.cpp`: this base's `rollback` has no commit gate; the blocker is added in front of this base's `csn` exchange and nothing else of that hunk is taken. `src/Interpreters/TransactionManager.cpp` does not exist here: its two guards go into `TransactionLog::finalizeCommittedTransaction` and `TransactionLog::rollbackTransaction` (not `commitTransaction`, whose precommit stays cancellable), with the `ThreadStatus.h` include. `CasOwner.cpp`: the compile-time probe for the blocker and its use in `uploadStopCheck` are deleted. No other hunk of upstream is left out. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Common/ThreadStatus.cpp | 19 +++++++++++++++++-- src/Common/ThreadStatus.h | 12 ++++++++++++ .../ContentAddressed/Backend/CasOwner.cpp | 11 +---------- src/Interpreters/MergeTreeTransaction.cpp | 5 +++++ src/Interpreters/TransactionLog.cpp | 3 +++ 5 files changed, 38 insertions(+), 12 deletions(-) diff --git a/src/Common/ThreadStatus.cpp b/src/Common/ThreadStatus.cpp index 419a52981100d..7b6ec866878b1 100644 --- a/src/Common/ThreadStatus.cpp +++ b/src/Common/ThreadStatus.cpp @@ -267,9 +267,24 @@ void ThreadStatus::flushUntrackedMemory() memory_tracker.adjustWithUntrackedMemory(current_untracked_memory); } +namespace +{ +thread_local bool query_cancellation_blocked = false; +} + +ThreadStatus::QueryCancellationBlocker::QueryCancellationBlocker() + : previous(std::exchange(query_cancellation_blocked, true)) +{ +} + +ThreadStatus::QueryCancellationBlocker::~QueryCancellationBlocker() +{ + query_cancellation_blocked = previous; +} + bool ThreadStatus::isQueryCanceled() const { - if (!thread_group) + if (!thread_group || query_cancellation_blocked) return false; if (local_data.query_is_canceled_predicate) @@ -279,7 +294,7 @@ bool ThreadStatus::isQueryCanceled() const void ThreadStatus::throwIfQueryCanceled() const { - if (!thread_group) + if (!thread_group || query_cancellation_blocked) return; if (local_data.throw_if_query_canceled_predicate) diff --git a/src/Common/ThreadStatus.h b/src/Common/ThreadStatus.h index c8f60bcd18d54..6ebfc1d14d274 100644 --- a/src/Common/ThreadStatus.h +++ b/src/Common/ThreadStatus.h @@ -316,6 +316,18 @@ class ThreadStatus : public boost::noncopyable /// Throws the real cancellation cause if the query has been cancelled. No-op if not attached to a query. void throwIfQueryCanceled() const; + /// While alive, `isQueryCanceled` returns false and `throwIfQueryCanceled` does nothing in the current thread. + /// For code that must not be interrupted, like the finalization of a committed transaction. + class QueryCancellationBlocker : private boost::noncopyable + { + public: + QueryCancellationBlocker(); + ~QueryCancellationBlocker(); + + private: + bool previous; + }; + /// Proper cal for fatal_error_callback void onFatalError(); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp index 86bc6f0af2416..3d73f563346c9 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp @@ -240,15 +240,6 @@ namespace thread_local std::function upload_stop; -template -bool cancellationBlocked() -{ - if constexpr (requires { typename Status::QueryCancellationBlocker; }) - return Status::QueryCancellationBlocker::isActive(); - else - return false; -} - template inline constexpr bool kGroupHasCancellationSetter = requires(Group & group, std::function is_canceled, std::function throw_if_canceled) { @@ -264,7 +255,7 @@ static_assert(!kGroupHasCancellationSetter, std::function uploadStopCheck() { const auto & owner = OwnerScope::current; - if (owner.owed || owner.shared || cancellationBlocked()) + if (owner.owed || owner.shared) return {}; ThreadGroupPtr thread_group = CurrentThread::getGroup(); if (!thread_group) diff --git a/src/Interpreters/MergeTreeTransaction.cpp b/src/Interpreters/MergeTreeTransaction.cpp index 7f0e2f3313333..c72de2f67ec1a 100644 --- a/src/Interpreters/MergeTreeTransaction.cpp +++ b/src/Interpreters/MergeTreeTransaction.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -338,6 +339,8 @@ void MergeTreeTransaction::afterCommit(CSN assigned_csn) noexcept { auto blocker = CannotAllocateThreadFaultInjector::blockFaultInjections(); LockMemoryExceptionInThread memory_tracker_lock(VariableContext::Global); + /// A cancelled query or merge must not interrupt this: an escaping exception terminates the server. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; DataPartsVector created_parts; DataPartsVector removed_parts; @@ -394,6 +397,8 @@ bool MergeTreeTransaction::rollback() noexcept { auto blocker = CannotAllocateThreadFaultInjector::blockFaultInjections(); LockMemoryExceptionInThread memory_tracker_lock(VariableContext::Global); + /// A cancelled query or merge must not interrupt this: an escaping exception terminates the server. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; CSN expected = Tx::UnknownCSN; bool need_rollback = csn.compare_exchange_strong(expected, Tx::RolledBackCSN); diff --git a/src/Interpreters/TransactionLog.cpp b/src/Interpreters/TransactionLog.cpp index dda4b78a0147c..a31fe4487e452 100644 --- a/src/Interpreters/TransactionLog.cpp +++ b/src/Interpreters/TransactionLog.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -493,6 +494,7 @@ CSN TransactionLog::finalizeCommittedTransaction(MergeTreeTransaction * txn, CSN { LockMemoryExceptionInThread memory_tracker_lock(VariableContext::Global); auto blocker = CannotAllocateThreadFaultInjector::blockFaultInjections(); + ThreadStatus::QueryCancellationBlocker cancellation_blocker; chassert(!allocated_csn == txn->isReadOnly()); if (allocated_csn) { @@ -540,6 +542,7 @@ bool TransactionLog::waitForCSNLoaded(CSN csn) const void TransactionLog::rollbackTransaction(const MergeTreeTransactionPtr & txn) noexcept { LockMemoryExceptionInThread memory_tracker_lock(VariableContext::Global); + ThreadStatus::QueryCancellationBlocker cancellation_blocker; LOG_TRACE(log, "Rolling back transaction {}{}", txn->tid, std::uncaught_exceptions() ? fmt::format(" due to uncaught exception (code: {})", getCurrentExceptionCode()) : ""); From 32dd1f4a0c0d75ec9d22ea90529a20c8e407cdc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Mar=C3=ADn?= Date: Thu, 8 Oct 2026 10:56:37 +0000 Subject: [PATCH 34/47] Carry `QueryCancellationBlocker` into the distributed cache background write thread Sync from private: the background thread now creates its own blocker when the caller had one, so a cancelled merge cannot throw from `MergeTreeTransaction::afterCommit`. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit c3d80332e980316e6cdcab8cd8247446b43ca7a3) Port notes: clean pick. Added in the same commit: `uploadStopCheck` in `CasOwner.cpp` returns an empty stop while the calling thread holds the blocker, and two tests in `gtest_cas_upload_guard.cpp` (`StopIsEmptyUnderACancellationBlocker`, `APoolJobInheritsTheBlockerOnlyForItself`). Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Common/ThreadPool.cpp | 15 ++++- src/Common/ThreadStatus.cpp | 5 ++ src/Common/ThreadStatus.h | 3 + .../ContentAddressed/Backend/CasOwner.cpp | 2 +- src/Disks/tests/gtest_cas_upload_guard.cpp | 65 +++++++++++++++++++ 5 files changed, 87 insertions(+), 3 deletions(-) diff --git a/src/Common/ThreadPool.cpp b/src/Common/ThreadPool.cpp index 40e24478ffa6e..37d3a0ea34319 100644 --- a/src/Common/ThreadPool.cpp +++ b/src/Common/ThreadPool.cpp @@ -238,6 +238,9 @@ class JobWithPriority DB::OpenTelemetry::TracingContextOnThread thread_trace_context; + /// Propagated like the tracing context: a job scheduled under `QueryCancellationBlocker` runs under one. + bool query_cancellation_blocked = false; + /// Call stacks of all jobs' schedulings leading to this one std::vector frame_pointers; bool enable_job_stack_trace = false; @@ -253,11 +256,12 @@ class JobWithPriority JobWithPriority( Job job_, Priority priority_, CurrentMetrics::Metric metric, - const DB::OpenTelemetry::TracingContextOnThread & thread_trace_context_, + const DB::OpenTelemetry::TracingContextOnThread & thread_trace_context_, bool query_cancellation_blocked_, bool capture_frame_pointers, ScopedDecrement available_threads_decrement_) : job(job_), priority(priority_), metric_increment(metric), available_threads_decrement(std::move(available_threads_decrement_)), - thread_trace_context(thread_trace_context_), enable_job_stack_trace(capture_frame_pointers) + thread_trace_context(thread_trace_context_), query_cancellation_blocked(query_cancellation_blocked_), + enable_job_stack_trace(capture_frame_pointers) { if (!capture_frame_pointers) return; @@ -542,6 +546,8 @@ ReturnType ThreadPoolImpl::scheduleImpl(Job job, Priority priority, std: metric_scheduled_jobs, /// Tracing context on this thread is used as parent context for the sub-thread that runs the job propagate_opentelemetry_tracing_context ? DB::OpenTelemetry::CurrentContext() : DB::OpenTelemetry::TracingContextOnThread(), + /// Not for pool worker threads (created without propagation), which outlive the scheduling scope + propagate_opentelemetry_tracing_context && DB::ThreadStatus::QueryCancellationBlocker::isActive(), /// capture_frame_pointers DB::Exception::enable_job_stack_trace, std::move(available_threads_decrement)); @@ -1108,6 +1114,11 @@ void ThreadPoolImpl::ThreadFromThreadPool::worker() /// Set up tracing context for this thread by its parent context. DB::OpenTelemetry::TracingContextHolder thread_trace_context("ThreadPool::worker()", job_data->thread_trace_context); + /// The job may attach to the thread group of the scheduling thread and inherit its cancellation predicates. + std::optional cancellation_blocker; + if (job_data->query_cancellation_blocked) + cancellation_blocker.emplace(); + DB::Exception::enable_job_stack_trace = job_data->enable_job_stack_trace; if (DB::Exception::enable_job_stack_trace) DB::Exception::setThreadFramePointers(std::move(job_data->frame_pointers)); diff --git a/src/Common/ThreadStatus.cpp b/src/Common/ThreadStatus.cpp index 7b6ec866878b1..adf00011c70ea 100644 --- a/src/Common/ThreadStatus.cpp +++ b/src/Common/ThreadStatus.cpp @@ -282,6 +282,11 @@ ThreadStatus::QueryCancellationBlocker::~QueryCancellationBlocker() query_cancellation_blocked = previous; } +bool ThreadStatus::QueryCancellationBlocker::isActive() +{ + return query_cancellation_blocked; +} + bool ThreadStatus::isQueryCanceled() const { if (!thread_group || query_cancellation_blocked) diff --git a/src/Common/ThreadStatus.h b/src/Common/ThreadStatus.h index 6ebfc1d14d274..dac47a912f206 100644 --- a/src/Common/ThreadStatus.h +++ b/src/Common/ThreadStatus.h @@ -324,6 +324,9 @@ class ThreadStatus : public boost::noncopyable QueryCancellationBlocker(); ~QueryCancellationBlocker(); + /// Whether a blocker is alive in the current thread. `ThreadPool` carries it into the jobs scheduled under it. + static bool isActive(); + private: bool previous; }; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp index 3d73f563346c9..5cb21ae2a29f8 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp @@ -255,7 +255,7 @@ static_assert(!kGroupHasCancellationSetter, std::function uploadStopCheck() { const auto & owner = OwnerScope::current; - if (owner.owed || owner.shared) + if (owner.owed || owner.shared || ThreadStatus::QueryCancellationBlocker::isActive()) return {}; ThreadGroupPtr thread_group = CurrentThread::getGroup(); if (!thread_group) diff --git a/src/Disks/tests/gtest_cas_upload_guard.cpp b/src/Disks/tests/gtest_cas_upload_guard.cpp index 714b04d1b15b7..2c81f809782c4 100644 --- a/src/Disks/tests/gtest_cas_upload_guard.cpp +++ b/src/Disks/tests/gtest_cas_upload_guard.cpp @@ -166,6 +166,21 @@ TEST(CASUploadGuard, StopCheckIsEmptyWhereWorkMustFinish) onThread(false, [] { EXPECT_FALSE(uploadStopCheck()); }); } +TEST(CASUploadGuard, StopIsEmptyUnderACancellationBlocker) +{ + onKillableQueryThread([](CasKillableQuery & query) + { + query.kill(); + { + ThreadStatus::QueryCancellationBlocker blocker; + EXPECT_FALSE(uploadStopCheck()); + } + const std::function stop = uploadStopCheck(); + ASSERT_TRUE(stop); + EXPECT_EQ(codeOf(stop), ErrorCodes::QUERY_WAS_CANCELLED); + }); +} + TEST(CASUploadGuard, StopCheckCarriesTheQueryVerdictAndKeepsTheGroup) { std::function check; @@ -717,4 +732,54 @@ TEST(CASUploadGuard, TheStagingSinkCarriesTheGuardAndKeepsItsDefaults) } } +TEST(CASUploadGuard, APoolJobInheritsTheBlockerOnlyForItself) +{ + ThreadPool pool(CurrentMetrics::LocalThread, CurrentMetrics::LocalThreadActive, CurrentMetrics::LocalThreadScheduled, 1, 1, 0); + + std::mutex mutex; + std::condition_variable cv; + bool released = false; + std::thread::id gate_thread; + std::thread::id thread_a; + std::thread::id thread_b; + bool active_a = false; + bool active_b = true; + + /// The only worker is busy here, so job A starts after the scheduling scope below is gone. + pool.scheduleOrThrow( + [&] + { + std::unique_lock lock(mutex); + gate_thread = std::this_thread::get_id(); + cv.wait(lock, [&] { return released; }); + }); + { + ThreadStatus::QueryCancellationBlocker blocker; + pool.scheduleOrThrow( + [&] + { + thread_a = std::this_thread::get_id(); + active_a = ThreadStatus::QueryCancellationBlocker::isActive(); + }); + } + EXPECT_FALSE(ThreadStatus::QueryCancellationBlocker::isActive()); + pool.scheduleOrThrow( + [&] + { + thread_b = std::this_thread::get_id(); + active_b = ThreadStatus::QueryCancellationBlocker::isActive(); + }); + { + std::lock_guard lock(mutex); + released = true; + } + cv.notify_all(); + pool.wait(); + + EXPECT_TRUE(active_a); + EXPECT_FALSE(active_b); + EXPECT_EQ(thread_a, gate_thread) << "the jobs must share the one retained worker"; + EXPECT_EQ(thread_b, gate_thread); +} + #endif From 831e3cb77e180c802330723a339c9c091cc654f7 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Wed, 21 Oct 2026 19:58:15 +0000 Subject: [PATCH 35/47] Do not let cancellation interrupt the rollback of a merge or mutation When a mutation is killed while its part is being committed, the commit fails and `MergeTreeData::Transaction::rollback` runs in the thread of the mutation, under its query cancellation predicates. Reading the version metadata in `setAndStoreCreationCSN` then threw `Cancelled mutating parts` (in ClickHouse Cloud, from the distributed cache read buffer), so the rolled back part was left Outdated without `RolledBackCSN`. Such a part is not skipped by `getMaxLevelMutationInBetween`, and merges of its neighbours (including `OPTIMIZE ... FINAL`) are refused with "There is an outdated part in a gap between two active parts" until it is removed. This made `01168_mutations_isolation` flaky: `OPTIMIZE TABLE mt FINAL` in tx 7 did nothing, so the mutation of tx 10 did not get the expected serialization error, and the mutation of tx 7 failed instead. Use `ThreadStatus::QueryCancellationBlocker` during the rollback, as `MergeTreeTransaction::rollback` does. Related: https://github.com/ClickHouse/clickhouse-private/issues/13092 Example failure: https://d1k2gkhrlfqv31.cloudfront.net/clickhouse-test-reports-private/praktika.html?PR=82719&sha=b87fa9bb1fa635e3ef67043098f0931d959a45ca&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20cache%2C%20meta%20in%20keeper%2C%20s3%20storage%2C%20parallel%29 PR: https://github.com/ClickHouse/clickhouse-private/pull/82719 Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 85c0301d2b5) Port notes: clean pick. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Storages/MergeTree/MergeTreeData.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index ad11f6d40f0d6..0ad726011e298 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -156,6 +156,7 @@ #include #include #include +#include #include #include #include @@ -10807,6 +10808,11 @@ void MergeTreeData::Transaction::rollback(DataPartsLock * acquired_lock) { if (!isEmpty()) { + /// The rollback of a cancelled merge or mutation must not be interrupted by its own cancellation: + /// otherwise reading the version metadata in `setAndStoreCreationCSN` may throw, and the rolled back part + /// stays without `RolledBackCSN`, which prevents merges of the neighbouring parts until the part is removed. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + for (const auto & part : precommitted_parts) part->version->setAndStoreCreationCSN(Tx::RolledBackCSN); From b3aaf391be93189c3f2eac7cd0ca2f7e3cfb2009 Mon Sep 17 00:00:00 2001 From: Sema Checherinda Date: Wed, 11 Nov 2026 15:19:29 +0100 Subject: [PATCH 36/47] fix: keep S3 retries of cleanup when the query or merge is cancelled Hold `ThreadStatus::QueryCancellationBlocker` in `WriteBufferFromS3::abortMultipartUpload`, the multipart abort of `copyS3File`, `DiskObjectStorageTransaction::undo` and `IMergeTreeDataPart::removeIfNeeded`. (cherry picked from commit 16d34d5a333) Port notes: one conflict in `src/IO/S3/copyS3File.cpp`, include block. This base has no `Common/getRandomASCIIString.h` include there, so only the `Common/ThreadStatus.h` include is added. The separate test commit `fdda364d55b` is not taken. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp | 4 ++++ src/IO/S3/copyS3File.cpp | 4 ++++ src/IO/WriteBufferFromS3.cpp | 4 ++++ src/Storages/MergeTree/IMergeTreeDataPart.cpp | 4 ++++ 4 files changed, 16 insertions(+) diff --git a/src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp b/src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp index 57b9633c53a99..039fbc4729a6e 100644 --- a/src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp +++ b/src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -824,6 +825,9 @@ TransactionCommitOutcomeVariant DiskObjectStorageTransaction::tryCommit(const Tr void DiskObjectStorageTransaction::undo() noexcept { + /// Keep the retries of this cleanup when the query or merge is cancelled: nothing removes orphaned blobs later. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + for (const auto & [location, blobs] : written_blobs) { try diff --git a/src/IO/S3/copyS3File.cpp b/src/IO/S3/copyS3File.cpp index 76f2dbb2df575..2f65b6421e6c8 100644 --- a/src/IO/S3/copyS3File.cpp +++ b/src/IO/S3/copyS3File.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -252,6 +253,9 @@ namespace void abortMultipartUpload() { + /// Keep the retries of this cleanup when the query or merge is cancelled. The in-flight parts are already waited for. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + LOG_TRACE(log, "Aborting multipart upload. Bucket: {}, Key: {}, Upload_id: {}", dest_bucket, dest_key, multipart_upload_id); S3::AbortMultipartUploadRequest abort_request; abort_request.SetBucket(dest_bucket); diff --git a/src/IO/WriteBufferFromS3.cpp b/src/IO/WriteBufferFromS3.cpp index 2b4be44f26c57..6d0e98d4db7c8 100644 --- a/src/IO/WriteBufferFromS3.cpp +++ b/src/IO/WriteBufferFromS3.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -493,6 +494,9 @@ void WriteBufferFromS3::abortMultipartUpload() return; } + /// Keep the retries of this cleanup when the query or merge is cancelled. The in-flight parts are already waited for. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + LOG_INFO(log, "Abort multipart upload. {}", getVerboseLogDetails()); S3::AbortMultipartUploadRequest req; diff --git a/src/Storages/MergeTree/IMergeTreeDataPart.cpp b/src/Storages/MergeTree/IMergeTreeDataPart.cpp index e441968da1ea7..5e9cf5673b1ae 100644 --- a/src/Storages/MergeTree/IMergeTreeDataPart.cpp +++ b/src/Storages/MergeTree/IMergeTreeDataPart.cpp @@ -60,6 +60,7 @@ #include #include #include +#include #include #include #include @@ -1149,6 +1150,9 @@ void IMergeTreeDataPart::removeIfNeeded() if (!is_temp && state != MergeTreeDataPartState::DeleteOnDestroy) return; + /// Keep the retries of this cleanup when the query or merge is cancelled (`plain_rewritable` removes synchronously). + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + try { if (!getDataPartStorage().exists()) // path From acc4f6099b4159fd6af023130738ee7be9a7ddfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Mar=C3=ADn?= Date: Sat, 3 Oct 2026 20:21:28 +0200 Subject: [PATCH 37/47] Revert "Revert "Cancel vector similarity index builds when a merge or mutation is cancelled"" (cherry picked from commit 9e118a6716f04272609ee9e9eba9b5edac3de6fc) Port notes: clean pick of the product and test files. One CAS file changed in the same commit: `CasOwner.cpp` loses the `static_assert` that `ThreadGroup::setQueryCancellationPredicates` does not exist, together with the `kGroupHasCancellationSetter` probe it used. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Common/ThreadStatus.h | 3 + .../ContentAddressed/Backend/CasOwner.cpp | 10 ---- src/Interpreters/ThreadStatusExt.cpp | 7 +++ src/Storages/MergeTree/MergeTask.cpp | 10 ++++ .../MergeTreeIndexVectorSimilarity.cpp | 55 ++++++++++++++++--- src/Storages/MergeTree/MutateTask.cpp | 17 ++++++ ...table_cancels_vector_index_merge.reference | 1 + ...4_drop_table_cancels_vector_index_merge.sh | 47 ++++++++++++++++ 8 files changed, 131 insertions(+), 19 deletions(-) create mode 100644 tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.reference create mode 100755 tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh diff --git a/src/Common/ThreadStatus.h b/src/Common/ThreadStatus.h index dac47a912f206..76bcdbe9c215b 100644 --- a/src/Common/ThreadStatus.h +++ b/src/Common/ThreadStatus.h @@ -126,6 +126,9 @@ class ThreadGroup return shared_data; } + /// Must be called before any thread attaches to the group: threads copy the predicates on attach. + void setQueryCancellationPredicates(QueryIsCanceledPredicate is_canceled, ThrowIfQueryCanceledPredicate throw_if_canceled); + /// Mutation shared data void attachInternalTextLogsQueue(const InternalTextLogsQueuePtr & logs_queue, LogsLevel logs_level); void attachQueryForLog(const String & query_, UInt64 normalized_hash = 0); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp index 5cb21ae2a29f8..661143b3c115b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp @@ -240,16 +240,6 @@ namespace thread_local std::function upload_stop; -template -inline constexpr bool kGroupHasCancellationSetter = requires(Group & group, std::function is_canceled, std::function throw_if_canceled) -{ - group.setQueryCancellationPredicates(is_canceled, throw_if_canceled); -}; - -static_assert(!kGroupHasCancellationSetter, - "merges are cancellable on this base: add a test that a merge's upload is stopped and correct the user docs on " - "stopping CAS work"); - } std::function uploadStopCheck() diff --git a/src/Interpreters/ThreadStatusExt.cpp b/src/Interpreters/ThreadStatusExt.cpp index 36b18da613167..65de606b7d380 100644 --- a/src/Interpreters/ThreadStatusExt.cpp +++ b/src/Interpreters/ThreadStatusExt.cpp @@ -197,6 +197,13 @@ UInt64 ThreadGroup::getGroupElapsedMs() const return elapsed_group_ms; } +void ThreadGroup::setQueryCancellationPredicates(QueryIsCanceledPredicate is_canceled, ThrowIfQueryCanceledPredicate throw_if_canceled) +{ + std::lock_guard lock(mutex); + shared_data.query_is_canceled_predicate = std::move(is_canceled); + shared_data.throw_if_query_canceled_predicate = std::move(throw_if_canceled); +} + void ThreadGroup::linkThread(UInt64 thread_id) { std::lock_guard lock(mutex); diff --git a/src/Storages/MergeTree/MergeTask.cpp b/src/Storages/MergeTree/MergeTask.cpp index 9904b970705ab..d1ddd49922024 100644 --- a/src/Storages/MergeTree/MergeTask.cpp +++ b/src/Storages/MergeTree/MergeTask.cpp @@ -61,6 +61,7 @@ #include #include #include +#include #include #include #include @@ -1187,6 +1188,15 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const return false; }; + /// Lets the worker threads of long single-block steps (e.g. vector similarity index build) stop on cancellation. + global_ctx->merge_list_element_ptr->thread_group->setQueryCancellationPredicates( + ctx->is_cancelled, + [is_cancelled = ctx->is_cancelled] + { + if (is_cancelled()) + throw Exception(ErrorCodes::ABORTED, "Cancelled merging parts"); + }); + /// This is the end of preparation. Execution will be per block. return false; } diff --git a/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp b/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp index 7ca361f46477b..2c26274f0d8eb 100644 --- a/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp @@ -24,7 +24,10 @@ #include #include +#include #include +#include +#include #include #include @@ -374,12 +377,9 @@ void updateImpl(const ColumnArray * column_array, const ColumnArray::Offsets & c /// the runner is destroyed first (waits for all tasks) and the lambda is destroyed second. auto add_vector_to_index = [&](USearchIndex::vector_key_t key, size_t row) { - /// Check if the query has been cancelled. USearch internally does not check for cancellation, - /// and a single `add` call can take a very long time under sanitizers. Without this check, KILL QUERY - /// cannot stop the index building. The check is cheap (reads an atomic flag). - if (auto query_context = CurrentThread::tryGetQueryContext()) - if (auto query_status = query_context->getProcessListElementSafe()) - query_status->throwIfKilled(); + /// USearch internally does not check for cancellation, and a single `add` call can take a very long time + /// under sanitizers. Without this check, KILL QUERY or cancelling a merge cannot stop the index building. + CurrentThread::checkIfNotCancelled(); const typename Column::ValueType & value = column_array_data_float_data[column_array_offsets[row - 1]]; @@ -410,14 +410,51 @@ void updateImpl(const ColumnArray * column_array, const ColumnArray::Offsets & c size_t index_size = index->size(); + + /// Stop waiting at the first error (e.g. cancellation) instead of waiting for every queued row: the pool is shared with + /// other index builds, so the rest of our rows may sit behind a lot of their work. The runner's destructor drops them. + std::mutex mutex; + std::condition_variable finished_or_failed; + size_t remaining_rows = rows; + std::exception_ptr first_exception; + std::atomic failed = false; + auto add_row = [&](USearchIndex::vector_key_t key, size_t row) + { + if (failed) + return; + try + { + add_vector_to_index(key, row); + } + catch (...) + { + std::lock_guard lock(mutex); + if (!first_exception) + first_exception = std::current_exception(); + failed = true; + finished_or_failed.notify_all(); + return; + } + std::lock_guard lock(mutex); + if (--remaining_rows == 0) + finished_or_failed.notify_all(); + }; + ThreadPoolCallbackRunnerLocal runner(thread_pool, ThreadName::MERGETREE_VECTOR_SIM_INDEX); - for (size_t row = 0; row < rows; ++row) + /// Enqueueing can block on a full pool queue for a long time, so it must stop on an error too + for (size_t row = 0; row < rows && !failed; ++row) { auto key = static_cast(index_size + row); - /// Passing add_vector_to_index by reference is safe because it outlives the runner - runner.enqueueAndKeepTrack([&add_vector_to_index, key, row] { add_vector_to_index(key, row); }); + /// Passing add_row by reference is safe because it outlives the runner + runner.enqueueAndKeepTrack([&add_row, key, row] { add_row(key, row); }); } + { + std::unique_lock lock(mutex); + finished_or_failed.wait(lock, [&] { return remaining_rows == 0 || first_exception; }); + if (first_exception) + std::rethrow_exception(first_exception); + } runner.waitForAllToFinishAndRethrowFirstError(); } diff --git a/src/Storages/MergeTree/MutateTask.cpp b/src/Storages/MergeTree/MutateTask.cpp index 42653cba1036a..9283b897dde5f 100644 --- a/src/Storages/MergeTree/MutateTask.cpp +++ b/src/Storages/MergeTree/MutateTask.cpp @@ -57,6 +57,7 @@ #include #include #include +#include #include #include #include @@ -3660,6 +3661,22 @@ MutateTask::MutateTask( ctx->storage_columns = metadata_snapshot_->getColumns().getAllPhysical(); ctx->txn = txn; ctx->source_part = ctx->future_part->parts[0]; + + /// Lets the worker threads of long single-block steps (e.g. vector similarity index build) stop on cancellation. + /// Same condition as `checkOperationIsNotCanceled`. + auto mutation_cancelled = [merges_blocker = ctx->merges_blocker, + partition_id = ctx->future_part->part_info.getPartitionId(), + mutate_entry = ctx->mutate_entry] + { + return merges_blocker->isCancelledForPartition(partition_id) || (*mutate_entry)->is_cancelled; + }; + (*ctx->mutate_entry)->thread_group->setQueryCancellationPredicates( + mutation_cancelled, + [mutation_cancelled] + { + if (mutation_cancelled()) + throw Exception(ErrorCodes::ABORTED, "Cancelled mutating parts"); + }); } diff --git a/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.reference b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.reference new file mode 100644 index 0000000000000..d86bac9de59ab --- /dev/null +++ b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.reference @@ -0,0 +1 @@ +OK diff --git a/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh new file mode 100755 index 0000000000000..9158223343d1c --- /dev/null +++ b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: the fast test build has no usearch + +# DROP TABLE SYNC must cancel a merge that is building a vector similarity index in one long step +# (one block of 200000 rows), instead of waiting minutes for the index build to finish. + +CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CUR_DIR"/../shell_config.sh + +$CLICKHOUSE_CLIENT -m -q " + CREATE TABLE tab + ( + id Int32, + vec Array(Float32), + INDEX idx vec TYPE vector_similarity('hnsw', 'L2Distance', 64, 'f32', 200, 400) + ) + ENGINE = MergeTree + ORDER BY id + SETTINGS merge_max_block_size = 10000000, merge_max_block_size_bytes = 10000000000; + + SYSTEM STOP MERGES tab; + SET materialize_skip_indexes_on_insert = 0; + INSERT INTO tab SELECT number, arrayMap(x -> rand(x) / 4294967295., range(64)) FROM numbers(100000); + INSERT INTO tab SELECT number + 100000, arrayMap(x -> rand(x) / 4294967295., range(64)) FROM numbers(100000); + SYSTEM START MERGES tab; +" + +$CLICKHOUSE_CLIENT -q "OPTIMIZE TABLE tab FINAL" >/dev/null 2>&1 & +optimize_pid=$! + +for _ in {1..600}; do + [ "$($CLICKHOUSE_CLIENT -q "SELECT count() FROM system.merges WHERE database = currentDatabase() AND table = 'tab' AND elapsed > 3")" != 0 ] && break + sleep 0.1 +done + +start=$(date +%s) +$CLICKHOUSE_CLIENT -q "DROP TABLE tab SYNC" +elapsed=$(( $(date +%s) - start )) +wait $optimize_pid + +if [ "$elapsed" -lt 30 ]; then + echo "OK" +else + echo "DROP TABLE took $elapsed seconds" +fi From df87d3478d0878bd9fad025203bc62672e4f0e3d Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Sat, 24 Oct 2026 02:34:11 +0000 Subject: [PATCH 38/47] Merge pull request #127662 from groeneai/05294-time-merge-cancellation-not-drop Fix flaky test `05294_drop_table_cancels_vector_index_merge` (cherry picked from commit 8802b185fc24b4c925e50d4dd72e3bc5c66383a5) Port notes: clean pick, first parent diff (`-m 1`); test file only. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- ...4_drop_table_cancels_vector_index_merge.sh | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh index 9158223343d1c..86d92dc6e00f9 100755 --- a/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh +++ b/tests/queries/0_stateless/05294_drop_table_cancels_vector_index_merge.sh @@ -30,18 +30,28 @@ $CLICKHOUSE_CLIENT -m -q " $CLICKHOUSE_CLIENT -q "OPTIMIZE TABLE tab FINAL" >/dev/null 2>&1 & optimize_pid=$! +merge_started=0 for _ in {1..600}; do - [ "$($CLICKHOUSE_CLIENT -q "SELECT count() FROM system.merges WHERE database = currentDatabase() AND table = 'tab' AND elapsed > 3")" != 0 ] && break + if [ "$($CLICKHOUSE_CLIENT -q "SELECT count() FROM system.merges WHERE database = currentDatabase() AND table = 'tab' AND elapsed > 3")" != 0 ]; then + merge_started=1 + break + fi sleep 0.1 done +# DROP TABLE SYNC also waits for the server-wide queue of dropped tables, which a concurrent drop of another table +# can hold for a long time, so time only the cancellation of the merge: the OPTIMIZE that runs it returns then. start=$(date +%s) -$CLICKHOUSE_CLIENT -q "DROP TABLE tab SYNC" -elapsed=$(( $(date +%s) - start )) +$CLICKHOUSE_CLIENT -q "DROP TABLE tab SYNC" & +drop_pid=$! wait $optimize_pid +elapsed=$(( $(date +%s) - start )) +wait $drop_pid -if [ "$elapsed" -lt 30 ]; then +if [ "$merge_started" -eq 0 ]; then + echo "The merge did not run for more than 3 seconds" +elif [ "$elapsed" -lt 30 ]; then echo "OK" else - echo "DROP TABLE took $elapsed seconds" + echo "Cancelling the merge took $elapsed seconds" fi From 0b2b72c3a5a165fd3dde6eb6651bbe9726f7f335 Mon Sep 17 00:00:00 2001 From: Sema Checherinda <104093494+CheSema@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:14:06 +0000 Subject: [PATCH 39/47] Merge pull request #113939 from groeneai/fix-background-mutation-cancellation-predicate Make background merges and mutations observe cancellation in the S3 retry loop (cherry picked from commit 356ae390b444128d7eb74b45915bc8d5c0dd93a1) Port notes: - `src/IO/ReadBufferFromS3.cpp`: the textually clean pick put the new throwing `CurrentThread::checkIfNotCancelled` after this fork's early return on `isQueryCanceled`. Moved it before that return, so a cancelled task gets the cancellation exception; the Boolean check stays (exports use it). - `tests/integration/helpers/s3_mocks/broken_s3.py`: conflict in `_ServerRuntime.__init__`. Kept the base; added only `at_object_get`. Upstream's `at_complete_multi_part_upload` initialisation is not taken: the base mock has no such state. The `MockControl` method, the reset line and the GET dispatch hunk are as upstream. - No hunk left out; the ported tests run here without fixture repair (`test_merge_cancel_s3_read`, `04826_kill_mutation_cancels_s3_read`). - Not upstream, same commit: `CasOwner.h` and `CasOwner.cpp` comments of `uploadStopCheck` (a merge's group can now throw; the blocker is honoured at capture), and `gtest_cas_upload_guard.cpp` (renamed the no-predicate merge test, added `AGroupWithATaskPredicateThrowsThroughTheGuard`). Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- .../ContentAddressed/Backend/CasOwner.cpp | 2 + .../ContentAddressed/Backend/CasOwner.h | 4 +- src/Disks/tests/gtest_cas_upload_guard.cpp | 27 +- src/IO/ReadBufferFromS3.cpp | 3 + src/Storages/MergeTree/MergeList.h | 4 + src/Storages/MergeTree/MergeTask.cpp | 7 +- .../MergeTree/MergeTreeDataMergerMutator.cpp | 53 ++ src/Storages/MergeTree/MutateTask.cpp | 12 +- .../integration/helpers/s3_mocks/broken_s3.py | 18 + .../test_merge_cancel_s3_read/__init__.py | 0 .../configs/storage_conf.xml | 21 + .../test_merge_cancel_s3_read/test.py | 581 ++++++++++++++++++ ...26_kill_mutation_cancels_s3_read.reference | 8 + .../04826_kill_mutation_cancels_s3_read.sh | 190 ++++++ 14 files changed, 924 insertions(+), 6 deletions(-) create mode 100644 tests/integration/test_merge_cancel_s3_read/__init__.py create mode 100644 tests/integration/test_merge_cancel_s3_read/configs/storage_conf.xml create mode 100644 tests/integration/test_merge_cancel_s3_read/test.py create mode 100644 tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.reference create mode 100755 tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.sh diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp index 661143b3c115b..849816887207a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp @@ -245,6 +245,8 @@ thread_local std::function upload_stop; std::function uploadStopCheck() { const auto & owner = OwnerScope::current; + /// The returned callable invokes the group's predicate directly, bypassing the blocker check of + /// `throwIfQueryCanceled`, so the blocker is honoured here, when the stop is captured. if (owner.owed || owner.shared || ThreadStatus::QueryCancellationBlocker::isActive()) return {}; ThreadGroupPtr thread_group = CurrentThread::getGroup(); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h index 125376b27897f..16fffc85e59e6 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h @@ -172,8 +172,8 @@ class OwnerScope }; /// The check an upload of a new build runs while it sends, built on the publishing thread; the callable may run on any -/// thread. Empty inside `owed` or `shared` and on a thread with no thread group. Otherwise it runs the group's throwing -/// cancellation predicate, which never throws for a background group such as a merge or a mutation. It holds the thread +/// thread. Empty inside `owed` or `shared`, on a thread with no thread group, and while the calling thread holds a +/// `QueryCancellationBlocker`. Otherwise it runs the group's throwing cancellation predicate. It holds the thread /// group, so it may outlive the scope that built it. Background owners are not part of it. std::function uploadStopCheck(); diff --git a/src/Disks/tests/gtest_cas_upload_guard.cpp b/src/Disks/tests/gtest_cas_upload_guard.cpp index 2c81f809782c4..9bdb8660b552c 100644 --- a/src/Disks/tests/gtest_cas_upload_guard.cpp +++ b/src/Disks/tests/gtest_cas_upload_guard.cpp @@ -40,6 +40,7 @@ namespace DB::ErrorCodes { + extern const int ABORTED; extern const int QUERY_WAS_CANCELLED; } @@ -202,7 +203,7 @@ TEST(CASUploadGuard, StopCheckCarriesTheQueryVerdictAndKeepsTheGroup) EXPECT_TRUE(group.expired()); } -TEST(CASUploadGuard, AMergeThreadGroupGetsAStopThatNeverThrows) +TEST(CASUploadGuard, AMergeThreadGroupWithNoTaskPredicateInstalledGetsAStopThatNeverThrows) { onThread(true, [] { @@ -218,6 +219,30 @@ TEST(CASUploadGuard, AMergeThreadGroupGetsAStopThatNeverThrows) }); } +TEST(CASUploadGuard, AGroupWithATaskPredicateThrowsThroughTheGuard) +{ + onThread(true, [] + { + auto group = ThreadGroup::createForMergeMutate(getContext().context); + std::atomic cancelled = false; + group->setQueryCancellationPredicates( + [&cancelled] { return cancelled.load(); }, + [&cancelled] + { + if (cancelled.load()) + throw Exception(ErrorCodes::ABORTED, "Cancelled merging parts"); + }); + CurrentThread::attachToGroup(group); + + auto limiter = std::make_shared(); + auto guard = makeUploadGuard(limiter, uploadStopCheck()); + EXPECT_NO_THROW(guard->throttle(32768, 0)); + + cancelled = true; + EXPECT_EQ(codeOf([&] { guard->throttle(32768, 0); }), ErrorCodes::ABORTED); + }); +} + TEST(CASUploadGuard, BodyGuardScopeMatchesTheExactKeyOnly) { auto outer = std::make_shared(); diff --git a/src/IO/ReadBufferFromS3.cpp b/src/IO/ReadBufferFromS3.cpp index 4eb5ee1ffec5f..651493eda5ba7 100644 --- a/src/IO/ReadBufferFromS3.cpp +++ b/src/IO/ReadBufferFromS3.cpp @@ -401,6 +401,9 @@ bool ReadBufferFromS3::processException(size_t read_offset, size_t attempt) cons bucket, key, version_id.empty() ? "Latest" : version_id, read_offset, attempt, request_settings[S3RequestSetting::max_single_read_retries].value, getCurrentExceptionMessage(/* with_stacktrace = */ false)); + /// Throws the cancellation cause, and is a no-op off-query, so an ordinary network error still retries. + CurrentThread::checkIfNotCancelled(); + /// A cancelled query must not keep retrying a transient read error (the SDK's RetryStrategy applies the same rule). if (CurrentThread::isInitialized() && CurrentThread::get().isQueryCanceled()) return false; diff --git a/src/Storages/MergeTree/MergeList.h b/src/Storages/MergeTree/MergeList.h index 6b6f30bfc1a82..a192e152d4217 100644 --- a/src/Storages/MergeTree/MergeList.h +++ b/src/Storages/MergeTree/MergeList.h @@ -95,6 +95,10 @@ struct MergeListElement : boost::noncopyable std::atomic progress{}; std::atomic is_cancelled{}; + /// Set once `MergeTask::prepare` has settled it: a regular merge that removes expired values is + /// cancellable by `SYSTEM STOP TTL MERGES`, one that had removal disabled up front is not. + std::atomic is_removing_expired_values{}; + UInt64 total_size_bytes_compressed{}; UInt64 total_size_bytes_uncompressed{}; UInt64 total_size_marks{}; diff --git a/src/Storages/MergeTree/MergeTask.cpp b/src/Storages/MergeTree/MergeTask.cpp index d1ddd49922024..283f662fb1635 100644 --- a/src/Storages/MergeTree/MergeTask.cpp +++ b/src/Storages/MergeTree/MergeTask.cpp @@ -655,6 +655,9 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const ctx->need_remove_expired_values = false; } + global_ctx->merge_list_element_ptr->is_removing_expired_values.store( + ctx->need_remove_expired_values, std::memory_order_relaxed); + const auto & patch_parts = global_ctx->future_part->patch_parts; /// Snapshot of pending mutations for the source parts, fetched once and reused for @@ -1167,7 +1170,7 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const ctx->is_cancelled = [merges_blocker = global_ctx->merges_blocker, ttl_merges_blocker = global_ctx->ttl_merges_blocker, - need_remove = ctx->need_remove_expired_values, + ttl_cancellable = ctx->need_remove_expired_values || isTTLMergeType(global_ctx->future_part->merge_type), merge_list_element = global_ctx->merge_list_element_ptr, partition_id = global_ctx->future_part->part_info.getPartitionId()]() -> bool { @@ -1177,7 +1180,7 @@ bool MergeTask::ExecuteAndFinalizeHorizontalPart::prepare() const return true; bool cancelled = merges_blocker->isCancelledForPartition(partition_id) - || (need_remove && ttl_merges_blocker->isCancelled()); + || (ttl_cancellable && ttl_merges_blocker->isCancelled()); if (cancelled) { diff --git a/src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp b/src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp index 05c0e36766b8d..b8b3bd9f1714b 100644 --- a/src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp +++ b/src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -456,6 +457,54 @@ MergeTaskPtr MergeTreeDataMergerMutator::mergePartsToTemporaryPart( metadata_snapshot = future_part->parts.front()->getMetadataSnapshot(); } + /// Root merges only: a projection sub-merge re-enters this under a running merge whose group is already + /// attached, and an attach copies `shared_data` once, so a write here would not reach its threads. + if (!projection_merge_list_element) + { + auto entry_context = (*merge_entry)->thread_group->query_context.lock(); + if (!entry_context) + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "Merge list entry for part {} has no query context: every caller keeps it alive for the " + "whole merge", + future_part->name); + + /// `optimizeDryRun` runs the task inline under a user query's group, whose cancellation already applies. + if (entry_context->isBackgroundContext()) + { + /// Latched, because a blocker released between two independent polls must not resurrect the read. + auto is_cancelled = [&blocker = merges_blocker, + &ttl_blocker = ttl_merges_blocker, + is_ttl_merge = isTTLMergeType(future_part->merge_type), + merge_entry, + partition_id = future_part->part_info.getPartitionId()] + { + if ((*merge_entry)->is_cancelled.load(std::memory_order_relaxed)) + return true; + + const bool removes_expired_values + = is_ttl_merge || (*merge_entry)->is_removing_expired_values.load(std::memory_order_relaxed); + + if (blocker.isCancelledForPartition(partition_id) || (removes_expired_values && ttl_blocker.isCancelled())) + { + (*merge_entry)->is_cancelled.store(true, std::memory_order_relaxed); + return true; + } + + return false; + }; + + /// Installed before the first attach: `MergeTask::prepare` replaces it only at its end, after its first reads. + (*merge_entry)->thread_group->setQueryCancellationPredicates( + is_cancelled, + [is_cancelled] + { + if (is_cancelled()) + throw Exception(ErrorCodes::ABORTED, "Cancelled merging parts"); + }); + } + } + return std::make_shared( std::move(future_part), std::move(metadata_snapshot), @@ -503,8 +552,12 @@ MutateTaskPtr MergeTreeDataMergerMutator::mutatePartToTemporaryPart( context->setInteractiveCancelCallback( [&blocker = merges_blocker, merge_entry, partition_id]() { + /// Persisted for the IO layer, which polls rarely and may miss a short-lived blocker. if (blocker.isCancelledForPartition(partition_id) || (*merge_entry)->is_cancelled) + { + (*merge_entry)->is_cancelled.store(true, std::memory_order_relaxed); throw Exception(ErrorCodes::ABORTED, "Cancelled mutating parts"); + } return false; }); diff --git a/src/Storages/MergeTree/MutateTask.cpp b/src/Storages/MergeTree/MutateTask.cpp index 9283b897dde5f..819ea2cb2bd57 100644 --- a/src/Storages/MergeTree/MutateTask.cpp +++ b/src/Storages/MergeTree/MutateTask.cpp @@ -3668,7 +3668,17 @@ MutateTask::MutateTask( partition_id = ctx->future_part->part_info.getPartitionId(), mutate_entry = ctx->mutate_entry] { - return merges_blocker->isCancelledForPartition(partition_id) || (*mutate_entry)->is_cancelled; + /// Latched, so that a blocker released between two polls does not resurrect a cancelled read. + if ((*mutate_entry)->is_cancelled.load(std::memory_order_relaxed)) + return true; + + if (merges_blocker->isCancelledForPartition(partition_id)) + { + (*mutate_entry)->is_cancelled.store(true, std::memory_order_relaxed); + return true; + } + + return false; }; (*ctx->mutate_entry)->thread_group->setQueryCancellationPredicates( mutation_cancelled, diff --git a/tests/integration/helpers/s3_mocks/broken_s3.py b/tests/integration/helpers/s3_mocks/broken_s3.py index a3fd6ab5852dc..70428549ed44e 100644 --- a/tests/integration/helpers/s3_mocks/broken_s3.py +++ b/tests/integration/helpers/s3_mocks/broken_s3.py @@ -70,6 +70,9 @@ def setup_at_part_upload(self, **kwargs): def setup_at_listing(self, **kwargs): self.setup_action("at_listing", **kwargs) + def setup_at_object_get(self, **kwargs): + self.setup_action("at_object_get", **kwargs) + def setup_at_create_multi_part_upload(self, **kwargs): self.setup_action("at_create_multi_part_upload", **kwargs) @@ -468,6 +471,7 @@ def __init__(self): self.slow_get = None self.fake_multipart_upload = None self.at_create_multi_part_upload = None + self.at_object_get = None def register_fake_upload(self, upload_id, key): with self.lock: @@ -490,6 +494,7 @@ def reset(self): self.fake_multipart_upload = None self.at_create_multi_part_upload = None self.at_listing = None + self.at_object_get = None _runtime = _ServerRuntime() @@ -685,6 +690,14 @@ def _mock_settings(self): self.log_message("set at_listing %s", _runtime.at_listing) return self._ok() + if path[1] == "at_object_get": + params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) + _runtime.at_object_get = _ServerRuntime.CountAfter.from_cgi_params( + _runtime.lock, params + ) + self.log_message("set at_object_get %s", _runtime.at_object_get) + return self._ok() + if path[1] == "reset": _runtime.reset() self.log_message("reset") @@ -707,6 +720,11 @@ def do_GET(self): if _runtime.at_listing.has_effect(): return _runtime.at_listing.inject_error(self) + if not is_listing and _runtime.at_object_get is not None: + if _runtime.at_object_get.has_effect(): + self.log_message("get at_object_get %s", _runtime.at_object_get) + return _runtime.at_object_get.inject_error(self) + if not is_listing and _runtime.slow_get is not None: timeout = _runtime.slow_get.get_timeout() if timeout is not None: diff --git a/tests/integration/test_merge_cancel_s3_read/__init__.py b/tests/integration/test_merge_cancel_s3_read/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/integration/test_merge_cancel_s3_read/configs/storage_conf.xml b/tests/integration/test_merge_cancel_s3_read/configs/storage_conf.xml new file mode 100644 index 0000000000000..203527349b559 --- /dev/null +++ b/tests/integration/test_merge_cancel_s3_read/configs/storage_conf.xml @@ -0,0 +1,21 @@ + + + + + s3 + http://resolver:8087/root/data/ + minio + ClickHouse_Minio_P@ssw0rd + 1 + + 1000000 + 1000000 + + + + +
broken_s3
+
+
+
+
diff --git a/tests/integration/test_merge_cancel_s3_read/test.py b/tests/integration/test_merge_cancel_s3_read/test.py new file mode 100644 index 0000000000000..150aa4481e7cd --- /dev/null +++ b/tests/integration/test_merge_cancel_s3_read/test.py @@ -0,0 +1,581 @@ +#!/usr/bin/env python3 + +import logging +import os +import time + +import pytest + +from helpers.cluster import ClickHouseCluster +from helpers.mock_servers import start_s3_mock + +CONFIG_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "configs") + +# Enough GETs to prove the merge is inside the retry loop rather than merely slow. +ATTEMPTS_TO_ACCRUE = 20 + +# The window oracle (b) must observe in full before it may pass. +SETTLED_WINDOW_SECONDS = 15 + +# A cancellation reaching the retry loop is observed after at most the remaining backoff +# (`DEFAULT_RETRY_MAX_DELAY_MS`, `IO/S3Defines.h`), so within seconds, while the retry budget it +# replaces is tens of minutes. Past this budget `stop_clickhouse` escalates to SIGKILL and reports +# the stop as not graceful, which is what the shutdown arm keys on. +SHUTDOWN_BUDGET_SECONDS = 60 + + +@pytest.fixture(scope="module") +def cluster(): + try: + cluster = ClickHouseCluster(__file__) + cluster.add_instance( + "node", + main_configs=["configs/storage_conf.xml"], + with_minio=True, + # The oracles count S3 events, which are server-global: a metadata disk would add + # its own requests to them. + with_remote_database_disk=False, + with_zookeeper=True, + stay_alive=True, + ) + logging.info("Starting cluster...") + cluster.start() + logging.info("Cluster started") + yield cluster + finally: + cluster.shutdown() + + +@pytest.fixture(scope="module") +def init_broken_s3(cluster): + yield start_s3_mock(cluster, "broken_s3", "8087") + + +@pytest.fixture(scope="function") +def broken_s3(init_broken_s3): + init_broken_s3.reset() + yield init_broken_s3 + + +# `DiskS3ReadRequestsCount` counts every request attempt, so it moves whatever error class the +# mock injects. The alternatives are both wrong here: `DiskS3GetObject` counts only the read +# buffer's outer attempts, not the SDK retries doing the spinning (measured 15 vs 2064 over one +# such read), and `...Errors` stays flat for a 429, which is accounted as throttling instead. +# `sumIf` because an event that has never fired has no row in `system.events` at all. +ATTEMPTS_QUERY = ( + "SELECT sumIf(value, event = 'DiskS3ReadRequestsCount') FROM system.events" +) + + +def get_attempts(node): + return int(node.query(ATTEMPTS_QUERY).strip() or 0) + + +def wait_for(node, query, predicate, attempts=300, sleep_time=0.2): + for _ in range(attempts): + value = node.query(query).strip() + if predicate(value): + return True + time.sleep(sleep_time) + return False + + +@pytest.mark.parametrize("replicated", [False, True]) +def test_stop_merges_cancels_s3_read(cluster, broken_s3, replicated): + """`SYSTEM STOP MERGES` must interrupt a merge stuck retrying an S3 read. + + A merge/mutate thread group's cancellation predicates resolve through a process-list + element it does not have, so before the fix they were constant `false` and the S3 retry + loop never observed the cancellation: the merge retried to its budget while holding the + table, which is what the stress-test hung check reported. + + Both engines are covered because the two root callers pass different contexts: the plain + one passes its per-task context, the replicated one passes the shared storage context. + A guard keyed on the argument rather than on the merge list entry's own thread group + would cover only the plain case. + """ + node = cluster.instances["node"] + table = "t_repl" if replicated else "t_plain" + engine = ( + f"ReplicatedMergeTree('/clickhouse/tables/{table}', 'r1')" + if replicated + else "MergeTree" + ) + + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + node.query( + f""" + CREATE TABLE {table} (id UInt64, s String) ENGINE = {engine} ORDER BY id + SETTINGS storage_policy = 'broken_s3', min_bytes_for_wide_part = 0 + """ + ) + node.query("SYSTEM STOP MERGES " + table) + node.query( + f"INSERT INTO {table} SELECT number, repeat('x', 200) FROM numbers(200000)" + ) + node.query( + f"INSERT INTO {table} SELECT number + 200000, repeat('y', 200) FROM numbers(200000)" + ) + assert ( + int( + node.query( + f"SELECT count() FROM system.parts " + f"WHERE database = currentDatabase() AND table = '{table}' AND active" + ) + ) + == 2 + ) + + # The merge must read the parts from the mock, not out of memory. + node.query("SYSTEM DROP MARK CACHE") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + # Immediate retryable failures, deliberately NOT `slow_get`: a sleep inside the request + # blocks a fixed and an unfixed server equally, so the arm would prove nothing. These + # spin the retry loop instead, so the cancellation predicate is polled promptly. + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + before = get_attempts(node) + node.query("SYSTEM START MERGES " + table) + # Not `node.query`: for a plain table OPTIMIZE runs the merge in this thread, so awaiting it + # would deadlock against the very hang under test. + optimize = node.get_query_request( + f"OPTIMIZE TABLE {table} FINAL SETTINGS alter_sync = 0, optimize_throw_if_noop = 0" + ) + + assert wait_for( + node, + f"SELECT count() FROM system.merges " + f"WHERE database = currentDatabase() AND table = '{table}'", + lambda v: int(v) >= 1, + ), "the merge never started, so the assertions below would be vacuous" + + assert wait_for( + node, + ATTEMPTS_QUERY, + lambda v: int(v or 0) - before >= ATTEMPTS_TO_ACCRUE, + ), "the merge is not retrying the read, so there is nothing to cancel" + + node.query("SYSTEM STOP MERGES " + table) + + # Oracle (a): the merge exits instead of retrying to its budget. + assert wait_for( + node, + f"SELECT count() FROM system.merges " + f"WHERE database = currentDatabase() AND table = '{table}'", + lambda v: int(v) == 0, + ), "the merge kept running after SYSTEM STOP MERGES" + + # Oracle (b): and it stops issuing requests. (a) alone could pass on a slow but finite + # read; (b) alone could pass on a merge that never started. + # Every sample across the whole window must hold, so a pass cannot be granted by the first + # one: `wait_for` would return on its initial evaluation, before any request had time to land. + settled = get_attempts(node) + for _ in range(SETTLED_WINDOW_SECONDS): + time.sleep(1) + attempts = get_attempts(node) + assert attempts - settled <= 2, ( + f"the read kept retrying after the merge left system.merges " + f"({attempts - settled} requests since it was cancelled)" + ) + + broken_s3.reset() + optimize.get_answer_and_error() + node.query("SYSTEM START MERGES " + table) + + # A cancelled merge keeps its source parts, so no data is lost. + assert int(node.query(f"SELECT count() FROM {table}")) == 400000 + node.query(f"DROP TABLE {table} SYNC") + + +def test_stop_ttl_merges_does_not_cancel_regular_merge(cluster, broken_s3): + """`SYSTEM STOP TTL MERGES` must not abort a merge that only happens to drop TTL values. + + The blocker is state-aware on the merge path: when it is already set as a regular merge + starts, `prepare()` disables opportunistic TTL removal and the merge must then run to + completion. The predicate therefore keys on the *settled* removal state, so an unguarded + condition -- or one publishing the pre-downgrade value -- would abort this merge. + + The merge runs through the broken mock, so it is parked in the retry loop polling the + predicate. Without that the arm would never reach the code it exists to constrain, and the + unguarded form -- the single mutant it targets -- would leave it green. + """ + node = cluster.instances["node"] + node.query("DROP TABLE IF EXISTS t_ttl SYNC") + node.query( + """ + CREATE TABLE t_ttl (d DateTime, x UInt64) ENGINE = MergeTree ORDER BY x + TTL d + INTERVAL 1 SECOND + SETTINGS storage_policy = 'broken_s3', min_bytes_for_wide_part = 0, + merge_with_ttl_timeout = 0 + """ + ) + node.query("SYSTEM STOP MERGES t_ttl") + node.query("INSERT INTO t_ttl SELECT now() - 3600, number FROM numbers(20000)") + node.query( + "INSERT INTO t_ttl SELECT now() - 3600, number + 20000 FROM numbers(20000)" + ) + + node.query("SYSTEM DROP MARK CACHE") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + node.query("SYSTEM STOP TTL MERGES t_ttl") + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + before = get_attempts(node) + node.query("SYSTEM START MERGES t_ttl") + # Not `node.query`, for the same reason as the sibling arm: on a plain table OPTIMIZE runs + # the merge in this thread, so awaiting it would block until the mock is reset. + optimize = node.get_query_request( + "OPTIMIZE TABLE t_ttl PARTITION tuple() FINAL " + "SETTINGS alter_sync = 0, optimize_throw_if_noop = 0" + ) + + # The oracle is "the merge is still alive", so every wait below must fail the moment it dies: + # otherwise an abort looks like a merge that is merely slow to get going, and the mutant this + # arm targets gets reported as a vacuous arm instead of as the bug it is. + # Keyed on our own OPTIMIZE still running: it drives the merge inline, and being `FINAL` it waits + # for a competing merge on these parts rather than returning, so it survives as long as the merge + # does. `system.merges` cannot tell "aborted" from "not started yet", and the server log is + # shared with the sibling arm, which cancels merges by design. + # `NOT LIKE '%system.processes%'` so this query does not match its own text. + optimize_running_query = ( + "SELECT count() FROM system.processes " + "WHERE query LIKE '%OPTIMIZE TABLE t_ttl%' AND query NOT LIKE '%system.processes%'" + ) + + def assert_not_aborted(): + assert ( + int(node.query(optimize_running_query)) >= 1 + ), "SYSTEM STOP TTL MERGES aborted a regular merge" + + # `get_query_request` only spawns a client and returns, so until the query reaches the server + # "not running" does not distinguish an abort from a connection still being made. + assert wait_for( + node, optimize_running_query, lambda v: int(v) >= 1 + ), "the OPTIMIZE never reached the server, so the assertions below would be vacuous" + + # Vacuity guard: the merge reaches the retry loop, so it does poll the predicate and the + # window below is an observation rather than an idle wait. + accrued = False + for _ in range(300): + assert_not_aborted() + if get_attempts(node) - before >= ATTEMPTS_TO_ACCRUE: + accrued = True + break + time.sleep(0.2) + assert accrued, "the merge is not retrying the read, so it never polls the predicate" + + # The oracle: with TTL merges stopped, this merge must NOT be cancelled. It stays alive across + # a window many times longer than the abort it guards against takes. + settled = get_attempts(node) + for _ in range(SETTLED_WINDOW_SECONDS): + time.sleep(1) + assert_not_aborted() + assert ( + get_attempts(node) - settled >= 1 + ), "the merge stopped reading, so it is no longer in the retry loop" + + broken_s3.reset() + optimize.get_answer_and_error() + + # A `FINAL` optimize waits for a competing merge on the same parts rather than returning, so + # its answer above does not by itself mean the merge list has drained. + assert wait_for( + node, + "SELECT count() FROM system.merges " + "WHERE database = currentDatabase() AND table = 't_ttl'", + lambda v: int(v) == 0, + ), "the merge did not finish after the mock stopped failing" + + assert ( + int( + node.query( + "SELECT count() FROM system.parts " + "WHERE database = currentDatabase() AND table = 't_ttl' AND active" + ) + ) + == 1 + ), "the merge was aborted instead of completing without TTL removal" + # TTL removal was skipped, which is what stopping TTL merges is supposed to do. + assert int(node.query("SELECT count() FROM t_ttl")) == 40000 + + node.query("SYSTEM START TTL MERGES t_ttl") + node.query("DROP TABLE t_ttl SYNC") + + +def create_partly_expired_ttl_table(node, table, ttl, extra_settings=""): + """Two wide parts on the broken disk, each half expired, with merges held off. + + Deliberately NOT fully expired: `TTLPartDropMergeSelector` runs at higher priority than the + row-delete one and keys on the part's *max* TTL, so all-expired parts would be assigned + `TTLDrop`, which skips creating the read pipeline altogether and so never reaches S3. The + live half keeps `part_max_ttl` in the future. The expired half is also what makes the merge + read enough to be cancellable. + """ + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + node.query( + f""" + CREATE TABLE {table} (d DateTime, x UInt64) ENGINE = MergeTree ORDER BY x + TTL {ttl} + SETTINGS storage_policy = 'broken_s3', min_bytes_for_wide_part = 0, + merge_with_ttl_timeout = 0{extra_settings} + """ + ) + node.query(f"SYSTEM STOP MERGES {table}") + for part in range(2): + node.query( + f"INSERT INTO {table} SELECT " + f"if(number % 2, now() + 3600, now() - 3600), number + {part} * 40000 " + f"FROM numbers(40000)" + ) + + # The merge must read the parts from the mock, not out of memory. + node.query("SYSTEM DROP MARK CACHE") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + +def drop_table_stopping_any_merge(node, table): + """Teardown that must run even when an assertion above failed. + + `ATTEMPTS_QUERY` is a server-global counter, so a merge left retrying by a failed arm keeps + issuing requests once the next arm's fixture resets the mock, and that arm's request-plateau + oracle fails for a reason that has nothing to do with it. `SYSTEM STOP MERGES` cancels the + merge outright, which is the path this PR's headline fix makes reliable. + """ + node.query(f"SYSTEM STOP MERGES {table}") + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + node.query(f"SYSTEM START TTL MERGES {table}", ignore_error=True) + + +def assert_ttl_cancellation_reaches_the_read(node, table, before): + """The two oracles the headline arm uses, after `SYSTEM STOP TTL MERGES`. + + Preconditions: the merge is in `system.merges` and inside the retry loop. + """ + assert wait_for( + node, + ATTEMPTS_QUERY, + lambda v: int(v or 0) - before >= ATTEMPTS_TO_ACCRUE, + ), "the merge is not retrying the read, so there is nothing to cancel" + + node.query(f"SYSTEM STOP TTL MERGES {table}") + + # Oracle (a): the merge exits instead of retrying to its budget. + assert wait_for( + node, + f"SELECT count() FROM system.merges " + f"WHERE database = currentDatabase() AND table = '{table}'", + lambda v: int(v) == 0, + ), "the merge kept running after SYSTEM STOP TTL MERGES" + + # Only TTL merges are stopped, so the assignee is free to retry these same parts as a + # regular merge, which would keep reading and defeat oracle (b) for reasons unrelated to + # the branch under test. Stop merges outright now that oracle (a) has been observed. + node.query(f"SYSTEM STOP MERGES {table}") + + # Oracle (b): and it stops issuing requests. Sampled across the whole window, so a pass + # cannot be granted by the first sample, before any request had time to land. + settled = get_attempts(node) + for _ in range(SETTLED_WINDOW_SECONDS): + time.sleep(1) + attempts = get_attempts(node) + assert attempts - settled <= 2, ( + f"the read kept retrying after the merge left system.merges " + f"({attempts - settled} requests since it was cancelled)" + ) + + +# Cold, the merge stalls in `MergeTask::prepare`, loading statistics and marks. Warm, with neither +# left to load, it stalls on the first data read, after `prepare` replaced the group's predicates. +@pytest.mark.parametrize("warm", [False, True]) +def test_stop_ttl_merges_cancels_assigned_recompression_merge(cluster, broken_s3, warm): + """`SYSTEM STOP TTL MERGES` must interrupt an assigned TTL merge stuck in an S3 read. + + Recompression specifically, because it is the only assigned TTL merge that the sibling + entry-flag condition does not already cover: a recompression TTL is recorded with + `update_part_min_max_ttls = false` (`MergeTreeDataWriter.cpp:997`), so it never feeds + `part_min_ttl` and `MergeTask::prepare` leaves `need_remove_expired_values` false. A + `TTLDelete` or `TTLDrop` merge is instead selected *by* `part_min_ttl <= now`, which is the + very condition that sets that flag, so for those the `isTTLMergeType` term is redundant and + an arm built on them cannot observe it. + + The merge is left to the background assignee: an explicit `OPTIMIZE` is always + `MergeType::Regular`. + """ + node = cluster.instances["node"] + table = "t_ttl_recompress" + # `d - INTERVAL 1 HOUR` so the expired half is already due for recompression while the live + # half keeps the part from being fully expired. `default_compression_codec` must differ from + # the target, or `will_change_codec` is false and no recompression merge is ever selected. + create_partly_expired_ttl_table( + node, + table, + ttl="d - INTERVAL 1 HOUR RECOMPRESS CODEC(ZSTD(3))", + extra_settings=", default_compression_codec = 'LZ4'" + + (", auto_statistics_types = ''" if warm else ""), + ) + if warm: + node.query(f"SELECT * FROM {table} FORMAT Null") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + try: + before = get_attempts(node) + node.query(f"SYSTEM START MERGES {table}") + + # Vacuity guard: the running merge really is an assigned TTL merge, so the branch under + # test is the one being exercised. `merge_type` is `magic_enum::enum_name(MergeType)` + # (`MergeList.cpp` -> `IO/WriteHelpers.h:1190`), so the enum spelling, not SCREAMING_CASE. + assert wait_for( + node, + f"SELECT count() FROM system.merges WHERE database = currentDatabase() " + f"AND table = '{table}' AND merge_type = 'TTLRecompress'", + lambda v: int(v) >= 1, + ), "no recompression TTL merge was assigned, so the assertions below would be vacuous" + + assert_ttl_cancellation_reaches_the_read(node, table, before) + + broken_s3.reset() + # A cancelled merge keeps its source parts, so no data is lost. + assert int(node.query(f"SELECT count() FROM {table}")) == 80000 + finally: + drop_table_stopping_any_merge(node, table) + + +def test_stop_ttl_merges_cancels_regular_merge_removing_expired_values( + cluster, broken_s3 +): + """`SYSTEM STOP TTL MERGES` must interrupt a regular merge that is removing expired values. + + `MergeTask` has two TTL cancellation conditions, and this is the second: a regular merge + whose `need_remove_expired_values` survived the check in `prepare()` treats a later block + as cancellation. The TTL blocker must therefore still be unset while `prepare()` runs -- + were it already set, removal would be disabled up front and the merge must instead run to + completion, which is what `test_stop_ttl_merges_does_not_cancel_regular_merge` pins. + """ + node = cluster.instances["node"] + table = "t_ttl_regular" + # `max_number_of_merges_with_ttl_in_pool = 0` makes `merge_with_ttl_allowed` false, so the + # assignee cannot pick a TTL merge for these parts and steal them before `OPTIMIZE` -- which + # bypasses the selector and is always `MergeType::Regular` -- gets them. + create_partly_expired_ttl_table( + node, + table, + ttl="d + INTERVAL 1 SECOND", + extra_settings=", max_number_of_merges_with_ttl_in_pool = 0", + ) + + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + try: + before = get_attempts(node) + node.query(f"SYSTEM START MERGES {table}") + # Not `node.query`: for a plain table OPTIMIZE runs the merge in this thread, so awaiting + # it would deadlock against the very hang under test. + optimize = node.get_query_request( + f"OPTIMIZE TABLE {table} PARTITION tuple() FINAL " + f"SETTINGS alter_sync = 0, optimize_throw_if_noop = 0" + ) + + # Vacuity guard: this arm is about the *regular* branch, so a background TTL merge + # claiming the parts first would silently make it a duplicate of the sibling arm. + assert wait_for( + node, + f"SELECT count() FROM system.merges WHERE database = currentDatabase() " + f"AND table = '{table}' AND merge_type = 'Regular'", + lambda v: int(v) >= 1, + ), "no regular merge started, so the assertions below would be vacuous" + + assert_ttl_cancellation_reaches_the_read(node, table, before) + + broken_s3.reset() + optimize.get_answer_and_error() + assert int(node.query(f"SELECT count() FROM {table}")) == 80000 + finally: + drop_table_stopping_any_merge(node, table) + + +def test_shutdown_cancels_s3_read(cluster, broken_s3): + """Shutdown must interrupt a background merge stuck retrying an S3 read. + + A different branch of the predicate from the arms above, and the only one shutdown can reach + while it matters: `Context::shutdown` cancels through `MergeList::cancelAll`, which sets the + merge list entry's own flag, and then waits for the merge executor, whereas the per-storage + `merges_blocker` is cancelled only later, in `DatabaseCatalog::shutdown` + (`Interpreters/Context.cpp`). That wait has no timeout: `Server.cpp`'s `safeExit` path is + registered in a later scope guard, so it runs first and covers only connections, refresh + tasks, background queries and backups. + + The merge is left to the background assignee. An `OPTIMIZE` would hold a client connection + open across the shutdown, and `waitServersToFinish` would then reach that forced exit after + `shutdown_wait_unfinished`, passing this arm with the merge never cancelled at all. + """ + node = cluster.instances["node"] + table = "t_shutdown" + + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + # `min_age_to_force_merge_seconds` because the selector declines two parts of this size on its + # own heuristic ("no need to merge parts according to merge selector algorithm"), and the + # merge has to come from the assignee rather than from `OPTIMIZE`. The short selecting sleep + # keeps the wait for it inside `wait_for`'s window. + node.query( + f""" + CREATE TABLE {table} (id UInt64, s String) ENGINE = MergeTree ORDER BY id + SETTINGS storage_policy = 'broken_s3', min_bytes_for_wide_part = 0, + min_age_to_force_merge_seconds = 1, merge_selecting_sleep_ms = 1000 + """ + ) + node.query(f"SYSTEM STOP MERGES {table}") + node.query( + f"INSERT INTO {table} SELECT number, repeat('x', 200) FROM numbers(200000)" + ) + node.query( + f"INSERT INTO {table} SELECT number + 200000, repeat('y', 200) FROM numbers(200000)" + ) + + # The merge must read the parts from the mock, not out of memory. + node.query("SYSTEM DROP MARK CACHE") + node.query("SYSTEM DROP UNCOMPRESSED CACHE") + + broken_s3.setup_at_object_get(count=1000000, action="slow_down") + + try: + before = get_attempts(node) + node.query(f"SYSTEM START MERGES {table}") + + in_merges = ( + f"SELECT count() FROM system.merges " + f"WHERE database = currentDatabase() AND table = '{table}'" + ) + assert wait_for( + node, in_merges, lambda v: int(v) >= 1 + ), "the assignee never started the merge, so the assertions below would be vacuous" + + assert wait_for( + node, + ATTEMPTS_QUERY, + lambda v: int(v or 0) - before >= ATTEMPTS_TO_ACCRUE, + ), "the merge is not retrying the read, so there is nothing to cancel" + + # And it is still retrying as the shutdown starts: otherwise a prompt shutdown could be + # granted by a merge that had already finished, or that something else had cancelled. + assert ( + int(node.query(in_merges)) >= 1 + ), "the merge left system.merges before the shutdown, so this arm would be vacuous" + + # The oracle: SIGTERM completes on its own. `stop_clickhouse` returns True only when the + # process is gone within the budget, and force-kills past it. + assert node.stop_clickhouse(stop_wait_sec=SHUTDOWN_BUDGET_SECONDS) is True, ( + f"the server did not shut down within {SHUTDOWN_BUDGET_SECONDS}s and had to be " + f"killed: the merge kept retrying the read after MergeList::cancelAll" + ) + finally: + # The mock must stop failing before the server reads these parts back on startup. The + # stop is a no-op after the oracle and stops a still-running server after an earlier + # failure, so the restart is deterministic either way. + broken_s3.reset() + node.stop_clickhouse() + node.start_clickhouse() + drop_table_stopping_any_merge(node, table) diff --git a/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.reference b/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.reference new file mode 100644 index 0000000000000..3fdf4950382a8 --- /dev/null +++ b/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.reference @@ -0,0 +1,8 @@ +mutation started: 1 +mutation stopped: 1 +cancelled, not S3 error: 1 +dropped: 0 +stop merges: mutation started: 1 +stop merges cancels the read: 1 +toggle: mutation started: 1 +toggle stop/start cancels the read: 1 diff --git a/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.sh b/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.sh new file mode 100755 index 0000000000000..be6efc3546930 --- /dev/null +++ b/tests/queries/0_stateless/04826_kill_mutation_cancels_s3_read.sh @@ -0,0 +1,190 @@ +#!/usr/bin/env bash +# Tags: no-fasttest +# no-fasttest: uses the s3 table function. + +# `KILL MUTATION` must stop a mutation whose `IN` subquery is stuck reading an unreachable S3 +# endpoint. The read happens while the mutation's plan is still being built (materializing the set for +# primary-key analysis), where cancellation is observable only through the thread's cancellation +# predicate -- which used to be constant `false` for background tasks, so the mutation retried the +# request to its budget and blocked any later DROP/DETACH of the table behind it. + +CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../shell_config.sh +. "$CURDIR"/../shell_config.sh + +# The pool pin makes the mutation schedulable regardless of what else this run has queued, and +# `auto_statistics_types = ''` keeps the set from being built via the statistics estimation path, so the +# read under test is the key-analysis build. Both siblings of this family pin the same pair. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE t_mut (id UInt64) ENGINE = MergeTree ORDER BY id + SETTINGS number_of_free_entries_in_pool_to_execute_mutation = 0, auto_statistics_types = ''" +$CLICKHOUSE_CLIENT -q "INSERT INTO t_mut SELECT number FROM numbers(1000)" + +# Nothing listens on this port, so the read never completes on its own. `enable_parallel_replicas = 0` +# keeps the read under test inside the background mutation: with parallel replicas `s3` resolves to the +# cluster engine, whose constructor probes the endpoint while `ALTER` is still being analysed, so the +# statement blocks instead of queueing a mutation. +$CLICKHOUSE_CLIENT -q " + ALTER TABLE t_mut DELETE WHERE id IN ( + SELECT * FROM s3('http://localhost:19999/dummy.parquet', 'NOSIGN', 'One') + ) SETTINGS mutations_sync = 0, enable_parallel_replicas = 0" + +# Wait for the mutation to actually start before killing it, otherwise the kill races the scheduler +# and the test would pass without ever exercising the cancellation. +for _ in {1..150}; do + started=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_mut'") + [[ "$started" -ge 1 ]] && break + sleep 0.2 +done +echo "mutation started: $([[ "$started" -ge 1 ]] && echo 1 || echo 0)" + +$CLICKHOUSE_CLIENT -q "KILL MUTATION WHERE database = currentDatabase() AND table = 't_mut' FORMAT Null" + +# The oracle is the task LEAVING system.merges, not the KILL statement returning: the KILL returns +# immediately even when the mutation keeps retrying, which is precisely the bug. No wall-clock +# assertion -- only that it stops well inside the retry budget it used to exhaust. +gone=0 +for _ in {1..300}; do + running=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_mut'") + if [[ "$running" -eq 0 ]]; then + gone=1 + break + fi + sleep 0.2 +done +echo "mutation stopped: $gone" + +# It must stop *because it was cancelled*, not with whatever S3/network error the last attempt +# happened to produce. A cancellation the read reports as an ordinary request failure instead would +# end the mutation in a misleading S3_ERROR, so error 236 and not 499 is the assertion. +$CLICKHOUSE_CLIENT -q "SYSTEM FLUSH LOGS part_log" +echo "cancelled, not S3 error: $($CLICKHOUSE_CLIENT -q " + SELECT countIf(error = 236) > 0 AND countIf(error = 499) = 0 + FROM system.part_log + WHERE database = currentDatabase() AND table = 't_mut' + AND event_type = 'MutatePart' AND error != 0")" + +# The table must now be droppable: before the fix the in-flight task still held it, so the DROP waited +# for the read to exhaust its retries, which is what the stress-test hung check reported. Bounded so a +# regression is reported as a diff rather than as a test timeout. +timeout 60 $CLICKHOUSE_CLIENT -q "DROP TABLE t_mut SYNC" >/dev/null 2>&1 +echo "dropped: $?" + +# The second cancellation source: stopping merges must reach the read as well, so that shutting a +# table (or the server) down does not wait out the retry budget either. `KILL MUTATION` cancels only +# the one mutation, so without this arm nothing covers the per-table stop. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE t_stop (id UInt64) ENGINE = MergeTree ORDER BY id + SETTINGS number_of_free_entries_in_pool_to_execute_mutation = 0, auto_statistics_types = ''" +$CLICKHOUSE_CLIENT -q "INSERT INTO t_stop SELECT number FROM numbers(1000)" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE t_stop DELETE WHERE id IN ( + SELECT * FROM s3('http://localhost:19999/dummy.parquet', 'NOSIGN', 'One') + ) SETTINGS mutations_sync = 0, enable_parallel_replicas = 0" +for _ in {1..150}; do + started=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_stop'") + [[ "$started" -ge 1 ]] && break + sleep 0.2 +done +echo "stop merges: mutation started: $([[ "$started" -ge 1 ]] && echo 1 || echo 0)" + +$CLICKHOUSE_CLIENT -q "SYSTEM STOP MERGES t_stop" +stopped=0 +for _ in {1..300}; do + running=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_stop'") + if [[ "$running" -eq 0 ]]; then + stopped=1 + break + fi + sleep 0.2 +done +echo "stop merges cancels the read: $stopped" +$CLICKHOUSE_CLIENT -q "SYSTEM START MERGES t_stop" +timeout 60 $CLICKHOUSE_CLIENT -q "DROP TABLE t_stop SYNC" >/dev/null 2>&1 + +# The blocker above stays cancelled until the task exits, so it does not cover a blocker that is +# released again while the read is still retrying -- which ordinary DDL does on every scope exit +# (TRUNCATE, DROP/DETACH PARTITION, REPLACE PARTITION all take a scoped lock). The read and the +# interactive-cancel callback poll the predicate independently, so a detected cancellation must be +# persisted rather than re-read, exactly as the merge path already does. +# +# The oracle here is the attempt REPORTING cancellation, not the task leaving system.merges: a +# released blocker leaves the mutation schedulable, so the entry legitimately reappears and the +# arm above's oracle is unsatisfiable for this shape. +# +# Exactly ONE read here. The flaky check runs this test in as many workers as the runner has cores, +# and they share the server's background mutation slots, so a premise that needs several of this +# run's own mutations resident at the same instant is not satisfiable in that job. +$CLICKHOUSE_CLIENT -q " + CREATE TABLE t_toggle (id UInt64) ENGINE = MergeTree ORDER BY id + SETTINGS number_of_free_entries_in_pool_to_execute_mutation = 0, auto_statistics_types = ''" +$CLICKHOUSE_CLIENT -q "INSERT INTO t_toggle SELECT number FROM numbers(1000)" +$CLICKHOUSE_CLIENT -q " + ALTER TABLE t_toggle DELETE WHERE id IN ( + SELECT * FROM s3('http://localhost:19999/dummy.parquet', 'NOSIGN', 'One') + ) SETTINGS mutations_sync = 0, enable_parallel_replicas = 0" +for _ in {1..150}; do + started=$($CLICKHOUSE_CLIENT -q " + SELECT count() FROM system.merges + WHERE database = currentDatabase() AND table = 't_toggle'") + [[ "$started" -ge 1 ]] && break + sleep 0.2 +done +echo "toggle: mutation started: $([[ "$started" -ge 1 ]] && echo 1 || echo 0)" + +# An entry in system.merges only means the task is running: the subquery's S3 client is built later, +# and under a sanitizer that took 16s, so a toggle can be over before the read makes its first +# attempt and cancel nothing. Each round leaves the mutation schedulable, so it is simply retried. +# No round is STARTED past the deadline below, which leaves one whole round plus the teardown +# inside the flaky check's per-test limit of 180s however slow the arms above were. +cancelled=0 +toggle_deadline=$((SECONDS + 70)) +[[ "$toggle_deadline" -gt 125 ]] && toggle_deadline=125 +while [[ "$cancelled" -eq 0 && "$SECONDS" -lt "$toggle_deadline" ]]; do + # The read tests cancellation once per retry attempt, 5s apart once its backoff has saturated. + # The settle both waits for that and is drawn over a whole attempt period: a narrower draw + # resonates with it, because the restart after a cancelled attempt re-creates the same phase. + settle=$((9000 + RANDOM % 5100)) + sleep "$(printf '%d.%03d' $((settle / 1000)) $((settle % 1000)))" + # One call: the window is a server-side sleep plus two round trips, so client startup cannot + # stretch it, and the fail times bracket it. It has to hold the blocker cancelled long enough for + # a poller to observe it, and still end well inside the read's own attempt cadence: an attempt + # that fell INSIDE the window read the blocker itself, which proves nothing, so that round is + # spent on a fresh draw rather than on the poll below. + mapfile -t stamps < <($CLICKHOUSE_CLIENT -q " + SELECT max(toUnixTimestamp(latest_fail_time)) FROM system.mutations + WHERE database = currentDatabase() AND table = 't_toggle'; + SYSTEM STOP MERGES t_toggle; + SELECT sleep(0.5) FORMAT Null; + SYSTEM START MERGES t_toggle; + SELECT max(toUnixTimestamp(latest_fail_time)) FROM system.mutations + WHERE database = currentDatabase() AND table = 't_toggle'") + [[ "${#stamps[@]}" -eq 2 && "${stamps[0]}" == "${stamps[1]}" ]] || continue + # A released blocker answers every later poll with "not cancelled", so a cancellation recorded + # after the release can only come from one that was persisted. An earlier one would only show + # the read reading the blocker itself, which the arm above already covers. + seen_deadline=$((SECONDS + 10)) + while [[ "$SECONDS" -lt "$seen_deadline" ]]; do + seen=$($CLICKHOUSE_CLIENT -q " + SELECT countIf(latest_fail_reason LIKE '%Cancelled mutating parts%' + AND toUnixTimestamp(latest_fail_time) > ${stamps[1]}) + FROM system.mutations + WHERE database = currentDatabase() AND table = 't_toggle'") + if [[ "${seen:-0}" -ge 1 ]]; then + cancelled=1 + break + fi + sleep 0.5 + done +done +echo "toggle stop/start cancels the read: $cancelled" +$CLICKHOUSE_CLIENT -q "KILL MUTATION WHERE database = currentDatabase() AND table = 't_toggle' FORMAT Null" +timeout 60 $CLICKHOUSE_CLIENT -q "DROP TABLE t_toggle SYNC" >/dev/null 2>&1 From d42b1bdb8ed3cf77809f8a7135324822e951f33f Mon Sep 17 00:00:00 2001 From: Christoph Wurm Date: Sun, 1 Nov 2026 10:12:59 +0100 Subject: [PATCH 40/47] Run system log flushes in a thread group without a query context Attaching a thread group with a query context applies the query settings to the thread, including the profilers, which the flush did not have before. The profile of a `trace_log` flush would be written to `trace_log` itself. The new `ThreadGroup::createWithoutQueryContext` gives the flush only the memory tracker of the group (with the overcommit wait time), so no query settings apply to it, and the query context of the thread stays empty as before. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 703cb2a994dd9a94a290a0ebb2900f04397e2aec) Port notes: taken in part, only the root constructor and `ThreadGroup::createWithoutQueryContext` (`ThreadStatus.h`, `ThreadStatusExt.cpp`). Left out: the `SystemLog.cpp` and `test_overcommit_tracker` hunks (conflict here, not needed). The upstream context hunks assumed `createWithoutQueryMemoryTracker`, `isNested` and a two-argument child constructor, which this base lacks; the existing one-argument child constructor is kept unchanged. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Common/ThreadStatus.h | 5 +++++ src/Interpreters/ThreadStatusExt.cpp | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/Common/ThreadStatus.h b/src/Common/ThreadStatus.h index 76bcdbe9c215b..761270bffe4a6 100644 --- a/src/Common/ThreadStatus.h +++ b/src/Common/ThreadStatus.h @@ -155,6 +155,10 @@ class ThreadGroup static ThreadGroupPtr createForFlushAsyncInsertQueue(ContextPtr context, ThreadGroupPtr parent_thread_group); static ThreadGroupPtr createForExplainAnalyze(ThreadGroupPtr parent_thread_group); + /// For background work outside of any query (e.g. a system log flush): the threads of the group share its memory + /// tracker, but get no query context and so none of the query settings (e.g. the profilers). + static ThreadGroupPtr createWithoutQueryContext(ContextPtr global_context_); + std::vector getInvolvedThreadIds() const; size_t getPeakThreadsUsage() const; UInt64 getGroupElapsedMs() const; @@ -184,6 +188,7 @@ class ThreadGroup explicit ThreadGroup(ThreadGroupPtr parent_thread_group); ThreadGroup(ContextPtr query_context_, ThreadGroupPtr parent_thread_group); + explicit ThreadGroup(const ContextWeakPtr & global_context_); }; /** Encapsulates all per-thread info (ProfileEvents, MemoryTracker, query_id, query context, etc.). diff --git a/src/Interpreters/ThreadStatusExt.cpp b/src/Interpreters/ThreadStatusExt.cpp index 65de606b7d380..5a99c86455b66 100644 --- a/src/Interpreters/ThreadStatusExt.cpp +++ b/src/Interpreters/ThreadStatusExt.cpp @@ -131,6 +131,15 @@ ThreadGroup::ThreadGroup(ContextPtr query_context_, Int32 os_threads_nice_value_ }; } +// c-tor for method createWithoutQueryContext +ThreadGroup::ThreadGroup(const ContextWeakPtr & global_context_) + : master_thread_id(CurrentThread::get().thread_id) + , global_context(global_context_) + , os_threads_nice_value(0) + , memory_spill_scheduler(std::make_shared()) +{ +} + ThreadGroup::ThreadGroup(ThreadGroupPtr parent_thread_group) : parent(std::move(parent_thread_group)) , master_thread_id(parent->master_thread_id) @@ -269,6 +278,11 @@ ThreadGroupPtr ThreadGroup::createForMaterializedView(ContextPtr context) return res_group; } +ThreadGroupPtr ThreadGroup::createWithoutQueryContext(ContextPtr global_context_) +{ + return ThreadGroupPtr(new ThreadGroup(ContextWeakPtr(global_context_->getGlobalContext()))); +} + ThreadGroupPtr ThreadGroup::createForExplainAnalyze(ThreadGroupPtr parent_thread_group) { return ThreadGroupPtr(new ThreadGroup(parent_thread_group)); From 685fa523088f44e24e1677157dad892b727c9b34 Mon Sep 17 00:00:00 2001 From: Christoph Wurm Date: Fri, 13 Nov 2026 12:43:22 +0000 Subject: [PATCH 41/47] Keep the profilers of a thread when it detaches from a group without a query context Pool threads, including the system log saving threads, start the global CPU and real time profilers once, in the same `ThreadStatus` slots as the query profilers. Detaching from a thread group always destroyed them, and attaching a group without a query context does not recreate them, so each saving thread lost global profiling after its first flush. Such a group does not set up query profilers, so detaching it now keeps the profilers of the thread. Nested groups inherit this from their parent. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 030903ff155f95495bcbe4809921fca664e69d7f) Port notes: one conflict, in `ThreadStatus::detachFromGroup`. Upstream wraps the finalization in `if (boundToOSThread())`, which this base lacks; the base's unconditional `finalizeQueryProfiler` and `finalizePerformanceCounters` are kept and only `finalizeQueryProfiler` is made conditional on `thread_group->with_query_context`. The flag is propagated by the one-argument child constructor; the constructor taking a query context keeps the default `true`. Also restores the `memory_tracker` initializer of the root constructor as upstream master has it (no peak-memory log line when such a group is destroyed), which the partial port of `703cb2a994d` did not carry. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- src/Common/ThreadStatus.h | 4 ++++ src/Interpreters/ThreadStatusExt.cpp | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Common/ThreadStatus.h b/src/Common/ThreadStatus.h index 761270bffe4a6..f221cbe86c982 100644 --- a/src/Common/ThreadStatus.h +++ b/src/Common/ThreadStatus.h @@ -92,6 +92,10 @@ class ThreadGroup const ContextWeakPtr query_context; const ContextWeakPtr global_context; + /// False for a group from `createWithoutQueryContext` and the groups nested in it: attaching them does not set up + /// query profilers, so detaching keeps the profilers of the thread (e.g. the global profiler of a pool thread). + const bool with_query_context = true; + const FatalErrorCallback fatal_error_callback; const Int32 os_threads_nice_value; diff --git a/src/Interpreters/ThreadStatusExt.cpp b/src/Interpreters/ThreadStatusExt.cpp index 5a99c86455b66..2c230f24b63cc 100644 --- a/src/Interpreters/ThreadStatusExt.cpp +++ b/src/Interpreters/ThreadStatusExt.cpp @@ -135,8 +135,10 @@ ThreadGroup::ThreadGroup(ContextPtr query_context_, Int32 os_threads_nice_value_ ThreadGroup::ThreadGroup(const ContextWeakPtr & global_context_) : master_thread_id(CurrentThread::get().thread_id) , global_context(global_context_) + , with_query_context(false) , os_threads_nice_value(0) , memory_spill_scheduler(std::make_shared()) + , memory_tracker(&total_memory_tracker, VariableContext::Process, /*log_peak_memory_usage_in_destructor*/ false) { } @@ -145,6 +147,7 @@ ThreadGroup::ThreadGroup(ThreadGroupPtr parent_thread_group) , master_thread_id(parent->master_thread_id) , query_context(parent->query_context) , global_context(parent->global_context) + , with_query_context(parent->with_query_context) , fatal_error_callback(parent->fatal_error_callback) , os_threads_nice_value(parent->os_threads_nice_value) , memory_spill_scheduler(parent->memory_spill_scheduler) @@ -447,7 +450,8 @@ void ThreadStatus::detachFromGroup() /// flush untracked memory before resetting memory_tracker parent flushUntrackedMemory(); - finalizeQueryProfiler(); + if (thread_group->with_query_context) + finalizeQueryProfiler(); finalizePerformanceCounters(); performance_counters.setParent(&ProfileEvents::global_counters); From 495b18d5df7d10cffbfdb655f74cde17158ad348 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sun, 29 Nov 2026 06:04:31 +0100 Subject: [PATCH 42/47] Test thread group switching with a group that has no query context A thread attached to such a group, or to a child of it, gets its original group and name back on detach, and the child reports `with_query_context` as `false`. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- .../tests/gtest_thread_group_switcher.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/Common/tests/gtest_thread_group_switcher.cpp b/src/Common/tests/gtest_thread_group_switcher.cpp index 6ea889809c7cf..93f72864ec946 100644 --- a/src/Common/tests/gtest_thread_group_switcher.cpp +++ b/src/Common/tests/gtest_thread_group_switcher.cpp @@ -130,4 +130,49 @@ TEST(ThreadGroupSwitcher, RestoresBorrowedThreadName) t.join(); } +/// A group without a query context, and a child of it, attach and detach like any other group: +/// the original group and name come back. +TEST(ThreadGroupSwitcher, WithoutQueryContextRestoresGroupAndName) +{ + std::thread t([&] + { + ThreadStatus ts; + auto context = getContext().context; + auto G0 = std::make_shared(context, 0); + auto contextless = ThreadGroup::createWithoutQueryContext(context); + auto child = ThreadGroup::createForExplainAnalyze(contextless); + + EXPECT_TRUE(G0->with_query_context); + EXPECT_FALSE(contextless->with_query_context); + EXPECT_FALSE(child->with_query_context); + EXPECT_TRUE(ThreadGroup::createForExplainAnalyze(G0)->with_query_context); + + /// Starting detached. + for (const auto & group : {contextless, child}) + { + { + ThreadGroupSwitcher switcher(group, ThreadName::MERGE_MUTATE); + EXPECT_EQ(getCurrentThreadGroup(), group); + } + EXPECT_EQ(getCurrentThreadGroup(), nullptr); + } + + /// Starting attached to G0 and named. + setThreadName(ThreadName::TCP_HANDLER); + CurrentThread::attachToGroupIfDetached(G0); + for (const auto & group : {contextless, child}) + { + { + ThreadGroupSwitcher switcher(group, ThreadName::MERGE_MUTATE, /*allow_existing_group*/ true); + EXPECT_EQ(getCurrentThreadGroup(), group); + EXPECT_EQ(getThreadName(), ThreadName::MERGE_MUTATE); + } + EXPECT_EQ(getCurrentThreadGroup(), G0); + EXPECT_EQ(getThreadName(), ThreadName::TCP_HANDLER); + } + CurrentThread::detachFromGroupIfNotDetached(); + }); + t.join(); +} + } // namespace DB From 7ee546cda39da930b2da4892297a3068a8fb3833 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sun, 29 Nov 2026 21:49:42 +0100 Subject: [PATCH 43/47] Cancel replication fetches and part moves that are blocked in a write A merge can be cancelled at any depth: its list entry owns a thread group, the task runs on it, and the group carries cancellation predicates. A replicated fetch and a part move had no thread group. Their cancellation checks sit on the read side (a fetch: each chunk received and between files; a move: each copied buffer and before the swap), so a write that blocks after the last of them ran to its end: a request to object storage that keeps retrying held `SYSTEM STOP FETCHES`, `SYSTEM STOP MOVES` and a server shutdown for the whole retry budget. Give both operations what a merge has. - `ThreadGroup::createForBackgroundOperation` makes a group without a query context, or a child of the caller's group when there is one, so a query's limits and its kill still apply. It is not `createForMergeMutate`: the memory of a fetch or a move must not count against merges and mutations. - `installCancellationPredicates` composes the group's inherited predicates with the operation's own stop: a shared latch and copies of the `ActionBlocker`s. The predicates own what they add, because threads of a writer pool can call them after the list entry is gone. - A fetch runs under its group from the registration in `system.replicated_fetches` through the commit of the downloaded part. Its predicates read the entry's flag and the fetcher's blocker. - A move runs the clone under its group. The copy hook and the check before the swap call the group's predicate. `MovesList::cancelAll` is a blocker cancelled for good that every move reads; `Context::shutdown` calls it next to the cancellation of merges and fetches, so a move no longer holds a shutdown. - Cleanup after a stop runs under a `QueryCancellationBlocker`, so its requests keep their retries: the removal of a stopped fetch's directory, the removal of a failed clone, and the short stretch between publishing a fetched or cloned part and arming its removal. A fetch stopped through a query (`QUERY_WAS_CANCELLED`) is cleaned up like one stopped with `ABORTED`, and a failure of that cleanup is logged and does not replace the cancellation. Behavior: | Signal | Fetch | Move | |---|---|---| | `SYSTEM STOP FETCHES` / `SYSTEM STOP MOVES`, `DROP TABLE`, `DETACH TABLE` | the existing read-side checks, and now a retry of a write request | the copy hook and the check before the swap, and now a retry of a write request | | server shutdown | the entry's flag | `MovesList::cancelAll` | | `KILL QUERY` on `ALTER ... MOVE` or `FETCH PARTITION` | unchanged: the child group calls the query's predicate first | unchanged, and it now reaches the copy hook and the swap check | Not covered: - A body that is being sent with no retry is not polled. - A byte fetch stopped after it wrote objects to an object storage disk leaves those objects: the handler removes the metadata and commits. - The repeated Keeper wait of a zero-copy move reads none of the new predicates, and a read that is already blocked in an HTTP refill is not interrupted. Either can still hold a shutdown. - A stop that coincides with a failed request in the stretch after publication can still leave a `tmp-fetch_` or `moving/` directory. - `system.part_log` rows of `DownloadPart` and `MovePart` do not gain the counters of the worker threads. A query-run fetch or move shows more rows in `system.query_thread_log` under the same query id, because the thread attaches to the child group. Tests: `gtest_background_operation_cancellation.cpp`, and `test_fetch_move_cancellation_s3`: a fetch and a move onto an S3 disk whose writes answer 503 are stopped by the statement, by SIGTERM and by `KILL QUERY`, and a failed first request of the clone cleanup is retried. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Fable 5.2 --- src/Common/ThreadStatus.h | 8 +- src/Interpreters/Context.cpp | 17 +- src/Interpreters/ThreadStatusExt.cpp | 7 + .../BackgroundOperationCancellation.cpp | 80 +++ .../BackgroundOperationCancellation.h | 42 ++ .../MergeTree/DataPartStorageOnDiskBase.cpp | 5 + src/Storages/MergeTree/DataPartsExchange.cpp | 73 ++- src/Storages/MergeTree/MergeTreeData.cpp | 33 +- .../MergeTree/MergeTreePartsMover.cpp | 26 +- src/Storages/MergeTree/MergeTreePartsMover.h | 11 +- src/Storages/MergeTree/MovesList.cpp | 5 + src/Storages/MergeTree/MovesList.h | 18 + src/Storages/MergeTree/ReplicatedFetchList.h | 15 +- ...test_background_operation_cancellation.cpp | 278 ++++++++ .../integration/helpers/s3_mocks/broken_s3.py | 169 ++++- .../__init__.py | 0 .../configs/mover_storage.xml | 42 ++ .../configs/receiver_storage.xml | 20 + .../configs/source_storage.xml | 9 + .../test_fetch_move_cancellation_s3/test.py | 601 ++++++++++++++++++ 20 files changed, 1415 insertions(+), 44 deletions(-) create mode 100644 src/Storages/MergeTree/BackgroundOperationCancellation.cpp create mode 100644 src/Storages/MergeTree/BackgroundOperationCancellation.h create mode 100644 src/Storages/MergeTree/tests/gtest_background_operation_cancellation.cpp create mode 100644 tests/integration/test_fetch_move_cancellation_s3/__init__.py create mode 100644 tests/integration/test_fetch_move_cancellation_s3/configs/mover_storage.xml create mode 100644 tests/integration/test_fetch_move_cancellation_s3/configs/receiver_storage.xml create mode 100644 tests/integration/test_fetch_move_cancellation_s3/configs/source_storage.xml create mode 100644 tests/integration/test_fetch_move_cancellation_s3/test.py diff --git a/src/Common/ThreadStatus.h b/src/Common/ThreadStatus.h index f221cbe86c982..86018eafe7462 100644 --- a/src/Common/ThreadStatus.h +++ b/src/Common/ThreadStatus.h @@ -123,7 +123,7 @@ class ThreadGroup ThrowIfQueryCanceledPredicate throw_if_query_canceled_predicate = {}; }; - SharedData getSharedData() + SharedData getSharedData() const { /// Critical section for making the copy of shared_data std::lock_guard lock(mutex); @@ -163,6 +163,12 @@ class ThreadGroup /// tracker, but get no query context and so none of the query settings (e.g. the profilers). static ThreadGroupPtr createWithoutQueryContext(ContextPtr global_context_); + /// For a background operation that owns its cancellation (e.g. a replication fetch or a part move): the group of + /// its own, nested in `parent` if there is one (it inherits the predicates of the parent), else without a query + /// context. It is not `createForMergeMutate`: the memory of a fetch or move must not count against the merges and +/// mutations tracker, unless `parent` is a merge's group. + static ThreadGroupPtr createForBackgroundOperation(ContextPtr global_context_, ThreadGroupPtr parent_thread_group); + std::vector getInvolvedThreadIds() const; size_t getPeakThreadsUsage() const; UInt64 getGroupElapsedMs() const; diff --git a/src/Interpreters/Context.cpp b/src/Interpreters/Context.cpp index f718b14aad35c..4ef66e7117813 100644 --- a/src/Interpreters/Context.cpp +++ b/src/Interpreters/Context.cpp @@ -1084,13 +1084,13 @@ struct ContextSharedPart : boost::noncopyable StreamingStorageRegistry::instance().shutdown(); /// Stop all MergeTree background executors and cancel the in-flight merges, - /// mutations and fetches, in this order: + /// mutations, fetches and moves, in this order: /// /// 1. Flip every executor into shutdown mode without joining it. From this point on /// no new task can be scheduled (`trySchedule` rejects them) and no pending task /// can start (worker threads exit at the next step boundary), so the set of /// running tasks cannot grow. - /// 2. Cancel everything that is currently running. `cancelAll` also marks entries + /// 2. Cancel the running merges, mutations, fetches and moves. `cancelAll` also marks entries /// inserted later as cancelled, so a task that is inside its first step and has /// not registered itself in the list yet cannot escape the cancellation. /// 3. Join the executors. @@ -1101,13 +1101,17 @@ struct ContextSharedPart : boost::noncopyable /// current task step completes, and a single slow step (e.g. a merge applying huge /// patch parts, which can spend minutes inside one block under sanitizers, or a /// fetch of a large part) would delay shutdown beyond any timeout. The results of - /// these merges and fetches are discarded after the restart anyway, so finishing - /// them is pure waste. Without step 1, the cancellation would be racy: a task + /// merges and fetches are discarded after the restart anyway, so finishing them is pure + /// waste. A finished move is kept, but it would only delay the shutdown. A running export step + /// is not cancelled and is waited for: the manifest of a direct `EXPORT PART` lives in memory + /// only, so a cancelled export would not be resumed. Without step 1, the cancellation would be racy: a task /// scheduled after step 2 would be invisible to `cancelAll` and block `wait` again. /// /// Merge and mutate tasks check `MergeListElement::is_cancelled` on every block /// through `MergeProgressCallback` and abort with the `ABORTED` exception; fetches - /// check `ReplicatedFetchListElement::is_cancelled` on every buffer refill. + /// check `ReplicatedFetchListElement::is_cancelled` on every buffer refill. Fetches and moves + /// also run in their own thread group, whose predicates see `cancelAll` of their list, so + /// the writes below them stop as well. /// /// Waiting for the executors before shutting down databases also ensures no /// background task is accessing a storage's data (e.g. data_parts_indexes) while @@ -1123,9 +1127,10 @@ struct ContextSharedPart : boost::noncopyable if (common_executor) common_executor->requestShutdown(); - LOG_TRACE(log, "Cancelling merges, mutations and fetches"); + LOG_TRACE(log, "Cancelling merges, mutations, fetches and moves"); merge_list.cancelAll(); replicated_fetch_list.cancelAll(); + moves_list.cancelAll(); SHUTDOWN(log, "merges executor", merge_mutate_executor, wait()); SHUTDOWN(log, "fetches executor", fetch_executor, wait()); diff --git a/src/Interpreters/ThreadStatusExt.cpp b/src/Interpreters/ThreadStatusExt.cpp index 2c230f24b63cc..94ca3382a8e5f 100644 --- a/src/Interpreters/ThreadStatusExt.cpp +++ b/src/Interpreters/ThreadStatusExt.cpp @@ -286,6 +286,13 @@ ThreadGroupPtr ThreadGroup::createWithoutQueryContext(ContextPtr global_context_ return ThreadGroupPtr(new ThreadGroup(ContextWeakPtr(global_context_->getGlobalContext()))); } +ThreadGroupPtr ThreadGroup::createForBackgroundOperation(ContextPtr global_context_, ThreadGroupPtr parent_thread_group) +{ + if (!parent_thread_group) + return createWithoutQueryContext(std::move(global_context_)); + return ThreadGroupPtr(new ThreadGroup(std::move(parent_thread_group))); +} + ThreadGroupPtr ThreadGroup::createForExplainAnalyze(ThreadGroupPtr parent_thread_group) { return ThreadGroupPtr(new ThreadGroup(parent_thread_group)); diff --git a/src/Storages/MergeTree/BackgroundOperationCancellation.cpp b/src/Storages/MergeTree/BackgroundOperationCancellation.cpp new file mode 100644 index 0000000000000..322a2cdd0952d --- /dev/null +++ b/src/Storages/MergeTree/BackgroundOperationCancellation.cpp @@ -0,0 +1,80 @@ +#include + +#include +#include + +namespace DB +{ + +namespace ErrorCodes +{ + extern const int ABORTED; + extern const int CANNOT_SCHEDULE_TASK; + extern const int LOGICAL_ERROR; +} + +namespace +{ + +/// Copies share the latch and the counters of the blockers. +struct StopPoll +{ + std::shared_ptr stopped; + std::vector blockers; + + bool operator()() const + { + if (stopped->load(std::memory_order_relaxed)) + return true; + for (const auto & blocker : blockers) + { + if (blocker.isCancelled()) + { + stopped->store(true, std::memory_order_relaxed); + return true; + } + } + return false; + } +}; + +} + +void installCancellationPredicates( + ThreadGroup & group, + std::shared_ptr stopped, + std::vector blockers, + std::string what) +{ + auto inherited = group.getSharedData(); + StopPoll poll{std::move(stopped), std::move(blockers)}; + + group.setQueryCancellationPredicates( + [inherited_is_canceled = std::move(inherited.query_is_canceled_predicate), poll]() -> bool + { + return (inherited_is_canceled && inherited_is_canceled()) || poll(); + }, + [inherited_throw = std::move(inherited.throw_if_query_canceled_predicate), poll, message = std::move(what)]() + { + if (inherited_throw) + inherited_throw(); + if (poll()) + throw Exception(ErrorCodes::ABORTED, "{}", message); + }); +} + +ThrowIfQueryCanceledPredicate getThrowingCancellationPredicate(const ThreadGroup & group) +{ + auto predicate = group.getSharedData().throw_if_query_canceled_predicate; + if (!predicate) + throw Exception(ErrorCodes::LOGICAL_ERROR, "No cancellation predicate installed on the thread group"); + return predicate; +} + +void checkAttachedTo(const ThreadGroupPtr & group) +{ + if (CurrentThread::getGroup() != group) + throw Exception(ErrorCodes::CANNOT_SCHEDULE_TASK, "Cannot attach the thread to the thread group of the background operation"); +} + +} diff --git a/src/Storages/MergeTree/BackgroundOperationCancellation.h b/src/Storages/MergeTree/BackgroundOperationCancellation.h new file mode 100644 index 0000000000000..cd5fec1233517 --- /dev/null +++ b/src/Storages/MergeTree/BackgroundOperationCancellation.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace DB +{ + +/// Makes `group` report a stop when `stopped` is set or any of `blockers` is cancelled, in addition to whatever the +/// group already reports (a nested group inherits the predicates of its parent). The Boolean predicate returns true +/// when the inherited predicate does or when `stopped` is set or a blocker is cancelled; the +/// throwing one calls the inherited throwing predicate first and then throws `ABORTED` with `what`. +/// +/// Must be called before any thread attaches to the group. A poll that sees a cancelled blocker sets `stopped`, so the +/// stop outlives the blocker being released; a blocker that is cancelled and released between two polls is not seen. +/// The predicates own everything this function adds (the latch, the blockers, the message). The inherited ones +/// borrow their ancestor: a parent group, or the list entry of a merge, which no group owns. A copy of a predicate +/// is valid while the operation that installed the inherited predicates is alive. Holding the group is necessary +/// but not sufficient. +void installCancellationPredicates( + ThreadGroup & group, + std::shared_ptr stopped, + std::vector blockers, + std::string what); + +/// An owned copy of the throwing predicate of `group`, for checks made after the thread has left the group. +/// The copy is valid only while `group` is alive and the operation that installed its inherited predicates is +/// (see `installCancellationPredicates`). +/// Never empty: throws `LOGICAL_ERROR` if no predicate was installed, which means a call site forgot +/// `installCancellationPredicates`. +ThrowIfQueryCanceledPredicate getThrowingCancellationPredicate(const ThreadGroup & group); + +/// Throws `CANNOT_SCHEDULE_TASK` unless the current thread is attached to `group`. `ThreadGroupSwitcher` only logs +/// a failed attach, and an operation that goes on outside its group could not be stopped. +void checkAttachedTo(const ThreadGroupPtr & group); + +} diff --git a/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp b/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp index b0646313fe027..7fe6dbecfe2ff 100644 --- a/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp +++ b/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -921,6 +922,10 @@ MutableDataPartStoragePtr DataPartStorageOnDiskBase::clonePart( } catch (...) { + /// The copy may have failed because the move was cancelled, and the cancelled group is still + /// attached: the removal must keep the retries of its own requests. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + /// It's safe to remove it recursively (even with zero-copy-replication) /// because we've just did full copy through copyDirectoryContent LOG_WARNING(log, "Removing directory {} after failed attempt to move a data part", path_to_clone); diff --git a/src/Storages/MergeTree/DataPartsExchange.cpp b/src/Storages/MergeTree/DataPartsExchange.cpp index fdb0511079343..c056a487e53b4 100644 --- a/src/Storages/MergeTree/DataPartsExchange.cpp +++ b/src/Storages/MergeTree/DataPartsExchange.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -35,6 +36,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -85,6 +89,7 @@ namespace ErrorCodes extern const int INSECURE_PATH; extern const int LOGICAL_ERROR; extern const int NO_REPLICA_HAS_PART; + extern const int QUERY_WAS_CANCELLED; extern const int S3_ERROR; extern const int ZERO_COPY_REPLICATION_ERROR; } @@ -185,7 +190,7 @@ struct ReplicatedFetchReadCallback { /// The entry is cancelled on server shutdown - there is no point in finishing /// the download, its result would be discarded anyway. - if (replicated_fetch_entry->is_cancelled) + if (replicated_fetch_entry->is_cancelled->load()) throw Exception(ErrorCodes::ABORTED, "Fetching of part {} was cancelled", replicated_fetch_entry->result_part_name); @@ -998,8 +1003,27 @@ std::pair Fetcher::fetchSelected part_info.getPartitionId(), part_name, new_part_path, replica_path, uri, to_detached, sum_files_size); + /// Run the fetch in its own thread group, so that a stop reaches the writes below it (requests to the + /// destination and their retries) and not only the reads of the response. The predicates are installed + /// before any thread attaches to the group. + auto thread_group = ThreadGroup::createForBackgroundOperation(data.getContext(), CurrentThread::getGroup()); + installCancellationPredicates(*thread_group, (*entry)->is_cancelled, {blocker}, "Fetching of part was cancelled"); + std::optional group_switcher; + group_switcher.emplace(thread_group, getThreadName(), /*allow_existing_group=*/ true); + checkAttachedTo(thread_group); + in->setNextCallback(ReplicatedFetchReadCallback(*entry)); + /// Ends this attempt before a retry that calls this function again: the response must no longer touch the + /// entry, the group is left before the entry and the directory lock are released. + auto end_attempt = [&] + { + in->setNextCallback([](size_t) {}); + group_switcher.reset(); + entry.reset(); + temporary_directory_lock = {}; + }; + /// CAS replication — fetch-by-relink (`part_manifest_v2`). The sender /// chose to relink: it sent only the part's encoded PartManifest body, no file bytes, and the /// reservation above already went to the offered pool's disk. Build the part by staging this @@ -1029,8 +1053,7 @@ std::pair Fetcher::fetchSelected auto fall_back_to_byte_fetch = [&] { /// The recursive call registers its own entry in the `ReplicatedFetchList`. - entry.reset(); - temporary_directory_lock = {}; + end_attempt(); return fetchSelectedPart( metadata_snapshot, context, part_name, zookeeper_name, replica_path, host, port, timeouts, user, password, interserver_scheme, throttler, to_detached, tmp_prefix, nullptr, false, disk, @@ -1122,9 +1145,7 @@ std::pair Fetcher::fetchSelected LOG_WARNING(log, "Will retry fetching part without zero-copy: {}", e.message()); /// The recursive call registers its own entry in the `ReplicatedFetchList`. - /// `in` still holds a callback referencing this entry, but it is never read after this point. - entry.reset(); - temporary_directory_lock = {}; + end_attempt(); /// Try again but without zero-copy. `allow_ca_relink=false` for the same reason as the relink /// branch's fallback above: this is a same-sender byte re-request, and it must not re-open a @@ -1350,12 +1371,29 @@ MergeTreeData::MutableDataPartPtr Fetcher::downloadPartToDisk( catch (const Exception & e) { /// Remove the whole part directory if fetch of base - /// part or fetch of any projection was stopped. - if (e.code() == ErrorCodes::ABORTED) + /// part or fetch of any projection was stopped. A fetch run by a query is stopped by the + /// inherited predicate of the query, which throws `QUERY_WAS_CANCELLED`. + if (e.code() == ErrorCodes::ABORTED || e.code() == ErrorCodes::QUERY_WAS_CANCELLED) { - part_storage_for_loading->removeSharedRecursive(true); - if (part_storage_for_loading->hasActiveTransaction()) - part_storage_for_loading->commitTransaction(); + /// The group's predicates already report the stop, which would end the retries of this cleanup. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + try + { + part_storage_for_loading->removeSharedRecursive(true); + if (part_storage_for_loading->hasActiveTransaction()) + part_storage_for_loading->commitTransaction(); + } + catch (...) + { + /// Nothing may replace the stop that is rethrown below, and building the log prefix can throw. + try + { + tryLogCurrentException(log, "Cannot remove the directory of the stopped fetch"); + } + catch (...) // NOLINT(bugprone-empty-catch) + { + } + } } throw; } @@ -1367,11 +1405,16 @@ MergeTreeData::MutableDataPartPtr Fetcher::downloadPartToDisk( if (part_storage_for_loading->hasActiveTransaction()) part_storage_for_loading->commitTransaction(); - MergeTreeDataPartBuilder builder(data, part_name, volume, part_relative_path, part_dir, getReadSettings(), PartDirIntent::OpenExisting); - new_data_part = builder.withPartFormatFromDisk().build(); + { + /// A stop between the commit and `is_temp` would leave a directory that no part object owns. + ThreadStatus::QueryCancellationBlocker cancellation_blocker; + + MergeTreeDataPartBuilder builder(data, part_name, volume, part_relative_path, part_dir, getReadSettings(), PartDirIntent::OpenExisting); + new_data_part = builder.withPartFormatFromDisk().build(); - new_data_part->version->setAndStoreCreationTID(Tx::NonTransactionalTID, nullptr); - new_data_part->is_temp = true; + new_data_part->version->setAndStoreCreationTID(Tx::NonTransactionalTID, nullptr); + new_data_part->is_temp = true; + } /// In case of replicated merge tree with zero copy replication /// Here ClickHouse claims that this new part can be deleted in temporary state without unlocking the blobs /// The blobs have to stay intact, this temporary part does not own them and does not share them yet. diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index 0ad726011e298..2f02b517b8c75 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -4,12 +4,15 @@ #include #include #include +#include #include #include #include #include #include #include +#include +#include #include #include @@ -12343,6 +12346,28 @@ MovePartsOutcome MergeTreeData::moveParts(const CurrentlyMovingPartsTaggerPtr & moving_part.reserved_space->getDisk()->getPath(), moving_part.part->getBytesOnDisk()); + /// The move runs in its own thread group, so that a stop (`SYSTEM STOP MOVES`, server shutdown, a killed + /// parent query) reaches the writes of the clone and not only the checks between its steps. + auto thread_group = ThreadGroup::createForBackgroundOperation(getContext(), CurrentThread::getGroup()); + installCancellationPredicates( + *thread_group, + (*moves_list_entry)->is_cancelled, + {parts_mover.moves_blocker, getContext()->getMovesList().getShutdownBlocker()}, + "Cancelled moving parts."); + + /// An owned copy, for the hook of `clonePart` (called inside the group) and for the checks made after + /// `clone_in_group` returned, when the group is no longer current. + /// `thread_group` is held because the copy calls the predicates the group inherited. Those can borrow + /// state the group does not own (a merge's list entry), which the enclosing task keeps alive. + const auto throw_if_cancelled = getThrowingCancellationPredicate(*thread_group); + + auto clone_in_group = [&] + { + ThreadGroupSwitcher group_switcher(thread_group, getThreadName(), /*allow_existing_group=*/ true); + checkAttachedTo(thread_group); + return parts_mover.clonePart(moving_part, read_settings, write_settings, throw_if_cancelled); + }; + try { /// If zero-copy replication enabled than replicas shouldn't try to @@ -12387,12 +12412,12 @@ MovePartsOutcome MergeTreeData::moveParts(const CurrentlyMovingPartsTaggerPtr & if (lock->isLocked()) { - cloned_part = parts_mover.clonePart(moving_part, read_settings, write_settings); + cloned_part = clone_in_group(); /// Cloning part can take a long time. /// Recheck if the lock (and keeper session expirity) is OK if (lock->isLocked()) { - parts_mover.swapClonedPart(cloned_part); + parts_mover.swapClonedPart(cloned_part, throw_if_cancelled); break; /// Successfully moved } else @@ -12420,8 +12445,8 @@ MovePartsOutcome MergeTreeData::moveParts(const CurrentlyMovingPartsTaggerPtr & } else /// Ordinary move as it should be { - cloned_part = parts_mover.clonePart(moving_part, read_settings, write_settings); - parts_mover.swapClonedPart(cloned_part); + cloned_part = clone_in_group(); + parts_mover.swapClonedPart(cloned_part, throw_if_cancelled); } write_part_log({}); } diff --git a/src/Storages/MergeTree/MergeTreePartsMover.cpp b/src/Storages/MergeTree/MergeTreePartsMover.cpp index 7638d6d43cb35..4203ce57819b4 100644 --- a/src/Storages/MergeTree/MergeTreePartsMover.cpp +++ b/src/Storages/MergeTree/MergeTreePartsMover.cpp @@ -18,7 +18,6 @@ namespace MergeTreeSetting namespace ErrorCodes { - extern const int ABORTED; extern const int DIRECTORY_ALREADY_EXISTS; } @@ -220,13 +219,13 @@ bool MergeTreePartsMover::selectPartsForMove( return false; } -MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const MergeTreeMoveEntry & moving_part, const ReadSettings & read_settings, const WriteSettings & write_settings) const +MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart( + const MergeTreeMoveEntry & moving_part, + const ReadSettings & read_settings, + const WriteSettings & write_settings, + const ThrowIfQueryCanceledPredicate & throw_if_cancelled) const { - auto cancellation_hook = [&my_moves_blocker = moves_blocker]() - { - if (my_moves_blocker.isCancelled()) - throw Exception(ErrorCodes::ABORTED, "Cancelled moving parts."); - }; + auto cancellation_hook = [throw_if_cancelled]() { throw_if_cancelled(); }; cancellation_hook(); auto settings = data->getSettings(); @@ -238,6 +237,10 @@ MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const Me MutableDataPartStoragePtr cloned_part_storage; bool preserve_blobs = false; + + /// From the moment the clone exists until the part object owns it (`is_temp` and the removal policy), + /// a stop must not fail a request and leave a directory that nothing removes. + std::optional ownership_handoff_blocker; if (disk->supportZeroCopyReplication() && (*settings)[MergeTreeSetting::allow_remote_fs_zero_copy_replication]) { /// Try zero-copy replication and fallback to default copy if it's not possible @@ -264,6 +267,7 @@ MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const Me if (zero_copy_part) { + ownership_handoff_blocker.emplace(); /// FIXME for some reason we cannot just use this part, we have to re-create it through MergeTreeDataPartBuilder preserve_blobs = true; zero_copy_part->is_temp = false; /// Do not remove it in dtor @@ -274,11 +278,13 @@ MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const Me LOG_INFO(log, "Part {} was not fetched, we are the first who move it to another disk, so we will copy it", part->name); cloned_part_storage = part->getDataPartStorage().clonePart( path_to_clone, part->getDataPartStorage().getPartDirectory(), disk, read_settings, write_settings, log, cancellation_hook); + ownership_handoff_blocker.emplace(); } } else { cloned_part_storage = part->makeCloneOnDisk(disk, MergeTreeData::MOVING_DIR_NAME, read_settings, write_settings, cancellation_hook); + ownership_handoff_blocker.emplace(); } MergeTreeDataPartBuilder builder(*data, part->name, cloned_part_storage, getReadSettings(), PartDirIntent::OpenExisting); @@ -296,6 +302,7 @@ MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const Me else cloned_part.part->remove_tmp_policy = IMergeTreeDataPart::BlobsRemovalPolicyForTemporaryParts::REMOVE_BLOBS; } + ownership_handoff_blocker.reset(); cloned_part.part->loadColumnsChecksumsIndexes(true, true); cloned_part.part->version->loadAndUpdateMetadata(); cloned_part.part->modification_time = cloned_part.part->getDataPartStorage().getLastModified().epochTime(); @@ -325,12 +332,11 @@ catch (...) throw; } -void MergeTreePartsMover::swapClonedPart(TemporaryClonedPart & cloned_part) const +void MergeTreePartsMover::swapClonedPart(TemporaryClonedPart & cloned_part, const ThrowIfQueryCanceledPredicate & throw_if_cancelled) const { /// Used to get some stuck parts in the moving directory by stopping moves while pause is active FailPointInjection::pauseFailPoint(FailPoints::stop_moving_part_before_swap_with_active); - if (moves_blocker.isCancelled()) - throw Exception(ErrorCodes::ABORTED, "Cancelled moving parts."); + throw_if_cancelled(); /// `getActiveContainingPart` and `swapActivePart` are called under the same lock /// to prevent part becoming inactive between calls diff --git a/src/Storages/MergeTree/MergeTreePartsMover.h b/src/Storages/MergeTree/MergeTreePartsMover.h index 7a6583008c0d0..5dd6c56a71a4a 100644 --- a/src/Storages/MergeTree/MergeTreePartsMover.h +++ b/src/Storages/MergeTree/MergeTreePartsMover.h @@ -8,6 +8,7 @@ #include #include #include +#include namespace DB { @@ -66,14 +67,20 @@ class MergeTreePartsMover const std::lock_guard & moving_parts_lock); /// Copies part to selected reservation in detached folder. Throws exception if part already exists. - TemporaryClonedPart clonePart(const MergeTreeMoveEntry & moving_part, const ReadSettings & read_settings, const WriteSettings & write_settings) const; + /// `throw_if_cancelled` is called between the steps of the copy; it throws when the move must stop. + TemporaryClonedPart clonePart( + const MergeTreeMoveEntry & moving_part, + const ReadSettings & read_settings, + const WriteSettings & write_settings, + const ThrowIfQueryCanceledPredicate & throw_if_cancelled) const; /// Replaces cloned part from detached directory into active data parts set. /// Replacing part changes state to DeleteOnDestroy and will be removed from disk after destructor of /// IMergeTreeDataPart called. If replacing part doesn't exists or not active (committed) than /// cloned part will be removed and log message will be reported. It may happen in case of concurrent /// merge or mutation. - void swapClonedPart(TemporaryClonedPart & cloned_part) const; + /// `throw_if_cancelled` is called once before the part is locked and renamed. + void swapClonedPart(TemporaryClonedPart & cloned_part, const ThrowIfQueryCanceledPredicate & throw_if_cancelled) const; /// Rename cloned part from `moving/` directory to the actual part storage void renameClonedPart(IMergeTreeDataPart & part) const; diff --git a/src/Storages/MergeTree/MovesList.cpp b/src/Storages/MergeTree/MovesList.cpp index 730cd44a69791..4a1cf0e0fe4b7 100644 --- a/src/Storages/MergeTree/MovesList.cpp +++ b/src/Storages/MergeTree/MovesList.cpp @@ -20,6 +20,11 @@ MovesListElement::MovesListElement( { } +void MovesList::cancelAll() +{ + shutdown_blocker.cancelForever(); +} + MoveInfo MovesListElement::getInfo() const { MoveInfo res; diff --git a/src/Storages/MergeTree/MovesList.h b/src/Storages/MergeTree/MovesList.h index fc1e7ffaadc0e..11e910b23a263 100644 --- a/src/Storages/MergeTree/MovesList.h +++ b/src/Storages/MergeTree/MovesList.h @@ -1,9 +1,12 @@ #pragma once #include #include +#include #include #include #include +#include +#include #include namespace CurrentMetrics @@ -38,6 +41,10 @@ struct MovesListElement : private boost::noncopyable Stopwatch watch; const UInt64 thread_id; + /// Latch of the cancellation predicates of the move's thread group. Shared, because copies of the predicates + /// outlive the entry's scope. + std::shared_ptr is_cancelled = std::make_shared(false); + MovesListElement( const StorageID & table_id_, const std::string & part_name_, @@ -59,6 +66,17 @@ class MovesList final : public BackgroundProcessList MovesList() : Parent(CurrentMetrics::Move) {} + + /// Cancel all current and future moves. Used on server shutdown. + /// A move sees it through the predicates it installs on its thread group. + void cancelAll(); + + /// Every entry's predicate holds a copy. The blocker stays cancelled for good, so a move that registers after + /// `cancelAll` is stopped too. A copy shares the counter with the list, also if taken before `cancelAll`. + ActionBlocker getShutdownBlocker() const { return shutdown_blocker; } + +private: + ActionBlocker shutdown_blocker; }; } diff --git a/src/Storages/MergeTree/ReplicatedFetchList.h b/src/Storages/MergeTree/ReplicatedFetchList.h index 381f46c717804..a0416efff0b0a 100644 --- a/src/Storages/MergeTree/ReplicatedFetchList.h +++ b/src/Storages/MergeTree/ReplicatedFetchList.h @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include @@ -69,9 +71,12 @@ struct ReplicatedFetchListElement : private boost::noncopyable const UInt64 thread_id; - /// Set on server shutdown. Checked in `ReplicatedFetchReadCallback` on every buffer - /// refill of the part download, which aborts with the `ABORTED` exception. - std::atomic is_cancelled{}; + /// Set on server shutdown, or when a poll of the cancellation predicates sees the fetcher's blocker cancelled. + /// Checked in `ReplicatedFetchReadCallback` on every buffer refill of the part download, which aborts with + /// the `ABORTED` exception. + /// Shared, unlike `MergeListElement::is_cancelled`: the cancellation predicates of the fetch's thread group + /// outlive the entry's scope on other threads. + std::shared_ptr is_cancelled = std::make_shared(false); ReplicatedFetchListElement( const std::string & database_, const std::string & table_, @@ -117,7 +122,7 @@ class ReplicatedFetchList final : public BackgroundProcessListstore(true); } template @@ -125,7 +130,7 @@ class ReplicatedFetchList final : public BackgroundProcessList(args)...); if (all_cancelled) - (*entry)->is_cancelled = true; + (*entry)->is_cancelled->store(true); return entry; } }; diff --git a/src/Storages/MergeTree/tests/gtest_background_operation_cancellation.cpp b/src/Storages/MergeTree/tests/gtest_background_operation_cancellation.cpp new file mode 100644 index 0000000000000..32cae7a20a185 --- /dev/null +++ b/src/Storages/MergeTree/tests/gtest_background_operation_cancellation.cpp @@ -0,0 +1,278 @@ +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace DB +{ + +namespace ErrorCodes +{ + extern const int ABORTED; + extern const int CANNOT_SCHEDULE_TASK; + extern const int LOGICAL_ERROR; +} + +namespace FailPoints +{ + extern const char thread_group_switcher_post_attach_failure[]; +} + +namespace +{ + +/// Runs `body` on a thread with its own `ThreadStatus`, as the groups read it on creation. +template +void runOnThread(F && body) +{ + std::thread t([&] + { + ThreadStatus ts; + body(getContext().context); + }); + t.join(); +} + +int errorCodeOf(const std::function & f) +{ + try + { + f(); + } + catch (const Exception & e) + { + return e.code(); + } + return 0; +} + +} + +TEST(BackgroundOperationCancellation, ParentThrowingPredicateFiresFirst) +{ + runOnThread([](ContextPtr context) + { + auto parent = ThreadGroup::createWithoutQueryContext(context); + parent->setQueryCancellationPredicates( + [] { return false; }, + [] { throw Exception(ErrorCodes::CANNOT_SCHEDULE_TASK, "parent"); }); + + auto child = ThreadGroup::createForBackgroundOperation(context, parent); + auto stopped = std::make_shared(true); + installCancellationPredicates(*child, stopped, {}, "child"); + + /// Both are stopped; the parent's message must win. + try + { + getThrowingCancellationPredicate(*child)(); + FAIL() << "expected an exception"; + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), ErrorCodes::CANNOT_SCHEDULE_TASK); + EXPECT_NE(e.message().find("parent"), std::string::npos); + } + }); +} + +TEST(BackgroundOperationCancellation, BooleanFormInheritsAndPolls) +{ + runOnThread([](ContextPtr context) + { + auto parent_stopped = std::make_shared(false); + auto parent = ThreadGroup::createWithoutQueryContext(context); + parent->setQueryCancellationPredicates([parent_stopped] { return parent_stopped->load(); }, [] {}); + + auto child = ThreadGroup::createForBackgroundOperation(context, parent); + auto stopped = std::make_shared(false); + installCancellationPredicates(*child, stopped, {}, "stopped"); + + auto is_canceled = child->getSharedData().query_is_canceled_predicate; + EXPECT_FALSE(is_canceled()); + parent_stopped->store(true); + EXPECT_TRUE(is_canceled()); + parent_stopped->store(false); + stopped->store(true); + EXPECT_TRUE(is_canceled()); + }); +} + +TEST(BackgroundOperationCancellation, ThrowingFormSeesBlockerWithoutBooleanForm) +{ + runOnThread([](ContextPtr context) + { + ActionBlocker blocker; + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + installCancellationPredicates(*group, std::make_shared(false), {blocker}, "stopped by blocker"); + + auto throwing = getThrowingCancellationPredicate(*group); + EXPECT_EQ(errorCodeOf(throwing), 0); + + blocker.cancelForever(); + EXPECT_EQ(errorCodeOf(throwing), ErrorCodes::ABORTED); + }); +} + +TEST(BackgroundOperationCancellation, BlockerSeenCancelledLatches) +{ + runOnThread([](ContextPtr context) + { + ActionBlocker blocker; + auto stopped = std::make_shared(false); + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + installCancellationPredicates(*group, stopped, {blocker}, "stopped"); + + std::optional lock = blocker.cancel(); + auto is_canceled = group->getSharedData().query_is_canceled_predicate; + EXPECT_TRUE(is_canceled()); + EXPECT_TRUE(stopped->load()); + + lock.reset(); + EXPECT_FALSE(blocker.isCancelled()); + EXPECT_TRUE(is_canceled()); + EXPECT_EQ(errorCodeOf(getThrowingCancellationPredicate(*group)), ErrorCodes::ABORTED); + }); +} + +TEST(BackgroundOperationCancellation, PredicateOutlivesItsListEntry) +{ + runOnThread([](ContextPtr context) + { + ThrowIfQueryCanceledPredicate throwing; + QueryIsCanceledPredicate is_canceled; + { + MovesList list; + auto entry = std::make_unique(StorageID("db", "t"), "part", "disk", "/path", 1); + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + installCancellationPredicates(*group, entry->is_cancelled, {list.getShutdownBlocker()}, "stopped"); + throwing = getThrowingCancellationPredicate(*group); + is_canceled = group->getSharedData().query_is_canceled_predicate; + entry->is_cancelled->store(true); + } + /// The entry, its group and the list are gone. + EXPECT_TRUE(is_canceled()); + EXPECT_EQ(errorCodeOf(throwing), ErrorCodes::ABORTED); + }); +} + +TEST(BackgroundOperationCancellation, ExceptionUnderSwitcherLeavesOriginalGroup) +{ + runOnThread([](ContextPtr context) + { + auto original = std::make_shared(context, 0); + setThreadName(ThreadName::TCP_HANDLER); + CurrentThread::attachToGroupIfDetached(original); + auto * original_status = current_thread; + + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + installCancellationPredicates(*group, std::make_shared(true), {}, "stopped"); + + try + { + ThreadGroupSwitcher switcher(group, ThreadName::MERGE_MUTATE, /*allow_existing_group*/ true); + checkAttachedTo(group); + EXPECT_EQ(CurrentThread::getGroup(), group); + throw Exception(ErrorCodes::ABORTED, "from under the switcher"); + } + catch (const Exception & e) + { + EXPECT_EQ(e.code(), ErrorCodes::ABORTED); + } + + EXPECT_EQ(current_thread, original_status); + EXPECT_EQ(CurrentThread::getGroup(), original); + EXPECT_EQ(getThreadName(), ThreadName::TCP_HANDLER); + CurrentThread::detachFromGroupIfNotDetached(); + }); +} + +TEST(BackgroundOperationCancellation, CheckAttachedToThrowsWhenAttachFailed) +{ + runOnThread([](ContextPtr context) + { + auto original = std::make_shared(context, 0); + setThreadName(ThreadName::TCP_HANDLER); + CurrentThread::attachToGroupIfDetached(original); + + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + + FailPointInjection::enableFailPoint(FailPoints::thread_group_switcher_post_attach_failure); + { + ThreadGroupSwitcher switcher(group, ThreadName::MERGE_MUTATE, /*allow_existing_group*/ true); + EXPECT_EQ(errorCodeOf([&] { checkAttachedTo(group); }), ErrorCodes::CANNOT_SCHEDULE_TASK); + EXPECT_EQ(CurrentThread::getGroup(), original); + } + FailPointInjection::disableFailPoint(FailPoints::thread_group_switcher_post_attach_failure); + + EXPECT_EQ(CurrentThread::getGroup(), original); + CurrentThread::detachFromGroupIfNotDetached(); + }); +} + +TEST(BackgroundOperationCancellation, ChildOfContextlessRootHasNoQueryContext) +{ + runOnThread([](ContextPtr context) + { + auto root = ThreadGroup::createWithoutQueryContext(context); + auto child = ThreadGroup::createForBackgroundOperation(context, root); + EXPECT_FALSE(root->with_query_context); + EXPECT_FALSE(child->with_query_context); + }); +} + +/// A group nobody installed predicates on is a call site that forgot to; `LOGICAL_ERROR` aborts in debug and +/// sanitizer builds. +#ifndef DEBUG_OR_SANITIZER_BUILD +TEST(BackgroundOperationCancellation, ThrowingPredicateWithoutInstallThrowsLogicalError) +{ + runOnThread([](ContextPtr context) + { + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + EXPECT_EQ(errorCodeOf([&] { getThrowingCancellationPredicate(*group); }), ErrorCodes::LOGICAL_ERROR); + }); +} +#else +TEST(BackgroundOperationCancellationDeathTest, ThrowingPredicateWithoutInstallAborts) +{ + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + EXPECT_DEATH( + { + runOnThread([](ContextPtr context) + { + auto group = ThreadGroup::createForBackgroundOperation(context, nullptr); + getThrowingCancellationPredicate(*group); + }); + }, + "No cancellation predicate installed"); +} +#endif + +TEST(BackgroundOperationCancellation, MovesListCancelAllCoversEarlierAndLaterBlockers) +{ + MovesList list; + auto before = list.getShutdownBlocker(); + EXPECT_FALSE(before.isCancelled()); + + list.cancelAll(); + + auto after = list.getShutdownBlocker(); + EXPECT_TRUE(before.isCancelled()); + EXPECT_TRUE(after.isCancelled()); +} + +} diff --git a/tests/integration/helpers/s3_mocks/broken_s3.py b/tests/integration/helpers/s3_mocks/broken_s3.py index 70428549ed44e..114113f8ddc1a 100644 --- a/tests/integration/helpers/s3_mocks/broken_s3.py +++ b/tests/integration/helpers/s3_mocks/broken_s3.py @@ -1,4 +1,5 @@ import http.server +import json import random import socket import socketserver @@ -76,6 +77,54 @@ def setup_at_object_get(self, **kwargs): def setup_at_create_multi_part_upload(self, **kwargs): self.setup_action("at_create_multi_part_upload", **kwargs) + def setup_key_rule( + self, name, prefix, target="put", contains=None, excludes=None, **kwargs + ): + """Fault the requests of kind `target` whose path starts with `prefix`, independently of + the other rules. `target` is one of: put (object and part uploads), object, part, delete, + delete_objects. `contains` and `excludes` narrow the path by a substring. `kwargs` are + those of `setup_action`: count, after, action, action_args.""" + url = ( + f"http://localhost:{self._port}/mock_settings/key_rule" + f"?name={urllib.parse.quote(name)}" + f"&prefix={urllib.parse.quote(prefix)}&target={target}" + ) + if contains is not None: + url += f"&contains={urllib.parse.quote(contains)}" + if excludes is not None: + url += f"&excludes={urllib.parse.quote(excludes)}" + for key in ("count", "after", "action"): + if kwargs.get(key) is not None: + url += f"&{key}={kwargs[key]}" + for arg in kwargs.get("action_args") or []: + url += f"&action_args={arg}" + self._apply(url) + + def remove_key_rule(self, name): + """Stops the rule from faulting; its counters stay readable until `reset`.""" + self._apply( + f"http://localhost:{self._port}/mock_settings/key_rule_remove" + f"?name={urllib.parse.quote(name)}" + ) + + def key_rule_stats(self, name): + """Returns {"seen", "hits", "max_hits_per_url", "retried_urls"}: the requests that matched + the rule, those it faulted, the largest number of faults answered to one URL, and the + number of URLs faulted at least twice (a retry shows as >= 2).""" + response = self._cluster.exec_in_container( + self._cluster.get_container_id(self._container), + [ + "curl", + "-s", + "--max-time", + "5", + f"http://localhost:{self._port}/mock_settings/key_rule_stats" + f"?name={urllib.parse.quote(name)}", + ], + nothrow=True, + ) + return json.loads(response) + def setup_fake_puts(self, part_length): self._apply( f"http://localhost:{self._port}/mock_settings/fake_puts?when_length_bigger={part_length}" @@ -263,6 +312,9 @@ def inject_error(self, request_handler): request_handler.write_error(404, data) class SlowDownAction: + def __init__(self, http_code="429"): + self.http_code = int(http_code) + def inject_error(self, request_handler): data = ( '' @@ -272,7 +324,7 @@ def inject_error(self, request_handler): "txfbd566d03042474888193-00608d7537" "" ) - request_handler.write_error(429, data) + request_handler.write_error(self.http_code, data) # make sure that Alibaba errors (QpsLimitExceeded, TotalQpsLimitExceededAction) are retriable # we patched contrib/aws to achive it: https://github.com/ClickHouse/aws-sdk-cpp/pull/22 https://github.com/ClickHouse/aws-sdk-cpp/pull/23 @@ -461,8 +513,60 @@ def has_effect(self): def inject_error(self, request_handler): self.error_handler.inject_error(request_handler) + class KeyRule: + def __init__(self, lock, prefix, target, counter, contains=None, excludes=None): + self.lock = lock + self.prefix = prefix + self.contains = contains + self.excludes = excludes + self.target = target + self.counter = counter + self.active = True + self.seen = 0 + self.hits = 0 + self.hits_per_url = dict() + + def matches(self, kind, path): + if not path.startswith(self.prefix): + return False + if self.contains is not None and self.contains not in path: + return False + if self.excludes is not None and self.excludes in path: + return False + if self.target == "put": + return kind in ("object", "part") + return kind == self.target + + def try_inject(self, request_handler, kind, url): + with self.lock: + if not self.active or not self.matches( + kind, urllib.parse.urlsplit(url).path + ): + return False + self.seen += 1 + if not self.counter.has_effect(): + return False + with self.lock: + self.hits += 1 + self.hits_per_url[url] = self.hits_per_url.get(url, 0) + 1 + request_handler.log_message("key rule %s hit %s", self.target, url) + self.counter.inject_error(request_handler) + return True + + def stats(self): + with self.lock: + return { + "seen": self.seen, + "hits": self.hits, + "max_hits_per_url": max(self.hits_per_url.values(), default=0), + "retried_urls": sum( + 1 for count in self.hits_per_url.values() if count >= 2 + ), + } + def __init__(self): self.lock = threading.Lock() + self.key_rules = dict() self.at_part_upload = None self.at_object_upload = None self.fake_put_when_length_bigger = None @@ -471,6 +575,7 @@ def __init__(self): self.slow_get = None self.fake_multipart_upload = None self.at_create_multi_part_upload = None + self.at_listing = None self.at_object_get = None def register_fake_upload(self, upload_id, key): @@ -483,8 +588,14 @@ def is_fake_upload(self, upload_id, key): return self.fake_uploads[upload_id] == key return False + def inject_by_key_rules(self, request_handler, kind, url): + with self.lock: + rules = list(self.key_rules.values()) + return any(rule.try_inject(request_handler, kind, url) for rule in rules) + def reset(self): with self.lock: + self.key_rules = dict() self.at_part_upload = None self.at_object_upload = None self.fake_put_when_length_bigger = None @@ -698,6 +809,50 @@ def _mock_settings(self): self.log_message("set at_object_get %s", _runtime.at_object_get) return self._ok() + if path[1] == "key_rule": + params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) + rule = _ServerRuntime.KeyRule( + _runtime.lock, + params["prefix"][0], + params.get("target", ["put"])[0], + _ServerRuntime.CountAfter.from_cgi_params(_runtime.lock, params), + params.get("contains", [None])[0], + params.get("excludes", [None])[0], + ) + with _runtime.lock: + _runtime.key_rules[params["name"][0]] = rule + self.log_message( + "set key_rule %s %s %s", params["name"][0], rule.target, rule.prefix + ) + return self._ok() + + if path[1] == "key_rule_remove": + params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) + with _runtime.lock: + rule = _runtime.key_rules.get(params["name"][0]) + if rule is not None: + with rule.lock: + rule.active = False + self.log_message("remove key_rule %s", params["name"][0]) + return self._ok() + + if path[1] == "key_rule_stats": + params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) + with _runtime.lock: + rule = _runtime.key_rules.get(params["name"][0]) + stats = ( + rule.stats() + if rule is not None + else {"seen": 0, "hits": 0, "max_hits_per_url": 0, "retried_urls": 0} + ) + data = json.dumps(stats) + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(bytes(data, "UTF-8")) + return + if path[1] == "reset": _runtime.reset() self.log_message("reset") @@ -747,6 +902,11 @@ def do_PUT(self): params = urllib.parse.parse_qs(parts.query, keep_blank_values=False) upload_id = params.get("uploadId", [None])[0] + if _runtime.inject_by_key_rules( + self, "object" if upload_id is None else "part", self.path + ): + return + if upload_id is not None: if _runtime.at_part_upload is not None: self.log_message( @@ -789,6 +949,11 @@ def do_PUT(self): def do_POST(self): parts = urllib.parse.urlsplit(self.path) params = urllib.parse.parse_qs(parts.query, keep_blank_values=True) + if "delete" in params and _runtime.inject_by_key_rules( + self, "delete_objects", self.path + ): + return + uploads = params.get("uploads", [None])[0] if uploads is not None: if _runtime.at_create_multi_part_upload is not None: @@ -815,6 +980,8 @@ def do_HEAD(self): self.redirect() def do_DELETE(self): + if _runtime.inject_by_key_rules(self, "delete", self.path): + return self.redirect() diff --git a/tests/integration/test_fetch_move_cancellation_s3/__init__.py b/tests/integration/test_fetch_move_cancellation_s3/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/integration/test_fetch_move_cancellation_s3/configs/mover_storage.xml b/tests/integration/test_fetch_move_cancellation_s3/configs/mover_storage.xml new file mode 100644 index 0000000000000..2f57ee2076250 --- /dev/null +++ b/tests/integration/test_fetch_move_cancellation_s3/configs/mover_storage.xml @@ -0,0 +1,42 @@ + + + + + s3 + http://resolver:8083/root/data/move_s3/ + minio + ClickHouse_Minio_P@ssw0rd + 1 + + 1000000 + + + object_storage + s3 + plain_rewritable + http://resolver:8083/root/data/move_plain/ + minio + ClickHouse_Minio_P@ssw0rd + 1 + 1000000 + + + + + + default + move_s3 + + + 0 + + + + default + move_plain + + 0 + + + + diff --git a/tests/integration/test_fetch_move_cancellation_s3/configs/receiver_storage.xml b/tests/integration/test_fetch_move_cancellation_s3/configs/receiver_storage.xml new file mode 100644 index 0000000000000..5da63a789a0fe --- /dev/null +++ b/tests/integration/test_fetch_move_cancellation_s3/configs/receiver_storage.xml @@ -0,0 +1,20 @@ + + + + + s3 + http://resolver:8083/root/data/fetch/ + minio + ClickHouse_Minio_P@ssw0rd + 1 + + 1000000 + + + + +
broken_s3
+
+
+
+
diff --git a/tests/integration/test_fetch_move_cancellation_s3/configs/source_storage.xml b/tests/integration/test_fetch_move_cancellation_s3/configs/source_storage.xml new file mode 100644 index 0000000000000..e0c7d50d6f122 --- /dev/null +++ b/tests/integration/test_fetch_move_cancellation_s3/configs/source_storage.xml @@ -0,0 +1,9 @@ + + + + +
default
+
+
+
+
diff --git a/tests/integration/test_fetch_move_cancellation_s3/test.py b/tests/integration/test_fetch_move_cancellation_s3/test.py new file mode 100644 index 0000000000000..f81c7641bd6dc --- /dev/null +++ b/tests/integration/test_fetch_move_cancellation_s3/test.py @@ -0,0 +1,601 @@ +#!/usr/bin/env python3 + +"""A replication fetch or a part move blocked in a write to its destination disk must stop on +`SYSTEM STOP FETCHES`, `SYSTEM STOP MOVES` and server shutdown. + +The destination is a plain S3 disk behind `broken_s3`: every write under its key prefix is answered with +`SlowDown` and the disk retries for far longer than any deadline here, so the operation can only end +because the stop reaches the retry loop of the S3 client. +""" + +import logging +import os +import time + +import pytest + +from helpers.cluster import ClickHouseCluster +from helpers.mock_servers import start_s3_mock + +FETCH_PREFIX = "/root/data/fetch/" +MOVE_PREFIX = "/root/data/move_s3/" +PLAIN_PREFIX = "/root/data/move_plain/" + +# The stop is noticed before the next retry, so it takes at most the longest backoff plus the +# time to unwind. The retry budget of the disks is far beyond both deadlines. +STOP_DEADLINE_SECONDS = 20 +SHUTDOWN_DEADLINE_SECONDS = 30 + +# Moves of a TTL rule start by themselves this long after the insert; the fault is armed first. +MOVE_TTL_SECONDS = 5 + +cluster = ClickHouseCluster(__file__) +source = cluster.add_instance( + "source", + main_configs=["configs/source_storage.xml"], + with_zookeeper=True, + macros={"shard": "s1", "replica": "source"}, +) +receiver = cluster.add_instance( + "receiver", + main_configs=["configs/receiver_storage.xml"], + with_minio=True, + with_zookeeper=True, + stay_alive=True, + macros={"shard": "s1", "replica": "receiver"}, +) +# Its config is installed after the mock is up: a `plain_rewritable` disk lists its bucket at startup. +mover = cluster.add_instance("mover", with_minio=True, stay_alive=True) + +CONFIG_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "configs") + + +@pytest.fixture(scope="module") +def init_broken_s3(): + try: + cluster.start() + control = start_s3_mock(cluster, "broken_s3", "8083") + mover.stop_clickhouse() + mover.copy_file_to_container( + os.path.join(CONFIG_DIR, "mover_storage.xml"), + "/etc/clickhouse-server/config.d/mover_storage.xml", + ) + mover.start_clickhouse() + yield control + finally: + cluster.shutdown() + + +@pytest.fixture(scope="function") +def broken_s3(init_broken_s3): + init_broken_s3.reset() + yield init_broken_s3 + init_broken_s3.reset() + + +def wait_until(probe, timeout, describe=None, interval=0.1, since=None): + """Polls `probe` until it returns a true value, within `timeout` wall-clock seconds from `since` + (default: now). Returns the elapsed seconds. A probe that returns true after the deadline fails + too, so a slow probe cannot stretch the bound. `describe()` is added to the error. + """ + started = time.monotonic() if since is None else since + while True: + done = probe() + elapsed = time.monotonic() - started + if elapsed > timeout or (not done and elapsed >= timeout): + detail = "" if describe is None else ": " + str(describe()) + state = "was true only after" if done else "not true within" + raise AssertionError( + f"{state} {timeout} s (elapsed {elapsed:.1f} s){detail}" + ) + if done: + return elapsed + time.sleep(min(interval, timeout - elapsed)) + + +def fault_writes(broken_s3, name, prefix, **kwargs): + """Answers every write under `prefix` with `SlowDown`.""" + broken_s3.setup_key_rule( + name, prefix, target="put", action="slow_down", action_args=[503], **kwargs + ) + + +def wait_for_failed_write_and_retry(broken_s3, name, retried_urls=1): + """The case is only meaningful if a write failed and was sent again.""" + wait_until( + lambda: broken_s3.key_rule_stats(name)["retried_urls"] >= retried_urls, + 60, + lambda: broken_s3.key_rule_stats(name), + ) + stats = broken_s3.key_rule_stats(name) + assert stats["hits"] >= 2 and stats["max_hits_per_url"] >= 2, stats + return stats + + +def log_count(node, text): + """Lines with `text` in the server log; reads the file, so it opens no query on the node.""" + return int(node.count_in_log(text)) + + +def wait_for_new_log_line(node, text, baseline): + """Waits for a `text` line beyond the `baseline` count: lines of earlier cases match too.""" + wait_until( + lambda: log_count(node, text) > baseline, + 20, + lambda: f"no new `{text}` line in the log of {node.name}", + ) + + +def count(node, query): + return int(node.query(query).strip() or 0) + + +def create_replicated_pair(table): + path = f"/clickhouse/tables/{{shard}}/{table}" + for node in (source, receiver): + node.query(f""" + CREATE TABLE {table} (p UInt8, k UInt64, s String) + ENGINE = ReplicatedMergeTree('{path}', '{{replica}}') + PARTITION BY p ORDER BY k + SETTINGS storage_policy = 'fetch_target', min_bytes_for_wide_part = 0 + """) + + +def drop_tables(node, *tables): + for table in tables: + node.query(f"SYSTEM STOP FETCHES {table}", ignore_error=True) + node.query(f"SYSTEM STOP MOVES {table}", ignore_error=True) + node.query(f"DROP TABLE IF EXISTS {table} SYNC") + + +def fetches_of(table): + return count( + receiver, + f"SELECT count() FROM system.replicated_fetches " + f"WHERE database = currentDatabase() AND table = '{table}'", + ) + + +def test_stop_fetches_cancels_fetch_blocked_in_a_write(broken_s3): + table = "fetch_stop" + create_replicated_pair(table) + try: + fault_writes(broken_s3, "fetch", FETCH_PREFIX) + source.query( + f"INSERT INTO {table} SELECT 1, number, repeat('x', 100) FROM numbers(20000)" + ) + + wait_until(lambda: fetches_of(table) == 1, 60, lambda: fetches_of(table)) + wait_for_failed_write_and_retry(broken_s3, "fetch") + assert fetches_of(table) == 1, "the fetch ended before the stop" + + cancelled = "Fetching of part was cancelled" + cancelled_before = log_count(receiver, cancelled) + started = time.monotonic() + receiver.query(f"SYSTEM STOP FETCHES {table}") + wait_until( + lambda: fetches_of(table) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("fetch"), + since=started, + ) + logging.info( + "fetch left system.replicated_fetches after %.1f s", + time.monotonic() - started, + ) + wait_for_new_log_line(receiver, cancelled, cancelled_before) + + assert count(receiver, f"SELECT count() FROM {table}") == 0 + + broken_s3.remove_key_rule("fetch") + receiver.query(f"SYSTEM START FETCHES {table}") + wait_until( + lambda: count(receiver, f"SELECT count() FROM {table}") == 20000, + 60, + lambda: receiver.query( + f"SELECT last_exception FROM system.replication_queue WHERE table = '{table}'" + ), + ) + finally: + broken_s3.reset() + drop_tables(receiver, table) + drop_tables(source, table) + + +def test_kill_query_stops_fetch_partition_blocked_in_writes(broken_s3): + """Control: a fetch run by a query is a child of the query's group and has always stopped on + `KILL QUERY`.""" + table = "fetch_partition_src" + destination = "fetch_partition_dst" + create_replicated_pair(table) + receiver.query(f""" + CREATE TABLE {destination} (p UInt8, k UInt64, s String) + ENGINE = ReplicatedMergeTree('/clickhouse/tables/{{shard}}/{destination}', '{{replica}}') + PARTITION BY p ORDER BY k + SETTINGS storage_policy = 'fetch_target', min_bytes_for_wide_part = 0 + """) + try: + source.query(f"SYSTEM STOP MERGES {table}") + receiver.query(f"SYSTEM STOP FETCHES {table}") + for offset in (0, 20000): + source.query( + f"INSERT INTO {table} SELECT 1, number + {offset}, repeat('x', 100) FROM numbers(20000)" + ) + fault_writes(broken_s3, "fetch", FETCH_PREFIX) + + query_id = "fetch_partition_to_kill" + request = receiver.get_query_request( + f"ALTER TABLE {destination} FETCH PARTITION 1 FROM '/clickhouse/tables/s1/{table}'", + query_id=query_id, + ) + wait_until( + lambda: fetches_of(destination) == 2, 60, lambda: fetches_of(destination) + ) + wait_for_failed_write_and_retry(broken_s3, "fetch", retried_urls=2) + # A fetch writes one file at a time, so two retried URLs belong to two fetches, and these + # are of two different parts. + assert ( + count( + receiver, + f"SELECT uniqExact(result_part_name) FROM system.replicated_fetches " + f"WHERE table = '{destination}'", + ) + == 2 + ) + + started = time.monotonic() + receiver.query(f"KILL QUERY WHERE query_id = '{query_id}'") + wait_until( + lambda: fetches_of(destination) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("fetch"), + since=started, + ) + logging.info("both fetches left after %.1f s", time.monotonic() - started) + _, error = request.get_answer_and_error() + assert error, "the query was expected to be cancelled" + assert ( + count( + receiver, + f"SELECT count() FROM system.detached_parts WHERE table = '{destination}'", + ) + == 0 + ) + finally: + broken_s3.reset() + drop_tables(receiver, table, destination) + drop_tables(source, table) + + +def create_tiered_table(table, policy="tiered"): + mover.query(f""" + CREATE TABLE {table} (d DateTime, k UInt64, s String) + ENGINE = MergeTree ORDER BY k + TTL d + INTERVAL {MOVE_TTL_SECONDS} SECOND TO VOLUME 'cold' + SETTINGS storage_policy = '{policy}', min_bytes_for_wide_part = 0 + """) + + +def insert_into_tiered_table(table, rows=20000): + mover.query( + f"INSERT INTO {table} SELECT now(), number, repeat('x', 100) FROM numbers({rows})" + ) + + +def moves_of(table): + return count( + mover, + f"SELECT count() FROM system.moves " + f"WHERE database = currentDatabase() AND table = '{table}'", + ) + + +def disks_of_active_parts(table): + return mover.query( + f"SELECT groupArray(disk_name) FROM system.parts " + f"WHERE database = currentDatabase() AND table = '{table}' AND active" + ).strip() + + +def drop_tiered_table(table): + drop_tables(mover, table) + + +def test_stop_moves_cancels_move_blocked_in_a_write(broken_s3): + table = "move_stop" + create_tiered_table(table) + try: + fault_writes(broken_s3, "move", MOVE_PREFIX) + insert_into_tiered_table(table) + + wait_until( + lambda: moves_of(table) == 1, 120, lambda: disks_of_active_parts(table) + ) + wait_for_failed_write_and_retry(broken_s3, "move") + assert moves_of(table) == 1, "the move ended before the stop" + + cancelled = "Cancelled moving parts" + cancelled_before = log_count(mover, cancelled) + started = time.monotonic() + mover.query(f"SYSTEM STOP MOVES {table}") + wait_until( + lambda: moves_of(table) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("move"), + since=started, + ) + logging.info("move left system.moves after %.1f s", time.monotonic() - started) + wait_for_new_log_line(mover, cancelled, cancelled_before) + + assert disks_of_active_parts(table) == "['default']" + assert count(mover, f"SELECT count() FROM {table}") == 20000 + + broken_s3.remove_key_rule("move") + mover.query(f"SYSTEM START MOVES {table}") + wait_until( + lambda: disks_of_active_parts(table) == "['move_s3']", + 120, + lambda: disks_of_active_parts(table), + ) + assert count(mover, f"SELECT count() FROM {table}") == 20000 + finally: + broken_s3.reset() + drop_tiered_table(table) + + +def test_kill_query_stops_synchronous_alter_move_blocked_in_a_write(broken_s3): + """Control: a synchronous `ALTER ... MOVE` is a child of the query's group.""" + table = "move_kill" + mover.query(f""" + CREATE TABLE {table} (k UInt64, s String) + ENGINE = MergeTree ORDER BY k + SETTINGS storage_policy = 'tiered', min_bytes_for_wide_part = 0 + """) + try: + mover.query( + f"INSERT INTO {table} SELECT number, repeat('x', 100) FROM numbers(20000)" + ) + fault_writes(broken_s3, "move", MOVE_PREFIX) + + query_id = "alter_move_to_kill" + part = mover.query( + f"SELECT name FROM system.parts WHERE database = currentDatabase() AND table = '{table}' AND active" + ).strip() + request = mover.get_query_request( + f"ALTER TABLE {table} MOVE PART '{part}' TO DISK 'move_s3'", + query_id=query_id, + ) + wait_until( + lambda: moves_of(table) == 1, 60, lambda: disks_of_active_parts(table) + ) + wait_for_failed_write_and_retry(broken_s3, "move") + + started = time.monotonic() + mover.query(f"KILL QUERY WHERE query_id = '{query_id}'") + wait_until( + lambda: moves_of(table) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("move"), + since=started, + ) + logging.info("move left system.moves after %.1f s", time.monotonic() - started) + _, error = request.get_answer_and_error() + assert error, "the query was expected to be cancelled" + assert disks_of_active_parts(table) == "['default']" + finally: + broken_s3.reset() + drop_tiered_table(table) + + +def directories_of_plain_disk(): + """The directory paths that the plain disk's metadata objects name.""" + return mover.query( + "SELECT line FROM s3('http://minio1:9001/root/data/move_plain/__meta/**', 'minio', " + "'ClickHouse_Minio_P@ssw0rd', 'LineAsString') ORDER BY line " + "SETTINGS s3_throw_on_zero_files_match = 0" + ).split() + + +def clone_directory(directories): + return [d for d in directories if d.endswith("/moving/all_1_1_0/")] + + +def test_cleanup_of_cut_clone_is_not_cut_on_plain_rewritable_disk(broken_s3): + """The clone of a cut move is removed with a directory rewrite and a delete. A failed rewrite + must be retried although the move is already cancelled, or the directory stays and the next + attempt of the move finds it.""" + table = "move_plain" + create_tiered_table(table, policy="tiered_plain") + try: + broken_s3.setup_key_rule( + "data", + PLAIN_PREFIX, + target="put", + excludes="/__meta/", + action="slow_down", + action_args=[503], + ) + insert_into_tiered_table(table) + + wait_until( + lambda: moves_of(table) == 1, 120, lambda: disks_of_active_parts(table) + ) + wait_for_failed_write_and_retry(broken_s3, "data") + assert len(clone_directory(directories_of_plain_disk())) == 1 + + # The next directory write is the cleanup's, as no other operation writes to this disk. + broken_s3.setup_key_rule( + "directory", + PLAIN_PREFIX, + target="put", + contains="/__meta/", + count=1, + action="slow_down", + action_args=[503], + ) + cancelled = "Cancelled moving parts" + cancelled_before = log_count(mover, cancelled) + started = time.monotonic() + mover.query(f"SYSTEM STOP MOVES {table}") + wait_until( + lambda: moves_of(table) == 0, + STOP_DEADLINE_SECONDS, + lambda: broken_s3.key_rule_stats("data"), + since=started, + ) + logging.info("move left system.moves after %.1f s", time.monotonic() - started) + wait_for_new_log_line(mover, cancelled, cancelled_before) + + directory_stats = broken_s3.key_rule_stats("directory") + assert ( + directory_stats["hits"] == 1 and directory_stats["seen"] >= 2 + ), directory_stats + assert clone_directory(directories_of_plain_disk()) == [] + assert disks_of_active_parts(table) == "['default']" + + broken_s3.reset() + mover.query(f"SYSTEM START MOVES {table}") + wait_until( + lambda: disks_of_active_parts(table) == "['move_plain']", + 120, + lambda: disks_of_active_parts(table), + ) + assert count(mover, f"SELECT count() FROM {table}") == 20000 + finally: + broken_s3.reset() + drop_tiered_table(table) + + +def server_is_alive(node, pid): + state = node.exec_in_container( + ["bash", "-c", f"ps -o stat= -p {pid} || true"], user="root" + ).strip() + return state != "" and not state.startswith("Z") + + +def server_pid(node): + """The PID the running server logged at its start: the server process itself. `get_process_pid` + returns the first match of `pgrep`, which can be the watchdog that supervises the server. + """ + line = node.exec_in_container( + [ + "bash", + "-c", + "grep -a 'Application: Starting ClickHouse' " + "/var/log/clickhouse-server/clickhouse-server.log | tail -n 1", + ] + ) + pid = int(line.rsplit("PID ", 1)[1].strip()) + assert server_is_alive(node, pid), line + return pid + + +def sigterm_and_expect_orderly_shutdown(node): + """One SIGTERM to the exact server PID, with no client connected: the server must exit by itself + within the deadline, through the orderly shutdown. The caller starts it again.""" + closed = "Application: Closed connections\\.$" + forced = "Will shutdown forcefully" + storages = "Shut down storages\\." + markers = (closed, forced, storages, "", "LOGICAL_ERROR") + before = {m: log_count(node, m) for m in markers} + pid = server_pid(node) + try: + # Taken before the command: the exec itself takes time that counts against the server. + signalled = time.monotonic() + # One signal: a second one would end the process without the orderly shutdown. + node.exec_in_container(["bash", "-c", f"kill -15 {pid}"], user="root") + exited_after = wait_until( + lambda: not server_is_alive(node, pid), + SHUTDOWN_DEADLINE_SECONDS, + lambda: f"{pid} still alive", + since=signalled, + ) + assert exited_after <= SHUTDOWN_DEADLINE_SECONDS, exited_after + logging.info("server exited %.1f s after SIGTERM", exited_after) + + delta = {m: log_count(node, m) - before[m] for m in markers} + assert delta == { + closed: 1, + forced: 0, + storages: 1, + "": 0, + "LOGICAL_ERROR": 0, + }, delta + finally: + if server_is_alive(node, pid): + node.exec_in_container(["bash", "-c", f"kill -9 {pid}"], user="root") + + +def test_sigterm_cancels_move_blocked_in_a_write(broken_s3): + """With no client connected, one SIGTERM ends the server although a move is retrying a write.""" + table = "move_sigterm" + create_tiered_table(table) + body_failed = False + try: + fault_writes(broken_s3, "move", MOVE_PREFIX) + insert_into_tiered_table(table) + wait_until( + lambda: moves_of(table) == 1, 120, lambda: disks_of_active_parts(table) + ) + wait_for_failed_write_and_retry(broken_s3, "move") + + sigterm_and_expect_orderly_shutdown(mover) + except BaseException: + body_failed = True + raise + finally: + broken_s3.reset() + mover.start_clickhouse() + try: + wait_until( + lambda: disks_of_active_parts(table) == "['move_s3']", + 120, + lambda: disks_of_active_parts(table), + ) + assert count(mover, f"SELECT count() FROM {table}") == 20000 + except Exception: + # A failed wait must not replace the exception of the test body. + if not body_failed: + raise + logging.exception("the restart check failed after the test body failed") + finally: + drop_tiered_table(table) + + +def test_sigterm_cancels_fetch_blocked_in_a_write(broken_s3): + """With no client connected, one SIGTERM ends the server although a fetch is retrying a write; the + fetch is a queue entry, so it completes after the restart.""" + table = "fetch_sigterm" + create_replicated_pair(table) + body_failed = False + try: + fault_writes(broken_s3, "fetch", FETCH_PREFIX) + source.query( + f"INSERT INTO {table} SELECT 1, number, repeat('x', 100) FROM numbers(20000)" + ) + wait_until(lambda: fetches_of(table) == 1, 60, lambda: fetches_of(table)) + wait_for_failed_write_and_retry(broken_s3, "fetch") + + sigterm_and_expect_orderly_shutdown(receiver) + except BaseException: + body_failed = True + raise + finally: + broken_s3.reset() + receiver.start_clickhouse() + try: + wait_until( + lambda: count(receiver, f"SELECT count() FROM {table}") == 20000, + 120, + lambda: receiver.query( + f"SELECT last_exception FROM system.replication_queue WHERE table = '{table}'" + ), + ) + except Exception: + # A failed wait must not replace the exception of the test body. + if not body_failed: + raise + logging.exception("the restart check failed after the test body failed") + finally: + drop_tables(receiver, table) + drop_tables(source, table) From f6e2ba30d89e148c02c22ab06c72923528b2221a Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sun, 29 Nov 2026 21:49:51 +0100 Subject: [PATCH 44/47] fix(cas): a stopped relink does not fall back to a byte fetch Relink preparation reports a cancellation as "relink not possible", and the fetch then started a byte fetch of the same part. Before that fallback the fetch now asks its thread group's cancellation predicate, so a stop it inherited (a killed `FETCH PARTITION`, a fetch inside a merge task) or latched ends the fetch. The stretch from the committed relink promote until the fetched part owns its directory runs under a `QueryCancellationBlocker`, as the byte fetch does after its commit. `uploadStopCheck` reads the blocker when the stop is captured, on the publisher's thread; its comment now says so. Test seams: failpoint `cas_relink_receiver_cancel_fetches_in_preparation`; `replicated_fetch_pause_after_projections` moves to the generic failpoints. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Fable 5.2 --- src/Common/FailPoint.cpp | 3 +- .../ContentAddressed/Backend/CasOwner.cpp | 3 +- .../ContentAddressed/Backend/CasOwner.h | 7 +++-- src/Disks/tests/gtest_cas_upload_guard.cpp | 10 +++---- src/Storages/MergeTree/DataPartsExchange.cpp | 29 ++++++++++++++++--- 5 files changed, 39 insertions(+), 13 deletions(-) diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index 41a57ead6e356..25b9a3f00bd53 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -45,6 +45,7 @@ static struct InitFiu REGULAR(merge_tree_sink_on_start_random_sleep) \ REGULAR(merge_tree_sequential_source_sleep_before_read) \ REGULAR(replicated_sends_sleep_before_file_send) \ + PAUSEABLE_ONCE(replicated_fetch_pause_after_projections) \ REGULAR(use_delayed_remote_source) \ ONCE(remote_query_executor_cancel_before_send) \ PAUSEABLE_ONCE(remote_query_executor_receive_packet_pause) \ @@ -407,7 +408,7 @@ static struct InitFiu REGULAR(smt_takeover_fake_hardware_error_after_set) \ REGULAR(cas_relink_receiver_force_mechanism_failure) \ PAUSEABLE_ONCE(cas_relink_receiver_pause_before_confirm) \ - PAUSEABLE_ONCE(replicated_fetch_pause_after_projections) \ + REGULAR(cas_relink_receiver_cancel_fetches_in_preparation) \ REGULAR(cas_relink_sender_omit_pool_cookie) \ REGULAR(cas_relink_receiver_drop_forced_disk) \ ONCE(cas_gc_scheduler_fail_before_heartbeat_worker_start) \ diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp index 849816887207a..161837ec81cba 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp @@ -246,7 +246,8 @@ std::function uploadStopCheck() { const auto & owner = OwnerScope::current; /// The returned callable invokes the group's predicate directly, bypassing the blocker check of - /// `throwIfQueryCanceled`, so the blocker is honoured here, when the stop is captured. + /// `throwIfQueryCanceled`, and runs on pool threads that do not see this thread's blocker. So the blocker is + /// honoured here, when the stop is captured. if (owner.owed || owner.shared || ThreadStatus::QueryCancellationBlocker::isActive()) return {}; ThreadGroupPtr thread_group = CurrentThread::getGroup(); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h index 16fffc85e59e6..3b042b958b439 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h @@ -173,8 +173,11 @@ class OwnerScope /// The check an upload of a new build runs while it sends, built on the publishing thread; the callable may run on any /// thread. Empty inside `owed` or `shared`, on a thread with no thread group, and while the calling thread holds a -/// `QueryCancellationBlocker`. Otherwise it runs the group's throwing cancellation predicate. It holds the thread -/// group, so it may outlive the scope that built it. Background owners are not part of it. +/// `QueryCancellationBlocker`. The blocker is read when the stop is captured; the callable runs on pool threads and +/// does not read it again, so a stop captured outside a blocker stays live. Otherwise it runs the group's throwing +/// cancellation predicate. It holds the thread group, so it may outlive the scope that built it, but not the +/// operation that installed the group's inherited predicates (a merge's list entry). Background owners are not part +/// of it. std::function uploadStopCheck(); /// Carries the stop check of the build being published from the publishing thread to the code that builds each diff --git a/src/Disks/tests/gtest_cas_upload_guard.cpp b/src/Disks/tests/gtest_cas_upload_guard.cpp index 9bdb8660b552c..45b59c7339d19 100644 --- a/src/Disks/tests/gtest_cas_upload_guard.cpp +++ b/src/Disks/tests/gtest_cas_upload_guard.cpp @@ -224,12 +224,12 @@ TEST(CASUploadGuard, AGroupWithATaskPredicateThrowsThroughTheGuard) onThread(true, [] { auto group = ThreadGroup::createForMergeMutate(getContext().context); - std::atomic cancelled = false; + auto cancelled = std::make_shared>(false); group->setQueryCancellationPredicates( - [&cancelled] { return cancelled.load(); }, - [&cancelled] + [cancelled] { return cancelled->load(); }, + [cancelled] { - if (cancelled.load()) + if (cancelled->load()) throw Exception(ErrorCodes::ABORTED, "Cancelled merging parts"); }); CurrentThread::attachToGroup(group); @@ -238,7 +238,7 @@ TEST(CASUploadGuard, AGroupWithATaskPredicateThrowsThroughTheGuard) auto guard = makeUploadGuard(limiter, uploadStopCheck()); EXPECT_NO_THROW(guard->throttle(32768, 0)); - cancelled = true; + *cancelled = true; EXPECT_EQ(codeOf([&] { guard->throttle(32768, 0); }), ErrorCodes::ABORTED); }); } diff --git a/src/Storages/MergeTree/DataPartsExchange.cpp b/src/Storages/MergeTree/DataPartsExchange.cpp index c056a487e53b4..a7e5bfe2a1c99 100644 --- a/src/Storages/MergeTree/DataPartsExchange.cpp +++ b/src/Storages/MergeTree/DataPartsExchange.cpp @@ -56,15 +56,18 @@ namespace DB namespace FailPoints { - /// CAS fetch-by-relink, receiver side. Both exist because the two exits they drive are properties of - /// the sender/receiver PAIR and of the interval between the receiver's publish and its confirm — and - /// neither is reachable from configuration, so an integration test cannot produce them any other way. + /// Receiver side of a relink: fails the relink mechanism before anything is staged. extern const char cas_relink_receiver_force_mechanism_failure[]; + /// Receiver side of a relink: cancels the current fetch while the relink is prepared. + extern const char cas_relink_receiver_cancel_fetches_in_preparation[]; + /// Receiver side of a relink: pauses between the publish and the confirm. extern const char cas_relink_receiver_pause_before_confirm[]; - extern const char replicated_fetch_pause_after_projections[]; /// Stands in for a sender that predates the `cas_pool_uuid` response cookie: the offer is made /// without naming the pool, and the receiver has to fall back on "the single advertised pool". extern const char cas_relink_sender_omit_pool_cookie[]; + + /// Pauses the receiver between the projections and the base part of a byte fetch. + extern const char replicated_fetch_pause_after_projections[]; } namespace MergeTreeSetting @@ -1052,6 +1055,11 @@ std::pair Fetcher::fetchSelected /// one as evidence that the brake is redundant.) auto fall_back_to_byte_fetch = [&] { + /// Relink preparation reads a stop as "relink not possible", and a stopped fetch must not go on + /// to fetch the bytes. The recursive call does not see every stop at once: an inherited one (a + /// killed `FETCH PARTITION`, a fetch inside a merge task) and a latched one whose blocker was + /// released are visible only through this predicate. + getThrowingCancellationPredicate(*thread_group)(); /// The recursive call registers its own entry in the `ReplicatedFetchList`. end_attempt(); return fetchSelectedPart( @@ -1634,6 +1642,15 @@ MergeTreeData::MutableDataPartPtr Fetcher::relinkPartToDisk( return nullptr; } + /// Test-only. Cancels the running fetches the way a server shutdown does, which sets the flag of the + /// fetch's entry but not the fetcher's blocker. + fiu_do_on(FailPoints::cas_relink_receiver_cancel_fetches_in_preparation, + { + LOG_INFO(log, "Failpoint cas_relink_receiver_cancel_fetches_in_preparation: cancelling the fetches while part {} " + "is in relink preparation", part_name); + data.getContext()->getReplicatedFetchList().cancelCurrent(); + }); + /// Test-only. Forces the "mechanism failed, the sender still has the part" exit (the ACTION of /// taxonomy rows 2 and 5) on EVERY attempt, which is precisely the shape the recursion brake has to /// bound: a persistent property of this sender/receiver pair, so the byte re-request re-offers and @@ -1785,6 +1802,9 @@ MergeTreeData::MutableDataPartPtr Fetcher::relinkPartToDisk( "committed, so the bytes must NOT be fetched; the fetch will be retried later", part_name, fetch_uri.getHost()); } + /// A stop between the commit and `is_temp` would leave a directory that no part object owns. + std::optional cancellation_blocker(std::in_place); + /// The single terminal operation is done, so the handle owes nothing; releasing it here also disarms /// the scope guard for the part-building code below. prepared.reset(); @@ -1799,6 +1819,7 @@ MergeTreeData::MutableDataPartPtr Fetcher::relinkPartToDisk( new_data_part->version->setAndStoreCreationTID(Tx::NonTransactionalTID, nullptr); new_data_part->is_temp = true; + cancellation_blocker.reset(); /// The blobs are shared in the pool; a discarded temporary relink part must NOT reclaim them (another /// replica's ref keeps them alive). Same policy a zero-copy-fetched temporary part uses. new_data_part->remove_tmp_policy = IMergeTreeDataPart::BlobsRemovalPolicyForTemporaryParts::PRESERVE_BLOBS; From 68f422e48d05c2d08bfa83dd8771a4dd6dc459f3 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sun, 29 Nov 2026 21:59:08 +0100 Subject: [PATCH 45/47] test(cas): cut the upload of a merge, a mutation, a fetch and a move `s3_fault_proxy.py` gains a mode that paces one upload body and records how it ended, a mode that holds a `GET` after its headers, and one that fails a single multipart abort. A case waits until the body of the target is in flight, issues the signal, lifts the pace and requires that the sender closed the request early with fewer bytes than `Content-Length`. A server that does not cut the upload completes the body, and the case fails. `test_cas_request_window`: - `SYSTEM STOP MERGES`, `KILL MUTATION`, `DROP TABLE`, `DETACH TABLE` and SIGTERM during the upload of a merge or a mutation; - `SYSTEM STOP FETCHES`, `SYSTEM STOP MOVES`, `DROP TABLE` and SIGTERM during the upload of a part fetched by bytes or moved from a local disk; - a multipart abort that fails once is retried; a merge stopped while a read fails reports the cancellation, not the read error; - controls with no signal, and self-tests of the proxy modes. The default set, which CI runs, has one or two variants per signal and adds about five minutes to the module. `CAS_CUT_FULL_MATRIX=1` runs all listed variants. `test_cas_replicated_relink`: a cancelled relink does not fall back to a byte fetch; the stopped-byte-fetch test compares a digest with the source. On a CAS disk a temporary fetch or move entry is not listed before its commit, so the "nothing left" checks show that no temporary part was published. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Fable 5.2 --- tests/integration/helpers/cas_paced_body.py | 147 ++ .../helpers/s3_mocks/s3_fault_proxy.py | 298 ++++- .../configs/storage_conf_other_pool.xml | 12 +- .../test_cas_replicated_relink/test.py | 169 ++- .../configs/cut_ro_disks.xml | 32 + .../configs/storage_conf_cut.xml | 158 +++ .../docker_compose_proxy.yml | 5 + .../test_cas_request_window/test.py | 1183 ++++++++++++++++- 8 files changed, 1897 insertions(+), 107 deletions(-) create mode 100644 tests/integration/helpers/cas_paced_body.py create mode 100644 tests/integration/test_cas_request_window/configs/cut_ro_disks.xml create mode 100644 tests/integration/test_cas_request_window/configs/storage_conf_cut.xml diff --git a/tests/integration/helpers/cas_paced_body.py b/tests/integration/helpers/cas_paced_body.py new file mode 100644 index 0000000000000..e1962a0be0cc7 --- /dev/null +++ b/tests/integration/helpers/cas_paced_body.py @@ -0,0 +1,147 @@ +"""Controller side of the paced-body mode of `s3_fault_proxy.py`. + +The proxy reads one selected upload body at a fixed rate and traces it (`paced_trace` in `/stats`). A request is +described by a record: `request_id`, `method`, `key`, `upload_id`, `part_number`, `content_length`, +`rate_bytes_per_s`, `received`, `outcome` (None while the body is still being read, else `complete`, `peer_eof`, +`peer_reset`, `timeout` or `proxy_error`), `t_unpaced_mono_ms`, `t_began_mono_ms` and `t_ended_mono_ms` on the proxy's +clock, and `forwarded` (True once the proxy sent the complete body on to the object store; a short body never is). + +`peer_eof` is a close by the sender, and a client-side request timeout looks the same: a caller keeps its client +timeouts far above the paced time and runs a no-signal control for every paced path. + +Cutting a paced request, the pattern of a case: `wait_body_gate`, then the signal (and the statement that sets the stop +flag returns), then `release_pace`, then `wait_cut`. The bytes the sender had already queued in the kernel arrive before +its close is seen, and at the paced rate that can take longer than the deadline; `release_pace` drains them at full +speed, so a sender that stopped ends the request short (`peer_eof`, `peer_reset`) and one that did not finishes the body +(`complete`). +""" + +import json +import time +import urllib.request + +DEFAULT_RATE_BYTES_PER_S = 256 * 1024 +CUT_OUTCOMES = ("peer_eof", "peer_reset") + + +def control_call(control_url, path, patch=None): + """A JSON `GET` (no `patch`) or `POST` to the control port of the proxy; returns the decoded reply.""" + data = None if patch is None else json.dumps(patch).encode() + request = urllib.request.Request( + control_url + path, data=data, headers={"Content-Type": "application/json"}, + method="GET" if data is None else "POST") + with urllib.request.urlopen(request, timeout=10) as response: + return json.loads(response.read().decode()) + + +def arm_paced_body(control_url, prefix, min_content_length, rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S): + """Arms the proxy to pace the first `PutObject` or `UploadPart` whose path starts with `prefix` and whose + `Content-Length` is at least `min_content_length` (above 0). The mode disarms itself when it claims a request. + Returns the request id the claimed request will carry; `wait_body_gate` waits for that one.""" + assert min_content_length > 0, "a paced body needs a size lower bound, or any small PUT would be claimed" + reply = control_call(control_url, "/config", {"paced_body": { + "prefix": prefix, "min_content_length": min_content_length, "rate_bytes_per_s": rate_bytes_per_s}}) + return reply["config"]["paced_body"]["request_id"] + + +def now_mono_ms(control_url): + """The proxy's monotonic clock, the clock of every `t_*_mono_ms` field.""" + return control_call(control_url, "/stats")["now_mono_ms"] + + +def release_pace(control_url, record): + """Makes the proxy read the rest of the claimed request at full speed.""" + control_call(control_url, "/config", {"unpace": {"request_id": record["request_id"]}}) + + +def paced_requests(control_url): + """The records of every claimed request, oldest first.""" + records = {} + for event in control_call(control_url, "/stats")["paced_trace"]: + record = records.setdefault(event["request_id"], {"received": 0, "outcome": None, "t_ended_mono_ms": None, "forwarded": False}) + if event["event"] == "began": + record.update( + request_id=event["request_id"], method=event["method"], key=event["key"], + upload_id=event["upload_id"], part_number=event["part_number"], + content_length=event["content_length"], rate_bytes_per_s=event["rate_bytes_per_s"], + t_began_mono_ms=event["t_mono_ms"]) + elif event["event"] == "forwarded": + record["forwarded"] = True + else: + record["received"] = event["bytes_read"] + if event["event"] == "unpaced": + record["t_unpaced_mono_ms"] = event["t_mono_ms"] + record["received_at_unpace"] = event["bytes_read"] + if event["event"] == "ended": + record["outcome"] = event["outcome"] + record["t_ended_mono_ms"] = event["t_mono_ms"] + return list(records.values()) + + +def _record(control_url, request_id): + return next((r for r in paced_requests(control_url) if r["request_id"] == request_id), None) + + +def record_of(control_url, record): + """The current record of the request that `record` describes. Fails when the proxy has no such record.""" + current = _record(control_url, record["request_id"]) + assert current is not None, "the proxy has no record of request {}".format(record["request_id"]) + return current + + +def wait_body_gate(control_url, request_id, min_received=256 << 10, min_left_s=5, timeout_s=60): + """Waits for the claimed request `request_id` (from `arm_paced_body`) to have received `min_received` bytes while + at least `min_left_s` seconds of body are left at its rate: the body must outlast the signal that follows. Returns + its record. Fails when the request ended or the time left is already too short.""" + end = time.monotonic() + timeout_s + last = None + while time.monotonic() < end: + last = _record(control_url, request_id) + if last is not None and "content_length" in last: + assert last["outcome"] is None, "the paced request ended before the gate: {}".format(last) + if last["received"] >= min_received: + left_s = (last["content_length"] - last["received"]) / last["rate_bytes_per_s"] + assert left_s >= min_left_s, "only {:.0f} s of body left at the gate: {}".format(left_s, last) + return last + time.sleep(0.2) + raise AssertionError("request {} did not reach {} bytes within {} s: {}".format(request_id, min_received, timeout_s, last)) + + +def _wait_ended(control_url, record, timeout_s): + end = time.monotonic() + timeout_s + current = record + while time.monotonic() < end: + current = _record(control_url, record["request_id"]) + if current is not None and current["outcome"] is not None: + return current + time.sleep(0.2) + return None + + +def wait_cut(control_url, record, deadline_s, not_before_mono_ms=None, signal_mono_ms=None): + """Asserts that the proxy saw the sender close the request early within `deadline_s` seconds from now: outcome + `peer_eof` or `peer_reset` with fewer bytes than `Content-Length`, ended at or after `not_before_mono_ms` (the + proxy's clock, read just before the signal) when given. A `timeout`, a `proxy_error` and a `complete` body fail. + With `signal_mono_ms` (the proxy's clock, read before the signal statement was issued) the end must also be within + `deadline_s` seconds of it, so a statement that itself takes long to cut cannot pass.""" + ended = _wait_ended(control_url, record, deadline_s) + assert ended is not None, "the body was not cut within {} s: {}".format( + deadline_s, _record(control_url, record["request_id"])) + assert ended["outcome"] in CUT_OUTCOMES, "the body ended as {}, not cut: {}".format(ended["outcome"], ended) + assert ended["received"] < ended["content_length"], "the cut body was complete: {}".format(ended) + assert not_before_mono_ms is None or ended["t_ended_mono_ms"] >= not_before_mono_ms, \ + "the body ended before the signal: {}".format(ended) + assert signal_mono_ms is None or ended["t_ended_mono_ms"] - signal_mono_ms <= deadline_s * 1000, \ + "the body ended {:.1f} s after the signal statement was issued, over {} s: {}".format( + (ended["t_ended_mono_ms"] - signal_mono_ms) / 1000.0, deadline_s, ended) + return ended + + +def wait_complete(control_url, record, timeout_s): + """Asserts that the whole body arrived within `timeout_s` seconds from now. Returns its final record.""" + ended = _wait_ended(control_url, record, timeout_s) + assert ended is not None, "the body did not end within {} s: {}".format( + timeout_s, _record(control_url, record["request_id"])) + assert ended["outcome"] == "complete", "the body ended as {}, not complete: {}".format(ended["outcome"], ended) + assert ended["received"] == ended["content_length"], ended + return ended diff --git a/tests/integration/helpers/s3_mocks/s3_fault_proxy.py b/tests/integration/helpers/s3_mocks/s3_fault_proxy.py index 641599683a30b..e6b4759a67cfb 100644 --- a/tests/integration/helpers/s3_mocks/s3_fault_proxy.py +++ b/tests/integration/helpers/s3_mocks/s3_fault_proxy.py @@ -27,7 +27,8 @@ (optionally scoped by `trace_path_substring`) and `/stats` returns it as `trace`, with the proxy's monotonic clock as `now_mono_ms`. A record names the fault it got; after a trickle, `outcome` is `delivered` once the last piece is flushed or `disconnected` when a write fails, and -`t_last_piece_mono_ms` is when the last piece started to be written. With `trace_bodies: true` a record +`t_last_piece_mono_ms` is when the last piece started to be written. `t_done_mono_ms` is when the +handler finished the request (response written, or a failure). With `trace_bodies: true` a record also carries the request body as Latin-1 text when it is at most `TRACE_BODY_MAX_BYTES`, else None. `rules` is an ordered script of `{method, path_substring, action, count}` with an optional @@ -39,6 +40,29 @@ parked request gets `t_release_mono_ms` when it is released. `GET /parked` lists the parked requests; `/stats` returns the rules with their remaining counts. +Three modes for the tests that cut an upload or a download (each is armed through `/config`, claims exactly one +request atomically before its body is read, and disarms itself): + +- `paced_body: {prefix, min_content_length, rate_bytes_per_s, recv_buffer_bytes, read_timeout_s}` claims the first + `PutObject` (a `PUT` with no query, no `x-amz-copy-source`) or `UploadPart` (`partNumber` and `uploadId` only) + whose path starts with `prefix` and whose `Content-Length` is at least `min_content_length` (required, above 0). + Arming answers with the `request_id` the claimed request will carry. It reads the body in small chunks on a timer + at `rate_bytes_per_s` (default 128 KiB/s) and never stops reading, so a back-pressured sender keeps sending at + that rate. A complete body is forwarded; a short one is never forwarded. `{"unpace": {"request_id"}}` makes the + claimed request read the rest at full speed and traces an `unpaced` event with the byte count at that moment. + `/stats` carries `paced_trace`: records with `event` `began` (request id, method, key, upload id, part number, + content length, receive buffer), `progress` (bytes read, about once a second), `unpaced` and `ended` (bytes read, + `outcome`). + Outcomes of `ended`: `complete`; `peer_eof` (the sender closed: FIN); `peer_reset` (connection error); `timeout` + (the proxy's own read gave up after `read_timeout_s`); `proxy_error` (any other exception). A client-side request + timeout looks like an early close (`peer_eof`), so a caller keeps its client timeouts far above the paced time and + runs a no-signal control for each paced path. When the server closes an upload, the bytes already queued in its + kernel send buffer are delivered before the close is seen; `unpace` drains them quickly. +- `hold_get: {prefix}` forwards the response headers of the first object `GET` under `prefix`, waits until + `POST /release_get {id}`, then sends half of the body and closes. `/stats` carries `held_gets`. +- `fail_abort: {key, upload_id, remaining}` answers `remaining` (default 1) `DELETE`s of that key with that + `uploadId` with 503. `/stats` carries `abort_trace` with every such `DELETE` and the status it got. + Control plane (separate port): POST /config {json}, GET /stats, GET /healthz. Deterministic: fault decisions are driven by a seeded PRNG keyed per-request-index, so a given (seed, rate) is reproducible. """ @@ -55,6 +79,7 @@ import sys import threading import time +import urllib.parse UPSTREAM = os.environ.get("RUSTFS_UPSTREAM", "rustfs1:11121") # host:port of the real store S3_PORT = int(os.environ.get("S3_PROXY_PORT", "11121")) @@ -82,6 +107,9 @@ "list_anomaly": None, # None | "duplicate" | "drop_token" "list_prefix": "roots/", # only LIST calls whose prefix contains this are perturbed "rules": [], # ordered script; see the module docstring + "paced_body": None, # see the module docstring + "hold_get": None, + "fail_abort": None, } _DEFAULT_STATS = { "forwarded": 0, @@ -90,17 +118,41 @@ "by_mode": {}, "drop_after_forward": [], "trace": [], + "paced_trace": [], + "abort_trace": [], } _cfg = dict(_DEFAULT_CFG) _stats = dict(_DEFAULT_STATS) _stats["by_mode"] = {} _stats["drop_after_forward"] = [] _stats["trace"] = [] +_stats["paced_trace"] = [] +_stats["abort_trace"] = [] _req_index = [0] _idx_lock = threading.Lock() # id -> {"id", "method", "path", "t_mono_ms", "event", "respond", "trace"}; guarded by _cfg_lock. _parked = {} _parked_ids = [0] +# id -> {"id", "key", "t_headers_mono_ms", "t_release_mono_ms", "state", "event"}; guarded by _cfg_lock. +_held_gets = {} +_held_get_ids = [0] +_paced_ids = [0] +# Bumped by `_reset`: a claimed paced request of an earlier generation drops its connection and records nothing. +_generation = [0] +# Ids of claimed paced requests whose pacing was released by `unpace`; guarded by `_cfg_lock`. +_unpaced_ids = set() +PACED_DEFAULT_RATE = 128 * 1024 +PACED_TICK_S = 0.1 +PACED_UNPACED_CHUNK = 1 << 20 +PACED_UNPACED_RECV_BUFFER = 4 << 20 +PACED_PROGRESS_S = 1.0 +PACED_DEFAULT_RECV_BUFFER = 4096 +PACED_DEFAULT_READ_TIMEOUT_S = 30 +HELD_GET_MAX_WAIT_S = 600 +# Hop-by-hop headers and `Expect`: the proxy sends the buffered body at once, so a relayed `Expect: 100-continue` +# would make the upstream reply with an interim 100 that `getresponse` would misread. +_HOP_HEADERS = {"transfer-encoding", "expect", "connection", "keep-alive", "proxy-connection", + "te", "trailer", "upgrade"} def _get_cfg(): @@ -149,6 +201,11 @@ def _reset(): for record in _parked.values(): _release(record, "503") _parked.clear() + for held in _held_gets.values(): + held["event"].set() + _held_gets.clear() + _generation[0] += 1 + _unpaced_ids.clear() _cfg.clear() _cfg.update(_DEFAULT_CFG) _stats.clear() @@ -156,6 +213,8 @@ def _reset(): _stats["by_mode"] = {} _stats["drop_after_forward"] = [] _stats["trace"] = [] + _stats["paced_trace"] = [] + _stats["abort_trace"] = [] with _idx_lock: _req_index[0] = 0 @@ -205,7 +264,8 @@ def _admit(self, ingress_mono_ms): # Every key exists before the record is published; later fields start as None. self._trace_record = {"t_mono_ms": ingress_mono_ms, "method": self.command, "path": self.path, "fault": None, "rule": action, "status": None, "outcome": None, - "t_last_piece_mono_ms": None, "t_release_mono_ms": None, "body": body} + "t_last_piece_mono_ms": None, "t_release_mono_ms": None, "t_done_mono_ms": None, + "body": body} _stats["trace"].append(self._trace_record) parked = None if action == "hold": @@ -299,6 +359,181 @@ def _emit_fault(self, mode): elif mode == "trickle": self._forward(trickle=True) + # --- paced body, held GET, failed abort --------------------------------- + def _claim_paced(self): + """Atomically disarms `paced_body` and returns its config when this request is the one to pace: a + `PutObject` or an `UploadPart` with the armed prefix and size. Tagging, ACL and copy requests never match.""" + if self.command != "PUT" or self.headers.get("x-amz-copy-source") is not None: + return None + length = self.headers.get("Content-Length") + if length is None: + return None + parsed = urllib.parse.urlparse(self.path) + query = set(urllib.parse.parse_qs(parsed.query, keep_blank_values=True)) + if query not in (set(), {"partNumber", "uploadId"}): + return None + with _cfg_lock: + armed = _cfg.get("paced_body") + if (armed is None or not parsed.path.startswith(armed["prefix"]) + or int(length) < armed["min_content_length"]): + return None + _cfg["paced_body"] = None + return dict(armed, generation=_generation[0]) + + def _paced_event(self, claim, **fields): + """Appends a record unless a reset happened since the claim.""" + with _cfg_lock: + if claim["generation"] != _generation[0]: + return False + _stats["paced_trace"].append(dict(fields, request_id=claim["request_id"], t_mono_ms=time.monotonic() * 1000.0)) + return True + + def _paced_body(self, claim): + """Reads the claimed body at the configured rate. A complete body goes upstream; any other end closes the + connection and forwards nothing.""" + length = int(self.headers["Content-Length"]) + rate = int(claim.get("rate_bytes_per_s", PACED_DEFAULT_RATE)) + query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query) + sock = self.connection + sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, int(claim.get("recv_buffer_bytes", PACED_DEFAULT_RECV_BUFFER))) + sock.settimeout(claim.get("read_timeout_s", PACED_DEFAULT_READ_TIMEOUT_S)) + self._paced_event( + claim, event="began", method=self.command, key=urllib.parse.unquote(urllib.parse.urlparse(self.path).path), + upload_id=(query.get("uploadId") or [None])[0], part_number=(query.get("partNumber") or [None])[0], + content_length=length, rate_bytes_per_s=rate, rcvbuf=sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)) + body = bytearray() + start = next_progress = time.monotonic() + outcome = None + error = None + unpaced = False + try: + while len(body) < length: + if not unpaced: + with _cfg_lock: + unpaced = claim["request_id"] in _unpaced_ids + if unpaced: + self._paced_event(claim, event="unpaced", bytes_read=len(body)) + # The small receive buffer of the paced read caps the transfer by itself (measured: tens of + # KiB/s); raising it alone does not help, the window clamp has to be raised as well. + sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, PACED_UNPACED_RECV_BUFFER) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_WINDOW_CLAMP, PACED_UNPACED_RECV_BUFFER) + chunk = PACED_UNPACED_CHUNK if unpaced else max(1, int(rate * PACED_TICK_S)) + data = self.rfile.read1(min(chunk, length - len(body))) + if not data: + outcome = "peer_eof" + break + body += data + now = time.monotonic() + if now >= next_progress: + next_progress = now + PACED_PROGRESS_S + if not self._paced_event(claim, event="progress", bytes_read=len(body)): + self._abandon() + return + pause = start + len(body) / rate - now + if pause > 0 and not unpaced: + time.sleep(pause) + else: + outcome = "complete" + except TimeoutError: + outcome = "timeout" + except ConnectionError as e: + outcome = "peer_reset" + error = repr(e) + except Exception as e: + outcome = "proxy_error" + error = repr(e) + if not self._paced_event(claim, event="ended", bytes_read=len(body), outcome=outcome, error=error): + self._abandon() + return + if outcome != "complete": + self._abandon() + return + sock.settimeout(None) + self._cached_body = bytes(body) + self._paced_event(claim, event="forwarded") + self._forward() + + def _abandon(self): + self.close_connection = True + try: + self.connection.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + def _claim_held_get(self): + if self.command != "GET": + return None + parsed = urllib.parse.urlparse(self.path) + if "list-type" in parsed.query or "uploads" in parsed.query: + return None + with _cfg_lock: + armed = _cfg.get("hold_get") + if armed is None or not parsed.path.startswith(armed["prefix"]): + return None + _cfg["hold_get"] = None + _held_get_ids[0] += 1 + held = {"id": _held_get_ids[0], "key": urllib.parse.unquote(parsed.path), "t_headers_mono_ms": None, + "t_release_mono_ms": None, "state": "claimed", "content_length": None, "event": threading.Event()} + _held_gets[held["id"]] = held + return held + + def _hold_get(self, held): + """Sends the real response headers, waits for `/release_get`, then sends half of the body and closes.""" + conn = http.client.HTTPConnection(UPSTREAM, timeout=60) + try: + conn.request("GET", self.path, headers=self._upstream_headers(0)) + resp = conn.getresponse() + data = resp.read() + finally: + conn.close() + self.send_response(resp.status) + for k, v in resp.getheaders(): + if k.lower() not in ("transfer-encoding", "connection", "content-length"): + self.send_header(k, v) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.flush() + with _cfg_lock: + held["t_headers_mono_ms"] = time.monotonic() * 1000.0 + held["content_length"] = len(data) + held["state"] = "waiting" + held["event"].wait(HELD_GET_MAX_WAIT_S) + try: + self.wfile.write(data[:len(data) // 2]) + self.wfile.flush() + except OSError: + pass + with _cfg_lock: + held["state"] = "truncated" + self._abandon() + + def _match_abort(self): + """The key and upload id of a `DELETE` that `fail_abort` is about, else None.""" + if self.command != "DELETE": + return None + parsed = urllib.parse.urlparse(self.path) + upload_id = (urllib.parse.parse_qs(parsed.query).get("uploadId") or [None])[0] + with _cfg_lock: + armed = _cfg.get("fail_abort") + if armed is None or upload_id != armed["upload_id"] or urllib.parse.unquote(parsed.path) != armed["key"]: + return None + return armed["key"], upload_id + + def _fail_abort(self, key, upload_id): + """Records the `DELETE`, answers it 503 while the budget lasts and forwards it afterwards.""" + with _cfg_lock: + armed = _cfg["fail_abort"] + inject = armed.get("remaining", 1) > 0 + if inject: + armed["remaining"] = armed.get("remaining", 1) - 1 + self._abort_record = {"t_mono_ms": time.monotonic() * 1000.0, "key": key, "upload_id": upload_id, + "injected": inject, "status": None} + _stats["abort_trace"].append(self._abort_record) + if inject: + self._send_error(503, _SLOWDOWN_BODY) + else: + self._forward() + # --- request body ------------------------------------------------------- def _read_body(self): length = self.headers.get("Content-Length") @@ -321,6 +556,12 @@ def _read_body(self): return b"" # --- forward to upstream ------------------------------------------------ + def _upstream_headers(self, body_length): + """The client's headers verbatim, including `Host` so that SigV4 stays valid, minus the hop-by-hop ones.""" + headers = {k: v for k, v in self.headers.items() if k.lower() not in _HOP_HEADERS} + headers["Content-Length"] = str(body_length) + return headers + def _forward(self, drop_after_forward=False, trickle=False): body = getattr(self, "_cached_body", None) if body is None: @@ -332,14 +573,7 @@ def _forward(self, drop_after_forward=False, trickle=False): # so relaying Expect makes the upstream reply with an interim 100 that getresponse() would # misread — corrupting the upload (observed: size-0 blobs on >=64 KiB PUTs). We already # buffered the full body and send it directly, so no 100-continue negotiation is needed. - _HOP = {"transfer-encoding", "expect", "connection", "keep-alive", "proxy-connection", - "te", "trailer", "upgrade"} - fwd_headers = {} - for k, v in self.headers.items(): - if k.lower() in _HOP: - continue - fwd_headers[k] = v - fwd_headers["Content-Length"] = str(len(body)) + fwd_headers = self._upstream_headers(len(body)) try: conn.request(self.command, self.path, body=body, headers=fwd_headers) resp = conn.getresponse() @@ -422,11 +656,28 @@ def _forward(self, drop_after_forward=False, trickle=False): def _trace_status(self, status): if self._trace_record is not None: self._trace_record["status"] = status + if self._abort_record is not None: + self._abort_record["status"] = status def _handle(self): - cfg = _get_cfg() self._trace_record = None + try: + self._dispatch() + finally: + if self._trace_record is not None: + self._trace_record["t_done_mono_ms"] = time.monotonic() * 1000.0 + + def _dispatch(self): + cfg = _get_cfg() + self._abort_record = None ingress_mono_ms = time.monotonic() * 1000.0 + # Claimed before the body is read: a paced body must never be buffered at full speed first. + claim = self._claim_paced() + if claim is not None: + return self._paced_body(claim) + held = self._claim_held_get() + if held is not None: + return self._hold_get(held) # Cache body once (fault paths + forward both may need it). try: self._cached_body = self._read_body() @@ -436,6 +687,9 @@ def _handle(self): print(f"[dbg] {self.command} {self.path[:60]} CL={self.headers.get('Content-Length')} " f"TE={self.headers.get('Transfer-Encoding')} CE={self.headers.get('Content-Encoding')} " f"Expect={self.headers.get('Expect')} read={len(self._cached_body)}", flush=True) + abort = self._match_abort() + if abort is not None: + return self._fail_abort(*abort) action, parked = self._admit(ingress_mono_ms) mode = self._should_fault(cfg) if action is None else None if self._trace_record is not None: @@ -513,6 +767,9 @@ def do_GET(self): snapshot["by_mode"] = dict(_stats["by_mode"]) snapshot["drop_after_forward"] = list(_stats["drop_after_forward"]) snapshot["trace"] = [dict(r) for r in _stats["trace"]] + snapshot["paced_trace"] = [dict(r) for r in _stats["paced_trace"]] + snapshot["abort_trace"] = [dict(r) for r in _stats["abort_trace"]] + snapshot["held_gets"] = [{k: v for k, v in r.items() if k != "event"} for r in _held_gets.values()] snapshot["rules"] = [dict(r) for r in _cfg["rules"]] snapshot["now_mono_ms"] = time.monotonic() * 1000.0 return self._json(200, snapshot) @@ -529,6 +786,14 @@ def do_POST(self): patch = json.loads(self.rfile.read(length) or b"{}") except Exception as e: return self._json(400, {"error": f"bad json: {e}"}) + if self.path.startswith("/release_get"): + with _cfg_lock: + held = _held_gets.get(patch.get("id")) + if held is None or held["state"] != "waiting" or held["event"].is_set(): + return self._json(404, {"error": "no waiting held GET"}) + held["t_release_mono_ms"] = time.monotonic() * 1000.0 + held["event"].set() + return self._json(200, {"ok": True}) if self.path.startswith("/release"): respond = patch.get("respond", "forward") if respond not in ("forward", "503"): @@ -544,6 +809,17 @@ def do_POST(self): reset = bool(patch.pop("reset", False)) if reset: _reset() + unpace = patch.pop("unpace", None) + if unpace is not None: + with _cfg_lock: + _unpaced_ids.add(unpace["request_id"]) + paced = patch.get("paced_body") + if paced is not None: + if int(paced.get("min_content_length") or 0) <= 0: + return self._json(400, {"error": "paced_body needs min_content_length above 0"}) + with _cfg_lock: + _paced_ids[0] += 1 + patch["paced_body"] = dict(paced, request_id=_paced_ids[0]) with _cfg_lock: if "rules" in patch: patch["rules"] = [dict(r) for r in patch["rules"]] diff --git a/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml b/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml index 0f644f2974b64..8f65c8fadadb3 100644 --- a/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml +++ b/tests/integration/test_cas_replicated_relink/configs/storage_conf_other_pool.xml @@ -1,7 +1,7 @@ - @@ -33,8 +33,8 @@ s3 0 - + object_storage s3 @@ -46,8 +46,6 @@ true 0 - object_storage s3 diff --git a/tests/integration/test_cas_replicated_relink/test.py b/tests/integration/test_cas_replicated_relink/test.py index f9e8ba2a10e19..9f31a7ae4c191 100644 --- a/tests/integration/test_cas_replicated_relink/test.py +++ b/tests/integration/test_cas_replicated_relink/test.py @@ -758,6 +758,105 @@ def test_recursion_brake_bounds_relink_to_one_attempt(): drop_everywhere(table) +def test_cancelled_fetch_does_not_fall_back_to_a_byte_fetch(): + """A fetch cancelled while relink is in progress ends with `ABORTED` and asks the sender nothing more. + + Relink preparation reads a stop as "relink not possible", and the fallback then fetched the bytes. + A stop that the byte fetch sees on entry (`SYSTEM STOP FETCHES`) would end the fallback anyway. The veto + matters for a stop it does not see: an inherited one (a killed `FETCH PARTITION`, a merge task's fetch) + or a latched per-attempt one. The first failpoint injects that kind of stop by cancelling the fetch's own + entry, not the fetcher's blocker. The second failpoint lands in the mechanism-failure branch, the one that + falls back. The sender must see relink offers only and no byte request; the part arrives by relink once + the failpoints are off. + """ + node1 = cluster.instances["node1"] + node2 = cluster.instances["node2"] + table = "veto" + drop_everywhere(table) + + create_replicated(node1, table) + create_replicated(node2, table) + + node2.query("SYSTEM STOP FETCHES {}".format(table)) + insert_rows(node1, table, 2_000_000) + part = active_part_names(node1, table)[0] + # Every pattern names the table and the part, and counts start from a baseline: a part name repeats across + # tables and a rerun of the test leaves lines of the same table in the log. + sender_requests = r"default\.{} .*Sending part {}$".format(table, re.escape(part)) + sender_offers = relink_offer_pattern(table, part) + aborted = r"default\.{} .*Fetching of part was cancelled".format(table) + forced_failure = r"default\.{} .*Failpoint cas_relink_receiver_force_mechanism_failure: abandoning the relink of part {}".format( + table, re.escape(part) + ) + not_possible = r"default\.{} .*Relink of part {} is not possible on this pair".format(table, re.escape(part)) + byte_download = download_finished_pattern(table, part) + + def new_lines(node, pattern): + return log_lines(node, pattern)[baseline[(node.name, pattern)]:] + + baseline = { + (node.name, pattern): len(log_lines(node, pattern)) + for node, patterns in ((node1, (sender_requests, sender_offers)), (node2, (aborted, forced_failure, not_possible, byte_download))) + for pattern in patterns + } + + node2.query("SYSTEM ENABLE FAILPOINT cas_relink_receiver_cancel_fetches_in_preparation") + node2.query("SYSTEM ENABLE FAILPOINT cas_relink_receiver_force_mechanism_failure") + try: + node2.query("SYSTEM START FETCHES {}".format(table)) + + wait_until( + lambda: new_lines(node2, aborted) or new_lines(node2, byte_download), + timeout=60, + what="the fetch of {} to end".format(part), + ) + assert not new_lines(node2, byte_download), "the cancelled fetch fetched the bytes" + assert new_lines(node2, aborted), "the fetch did not end with ABORTED" + assert new_lines(node2, forced_failure), "the mechanism-failure branch was not reached" + assert new_lines(node2, not_possible) + # The receiver logs the abort before the queue entry publishes `last_exception`, so the entry is awaited. + wait_until( + lambda: "ABORTED" + in node2.query( + "SELECT last_exception FROM system.replication_queue WHERE database = 'default' AND table = '{}'".format(table) + ), + timeout=30, + what="the queue entry of {} to publish the abort".format(part), + ) + + def sender_counts(): + """New request lines and new offer lines, counted in one read of the sender's log.""" + lines = log_lines(node1, "({})|({})".format(sender_requests, sender_offers)) + requests = [line for line in lines if re.search(sender_requests, line)] + offers = [line for line in lines if re.search(sender_offers, line)] + return ( + len(requests) - baseline[(node1.name, sender_requests)], + len(offers) - baseline[(node1.name, sender_offers)], + ) + + # Every request the sender logs must be a relink offer: an offer logs both lines, a byte request only the + # first. The second line follows the first, so the counts are awaited; a byte request never evens them. + def only_offers(): + requests, offers = sender_counts() + return offers > 0 and requests == offers + + wait_until( + only_offers, + timeout=10, + what="every request of the sender for {} to be a relink offer".format(part), + ) + assert active_part_names(node2, table) == [] + finally: + node2.query("SYSTEM DISABLE FAILPOINT cas_relink_receiver_force_mechanism_failure") + node2.query("SYSTEM DISABLE FAILPOINT cas_relink_receiver_cancel_fetches_in_preparation") + + node2.query("SYSTEM SYNC REPLICA {}".format(table), timeout=90) + assert_relinked(node2, table, part) + assert int(node2.query("SELECT count() FROM {}".format(table))) == NUM_ROWS + + drop_everywhere(table) + + # Settings that make node1 drop an outdated part — and with it the CA ref the confirm asks about — # within a few seconds instead of the default eight minutes. FAST_OLD_PART_REMOVAL = ( @@ -1271,41 +1370,43 @@ def test_stopped_byte_fetch_leaves_no_tmp_fetch_ref(policy, disk): "SETTINGS storage_policy = '{policy}'" ) drop_everywhere(table) - zk = "/clickhouse/tables/" + table - node1.query(create_sql.format(policy=STORAGE_POLICY, zk=zk)) - node2.query(create_sql.format(policy=policy, zk=zk)) - node2.query("SYSTEM STOP FETCHES {}".format(table)) - insert_rows(node1, table, 0) - part = active_part_names(node1, table)[0] - expected_sum = int(node1.query("SELECT sum(v) FROM {}".format(table))) - data_path = node2.query( - "SELECT arrayJoin(data_paths) FROM system.tables WHERE database = 'default' AND name = '{}'".format(table) - ).strip() - table_path = data_path[data_path.index("store/"):] - - node2.query("SYSTEM ENABLE FAILPOINT " + failpoint) try: - node2.query("SYSTEM START FETCHES {}".format(table)) - node2.query("SYSTEM WAIT FAILPOINT {} PAUSE".format(failpoint), timeout=120) - assert int(node2.query("SELECT count() FROM system.replicated_fetches WHERE table = '{}'".format(table))) == 1 + zk = "/clickhouse/tables/" + table + node1.query(create_sql.format(policy=STORAGE_POLICY, zk=zk)) + node2.query(create_sql.format(policy=policy, zk=zk)) node2.query("SYSTEM STOP FETCHES {}".format(table)) - finally: - node2.query("SYSTEM DISABLE FAILPOINT " + failpoint) + insert_rows(node1, table, 0) + part = active_part_names(node1, table)[0] + expected_digest = node1.query("SELECT count(), sum(cityHash64(id, v, s)) FROM {}".format(table)) + data_path = node2.query( + "SELECT arrayJoin(data_paths) FROM system.tables WHERE database = 'default' AND name = '{}'".format(table) + ).strip() + table_path = data_path[data_path.index("store/"):] + + node2.query("SYSTEM ENABLE FAILPOINT " + failpoint) + try: + node2.query("SYSTEM START FETCHES {}".format(table)) + node2.query("SYSTEM WAIT FAILPOINT {} PAUSE".format(failpoint), timeout=120) + assert int(node2.query("SELECT count() FROM system.replicated_fetches WHERE table = '{}'".format(table))) == 1 + node2.query("SYSTEM STOP FETCHES {}".format(table)) + finally: + node2.query("SYSTEM DISABLE FAILPOINT " + failpoint) - wait_until( - lambda: int(node2.query("SELECT count() FROM system.replicated_fetches WHERE table = '{}'".format(table))) == 0, - 60, - "the stopped fetch to leave system.replicated_fetches", - ) - entries = list_disk_dir(node2, disk, table_path) + list_disk_dir(node2, disk, table_path + "detached") - assert not [e for e in entries if e.startswith("tmp-fetch_")], entries - assert fsck(node2, disk)["dangling"] == "0" - assert any_state_part_count(node2, table, part) == 0 + wait_until( + lambda: int(node2.query("SELECT count() FROM system.replicated_fetches WHERE table = '{}'".format(table))) == 0, + 60, + "the stopped fetch to leave system.replicated_fetches", + ) + entries = list_disk_dir(node2, disk, table_path) + list_disk_dir(node2, disk, table_path + "detached") + assert not [e for e in entries if e.startswith("tmp-fetch_")], entries + assert fsck(node2, disk)["dangling"] == "0" + assert any_state_part_count(node2, table, part) == 0 - node2.query("SYSTEM START FETCHES {}".format(table)) - node2.query("SYSTEM SYNC REPLICA {}".format(table), timeout=90) - assert int(node2.query("SELECT count() FROM {}".format(table))) == NUM_ROWS - assert int(node2.query("SELECT sum(v) FROM {}".format(table))) == expected_sum - # Control for the listing helper: it must see the part that arrived. - assert part in list_disk_dir(node2, disk, table_path) - drop_everywhere(table) + node2.query("SYSTEM START FETCHES {}".format(table)) + node2.query("SYSTEM SYNC REPLICA {}".format(table), timeout=90) + assert node2.query("SELECT count(), sum(cityHash64(id, v, s)) FROM {}".format(table)) == expected_digest + assert int(node2.query("SELECT count() FROM {}".format(table))) == NUM_ROWS + # Control for the listing helper: it must see the part that arrived. + assert part in list_disk_dir(node2, disk, table_path) + finally: + drop_everywhere(table) diff --git a/tests/integration/test_cas_request_window/configs/cut_ro_disks.xml b/tests/integration/test_cas_request_window/configs/cut_ro_disks.xml new file mode 100644 index 0000000000000..f8c1473a7f58d --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/cut_ro_disks.xml @@ -0,0 +1,32 @@ + + + + + + object_storage + s3 + cas + http://rustfs1:11121/test/cas_request_cut/ + clickhouse + clickhouse + itest-cas-cut + true + false + + + object_storage + s3 + cas + http://rustfs1:11121/test/cas_request_cut_s3/ + clickhouse + clickhouse + itest-cas-cut-s3 + s3 + true + false + + + + diff --git a/tests/integration/test_cas_request_window/configs/storage_conf_cut.xml b/tests/integration/test_cas_request_window/configs/storage_conf_cut.xml new file mode 100644 index 0000000000000..67bbcac74a15e --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/storage_conf_cut.xml @@ -0,0 +1,158 @@ + + + 01 + node_cut + + + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-cut + http://s3proxy:11121/test/cas_request_cut/ + clickhouse + clickhouse + false + + 300000 + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-cut-s3 + http://s3proxy:11121/test/cas_request_cut_s3/ + clickhouse + clickhouse + s3 + false + 300000 + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-cut-mp + http://s3proxy:11121/test/cas_request_cut_mp/ + clickhouse + clickhouse + false + 300000 + 5242880 + 5242880 + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-cut-s3-mp + http://s3proxy:11121/test/cas_request_cut_s3_mp/ + clickhouse + clickhouse + s3 + false + 300000 + 5242880 + 5242880 + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + + +
+ disk_cas_cut +
+
+
+ + +
+ disk_cas_cut_s3 +
+
+
+ + +
+ disk_cas_cut_mp +
+
+
+ + +
+ disk_cas_cut_s3_mp +
+
+
+ + + + + default + + + disk_cas_cut + 0 + + + 0 + + + + + default + + + disk_cas_cut_s3 + 0 + + + 0 + +
+
+
diff --git a/tests/integration/test_cas_request_window/docker_compose_proxy.yml b/tests/integration/test_cas_request_window/docker_compose_proxy.yml index 210d732547b7c..73118f2b628f0 100644 --- a/tests/integration/test_cas_request_window/docker_compose_proxy.yml +++ b/tests/integration/test_cas_request_window/docker_compose_proxy.yml @@ -38,3 +38,8 @@ services: depends_on: s3proxy: condition: service_healthy + + node_cut: + depends_on: + s3proxy: + condition: service_healthy diff --git a/tests/integration/test_cas_request_window/test.py b/tests/integration/test_cas_request_window/test.py index 902f8984e9689..ca25d9d2ffd6f 100644 --- a/tests/integration/test_cas_request_window/test.py +++ b/tests/integration/test_cas_request_window/test.py @@ -22,19 +22,32 @@ Each test drops the tables it leaves and scopes its fault rules and trace to its own pool, so the module passes in any order and when repeated. + +The cut-upload tests (from `CUT_PREFIX` on) run a reduced parameter set by default; `CAS_CUT_FULL_MATRIX=1` selects +all listed variants (`matrix`). Both sets were run locally. """ +import datetime +import hashlib +import hmac import json import logging import os import re +import shlex import subprocess import threading import time +import urllib.error +import urllib.parse import urllib.request +from xml.etree import ElementTree import pytest +from helpers.cas_paced_body import ( + DEFAULT_RATE_BYTES_PER_S, arm_paced_body, control_call, now_mono_ms, paced_requests, record_of, release_pace, wait_body_gate, + wait_complete, wait_cut) from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) @@ -56,15 +69,6 @@ GC_POOL = "cas_request_gc" -def _control(url, path, patch=None): - data = None if patch is None else json.dumps(patch).encode() - request = urllib.request.Request( - url + path, data=data, headers={"Content-Type": "application/json"}, method="GET" if data is None else "POST" - ) - with urllib.request.urlopen(request, timeout=10) as response: - return json.loads(response.read().decode()) - - def _wait_until(probe, timeout, describe=None): """Polls `probe` until it returns a true value. On a timeout the error carries `describe()`, when given.""" end = time.monotonic() + timeout @@ -90,12 +94,16 @@ def node(): with_rustfs=True, with_zookeeper=True, stay_alive=True) cluster.add_instance("node_gc", main_configs=["configs/storage_conf_gc.xml"], with_rustfs=True) cluster.add_instance("node_guard", main_configs=["configs/guard.xml"], with_rustfs=True, stay_alive=True) + # The source of the fetches into `node_cut`: its tables are on the local disk, so a part is sent as bytes. + cluster.add_instance("node_src", macros={"shard": "01", "replica": "node_src"}, with_zookeeper=True) + cluster.add_instance("node_cut", main_configs=["configs/storage_conf_cut.xml", "configs/drop_delay.xml"], + with_rustfs=True, with_zookeeper=True, stay_alive=True) cluster.base_cmd.extend(["--file", os.path.join(os.path.dirname(__file__), "docker_compose_proxy.yml")]) try: cluster.start() binding = subprocess.check_output(cluster.base_cmd + ["port", "s3proxy", "8474"], text=True).strip() cluster.proxy_url = "http://{}".format(binding) - _wait_until(lambda: _control(cluster.proxy_url, "/healthz"), timeout=30) + _wait_until(lambda: control_call(cluster.proxy_url, "/healthz"), timeout=30) yield cluster.instances["node"] finally: cluster.shutdown() @@ -116,6 +124,18 @@ def node_guard(node): return cluster.instances["node_guard"] +@pytest.fixture(scope="module") +def node_src(node): + return cluster.instances["node_src"] + + +@pytest.fixture(scope="module") +def node_cut(node): + """Keeper, a local-staging and an S3-staging CAS policy on pools of their own behind the proxy, and no other + writer to those pools. Body requests may last 300 s, longer than the paced duration of the largest body.""" + return cluster.instances["node_cut"] + + def _drop_all_tables(instance): for name in instance.query("SELECT table FROM system.detached_tables WHERE database = 'default'").split(): instance.query("ATTACH TABLE default.`{}`".format(name)) @@ -124,20 +144,26 @@ def _drop_all_tables(instance): @pytest.fixture(autouse=True) -def clean_state(node, node_stop, node_gc, node_guard): - _control(cluster.proxy_url, "/config", {"reset": True}) +def clean_state(request, node, node_stop, node_gc, node_guard, node_cut, node_src): + control_call(cluster.proxy_url, "/config", {"reset": True}) + first_line = node_cut.count_log_lines() + 1 yield - _control(cluster.proxy_url, "/config", {"reset": True}) - for instance in (node, node_stop, node_gc, node_guard): + control_call(cluster.proxy_url, "/config", {"reset": True}) + # A statement of `in_thread` that a failed case left running ends once the proxy is reset; the drop must not race it. + for thread in RUNNING_STATEMENTS: + thread.join(120) + RUNNING_STATEMENTS.clear() + for instance in (node, node_stop, node_gc, node_guard, node_cut, node_src): _drop_all_tables(instance) + record_log_anomalies(node_cut, request.node.name, first_line) def _arm(**config): - _control(cluster.proxy_url, "/config", dict(rate=1.0, trace=True, **config)) + control_call(cluster.proxy_url, "/config", dict(rate=1.0, trace=True, **config)) def _stats(): - return _control(cluster.proxy_url, "/stats") + return control_call(cluster.proxy_url, "/stats") def _create(node, name): @@ -239,7 +265,7 @@ def _rule(method, path_substring, action, count=1, body_substring=None): def _arm_rules(rules): - _control(cluster.proxy_url, "/config", + control_call(cluster.proxy_url, "/config", {"rules": rules, "trace": True, "trace_path_substring": STOP_PREFIX, "trace_bodies": True}) @@ -252,7 +278,7 @@ def _stop_and_release(node, query_id, path_substring, respond="forward", kill=Tr """Parked request, stop, `is_cancelled`, release: nothing the stopped query does after the release can predate the stop. Returns the release time on the proxy's clock.""" parked = _wait_until( - lambda: [p for p in _control(cluster.proxy_url, "/parked")["parked"] if path_substring in p["path"]], timeout=60) + lambda: [p for p in control_call(cluster.proxy_url, "/parked")["parked"] if path_substring in p["path"]], timeout=60) assert len(parked) == 1, parked # The release must reach the parked request before its socket times out, or the stopped query sees a timeout # instead of the released answer. Killed and polled over HTTP: a client start per query is slow in a sanitizer @@ -263,7 +289,7 @@ def _stop_and_release(node, query_id, path_substring, respond="forward", kill=Tr _wait_until(lambda: node.http_query( "SELECT is_cancelled FROM system.processes WHERE query_id = '{}'".format(query_id)).strip() == "1", timeout=STOP_ATTEMPT_TIMEOUT_S - 1) - _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": respond}) + control_call(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": respond}) released = [r for r in _stats()["trace"] if r["t_release_mono_ms"] is not None] assert len(released) == 1, released return released[0]["t_release_mono_ms"] @@ -389,7 +415,7 @@ def test_failed_read_after_a_lost_race_and_stop_starts_no_further_put(node_stop, query's own stop.""" def lose_race_then_fail_the_read(suffix): - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) _arm_rules([_rule("PUT", STOP_CATALOG, "412"), _rule("GET", STOP_CATALOG, "hold"), _rule("PUT", STOP_CATALOG, "412", count=1000)]) query_id = "failed_read_{}_{}".format(suffix, stop) @@ -404,7 +430,7 @@ def lose_race_then_fail_the_read(suffix): return request.get_error() # A table created without faults leaves the lane holding the catalog it wrote. - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) node_stop.query(_create_sql("failed_read_warm_" + stop), timeout=120) error = lose_race_then_fail_the_read("cached") # `ABORTED`: the conflict the settling read could not resolve. @@ -429,7 +455,7 @@ def test_kill_after_ambiguous_create_keeps_unresolved_exit(node_stop): assert _remaining_counts() == [0, 0] # Control: a live owner decides again after each ambiguous attempt until one lands. - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) _arm_rules([_rule("PUT", STOP_CATALOG, "503", count=8)]) node_stop.query(_create_sql("ambiguous_create_live"), timeout=120) statuses = [r["status"] for r in _catalog_puts(_stats()["trace"])] @@ -450,7 +476,7 @@ def test_killed_leader_with_chunk_in_flight_leaves_a_usable_lane(node_stop): sync = {"async_insert": 0} leader = node_stop.get_query_request("INSERT INTO ref_batch VALUES (1, 'leader')", query_id="ref_batch_leader", settings=sync, timeout=120) - _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + _wait_until(lambda: control_call(cluster.proxy_url, "/parked")["parked"], timeout=60) neighbor = node_stop.get_query_request("INSERT INTO ref_batch VALUES (2, 'neighbor')", settings=sync, timeout=120) # The release answers 503 without forwarding, so the chunk's settling read meets a 404. released_ms = _stop_and_release(node_stop, "ref_batch_leader", "/_log/", respond="503") @@ -479,16 +505,16 @@ def test_atomic_sync_drop_kill_releases_only_waiter(node_stop): seen = len(_stats()["trace"]) query_id = "atomic_sync_drop" request = node_stop.get_query_request("DROP TABLE atomic_sync_drop SYNC", query_id=query_id, timeout=120) - parked = _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + parked = _wait_until(lambda: control_call(cluster.proxy_url, "/parked")["parked"], timeout=60) assert len(parked) == 1, parked # Over HTTP: the parked write must still be parked when the kill returns. node_stop.http_query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) _wait_until(lambda: request.process.poll() is not None, timeout=30) error = request.get_error() assert re.search(r"Code: 394\b", error), error - assert _control(cluster.proxy_url, "/parked")["parked"] == parked + assert control_call(cluster.proxy_url, "/parked")["parked"] == parked - _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) + control_call(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) _wait_until(lambda: node_stop.query( "SELECT count() FROM system.dropped_tables WHERE uuid = '{}'".format(uuid)).strip() == "0", timeout=60) _wait_until(lambda: _removal_records(node_stop, _stats()["trace"][seen:], life), timeout=60) @@ -510,7 +536,7 @@ def _detach_cold(node, name): parts = _active_parts(node, name) node.query("DETACH TABLE {} PERMANENTLY".format(name)) node.restart_clickhouse() - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) return life, parts @@ -594,7 +620,7 @@ def recovery_retries(): assert re.search(r"Code: 210\b", error) and re.search(r"_log/.*gave up at the \w+ deadline", error, re.DOTALL), error assert len([r for r in _stats()["trace"] if life in r["path"]]) == life_gets_at_kill, "another walk started" - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) node_stop.query("ATTACH TABLE {}".format(name)) _assert_reattached(node_stop, name, parts) @@ -659,7 +685,7 @@ def _checked_blob_fixture(node, name, table, insert, new_blobs): assert len(puts) == new_blobs and puts == missing, \ "the fixture of {} publishes {} blob(s), not {}: PUT {}, HEAD 404 {}".format(name, len(puts), new_blobs, puts, missing) node.query("CREATE TABLE {} {}".format(name, table)) - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) def _blob_fixture_insert(node, name, insert): @@ -924,7 +950,7 @@ def test_manual_gc_kill_preserves_owner_code(node_gc): params={"default_format": "JSONEachRow"}, method="POST")) assert first["acquired_lease"] in (1, True), first catalog = GC_POOL + "/cas/ref_catalog" - _control(cluster.proxy_url, "/config", + control_call(cluster.proxy_url, "/config", {"rules": [_rule("GET", catalog, "hold")], "trace": True, "trace_path_substring": GC_POOL}) query_id = "manual_gc_kill" request = node_gc.get_query_request("SYSTEM CAS GC RUN {}".format(GC_DISK), query_id=query_id, timeout=120) @@ -955,22 +981,21 @@ def test_shutdown_hands_atomic_drop_to_restart(node_stop): shutting_down_before = int(node_stop.count_in_log("Waiting for current connections to close").strip()) fatal_before = int(node_stop.count_in_log("").strip()) # Taken before the hold, so only the kill and the log poll run before the parked `PUT`'s attempt timeout. - pid = node_stop.get_process_pid("clickhouse") - assert pid is not None + pid = server_pid(node_stop) - _control(cluster.proxy_url, "/config", {"reset": True}) + control_call(cluster.proxy_url, "/config", {"reset": True}) # Only this table's `Live -> Removing` write names its life as `Removing`. _arm_rules([_rule("PUT", STOP_CATALOG, "hold", body_substring=_removing_body(life))]) node_stop.query("DROP TABLE {}".format(name)) - parked = _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + parked = _wait_until(lambda: control_call(cluster.proxy_url, "/parked")["parked"], timeout=60) assert len(parked) == 1, parked node_stop.exec_in_container(["bash", "-c", "kill -15 {}".format(pid)], user="root") # Logged right after `IsServerShuttingDown` is set, so the removal resumes under shutdown. _wait_until(lambda: int(node_stop.count_in_log("Waiting for current connections to close").strip()) > shutting_down_before, timeout=30) - _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) + control_call(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) released_ms = [r for r in _stats()["trace"] if r["t_release_mono_ms"] is not None][0]["t_release_mono_ms"] - _wait_until(lambda: node_stop.get_process_pid("clickhouse") is None, timeout=60) + _wait_until(lambda: not _server_alive(node_stop, pid), timeout=60) trace = _stats()["trace"] held = next(r for r in trace if r["rule"] == "hold") @@ -1213,6 +1238,47 @@ def _server_alive(node, pid): return bool(state) and not state.startswith("Z") +def server_pid(instance): + """The PID the running server logged at its start: the server process itself. `get_process_pid` returns the + first match of `pgrep`, which can be the watchdog that supervises the server.""" + line = instance.exec_in_container(["bash", "-c", "grep -a 'Application: Starting ClickHouse' " + "/var/log/clickhouse-server/clickhouse-server.log | tail -n 1"]) + pid = int(line.rsplit("PID ", 1)[1].strip()) + assert _server_alive(instance, pid), line + return pid + + +def sigterm_orderly(instance, exit_deadline_s=30, after_exit=None): + """One SIGTERM to the exact server PID: the server must exit by itself within `exit_deadline_s` and log the + orderly shutdown (a forced exit can lose its own line, so the two success lines carry the check). A second + signal, or SIGKILL, would end the process without the shutdown under test, so the process is killed only when + the check failed. `after_exit(seconds)` runs between the exit and the check of the log. Returns the seconds from the + signal to the exit. The caller starts the server again.""" + # The success line only: the warning about remaining connections starts with the same words. + closed = "Application: Closed connections\\.$" + forced = "Will shutdown forcefully" + storages = "Shut down storages\\." + markers = (closed, forced, storages, "", "LOGICAL_ERROR") + before = {line: int(instance.count_in_log(line).strip()) for line in markers} + pid = server_pid(instance) + signalled = time.monotonic() + try: + instance.exec_in_container(["bash", "-c", "kill -15 {}".format(pid)], user="root") + # The deadline runs from the signal, the exec that sends it included, and a probe that succeeds after it fails. + _wait_until(lambda: not _server_alive(instance, pid), timeout=max(0.0, exit_deadline_s - (time.monotonic() - signalled)), + describe=lambda: "{} still alive {:.1f} s after the signal".format(pid, time.monotonic() - signalled)) + exited = time.monotonic() - signalled + assert exited <= exit_deadline_s, "the server exited {:.1f} s after the signal, over {} s".format(exited, exit_deadline_s) + if after_exit is not None: + after_exit(exited) + delta = {line: int(instance.count_in_log(line).strip()) - count for line, count in before.items()} + assert delta == {closed: 1, forced: 0, storages: 1, "": 0, "LOGICAL_ERROR": 0}, delta + finally: + if _server_alive(instance, pid): + instance.exec_in_container(["bash", "-c", "kill -9 {}".format(pid)], user="root") + return exited + + def test_sigterm_during_insert_upload_is_orderly(node_guard): """SIGTERM while a paced body goes out: shutdown kills the query, its upload stops, and the server closes its connections within `shutdown_wait_unfinished` (30 s, well below the body's remaining time), shuts its storages @@ -1220,29 +1286,1036 @@ def test_sigterm_during_insert_upload_is_orderly(node_guard): the process without the orderly shutdown under test.""" node_guard.query("CREATE TABLE sigterm_upload (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " "SETTINGS storage_policy = '{}'".format(GUARD_POLICY)) - # The success line only: the warning about remaining connections starts with the same words. - closed = "Application: Closed connections\\.$" - forced = "Will shutdown forcefully" - storages = "Shut down storages\\." - before = {line: int(node_guard.count_in_log(line).strip()) for line in (closed, forced, storages, "")} - pid = node_guard.get_process_pid("clickhouse") - assert pid is not None query_id = "sigterm_upload_insert" request = node_guard.get_query_request(PACED_INSERT.format("sigterm_upload"), query_id=query_id, settings=_paced(), timeout=UNSTOPPED_WAIT_S) try: sent = _wait_body_going_out(node_guard, request, query_id, baseline=0) - signalled = time.monotonic() - node_guard.exec_in_container(["bash", "-c", "kill -15 {}".format(pid)], user="root") - _wait_until(lambda: not _server_alive(node_guard, pid), timeout=120, describe=lambda: "{} still alive {:.1f} s " - "after the signal".format(pid, time.monotonic() - signalled)) - logging.info("sigterm: %d bytes paced at the gate, server exited %.1f s after the signal", - sent, time.monotonic() - signalled) - _wait_until(lambda: request.process.poll() is not None, timeout=60) - delta = {line: int(node_guard.count_in_log(line).strip()) - count for line, count in before.items()} - # A forced exit can lose its own log line, so the two success lines carry the check. - assert delta == {closed: 1, forced: 0, storages: 1, "": 0}, delta + exited = sigterm_orderly(node_guard, exit_deadline_s=120, + after_exit=lambda _: _wait_until(lambda: request.process.poll() is not None, timeout=60)) + logging.info("sigterm: %d bytes paced at the gate, server exited %.1f s after the signal", sent, exited) finally: - if node_guard.get_process_pid("clickhouse") is None: - node_guard.start_clickhouse() + node_guard.start_clickhouse() assert node_guard.query("SELECT 1").strip() == "1" + + +# The paced-body tooling (`helpers/cas_paced_body.py`) and the pools of `node_cut` (`configs/storage_conf_cut.xml`). +# Where a data body goes: local staging uploads it to `blobs/` at the disk commit of the part; S3 staging uploads it to +# `staging/` while the file is written. Arming on these prefixes keeps leases, ref logs and manifests out of reach. +CUT_PREFIX = {"local": "/test/cas_request_cut/blobs/", "s3": "/test/cas_request_cut_s3/staging/", + "local_mp": "/test/cas_request_cut_mp/blobs/", "s3_mp": "/test/cas_request_cut_s3_mp/staging/"} +CUT_POLICY = {"local": "cas_cut", "s3": "cas_cut_s3", "local_mp": "cas_cut_mp", "s3_mp": "cas_cut_s3_mp"} +# A body of a cut case: incompressible, over the claim bound `CUT_MIN_BODY`, and over what the kernels of both ends queue +# for a sender (about 2.3 MB were measured on loopback): a sender that is stopped must still have bytes to withhold, or +# the proxy sees the whole body. At the default pace (256 KiB/s) it is in flight for 32 s, far longer than the few +# seconds from the gate to the signal. +CUT_BODY = 8 << 20 +CUT_MIN_BODY = 1 << 20 +# The merge selector takes equal parts only once there are enough of them. +SEED_PARTS = 6 +SEED_PART = CUT_BODY // SEED_PARTS +# A no-signal control proves that a paced body completes and no timeout is taken for a cut, so its body is small and +# its pace is fast enough to finish in seconds, slow enough to be seen at the gate. +CONTROL_BODY = 2 << 20 +CONTROL_SEED_PART = CONTROL_BODY // SEED_PARTS +CONTROL_RATE = 512 << 10 +CONTROL_MIN_LEFT_S = 1 +NO_SIGNAL_TIMEOUT_S = 60 +# The multipart cases use the `*_mp` disks, whose part size is the smallest the object store accepts: a body over two +# parts is multipart and the claim bound is a full part (parts go out in parallel and the last one is shorter). +CUT_PART = 5 << 20 +MULTIPART_BODY = 12 << 20 +MULTIPART_SEED_PART = MULTIPART_BODY // SEED_PARTS + +FULL_MATRIX = os.environ.get("CAS_CUT_FULL_MATRIX") == "1" + + +def matrix(default, full): + """The parameter list of a cut-upload test: `default` in CI, `full` when `CAS_CUT_FULL_MATRIX=1`.""" + return full if FULL_MATRIX else default + + +def create_large_body_table(instance, name, staging, replicated=False): + """A table whose data is one incompressible `String` column in a `Wide` part, so that a part of + `insert_large_body` has one body of its own.""" + engine = "ReplicatedMergeTree('/clickhouse/tables/{}', '{{replica}}')".format(name) if replicated else "MergeTree" + instance.query( + "CREATE TABLE {} (id UInt64, payload String CODEC(NONE)) ENGINE = {} ORDER BY id " + "SETTINGS storage_policy = '{}', min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, " + "min_bytes_for_full_part_storage = 0".format(name, engine, CUT_POLICY[staging])) + + +def insert_large_body(instance, name, row_id, size=CUT_BODY): + """One part holding one row with `size` random bytes.""" + instance.query("INSERT INTO {} SELECT {}, randomString({})".format(name, row_id, size), + settings={"async_insert": 0}, timeout=120) + + +def seed_mergeable_parts(instance, name, parts=SEED_PARTS, size=SEED_PART): + """Stops merges of `name` and inserts `parts` equal parts, so that the merge selector takes all of them at once + after `SYSTEM START MERGES`. The merged column body is `parts * size` bytes.""" + instance.query("SYSTEM STOP MERGES {}".format(name)) + for row_id in range(1, parts + 1): + insert_large_body(instance, name, row_id, size=size) + + +def payload_digest(instance, name): + return instance.query("SELECT count(), sum(cityHash64(id, payload)) FROM {}".format(name)).strip() + + +def _s3_url(pool, key): + return "http://s3proxy:11121/test/{}/{}".format(pool, key) + + +def _s3_function(pool, key): + return "s3('{}', 'clickhouse', 'clickhouse', 'RawBLOB', 'x String')".format(_s3_url(pool, key)) + + +# The self-tests only need some bytes at the gate; the paced read of a sender that writes at full speed is slow to start. +SELFTEST_GATE_BYTES = 64 << 10 + + +def test_proxy_paces_one_body(node_cut): + """The proxy claims one matching body and then disarms: a second matching upload passes at once, while the claimed + body is still being read at the armed rate. The order is read from the proxy's own records.""" + size = 1 << 20 + claimed_size = 8 << 20 + rate = 256 << 10 + control_call(cluster.proxy_url, "/config", {"trace": True, "trace_path_substring": "/test/selftest_paced/bystander"}) + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_paced/", 512 << 10, rate_bytes_per_s=rate) + request = node_cut.get_query_request( + "INSERT INTO FUNCTION {} SELECT randomString({})".format(_s3_function("selftest_paced", "claimed.bin"), claimed_size), + timeout=120) + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES, min_left_s=20) + assert record["method"] == "PUT" and record["key"] == "/test/selftest_paced/claimed.bin", record + assert record["content_length"] == claimed_size and record["upload_id"] is None, record + + # The bystander matches the armed prefix and size: it passes only if the mode disarmed after the claim. + node_cut.query("INSERT INTO FUNCTION {} SELECT randomString({})".format( + _s3_function("selftest_paced", "bystander.bin"), size)) + + def bystander_done(): + stats = _stats() + done = [r for r in stats["trace"] if r["method"] == "PUT" and r["path"] == "/test/selftest_paced/bystander.bin" + and r["t_done_mono_ms"] is not None] + return (done, stats) if done else None + + bystander, stats = _wait_until(bystander_done, timeout=60) + assert len(bystander) == 1 and bystander[0]["status"] == 200, bystander + assert not [e for e in stats["paced_trace"] if e["event"] == "ended"], stats["paced_trace"] + assert {e["request_id"] for e in stats["paced_trace"]} == {request_id}, stats["paced_trace"] + + release_pace(cluster.proxy_url, record) + ended = wait_complete(cluster.proxy_url, record, timeout_s=60) + assert bystander[0]["t_done_mono_ms"] < ended["t_ended_mono_ms"], \ + "the bystander finished only after the claimed body: {} {}".format(bystander, ended) + request.get_answer() + for key, expected in (("claimed.bin", claimed_size), ("bystander.bin", size)): + assert node_cut.query("SELECT length(x) FROM {}".format(_s3_function("selftest_paced", key))).strip() == str(expected) + assert len({e["request_id"] for e in _stats()["paced_trace"]}) == 1 + + +def test_proxy_holds_a_get_after_its_headers(node_cut): + """`hold_get` sends the headers of the first `GET`, waits for the release and then sends half of the body.""" + size = 1 << 20 + node_cut.query("INSERT INTO FUNCTION {} SELECT randomString({})".format(_s3_function("selftest_get", "o.bin"), size)) + control_call(cluster.proxy_url, "/config", {"hold_get": {"prefix": "/test/selftest_get/"}}) + request = node_cut.get_query_request( + "SELECT length(x) FROM {} SETTINGS s3_max_get_rps = 0, s3_retry_attempts = 1".format( + _s3_function("selftest_get", "o.bin")), timeout=60) + held = _wait_until(lambda: next((h for h in _stats()["held_gets"] if h["state"] == "waiting"), None), timeout=30) + # The first `GET` may be a ranged read, so its body can be shorter than the object. + assert held["key"] == "/test/selftest_get/o.bin" and 0 < held["content_length"] <= size, held + assert held["t_release_mono_ms"] is None, held + control_call(cluster.proxy_url, "/release_get", {"id": held["id"]}) + released = _wait_until(lambda: next((h for h in _stats()["held_gets"] if h["state"] == "truncated"), None), timeout=30) + assert released["t_release_mono_ms"] >= held["t_headers_mono_ms"], released + # The client may serve the query from another read or retry this one: the mode disarmed itself. + _wait_until(lambda: request.process.poll() is not None, timeout=60) + + +def test_proxy_fails_one_abort(node_cut): + """`fail_abort` answers the first `DELETE ?uploadId=` of the key with 503 and forwards the second.""" + key = "/test/selftest_abort/k.bin" + control_call(cluster.proxy_url, "/config", {"fail_abort": {"key": key, "upload_id": "u1", "remaining": 1}}) + url = "http://s3proxy:11121{}?uploadId=u1".format(key) + statuses = [node_cut.exec_in_container( + ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "-X", "DELETE", url]).strip() for _ in range(2)] + other = node_cut.exec_in_container( + ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "-X", "DELETE", url.replace("u1", "u2")]).strip() + assert statuses[0] == "503" and statuses[1] != "503" and other != "503", (statuses, other) + trace = _stats()["abort_trace"] + assert [(r["upload_id"], r["injected"], r["status"]) for r in trace] == [("u1", True, 503), ("u1", False, int(statuses[1]))], trace + + +# A client for the cut self-tests, run next to the proxy: it sends one large `PUT` as fast as the connection takes it. +# `fin` and `rst` wait for a line on stdin and then end the process, like a server that stops its upload: the kernel +# closes the socket with a FIN queued behind the bytes it still holds, or with an RST that drops them. `complete` +# sends the whole body. +PUT_CLIENT = r""" +import os, socket, struct, sys, threading +mode, size, key = sys.argv[1], int(sys.argv[2]), sys.argv[3] +sock = socket.create_connection(("127.0.0.1", 11121)) +sock.sendall(("PUT %s HTTP/1.1\r\nHost: s3proxy:11121\r\nContent-Length: %d\r\n\r\n" % (key, size)).encode()) +print("connected", flush=True) +body = b"x" * size +if mode == "complete": + sock.sendall(body) + print("sent", flush=True) + print(sock.recv(4096).split(b"\r\n")[0].decode(), flush=True) +else: + threading.Thread(target=lambda: sock.sendall(body), daemon=True).start() + sys.stdin.readline() + if mode == "rst": + sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) + os._exit(0) +""" +# Over what the kernels of both ends queue for a sender (about 2.3 MB were measured), so that the sender is still +# writing when it ends. +SELFTEST_CUT_SIZE = 8 << 20 + + +def start_put_client(mode, key): + return subprocess.Popen( + cluster.base_cmd + ["exec", "-T", "s3proxy", "python3", "-c", PUT_CLIENT, mode, str(SELFTEST_CUT_SIZE), "/test/selftest_cut/" + key], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + + +def close_put_client(client): + client.stdin.write("close\n") + client.stdin.flush() + client.wait(timeout=30) + + +@pytest.mark.parametrize("mode", matrix(["fin"], ["fin", "rst"])) +def test_proxy_sees_a_cut_body(node_cut, mode): + """A sender that ends its process mid-body is seen as `peer_eof` (FIN) or `peer_reset` (RST) with fewer bytes than + `Content-Length`, promptly after `release_pace`. Without the release the queued bytes drain at the paced rate first + (measured once with a 24 MiB body: 60 s after a FIN, so the tests always release).""" + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_cut/", 1 << 20) + client = start_put_client(mode, "{}.bin".format(mode)) + try: + assert client.stdout.readline().strip() == "connected" + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + before_close = now_mono_ms(cluster.proxy_url) + close_put_client(client) + release_pace(cluster.proxy_url, record) + ended = wait_cut(cluster.proxy_url, record, 30, not_before_mono_ms=before_close) + finally: + if client.poll() is None: + client.kill() + assert record_of(cluster.proxy_url, record)["forwarded"] is False, "a short body must not be forwarded: {}".format( + record_of(cluster.proxy_url, record)) + delay = (ended["t_ended_mono_ms"] - before_close) / 1000.0 + expected = "peer_eof" if mode == "fin" else "peer_reset" + record_measurement("selftest_cut_" + mode, delay_s=round(delay, 1), outcome=ended["outcome"], + received=ended["received"], received_at_close=record["received"]) + assert ended["outcome"] == expected, ended + assert delay < 15, "a released pace must see the close quickly: {}".format(ended) + + +def test_proxy_sees_a_complete_body_after_release(node_cut): + """The reverse control: a sender that is not cut finishes the body at full speed after `release_pace`, and + `wait_cut` rejects it while `wait_complete` accepts it.""" + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_cut/", 1 << 20) + client = start_put_client("complete", "complete.bin") + try: + assert client.stdout.readline().strip() == "connected" + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + release_pace(cluster.proxy_url, record) + with pytest.raises(AssertionError, match="not cut"): + wait_cut(cluster.proxy_url, record, 30) + wait_complete(cluster.proxy_url, record, 5) + _wait_until(lambda: record_of(cluster.proxy_url, record)["forwarded"], timeout=10) + finally: + client.kill() + + +def test_wait_cut_rejects_a_cut_before_the_signal(node_cut): + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_cut/", 1 << 20) + client = start_put_client("rst", "early.bin") + try: + assert client.stdout.readline().strip() == "connected" + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + close_put_client(client) + after_close = now_mono_ms(cluster.proxy_url) + release_pace(cluster.proxy_url, record) + with pytest.raises(AssertionError, match="before the signal"): + wait_cut(cluster.proxy_url, record, 30, not_before_mono_ms=after_close + 1000) + finally: + if client.poll() is None: + client.kill() + + +def test_wait_cut_bounds_the_time_from_the_signal_statement(node_cut): + """The deadline counts from the clock read before the signal statement, not from when the wait starts.""" + request_id = arm_paced_body(cluster.proxy_url, "/test/selftest_cut/", 1 << 20) + client = start_put_client("rst", "late.bin") + try: + assert client.stdout.readline().strip() == "connected" + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + before_close = now_mono_ms(cluster.proxy_url) + close_put_client(client) + release_pace(cluster.proxy_url, record) + wait_cut(cluster.proxy_url, record, 30, not_before_mono_ms=before_close, signal_mono_ms=before_close) + with pytest.raises(AssertionError, match="after the signal statement was issued"): + wait_cut(cluster.proxy_url, record, 30, signal_mono_ms=before_close - 60 * 1000) + finally: + if client.poll() is None: + client.kill() + + +def test_paced_body_claims_only_the_bodies_it_is_armed_for(node_cut): + """A lower bound of 0 is refused. Under the armed prefix a small `PUT`, a large `PUT` with a query (`?tagging`) and + a large `PUT` with `x-amz-copy-source` are not claimed; the control is that a plain large `PUT` is.""" + with pytest.raises(AssertionError): + arm_paced_body(cluster.proxy_url, "/test/selftest_claim/", 0) + with pytest.raises(urllib.error.HTTPError): + control_call(cluster.proxy_url, "/config", {"paced_body": {"prefix": "/test/selftest_claim/", "min_content_length": 0}}) + arm_paced_body(cluster.proxy_url, "/test/selftest_claim/", 1 << 20, rate_bytes_per_s=1 << 20) + node_cut.query("INSERT INTO FUNCTION {} SELECT randomString(1000)".format(_s3_function("selftest_claim", "small.bin"))) + node_cut.exec_in_container(["bash", "-c", "head -c 2000000 /dev/zero > /tmp/claim_body.bin"]) + + def put(path, *headers): + # Unsigned: the store refuses it, which does not matter; the proxy decides on the request line and headers. + node_cut.exec_in_container(["curl", "-s", "--max-time", "60", "-o", "/dev/null", "-X", "PUT", "--data-binary", "@/tmp/claim_body.bin", + *[a for h in headers for a in ("-H", h)], "http://s3proxy:11121/test/selftest_claim/" + path]) + + put("tagged.bin?tagging") + put("copied.bin", "x-amz-copy-source: /test/selftest_claim/small.bin") + assert _stats()["paced_trace"] == [] + put("plain.bin") + claimed = _wait_until(lambda: [r for r in paced_requests(cluster.proxy_url) if r["key"] == "/test/selftest_claim/plain.bin"], + timeout=30) + assert claimed[0]["content_length"] == 2000000, claimed + + +@pytest.mark.parametrize("staging", matrix(["local"], ["local", "s3"])) +def test_merge_without_a_stop_completes_paced(node_cut, staging): + """No-signal control of a merge: the paced body is neither cut nor timed out, the merge commits and the data is + the sources' data.""" + name = "ctl_merge_" + staging + create_large_body_table(node_cut, name, staging) + merge, record, sources, digest = start_paced_merge( + node_cut, name, staging, part_size=CONTROL_SEED_PART, rate_bytes_per_s=CONTROL_RATE, min_left_s=CONTROL_MIN_LEFT_S) + wait_complete(cluster.proxy_url, record, NO_SIGNAL_TIMEOUT_S) + _wait_until(lambda: part_names(node_cut, name, active_only=True) == [merge], timeout=NO_SIGNAL_TIMEOUT_S) + assert payload_digest(node_cut, name) == digest + + +def test_mutation_without_a_stop_completes_paced(node_cut): + """No-signal control of a mutation (local staging): the paced body of the rewritten column completes, the + mutation finishes and the data is the mutated data.""" + name = "ctl_mutation" + create_large_body_table(node_cut, name, "local") + source, result_part, record, original, mutated = start_paced_mutation( + node_cut, name, size=CONTROL_BODY, rate_bytes_per_s=CONTROL_RATE, min_left_s=CONTROL_MIN_LEFT_S) + wait_complete(cluster.proxy_url, record, NO_SIGNAL_TIMEOUT_S) + _wait_until(lambda: node_cut.query("SELECT is_done FROM system.mutations WHERE table = '{}'".format(name)).strip() == "1", + timeout=NO_SIGNAL_TIMEOUT_S) + assert payload_digest(node_cut, name) == mutated + + +CUT_DISK = {"local": "disk_cas_cut", "s3": "disk_cas_cut_s3", "local_mp": "disk_cas_cut_mp", "s3_mp": "disk_cas_cut_s3_mp"} +# An upper bound: a stopped body is cut within about a second. +CUT_DEADLINE_S = 10 +# The cases whose signal is a synchronous statement (`DROP TABLE ... SYNC`, `DETACH TABLE ... SYNC`, +# `KILL QUERY ... SYNC`) free the pace only after the statement has returned. That takes 5 to 6 s on the development +# machine, so the bound leaves room for a runner that is twice as slow. The other cases cut within 1 s locally and +# keep `CUT_DEADLINE_S`. +SYNC_CUT_DEADLINE_S = 20 +RO_DISKS_CONFIG = "/etc/clickhouse-server/cut_ro_disks.xml" + + +def list_disk_dir(instance, disk, path): + """Entries of `path` as the pool's read-only window lists them: a part's files are refs, not files of a local + directory. An absent directory lists as empty; any other error fails the test.""" + return list_disk_dir_or_absent(instance, disk, path) or [] + + +def list_disk_dir_or_absent(instance, disk, path): + """Like `list_disk_dir`, but None for an absent directory, so that "absent" and "present and empty" differ.""" + instance.copy_file_to_container(os.path.join(os.path.dirname(__file__), "configs", "cut_ro_disks.xml"), RO_DISKS_CONFIG) + out = instance.exec_in_container( + ["bash", "-c", "clickhouse disks -C {} --disk {} --save-logs --query {} 2>&1; true".format( + RO_DISKS_CONFIG, shlex.quote(disk + "_ro"), shlex.quote("list '{}'".format(path)))]) + if "Code: 107" in out or "Code: 479" in out: + return None + assert "Code:" not in out, out + return out.split() + + +def fsck(instance, disk): + """`SYSTEM CAS FSCK ` as a dict of column -> value.""" + out = instance.exec_in_container( + ["bash", "-c", "clickhouse client --format TSVWithNames --query {}".format(shlex.quote("SYSTEM CAS FSCK '{}'".format(disk)))] + ).splitlines() + summary = dict(zip(out[0].split("\t"), out[1].split("\t"))) + assert "dangling" in summary, out + return summary + + +def table_namespace(instance, name): + data_path = instance.query("SELECT arrayJoin(data_paths) FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).strip() + first = data_path.splitlines()[0] + return first[first.index("store/"):] + + +def part_names(instance, name, active_only=False): + return instance.query("SELECT name FROM system.parts WHERE database = 'default' AND table = '{}'{} ORDER BY name".format( + name, " AND active" if active_only else "")).split() + + +def assert_namespace_holds_only_parts(instance, name, staging, namespace): + """The table's directory lists the parts the table knows (any state) and nothing else; `detached/` and `moving/` + are empty. The listing has a positive control: it must show the active parts.""" + disk = CUT_DISK[staging] + entries = list_disk_dir(instance, disk, namespace) + known = set(part_names(instance, name)) + assert set(part_names(instance, name, active_only=True)) <= set(entries), ("the listing does not show the active parts", entries) + extra = {e for e in set(entries) - known - {"detached", "moving", "format_version.txt"} if not re.fullmatch(r"mutation_\d+\.txt", e)} + assert not extra, ("extra entries in the table namespace", sorted(extra), entries) + for sub in ("detached", "moving"): + assert list_disk_dir(instance, disk, namespace + sub) == [], sub + assert instance.query("SELECT count() FROM system.detached_parts WHERE database = 'default' AND table = '{}'".format(name)).strip() == "0" + assert fsck(instance, disk)["dangling"] == "0" + + +def merges_of(instance, name): + return int(instance.query("SELECT count() FROM system.merges WHERE database = 'default' AND table = '{}'".format(name))) + + +def timed_cut(instance, name, record, signal, rows=merges_of, deadline_s=CUT_DEADLINE_S): + """Runs `signal`, which may return a waiter for a statement that is still running (waited for, so the stop flag is + set), then releases the pace, requires the body to be cut within the deadline and the task to leave + its system table (`rows` counts the table's rows there, merges by default). Returns the seconds from the signal to + the cut (proxy clock) and to the row leaving that table, the outcome and the bytes received.""" + t_proxy = now_mono_ms(cluster.proxy_url) + t_signal = time.monotonic() + waiter = signal() + statement = waiter(STATEMENT_RETURN_S) if callable(waiter) else None + release_pace(cluster.proxy_url, record) + ended = wait_cut(cluster.proxy_url, record, deadline_s, not_before_mono_ms=t_proxy, signal_mono_ms=t_proxy) + _wait_until(lambda: rows(instance, name) == 0, timeout=deadline_s) + result = ((ended["t_ended_mono_ms"] - t_proxy) / 1000.0, time.monotonic() - t_signal, ended["outcome"], ended["received"]) + record_measurement(name, cut_s=round(result[0], 1), row_gone_s=round(result[1], 1), outcome=result[2], received=result[3], + statement_s=None if statement is None else round(statement[0], 1)) + return result + + +def record_measurement(case, **values): + """Logs a measurement for the reader of a run.""" + logging.info("MEASURED %s %s", case, values) + + +def part_blocks(part): + """(min block, max block) of a part name such as `all_0_4_1`.""" + fields = part.split("_") + return int(fields[1]), int(fields[2]) + + +def start_paced_merge(instance, name, staging, part_size=SEED_PART, min_body=CUT_MIN_BODY, + rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S, min_left_s=5): + """Seeds mergeable parts, arms the proxy, starts the merge and waits at the gate. Returns the result part name, + the gate record, the source part names and the data digest. The selector may leave the newest part out of the + range (a replicated table does), so the range is read from `system.merges` and checked against the sources.""" + seed_mergeable_parts(instance, name, size=part_size) + sources = part_names(instance, name, active_only=True) + digest = payload_digest(instance, name) + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX[staging], min_body, rate_bytes_per_s) + instance.query("SYSTEM START MERGES {}".format(name)) + merge = _wait_until(lambda: instance.query("SELECT result_part_name FROM system.merges WHERE table = '{}'".format(name)).strip(), + timeout=60) + record = wait_body_gate(cluster.proxy_url, request_id, min_left_s=min_left_s) + assert merges_of(instance, name) == 1 + first, last = part_blocks(merge) + lowest = min(part_blocks(source)[0] for source in sources) + highest = max(part_blocks(source)[1] for source in sources) + assert lowest <= first and last <= highest, (merge, sources) + assert last > first, merge + if not instance.query("SELECT engine FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).startswith("Replicated"): + # A plain table merges every source: the result is deterministic. + assert merge == "all_{}_{}_1".format(lowest, highest), (merge, sources) + return merge, record, sources, digest + + +def merge_result_active(instance, name, merge): + """A part that covers `merge` is active: the merge completed, or was followed by a wider one.""" + first, last = part_blocks(merge) + return int(instance.query("SELECT count() FROM system.parts WHERE database = 'default' AND table = '{}' AND active " + "AND min_block_number <= {} AND max_block_number >= {}".format(name, first, last))) == 1 + + +def queue_entry(instance, name): + return instance.query("SELECT node_name, num_tries FROM system.replication_queue WHERE database = 'default' AND table = '{}' " + "AND type = 'MERGE_PARTS'".format(name)).strip() + + +@pytest.mark.parametrize("engine, staging", matrix( + [("mergetree", "local"), ("replicated", "s3")], + [("mergetree", "local"), ("mergetree", "s3"), ("replicated", "local"), ("replicated", "s3")])) +def test_stop_merges_cuts_the_merge_upload(node_cut, engine, staging): + name = "stop_{}_{}".format(engine, staging) + replicated = engine == "replicated" + create_large_body_table(node_cut, name, staging, replicated) + merge, record, sources, digest = start_paced_merge(node_cut, name, staging) + queue = queue_entry(node_cut, name) if replicated else None + assert not replicated or queue, "no MERGE_PARTS entry while the merge runs" + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP MERGES {}".format(name))) + # While the stop holds: no merge starts, the queue entry is the same and was not tried again. + assert_quiet(node_cut, name) + assert part_names(node_cut, name, active_only=True) == sources + assert payload_digest(node_cut, name) == digest + if replicated: + assert queue_entry(node_cut, name) == queue, (queue, queue_entry(node_cut, name)) + record_measurement("stop_" + engine + "_" + staging + "_queue", before=queue, held=queue_entry(node_cut, name)) + namespace = table_namespace(node_cut, name) + assert_namespace_holds_only_parts(node_cut, name, staging, namespace) + node_cut.query("SYSTEM START MERGES {}".format(name)) + _wait_until(lambda: merge_result_active(node_cut, name, merge), timeout=120, describe=lambda: part_names(node_cut, name)) + assert payload_digest(node_cut, name) == digest + assert_namespace_holds_only_parts(node_cut, name, staging, namespace) + + +MUTATION_SQL = "ALTER TABLE {} UPDATE payload = reverse(payload) WHERE 1" +MUTATED_DIGEST_SQL = "SELECT count(), sum(cityHash64(id, reverse(payload))) FROM {}" +# How long a stopped task must stay unselected. The full matrix keeps the 10 s that match the idle sleep of a +# background assignee; the default set waits half of it. +QUIET_S = 10 if FULL_MATRIX else 5 +# A statement that waits for the cut task: measured at 0.2 to 0.6 s, so this bound has a wide margin. +STATEMENT_RETURN_S = 60 + + +def start_paced_mutation(instance, name, staging="local", size=CUT_BODY, rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S, + min_left_s=5): + """One part with one large body, a mutation that rewrites it, the proxy armed, the mutation at the gate. Returns + the part name, the gate record, the digest of the original data and the digest the mutation produces.""" + insert_large_body(instance, name, 1, size=size) + source = part_names(instance, name, active_only=True) + assert len(source) == 1, source + original = payload_digest(instance, name) + mutated = instance.query(MUTATED_DIGEST_SQL.format(name)).strip() + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX[staging], CUT_MIN_BODY, rate_bytes_per_s) + instance.query(MUTATION_SQL.format(name), settings={"mutations_sync": 0}) + probe = "SELECT result_part_name FROM system.merges WHERE database = 'default' AND table = '{}' AND is_mutation".format(name) + result_part = _wait_until(lambda: instance.query(probe).strip(), timeout=60) + assert result_part.startswith(source[0] + "_"), (source, result_part) + record = wait_body_gate(cluster.proxy_url, request_id, min_left_s=min_left_s) + assert merges_of(instance, name) == 1 + return source[0], result_part, record, original, mutated + + +def assert_quiet(instance, name, rows=merges_of): + """No task of the table starts while the stop or the kill holds. `rows` counts the table's rows in the system + table of the task.""" + for _ in range(2 * QUIET_S): + assert rows(instance, name) == 0 + time.sleep(0.5) + + +# Threads of `in_thread`; `clean_state` joins them before the tables are dropped. +RUNNING_STATEMENTS = [] + + +def in_thread(statement): + """Runs `statement` in a thread. Returns a function that waits for it and returns the seconds it took.""" + outcome = {} + + def run(): + begin = time.monotonic() + try: + statement() + except Exception as error: # reported by the waiter, in the test's thread + outcome["error"] = error + outcome["seconds"] = time.monotonic() - begin + + thread = threading.Thread(target=run, daemon=True) + RUNNING_STATEMENTS.append(thread) + thread.start() + + def wait(timeout_s): + thread.join(timeout_s) + assert not thread.is_alive(), "the statement did not return within {} s".format(timeout_s) + assert "error" not in outcome, outcome["error"] + return (outcome["seconds"],) + + return wait + + +def mutation_rows(instance, name): + return int(instance.query("SELECT count() FROM system.mutations WHERE database = 'default' AND table = '{}'".format(name))) + + +def test_stop_then_start_resumes_a_registered_mutation(node_cut): + name = "stop_mutation_local" + create_large_body_table(node_cut, name, "local") + source, result_part, record, original, mutated = start_paced_mutation(node_cut, name) + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP MERGES {}".format(name))) + assert_quiet(node_cut, name) + assert part_names(node_cut, name, active_only=True) == [source] + assert payload_digest(node_cut, name) == original + assert node_cut.query("SELECT is_done FROM system.mutations WHERE table = '{}'".format(name)).strip() == "0" + namespace = table_namespace(node_cut, name) + assert_namespace_holds_only_parts(node_cut, name, "local", namespace) + node_cut.query("SYSTEM START MERGES {}".format(name)) + _wait_until(lambda: node_cut.query("SELECT is_done FROM system.mutations WHERE table = '{}'".format(name)).strip() == "1", + timeout=120) + assert part_names(node_cut, name, active_only=True) == [result_part] + assert payload_digest(node_cut, name) == mutated + assert_namespace_holds_only_parts(node_cut, name, "local", namespace) + + +@pytest.mark.parametrize("engine, staging", matrix( + [("replicated", "local")], + [("mergetree", "local"), ("replicated", "local"), ("mergetree", "s3"), ("replicated", "s3")])) +def test_kill_mutation_cuts_the_upload(node_cut, engine, staging): + name = "kill_mutation_{}_{}".format(engine, staging) + replicated = engine == "replicated" + create_large_body_table(node_cut, name, staging, replicated) + source, result_part, record, original, mutated = start_paced_mutation(node_cut, name, staging) + kill = "KILL MUTATION WHERE database = 'default' AND table = '{}'".format(name) + timed_cut(node_cut, name, record, lambda: node_cut.query(kill)) + _wait_until(lambda: mutation_rows(node_cut, name) == 0, timeout=60) + if replicated: + # The entry that survives the kill runs once more with no command left, which shows as a merge row, so the + # quiet period starts when it has left the queue. + _wait_until(lambda: node_cut.query("SELECT count() FROM system.replication_queue WHERE database = 'default' " + "AND table = '{}' AND type = 'MUTATE_PART'".format(name)).strip() == "0", timeout=60, + describe=lambda: node_cut.query("SELECT * FROM system.replication_queue WHERE table = '{}' FORMAT Vertical".format(name))) + assert_quiet(node_cut, name) + active = part_names(node_cut, name, active_only=True) + # A replicated entry that survives the kill runs again with no command left and may leave the part one data + # version higher with the same data: the digest is the check, the name is recorded. + assert active == [source] or (replicated and len(active) == 1 and active[0].startswith(source + "_")), active + record_measurement(name + "_part", source=source, active=active) + assert payload_digest(node_cut, name) == original + assert_namespace_holds_only_parts(node_cut, name, staging, table_namespace(node_cut, name)) + + +def store_request(method, key, query=""): + """A hand-signed (SigV4) request sent to the object store directly, not through the proxy. `key` is a proxy path + such as `/test//blobs/`. Returns `(status, body)`; an error status is returned, not raised.""" + bucket, _, object_key = key.lstrip("/").partition("/") + host = "{}:{}".format(cluster.rustfs_ip, cluster.rustfs_port) + now = datetime.datetime.now(datetime.timezone.utc) + amz_date, date = now.strftime("%Y%m%dT%H%M%SZ"), now.strftime("%Y%m%d") + payload_hash = hashlib.sha256(b"").hexdigest() + path = "/" + bucket + ("/" + urllib.parse.quote(object_key, safe="/-_.~") if object_key and not query else "") + headers = "host:{}\nx-amz-content-sha256:{}\nx-amz-date:{}\n".format(host, payload_hash, amz_date) + signed = "host;x-amz-content-sha256;x-amz-date" + canonical = "\n".join([method, path, query, headers, signed, payload_hash]) + scope = "{}/us-east-1/s3/aws4_request".format(date) + to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, hashlib.sha256(canonical.encode()).hexdigest()]) + + def mac(key_bytes, message): + return hmac.new(key_bytes, message.encode(), hashlib.sha256).digest() + + signing_key = mac(mac(mac(mac(("AWS4" + cluster.rustfs_secret_key).encode(), date), "us-east-1"), "s3"), "aws4_request") + request = urllib.request.Request("http://{}{}{}".format(host, path, "?" + query if query else ""), method=method, headers={ + "x-amz-date": amz_date, "x-amz-content-sha256": payload_hash, + "Authorization": "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}".format( + cluster.rustfs_access_key, scope, signed, hmac.new(signing_key, to_sign.encode(), hashlib.sha256).hexdigest())}) + try: + with urllib.request.urlopen(request, timeout=20) as response: + return response.status, response.read() + except urllib.error.HTTPError as error: + return error.code, error.read() + + +def open_multipart_uploads(key): + """`(key, upload id)` of every multipart upload the store lists for `key` (a proxy path), by a signed + `ListMultipartUploads`. An error status fails the test.""" + bucket, _, object_key = key.lstrip("/").partition("/") + status, body = store_request("GET", "/" + bucket, "prefix={}&uploads=".format(urllib.parse.quote(object_key, safe="-_.~"))) + assert status == 200, "ListMultipartUploads answered {}: {}".format(status, body[:300]) + uploads = [] + for upload in ElementTree.fromstring(body).iter(): + if upload.tag.rpartition("}")[2] == "Upload": + fields = {child.tag.rpartition("}")[2]: child.text for child in upload} + uploads.append((fields["Key"], fields["UploadId"])) + return uploads + + +def arm_failed_abort(record): + """The proxy answers the first abort of the claimed multipart upload with 503 and forwards the retry. The listing + must show the upload now: that is the control for the listing that later shows it gone.""" + assert record["upload_id"], "the claimed body is not a part of a multipart upload: {}".format(record) + object_key = record["key"].partition("/")[2].partition("/")[2] + assert (object_key, record["upload_id"]) in open_multipart_uploads(record["key"]), record + control_call(cluster.proxy_url, "/config", {"fail_abort": {"key": record["key"], "upload_id": record["upload_id"], "remaining": 1}}) + + +def assert_abort_retried_and_gone(record): + """The abort `DELETE` of the upload failed once (injected 503) and succeeded on retry, and the store no longer + lists the upload.""" + def attempts(): + trace = [r for r in _stats()["abort_trace"] if r["key"] == record["key"] and r["upload_id"] == record["upload_id"]] + # The proxy records a `DELETE` before it forwards it, so the retry's status is set a moment later. + return trace if len(trace) >= 2 and trace[1]["status"] is not None else None + + trace = _wait_until(attempts, timeout=30, describe=lambda: _stats()["abort_trace"]) + assert [(r["injected"], r["status"]) for r in trace][0] == (True, 503), trace + assert not trace[1]["injected"] and 200 <= trace[1]["status"] < 300, trace + _wait_until(lambda: not open_multipart_uploads(record["key"]), timeout=30, describe=lambda: open_multipart_uploads(record["key"])) + assert not any(upload_id == record["upload_id"] for _, upload_id in open_multipart_uploads(record["key"])) + + +def test_killed_insert_retries_the_multipart_abort(node_cut): + name = "abort_insert" + create_large_body_table(node_cut, name, "local_mp") + insert_large_body(node_cut, name, 0, size=1 << 20) + digest = payload_digest(node_cut, name) + sources = part_names(node_cut, name, active_only=True) + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX["local_mp"], CUT_PART) + query_id = name + "_insert" + request = node_cut.get_query_request( + "INSERT INTO {} SELECT 1, randomString({})".format(name, MULTIPART_BODY), query_id=query_id, + settings={"async_insert": 0}, timeout=NO_SIGNAL_TIMEOUT_S) + record = wait_body_gate(cluster.proxy_url, request_id, min_received=SELFTEST_GATE_BYTES) + assert node_cut.query("SELECT count() FROM system.processes WHERE query_id = '{}'".format(query_id)).strip() == "1" + arm_failed_abort(record) + t_proxy = now_mono_ms(cluster.proxy_url) + node_cut.http_query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id), timeout=STATEMENT_RETURN_S) + release_pace(cluster.proxy_url, record) + wait_cut(cluster.proxy_url, record, SYNC_CUT_DEADLINE_S, not_before_mono_ms=t_proxy, signal_mono_ms=t_proxy) + assert_abort_retried_and_gone(record) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + assert part_names(node_cut, name, active_only=True) == sources + assert payload_digest(node_cut, name) == digest + + +def test_stopped_merge_retries_the_multipart_abort(node_cut): + name = "abort_merge" + create_large_body_table(node_cut, name, "s3_mp") + # The merged body is over two parts of the `*_mp` disk, so it goes out as a multipart upload. + merge, record, sources, digest = start_paced_merge(node_cut, name, "s3_mp", part_size=MULTIPART_SEED_PART, min_body=CUT_PART) + arm_failed_abort(record) + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP MERGES {}".format(name))) + assert_abort_retried_and_gone(record) + assert part_names(node_cut, name, active_only=True) == sources + assert payload_digest(node_cut, name) == digest + + +def queue_state(instance, name, result_part): + """The one queue entry that creates `result_part`, as a dict of the columns that a failure changes.""" + rows = instance.query( + "SELECT is_currently_executing, num_tries, num_postponed, last_exception, postpone_reason FROM system.replication_queue " + "WHERE database = 'default' AND table = '{}' AND type = 'MERGE_PARTS' AND new_part_name = '{}' FORMAT JSONEachRow".format( + name, result_part)).splitlines() + assert len(rows) == 1, rows + return json.loads(rows[0]) + + +def test_merge_stopped_during_a_failing_read_ends_aborted(node_cut): + """A source read that is held after its headers and then truncated fails while the merge is already stopped. The + cancellation must win over the read error. The check that carries this is `last_exception`: it must be empty or + the cancellation. `num_tries` unchanged is only the no-backoff half and holds with the read error too. + + What the trace does not prove: that the held `GET` is a read of this merge. The proxy is armed after the table is + filled and its digest read, and nothing else reads that prefix then, so the first `GET` under `blobs/` after + `SYSTEM START MERGES` can only be the merge's; the key is not mapped to a source part.""" + name = "read_order" + create_large_body_table(node_cut, name, "local", replicated=True) + seed_mergeable_parts(node_cut, name) + sources = part_names(node_cut, name, active_only=True) + digest = payload_digest(node_cut, name) + control_call(cluster.proxy_url, "/config", {"hold_get": {"prefix": CUT_PREFIX["local"]}}) + node_cut.query("SYSTEM START MERGES {}".format(name)) + held = _wait_until(lambda: next((h for h in _stats()["held_gets"] if h["state"] == "waiting"), None), timeout=60) + assert held["key"].startswith(CUT_PREFIX["local"]), held + result_part = _wait_until(lambda: node_cut.query("SELECT result_part_name FROM system.merges WHERE table = '{}'".format(name)).strip(), + timeout=60) + assert merges_of(node_cut, name) == 1 + before = queue_state(node_cut, name, result_part) + assert before["is_currently_executing"] == 1, before + node_cut.query("SYSTEM STOP MERGES {}".format(name)) + control_call(cluster.proxy_url, "/release_get", {"id": held["id"]}) + _wait_until(lambda: merges_of(node_cut, name) == 0, timeout=CUT_DEADLINE_S) + # The entry records the outcome of the attempt when the executing flag drops. + after = _wait_until(lambda: (lambda state: state if state["is_currently_executing"] == 0 else None)(queue_state(node_cut, name, result_part)), + timeout=CUT_DEADLINE_S) + record_measurement("read_order_queue", before=before, after=after, held=held) + assert after["last_exception"] == "" or "Cancelled merging parts" in after["last_exception"], str(after)[:400] + assert after["num_tries"] == before["num_tries"], (before, after) + assert part_names(node_cut, name, active_only=True) == sources + assert payload_digest(node_cut, name) == digest + + +@pytest.mark.parametrize("staging", matrix(["local"], ["local", "s3"])) +def test_drop_table_cuts_the_merge_upload(node_cut, staging): + name = "drop_" + staging + create_large_body_table(node_cut, name, staging) + merge, record, sources, digest = start_paced_merge(node_cut, name, staging) + namespace = table_namespace(node_cut, name) + timed_cut(node_cut, name, record, lambda: in_thread(lambda: node_cut.query("DROP TABLE {} SYNC".format(name))), deadline_s=SYNC_CUT_DEADLINE_S) + assert_dropped_and_clean(node_cut, name, staging, namespace) + + +def test_detach_table_cuts_the_merge_upload(node_cut): + name = "detach_replicated_local" + create_large_body_table(node_cut, name, "local", replicated=True) + merge, record, sources, digest = start_paced_merge(node_cut, name, "local") + namespace = table_namespace(node_cut, name) + timed_cut(node_cut, name, record, lambda: in_thread(lambda: node_cut.query("DETACH TABLE {} SYNC".format(name))), deadline_s=SYNC_CUT_DEADLINE_S) + assert node_cut.query("SELECT count() FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).strip() == "0" + node_cut.query("ATTACH TABLE {}".format(name)) + assert payload_digest(node_cut, name) == digest + _wait_until(lambda: merge_result_active(node_cut, name, merge), timeout=180, describe=lambda: part_names(node_cut, name)) + assert payload_digest(node_cut, name) == digest + assert_namespace_holds_only_parts(node_cut, name, "local", namespace) + + +@pytest.mark.parametrize("task, staging", matrix( + [("merge", "local"), ("mutation", "s3")], + [("merge", "local"), ("merge", "s3"), ("mutation", "local"), ("mutation", "s3")])) +def test_sigterm_during_a_background_task_upload_is_orderly(node_cut, task, staging): + """One SIGTERM to the exact server PID while a background merge or mutation sends its paced body, with no client + connected. The process must exit by itself within 30 s; the task finishes after the restart.""" + name = "sigterm_{}_{}".format(task, staging) + create_large_body_table(node_cut, name, staging) + if task == "merge": + target, record, _, digest = start_paced_merge(node_cut, name, staging) + expected_digest = digest + else: + source, target, record, digest, expected_digest = start_paced_mutation(node_cut, name, staging) + sigterm_and_restart(node_cut, "sigterm_{}_{}".format(task, staging), record) + if task == "merge": + _wait_until(lambda: merge_result_active(node_cut, name, target), timeout=180, describe=lambda: part_names(node_cut, name)) + assert payload_digest(node_cut, name) == expected_digest + else: + _wait_until(lambda: node_cut.query("SELECT is_done FROM system.mutations WHERE table = '{}'".format(name)).strip() == "1", + timeout=180) + assert part_names(node_cut, name, active_only=True) == [target] + assert payload_digest(node_cut, name) == expected_digest + + +# Fetches and moves onto the pool. A fetch is a byte fetch from `node_src` (local disk, so the sender offers no relink) +# into a replica on a CAS pool; a move is a TTL move from the local volume to the CAS volume of `cas_move`. Nothing +# paces either one except the proxy. +MOVE_POLICY = {"local": "cas_move", "s3": "cas_move_s3"} +# The cold volumes do not take a part at insert (`perform_ttl_move_on_insert` 0), so rows that are already expired +# still land on the local volume and only the move task takes them away. +MOVE_TTL_S = 3 +WIDE_SETTINGS = "min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, min_bytes_for_full_part_storage = 0" + + +def fetches_of(instance, name): + return int(instance.query("SELECT count() FROM system.replicated_fetches WHERE database = 'default' AND table = '{}'".format(name))) + + +def moves_of(instance, name): + return int(instance.query("SELECT count() FROM system.moves WHERE database = 'default' AND table = '{}'".format(name))) + + +def assert_cas_namespace(instance, staging, namespace, parts): + """The table's directory on the pool lists exactly `parts` (the part refs, in any state) and nothing else, so no + `tmp-fetch_` ref is left; `detached/` and `moving/` are empty and the pool has no dangling blob. A call with the + part present is the positive control of the listing.""" + disk = CUT_DISK[staging] + entries = list_disk_dir(instance, disk, namespace) + listed = sorted(set(entries) - {"detached", "moving", "format_version.txt"}) + assert listed == sorted(parts), ("the table namespace lists other entries than the parts", listed, entries) + for sub in ("detached", "moving"): + assert list_disk_dir(instance, disk, namespace + sub) == [], sub + assert fsck(instance, disk)["dangling"] == "0" + + +def start_paced_fetch(source, receiver, name, staging, size=CUT_BODY, rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S, min_left_s=5): + """A replica on the `staging` pool of `receiver` with fetches stopped, one large part inserted on `source`, the + proxy armed, fetches started and the fetch waited for at the gate. Returns the part name, the gate record and the + data digest.""" + ddl = ("CREATE TABLE {} (id UInt64, payload String CODEC(NONE)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{}', " + "'{{replica}}') ORDER BY id SETTINGS {}") + source.query(ddl.format(name, name, WIDE_SETTINGS)) + receiver.query(ddl.format(name, name, WIDE_SETTINGS + ", storage_policy = '{}'".format(CUT_POLICY[staging]))) + receiver.query("SYSTEM STOP FETCHES {}".format(name)) + insert_large_body(source, name, 1, size=size) + part = part_names(source, name, active_only=True)[0] + digest = payload_digest(source, name) + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX[staging], CUT_MIN_BODY, rate_bytes_per_s) + receiver.query("SYSTEM START FETCHES {}".format(name)) + _wait_until(lambda: fetches_of(receiver, name) == 1, timeout=60, describe=lambda: part_names(receiver, name)) + record = wait_body_gate(cluster.proxy_url, request_id, min_left_s=min_left_s) + assert fetches_of(receiver, name) == 1 + return part, record, digest + + +def assert_fetch_completes(source, receiver, name, staging, part, digest): + _wait_until(lambda: part_names(receiver, name, active_only=True) == [part], timeout=120, + describe=lambda: part_names(receiver, name)) + assert payload_digest(receiver, name) == digest + assert payload_digest(source, name) == digest + assert_cas_namespace(receiver, staging, table_namespace(receiver, name), [part]) + + +@pytest.mark.parametrize("staging", matrix(["s3"], ["local", "s3"])) +def test_fetch_without_a_stop_completes_paced(node_cut, node_src, staging): + """No-signal control of a fetch: the paced body is neither cut nor timed out and the part arrives whole.""" + name = "ctl_fetch_" + staging + part, record, digest = start_paced_fetch( + node_src, node_cut, name, staging, size=CONTROL_BODY, rate_bytes_per_s=CONTROL_RATE, min_left_s=CONTROL_MIN_LEFT_S) + # The part directory exists on the pool only as a ref after the publish, so at the gate the listing is non-empty + # but holds no part: the absence assertions of `assert_cas_namespace` prove "no published temporary part" only. + in_flight = list_disk_dir(node_cut, CUT_DISK[staging], table_namespace(node_cut, name)) + assert in_flight == ["format_version.txt"], in_flight + wait_complete(cluster.proxy_url, record, NO_SIGNAL_TIMEOUT_S) + assert_fetch_completes(node_src, node_cut, name, staging, part, digest) + + +@pytest.mark.parametrize("staging", ["local", "s3"]) +def test_stop_fetches_cuts_the_fetch_upload(node_cut, node_src, staging): + name = "stop_fetch_" + staging + part, record, digest = start_paced_fetch(node_src, node_cut, name, staging) + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP FETCHES {}".format(name)), rows=fetches_of) + # While the stop holds: no fetch starts and no part appears. + assert_quiet(node_cut, name, fetches_of) + assert part_names(node_cut, name) == [] + assert part_names(node_src, name, active_only=True) == [part] + assert payload_digest(node_src, name) == digest + namespace = table_namespace(node_cut, name) + assert_cas_namespace(node_cut, staging, namespace, []) + node_cut.query("SYSTEM START FETCHES {}".format(name)) + assert_fetch_completes(node_src, node_cut, name, staging, part, digest) + + +@pytest.mark.parametrize("staging", matrix(["local"], ["local", "s3"])) +def test_drop_table_cuts_the_fetch_upload(node_cut, node_src, staging): + name = "drop_fetch_" + staging + part, record, digest = start_paced_fetch(node_src, node_cut, name, staging) + namespace = table_namespace(node_cut, name) + timed_cut(node_cut, name, record, lambda: in_thread(lambda: node_cut.query("DROP TABLE {} SYNC".format(name))), rows=fetches_of, deadline_s=SYNC_CUT_DEADLINE_S) + assert_dropped_and_clean(node_cut, name, staging, namespace) + assert part_names(node_src, name, active_only=True) == [part] + assert payload_digest(node_src, name) == digest + + +def assert_dropped_and_clean(instance, name, staging, namespace): + """The table is gone, the pool has no dangling blob and the table's namespace on it is absent or empty.""" + assert instance.query("SELECT count() FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).strip() == "0" + assert fsck(instance, CUT_DISK[staging])["dangling"] == "0" + entries = list_disk_dir_or_absent(instance, CUT_DISK[staging], namespace) + record_measurement("drop_" + name + "_namespace_after", entries=entries) + assert entries in (None, []), "the dropped table's namespace still lists {}".format(entries) + + +def seed_ttl_move(instance, name, staging, size=CUT_BODY): + """A table whose one large part sits on the local volume with its move TTL expired and moves stopped, so that + `SYSTEM START MOVES` is what starts the move.""" + instance.query( + "CREATE TABLE {} (id UInt64, payload String CODEC(NONE), d DateTime) ENGINE = MergeTree ORDER BY id " + "TTL d + toIntervalSecond({}) TO VOLUME 'cold' SETTINGS storage_policy = '{}', {}".format( + name, MOVE_TTL_S, MOVE_POLICY[staging], WIDE_SETTINGS)) + instance.query("SYSTEM STOP MOVES {}".format(name)) + instance.query("INSERT INTO {} SELECT 1, randomString({}), now() - toIntervalHour(1)".format(name, size), + settings={"async_insert": 0}, timeout=120) + assert part_disks(instance, name) == ["default"] + + +def part_disks(instance, name): + return instance.query("SELECT disk_name FROM system.parts WHERE database = 'default' AND table = '{}' AND active".format(name)).split() + + +def start_paced_move(instance, name, staging, size=CUT_BODY, rate_bytes_per_s=DEFAULT_RATE_BYTES_PER_S, min_left_s=5): + """Returns the part name, the gate record and the data digest of a move that is going out at the gate.""" + seed_ttl_move(instance, name, staging, size=size) + part = part_names(instance, name, active_only=True)[0] + digest = payload_digest(instance, name) + request_id = arm_paced_body(cluster.proxy_url, CUT_PREFIX[staging], CUT_MIN_BODY, rate_bytes_per_s) + instance.query("SYSTEM START MOVES {}".format(name)) + _wait_until(lambda: moves_of(instance, name) == 1, timeout=60, describe=lambda: part_disks(instance, name)) + record = wait_body_gate(cluster.proxy_url, request_id, min_left_s=min_left_s) + assert moves_of(instance, name) == 1 + return part, record, digest + + +def assert_move_completes(instance, name, staging, part, digest): + _wait_until(lambda: part_disks(instance, name) == [CUT_DISK[staging]], timeout=120, describe=lambda: part_disks(instance, name)) + assert part_names(instance, name, active_only=True) == [part] + assert payload_digest(instance, name) == digest + assert_cas_namespace(instance, staging, table_namespace(instance, name), [part]) + + +@pytest.mark.parametrize("staging", matrix(["s3"], ["local", "s3"])) +def test_move_without_a_stop_completes_paced(node_cut, staging): + """No-signal control of a policy move: the paced body is neither cut nor timed out and the part is on the pool.""" + name = "ctl_move_" + staging + part, record, digest = start_paced_move( + node_cut, name, staging, size=CONTROL_BODY, rate_bytes_per_s=CONTROL_RATE, min_left_s=CONTROL_MIN_LEFT_S) + wait_complete(cluster.proxy_url, record, NO_SIGNAL_TIMEOUT_S) + assert_move_completes(node_cut, name, staging, part, digest) + + +@pytest.mark.parametrize("staging", ["local", "s3"]) +def test_stop_moves_cuts_the_move_upload(node_cut, staging): + name = "stop_move_" + staging + part, record, digest = start_paced_move(node_cut, name, staging) + timed_cut(node_cut, name, record, lambda: node_cut.query("SYSTEM STOP MOVES {}".format(name)), rows=moves_of) + assert_quiet(node_cut, name, moves_of) + assert part_disks(node_cut, name) == ["default"] + assert part_names(node_cut, name, active_only=True) == [part] + assert payload_digest(node_cut, name) == digest + assert_cas_namespace(node_cut, staging, table_namespace(node_cut, name), []) + # The TTL rule selects the part again once moves are allowed. + node_cut.query("SYSTEM START MOVES {}".format(name)) + assert_move_completes(node_cut, name, staging, part, digest) + + +@pytest.mark.parametrize("staging", matrix(["s3"], ["local", "s3"])) +def test_drop_table_cuts_the_move_upload(node_cut, staging): + name = "drop_move_" + staging + part, record, digest = start_paced_move(node_cut, name, staging) + namespace = table_namespace(node_cut, name) + timed_cut(node_cut, name, record, lambda: in_thread(lambda: node_cut.query("DROP TABLE {} SYNC".format(name))), rows=moves_of, deadline_s=SYNC_CUT_DEADLINE_S) + assert_dropped_and_clean(node_cut, name, staging, namespace) + + +def sigterm_and_restart(instance, case, record): + """`sigterm_orderly` while the claimed body `record` is going out, with no client connected. The pace is released + after the exit: the dead process closed the connection whatever the product did, so this checks that the body did + not complete, not how fast it was cut. The server is started again before the function returns.""" + t_proxy = now_mono_ms(cluster.proxy_url) + + def body_did_not_complete(exited): + release_pace(cluster.proxy_url, record) + wait_cut(cluster.proxy_url, record, CUT_DEADLINE_S, not_before_mono_ms=t_proxy) + ended = record_of(cluster.proxy_url, record) + record_measurement(case, exit_s=round(exited, 1), cut_s=round((ended["t_ended_mono_ms"] - t_proxy) / 1000.0, 1), + outcome=ended["outcome"]) + + try: + sigterm_orderly(instance, after_exit=body_did_not_complete) + finally: + instance.start_clickhouse() + + +@pytest.mark.parametrize("staging", matrix(["local"], ["local", "s3"])) +def test_sigterm_during_a_fetch_upload_is_orderly(node_cut, node_src, staging): + """The fetch is a queue entry, so it runs again after the restart and the part arrives whole.""" + name = "sigterm_fetch_" + staging + part, record, digest = start_paced_fetch(node_src, node_cut, name, staging) + sigterm_and_restart(node_cut, "sigterm_fetch_" + staging, record) + assert_fetch_completes(node_src, node_cut, name, staging, part, digest) + + +@pytest.mark.parametrize("staging", matrix(["s3"], ["local", "s3"])) +def test_sigterm_during_a_move_upload_is_orderly(node_cut, staging): + """The expired TTL selects the part again after the restart, and it ends on the pool.""" + name = "sigterm_move_" + staging + part, record, digest = start_paced_move(node_cut, name, staging) + sigterm_and_restart(node_cut, "sigterm_move_" + staging, record) + assert_move_completes(node_cut, name, staging, part, digest) + + +def record_log_anomalies(instance, case, first_line): + """Records the distinct `` and `` messages and every `LOGICAL_ERROR` that `instance` logged since + `first_line`, for the reader of a run: a passed test can still log them.""" + lines = instance.exec_in_container( + ["bash", "-c", "tail -n +{} /var/log/clickhouse-server/clickhouse-server.log | grep -a '\\|\\|LOGICAL_ERROR' || true".format(first_line)]) + distinct = {} + for line in lines.splitlines(): + # Drop the timestamp, thread and query id: what is left is the logger and the message. + key = re.sub(r"^\S+ \S+ \[ \d+ \] \{[^}]*\} ", "", line)[:300] + distinct[key] = distinct.get(key, 0) + 1 + if distinct: + record_measurement("log_anomalies:" + case, messages=sorted(distinct.items(), key=lambda kv: -kv[1])[:20]) + From b5edc12cfc0a13aa94bbe5e302c1d85f17812370 Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Sun, 29 Nov 2026 21:59:08 +0100 Subject: [PATCH 46/47] docs(cas): stopping the upload of background work `SYSTEM STOP MERGES`, `STOP FETCHES`, `STOP MOVES`, `KILL MUTATION`, `DROP TABLE`, `DETACH TABLE` and a server shutdown now end the upload of a merge, a mutation, a fetched part and a moved part. The troubleshooting page lists what stops, what does not, what a stop leaves behind and what an operator sees in the logs and system tables. Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Fable 5.2 --- docs/en/antalya/cas/configuration.md | 3 +- .../antalya/cas/operations/troubleshooting.md | 51 +++++++++++++++++-- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/docs/en/antalya/cas/configuration.md b/docs/en/antalya/cas/configuration.md index aa5dfec200df3..c4faa4bf49ffc 100644 --- a/docs/en/antalya/cas/configuration.md +++ b/docs/en/antalya/cas/configuration.md @@ -477,7 +477,8 @@ are a token request with `http_client = gcp_oauth` and the bucket region lookup request yet. After an upgrade, a server that already has one of these limits set starts to pace `CAS` uploads. A low server-wide -limit makes merges and mutations hold their queue slots longer, and they are not stopped while they upload. +limit makes merges and mutations hold their queue slots longer while they upload. A stop ends such an upload; see +[stopping `CAS` work](/antalya/cas/operations/troubleshooting#stopping-cas-work). ## `SYSTEM CAS` commands {#system-commands} diff --git a/docs/en/antalya/cas/operations/troubleshooting.md b/docs/en/antalya/cas/operations/troubleshooting.md index d1aeb0a23b316..15faf620d5a17 100644 --- a/docs/en/antalya/cas/operations/troubleshooting.md +++ b/docs/en/antalya/cas/operations/troubleshooting.md @@ -167,16 +167,59 @@ A stop also ends the upload of a part that is being built: - The server aborts the incomplete multipart upload of a cut body. If the abort fails, the upload stays until the bucket's lifecycle rule removes it. - A stopped upload may log an error line for each cancelled request of a multipart upload. -- The upload of a merge, a mutation, a background replication fetch or a background move is not stopped. Server - shutdown waits for it. A fetch or a move that a query runs itself (`ALTER TABLE ... FETCH PARTITION`, - `ALTER TABLE ... MOVE PARTITION`) is stopped with that query. +- A fetch or a move that a query runs itself (`ALTER TABLE ... FETCH PARTITION`, `ALTER TABLE ... MOVE PARTITION`) + is stopped with that query. + +The upload of the result of a merge or a mutation, of a fetched part and of a moved part is stopped too. The stop +reaches the body being sent at its next check. On a test stand the upload stopped within seconds. That is a measured +time, not a bound. + +| What stops the upload | What does not | +|---|---| +| `SYSTEM STOP MERGES`, `SYSTEM STOP FETCHES`, `SYSTEM STOP MOVES` for the table | `KILL QUERY` on a foreground `OPTIMIZE`: the merge runs under its own task. `OPTIMIZE ... DRY RUN PARTS` runs inside the query and stops with it | +| `KILL MUTATION` | A shutdown while a client connection is still open: it waits for the connection first | +| `DROP TABLE`, `DETACH TABLE` | Another replica that is already uploading the same result | +| Server shutdown | `SYSTEM STOP MERGES ... ON VOLUME`: it changes selection and does not cancel a running merge | +| | A server-side copy: no body is streamed | + +What you see after such a stop: + +- A cancelled merge or mutation is expected after a stop, not a failure. A `MergeTree` table usually logs an error + line "Cancelled merging parts" or "Cancelled mutating parts" with code `ABORTED`. A cut that lands at the final + commit can log it at a lower level. A `ReplicatedMergeTree` table logs the cancellation at information level and + leaves `last_exception` of the queue entry as it was. +- A cut with local staging may leave no failed row in `system.part_log`. +- The source parts of a merge or mutation stay active, as long as the table exists. `DROP TABLE` removes its data. +- After `SYSTEM STOP MERGES`, `SYSTEM STOP FETCHES` or `SYSTEM STOP MOVES`, work that is still eligible can be + selected again after the matching `SYSTEM START`. A `MergeTree` table selects afresh, so an insert made while + merges were stopped can change which parts are merged. After a restart, the work is scheduled again. This holds while the table and the work + still exist: a killed mutation is gone. +- A running fetch has a row in `system.replicated_fetches`, also a fetch by relink. A running move has a row in + `system.moves`. + +A stop can leave: + +- The objects of a cancelled merge or mutation whose result part goes to a plain S3 disk of the same storage policy. +- The objects that a stopped byte fetch onto a plain S3 disk had already written. +- A `tmp-fetch_` directory or a `moving/` directory, when the stop coincides with a failed request. A later byte fetch of the same part removes + a `tmp-fetch_` directory only when it uses the same disk and the same temporary path; a retry can choose another disk. The startup + cleanup does not look under `detached/`: there, `ALTER TABLE ... DROP DETACHED PART` removes a named leftover, and it needs the + setting `allow_drop_detached`. A `moving/` directory is + removed when the table is loaded again, if removal of stale moving parts is enabled (the default). + +Known limits: + +- A `SYSTEM STOP` followed by a `SYSTEM START` in quick succession can be missed by an upload that is running. +- Other work can still hold a shutdown, for example a fetch blocked in a read that does not return. +- A running step of an `EXPORT PART` is not cancelled by a shutdown. It is waited for and can hold the shutdown. +- Cleanup after a cut retries its requests. A shutdown with the object store unreachable waits for those retries. No stop interrupts: - Any other request already in flight. - The first attempt of a read, and a read that only waits for another reader's result. - A recovery walk that is already running. On S3 the walk of a stopped query still fails at the first error answer. A walk that looks for a record after its last one ends with such an answer, the `404` for that key; a walk that ends at the table's final removal record looks for none. The failed read is not retried. When the stop cuts short the read that follows a refused write of the walk, the walk ends with a retry-later `NETWORK_ERROR` (210) instead of starting again. -- Cleanup that the operation owes after a send, and merges. +- Cleanup that the operation owes after a send. If the stop lands after a metadata write whose outcome is unknown, the error is the retry-later `NETWORK_ERROR` (210), and its message says the write is unresolved or its outcome is unknown. Check the table before you repeat the write. From 8369d42aab3fa7d3fb66522903bea6033cdf737a Mon Sep 17 00:00:00 2001 From: Mikhail Filimonov Date: Mon, 30 Nov 2026 20:05:49 +0100 Subject: [PATCH 47/47] fix(cas): the leader of a shared ref-log flush ignores its query's cancellation The S3 client replaces a failed request's result with the thread's cancellation cause. Inside `OwnerScope::shared` nothing recognizes that cause, so CAS read its code as the store's answer: a `READONLY` cause made a landed log PUT `Refused` with no settling read, the next append reused the transaction id and the lane went `Faulted`; a `BAD_ARGUMENTS` cause left the lane wedged; a stored `NoSuchKey` or precondition error was read as absence or as a conflict. The leader now holds a `ThreadStatus::QueryCancellationBlocker` next to the scope for its whole tenure, so the store's real answer decides the work done for several callers. The leader's own cancellation takes effect when the flush ends. Tests run inside the real flush: a lost reply under a `READONLY` and a `BAD_ARGUMENTS` cause, a failed read of a present key, a real `412` and a real miss through the native backend (each with a control that shows the wrong answer without the blocker), a leader that leaves by an exception, and a leader of a cancelled background operation. Review: https://github.com/Altinity/ClickHouse/pull/2970#pullrequestreview-6114600123 Signed-off-by: Mikhail Filimonov Co-Authored-By: Claude Sonnet 5.5 --- .../ContentAddressed/Backend/CasOwner.h | 19 +- .../ContentAddressed/Pool/CasRefLedger.cpp | 11 +- src/Disks/tests/cas_killable_query.h | 2 +- .../tests/gtest_cas_ref_chunked_flush.cpp | 645 +++++++++++++++++- 4 files changed, 661 insertions(+), 16 deletions(-) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h index 3b042b958b439..70ac37dcd5726 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h @@ -59,13 +59,15 @@ namespace DB::Cas /// except that a vetoed resend with refreshed credentials ends as a retry-later `NETWORK_ERROR` carrying the /// refusal. A scan head throws the query's verdict. /// - A killed query's conditional write that loses a race can end as `ABORTED` "conflict": the S3 client replaces the -/// 412 with the query's exception, and the settling read shows the other writer's object. +/// 412 with the query's exception, and the settling read shows the other writer's object. Where the thread's +/// cancellation is masked (`shared` held with a `ThreadStatus::QueryCancellationBlocker`), the 412 stays a conflict. /// - An unresolved sent write keeps its "outcome unknown" exit; a later owner verdict does not overwrite it. /// - `OwnerScope::owed` removes the checks before work and the query's cut of a pause: the pause runs to its end, and /// the next attempt is sent unless the fence, the lease or a deadline refuses it after the pause. A failure after a /// stop is still not retried, and a background owner's verdict still replaces it. `OwnerScope::shared` removes the -/// owner. Neither hides a query from the S3 client, which replaces a failed request's answer with the query's -/// verdict; a bulk delete that succeeds with an error for one key keeps that key's error. +/// owner. `owed` does not hide a query from the S3 client, which replaces a failed request's answer with the query's +/// verdict; a bulk delete that succeeds with an error for one key keeps that key's error. Where the thread's +/// cancellation is masked, such as `owed` nested under `shared` held with the blocker, nothing is replaced. /// - Code above the engine may still do follow-up work its own counts bound, such as another recovery walk. With a /// lease loss or a credential refusal at the same time, the error can be the less specific of the two. @@ -78,7 +80,8 @@ std::exception_ptr ownerStopRequested(); /// True when the thread's query, not a background owner, asked to stop. False inside `shared`. /// The S3 client throws the query's verdict in place of a failed request's answer, but not of one key's error in a -/// bulk delete that succeeded, and it cannot see a background owner. +/// bulk delete that succeeded, and it cannot see a background owner. It sees no query where the thread's cancellation +/// is masked by a `ThreadStatus::QueryCancellationBlocker`. bool queryStopRequested(); /// Rethrows the verdict of the background owners in scope, except inside `owed` or `shared`. Ignores the query. @@ -96,7 +99,8 @@ std::exception_ptr backgroundStopRequested(); /// True when `e` is the query's stored cancellation cause, the one verdict rethrown as the same object to every thread /// the query stops; false inside `shared`. A kill or timeout without a stored cause and every background owner's verdict /// are built anew on each check, so they never match. Such a cause is neither a store answer nor a local fault, -/// whatever its code or type. +/// whatever its code or type. The cause is recognized only while the thread's cancellation check is enabled: under a +/// `QueryCancellationBlocker` the check does not throw and the answer is false. bool isQueryStoredCause(const std::exception_ptr & e); /// Adds `message` to `e`, the exception being handled, unless `e` is the query's stored cause, whatever the scope: @@ -136,8 +140,9 @@ class OwnerScope static OwnerScope background(std::function throw_if_stopped); /// Work owed to a possibly-sent write, a failed commit or a claimed resource: no throwing check. static OwnerScope owed(); - /// Work for several callers: CAS owner checks see no owner. The S3 client still replaces a failed answer with the - /// exception of the thread's query. + /// Work for several callers: CAS owner checks see no owner. The caller must also hold a + /// `ThreadStatus::QueryCancellationBlocker` for the scope's lifetime. Without it the S3 client replaces a failed + /// answer with the thread's query exception, and nothing inside this scope recognizes that as no store answer. static OwnerScope shared(); /// This thread's background owner check, to keep calling inside a later `shared` scope. Valid only while the diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index b7b9374a85725..074fa3c0ce1cc 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -1830,8 +1831,11 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( bool unresolved_sent = false; try { - /// Owed so that CAS's own checks do not cut a started walk. On S3 a stopped query's walk still - /// fails at its first error answer, the `404` that ends every walk included. + /// Owed so that CAS's own checks do not cut a started walk. On S3 a stopped query's walk fails at + /// its first failed request, because the client replaces that failure with the query's exception + /// (the `404` that ends an ordinary walk is such a failure). A walk that ends on a successful read, + /// or whose failed write is settled by a successful read, is not affected. Nothing is replaced + /// while the thread's cancellation is masked. const auto owed = Cas::OwnerScope::owed(); walked = runRecoveryWalkOnce( ns, rt, admitted_generation, live, retained_attempt, hole_detail, cancelled, unresolved_sent, token); @@ -2650,6 +2654,9 @@ void CasRefLedger::runRefQueueLeader(const RootNamespace & ns, const std::shared const std::function owner_check = Cas::OwnerScope::effectiveCheck(); /// One caller's owner must not decide work done for several callers. const auto shared = Cas::OwnerScope::shared(); + /// The S3 client replaces a failed request's result with the thread's cancellation cause, which says nothing + /// about the store. Work done for several callers must be judged by the store's answer. + const ThreadStatus::QueryCancellationBlocker no_query_cancellation; /// Fairness baton pass: serve flushes only until the caller's OWN item is done, then hand off to a /// woken waiter. diff --git a/src/Disks/tests/cas_killable_query.h b/src/Disks/tests/cas_killable_query.h index a4b3157ce5ec1..cd7029261326a 100644 --- a/src/Disks/tests/cas_killable_query.h +++ b/src/Disks/tests/cas_killable_query.h @@ -154,7 +154,7 @@ auto checkedUnless(Call && call, Succeeded && succeeded) /// Forwards to `inner` and, as the S3 client does after every unsuccessful response, checks the current /// thread's query on each miss, conflict or failure before answering. Success is never checked. The /// sentinel probe stays the base default, which goes through the decorated `head` and `read`. -class CasClientLikeBackend final : public Backend +class CasClientLikeBackend : public Backend { public: explicit CasClientLikeBackend(BackendPtr inner_) : inner(std::move(inner_)) {} diff --git a/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp b/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp index 34295f4079788..1a965e9fc53cb 100644 --- a/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp +++ b/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp @@ -10,9 +10,13 @@ #include #include #include +#include +#include #include #include #include +#include +#include #include #include #include @@ -22,6 +26,8 @@ #include #include +#include +#include #include @@ -32,12 +38,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include namespace DB::ErrorCodes @@ -47,6 +55,8 @@ extern const int CORRUPTED_DATA; extern const int NETWORK_ERROR; extern const int LOGICAL_ERROR; extern const int ABORTED; +extern const int READONLY; +extern const int BAD_ARGUMENTS; } namespace ProfileEvents @@ -225,11 +235,12 @@ void waitEntered(const std::shared_ptr & sync) sync->cv.wait_for(lk, std::chrono::seconds(10), [&] { return sync->entered; }); } -void waitPendingAtLeast(const PoolPtr & store, const RootNamespace & ns, size_t n) +bool waitPendingAtLeast(const PoolPtr & store, const RootNamespace & ns, size_t n) { const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); while (store->refQueuePendingForTest(ns) < n && std::chrono::steady_clock::now() < deadline) std::this_thread::yield(); + return store->refQueuePendingForTest(ns) >= n; } /// Asserts `err` is non-null and carries EXACTLY `expected_code` -- distinguishes the new counts-only @@ -1170,6 +1181,10 @@ class LeaderKillLogPutBackend final : public DB::Cas::tests::CountingBackend std::function before_answer; std::atomic armed{false}; std::atomic fired{false}; + /// Runs right after the armed create landed, before its reply is lost or returned. + std::function after_landed; + /// The armed create lands, and its reply is lost. + bool lose_reply = false; std::expected write(const String & key, const String & bytes, const std::optional & expected_value, @@ -1178,6 +1193,10 @@ class LeaderKillLogPutBackend final : public DB::Cas::tests::CountingBackend if (!expected_value && key.starts_with(log_prefix) && armed.exchange(false)) { fired = true; + if (lose_reply) + injectAmbiguousLandedWrite(key); + if (after_landed) + onWriteCommitted(key, after_landed); if (before_answer) before_answer(); } @@ -1185,9 +1204,52 @@ class LeaderKillLogPutBackend final : public DB::Cas::tests::CountingBackend } }; +/// Records the first exception of a ref-log create that leaves the client-like layer, which is what the request engine +/// sees. +class RecordingClientLikeBackend final : public CasClientLikeBackend +{ +public: + RecordingClientLikeBackend(std::shared_ptr faults_) + : CasClientLikeBackend(faults_), faults(std::move(faults_)) + { + } + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + try + { + return CasClientLikeBackend::write(key, bytes, expected_value, access); + } + catch (...) + { + if (key.starts_with(faults->log_prefix)) + { + std::lock_guard lock(mutex); + if (!first_log_write_failure) + first_log_write_failure = std::current_exception(); + } + throw; + } + } + + std::exception_ptr firstLogWriteFailure() const + { + std::lock_guard lock(mutex); + return first_log_write_failure; + } + +private: + std::shared_ptr faults; + mutable std::mutex mutex; + std::exception_ptr first_log_write_failure; +}; + struct KilledLeaderFixture { std::shared_ptr faults = std::make_shared(); + std::shared_ptr client = std::make_shared(faults); PoolPtr store; std::shared_ptr clock; RootNamespace ns; @@ -1195,7 +1257,7 @@ struct KilledLeaderFixture explicit KilledLeaderFixture(const String & ns_suffix) : ns(String("srv1/") + ns_suffix) { - store = openPoolWith(std::make_shared(faults), PoolConfig{}); + store = openPoolWith(client, PoolConfig{}); clock = VirtualRetryClock::installOn(store); publishEmptyPart(store, ns, "seed"); faults->log_prefix = store->layout().namespaceStreamPrefix(DB::Cas::tests::fixture::fixtureLife(ns)) + "_log/"; @@ -1220,6 +1282,22 @@ int exceptionCode(const std::exception_ptr & e) } } +bool isTransportTimeout(const std::exception_ptr & e) +{ + try + { + std::rethrow_exception(e); + } + catch (const Poco::TimeoutException &) + { + return true; + } + catch (...) + { + return false; + } +} + /// The leader's side of a killed-leader case, run on a raw thread with its own `ThreadStatus` and a /// query registered in the process list. `body` gets the query and returns the append's result. struct LeaderRun @@ -1255,18 +1333,79 @@ struct KilledLeaderOutcome LeaderRun leader; AppendResult neighbor; int neighbor_builds = 0; + /// The neighbor's item was queued before the blocked leader was released to carve. + bool neighbor_queued_before_release = false; +}; + +/// What the leader thread does around its append: `before_answer` runs before the chunk's create is answered, +/// `after_landed` right after a lost-reply create landed, and `finish` after the append returned or threw. +struct LeaderArm +{ + std::function before_answer; + std::function after_landed; + std::function finish; +}; + +/// What a direct cancellation check on the calling thread does. +struct CancellationProbe +{ + bool threw = false; + bool same_cause = false; + int code = 0; }; -KilledLeaderOutcome runKilledLeaderChunk(KilledLeaderFixture & fx) +CancellationProbe probeCancellation(const std::exception_ptr & cause) +{ + CancellationProbe probe; + try + { + DB::CurrentThread::checkIfNotCancelled(); + } + catch (...) + { + const std::exception_ptr thrown = std::current_exception(); + probe.threw = true; + probe.same_cause = thrown == cause; + probe.code = exceptionCode(thrown); + } + return probe; +} + +enum class KillAt : uint8_t { BeforeAnswer, AfterLanded }; + +/// Kills the leader's query at `at`; with `probe`, checks the cancellation again once the append ended. +LeaderArm killLeaderWith( + CasKillableQuery & query, std::exception_ptr cause = nullptr, KillAt at = KillAt::BeforeAnswer, CancellationProbe * probe = nullptr) +{ + LeaderArm arm; + auto kill = [&query, cause] { query.kill(cause); }; + (at == KillAt::BeforeAnswer ? arm.before_answer : arm.after_landed) = kill; + if (probe) + arm.finish = [probe, cause] { *probe = probeCancellation(cause); }; + return arm; +} + +std::exception_ptr storedCauseWithCode(int code) +{ + return std::make_exception_ptr(DB::Exception(code, "the query's stored cause")); +} + +KilledLeaderOutcome runKilledLeaderChunk( + KilledLeaderFixture & fx, + const std::function & arm = [](CasKillableQuery & query) { return killLeaderWith(query); }, + bool lose_reply = false) { auto sync = std::make_shared(); armPreCarveBlock(fx.store, fx.ns, sync, 2); auto neighbor_builds = std::make_shared>(0); std::thread leader_thread; - std::future leader = launchQueryLeader(leader_thread, [&fx](CasKillableQuery & query) + std::future leader = launchQueryLeader(leader_thread, [&fx, &arm, lose_reply](CasKillableQuery & query) { - fx.faults->before_answer = [&query] { query.kill(); }; + const LeaderArm leader_arm = arm(query); + fx.faults->before_answer = leader_arm.before_answer; + fx.faults->after_landed = leader_arm.after_landed; + fx.faults->lose_reply = lose_reply; fx.faults->armed = true; AppendResult r; try @@ -1279,15 +1418,18 @@ KilledLeaderOutcome runKilledLeaderChunk(KilledLeaderFixture & fx) { r.err = std::current_exception(); } + if (leader_arm.finish) + leader_arm.finish(); return r; }); waitEntered(sync); AppendCaller neighbor = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_neighbor"), addRemovePrecommitPairs("item_neighbor", 1, 910000002), neighbor_builds); - waitPendingAtLeast(fx.store, fx.ns, 2); + const bool neighbor_queued = waitPendingAtLeast(fx.store, fx.ns, 2); sync->cv.notify_all(); KilledLeaderOutcome out; + out.neighbor_queued_before_release = neighbor_queued; EXPECT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the killed leader must not hang"; EXPECT_EQ(neighbor.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the neighbor must not hang"; out.leader = leader.get(); @@ -1295,6 +1437,8 @@ KilledLeaderOutcome runKilledLeaderChunk(KilledLeaderFixture & fx) leader_thread.join(); neighbor.t.join(); fx.faults->before_answer = {}; + fx.faults->after_landed = {}; + fx.faults->lose_reply = false; fx.store->setRefPreCarveHookForTest(nullptr); out.neighbor_builds = neighbor_builds->load(); return out; @@ -1324,6 +1468,495 @@ TEST(CASRefWriterChunkedFlush, KilledLeaderOnHealthyStoreCommitsWithNeighbor) << "the chunk is durable exactly once"; } +namespace +{ + +size_t countRequests(const DB::Cas::tests::CountingBackend & backend, DB::Cas::tests::JournalVerb verb, const String & key) +{ + const auto journal = backend.journal(); + return static_cast(std::count_if(journal.begin(), journal.end(), [&](const DB::Cas::tests::JournalEntry & entry) + { + return entry.verb == verb && entry.keys.size() == 1 && entry.keys.front() == key; + })); +} + +/// The leader's query is killed with a stored cause right after the chunk's create landed and its reply was lost. The +/// store's answer, not the cause, decides: one settling read finds the chunk, both callers commit, and the lane is not +/// wedged, so the next distinct mutation takes the next id. +void expectLostReplyOfKilledLeaderIsSettled(int cause_code, const String & ns_suffix) +{ + KilledLeaderFixture fx(ns_suffix); + const std::exception_ptr cause = storedCauseWithCode(cause_code); + CancellationProbe probe; + + const KilledLeaderOutcome out = runKilledLeaderChunk( + fx, [&](CasKillableQuery & query) { return killLeaderWith(query, cause, KillAt::AfterLanded, &probe); }, true); + + ASSERT_TRUE(fx.faults->fired) << "the kill never ran after the chunk's create"; + EXPECT_TRUE(probe.threw) << "the kill took effect: the query is cancelled again once the leader returned"; + EXPECT_TRUE(probe.same_cause) << "the check throws the stored cause itself, code " << probe.code; + /// Fatal: a failed append leaves a zero id, which the key derivation below rejects. + ASSERT_EQ(exceptionCode(out.leader.result.err), 0) << "the killed leader's item is acknowledged"; + ASSERT_EQ(exceptionCode(out.neighbor.err), 0) << "the neighbor's item is acknowledged"; + EXPECT_EQ(out.leader.result.id, out.neighbor.id) << "both items were in one chunk"; + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); + + const String log_key = fx.store->layout().refLogKey(DB::Cas::tests::fixture::fixtureLife(fx.ns), out.neighbor.id); + EXPECT_EQ(countRequests(*fx.faults, DB::Cas::tests::JournalVerb::Write, log_key), 1u) << "the chunk is sent once"; + EXPECT_EQ(countRequests(*fx.faults, DB::Cas::tests::JournalVerb::Read, log_key), 1u) << "one settling read"; + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + EXPECT_EQ(std::count_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == out.neighbor.id; }), 1); + + /// Synchronous on the test thread: a failed assertion cannot leave a blocked thread to join. + AppendResult after; + try + { + after.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_next"), + [](const RefTableState &) { return addRemovePrecommitPairs("item_next", 1, 910000003); }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + after.err = std::current_exception(); + } + EXPECT_EQ(exceptionCode(after.err), 0) << "a distinct mutation appends after the settled chunk"; + EXPECT_EQ(after.id.writer_epoch, out.neighbor.id.writer_epoch); + EXPECT_EQ(after.id.ref_sequence, out.neighbor.id.ref_sequence + 1) << "the settled chunk's id is not reused"; + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); +} + +} + +/// The S3 client replaces a failed request's answer with the query's stored cause. A `READONLY` cause read as a store +/// refusal would declare the landed chunk's id free. +TEST(CASRefWriterChunkedFlush, KilledLeaderLostReplyWithReadonlyCauseIsSettledByRead) +{ + expectLostReplyOfKilledLeaderIsSettled(DB::ErrorCodes::READONLY, "killed_leader_lost_reply_readonly"); +} + +/// A `BAD_ARGUMENTS` cause read as a local fault would end the flush with no settling read and leave the lane wedged. +TEST(CASRefWriterChunkedFlush, KilledLeaderLostReplyWithBadArgumentsCauseIsSettledByRead) +{ + expectLostReplyOfKilledLeaderIsSettled(DB::ErrorCodes::BAD_ARGUMENTS, "killed_leader_lost_reply_bad_arguments"); +} + +/// After the leader's flush ended, the query's own cancellation is visible again on its thread: a direct check throws +/// the stored cause itself. +TEST(CASRefWriterChunkedFlush, KilledLeaderQueryIsCancelledAgainAfterAFlush) +{ + KilledLeaderFixture fx("killed_leader_visible_after_flush"); + const std::exception_ptr cause = storedCauseWithCode(DB::ErrorCodes::READONLY); + CancellationProbe probe; + + const KilledLeaderOutcome out = runKilledLeaderChunk( + fx, [&](CasKillableQuery & query) { return killLeaderWith(query, cause, KillAt::BeforeAnswer, &probe); }); + + ASSERT_TRUE(fx.faults->fired); + EXPECT_EQ(exceptionCode(out.leader.result.err), 0); + EXPECT_TRUE(probe.threw) << "the killed query is cancelled again once the leader returned"; + EXPECT_TRUE(probe.same_cause) << "the check throws the stored cause itself, code " << probe.code; +} + +/// An exception that leaves the leader's flush ends its tenure with the cancellation visible again: the query's +/// check throws the stored cause itself. The exception is the flush's own, not the cause, the check is masked while +/// the flush runs, and a queued neighbor takes the baton and commits. +TEST(CASRefWriterChunkedFlush, KilledLeaderQueryIsCancelledAgainAfterAThrowingFlush) +{ + KilledLeaderFixture fx("killed_leader_visible_after_throwing_flush"); + const std::exception_ptr cause = storedCauseWithCode(DB::ErrorCodes::READONLY); + const String sentinel = "sentinel thrown from the carve plan"; + std::atomic thrown{false}; + bool masked_in_flush = false; + CancellationProbe probe; + + const KilledLeaderOutcome out = runKilledLeaderChunk(fx, [&](CasKillableQuery & query) + { + fx.store->setCarveHookForTest([&](CasRefLedger::CarvePhaseForTest phase) + { + if (phase != CasRefLedger::CarvePhaseForTest::PlanSeenRefs || thrown.exchange(true)) + return; + query.kill(cause); + masked_in_flush = !probeCancellation(cause).threw; + throw DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "{}", sentinel); + }); + LeaderArm arm; + arm.finish = [&] { probe = probeCancellation(cause); }; + return arm; + }); + fx.store->setCarveHookForTest(nullptr); + + ASSERT_TRUE(thrown) << "the exception never left the carve plan"; + ASSERT_TRUE(out.neighbor_queued_before_release) << "the neighbor's item was not queued before the leader's flush began"; + EXPECT_TRUE(masked_in_flush) << "a killed leader's cancellation is masked while its flush runs"; + ASSERT_EQ(exceptionCode(out.leader.result.err), DB::ErrorCodes::CORRUPTED_DATA) << "the leader gets the flush's own exception"; + try + { + std::rethrow_exception(out.leader.result.err); + } + catch (const DB::Exception & e) + { + EXPECT_NE(String(e.message()).find(sentinel), String::npos) << e.message(); + } + EXPECT_TRUE(probe.threw) << "the killed query is cancelled again once the leader returned"; + EXPECT_TRUE(probe.same_cause) << "the check throws the stored cause itself, code " << probe.code; + EXPECT_TRUE(out.leader.group_restored); + + ASSERT_EQ(exceptionCode(out.neighbor.err), 0) << "the neighbor takes the baton and commits"; + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + EXPECT_EQ(std::count_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == out.neighbor.id; }), 1); + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); +} + +/// A leader running a background operation whose group has a throwing cancellation predicate (a cancelled merge) is +/// not a query. A lost reply inside its flush is still settled by a read, and the other callers' items are acknowledged. +/// The transport timeout, not the operation's `ABORTED`, is what leaves the client-like layer. +TEST(CASRefWriterChunkedFlush, LeaderOfACancelledBackgroundOperationSettlesALostReplyByRead) +{ + KilledLeaderFixture fx("cancelled_background_leader_lost_reply"); + auto cancelled = std::make_shared>(false); + CancellationProbe probe; + + const KilledLeaderOutcome out = runKilledLeaderChunk(fx, [&](CasKillableQuery & query) + { + auto group = DB::ThreadGroup::createForMergeMutate(getContext().context); + group->setQueryCancellationPredicates( + [cancelled] { return cancelled->load(); }, + [cancelled] + { + if (cancelled->load()) + throw DB::Exception(DB::ErrorCodes::ABORTED, "Cancelled merging parts"); + }); + DB::CurrentThread::detachFromGroupIfNotDetached(); + DB::CurrentThread::attachToGroup(group); + LeaderArm arm; + arm.before_answer = [cancelled] { *cancelled = true; }; + arm.finish = [&query, &probe] + { + /// Still attached to the operation's group: its predicate is live. + probe = probeCancellation(nullptr); + DB::CurrentThread::detachFromGroupIfNotDetached(); + query.attachCurrentThread(); + }; + return arm; + }, true); + + ASSERT_TRUE(fx.faults->fired); + EXPECT_TRUE(probe.threw) << "the operation's cancellation predicate is live once the leader returned"; + EXPECT_EQ(probe.code, DB::ErrorCodes::ABORTED); + const std::exception_ptr leaving_client = fx.client->firstLogWriteFailure(); + ASSERT_TRUE(leaving_client != nullptr); + EXPECT_TRUE(isTransportTimeout(leaving_client)) << "the lost reply leaves the client-like layer as the transport timeout"; + ASSERT_EQ(exceptionCode(out.leader.result.err), 0) << "the leader's item is acknowledged"; + ASSERT_EQ(exceptionCode(out.neighbor.err), 0) << "the neighbor's item is acknowledged"; + EXPECT_EQ(out.leader.result.id, out.neighbor.id); + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); + const String log_key = fx.store->layout().refLogKey(DB::Cas::tests::fixture::fixtureLife(fx.ns), out.neighbor.id); + EXPECT_EQ(countRequests(*fx.faults, DB::Cas::tests::JournalVerb::Write, log_key), 1u); + EXPECT_EQ(countRequests(*fx.faults, DB::Cas::tests::JournalVerb::Read, log_key), 1u) << "one settling read"; +} + +#if USE_AWS_S3 + +namespace +{ + +/// Where a request classified by the native object-storage backend runs after its query was killed with a stored +/// cause. `InsideLeaderFlush` is the production case. `SharedWithoutBlocker` is the control: the same scope the leader +/// holds, minus the cancellation blocker, which shows that `OwnerScope::shared` alone does not keep the S3 client from +/// substituting the query's cause. +enum class KilledQueryPlace : uint8_t { InsideLeaderFlush, SharedWithoutBlocker }; + +/// Kills a query with `cause` and runs `scenario` on its thread in `place`. +template +void runKilledQueryScenario(KilledQueryPlace place, const std::exception_ptr & cause, Scenario && scenario) +{ + if (place == KilledQueryPlace::SharedWithoutBlocker) + { + DB::Cas::tests::onKillableQueryThread([&](CasKillableQuery & query) + { + const auto shared = DB::Cas::OwnerScope::shared(); + query.kill(cause); + scenario(); + }); + return; + } + + KilledLeaderFixture fx("killed_leader_native_classifier"); + std::atomic ran{false}; + int append_code = -2; + DB::Cas::tests::onKillableQueryThread([&](CasKillableQuery & query) + { + fx.store->setRefPreCarveHookForTest([&] + { + if (ran.exchange(true)) + return; + query.kill(cause); + scenario(); + }); + try + { + fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [](const RefTableState &) { return addRemovePrecommitPairs("item_leader", 1, 910000001); }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + append_code = 0; + } + catch (...) + { + append_code = exceptionCode(std::current_exception()); + } + }); + fx.store->setRefPreCarveHookForTest(nullptr); + EXPECT_TRUE(ran) << "the scenario never ran inside the leader's flush"; + EXPECT_EQ(append_code, 0) << "the leader's own append commits"; +} + +/// A local object storage whose reads and conditional writes fail the way the S3 client fails a request: a failure +/// first asks the thread's query, so the query's cause replaces the failure. +class ClientLikeNativeStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + mutable std::atomic fail_next{false}; + mutable std::atomic miss_next{false}; + mutable std::atomic reads{0}; + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, + const DB::ReadSettings & read_settings, + size_t max_size_bytes, + std::optional read_hint) const override + { + ++reads; + if (fail_next.exchange(false)) + { + DB::CurrentThread::checkIfNotCancelled(); + throw Poco::TimeoutException("ClientLikeNativeStorage: the read timed out"); + } + if (miss_next.exchange(false)) + { + DB::CurrentThread::checkIfNotCancelled(); + throw DB::S3Exception("the store answered NoSuchKey for " + object.remote_path, Aws::S3::S3Errors::NO_SUCH_KEY, "NoSuchKey"); + } + return DB::LocalObjectStorage::readSmallObjectAndGetObjectMetadata(object, read_settings, max_size_bytes, read_hint); + } +}; + +/// Finalizes by asking the thread's query, as the S3 client does, then failing with the store's own `412`. +class PreconditionFailedNativeBuffer final : public DB::WriteBufferFromFileBase +{ +public: + PreconditionFailedNativeBuffer() : DB::WriteBufferFromFileBase(DB::DBMS_DEFAULT_BUFFER_SIZE, nullptr, 0) {} + + void sync() override { next(); } + std::string getFileName() const override { return "precondition-failed-native-buffer"; } + +private: + void nextImpl() override {} + + void finalizeImpl() override + { + next(); + DB::CurrentThread::checkIfNotCancelled(); + throw DB::S3Exception("the store answered 412", Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); + } +}; + +class PreconditionFailedNativeStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + std::atomic writes{0}; + + std::unique_ptr writeObject( + const DB::StoredObject &, DB::WriteMode, std::optional, size_t, const DB::WriteSettings &) override + { + ++writes; + return std::make_unique(); + } +}; + +template +std::shared_ptr makeNativeTestStorage() +{ + static std::atomic counter{0}; + const auto root = (std::filesystem::temp_directory_path() + / ("cas_flush_native_unit_" + std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)))).string(); + std::filesystem::remove_all(root); + std::filesystem::create_directories(root); + DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); + return DB::Cas::tests::ownedByDirectory(std::make_shared(std::move(settings)), root); +} + +struct NativeReadOutcome +{ + bool absent = false; + String bytes; + bool cause_thrown = false; + int code = 0; + int reads = 0; +}; + +/// One native read through the request engine of an object that is present, whose first read fails with a timeout. +NativeReadOutcome readWithFailedFirstGet(KilledQueryPlace place, const std::exception_ptr & cause) +{ + auto storage = makeNativeTestStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "present"); + { + auto out = storage->writeObject(DB::StoredObject(key), DB::WriteMode::Rewrite); + DB::writeString(String("body"), *out); + out->finalize(); + } + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + NativeReadOutcome out; + runKilledQueryScenario(place, cause, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + storage->reads = 0; + storage->fail_next = true; + try + { + const auto read = op.read(key, Retry::standard()); + out.absent = !read.has_value(); + if (read) + out.bytes = String(read->bytes); + } + catch (...) + { + out.code = exceptionCode(std::current_exception()); + } + out.reads = storage->reads.load(); + }); + return out; +} + +} + +/// A failed GET of a present key, while the thread carries a stored `NoSuchKey`: the leader's masked cancellation lets +/// the timeout be retried and the original bytes come back. Without the blocker the stored cause replaces the timeout +/// and is read as the key's absence. +TEST(CASRefWriterChunkedFlush, FailedGetOfAPresentKeyUnderAKilledLeaderIsRetried) +{ + const std::exception_ptr cause + = std::make_exception_ptr(DB::S3Exception("the query's stored cause", Aws::S3::S3Errors::NO_SUCH_KEY, "NoSuchKey")); + const NativeReadOutcome in_leader = readWithFailedFirstGet(KilledQueryPlace::InsideLeaderFlush, cause); + EXPECT_EQ(in_leader.code, 0); + EXPECT_FALSE(in_leader.absent) << "a failed GET of a present key is not absence"; + EXPECT_EQ(in_leader.bytes, "body") << "the retry returns the original bytes"; + EXPECT_EQ(in_leader.reads, 2) << "the timeout was retried once"; + + const NativeReadOutcome without_blocker = readWithFailedFirstGet(KilledQueryPlace::SharedWithoutBlocker, cause); + EXPECT_TRUE(without_blocker.absent) << "control: shared alone lets the stored NoSuchKey be read as absence; code " + << without_blocker.code; +} + +/// A genuine `412` on a conditional write, while the thread carries a distinct stored cause: a clean conflict. +/// Without the blocker the stored cause replaces the `412`, which is then not a conflict. +TEST(CASRefWriterChunkedFlush, GenuinePreconditionFailedUnderAKilledLeaderIsAConflict) +{ + struct Outcome + { + bool conflict = false; + bool any_ambiguous = false; + bool refused = false; + int refused_code = 0; + int code = 0; + int writes = 0; + }; + const auto run = [](KilledQueryPlace place) + { + auto storage = makeNativeTestStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "absent"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + Outcome out; + runKilledQueryScenario(place, storedCauseWithCode(DB::ErrorCodes::READONLY), [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + const WriteResult written = op.create(key, "bytes", Retry::standard()); + if (const auto * conflict = std::get_if(&written)) + { + out.conflict = true; + out.any_ambiguous = conflict->any_ambiguous; + } + else if (const auto * refused = std::get_if(&written)) + { + out.refused = true; + out.refused_code = refused->store_error; + } + } + catch (...) + { + out.code = exceptionCode(std::current_exception()); + } + }); + out.writes = storage->writes.load(); + return out; + }; + + const Outcome in_leader = run(KilledQueryPlace::InsideLeaderFlush); + EXPECT_EQ(in_leader.code, 0); + EXPECT_TRUE(in_leader.conflict) << "the store's own 412 is a conflict"; + EXPECT_FALSE(in_leader.any_ambiguous); + EXPECT_EQ(in_leader.writes, 1); + + const Outcome without_blocker = run(KilledQueryPlace::SharedWithoutBlocker); + EXPECT_FALSE(without_blocker.conflict) << "control: shared alone lets the stored cause replace the 412"; + EXPECT_EQ(without_blocker.code, 0) << "control: the 412 is refused, not thrown"; + EXPECT_TRUE(without_blocker.refused) << "control: the stored cause is read as a store refusal"; + EXPECT_EQ(without_blocker.refused_code, DB::ErrorCodes::READONLY); + EXPECT_EQ(without_blocker.writes, 1) << "control: exactly one attempt was sent"; +} + +/// A genuine miss, which the fake checks the cancellation before emitting as the S3 client does: absence under the +/// leader's masked cancellation. Without the blocker the stored cause replaces the miss. +TEST(CASRefWriterChunkedFlush, GenuineMissUnderAKilledLeaderIsAbsence) +{ + const std::exception_ptr cause = storedCauseWithCode(DB::ErrorCodes::READONLY); + const auto run = [&cause](KilledQueryPlace place) + { + auto storage = makeNativeTestStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "absent"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + NativeReadOutcome out; + runKilledQueryScenario(place, cause, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + storage->reads = 0; + storage->miss_next = true; + try + { + out.absent = !op.read(key, Retry::standard()).has_value(); + } + catch (...) + { + out.code = exceptionCode(std::current_exception()); + out.cause_thrown = std::current_exception() == cause; + } + out.reads = storage->reads.load(); + }); + return out; + }; + + const NativeReadOutcome in_leader = run(KilledQueryPlace::InsideLeaderFlush); + EXPECT_EQ(in_leader.code, 0); + EXPECT_TRUE(in_leader.absent) << "the store's own miss is absence"; + EXPECT_EQ(in_leader.reads, 1); + + const NativeReadOutcome without_blocker = run(KilledQueryPlace::SharedWithoutBlocker); + EXPECT_FALSE(without_blocker.absent) << "control: shared alone lets the stored cause replace the miss"; + EXPECT_EQ(without_blocker.code, DB::ErrorCodes::READONLY) << "control: the read throws the stored cause"; + EXPECT_TRUE(without_blocker.cause_thrown) << "control: the exception is the stored cause itself"; + EXPECT_EQ(without_blocker.reads, 1) << "control: exactly one attempt was sent"; +} + +#endif + /// Leaving a query's thread group finalizes the thread's counters and writes a `system.query_thread_log` row, so a /// leader must flush in its caller's group: the same group before the append, inside the flush and after it. TEST(CASRefWriterChunkedFlush, LeaderFlushesInItsCallersThreadGroup)