Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/en/antalya/cas/architecture/garbage-collection.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,11 @@ follower or a deferred round execution returns before that commit.

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
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`.
phase 4 on a first `DEFER`. Once a `DEFER` round settles with zero changed shards, no non-`Live`
catalog entries, and a clean janitor sweep, subsequent idle rounds short-circuit when `rowDecisionDue`
is false (and no orphan-manifest sweep is due) and the `cas/ref_catalog` ETag and `cas/ns/stream/` listing fingerprint match — running only
`lease`, `heartbeat_floor` (which skips `GET`s for cached terminal mount slots), and a short-circuited
`defer_decision` without forcing periodic empty folds or pulsing `gc/hb` between rounds.
Its lease `CAS` may already have created or renewed the lease in phase 1:

```mermaid
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h>
#include <Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.h>
#include <Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h>
#include <Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.h>
#include <Common/Logger.h>
#include <atomic>
#include <exception>
Expand Down Expand Up @@ -249,6 +250,10 @@ struct RefScanSummary
std::map<UInt128, RefLifeFoldState> parent_ref_lives;
/// Listed ids absent from the `RoundInput` catalog cut are inert dead-life debris.
size_t dead_life_debris = 0;
/// Fingerprint of all `(key, etag)` pairs seen by `enumerateRefPrefix()`, used by the idle
/// short-circuit when every listed key carried a backend ETag (`stream_etags_complete == true`).
uint64_t stream_fingerprint = 0;
bool stream_etags_complete = true;
};

class RefPlan;
Expand Down Expand Up @@ -657,7 +662,9 @@ class Gc
/// the one round-wide destructive verdict when it exists; DEFER passes suppression because it has
/// no folded frontier verdict, which takes one page. This helper owns only janitor I/O and phase
/// metrics, never lifecycle transitions or the hot stream walk plan.
void runNamespaceJanitor(
/// Returns `true` if any pending janitor work, dead-life debris, non-empty cursor, leak, or
/// anomaly remains (or if the pass threw).
bool runNamespaceJanitor(
const GcState & leased_state, bool suppress_destructive, uint64_t cleanup_evidence_rows);

/// The janitor's `RemoveWriteOnce`: one job per `bulkDeleteChunkKeys` keys on the GC I/O pool, waited for
Expand Down Expand Up @@ -1169,10 +1176,40 @@ class Gc
/// leader (after a steal, or a process restart) starts empty, which only delays fencing an
/// already-dead mount by one extra round (safe: never fences early).
MountObservationMap mount_obs;
/// Leader-local cache of terminal (`gc_fenced` / clean-release) mount ETags so `computeHeartbeatFloor`
/// skips per-slot GETs for unchanged terminal slots.
MountTerminalCache mount_terminal_cache;
/// Srids `computeHeartbeatFloor` already warned about for a lease length different from ours.
/// In-memory: a new leader names each mismatched holder once more.
std::set<String> lease_mismatch_warned;

/// Per-round cache for `readFoldSeal` (cleared on exit of `runRegularRound`) so a single round
/// never reads the same immutable `(generation, attempt)` fold seal multiple times.
struct RoundFoldSealCache
{
uint64_t generation = 0;
uint64_t attempt = 0;
std::optional<CasFoldSeal> seal;
};
bool round_seal_cache_active_ = false;
std::optional<RoundFoldSealCache> round_seal_cache_;
uint64_t round_seal_reads_ = 0;

/// Leader-local steady-state idle baseline recorded after a settled DEFER round with zero
/// changed shards, no pending catalog lifecycle transitions, and a clean janitor sweep.
/// When the next round sees the same `(snap_generation, snap_attempt)`, unchanged catalog ETag,
/// unchanged `cas/ns/stream/` fingerprint, `!rowDecisionDue`, and no due orphan-manifest sweep,
/// it skips drain, walk-plan, and janitor re-scans and does not force periodic empty folds at
/// `gc_fold_max_defer_rounds`.
struct IdleBaseline
{
uint64_t snap_generation = 0;
uint64_t snap_attempt = 0;
Etag catalog_etag;
uint64_t stream_fingerprint = 0;
};
std::optional<IdleBaseline> idle_baseline_;

/// Throttle for the orphan sweep's retention rollup. The premise retains on any pass whose epochs are
/// not closed-and-folded, so an unconditional `LOG_INFO` would repeat the same sentence for as long as
/// that lasts and train operators to filter out the channel carrying the answer they need. It is reported when the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,12 @@ void CasGcScheduler::requestRoundSoon()

void CasGcScheduler::onLeaseAcquired()
{
i_am_leader.store(true, std::memory_order_relaxed);
const bool was_leader = i_am_leader.exchange(true, std::memory_order_relaxed);
/// Only pulse `gc/hb` synchronously when newly acquiring/stealing the lease. Steady-state
/// renewals just bumped `gc/state.lease.seq` (which already proves liveness to followers), and
/// `heartbeatLoop` will pulse `gc/hb` if the round stays in flight past `hb_interval`.
if (was_leader)
return;
try
{
Cas::Gc::pulseHeartbeat(*store, gc_id);
Expand Down Expand Up @@ -318,6 +323,7 @@ Cas::RoundReport CasGcScheduler::runRoundLogged(Cas::Gc & round_gc, GcRoundLogRe
try
{
(void)round_gc.runRegularRound(std::move(on_lease_acquired), allow_steal, Cas::UniversePolicy::kDefault, &rep);
last_round_failed_transiently.store(false, std::memory_order_release);
if (rep.acquired_lease)
{
/// Keep health state per scheduler. Process-global gauges cannot distinguish multiple
Expand Down Expand Up @@ -346,9 +352,11 @@ Cas::RoundReport CasGcScheduler::runRoundLogged(Cas::Gc & round_gc, GcRoundLogRe
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;
const bool transient = isTransientGcRoundError(fin.error_code);
last_round_failed_transiently.store(transient, std::memory_order_release);
fin.outcome = !transient ? Rec::Outcome::Failed
: store->teardownBegun() ? Rec::Outcome::Stopped
: Rec::Outcome::Aborted;
fin.error = getCurrentExceptionMessage(false);
fill_counters(rep);
fin.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
Expand Down Expand Up @@ -560,6 +568,9 @@ void CasGcScheduler::heartbeatLoop()
}
if (!i_am_leader.load(std::memory_order_relaxed))
continue;
if (!round_in_flight.load(std::memory_order_acquire)
&& !last_round_failed_transiently.load(std::memory_order_acquire))
continue;
try
{
Cas::Gc::pulseHeartbeat(*store, gc_id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,11 @@ class CasGcScheduler
/// critical section a scheduled or manual round runs under) and cleared when it returns, on the
/// success AND exception paths. Read by `isQuiescent` (the FORGET / GC-STOP join-completion signal).
std::atomic<bool> round_in_flight{false};
/// Set true when a round ends with a transient failure (keeping `i_am_leader` intact), cleared on
/// any completed round. `heartbeatLoop()` only pulses `gc/hb` while a round is actively in flight or
/// recovering from a transient failure; between healthy idle rounds, the periodic `gc/state` lease
/// renewal itself keeps followers from stealing.
std::atomic<bool> last_round_failed_transiently{false};

/// rev.7 §3 [C1] test-observation seam: set (under `terminal_exit_mutex`) by `loop`/`heartbeatLoop`
/// respectively when they SELF-EXIT via the terminal-lifecycle check, NOT when `stop()` flips
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven
bool page_decided = !ambiguous && !suppress_deletes;
std::vector<WriteOnceKey> dead_stream_keys;

if (ambiguous || !cursor.empty() || !page.next_cursor.empty())
result.has_pending_work = true;

for (const ListedKey & listed : page.keys)
{
std::optional<NamespaceLifePhysicalId> life_id;
Expand Down Expand Up @@ -137,6 +140,8 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven
result.anomalies.push_back(listed.key + ": unrecognized namespace object key");
continue;
}
if (!ambiguous && !catalog_cut.life_index.resolve(*life_id))
result.has_pending_work = true;
if (ambiguous || suppress_deletes || catalog_cut.life_index.resolve(*life_id))
continue;

Expand Down Expand Up @@ -218,6 +223,8 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven
/// An unpublished page is listed again, so its failed keys are not leaked yet.
if (!published)
result.leaked = 0;
if (result.leaked > 0 || !result.anomalies.empty() || result.deleted > 0)
result.has_pending_work = true;
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ struct NamespaceJanitorResult
/// the next page is worth taking now. After the last page of the stream the next one starts from its
/// beginning.
bool more = false;
/// True when the page observed any unresolved/un-deleted dead-life key, non-empty cursor,
/// ambiguous catalog, leak, or anomaly (used by idle GC short-circuiting).
bool has_pending_work = false;
std::vector<String> anomalies;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1344,7 +1344,8 @@ void warnOnceIfHolderLeaseDiffers(
HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64_t now_ms,
const std::function<uint64_t()> & mono_ms_fn,
uint64_t observer_lease_ms, uint64_t cadence_ms, MountObservationMap & obs,
std::set<String> & lease_mismatch_warned)
std::set<String> & lease_mismatch_warned,
MountTerminalCache * terminal_cache)
{
HeartbeatFloor floor;
/// Taken before any read: it can confirm that a token held, never date a sighting.
Expand All @@ -1367,6 +1368,28 @@ HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64
const String srid = key.substr(prefix.size(), key.size() - prefix.size() - mount_suffix.size());
seen_srids.insert(srid);

/// Fast path: a terminal slot (`gc_fenced` or clean release) whose `LIST` ETag matches our
/// previous observation cannot have changed, so skip the per-slot GET completely.
if (terminal_cache && listed.etag)
{
if (const auto cached = terminal_cache->find(srid); cached != terminal_cache->end()
&& sameVersion(*listed.etag, cached->second.etag))
{
if (cached->second.gc_fenced)
{
++floor.already_fenced;
obs.erase(srid);
return true;
}
if (cached->second.clean_release)
{
++floor.terminated;
obs.erase(srid);
return true;
}
}
}

/// One decision per re-read: a refused fence-out re-enters this lambda with the body the
/// holder's own renewal installed, and the observation check below then sees the new
/// incarnation and restarts the window -- which counts the slot `live` and declines the write.
Expand All @@ -1378,6 +1401,8 @@ HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64
if (!observed)
{
obs.erase(srid);
if (terminal_cache)
terminal_cache->erase(srid);
return std::nullopt; /// raced away (deleted) — nothing to classify
}

Expand All @@ -1387,15 +1412,22 @@ HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64
{
++floor.already_fenced;
obs.erase(srid); /// terminal — no further observation needed
if (terminal_cache)
terminal_cache->insert_or_assign(srid, CachedMountSlot{observed->etag, /*gc_fenced=*/true, /*clean_release=*/false});
return std::nullopt;
}
if (m.isCleanRelease())
{
++floor.terminated;
obs.erase(srid); /// terminal — no further observation needed
if (terminal_cache)
terminal_cache->insert_or_assign(srid, CachedMountSlot{observed->etag, /*gc_fenced=*/false, /*clean_release=*/true});
return std::nullopt;
}

if (terminal_cache)
terminal_cache->erase(srid);

warnOnceIfHolderLeaseDiffers(srid, m, observer_lease_ms, lease_mismatch_warned);
threshold_ms = mountObservationThresholdMs(observer_lease_ms, declaredMountLeaseMs(m), cadence_ms);

Expand Down Expand Up @@ -1428,6 +1460,9 @@ HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64
++floor.fenced_now;
floor.fenced_srids.push_back(srid);
obs.erase(srid);
if (terminal_cache)
terminal_cache->insert_or_assign(
srid, CachedMountSlot{std::get<Committed>(fenced_out).etag, /*gc_fenced=*/true, /*clean_release=*/false});
LOG_INFO(getLogger("CasHeartbeatFloor"),
"CAS GC fenced out mount lease for content-addressed server root {} at "
"wall-clock ms {}: its write incarnation held unchanged for >= {} ms on the GC "
Expand All @@ -1447,6 +1482,8 @@ HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64
/// stay in both maps forever on a long-lived leader.
std::erase_if(obs, [&](const auto & entry) { return !seen_srids.contains(entry.first); });
std::erase_if(lease_mismatch_warned, [&](const String & s) { return !seen_srids.contains(s); });
if (terminal_cache)
std::erase_if(*terminal_cache, [&](const auto & entry) { return !seen_srids.contains(entry.first); });

return floor;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -473,10 +473,23 @@ struct HeartbeatFloor
std::vector<String> fenced_srids;
};

/// Cached terminal mount classification keyed by `server_root_id`. A `gc_fenced` or clean-release
/// mount slot never mutates again unless a successor reclaims it, which changes the object's ETag.
/// Passing this cache across GC rounds lets `computeHeartbeatFloor` skip GET/readModifyWrite on
/// unchanged terminal slots when `LIST` returns the same ETag.
struct CachedMountSlot
{
Etag etag;
bool gc_fenced = false;
bool clean_release = false;
};
using MountTerminalCache = std::map<String, CachedMountSlot>;

HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64_t now_ms,
const std::function<uint64_t()> & mono_ms_fn,
uint64_t observer_lease_ms, uint64_t cadence_ms, MountObservationMap & obs,
std::set<String> & lease_mismatch_warned);
std::set<String> & lease_mismatch_warned,
MountTerminalCache * terminal_cache = nullptr);

/// One `gc/server-roots/<srid>/mount` slot whose holder is not provably finished with the prefix.
struct NonTerminalMountSlot
Expand Down
4 changes: 2 additions & 2 deletions src/Disks/tests/gtest_cas_gc_log.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -955,10 +955,10 @@ TEST(CASGCLog, FoldingRoundEmitsEveryPhaseInOrder)
EXPECT_TRUE(r.error.empty());
}

/// The defer decision reports the signal it decided on, and the two fold-seal reads it paid for.
/// The defer decision reports the signal it decided on, and the per-round fold-seal reads (0 on gen 0).
const auto defer = metricsOf(rows, 0, "defer_decision");
EXPECT_EQ(defer.at("deferred"), 0u) << "this round folded, so it cannot report itself deferred";
EXPECT_EQ(defer.at("fold_seal_reads"), 2u);
EXPECT_LE(defer.at("fold_seal_reads"), 1u);
EXPECT_GT(defer.at("namespaces_seen"), 0u);

const auto ref_group = metricsOf(rows, 0, "fold_ref_group");
Expand Down
Loading