From 120ea0bd641f5f9dca2e3d18e0f53d7fa434405e Mon Sep 17 00:00:00 2001 From: sabith Date: Wed, 18 Nov 2026 14:28:52 -0800 Subject: [PATCH] perf(cas): short-circuit idle GC rounds, cache terminal mount ETags, and suppress idle heartbeats Reduces idle S3 traffic on settled CAS pools without weakening lease-steal or deletion safety: 1. CasGcScheduler: suppress periodic gc/hb writes in heartbeatLoop() when no round is in flight and the last round did not fail transiently; skip synchronous gc/hb write in onLeaseAcquired() on steady-state leader renewals (gc/state lease seq bump already proves liveness). 2. computeHeartbeatFloor (CasServerRoot): cache terminal (gc_fenced / clean-release) mount ETags across rounds and skip per-slot GET/readModifyWrite when LIST returns the same ETag. 3. CasGc: add per-round CasFoldSeal cache (avoiding duplicate fold_seal GETs and gen-0 404s) and steady-state IdleBaseline short-circuit (comparing catalog ETag and cas/ns/stream/ (key, etag) SipHash fingerprint) so settled idle pools skip drain, walk-plan, janitor re-scans, and periodic forced empty folds. 4. Update gtest_cas_gc_round_defer.cpp, gtest_cas_gc_log.cpp, and docs/en/antalya/cas/architecture/garbage-collection.md. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: sabith --- .../cas/architecture/garbage-collection.md | 8 +- .../ContentAddressed/Gc/CasGc.cpp | 276 +++++++++++++----- .../ContentAddressed/Gc/CasGc.h | 39 ++- .../ContentAddressed/Gc/CasGcScheduler.cpp | 19 +- .../ContentAddressed/Gc/CasGcScheduler.h | 5 + .../Gc/CasNamespaceJanitor.cpp | 7 + .../ContentAddressed/Gc/CasNamespaceJanitor.h | 3 + .../ContentAddressed/Pool/CasServerRoot.cpp | 39 ++- .../ContentAddressed/Pool/CasServerRoot.h | 15 +- src/Disks/tests/gtest_cas_gc_log.cpp | 4 +- src/Disks/tests/gtest_cas_gc_round_defer.cpp | 63 ++++ 11 files changed, 394 insertions(+), 84 deletions(-) diff --git a/docs/en/antalya/cas/architecture/garbage-collection.md b/docs/en/antalya/cas/architecture/garbage-collection.md index c7a76e8ae8444..935d6f3682a1c 100644 --- a/docs/en/antalya/cas/architecture/garbage-collection.md +++ b/docs/en/antalya/cas/architecture/garbage-collection.md @@ -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 diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp index 39c2b289ad513..38e414bc607ff 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -467,13 +468,14 @@ Gc::Gc(PoolPtr store_, UInt128 gc_id_, std::function now_ms_fn_, io_pool_refuse_at_for_test = store->poolConfig().gc_io_pool_refuse_at_for_test; } -void Gc::runNamespaceJanitor( +bool Gc::runNamespaceJanitor( const GcState & leased_state, bool suppress_destructive, uint64_t cleanup_evidence_rows) { GcPhaseTimer t(phase_sink, "namespace_cleanup"); t.metric("evidence_rows", cleanup_evidence_rows); NamespaceJanitorResult janitor_result; bool budget_exhausted = false; + bool threw = false; try { CasRequests & requests = store->openRequests(); @@ -496,6 +498,7 @@ void Gc::runNamespaceJanitor( janitor_result.deleted += page.deleted; janitor_result.leaked += page.leaked; janitor_result.delete_requests += page.delete_requests; + janitor_result.has_pending_work = janitor_result.has_pending_work || page.has_pending_work; for (const String & anomaly : page.anomalies) LOG_WARNING(logger, "CAS namespace janitor: {}", anomaly); if (!page.more) @@ -509,6 +512,7 @@ void Gc::runNamespaceJanitor( } catch (const std::exception & e) { + threw = true; LOG_WARNING(logger, "CAS namespace janitor stopped this round: {}", e.what()); } if (janitor_result.leaked) @@ -519,6 +523,7 @@ void Gc::runNamespaceJanitor( t.metric("leaked", janitor_result.leaked); t.metric("delete_requests", janitor_result.delete_requests); t.metric("budget_exhausted", budget_exhausted ? 1 : 0); + return threw || budget_exhausted || janitor_result.has_pending_work; } void Gc::removeWriteOnceOnIoPool(CasOperation & op, const std::vector & keys, NamespaceJanitorResult & out) @@ -828,6 +833,14 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al GcState state; std::optional state_etag; + round_seal_cache_active_ = true; + round_seal_cache_.reset(); + round_seal_reads_ = 0; + SCOPE_EXIT({ + round_seal_cache_active_ = false; + round_seal_cache_.reset(); + }); + /// Phase `lease`. Also the ONLY phase a `NotALeader` round emits, which is why the phase rows /// are correlated by `round_id` and not by the round number a follower never learns. { @@ -856,60 +869,15 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al CasOperation op = store->openRequests().admit(); const uint64_t new_round = state.round + 1; - /// ONE budget instance for the WHOLE round, threaded into every destructive-or-observability-write - /// family below: `fold` (blob intent creates and body deletes, the `GcOutcomes` audit rows, the orphan-manifest - /// planner), `pruneSupersededGenerations`, the post-CAS hand-off reclaim (its OWN reserve, never - /// `pruneSupersededGenerations`' shared remainder), the post-CAS manifest-body cleanup, and - /// `cleanupRefObjects`. A cap is therefore cumulative over the round, never reset between families or - /// shards, except the outcome log byte limit, which is per shard. See `GcRoundWorkBudget`'s own - /// comment for the fail-closed contract each family applies on exhaustion. - GcRoundWorkBudget round_work_budget; - round_work_budget.intent_creates.cap = store->poolConfig().gc_round_intent_create_budget; - round_work_budget.intent_creates.resume_after = creates_resume_after_; - round_work_budget.redeletes.cap = store->poolConfig().gc_round_redelete_budget; - round_work_budget.redeletes.resume_after = redeletes_resume_after_; - round_work_budget.max_sweep_namespaces = store->poolConfig().gc_round_sweep_namespace_budget; - round_work_budget.max_sweep_recovery_ops = store->poolConfig().gc_round_sweep_recovery_op_budget; - round_work_budget.max_ref_cleanup_objects = store->poolConfig().gc_round_ref_cleanup_budget; - round_work_budget.max_prefix_wholesale_objects = store->poolConfig().gc_round_prefix_wholesale_budget; - round_work_budget.max_handoff_prefix_wholesale_objects = store->poolConfig().gc_round_handoff_prefix_wholesale_budget; - round_work_budget.max_outcome_entries = store->poolConfig().gc_round_outcome_entry_budget; - if (const auto limit = store->poolConfig().gc_outcome_log_byte_limit_for_test) - round_work_budget.max_outcome_log_bytes = *limit; - - /// 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. - { - GcPhaseTimer t(phase_sink, "pre_fold_ref_drain"); - 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. - SCOPE_EXIT({ - t.metric("deleted", completed_erases); - t.metric("cancelled_creating", cancelled_creating); - }); - const CatalogLifecycleReconcileResult drain_result - = drainCompletedRemoving(state, state_etag, completed_erases, cancelled_creating); - if (drain_result.authority_status != AuthorityStatus::Authoritative - || drain_result.catalog_resolution != CatalogResolution::DrainComplete) - throwCasRequestRetryLater("CAS GC pre-fold drain lost authority before the catalog settled"); - } - - /// Etag-guarded fence-out of dead mounts (liveness only — row decisions pace on GC - /// rounds via `new_round`, not on heartbeat acks). A slot is fenced only after `mount_obs` has - /// watched its token hold unchanged on this leader's own monotonic clock for - /// `mountObservationThresholdMs` over the longer of this server's lease and the one the slot - /// declares, with the full renewal period as the step. const uint64_t ttl_ms = static_cast(store->poolConfig().mount_lease_ttl_ms.count()); const uint64_t renew_period_ms = static_cast(store->poolConfig().mount_renew_period.count()); - /// Phase `heartbeat_floor`: one LIST of `gc/server-roots/`, one GET per mount slot, and a fence - /// PUT per newly-fenced mount. + auto run_heartbeat_floor = [&] { GcPhaseTimer t(phase_sink, "heartbeat_floor"); - const HeartbeatFloor floor = computeHeartbeatFloor(op, layout, now_ms_fn(), mono_ms_fn, - ttl_ms, renew_period_ms, mount_obs, lease_mismatch_warned); + const HeartbeatFloor floor = computeHeartbeatFloor( + op, layout, now_ms_fn(), mono_ms_fn, + ttl_ms, renew_period_ms, mount_obs, lease_mismatch_warned, &mount_terminal_cache); report.fence_outs = floor.fenced_now; if (floor.fenced_now > 0) ProfileEvents::increment(ProfileEvents::CASGCHeartbeatFenceOuts, floor.fenced_now); @@ -949,8 +917,122 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al t.metric("terminated", floor.terminated); t.metric("fenced_now", floor.fenced_now); t.metric("already_fenced", floor.already_fenced); + }; + + const uint64_t orphan_manifest_sweep_decision_at_ms = now_ms_fn(); + const auto orphan_manifest_sweep_decision = orphanManifestSweepDecisionOf( + state, store->poolConfig().orphan_manifest_sweep_interval_sec, + 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; + const bool orphan_manifest_sweep_waiting_for_clock + = orphan_manifest_sweep_decision == OrphanManifestSweepDecision::SkipUntilIntervalElapsed + && orphan_manifest_sweep_decision_at_ms < state.orphan_manifest_sweep_completed_at_ms; + + /// Steady-state idle short-circuit: when the previous round settled cleanly (`changed_shards == 0`, + /// no pending catalog lifecycle transitions, and a clean janitor sweep) and neither the catalog + /// ETag, the `cas/ns/stream/` `(key, etag)` fingerprint, `rowDecisionDue`, nor an orphan-manifest + /// sweep is due, run `heartbeat_floor` (with terminal-mount ETag caching) and return `Deferred` + /// without re-reading `cas/ref_catalog`, rebuilding `RefPlan`, running `namespace_cleanup`, or + /// counting toward `gc_fold_max_defer_rounds`. + if (idle_baseline_ + && idle_baseline_->snap_generation == state.snap_generation + && idle_baseline_->snap_attempt == state.snap_attempt + && !run_orphan_manifest_sweep + && !orphan_manifest_sweep_waiting_for_clock + && state.manifest_sweep_cursor.empty() + && store->poolConfig().gc_fold_max_defer_rounds > 0) + { + bool still_idle = false; + if (!rowDecisionDue(state, new_round)) + { + const std::optional cat_head = op.head(layout.refCatalogKey(), Retry::standard()); + if (cat_head && sameVersion(cat_head->etag, idle_baseline_->catalog_etag)) + { + const RefScanSummary idle_scan = enumerateRefPrefix(); + if (idle_scan.stream_etags_complete + && idle_scan.stream_fingerprint == idle_baseline_->stream_fingerprint) + still_idle = true; + } + } + if (still_idle) + { + run_heartbeat_floor(); + { + GcPhaseTimer t(phase_sink, "defer_decision"); + t.metric("changed_shards", 0); + t.metric("row_decision_due", 0); + t.metric("run_orphan_manifest_sweep", 0); + t.metric("orphan_manifest_sweep_active", 0); + t.metric("orphan_manifest_sweep_waiting_for_clock", 0); + t.metric("deferred", 1); + t.metric("idle_short_circuit", 1); + t.metric("rounds_deferred_before", rounds_since_last_fold_); + t.metric("fold_seal_reads", round_seal_reads_); + } + report.deferred = true; + report.round = state.round; + EventEmitter{*store}.emit([&](CasEvent & e) + { + e.type = CasEventType::GcFence; + e.object_kind = CasEventObjectKind::Snap; + e.round = state.round; + e.gen = state.snap_generation; + e.outcome = "deferred"; + e.reason = "idle-short-circuit: catalog etag and ref stream unchanged; skipping drain, " + "walk-plan, and janitor"; + e.detail = {{"changed_shards", "0"}, + {"rounds_since_last_fold", std::to_string(rounds_since_last_fold_)}}; + }); + return report; + } + idle_baseline_.reset(); + } + + /// ONE budget instance for the WHOLE round, threaded into every destructive-or-observability-write + /// family below: `fold` (blob intent creates and body deletes, the `GcOutcomes` audit rows, the orphan-manifest + /// planner), `pruneSupersededGenerations`, the post-CAS hand-off reclaim (its OWN reserve, never + /// `pruneSupersededGenerations`' shared remainder), the post-CAS manifest-body cleanup, and + /// `cleanupRefObjects`. A cap is therefore cumulative over the round, never reset between families or + /// shards, except the outcome log byte limit, which is per shard. See `GcRoundWorkBudget`'s own + /// comment for the fail-closed contract each family applies on exhaustion. + GcRoundWorkBudget round_work_budget; + round_work_budget.intent_creates.cap = store->poolConfig().gc_round_intent_create_budget; + round_work_budget.intent_creates.resume_after = creates_resume_after_; + round_work_budget.redeletes.cap = store->poolConfig().gc_round_redelete_budget; + round_work_budget.redeletes.resume_after = redeletes_resume_after_; + round_work_budget.max_sweep_namespaces = store->poolConfig().gc_round_sweep_namespace_budget; + round_work_budget.max_sweep_recovery_ops = store->poolConfig().gc_round_sweep_recovery_op_budget; + round_work_budget.max_ref_cleanup_objects = store->poolConfig().gc_round_ref_cleanup_budget; + round_work_budget.max_prefix_wholesale_objects = store->poolConfig().gc_round_prefix_wholesale_budget; + round_work_budget.max_handoff_prefix_wholesale_objects = store->poolConfig().gc_round_handoff_prefix_wholesale_budget; + round_work_budget.max_outcome_entries = store->poolConfig().gc_round_outcome_entry_budget; + if (const auto limit = store->poolConfig().gc_outcome_log_byte_limit_for_test) + round_work_budget.max_outcome_log_bytes = *limit; + + /// 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. + { + GcPhaseTimer t(phase_sink, "pre_fold_ref_drain"); + 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. + SCOPE_EXIT({ + t.metric("deleted", completed_erases); + t.metric("cancelled_creating", cancelled_creating); + }); + const CatalogLifecycleReconcileResult drain_result + = drainCompletedRemoving(state, state_etag, completed_erases, cancelled_creating); + if (drain_result.authority_status != AuthorityStatus::Authoritative + || drain_result.catalog_resolution != CatalogResolution::DrainComplete) + throwCasRequestRetryLater("CAS GC pre-fold drain lost authority before the catalog settled"); } + /// Phase `heartbeat_floor`: one LIST of `gc/server-roots/`, one GET per live mount slot (cached + /// terminal slots skip GETs via ETag), and a fence PUT per newly-fenced mount. + run_heartbeat_floor(); + /// Decide DEFER vs FOLD from cheap pre-fold signals. /// A DEFER round re-adopts the sealed generation — no fold, no delete, no gc/state write — so a /// slow idle/small-delta round no longer rebuilds the whole in-degree snapshot. Safety: a due @@ -962,20 +1044,14 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al /// /// Phase `defer_decision`. `ref_scan` OUTLIVES the timer because the fold consumes it, and /// `report.deferred` is set INSIDE the scope so the row already reflects the verdict when the - /// timer's destructor fires on the deferred round's early return. This phase also performs TWO of - /// the round's reads of the adopted fold seal (`rowDecisionDue` and `listRefPrefix` each read the - /// same key) -- see `fold_seal_reads` below. + /// timer's destructor fires on the deferred round's early return. std::optional walk_plan; bool defer_round = false; - const uint64_t orphan_manifest_sweep_decision_at_ms = now_ms_fn(); - const auto orphan_manifest_sweep_decision = orphanManifestSweepDecisionOf( - state, store->poolConfig().orphan_manifest_sweep_interval_sec, - 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; + bool row_decision_due = false; { GcPhaseTimer t(phase_sink, "defer_decision"); - const bool row_decision_due = rowDecisionDue(state, new_round); + const uint64_t seal_reads_before = round_seal_reads_; + row_decision_due = rowDecisionDue(state, new_round); walk_plan.emplace(buildRefWalkPlan(listRefPrefix(state, state_etag))); reportStuckRemovals(*walk_plan, state.round); const RefScanSummary & ref_scan = walk_plan->refScan(); @@ -993,8 +1069,7 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al t.metric("row_decision_due", row_decision_due ? 1 : 0); t.metric("run_orphan_manifest_sweep", run_orphan_manifest_sweep ? 1 : 0); t.metric("orphan_manifest_sweep_active", state.manifest_sweep_cursor.empty() ? 0 : 1); - t.metric("orphan_manifest_sweep_waiting_for_clock", orphan_manifest_sweep_decision == OrphanManifestSweepDecision::SkipUntilIntervalElapsed - && orphan_manifest_sweep_decision_at_ms < state.orphan_manifest_sweep_completed_at_ms ? 1 : 0); + t.metric("orphan_manifest_sweep_waiting_for_clock", orphan_manifest_sweep_waiting_for_clock ? 1 : 0); t.metric("dead_life_debris", ref_scan.dead_life_debris); t.metric("walk_plan_builds", 1); t.metric("walk_plan_rows", walk_plan->size()); @@ -1005,10 +1080,7 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al /// The number of consecutive rounds already deferred BEFORE this one (this round's own verdict is /// `deferred` above), so the pair reads unambiguously against `gc_fold_max_defer_rounds`. t.metric("rounds_deferred_before", rounds_since_last_fold_); - /// `rowDecisionDue` and `listRefPrefix` each GET the adopted fold seal at the SAME - /// (generation, attempt). Recorded, not fixed -- see the `fold_seal_read` phase, which records - /// the other duplicate pair; the round GETs that one key FIVE times on a folding round. - t.metric("fold_seal_reads", 2); + t.metric("fold_seal_reads", round_seal_reads_ - seal_reads_before); if (defer_round) { @@ -1048,10 +1120,38 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al /// DEFER has no `FoldResult`, hence no complete global destructive verdict. The janitor still /// takes its bounded page and catalog cut, but suppression keeps both deletes and valid-page /// cursor progress at the same position for the bounded forced fold to retry. - runNamespaceJanitor(state, /*suppress_destructive=*/true, /*cleanup_evidence_rows=*/0); + const bool janitor_pending = runNamespaceJanitor(state, /*suppress_destructive=*/true, /*cleanup_evidence_rows=*/0); + const CasRefCatalog::Snapshot & cat = walk_plan->catalogCut(); + const bool has_non_live_catalog_entries = std::any_of( + cat.catalog.entries.begin(), cat.catalog.entries.end(), + [](const CatalogEntry & entry) { return entry.state != NsState::Live; }); + if (!janitor_pending + && !row_decision_due + && !run_orphan_manifest_sweep + && !orphan_manifest_sweep_waiting_for_clock + && walk_plan->changedRows() == 0 + && walk_plan->refScan().dead_life_debris == 0 + && walk_plan->refScan().stream_etags_complete + && cat.etag.has_value() + && !has_non_live_catalog_entries + && state.manifest_sweep_cursor.empty() + && store->poolConfig().gc_fold_max_defer_rounds > 0) + { + idle_baseline_ = IdleBaseline{ + state.snap_generation, + state.snap_attempt, + *cat.etag, + walk_plan->refScan().stream_fingerprint}; + } + else + { + idle_baseline_.reset(); + } return report; /// no fold, no pre-CAS deletes, no gc/state CAS — sealed generation stays pinned } + idle_baseline_.reset(); + /// Emit that the round's single pass begins. EventEmitter{*store}.emit([&](CasEvent & e) { @@ -1079,6 +1179,8 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al parent_seal_runs = parent_seal->blob_target_runs; t.metric("parent_runs", parent_seal_runs.size()); } + if (phase_sink) + round_seal_cache_.reset(); /// The pass performs discovery, windowing, and the three-cursor merge (spare / confirm intent / condemn). /// It emits phases 5..10 of its own. @@ -1609,7 +1711,7 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al 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); + (void)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. @@ -2489,6 +2591,7 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, /// metric is the evidence for deciding it. std::optional seal_read_timer; seal_read_timer.emplace(phase_sink, "fold_seal_read"); + const uint64_t seal_reads_before = round_seal_reads_; const std::optional adopted_seal = readFoldSeal(state.snap_generation, state.snap_attempt); if (!adopted_seal && state.snap_generation > 0) { @@ -2754,8 +2857,8 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, CasFoldSeal discover_ref_seal; if (const auto fold_seal = readFoldSeal(state.snap_generation, state.snap_attempt)) discover_ref_seal = *fold_seal; - seal_read_timer->metric("seal_reads", 2); - seal_read_timer->metric("redundant_reads", 1); + seal_read_timer->metric("seal_reads", round_seal_reads_ - seal_reads_before); + seal_read_timer->metric("redundant_reads", 0); seal_read_timer->metric("parent_ref_lives", parent_ref_lives.size()); seal_read_timer->metric("dropped_parent_ref_lives", dropped_parent_ref_lives); seal_read_timer->metric("parent_runs", discover_ref_seal.blob_target_runs.size()); @@ -5163,11 +5266,21 @@ void Gc::pruneSupersededGenerations(uint64_t adopted_generation, uint64_t attemp std::optional Gc::readFoldSeal(uint64_t generation, uint64_t attempt) { + if (generation == 0) + return std::nullopt; + if (round_seal_cache_active_ && round_seal_cache_ && round_seal_cache_->generation == generation + && round_seal_cache_->attempt == attempt) + return round_seal_cache_->seal; + + ++round_seal_reads_; CasOperation op = store->openRequests().admit(); + std::optional decoded; if (const auto got = op.read(store->layout().foldSealKey(generation, attempt), Retry::standard())) - return decodeFoldSeal( + decoded = decodeFoldSeal( got->bytes, store->layout(), store->poolConfig().gc_shards, generation); - return std::nullopt; + if (round_seal_cache_active_) + round_seal_cache_ = RoundFoldSealCache{generation, attempt, decoded}; + return decoded; } void Gc::throwIfStateMoved(CasOperation & op, const std::optional & state_etag, const String & failure) @@ -5285,11 +5398,24 @@ RefScanSummary Gc::enumerateRefPrefix() CasOperation op = store->openRequests().admit(); RefScanSummary scan; + SipHash fingerprint_hash; static constexpr size_t kListPageLimit = CasOperation::kCasListPageKeys; size_t count_in_page = 0; op.forEachListedKey(layout.casRefsPrefix(), [&](const ListedKey & lk) { scan.keys.push_back(lk.key); + fingerprint_hash.update(lk.key.size()); + fingerprint_hash.update(lk.key); + if (lk.etag) + { + const String rendered = lk.etag->render(); + fingerprint_hash.update(rendered.size()); + fingerprint_hash.update(rendered); + } + else + { + scan.stream_etags_complete = false; + } const auto parsed = parseRefObjectKeyForEnumeration(layout, lk.key); if (parsed) { @@ -5309,6 +5435,8 @@ RefScanSummary Gc::enumerateRefPrefix() } return true; }, Retry::standard(), kListPageLimit, onGcEnumerationPage); + fingerprint_hash.update(scan.keys.size()); + scan.stream_fingerprint = fingerprint_hash.get64(); /// The walk's list lands at least once even for an empty/undersized final page -- /// count it (one increment per physical LIST call). if (count_in_page > 0 || scan.keys.empty()) @@ -5331,12 +5459,16 @@ RoundInput Gc::listRefPrefix(const GcState & state, const std::optional & /// the very `std::function` executing it. if (post_hot_scan_catalog_read_hook_for_test) { + round_seal_cache_.reset(); std::function hook_to_run; std::swap(hook_to_run, post_hot_scan_catalog_read_hook_for_test); hook_to_run(); } if (round_point_hook_for_test) + { + round_seal_cache_.reset(); runRoundPointHookForTest(RoundPointForTest::AfterCatalogRead); + } catalog_cut.life_index.throwIfAmbiguous("CAS GC hot scan"); store->reconcileRefCatalogCut(catalog_cut); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h index b1bc1a2db24ec..2a230a4cb3afb 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -249,6 +250,10 @@ struct RefScanSummary std::map 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; @@ -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 @@ -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 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 seal; + }; + bool round_seal_cache_active_ = false; + std::optional 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 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 diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp index 6a057b0156f63..c2f05c101672c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp @@ -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); @@ -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 @@ -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( @@ -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); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h index 4eb8381146f7f..3c7d8d365f52f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h @@ -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 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 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 diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp index 0a8857f714799..029c6ad7c17f8 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp @@ -106,6 +106,9 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven bool page_decided = !ambiguous && !suppress_deletes; std::vector dead_stream_keys; + if (ambiguous || !cursor.empty() || !page.next_cursor.empty()) + result.has_pending_work = true; + for (const ListedKey & listed : page.keys) { std::optional life_id; @@ -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; @@ -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; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.h index 417d2ba2b8f4a..2c8627eb013ae 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.h @@ -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 anomalies; }; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp index aba6503d21a38..79e456b28964b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp @@ -1344,7 +1344,8 @@ void warnOnceIfHolderLeaseDiffers( HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64_t now_ms, const std::function & mono_ms_fn, uint64_t observer_lease_ms, uint64_t cadence_ms, MountObservationMap & obs, - std::set & lease_mismatch_warned) + std::set & lease_mismatch_warned, + MountTerminalCache * terminal_cache) { HeartbeatFloor floor; /// Taken before any read: it can confirm that a token held, never date a sighting. @@ -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. @@ -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 } @@ -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); @@ -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(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 " @@ -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; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.h index 6eb1d2f55038b..99498116c6143 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.h @@ -473,10 +473,23 @@ struct HeartbeatFloor std::vector 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; + HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64_t now_ms, const std::function & mono_ms_fn, uint64_t observer_lease_ms, uint64_t cadence_ms, MountObservationMap & obs, - std::set & lease_mismatch_warned); + std::set & lease_mismatch_warned, + MountTerminalCache * terminal_cache = nullptr); /// One `gc/server-roots//mount` slot whose holder is not provably finished with the prefix. struct NonTerminalMountSlot diff --git a/src/Disks/tests/gtest_cas_gc_log.cpp b/src/Disks/tests/gtest_cas_gc_log.cpp index 75667566f0566..4129c3d07fb75 100644 --- a/src/Disks/tests/gtest_cas_gc_log.cpp +++ b/src/Disks/tests/gtest_cas_gc_log.cpp @@ -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"); diff --git a/src/Disks/tests/gtest_cas_gc_round_defer.cpp b/src/Disks/tests/gtest_cas_gc_round_defer.cpp index c03934fe3a4be..00eb7ec1d9cf7 100644 --- a/src/Disks/tests/gtest_cas_gc_round_defer.cpp +++ b/src/Disks/tests/gtest_cas_gc_round_defer.cpp @@ -689,3 +689,66 @@ TEST(CASGCRoundDefer, OneShardMergesWhenATableChangedWithoutAnyBlobDelta) ASSERT_FALSE(runRegularRoundReclaiming(gc).deferred); EXPECT_EQ(reduceMetrics().at("shards_pure_carry"), 1u) << "positive control: nothing changed, so the shard is carried"; } + +/// Steady-state idle short-circuit: once a deferred round settles with zero changed shards, zero +/// pending catalog transitions, and a clean janitor sweep, subsequent idle rounds skip `cas/ref_catalog` +/// GETs, `namespace_cleanup` scans, and forced empty folds across `gc_fold_max_defer_rounds`, and a +/// subsequent publish wakes GC immediately. +TEST(CASGCRoundDefer, SteadyStateIdleShortCircuitsWithoutForcedEmptyFoldsAndWakesOnPublish) +{ + auto backend = std::make_shared(); + auto store = Pool::open(backend, + PoolConfig{.pool_prefix = "p", .server_root_id = "test", + .gc_fold_threshold = 1, .gc_fold_max_defer_rounds = 2}); + const Layout & layout = store->layout(); + const RootNamespace ns{"00/idle@cas@"}; + const ManifestRef r1{.writer_epoch = 1, .build_sequence = 1, .manifest_ordinal = 0xAA}; + writeBlobBody(*backend, layout, UInt128(1)); + writeManifestRaw(*backend, layout, ns, r1, {blobEntryFor("a", UInt128(1))}); + publishCommittedTransition(*backend, layout, ns, "tbl", std::nullopt, r1); + + /// Seed a fenced mount slot to confirm terminal-mount ETag caching skips repeated mount GETs. + { + OperationForTest seed_op(*backend); + const MountLease fenced_mount{ + .server_uuid = UInt128(0xDEAD), + .writer_epoch = 1, + .hostname = "ephemeral-node", + .pid = 42, + .started_at_ms = 1, + .seq = 1, + .expires_at_ms = 2, + .min_active_build_sequence = 0, + .gc_fenced = true, + .write_attempt_id = UInt128(1)}; + ASSERT_TRUE(std::holds_alternative( + (*seed_op).create(layout.mountKey("ephemeral-node"), encodeMountLease(fenced_mount), Retry::once()))); + } + + Gc gc(store, kGc); + /// Round 1: folds r1. + ASSERT_FALSE(gc.runRegularRound().deferred); + /// Round 2: first idle defer runs full defer_decision + janitor and records idle baseline. + ASSERT_TRUE(gc.runRegularRound().deferred); + + /// Rounds 3..6 exceed gc_fold_max_defer_rounds=2, yet stay deferred with zero catalog GETs, + /// zero namespace_cleanup LISTs, and zero GETs on the cached fenced mount slot. + for (int i = 0; i < 4; ++i) + { + backend->resetCounts(); + const RoundReport idle_rep = gc.runRegularRound(); + EXPECT_TRUE(idle_rep.deferred) << "idle round " << (i + 3) << " should remain short-circuited"; + EXPECT_EQ(backend->getCount(layout.refCatalogKey()), 0u); + EXPECT_EQ(backend->listCount(layout.namespaceRootPrefix()), 0u); + EXPECT_EQ(backend->getCount(layout.mountKey("ephemeral-node")), 0u); + } + + /// Publishing a new manifest immediately invalidates the idle baseline and forces a fold. + const ManifestRef r2{.writer_epoch = 1, .build_sequence = 2, .manifest_ordinal = 0xBB}; + writeBlobBody(*backend, layout, UInt128(2)); + writeManifestRaw(*backend, layout, ns, r2, {blobEntryFor("b", UInt128(2))}); + publishCommittedTransition(*backend, layout, ns, "tbl2", std::nullopt, r2); + + const RoundReport active_rep = gc.runRegularRound(); + EXPECT_FALSE(active_rep.deferred) << "a new ref publish must wake GC from idle short-circuit"; +}