From 4858112cd40a138f3fbf1534f571c5fd6ed5ba14 Mon Sep 17 00:00:00 2001 From: sabith Date: Wed, 18 Nov 2026 14:31:13 -0800 Subject: [PATCH] feat(cas): auto-prune expired empty fenced mount slots Adds cas_auto_forget_fenced_empty_after_sec (default 0, disabled) so the CAS GC leader automatically reclaims expired gc_fenced mount slots left behind by ephemeral ASG/pod instances once they own zero catalog namespaces and zero manifest/staging/data objects. 1. ContentAddressedSettings / PoolConfig / ContentAddressedMetadataStorage: add cas_auto_forget_fenced_empty_after_sec. 2. CasServerRoot: track all_fenced_srids in HeartbeatFloor and add pruneExpiredEmptyFencedServerRoots() which verifies m.gc_fenced, expiry age >= threshold, zero entries in cas/ref_catalog, and empty cas/manifests//, staging//, and roots// prefixes before exact-token deleting mount, epoch, and owner (aborting safely on any ETag Mismatch). 3. CasGc: invoke pruneExpiredEmptyFencedServerRoots() under leader authority after heartbeat_floor when configured. 4. Add ProfileEvents::CASGCAutoPrunedFencedMounts, unit tests in gtest_cas_decommission.cpp, and docs in docs/en/antalya/cas/configuration.md. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: sabith --- docs/en/antalya/cas/configuration.md | 1 + src/Common/ProfileEvents.cpp | 1 + .../ContentAddressedMetadataStorage.cpp | 3 + .../ContentAddressedMetadataStorage.h | 1 + .../ContentAddressedSettings.cpp | 1 + .../ContentAddressed/Gc/CasGc.cpp | 27 +++++ .../ContentAddressed/Pool/CasPool.h | 3 + .../ContentAddressed/Pool/CasServerRoot.cpp | 101 ++++++++++++++++++ .../ContentAddressed/Pool/CasServerRoot.h | 18 ++++ src/Disks/tests/gtest_cas_decommission.cpp | 98 +++++++++++++++++ 10 files changed, 254 insertions(+) diff --git a/docs/en/antalya/cas/configuration.md b/docs/en/antalya/cas/configuration.md index 0e0ec0aa4f66c..0807cde199479 100644 --- a/docs/en/antalya/cas/configuration.md +++ b/docs/en/antalya/cas/configuration.md @@ -100,6 +100,7 @@ entirely before release. Treat this table as a snapshot of the current build, no | `cas_mount_lease_ttl_ms` | `40000` | How long this server may write after its last confirmed renewal; every other server waits at least this long before fencing or reclaiming its slot (≥ 1, at most 600000 — a larger value is clamped to 10 minutes with a warning at startup, so no holder declares a longer lease). Lower values shorten recovery after this server's crash but reduce tolerance for object-storage and scheduling delays. Set `30000` for faster recovery after a crash, at the costs [below](#mount-lease-costs) | | `cas_mount_renew_period_ms` | `10000` | Milliseconds between background mount-lease renewals (≥ 1). It must leave enough time for two attempt envelopes (a renewal write and its settlement read) and the lease safety margin before the TTL expires: `period + 2 × envelope + margin < TTL` | | `cas_gc_snapshot_generations_to_keep` | `3` | GC snapshot generations retained. `0` is refused: set a large number instead. `1` is loaded as `2` with a warning: with one generation, a round that loses its commit can delete the generation the pool still adopts | +| `cas_auto_forget_fenced_empty_after_sec` | `0` | Automatically prune `gc_fenced` mount slots (`mount`, `epoch`, `owner`) once `expires_at_ms` is at least this many seconds old and the slot owns zero `cas/ref_catalog` namespaces and zero objects under `cas/manifests//`, `staging//`, and `roots//`. `0` disables automatic pruning; set e.g. `86400` for ephemeral ASG/pod `cas_server_root_id` deployments | | `cas_gc_shards` | `1` | Blob-hash-prefix reducer shards (≥ 1). Recorded in the pool at creation; a mismatching config is refused at mount | | `gcs_max_conditional_put_bytes` | 1 GiB | Largest conditional non-blob `PUT` on a generation-token store, including create-if-absent metadata/control artifacts and conditional replacements. Blob publication is unconditional, uses ordinary multipart, and is not subject to this cap | | `cas_part_folder_cache_bytes` | 64 MiB | Part-folder view cache byte budget (`0` disables retention) | diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp index c9b79615610b7..61c4e3c2fb6bb 100644 --- a/src/Common/ProfileEvents.cpp +++ b/src/Common/ProfileEvents.cpp @@ -980,6 +980,7 @@ The server successfully detected this situation and will download merged part fr M(CASGCRetiredRedeleteFailed, "The earlier name of CASGCRetiredBodyDeleteFailed, incremented together with it.", ValueType::Number) \ M(CASGCUnmatchedRemoveDeltas, "Number of CAS GC in-degree removal deltas that matched no existing source edge. The in-degree model is a set, not a counter, so this is a per-key no-op by design and never causes a false deletion — but a persistent nonzero rate means removal deltas are reaching the reducer without their matching activation, which is a correctness signal.", ValueType::Number) \ M(CASGCHeartbeatFenceOuts, "Number of CAS GC operations fenced out for expired mounts. A non-zero value indicates stale mounts or heartbeat delays.", ValueType::Number) \ + M(CASGCAutoPrunedFencedMounts, "Number of empty fenced CAS mount slots automatically pruned after cas_auto_forget_fenced_empty_after_sec.", ValueType::Number) \ M(CASBlobPublishDigestMismatch, "Number of streamed CAS blob publications refused because the payload did not hash to the blob's key. Any non-zero value means a corrupted or changed source.", ValueType::Number) \ M(CASGCEnumerationPages, "Number of CAS GC LIST pages fetched while enumerating the object universe. Growing values indicate a larger universe or more frequent scans.", ValueType::Number) \ M(CASBulkDeleteRequests, "Number of CAS batch delete requests: one DeleteObjects carrying up to 1000 write-once keys (manifest bodies, ref logs, ref snapshots). The per-key class counters (CASManifestDelete, CASRootDelete) say how many keys each request carried.", ValueType::Number) \ diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedMetadataStorage.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedMetadataStorage.cpp index 872baee99f817..fef0ec5df6cc0 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedMetadataStorage.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedMetadataStorage.cpp @@ -68,6 +68,7 @@ namespace ContentAddressedSetting extern const ContentAddressedSettingsBool gc_enabled; extern const ContentAddressedSettingsUInt64 gc_interval_sec; extern const ContentAddressedSettingsUInt64 gc_snapshot_generations_to_keep; + extern const ContentAddressedSettingsUInt64 auto_forget_fenced_empty_after_sec; extern const ContentAddressedSettingsUInt64 gc_shards; extern const ContentAddressedSettingsUInt64 manifest_sweep_list_budget_keys; extern const ContentAddressedSettingsUInt64 intent_sweep_list_budget_keys; @@ -295,6 +296,7 @@ ContentAddressedMetadataStorage::ContentAddressedMetadataStorage( , gc_enabled(settings_[ContentAddressedSetting::gc_enabled].value) , gc_interval(std::chrono::seconds(settings_[ContentAddressedSetting::gc_interval_sec].value)) , gc_snapshot_generations_to_keep(settings_[ContentAddressedSetting::gc_snapshot_generations_to_keep].value) + , cas_auto_forget_fenced_empty_after_sec(settings_[ContentAddressedSetting::auto_forget_fenced_empty_after_sec].value) , gc_shards(settings_[ContentAddressedSetting::gc_shards].value) , manifest_sweep_list_budget_keys(settings_[ContentAddressedSetting::manifest_sweep_list_budget_keys].value) , intent_sweep_list_budget_keys(settings_[ContentAddressedSetting::intent_sweep_list_budget_keys].value) @@ -817,6 +819,7 @@ ContentAddressedMetadataStorage::PoolView ContentAddressedMetadataStorage::openP pool_config.blob_hash_allow_new = blob_hash_allow_new; pool_config.manifest_decode_cache_bytes = manifest_decode_cache_bytes; pool_config.gc_snapshot_generations_to_keep = gc_snapshot_generations_to_keep; + pool_config.auto_forget_fenced_empty_after_sec = cas_auto_forget_fenced_empty_after_sec; pool_config.gc_shards = gc_shards; pool_config.manifest_sweep_list_budget_keys = manifest_sweep_list_budget_keys; pool_config.intent_sweep_list_budget_keys = intent_sweep_list_budget_keys; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedMetadataStorage.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedMetadataStorage.h index 0183da0cd34b4..ec56210f80e9e 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedMetadataStorage.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedMetadataStorage.h @@ -656,6 +656,7 @@ class ContentAddressedMetadataStorage final : public IMetadataStorage, public IC const bool gc_enabled; const std::chrono::seconds gc_interval; const uint64_t gc_snapshot_generations_to_keep; /// Number of GC snapshots retained (the disk setting refuses 0 and loads 1 as 2; `PoolConfig` 0 prunes nothing). + const uint64_t cas_auto_forget_fenced_empty_after_sec; const uint64_t gc_shards; /// Blob-hash-prefix reducer shard count, fixed at pool creation. const uint64_t manifest_sweep_list_budget_keys; const uint64_t intent_sweep_list_budget_keys; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp index 7933094762862..2358802c5b848 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp @@ -94,6 +94,7 @@ constexpr std::string_view CAS_KEY_PREFIX = "cas_"; 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, 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) \ + DECLARE(UInt64, auto_forget_fenced_empty_after_sec, 0, "Automatically prune fenced CAS mount slots that own zero catalog namespaces and zero manifest/staging/data objects after this many seconds past lease expiry (0 disables)", 0) \ DECLARE_SETTINGS_TRAITS(ContentAddressedSettingsTraits, LIST_OF_CONTENT_ADDRESSED_SETTINGS, CONTENT_ADDRESSED_SETTINGS_SUPPORTED_TYPES) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp index 39c2b289ad513..278d0e6daf3b6 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp @@ -949,6 +949,33 @@ 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 auto_prune_after_sec = store->poolConfig().auto_forget_fenced_empty_after_sec; + if (auto_prune_after_sec > 0 && !floor.all_fenced_srids.empty()) + { + refreshAuthority(state.lease.seq); + if (authority_held) + { + CasOperation prune_op = store->openRequests().admit([this] { return authority_held; }); + try + { + const CasRefCatalog::Snapshot cat = CasRefCatalog::read(prune_op, layout); + cat.life_index.throwIfAmbiguous("CAS GC fenced mount auto-prune"); + const CasEventSink event_sink = [this](CasEvent e) { store->emitEvent(std::move(e)); }; + const size_t pruned = pruneExpiredEmptyFencedServerRoots( + prune_op, layout, cat.catalog, floor.all_fenced_srids, + store->poolConfig().server_root_id, now_ms_fn(), auto_prune_after_sec, &event_sink); + t.metric("auto_pruned_fenced", pruned); + } + catch (const Exception & e) + { + if (e.code() == ErrorCodes::CORRUPTED_DATA) + LOG_WARNING(logger, "CAS GC skipped fenced mount auto-prune: {}", e.message()); + else + throw; + } + } + } } /// Decide DEFER vs FOLD from cheap pre-fold signals. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h index ed020b7b3c1c6..b8caaa14296d8 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h @@ -86,6 +86,9 @@ struct PoolConfig /// margin covering any in-flight/resuming leader (a leader more than `keep` generations behind /// has lost its lease; its round-commit CAS fails). uint64_t gc_snapshot_generations_to_keep = 3; + /// Auto-prune fenced mount slots that own zero catalog namespaces and zero manifest/staging/data + /// objects after this many seconds past lease expiry. 0 = disabled. + uint64_t auto_forget_fenced_empty_after_sec = 0; /// Blob target shards for GC. Default 1 (a single shard, i.e. no fan-out). Creation-time only; /// the pool is authoritative on reopen. This is the BLOB-HASH-prefix reducer axis. uint64_t gc_shards = 1; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp index aba6503d21a38..cfce67b2f207b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp @@ -32,6 +32,7 @@ namespace ProfileEvents { extern const Event CASMountReleaseSkippedForeignOccupant; extern const Event CASMountExclusivityViolation; + extern const Event CASGCAutoPrunedFencedMounts; } namespace DB @@ -1386,6 +1387,7 @@ HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64 if (m.gc_fenced) { ++floor.already_fenced; + floor.all_fenced_srids.push_back(srid); obs.erase(srid); /// terminal — no further observation needed return std::nullopt; } @@ -1427,6 +1429,7 @@ HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64 { ++floor.fenced_now; floor.fenced_srids.push_back(srid); + floor.all_fenced_srids.push_back(srid); obs.erase(srid); LOG_INFO(getLogger("CasHeartbeatFloor"), "CAS GC fenced out mount lease for content-addressed server root {} at " @@ -1451,6 +1454,104 @@ HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64 return floor; } +size_t pruneExpiredEmptyFencedServerRoots( + CasOperation & op, + const Layout & layout, + const RefCatalog & catalog, + const std::vector & candidate_fenced_srids, + const String & own_srid, + uint64_t now_ms, + uint64_t after_sec, + const CasEventSink * event_sink) +{ + if (after_sec == 0 || candidate_fenced_srids.empty()) + return 0; + + const uint64_t after_ms = after_sec <= std::numeric_limits::max() / 1000 + ? after_sec * 1000 + : std::numeric_limits::max(); + size_t pruned = 0; + + for (const String & srid : candidate_fenced_srids) + { + if (srid.empty() || srid == own_srid) + continue; + if (!op.admitted()) + break; + + const String srid_prefix = srid + "/"; + const bool owns_catalog_entry = std::any_of( + catalog.entries.begin(), catalog.entries.end(), + [&](const CatalogEntry & entry) + { + return entry.ns.string() == srid || entry.ns.string().starts_with(srid_prefix); + }); + if (owns_catalog_entry) + continue; + + const String mount_key = layout.mountKey(srid); + const std::optional mount_got = op.read(mount_key, Retry::standard()); + if (!mount_got) + continue; + + MountLease mount_lease; + try + { + mount_lease = decodeMountLease(mount_got->bytes); + } + catch (...) + { + continue; + } + if (!mount_lease.gc_fenced) + continue; + if (now_ms <= mount_lease.expires_at_ms || (now_ms - mount_lease.expires_at_ms) < after_ms) + continue; + + if (prefixHasAnyKey(op, layout.casManifestsServerPrefix(srid)) + || prefixHasAnyKey(op, layout.stagingPrefix(srid)) + || prefixHasAnyKey(op, layout.serverRootDataPrefix(srid))) + continue; + + if (!op.admitted()) + break; + + const Removal mount_rm = op.remove(mount_key, mount_got->etag, Retry::standard()); + if (mount_rm == Removal::Mismatch) + continue; + + auto remove_if_present = [&](const String & key) -> bool + { + const std::optional got = op.read(key, Retry::standard()); + if (!got) + return true; + return op.remove(key, got->etag, Retry::standard()) != Removal::Mismatch; + }; + + if (remove_if_present(layout.epochKey(srid))) + (void)remove_if_present(layout.ownerKey(srid)); + + ++pruned; + ProfileEvents::increment(ProfileEvents::CASGCAutoPrunedFencedMounts); + LOG_INFO(getLogger("CasHeartbeatFloor"), + "Auto-pruned empty fenced CAS mount slot '{}' (expired {} ms ago, threshold {} ms)", + srid, now_ms - mount_lease.expires_at_ms, after_ms); + if (event_sink && *event_sink) + { + CasEvent e; + e.type = CasEventType::MemberDecommission; + e.outcome = "auto_pruned"; + e.reason = "auto-pruned empty fenced mount slot past cas_auto_forget_fenced_empty_after_sec"; + e.detail = { + {"server_root_id", srid}, + {"expired_age_ms", std::to_string(now_ms - mount_lease.expires_at_ms)}}; + (*event_sink)(std::move(e)); + } + } + + return pruned; +} + std::vector probeNonTerminalMountSlots(CasOperation & op, const Layout & l) { std::vector slots; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.h index 6eb1d2f55038b..52c7b9ca5b5a8 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.h @@ -471,6 +471,9 @@ struct HeartbeatFloor size_t already_fenced = 0; /// The srids of every mount fenced-out THIS call (one GcFenceOut audit event each). std::vector fenced_srids; + /// All srids observed as `gc_fenced` (both newly fenced and already fenced), used when + /// `cas_auto_forget_fenced_empty_after_sec > 0`. + std::vector all_fenced_srids; }; HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64_t now_ms, @@ -478,6 +481,21 @@ HeartbeatFloor computeHeartbeatFloor(CasOperation & op, const Layout & l, uint64 uint64_t observer_lease_ms, uint64_t cadence_ms, MountObservationMap & obs, std::set & lease_mismatch_warned); +/// Auto-prune `gc_fenced` mount slots whose `expires_at_ms` is at least `after_sec` seconds in the +/// past, provided the slot owns zero entries in `catalog` (`Creating`, `Live`, or `Removing`) and +/// zero objects under its manifest, staging, and data prefixes. Deletes `mount`, `epoch`, and `owner` +/// via exact-token `op.remove`, aborting safely on any `Mismatch`. Never prunes `own_srid`. +/// Returns the number of mount slots pruned. +size_t pruneExpiredEmptyFencedServerRoots( + CasOperation & op, + const Layout & layout, + const RefCatalog & catalog, + const std::vector & candidate_fenced_srids, + const String & own_srid, + uint64_t now_ms, + uint64_t after_sec, + const CasEventSink * event_sink = 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_decommission.cpp b/src/Disks/tests/gtest_cas_decommission.cpp index 66c9aa395142b..69fdc66174063 100644 --- a/src/Disks/tests/gtest_cas_decommission.cpp +++ b/src/Disks/tests/gtest_cas_decommission.cpp @@ -3039,3 +3039,101 @@ TEST(CASRejoin, ZeroUuidDoesNotRejoin) EXPECT_EQ(readSlot(*backend, layout, "victim").seq, slot_before.seq); } } + +TEST(CASAutoPruneFencedMounts, PrunesEmptyExpiredFencedSlotAfterThreshold) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + auto now_ms = std::make_shared>(1'000'000); + auto store = Pool::open(backend, PoolConfig{ + .pool_prefix = "p", + .server_root_id = "leader", + .auto_forget_fenced_empty_after_sec = 86400}); + + OperationForTest seed_op(*backend); + const MountLease fenced_empty{ + .server_uuid = UInt128(0xAA01), + .writer_epoch = 1, + .hostname = "asg-old", + .pid = 10, + .started_at_ms = 100, + .seq = 1, + .expires_at_ms = 1'000'000, + .min_active_build_sequence = 0, + .gc_fenced = true, + .write_attempt_id = UInt128(1)}; + ASSERT_TRUE(std::holds_alternative( + (*seed_op).create(layout.mountKey("asg-old"), encodeMountLease(fenced_empty), Retry::once()))); + ASSERT_TRUE(std::holds_alternative( + (*seed_op).create(layout.epochKey("asg-old"), encodeServerEpoch(ServerEpoch{.next_writer_epoch = 2}), Retry::once()))); + ASSERT_TRUE(std::holds_alternative( + (*seed_op).create(layout.ownerKey("asg-old"), encodeOwner(OwnerObject{.server_uuid = UInt128(0xAA01)}), Retry::once()))); + + /// Before TTL elapses: slot is preserved. + { + Gc gc(store, UInt128(0x9C01), [now_ms] { return now_ms->load(); }); + ASSERT_TRUE(gc.runRegularRound().acquired_lease); + EXPECT_TRUE((*seed_op).head(layout.mountKey("asg-old"), Retry::once()).has_value()); + } + + /// Advance wall clock past 86400s: empty fenced slot is pruned (mount, epoch, owner removed). + now_ms->store(1'000'000 + 86400ULL * 1000 + 1); + { + Gc gc(store, UInt128(0x9C02), [now_ms] { return now_ms->load(); }); + ASSERT_TRUE(gc.runRegularRound().acquired_lease); + EXPECT_FALSE((*seed_op).head(layout.mountKey("asg-old"), Retry::once()).has_value()); + EXPECT_FALSE((*seed_op).head(layout.epochKey("asg-old"), Retry::once()).has_value()); + EXPECT_FALSE((*seed_op).head(layout.ownerKey("asg-old"), Retry::once()).has_value()); + } +} + +TEST(CASAutoPruneFencedMounts, SkipsFencedSlotWithCatalogNamespaceOrManifestDebris) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + auto now_ms = std::make_shared>(100'000'000); + auto store = Pool::open(backend, PoolConfig{ + .pool_prefix = "p", + .server_root_id = "leader", + .auto_forget_fenced_empty_after_sec = 60}); + + OperationForTest seed_op(*backend); + const MountLease fenced_with_ns{ + .server_uuid = UInt128(0xBB01), + .writer_epoch = 1, + .hostname = "asg-ns", + .pid = 11, + .started_at_ms = 100, + .seq = 1, + .expires_at_ms = 1000, + .min_active_build_sequence = 0, + .gc_fenced = true, + .write_attempt_id = UInt128(2)}; + ASSERT_TRUE(std::holds_alternative( + (*seed_op).create(layout.mountKey("asg-ns"), encodeMountLease(fenced_with_ns), Retry::once()))); + CasRefCatalog::casAdmitEntry(*seed_op, layout, 1, CatalogEntry{ + .ns = RootNamespace{"asg-ns/table1"}, + .state = NsState::Live, + .incarnation = UInt128(0xCC01)}); + + const MountLease fenced_with_manifest{ + .server_uuid = UInt128(0xBB02), + .writer_epoch = 1, + .hostname = "asg-manifest", + .pid = 12, + .started_at_ms = 100, + .seq = 1, + .expires_at_ms = 1000, + .min_active_build_sequence = 0, + .gc_fenced = true, + .write_attempt_id = UInt128(3)}; + ASSERT_TRUE(std::holds_alternative( + (*seed_op).create(layout.mountKey("asg-manifest"), encodeMountLease(fenced_with_manifest), Retry::once()))); + const ManifestRef ref{.writer_epoch = 1, .build_sequence = 1, .manifest_ordinal = 1}; + writeManifestRaw(*backend, layout, RootNamespace{"asg-manifest/t"}, ref, {}); + + Gc gc(store, UInt128(0x9C03), [now_ms] { return now_ms->load(); }); + ASSERT_TRUE(gc.runRegularRound().acquired_lease); + EXPECT_TRUE((*seed_op).head(layout.mountKey("asg-ns"), Retry::once()).has_value()); + EXPECT_TRUE((*seed_op).head(layout.mountKey("asg-manifest"), Retry::once()).has_value()); +}