diff --git a/docs/concepts/features/configuration/server-config/storing-data.mdx b/docs/concepts/features/configuration/server-config/storing-data.mdx index 74458761d9c76..838aded4ec38f 100644 --- a/docs/concepts/features/configuration/server-config/storing-data.mdx +++ b/docs/concepts/features/configuration/server-config/storing-data.mdx @@ -547,7 +547,7 @@ disk-level and server-level settings surface. `0` disables decode caching entirely (a diagnostic mode). - `cas_gc_meta_pool_size` — declared and ignored: `GC` writes no per-blob metadata objects. A configuration that sets it still loads; the server logs a warning at start when it is set to a value other than the default. -- `cas_gc_io_concurrency` — `16` by default. Bounded thread-pool size for the GC object-storage requests +- `cas_gc_io_concurrency` — `48` by default. Bounded thread-pool size for the GC object-storage requests that run in parallel. It covers: - the fold's read-ahead of checkpoints, ref logs, manifest bodies and zero-candidate `HEAD`s; - the planning reads of the orphan-manifest sweep and the read-ahead of `SYSTEM CAS GC REBUILD`; diff --git a/docs/en/antalya/cas/architecture/garbage-collection.md b/docs/en/antalya/cas/architecture/garbage-collection.md index eed248b17f949..84f661522f6ce 100644 --- a/docs/en/antalya/cas/architecture/garbage-collection.md +++ b/docs/en/antalya/cas/architecture/garbage-collection.md @@ -441,15 +441,16 @@ proof that nothing was appended. When the GC process does not remember the curso can issue additional `GET`s: none in some cases, several when it follows links across epochs. **Read-ahead.** The checkpoint, walk-position, manifest-edge and (in phase 10) zero-candidate `HEAD` -reads are hinted ahead onto a bounded pool (`cas_gc_io_concurrency`, default 16; `1` runs the reads inline) and +reads are hinted ahead onto a bounded pool (`cas_gc_io_concurrency`, default 48; `1` runs the reads inline) and taken by the walk at exactly the sites, and in exactly the order, of the inline reads, so every -decision, decode, counter and event stays on the round thread and, for the same completed work, the -phase's semantic metrics do not depend on the setting. Two things do: a request a worker performed lands on that worker's +decision, decode, counter and event stays on the round thread. For the same completed work, the phase's metrics do +not depend on the setting, except the ones that describe the read-ahead itself: `*_reads_issued`, `*_awaited`, +`*_wait_us`, `*_apply_us`, `*_hinted_at_settle`, and the `candidate_head_*` and `pending_head_*` keys other than their `_takes`. The three kinds of `HEAD` the merge reads ahead (candidates, pending rows, spared rows) each keep a window of their own, so a run of one kind cannot hold the look-ahead of another. Two more things do: a request a worker performed lands on that worker's `ProfileEvents`, not the phase row's, and a hinted key the walk never takes is a wasted request: ref logs and manifests of later ref logs read ahead of a walk that stops at a hold, at the end of its time slice or at a stop request, and a `HEAD` candidate that kept an edge. `CASGCReadAheadHit` and `CASGCReadAheadMiss` are charged to the phase that takes the result. `CASGCReadAheadWasted` is counted on the phase-8 row when a walk drops its unused reads, -and in the round-level `ProfileEvents` for reads still untaken when the reader is destroyed after phase 11. +on the phase-10 row for `HEAD`s read ahead in the merge and not taken, and in the round-level `ProfileEvents` for reads still untaken when the reader is destroyed after phase 11. ## Phase 9 — intent sweep list {#phase-9-intent-sweep-list} @@ -509,7 +510,10 @@ Recomputes the per-shard in-degree snapshot and computes the round's single dest deletes decided), `adopted` (orphan intents given a row), `nominations_waiting` (nominated intents of a shard that stayed a pure carry), `read_ahead_blobs` (blobs held to read row `HEAD`s ahead), `suppress_destructive`, `frontier_complete`, `parent_unconfirmed`, `condemned_rows` (rows the round leaves on - file: `candidate`, `pending` and `standing`) and `pending_rows` (`pending` and `standing` rows among them) + file: `candidate`, `pending` and `standing`), `pending_rows` (`pending` and `standing` rows among them), and the + `candidate_head_*`, `pending_head_*`, `intent_create*` and `head_discard_wait_us` keys: how the + `HEAD`s and intent creates of the merge were served and how long the round thread waited for them (see + [`system.cas_gc_log`](/operations/system-tables/cas_gc_log)) `suppress_destructive` is true on any recorded anomaly, any hold in the seal about to be made durable, an incomplete frontier (`frontier_proven ≠ frontier_namespaces`, a universe neither @@ -789,7 +793,13 @@ without that wait. (mount-floor lookups per namespace and the reads they cost), `deleted`, `skipped`, `undecodable`, `cursor_advanced`, `suppressed`, and the retained share of `skipped` by reason: `retained_no_coverage`, `retained_hold`, `retained_unconsumed_seal`, `retained_tail_removal`, - `retained_work_budget` (candidates retained because the sweep's work budget ran out) + `retained_work_budget` (candidates retained because the sweep's work budget ran out). + `retained_before_view` counts keys refused before their namespace's protection view was built. + The sweep has not checked who owns them, so they can be live parts. They are in `skipped`, not in + any other `retained_*` metric, and the sweep does not build a view for a namespace whose keys are + all refused this way. An unowned body of the epoch the namespace's fold cursor is in is counted + here, not in `retained_unconsumed_seal`, unless an older build of the same namespace earlier on the + page already built the view. Under `suppress_destructive` phase 10 planned nothing, so the nomination list is empty and the cursor does not move. @@ -1114,7 +1124,7 @@ disables the sweep and `cas_manifest_sweep_delete_budget_keys = 0` lists without | `cas_gc_round_sweep_namespace_budget` | 20 | namespaces whose protection view the sweep may build per page (phase 10) | | `cas_gc_round_sweep_recovery_op_budget` | 5000 | committed-tail ref-log reads the sweep's recovery walk may spend (phase 10) | | `cas_gc_bulk_delete_chunk_keys` | 1000 | keys per batch `DELETE` request for write-once families (phases 15, 17); `1` to `1000` | -| `cas_gc_io_concurrency` | 16 | bounded pool for the fold's read-ahead of checkpoints, ref logs, manifest bodies and zero-candidate `HEAD`s (phases 8, 10), the orphan-sweep planning reads (phase 10), the rebuild read-ahead and the `pending_deletes` conditional `DELETE` fan-out (phase 12); other GC requests 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_gc_io_concurrency` | 48 | bounded pool for the fold's read-ahead of checkpoints, ref logs, manifest bodies and zero-candidate `HEAD`s (phases 8, 10), the orphan-sweep planning reads (phase 10), the rebuild read-ahead and the `pending_deletes` conditional `DELETE` fan-out (phase 12); other GC requests 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 | The fold-batching controls `gc_fold_threshold` (default 1), `gc_fold_max_defer_rounds` (default 8) and `gc_frontier_probe_budget` (default unbounded) are internal `PoolConfig` fields with no disk diff --git a/docs/en/antalya/cas/configuration.md b/docs/en/antalya/cas/configuration.md index c4faa4bf49ffc..5dab4351ba653 100644 --- a/docs/en/antalya/cas/configuration.md +++ b/docs/en/antalya/cas/configuration.md @@ -106,7 +106,7 @@ entirely before release. Treat this table as a snapshot of the current build, no | `cas_part_folder_cache_max_entries` | `10000` | Part-folder view cache entry cap | | `cas_part_folder_cache_max_entry_bytes` | 16 MiB | Oversized part-folder views bypass retention above this size | | `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_gc_io_concurrency` | `48` | 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. On a store with a network round trip the pool is what limits a GC round: on S3 and GCS a drain of a fixed backlog was about twice as fast at `48` as at `16`. On a store that is bound by its own write rate the value changes nothing. The default was `16` before; a server that takes the new default sends up to three times as many GC requests at once, the conditional blob `DELETE`s included. Set `16` to keep the old behavior, for example when GC and the writers share a store that answers `SlowDown`. `clickhouse-disks cas-migrate-pool --concurrency` takes its default from this setting. `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 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 | diff --git a/docs/en/operations/system-tables/cas_gc_log.md b/docs/en/operations/system-tables/cas_gc_log.md index 68e76dbb294a5..c15308b254ca7 100644 --- a/docs/en/operations/system-tables/cas_gc_log.md +++ b/docs/en/operations/system-tables/cas_gc_log.md @@ -92,7 +92,7 @@ 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; when the orphan-manifest sweep is planned, its manifest `LIST` page and the `GET`s that decide its nominations | +| `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). Six keys cover the `HEAD` of each blob that lost its last reference in this round and has no row yet: `candidate_head_reads_issued` (requests started, ahead of time or at the moment the fold needs the result), `candidate_head_takes` (results the fold consumed), `candidate_head_awaited` (takes whose result was not ready when the fold asked for it; `candidate_head_takes` minus this is the number that were ready ahead), `candidate_head_unhinted` (requests made at that moment because none was started ahead), `candidate_head_discarded` (requests started ahead for blobs the merge passed without needing them, for example because the blob kept a reference from another part; each is one unused `HEAD`) and `candidate_head_wait_us` (time the GC thread spent waiting for the results it consumed; the wait to drop an unused request is in `head_discard_wait_us`). Six keys cover the `HEAD` before the body delete of each `pending` row the same way: `pending_head_reads_issued`, `pending_head_takes`, `pending_head_awaited`, `pending_head_discarded`, `pending_head_wait_us`, and `pending_head_hinted_at_settle` (rows whose `HEAD` was started only when the fold reached the row, because the look-ahead had not offered it; such a request is a serial one). `intent_creates_awaited` and `intent_create_wait_us` count the intent creates whose answer was not ready when the fold needed it and the time it waited for them; `head_discard_wait_us` is the time the GC thread spent waiting for hinted `HEAD`s the merge dropped unused. The `*_awaited`, `*_wait_us` and `*_hinted_at_settle` keys depend on `cas_gc_io_concurrency`; the takes do not. | 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 | diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp index 59ec17f6724d5..e99efb3b38339 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp @@ -88,7 +88,7 @@ constexpr std::string_view CAS_KEY_PREFIX = "cas_"; DECLARE(Bool, allow_packed_parts, false, "Allow new MergeTree parts on this disk to use the Packed format", 0) \ DECLARE(UInt64, manifest_decode_cache_bytes, 128ULL << 20, "Manifest DECODE cache byte budget (0 disables)", 0) \ DECLARE(UInt64, gc_meta_pool_size, 16, "Ignored: GC writes no per-blob metadata objects", SettingsTierType::OBSOLETE) \ - 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_io_concurrency, 48, "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 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) \ diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp index 61e50cc27e750..e489854611400 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp @@ -1701,12 +1701,13 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al /// closed-and-folded epoch, so a pass in which everything examined was RETAINED is an ordinary /// outcome, and without these numbers it is indistinguishable on the row from a pass that found /// nothing to do. - /// A row where `deleted` is 0 and all five are 0 means the sweep genuinely had no candidates. + /// A row where `deleted` and every `retained_*` metric are 0 means the sweep genuinely had no candidates. t.metric("retained_no_coverage", sweep.retained_no_coverage); t.metric("retained_hold", sweep.retained_hold); t.metric("retained_unconsumed_seal", sweep.retained_unconsumed_seal); t.metric("retained_tail_removal", sweep.retained_tail_removal); t.metric("retained_work_budget", sweep.retained_work_budget); + t.metric("retained_before_view", sweep.retained_before_view); } uint64_t cleanup_evidence_rows = 0; @@ -2562,16 +2563,32 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, /// /// Hints are issued from INSIDE the lambda rather than in one burst at phase start, so the requests /// this can ever add are bounded by one window past the last candidate the merge actually reaches. - /// A superset that overshoots badly therefore costs a window, not its own size -- which matters - /// because nothing bounds a round's condemnation count. std::vector> head_candidates(state.gc_shards); size_t head_hint_shard = 0; + /// The candidates in `[first_live_hint, next_head_hint)` are hinted; the ones a take consumed hold no slot. + size_t first_live_hint = 0; size_t next_head_hint = 0; - const auto topUpHeadHints = [&] + /// Blobs close in strictly ascending order within a shard, so a candidate below `ref` is never taken: its slot + /// is freed and an unhinted one is skipped. Otherwise a run of candidates that keep an edge fills the window. + const auto topUpHeadHints = [&](const BlobRef & ref) { const std::vector & shard_candidates = head_candidates[head_hint_shard]; - while (next_head_hint < shard_candidates.size() && reads.pendingHeads() < reads.window()) - reads.hintHead(layout.blobKey(shard_candidates[next_head_hint++])); + for (; first_live_hint < next_head_hint && shard_candidates[first_live_hint] < ref; ++first_live_hint) + reads.discardHead(layout.blobKey(shard_candidates[first_live_hint]), ReadFamily::CandidateHead); + if (first_live_hint == next_head_hint) + { + while (next_head_hint < shard_candidates.size() && shard_candidates[next_head_hint] < ref) + ++next_head_hint; + first_live_hint = next_head_hint; + } + while (next_head_hint < shard_candidates.size() && reads.pendingHeads(ReadFamily::CandidateHead) < reads.window()) + reads.hintHead(layout.blobKey(shard_candidates[next_head_hint++]), ReadFamily::CandidateHead); + }; + const auto discardLiveHeadHints = [&] + { + const std::vector & shard_candidates = head_candidates[head_hint_shard]; + for (; first_live_hint < next_head_hint; ++first_live_hint) + reads.discardHead(layout.blobKey(shard_candidates[first_live_hint]), ReadFamily::CandidateHead); }; /// Condemn-time observation: ONE HEAD per new zero-transition captures the exact incarnation token @@ -2626,8 +2643,8 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, e.gen = state.snap_generation + 1; e.reason = "last folded owner edge dropped; in-degree reached 0"; }); - topUpHeadHints(); - const std::optional observed = reads.takeHead(layout.blobKey(ref)); + topUpHeadHints(ref); + const std::optional observed = reads.takeHead(layout.blobKey(ref), ReadFamily::CandidateHead); EventEmitter{*store}.emit([&](CasEvent & e) { e.type = CasEventType::GcRetireObserve; @@ -2674,6 +2691,8 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, std::unordered_set spare_head_reserved; /// The pending row whose redelete slot the fold has taken and whose `HEAD` it takes next. std::optional settling_pending_head; + /// Pending rows whose `HEAD` no scan had hinted when the fold settled them. + uint64_t pending_heads_hinted_at_settle = 0; /// The `HEAD` before a pending row's body delete, taken when the merge settles the row. It is sent in the /// merge, so after the round's cut and before the row's run is written. A failed `HEAD` fails the round before @@ -2685,7 +2704,7 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, settling_pending_head.reset(); try { - return blobHeadOf(ref, reads.takeHead(key)); + return blobHeadOf(ref, reads.takeHead(key, ReadFamily::PendingHead)); } catch (...) { @@ -2707,7 +2726,7 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, spare_head_reserved.erase(key); try { - return blobHeadOf(ref, reads.takeHead(key), /*spared*/ true); + return blobHeadOf(ref, reads.takeHead(key, ReadFamily::SpareHead), /*spared*/ true); } catch (...) { @@ -4505,9 +4524,9 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, /// A row the rotation skips this round is carried without its `HEAD`. if (!work_budget.redeletes.admits(blobShard(ref, state.gc_shards), ref)) return true; - if (reads.pendingHeads() >= reads.window()) + if (reads.pendingHeads(ReadFamily::PendingHead) >= reads.window()) return false; - reads.hintHead(key); + reads.hintHead(key, ReadFamily::PendingHead); pending_head_reserved.insert(key); return true; }; @@ -4519,9 +4538,9 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, const String key = layout.blobKey(ref); if (spare_head_reserved.contains(key)) return true; - if (reads.pendingHeads() >= reads.window()) + if (reads.pendingHeads(ReadFamily::SpareHead) >= reads.window()) return false; - reads.hintHead(key); + reads.hintHead(key, ReadFamily::SpareHead); spare_head_reserved.insert(key); return true; }; @@ -4542,25 +4561,29 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, { const String key = layout.blobKey(ref); if (pending_head_reserved.erase(key) == 0) - reads.hintHead(key); + { + reads.hintHead(key, ReadFamily::PendingHead); + ++pending_heads_hinted_at_settle; + } settling_pending_head = key; }, .take_spare = [&](const BlobRef & ref) { const String key = layout.blobKey(ref); if (spare_head_reserved.insert(key).second) - reads.hintHead(key); + reads.hintHead(key, ReadFamily::SpareHead); }}; const PendingHeadHints * pending_hints = reads.window() > 0 ? &pending_head_hints : nullptr; /// A reservation left after a shard's merge belongs to no settlement. const auto discardReservedReads = [&] { for (const String & key : pending_head_reserved) - reads.discardHead(key); + reads.discardHead(key, ReadFamily::PendingHead); pending_head_reserved.clear(); for (const String & key : spare_head_reserved) - reads.discardHead(key); + reads.discardHead(key, ReadFamily::SpareHead); spare_head_reserved.clear(); + discardLiveHeadHints(); }; /// A nomination alone does not take a shard off the pure carry, or an idle pool with one intent left over a @@ -4613,6 +4636,7 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, /// Empty deltas still settle the `RunMarker::Condemned` rows riding the parent run. Two replicas may /// run reducers for DIFFERENT shards concurrently (CasGcScheduler ownership); their run keys never collide. head_hint_shard = shard; + first_live_hint = 0; next_head_hint = 0; RunRef shard_run; bool absence_classified = false; @@ -4726,6 +4750,24 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, } reduce_timer->metric("condemned_rows", condemned_rows); reduce_timer->metric("pending_rows", pending_rows); + const ReadFamilyStats & candidate_heads = reads.familyStats(ReadFamily::CandidateHead); + reduce_timer->metric("candidate_head_reads_issued", candidate_heads.issued); + reduce_timer->metric("candidate_head_takes", candidate_heads.takes); + reduce_timer->metric("candidate_head_awaited", candidate_heads.awaited); + reduce_timer->metric("candidate_head_unhinted", candidate_heads.unhinted); + reduce_timer->metric("candidate_head_discarded", candidate_heads.discarded); + reduce_timer->metric("candidate_head_wait_us", candidate_heads.wait_ns / 1000); + const ReadFamilyStats & pending_heads = reads.familyStats(ReadFamily::PendingHead); + reduce_timer->metric("pending_head_reads_issued", pending_heads.issued); + reduce_timer->metric("pending_head_takes", pending_heads.takes); + reduce_timer->metric("pending_head_awaited", pending_heads.awaited); + reduce_timer->metric("pending_head_hinted_at_settle", pending_heads_hinted_at_settle); + reduce_timer->metric("pending_head_discarded", pending_heads.discarded); + reduce_timer->metric("pending_head_wait_us", pending_heads.wait_ns / 1000); + const GcReadAhead::WaitStats & waits = reads.waitStats(); + reduce_timer->metric("intent_creates_awaited", waits.creates_awaited); + reduce_timer->metric("intent_create_wait_us", waits.create_wait_ns / 1000); + reduce_timer->metric("head_discard_wait_us", waits.head_discard_wait_ns / 1000); } reduce_timer.reset(); /// emits the `fold_reduce` row diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp index c3faf732d4515..086e695856383 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp @@ -70,7 +70,10 @@ void GcReadAhead::hint(Slots & slots, const String & key, Request request, Re return; auto slot = std::make_shared>(); + slot->family = family; slots.emplace(key, slot); + if constexpr (std::is_same_v) + ++head_slots_by_family[static_cast(family)]; try { /// The worker joins a manual round's query, so the query's stop vetoes the worker's retry of a failed request. @@ -100,6 +103,8 @@ void GcReadAhead::hint(Slots & slots, const String & key, Request request, Re /// Drop it and let the take read inline; the scheduling failure itself propagates to the /// hinting site, which is a round-thread site like any other. slots.erase(key); + if constexpr (std::is_same_v) + --head_slots_by_family[static_cast(family)]; throw; } if (accounts(family)) @@ -123,6 +128,8 @@ std::optional GcReadAhead::take(Slots & slots, const String & key, Inline { slot = std::move(it->second); slots.erase(it); + if constexpr (std::is_same_v) + --head_slots_by_family[static_cast(slot->family)]; ProfileEvents::increment(ProfileEvents::CASGCReadAheadHit); } else @@ -145,6 +152,7 @@ std::optional GcReadAhead::take(Slots & slots, const String & key, Inline { ++family_stats->issued; ++family_stats->awaited; + ++family_stats->unhinted; } else { @@ -181,33 +189,41 @@ void GcReadAhead::hintRead(const String & key, ReadFamily family) [](CasOperation & worker, const String & k) { return worker.read(k, Retry::standard()); }, family); } -void GcReadAhead::hintHead(const String & key) +void GcReadAhead::hintHead(const String & key, ReadFamily family) { hint(heads, key, - [](CasOperation & worker, const String & k) { return worker.head(k, Retry::standard()); }, ReadFamily::Other); + [](CasOperation & worker, const String & k) { return worker.head(k, Retry::standard()); }, family); } template -void GcReadAhead::discard(Slots & slots, const String & key) +void GcReadAhead::discard(Slots & slots, const String & key, ReadFamily family) { const auto it = slots.find(key); if (it == slots.end()) return; std::shared_ptr> slot = std::move(it->second); slots.erase(it); + if constexpr (std::is_same_v) + --head_slots_by_family[static_cast(slot->family)]; /// `wait`, not `get`: the result and any exception belong to a request nobody wanted. + const bool timed = clock_ns != nullptr && std::is_same_v; + const UInt64 wait_from_ns = timed ? steadyNowNs() : 0; slot->future.wait(); + if (timed) + wait_stats.head_discard_wait_ns += steadyNowNs() - wait_from_ns; ProfileEvents::increment(ProfileEvents::CASGCReadAheadWasted); + if (accounts(family)) + ++stats[static_cast(family)].discarded; } void GcReadAhead::discardRead(const String & key) { - discard(reads, key); + discard(reads, key, ReadFamily::Other); } -void GcReadAhead::discardHead(const String & key) +void GcReadAhead::discardHead(const String & key, ReadFamily family) { - discard(heads, key); + discard(heads, key, family); } std::function GcReadAhead::startCreate(std::function request) @@ -268,6 +284,13 @@ std::function GcReadAhead::startCreate(std::function GcReadAhead::takeRead(const String & key, ReadFamily famil [](CasOperation & inline_op, const String & k) { return inline_op.read(k, Retry::standard()); }, family); } -std::optional GcReadAhead::takeHead(const String & key) +std::optional GcReadAhead::takeHead(const String & key, ReadFamily family) { return take(heads, key, - [](CasOperation & inline_op, const String & k) { return inline_op.head(k, Retry::standard()); }, ReadFamily::Other); + [](CasOperation & inline_op, const String & k) { return inline_op.head(k, Retry::standard()); }, family); } const Object * GcReadAhead::peekRead(const String & key) const diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.h index 67d70f3a4ae2d..31080d08d26b6 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.h @@ -20,12 +20,18 @@ namespace DB::Cas { -/// The source a tagged read belongs to, for the fold's per-family intake accounting. `Other` is never counted. +/// The source a tagged read belongs to, for the fold's per-family accounting. `Other` is never counted. enum class ReadFamily : uint8_t { RefCheckpoint, RefLog, Manifest, + /// The `HEAD` of a blob the reduce may bring to in-degree zero with no row. + CandidateHead, + /// The `HEAD` before the body delete of a pending row. + PendingHead, + /// The `HEAD` of a row whose blob gained a reference in this round. + SpareHead, Other, }; @@ -35,6 +41,8 @@ struct ReadFamilyStats UInt64 issued = 0; UInt64 takes = 0; UInt64 awaited = 0; + UInt64 unhinted = 0; + UInt64 discarded = 0; UInt64 wait_ns = 0; UInt64 apply_ns = 0; @@ -81,10 +89,10 @@ class GcReadAhead GcReadAhead & operator=(const GcReadAhead &) = delete; void hintRead(const String & key, ReadFamily family = ReadFamily::Other); - void hintHead(const String & key); + void hintHead(const String & key, ReadFamily family = ReadFamily::Other); std::optional takeRead(const String & key, ReadFamily family = ReadFamily::Other); - std::optional takeHead(const String & key); + std::optional takeHead(const String & key, ReadFamily family = ReadFamily::Other); /// The body of a hinted read whose worker already answered present, without taking it. Null when `key` is not /// hinted, not answered yet, answered absent, or failed. Never blocks and counts nothing. Owner thread only; the @@ -94,7 +102,8 @@ class GcReadAhead /// Starts counting tagged reads on this object; off until called, and then an untagged read is still /// not counted, polls nothing and reads no clock. Per family: `issued` counts accepted hints and inline /// takes; `takes` every take, absent or throwing included; `awaited` inline takes and hinted takes - /// whose result was not ready at one poll before `get`; `wait_ns` the time from the take's entry + /// whose result was not ready at one poll before `get`; `unhinted` the inline takes; `discarded` hinted + /// keys dropped by `discardHead`; `wait_ns` the time from the take's entry /// to its result (the whole read when inline); `apply_ns` the time from a take's return to the next tagged take /// or `closeApply`. Owner thread only; `clock` is the seam for a fake clock. void enableFamilyAccounting(UInt64 (*clock)() noexcept = &steadyNowNs); @@ -102,13 +111,24 @@ class GcReadAhead void closeApply(); const ReadFamilyStats & familyStats(ReadFamily family) const { return stats[static_cast(family)]; } + /// Owner-thread waits outside the family counters, in nanoseconds of `steadyNowNs`; zero while accounting is off. + struct WaitStats + { + /// Creates whose answer was not ready when the fold took it, and the time it waited for them. + UInt64 creates_awaited = 0; + UInt64 create_wait_ns = 0; + /// Time spent waiting for hinted `HEAD`s the fold dropped unused. + UInt64 head_discard_wait_ns = 0; + }; + const WaitStats & waitStats() const { return wait_stats; } + /// Drops a hinted key the caller will never take. The request is already in flight or done; the /// wait is bounded by that one request, its result and its exception are dropped, and the slot is /// counted as wasted now rather than in the destructor. The exception is dropped because no /// sequential walk would have issued this request, so none could have failed on it; the fence and /// the budget are re-observed by the very next request anyway. A key nobody hinted is a no-op. void discardRead(const String & key); - void discardHead(const String & key); + void discardHead(const String & key, ReadFamily family = ReadFamily::Other); /// Runs one intent create on the pool, under the same admitted generation, and returns the function that /// waits for its answer or rethrows what it threw; call it once, on the owning thread, while this object lives. @@ -124,6 +144,9 @@ class GcReadAhead size_t pending() const { return reads.size() + heads.size(); } /// Hinted HEADs not yet taken: the head hinting site throttles on its own count. size_t pendingHeads() const { return heads.size(); } + /// Hinted HEADs of one family not yet taken. Each family of the reduce throttles on its own count: with one + /// shared count the candidates and the pending rows take the window from each other in turn. + size_t pendingHeads(ReadFamily family) const { return head_slots_by_family[static_cast(family)]; } /// How many requests a hinting site should keep in flight. Zero at concurrency 1, which is what /// makes every `while (pending() < window())` loop hint nothing at all on the sequential setting. @@ -138,6 +161,7 @@ class GcReadAhead std::optional result; std::promise promise; std::future future; + ReadFamily family = ReadFamily::Other; Slot() : future(promise.get_future()) {} }; @@ -154,7 +178,7 @@ class GcReadAhead void closeApplyAt(UInt64 now_ns); template - void discard(Slots & slots, const String & key); + void discard(Slots & slots, const String & key, ReadFamily family); CasOperation & op; CasRequests & requests; @@ -175,13 +199,15 @@ class GcReadAhead Slots reads; Slots heads; + std::array(ReadFamily::Other) + 1> head_slots_by_family{}; std::unordered_map> creates; uint64_t next_create = 0; const std::shared_ptr create_failure = std::make_shared(); /// Null while accounting is off. UInt64 (*clock_ns)() noexcept = nullptr; - std::array stats{}; + std::array(ReadFamily::Other) + 1> stats{}; + WaitStats wait_stats; std::optional apply_family; UInt64 apply_since_ns = 0; }; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp index 525ee36411b26..23a040c622bce 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp @@ -812,6 +812,28 @@ ManifestSweepResult planManifestCursorPage( const CatalogEntry * catalog_entry = catalogEntryOf(catalog_cut, parsed->ns); auto [view_it, view_inserted] = view_by_ns.emplace(parsed->ns.string(), NamespaceFoldView{}); + if (view_inserted) + view_it->second.coverage = coverageOf(adopted_seal.seal, catalog_cut, parsed->ns); + + /// The premise without its `TailRemoval` check, before the view is built: the view costs a table recovery and a + /// chain walk, and on a namespace whose listed builds are all of the cursor's epoch it decides + /// nothing. The `TailRemoval` check needs the view and is applied with it below. The key's ownership is not yet + /// known, so a refusal here is not counted as retained debris. + if (catalog_entry && !active_by_ns.contains(parsed->ns.string())) + { + String retain_reason; + if (!manifestDeletionPremise(view_it->second, ManifestKey{parsed->key, parsed->build_prefix}, &retain_reason)) + { + LOG_DEBUG(getLogger("CasOrphanManifestSweep"), + "CAS orphan sweep: retaining {} before its namespace's protection view -- {}", + parsed->key, retain_reason); + ++result.retained_before_view; + ++result.skipped; + decided_through = listed.key; + continue; + } + } + auto [active_it, inserted] = active_by_ns.emplace(parsed->ns.string(), std::set{}); if (inserted) { @@ -833,7 +855,6 @@ ManifestSweepResult planManifestCursorPage( } if (work_budget) ++work_budget->sweep_namespaces_used; - view_it->second.coverage = coverageOf(adopted_seal.seal, catalog_cut, parsed->ns); if (catalog_entry && !catalog_recovery_authoritative) { LOG_DEBUG(getLogger("CasOrphanManifestSweep"), diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h index aea312ffb55f3..44136803a7a83 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h @@ -138,6 +138,9 @@ struct ManifestSweepResult uint64_t retained_unconsumed_seal = 0; uint64_t retained_tail_removal = 0; uint64_t retained_work_budget = 0; + /// Keys the premise refused before their namespace's protection view was built. Their ownership is + /// unknown, so they may be live parts, and they are in no `retained_*` class above. + uint64_t retained_before_view = 0; /// The floor a namespace's builds are judged against is one mount body per server root. A page /// resolves it once per namespace (`floor_lookups`); each lookup reads the mount key of every diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index 744036270fb26..3ef58c34876bd 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -835,6 +835,9 @@ void PartWriteTxn::precommitAdd(const RootNamespace & target_ns, const String & precommit_manifest = id.ref; precommit_state = PrecommitState::Uncertain; + if (precommit_before_append_hook_for_test) + precommit_before_append_hook_for_test(); + try { store->appendRefOps(target_ns, MutationScope::ref(final_ref_name), @@ -842,8 +845,17 @@ void PartWriteTxn::precommitAdd(const RootNamespace & target_ns, const String & /// 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 + [pool = store, target_ns, final_ref_name, id, id_staged_by_this_txn, txn_build_id = build_id, build_epoch = epoch]( + const RefTableState & state) -> std::vector { + /// The entry check can pass and the caller stall across a whole self-remount; this runs in the + /// flush, after the remount published its epoch. A grant must not cross epochs: the orphan + /// sweep may already have deleted a superseded build's manifest. + if (const uint64_t live = pool->liveWriterEpoch(); build_epoch != live) + throw RefAdmissionRefusedException(makeCasWriteRetryLaterException(fmt::format( + "PartWriteTxn (writer_epoch {}) belongs to a superseded mount incarnation (live epoch {}) — " + "the mount was self-remounted before its precommit was appended; restart the build", + build_epoch, live))); /// 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 @@ -891,7 +903,7 @@ void PartWriteTxn::precommitAdd(const RootNamespace & target_ns, const String & } catch (const RefAdmissionRefusedException &) { - /// Refused before the lane queued the append: this invocation created no binding and owes no duty. + /// This invocation's mutation was certainly not submitted: it 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; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h index e9d1b75debdba..3d4c6a3a317ee 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h @@ -199,6 +199,9 @@ class PartWriteTxn /// 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); } + /// Test-only: runs in `precommitAdd` after its liveness check and before its append. Set before `precommitAdd`. + void setPrecommitBeforeAppendHookForTest(std::function hook) { precommit_before_append_hook_for_test = std::move(hook); } + /// Test-only DEEP snapshot of this build's recorded deps, keyed by `BlobRef`. A plain copy of the /// private `deps` map -- lets a test assert the whole build is byte-for-byte untouched after a /// rejected or aborted merge, rather than probing one ref at a time via `dependencyProof`. @@ -331,6 +334,19 @@ class PartWriteTxn enum class PrecommitState : uint8_t { NotAttempted, Uncertain, Durable, Settled }; PrecommitState precommitState() const { return precommit_state; } + /// Test-only: the recorded precommit intent, the fields `precommitAdd` restores on a refusal. + struct PrecommitIntentForTest + { + RootNamespace target_ns; + String final_ref; + ManifestRef manifest; + PrecommitState state; + }; + PrecommitIntentForTest precommitIntentForTest() const + { + return {precommit_target_ns, precommit_final_ref, precommit_manifest, precommit_state}; + } + /// Lifecycle of THIS build's promote (precommit -> committed) append, recorded for the same reason /// and in the same way as `precommitState`: a promote whose append threw may still have COMMITTED /// the ref. The distinction is load-bearing one layer up -- the interserver relink maps a promote @@ -422,6 +438,8 @@ class PartWriteTxn std::function adoption_hook_for_test; /// Backing state for `setPromoteBeforeAppendHookForTest`; empty in production. std::function promote_before_append_hook_for_test; + /// Backing state for `setPrecommitBeforeAppendHookForTest`; empty in production. + std::function precommit_before_append_hook_for_test; }; } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h index 0a326138d792f..c3b5b1c0581c0 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h @@ -178,7 +178,7 @@ struct PoolConfig /// Every decision stays on the round thread, in the order it always ran; only the requests /// overlap. `1` issues no read-ahead and no fan-out at all and is the sequential round, request /// for request. - uint64_t gc_io_concurrency = 16; + uint64_t gc_io_concurrency = 48; /// Tests drive `renewWatermarkOnce` explicitly; gates both persistent runtime workers. bool background_watermark = false; /// See `MountConfig::bounded_background_renewal`. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h index 70f38f82d8606..34024d879f308 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h @@ -40,9 +40,9 @@ enum class ResolveAudit : uint8_t { Emit, Deferred }; /// 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`. +/// Thrown when this invocation's mutation was certainly not submitted, so it wrote nothing and bound nothing: +/// the namespace's positive admission is closed for a removal, or a precommit's build belongs to a superseded +/// mount incarnation. Catch sites match by type; the code and text are those of `throwCasWriteRetryLater`. class RefAdmissionRefusedException : public Exception { public: diff --git a/src/Disks/tests/gtest_cas_gc_read_ahead.cpp b/src/Disks/tests/gtest_cas_gc_read_ahead.cpp index 39e3846ee61b7..06039feac622e 100644 --- a/src/Disks/tests/gtest_cas_gc_read_ahead.cpp +++ b/src/Disks/tests/gtest_cas_gc_read_ahead.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -547,8 +548,10 @@ TEST(CASGCReadAhead, FamilyCountersFollowTheCalls) ASSERT_NO_FATAL_FAILURE(runFamilyCalls(rig, reads)); const bool hinting = concurrency > 1; - EXPECT_EQ(reads.familyStats(ReadFamily::RefLog), (ReadFamilyStats{.issued = 1, .takes = 1, .awaited = hinting ? 0u : 1u})); - EXPECT_EQ(reads.familyStats(ReadFamily::Manifest), (ReadFamilyStats{.issued = 2, .takes = 2, .awaited = hinting ? 1u : 2u})); + EXPECT_EQ(reads.familyStats(ReadFamily::RefLog), + (ReadFamilyStats{.issued = 1, .takes = 1, .awaited = hinting ? 0u : 1u, .unhinted = hinting ? 0u : 1u})); + EXPECT_EQ(reads.familyStats(ReadFamily::Manifest), + (ReadFamilyStats{.issued = 2, .takes = 2, .awaited = hinting ? 1u : 2u, .unhinted = hinting ? 1u : 2u})); EXPECT_EQ(reads.familyStats(ReadFamily::RefCheckpoint), ReadFamilyStats{}); EXPECT_EQ(reads.familyStats(ReadFamily::Other), ReadFamilyStats{}); } @@ -683,11 +686,38 @@ TEST(CASGCReadAhead, ApplyBelongsToThePrecedingTake) namespace { -/// Holds the read of one key inside the backend until `open`, bounded so a defect cannot hang the suite. +std::mutex ticking_mutex; +std::condition_variable ticking_cv; +UInt64 ticking_calls = 0; + +/// Moves by one per call, so a take's wait is exactly one tick. +UInt64 tickingClockNs() noexcept +{ + std::lock_guard lock(ticking_mutex); + const UInt64 now = ticking_calls++; + ticking_cv.notify_all(); + return now; +} + +void resetTickingClock() +{ + std::lock_guard lock(ticking_mutex); + ticking_calls = 0; +} + +/// A take reads the clock once before it polls its slot, so the first tick marks a take that has begun. +bool waitForFirstTick() +{ + std::unique_lock lock(ticking_mutex); + return ticking_cv.wait_for(lock, std::chrono::seconds(10), [] { return ticking_calls >= 1; }); +} + +/// Holds the read of one key inside the backend until a take has begun and for a fixed time after it, +/// then lets it finish. class GatedReadBackend : public CountingBackend { public: - explicit GatedReadBackend(String gated_key_) : gated_key(std::move(gated_key_)) {} + GatedReadBackend(String gated_key_, std::chrono::milliseconds hold_) : gated_key(std::move(gated_key_)), hold(hold_) {} std::optional read(const String & key, DB::Cas::TransportAccess & access) override { @@ -696,7 +726,12 @@ class GatedReadBackend : public CountingBackend std::unique_lock lock(mutex); inside = true; cv.notify_all(); - cv.wait_for(lock, std::chrono::seconds(10), [&] { return opened; }); + lock.unlock(); + waitForFirstTick(); + lock.lock(); + /// Nothing opens the gate: the read waits out the whole hold. + cv.wait_for(lock, hold, [] { return false; }); + released_at = std::chrono::steady_clock::now(); } return CountingBackend::read(key, access); } @@ -707,42 +742,29 @@ class GatedReadBackend : public CountingBackend return cv.wait_for(lock, std::chrono::seconds(10), [&] { return inside; }); } - void open() + std::optional releasedAt() { std::lock_guard lock(mutex); - opened = true; - cv.notify_all(); + return released_at; } private: const String gated_key; + const std::chrono::milliseconds hold; std::mutex mutex; std::condition_variable cv; bool inside = false; - bool opened = false; + std::optional released_at; }; -/// Moves by one per call; its second call after `reset` is the one after the readiness poll, and it -/// signals the thread that opens the gate. -std::atomic ticking_calls{0}; -std::atomic poll_passed{false}; - -UInt64 tickingClockNs() noexcept -{ - const UInt64 call = ticking_calls.fetch_add(1); - if (call == 1) - { - poll_passed.store(true); - poll_passed.notify_all(); - } - return call; -} - } TEST(CASGCReadAhead, AHintedUnreadyTakeIsAwaited) { - auto backend = std::make_shared("gated"); + /// The read is released only after the take has read its clock, which is the statement before its readiness + /// poll, and then held 50 ms more: the poll sees an unready slot unless the round thread is descheduled for + /// that long between two adjacent statements. + auto backend = std::make_shared("gated", std::chrono::milliseconds(50)); CasRequests requests = openRequestsForTest(backend); CasOperation op = requests.admit(); ThreadPool pool{CurrentMetrics::LocalThread, CurrentMetrics::LocalThreadActive, @@ -750,28 +772,22 @@ TEST(CASGCReadAhead, AHintedUnreadyTakeIsAwaited) /*max_threads*/ 4, /*max_free_threads*/ 4, /*queue_size*/ 0}; ASSERT_TRUE(std::holds_alternative(op.create("gated", "bytes", Retry::once()))); backend->resetCounts(); - - ticking_calls.store(0); - poll_passed.store(false); - std::thread releaser([&] - { - poll_passed.wait(false); - backend->open(); - }); - SCOPE_EXIT({ - poll_passed.store(true); - poll_passed.notify_all(); - releaser.join(); - }); + resetTickingClock(); GcReadAhead reads(op, requests, pool, 4); reads.enableFamilyAccounting(&tickingClockNs); reads.hintRead("gated", ReadFamily::Manifest); ASSERT_TRUE(backend->waitUntilInside()); + const auto take_began = std::chrono::steady_clock::now(); const auto got = reads.takeRead("gated", ReadFamily::Manifest); ASSERT_TRUE(got.has_value()); EXPECT_EQ(got->bytes, "bytes"); + /// The control: the read was still held when the take began, so `awaited` below is not luck. + const auto released_at = backend->releasedAt(); + ASSERT_TRUE(released_at.has_value()); + EXPECT_LT(take_began, *released_at); + const ReadFamilyStats & stats = reads.familyStats(ReadFamily::Manifest); EXPECT_EQ(stats.awaited, 1u); EXPECT_EQ(stats.takes, 1u); @@ -994,15 +1010,17 @@ TEST(CASGCReadAhead, FoldIsIdenticalAtConcurrencyOneAndEight) for (size_t i = 0; i < kRounds; ++i) EXPECT_EQ(one.seals[i], eight.seals[i]) << "fold seal differs at round " << i; - /// Times differ between any two runs; the counts must not. + /// Times, and whether a take found its result hinted, differ between the two widths. The other counts are equal + /// here because this fixture has no candidate that keeps an edge; one would add to `candidate_head_reads_issued` + /// and `candidate_head_discarded` at width 8 only. const auto withoutTimes = [](std::vector> rounds) { for (std::map & metrics : rounds) std::erase_if(metrics, [](const auto & entry) { const String & key = entry.first; - return key.ends_with("_awaited") || key.ends_with("_wait_us") || key.ends_with("_apply_us") - || key == "cursor_resolve_us"; + return key.ends_with("_awaited") || key.ends_with("_unhinted") || key.ends_with("_wait_us") + || key.ends_with("_apply_us") || key.ends_with("_hinted_at_settle") || key == "cursor_resolve_us"; }); return rounds; }; @@ -1014,7 +1032,7 @@ TEST(CASGCReadAhead, FoldIsIdenticalAtConcurrencyOneAndEight) EXPECT_EQ(run->intake[i].at(fmt::format("{}_reads_issued", family)), run->intake[i].at(fmt::format("{}_takes", family))) << family << " at round " << i << (run == &one ? " (concurrency 1)" : " (concurrency 8)"); - EXPECT_EQ(one.reduce, eight.reduce); + EXPECT_EQ(withoutTimes(one.reduce), withoutTimes(eight.reduce)); EXPECT_EQ(one.condemned, eight.condemned); EXPECT_EQ(one.deleted, eight.deleted); @@ -2488,3 +2506,470 @@ TEST(CASGCReadAhead, FutureManifestWorkEndsWithTheVisit) EXPECT_EQ(lifeCursor(*backend, layout), (RefTxnId{1, 2})); } } + +/// ============================ candidate HEAD hints the merge passes ============================ + +namespace +{ + +/// Counts the `HEAD`s of watched keys by the thread that sends them: the round's own thread, or a read-ahead +/// worker. With `latch` set, a `HEAD` of a latched key also waits until two of them are in flight at once. The +/// wait is bounded, and waiting stops for good at the first overlap or the first timeout. +class CandidateHeadBackend : public CountingBackend +{ +public: + void watch(std::set keys, std::set latch) + { + std::lock_guard lock(mutex); + watched = std::move(keys); + latched = std::move(latch); + round_thread = std::this_thread::get_id(); + armed = true; + } + + void disarm() + { + std::lock_guard lock(mutex); + armed = false; + } + + std::optional head(const String & key, DB::Cas::TransportAccess & access) override + { + bool is_latched = false; + { + std::unique_lock lock(mutex); + if (armed && watched.contains(key)) + ++(std::this_thread::get_id() == round_thread ? on_round_thread : on_workers)[key]; + is_latched = armed && latched.contains(key); + if (is_latched) + { + ++latched_in_flight; + if (latched_in_flight >= 2) + { + saw_overlap = true; + gate.notify_all(); + } + else if (!gave_up) + { + /// A watchdog, not a scheduling requirement: a second worker ends the wait at once. After one + /// wait without overlap, more waits would only slow a failing run. + gave_up = !gate.wait_for(lock, std::chrono::seconds(5), [&] { return saw_overlap; }); + } + } + } + auto meta = CountingBackend::head(key, access); + if (is_latched) + { + std::lock_guard lock(mutex); + --latched_in_flight; + } + return meta; + } + + uint64_t roundThreadHeads(const std::vector & keys) const { return sum(on_round_thread, keys); } + uint64_t workerHeads(const std::vector & keys) const { return sum(on_workers, keys); } + uint64_t allHeads(const std::vector & keys) const { return roundThreadHeads(keys) + workerHeads(keys); } + + bool sawOverlap() const + { + std::lock_guard lock(mutex); + return saw_overlap; + } + +private: + uint64_t sum(const std::map & counts, const std::vector & keys) const + { + std::lock_guard lock(mutex); + uint64_t total = 0; + for (const String & key : keys) + if (const auto it = counts.find(key); it != counts.end()) + total += it->second; + return total; + } + + mutable std::mutex mutex; + std::condition_variable gate; + bool armed = false; + std::set watched; + std::set latched; + std::thread::id round_thread; + std::map on_round_thread; + std::map on_workers; + size_t latched_in_flight = 0; + bool saw_overlap = false; + bool gave_up = false; +}; + +/// Blobs of one GC shard, in the merge's order: `lead` fresh candidates, a `stale` run, `tail` fresh candidates, a +/// `trailing` stale run. A stale blob loses the edge of the dropped part and keeps the edge of a part the baseline +/// round already folded, so it is a candidate the merge passes without a `HEAD`. +struct ShardShape +{ + size_t lead = 0; + size_t stale = 0; + size_t tail = 0; + size_t trailing = 0; +}; + +struct StaleRunBlobs +{ + std::vector payloads; /// every blob, all in the dropped part + std::vector keep; /// the stale blobs, also in the kept part + std::vector stale_keys; + std::vector fresh_keys; + std::vector> tail_keys; /// per shard +}; + +BlobRef refOfPayload(const String & payload) +{ + return BlobRef{BlobHashAlgo::CityHash128, BlobDigest::fromU128(u128Of(payload))}; +} + +StaleRunBlobs mineStaleRunBlobs(const Layout & layout, uint64_t gc_shards, const ShardShape & shape) +{ + const size_t per_shard = shape.lead + shape.stale + shape.tail + shape.trailing; + std::vector>> by_shard(gc_shards); + for (size_t i = 0;; ++i) + { + bool full = true; + for (const auto & shard : by_shard) + full = full && shard.size() >= per_shard; + if (full) + break; + const String payload = fmt::format("stale-run-payload-{}", i); + auto & shard = by_shard[blobShard(refOfPayload(payload), gc_shards)]; + if (shard.size() < per_shard) + shard.emplace_back(refOfPayload(payload), payload); + } + + StaleRunBlobs blobs; + blobs.tail_keys.resize(gc_shards); + for (uint64_t shard = 0; shard < gc_shards; ++shard) + { + auto & sorted = by_shard[shard]; + std::sort(sorted.begin(), sorted.end()); + for (size_t rank = 0; rank < sorted.size(); ++rank) + { + const auto & [ref, payload] = sorted[rank]; + const String key = layout.blobKey(ref); + blobs.payloads.push_back(payload); + const bool is_lead = rank < shape.lead; + const bool is_tail = rank >= shape.lead + shape.stale && rank < shape.lead + shape.stale + shape.tail; + if (is_lead || is_tail) + { + blobs.fresh_keys.push_back(key); + if (is_tail) + blobs.tail_keys[shard].push_back(key); + } + else + { + blobs.keep.push_back(payload); + blobs.stale_keys.push_back(key); + } + } + } + return blobs; +} + +/// One part of `ns` holding a blob per payload. +void publishBlobs(const PoolPtr & s, const String & ns, const String & ref, const std::vector & payloads) +{ + const RootNamespace nsr{ns}; + PartWriteInfo info; + info.intended_ref = ns + "/" + ref; + auto build = s->beginPartWrite(info); + + std::vector entries; + for (size_t i = 0; i < payloads.size(); ++i) + { + ManifestEntry e; + e.path = fmt::format("data_{:05}.bin", i); + e.placement = EntryPlacement::Blob; + e.ref = refOfPayload(payloads[i]); + e.blob_size = payloads[i].size(); + entries.push_back(std::move(e)); + } + const ManifestId id = build->stageManifest(std::move(entries)); + build->precommitAdd(nsr, ref, id); + for (const String & payload : payloads) + build->putBlob(idOf(payload), BlobSource::fromString(payload)); + build->promote(nsr, ref, build->buildId(), id); +} + +/// What the measured round decided and how its candidate `HEAD`s were served. +struct StaleRunOutcome +{ + size_t condemned = 0; + std::vector rows; /// the condemned and zero rows of the round's runs, with their tokens + std::vector intents; /// every intent key after the round + std::map reduce; + uint64_t tail_on_round_thread = 0; + uint64_t tail_on_workers = 0; + uint64_t stale_heads = 0; + uint64_t fresh_heads = 0; + bool saw_overlap = false; +}; + +/// The condemned and zero rows of the last fold seal, and every intent key. +void readFoldDecisions(Backend & backend, const Layout & layout, StaleRunOutcome & out) +{ + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const GcState st = decodeGcState(op.read(layout.gcStateKey(), Retry::once())->bytes); + const auto seal_bytes = op.read(layout.foldSealKey(st.snap_generation, st.snap_attempt), Retry::once()); + ASSERT_TRUE(seal_bytes.has_value()); + for (const RunRef & run : decodeFoldSeal(seal_bytes->bytes).blob_target_runs) + { + auto view = openSourceEdgeRun(op, run.key); + SourceEdgeRecord rec; + while (view.next(rec)) + { + if (rec.marker == RunMarker::Condemned) + out.rows.push_back(fmt::format("condemned {} {}:{} pending={} standing={} round={}", layout.blobKey(rec.ref), + rec.token.dialect, rec.token.value, rec.delete_pending, rec.standing, rec.condemn_round)); + else if (rec.marker == RunMarker::Zero) + out.rows.push_back(fmt::format("zero {}", layout.blobKey(rec.ref))); + } + } + op.forEachListedKey(layout.blobIntentsPrefix(), [&](const ListedKey & k) { out.intents.push_back(k.key); return true; }, + Retry::standard(), CasOperation::kCasListPageKeys); +} + +/// A baseline round folds both parts; the measured round folds the drop of the part that holds every blob. With +/// `latch_shard` set, the tail `HEAD`s of that shard must overlap before they answer. +void runStaleRun(uint64_t concurrency, uint64_t gc_shards, const ShardShape & shape, StaleRunOutcome & out, + std::optional latch_shard = std::nullopt) +{ + auto backend = std::make_shared(); + auto store = Pool::open(backend, + PoolConfig{.pool_prefix = "p", .server_root_id = "test", .gc_shards = gc_shards, + .gc_fold_max_defer_rounds = 0, .gc_io_concurrency = concurrency}); + const Layout & layout = store->layout(); + const StaleRunBlobs blobs = mineStaleRunBlobs(layout, gc_shards, shape); + + publishBlobs(store, "srv1/keep", "part", blobs.keep); + publishBlobs(store, "srv1/drop", "part", blobs.payloads); + store->renewWatermarkOnce(); + + Gc gc(store, kGc); + const RoundReport baseline = gc.runRegularRound(); + ASSERT_TRUE(baseline.acquired_lease); + ASSERT_EQ(baseline.condemned, 0u); + + store->dropRef(RootNamespace{"srv1/drop"}, "part"); + store->renewWatermarkOnce(); + + std::vector all_tail; + for (const auto & keys : blobs.tail_keys) + all_tail.insert(all_tail.end(), keys.begin(), keys.end()); + std::set watched(blobs.stale_keys.begin(), blobs.stale_keys.end()); + watched.insert(blobs.fresh_keys.begin(), blobs.fresh_keys.end()); + std::set latched; + if (latch_shard) + latched.insert(blobs.tail_keys[*latch_shard].begin(), blobs.tail_keys[*latch_shard].end()); + + gc.setPhaseSink([&](const GcPhaseRecord & rec) + { + if (rec.phase == "fold_reduce") + out.reduce = rec.metrics; + }); + backend->watch(std::move(watched), std::move(latched)); + const RoundReport report = gc.runRegularRound(); + backend->disarm(); + gc.setPhaseSink({}); + ASSERT_TRUE(report.acquired_lease); + + out.condemned = report.condemned; + out.tail_on_round_thread = backend->roundThreadHeads(all_tail); + out.tail_on_workers = backend->workerHeads(all_tail); + out.stale_heads = backend->allHeads(blobs.stale_keys); + out.fresh_heads = backend->allHeads(blobs.fresh_keys); + out.saw_overlap = backend->sawOverlap(); + + ASSERT_NO_FATAL_FAILURE(readFoldDecisions(*backend, layout, out)); +} + +/// The fold at `gc_io_concurrency` 8 against 1 over the same input: the same condemned rows with the same tokens, +/// the same intents, every tail `HEAD` sent by a worker rather than inline, and two tail `HEAD`s of `latch_shard` in +/// flight at once. A window held by passed hints fails the last check even when its one free slot keeps the +/// `HEAD`s off the round thread. +void expectSameDecisionsAndTailReadAhead(uint64_t gc_shards, const ShardShape & shape, size_t tail_total, + StaleRunOutcome & one, StaleRunOutcome & eight, uint64_t latch_shard = 0) +{ + ASSERT_NO_FATAL_FAILURE(runStaleRun(1, gc_shards, shape, one)); + ASSERT_NO_FATAL_FAILURE(runStaleRun(8, gc_shards, shape, eight, latch_shard)); + + EXPECT_TRUE(eight.saw_overlap) << "no two tail HEADs of shard " << latch_shard << " were in flight at once"; + + /// The sequential setting sends every candidate `HEAD` inline: the control for the thread attribution below. + EXPECT_EQ(one.tail_on_round_thread, tail_total); + EXPECT_EQ(one.tail_on_workers, 0u); + + EXPECT_EQ(eight.tail_on_round_thread, 0u) << "tail candidate HEADs read inline on the round thread"; + EXPECT_EQ(eight.tail_on_workers, tail_total); + + const size_t fresh_total = gc_shards * (shape.lead + shape.tail); + EXPECT_EQ(one.condemned, fresh_total); + EXPECT_EQ(eight.condemned, fresh_total); + EXPECT_EQ(one.rows, eight.rows); + EXPECT_EQ(one.intents, eight.intents); + EXPECT_FALSE(one.rows.empty()); + EXPECT_FALSE(one.intents.empty()); + + EXPECT_EQ(eight.reduce.at("candidate_head_takes"), fresh_total); + EXPECT_EQ(eight.reduce.at("candidate_head_unhinted"), 0u); + EXPECT_EQ(one.reduce.at("candidate_head_unhinted"), fresh_total); + /// Every stale `HEAD` the fold sent is a hint it dropped once the merge passed its key. + EXPECT_EQ(eight.reduce.at("candidate_head_discarded"), eight.stale_heads); + EXPECT_EQ(eight.reduce.at("candidate_head_reads_issued"), fresh_total + eight.stale_heads); +} + +constexpr size_t kWindowAtEight = 32; + +} + +TEST(CASGCReadAhead, PassedCandidateHintsDoNotPinTheHeadWindow) +{ + /// One fresh candidate first, so the stale run behind it is really hinted; the run is longer than the window, + /// and the tail after it is longer than the window too. + const ShardShape shape{.lead = 1, .stale = kWindowAtEight + 8, .tail = 3 * kWindowAtEight}; + StaleRunOutcome one; + StaleRunOutcome eight; + ASSERT_NO_FATAL_FAILURE(expectSameDecisionsAndTailReadAhead(1, shape, shape.tail, one, eight)); + /// The lead's top-up fills the window: itself and one window less one of the stale run. + EXPECT_EQ(eight.stale_heads, kWindowAtEight - 1); + EXPECT_EQ(one.stale_heads, 0u); +} + +TEST(CASGCReadAhead, AStaleRunBeforeTheFirstFreshTakeIsNeverRead) +{ + const ShardShape shape{.stale = kWindowAtEight + 8, .tail = 3 * kWindowAtEight}; + StaleRunOutcome one; + StaleRunOutcome eight; + ASSERT_NO_FATAL_FAILURE(expectSameDecisionsAndTailReadAhead(1, shape, shape.tail, one, eight)); + EXPECT_EQ(eight.stale_heads, 0u) << "the fold sent HEADs for stale candidates the merge had already passed"; + EXPECT_EQ(eight.reduce.at("candidate_head_discarded"), 0u); +} + +TEST(CASGCReadAhead, TheCandidateAtTheMergeKeepsItsHintedSlot) +{ + /// Only fresh candidates: every top-up finds the current key already hinted, and its slot must survive the + /// discard of the keys below it. + const ShardShape shape{.tail = 3 * kWindowAtEight}; + StaleRunOutcome one; + StaleRunOutcome eight; + ASSERT_NO_FATAL_FAILURE(expectSameDecisionsAndTailReadAhead(1, shape, shape.tail, one, eight)); + EXPECT_EQ(eight.fresh_heads, shape.tail); + EXPECT_EQ(eight.reduce.at("candidate_head_discarded"), 0u); +} + +TEST(CASGCReadAhead, PassedCandidateHintsAreDrainedAtEachShardEnd) +{ + /// Each shard ends on a stale run its last take hinted, so the second shard starts with the first one's + /// leftovers unless they are drained. + const ShardShape shape{.lead = 1, .stale = kWindowAtEight + 8, .tail = 3 * kWindowAtEight, .trailing = kWindowAtEight + 8}; + StaleRunOutcome one; + StaleRunOutcome eight; + /// The second shard's tail `HEAD`s overlap only if the first shard's leftovers no longer hold the window. + ASSERT_NO_FATAL_FAILURE(expectSameDecisionsAndTailReadAhead(2, shape, 2 * shape.tail, one, eight, /*latch_shard*/ 1)); + EXPECT_GT(eight.stale_heads, 2 * (kWindowAtEight - 1)) << "the trailing stale runs must be hinted, or the drain is untested"; +} + +namespace +{ + +constexpr size_t kPendingRows = 2 * kWindowAtEight + 16; + +/// Blob payloads by merge position: a fresh candidate first, then pending rows and unmerged candidates alternating, +/// then a short fresh tail. The first fresh take fills the candidate window with the unmerged ones. +struct InterleavedBlobs +{ + std::vector pending; + std::vector shared; + std::vector fresh; +}; + +InterleavedBlobs mineInterleavedBlobs() +{ + constexpr size_t kTail = 4; + std::vector> sorted; + for (size_t i = 0; i < 1 + 2 * kPendingRows + kTail; ++i) + { + String payload = fmt::format("interleaved-payload-{}", i); + sorted.emplace_back(refOfPayload(payload), std::move(payload)); + } + std::sort(sorted.begin(), sorted.end()); + + InterleavedBlobs blobs; + for (size_t rank = 0; rank < sorted.size(); ++rank) + { + const bool is_fresh = rank == 0 || rank > 2 * kPendingRows; + (is_fresh ? blobs.fresh : rank % 2 ? blobs.pending : blobs.shared).push_back(sorted[rank].second); + } + return blobs; +} + +struct InterleavedOutcome +{ + StaleRunOutcome decisions; + uint64_t deleted = 0; +}; + +/// Round 1 condemns the pending set; round 2 drops the fresh set and one of two owners of the shared set. +void runInterleavedRounds(uint64_t concurrency, InterleavedOutcome & out) +{ + auto backend = std::make_shared(); + auto store = Pool::open(backend, + PoolConfig{.pool_prefix = "p", .server_root_id = "test", .gc_shards = 1, + .gc_fold_max_defer_rounds = 0, .gc_io_concurrency = concurrency}); + const InterleavedBlobs blobs = mineInterleavedBlobs(); + publishBlobs(store, "srv1/pending", "part", blobs.pending); + publishBlobs(store, "srv1/fresh", "part", blobs.fresh); + publishBlobs(store, "srv1/shared_a", "part", blobs.shared); + publishBlobs(store, "srv1/shared_b", "part", blobs.shared); + store->renewWatermarkOnce(); + + Gc gc(store, kGc); + ASSERT_EQ(gc.runRegularRound().condemned, 0u); + store->dropRef(RootNamespace{"srv1/pending"}, "part"); + store->renewWatermarkOnce(); + ASSERT_EQ(gc.runRegularRound().condemned, blobs.pending.size()); + store->dropRef(RootNamespace{"srv1/fresh"}, "part"); + store->dropRef(RootNamespace{"srv1/shared_a"}, "part"); + store->renewWatermarkOnce(); + + gc.setPhaseSink([&](const GcPhaseRecord & rec) + { + if (rec.phase == "fold_reduce") + out.decisions.reduce = rec.metrics; + }); + const RoundReport report = gc.runRegularRound(); + gc.setPhaseSink({}); + ASSERT_TRUE(report.acquired_lease); + out.decisions.condemned = report.condemned; + out.deleted = report.deleted; + ASSERT_NO_FATAL_FAILURE(readFoldDecisions(*backend, store->layout(), out.decisions)); +} + +} + +TEST(CASGCReadAhead, PendingRowsAreHintedWhileUnmergedCandidatesFillTheirOwnWindow) +{ + InterleavedOutcome one; + InterleavedOutcome eight; + ASSERT_NO_FATAL_FAILURE(runInterleavedRounds(1, one)); + ASSERT_NO_FATAL_FAILURE(runInterleavedRounds(8, eight)); + + EXPECT_EQ(eight.decisions.rows, one.decisions.rows); + EXPECT_EQ(eight.decisions.intents, one.decisions.intents); + EXPECT_EQ(eight.decisions.condemned, one.decisions.condemned); + EXPECT_EQ(eight.deleted, one.deleted); + EXPECT_EQ(eight.deleted, kPendingRows) << "the pending rows must be deleted in the measured round"; + + const std::map & reduce = eight.decisions.reduce; + EXPECT_EQ(reduce.at("pending_head_takes"), kPendingRows); + /// Only the first settled row has no hint ahead of it. The count is decided by window accounting on the round + /// thread, so it does not depend on worker timing. + EXPECT_LE(reduce.at("pending_head_hinted_at_settle"), 1u); + EXPECT_GT(reduce.at("candidate_head_discarded"), 0u) << "unmerged candidates must have been hinted"; +} diff --git a/src/Disks/tests/gtest_cas_orphan_sweep_requests.cpp b/src/Disks/tests/gtest_cas_orphan_sweep_requests.cpp index c35a08bfad95e..92157b13301b6 100644 --- a/src/Disks/tests/gtest_cas_orphan_sweep_requests.cpp +++ b/src/Disks/tests/gtest_cas_orphan_sweep_requests.cpp @@ -63,8 +63,8 @@ struct PageFixture store = Pool::open(backend, config); const Layout & layout = store->layout(); casAdmitEntry(*backend, layout, kNs); - /// One committed birth log at {1,1} and a checkpoint naming it, so the namespace has a protection - /// view and every eligible key reaches the premise (which retains it for lack of fold coverage). + /// One committed birth log at {1,1} and a checkpoint naming it. The namespace has no fold coverage, + /// so the premise retains every eligible key before a protection view is built. /// The live ref's own manifest occupies build_sequence == manifests (it is itself one of the /// `manifests` listed objects, always active); the loop below fills the debris below it. publishAt(*backend, layout, kNs, RefTxnId{1, 1}, "live", /*build_sequence=*/manifests, @@ -303,8 +303,9 @@ TEST(CASOrphanSweepRequests, FloorIsReadOncePerNamespacePerPage) EXPECT_EQ(f.backend->getCount(layout.mountKey("test/store")), 1u); EXPECT_EQ(f.backend->getCount(layout.mountKey("test")), 1u); /// Builds 1..24 are retired under the floor and reach the premise, which retains them for lack of - /// coverage; builds 25..50 are active and never get that far. - EXPECT_EQ(result.retained_no_coverage, 24u); + /// coverage before any protection view is built; builds 25..50 are active and never get that far. + EXPECT_EQ(result.retained_before_view, 24u); + EXPECT_EQ(result.retained_no_coverage, 0u); EXPECT_TRUE(result.nominations.empty()); } @@ -326,6 +327,7 @@ TEST(CASOrphanSweepRequests, AbsentFloorRetainsEverythingWithOneLookup) EXPECT_EQ(result.listed, 10u); EXPECT_EQ(result.skipped, 10u); EXPECT_EQ(result.retained_no_coverage, 0u) << "an absent floor admits nothing, so no key reaches the premise"; + EXPECT_EQ(result.retained_before_view, 0u) << "an absent floor admits nothing, so no key reaches the premise"; } TEST(CASOrphanSweepRequests, RetainedKeysCostNoBodyRead) @@ -333,7 +335,7 @@ TEST(CASOrphanSweepRequests, RetainedKeysCostNoBodyRead) PageFixture f(/*manifests=*/50, /*min_active=*/25); const Layout & layout = f.store->layout(); const ManifestSweepResult result = f.page(); - EXPECT_EQ(result.retained_no_coverage, 24u); + EXPECT_EQ(result.retained_before_view, 24u); for (uint64_t seq = 1; seq <= 50; ++seq) EXPECT_EQ(f.backend->getCount(layout.manifestKey(ManifestId{kNs, build(seq)})), 0u) << seq; } @@ -399,7 +401,7 @@ TEST(CASOrphanSweepRequests, MountVanishingMidPageKeepsTheDecisionsOfTheFloorAsR const ManifestSweepResult result = planManifestCursorPage(*store, "", 1000, 100, true, nullptr); EXPECT_TRUE(backend->fired); EXPECT_EQ(result.floor_lookups, 1u); - EXPECT_EQ(result.retained_no_coverage, 24u) << "the 24 retired builds were decided under the floor as read"; + EXPECT_EQ(result.retained_before_view, 24u) << "the 24 retired builds were decided under the floor as read"; EXPECT_TRUE(result.nominations.empty()); OperationForTest op(*backend); EXPECT_FALSE((*op).head(layout.mountKey("test"), Retry::once()).has_value()); @@ -565,6 +567,8 @@ TEST(CASOrphanSweepRequests, EpochCrossingDiscardsAtMostOneWindowAndTheNewEpochI .life_epoch = 1, .committed_through = RefTxnId{2, 40}, .checkpoint_snapshot_id = std::nullopt, .last_epoch_seal = RefTxnId{1, 8}}); writeManifestRaw(*backend, layout, kNs, build(1), {blobEntryFor("a", DB::UInt128(0x100))}); + /// A fold cursor in epoch 2 lets the epoch-1 builds pass the `UnconsumedSeal` check, so the page builds the view. + seedFoldCursorForTest(*backend, layout, kNs, RefTxnId{2, 1}); setWatermarkMinActive(*backend, layout, "test", 2, /*min_active=*/1000); backend->resetCounts(); @@ -579,14 +583,12 @@ TEST(CASOrphanSweepRequests, EpochCrossingDiscardsAtMostOneWindowAndTheNewEpochI /// every one of those (47) plus the one raw manifest -- the fixture is about the hint/discard /// mechanics of the ref-log walks a namespace's first candidate triggers, not about the listing. EXPECT_EQ(result.listed, 48u); - /// The SAME reader crosses the epoch twice on this fixture: once inside the recovery walk - /// `activeManifestKeys` runs via `recoverRefTableDetailedFromAuthorityBounded`, and again in its own - /// committed-tail walk over the same {1,1}..{2,40} range (today's pre-existing double walk, not - /// something this change introduces) -- so at most two windows are discarded, not one. - EXPECT_LE(wasted, 128u) << "at most two windows at concurrency 16: one per walk crossing the epoch"; + /// Only the recovery walk, from {1,1}, crosses the epoch; the committed-tail walk starts at the + /// cursor in epoch 2. So at most one window is discarded. + EXPECT_LE(wasted, 64u) << "at most one window at concurrency 16"; EXPECT_GE(hits, 30u) << "the new epoch's logs were hinted and taken"; - /// Both walks read epoch 2's logs once each, so every key is read twice -- today's behaviour with - /// or without read-ahead, not something the hint/discard rule changes. + /// Every epoch-2 key is read twice: by the recovery walk, and by the committed-tail walk or, for + /// {2,1}, by the resolution of the cursor that sits on it. for (uint64_t seq = 1; seq <= 40; ++seq) EXPECT_EQ(backend->getCount(layout.refLogKey(NamespaceLifeId::fromCatalogEntry(kNs, catalogLifeIdForTest(*backend, layout, kNs)), RefTxnId{2, seq})), 2u) << seq; } @@ -639,7 +641,7 @@ TEST(CASOrphanSweepRequests, GenerationThreeTailWalksHintAFewKeysPastTheEnd) EXPECT_LE(wasted, 2 * kHintDepth) << "CASGCReadAheadWasted " << wasted; } -/// The same namespace through whole GC rounds at the default window: the fold reads the first absent key +/// The same namespace through whole GC rounds at a window of 16: the fold reads the first absent key /// once per round and hints only listed keys; the sweep's two walks waste at most the hint depth each. TEST(CASOrphanSweepRequests, GcRoundsOverAQuietGenerationThreeNamespaceWasteFewReads) { @@ -649,8 +651,7 @@ TEST(CASOrphanSweepRequests, GcRoundsOverAQuietGenerationThreeNamespaceWasteFewR auto store = Pool::open(backend, PoolConfig{.pool_prefix = "p", .server_root_id = "test", .manifest_sweep_list_budget_keys = 1000, .manifest_sweep_delete_budget_keys = 100, - .gc_fold_max_defer_rounds = 0}); - ASSERT_EQ(store->poolConfig().gc_io_concurrency, 16u) << "the default window, or this measures the wrong shape"; + .gc_fold_max_defer_rounds = 0, .gc_io_concurrency = 16}); const Layout & layout = store->layout(); casAdmitEntry(*backend, layout, kNs); for (uint64_t seq = 1; seq <= kDebrisManifests; ++seq) @@ -672,9 +673,15 @@ TEST(CASOrphanSweepRequests, GcRoundsOverAQuietGenerationThreeNamespaceWasteFewR constexpr uint64_t kRounds = 2; const uint64_t wasted_before = ProfileEvents::global_counters[ProfileEvents::CASGCReadAheadWasted]; { - Gc gc(store, hexToU128("00000000000000000000000000000001")); + /// The first round seals the cursor into epoch 2; the sweep of the second, due again because the + /// clock moved past the interval, is the one whose epoch-1 debris passes the `UnconsumedSeal` check and walks. + uint64_t now_ms = 1000; + Gc gc(store, hexToU128("00000000000000000000000000000001"), [&] { return now_ms; }); for (uint64_t round = 0; round < kRounds; ++round) + { ASSERT_TRUE(gc.runRegularRound({}, /*allow_steal*/true, UniversePolicy::kDefault).acquired_lease); + now_ms += store->poolConfig().orphan_manifest_sweep_interval_sec * 1000; + } } const uint64_t wasted = ProfileEvents::global_counters[ProfileEvents::CASGCReadAheadWasted] - wasted_before; /// The fold reads the head once; any further read of it is a sweep walk. @@ -690,3 +697,103 @@ TEST(CASOrphanSweepRequests, GcRoundsOverAQuietGenerationThreeNamespaceWasteFewR EXPECT_LE(past_end, kRounds * (1 + 2 * (1 + kHintDepth))) << "absent GETs past the end " << past_end; EXPECT_LE(wasted, kRounds * 2 * kHintDepth) << "CASGCReadAheadWasted " << wasted; } + +namespace +{ + +/// A catalogued namespace whose fold cursor sits in epoch 2, the epoch every listed manifest below is +/// from: three committed parts and `kDebrisManifests` unowned bodies, all under the floor. +struct CurrentEpochFixture +{ + std::shared_ptr backend = std::make_shared(); + PoolPtr store; + NamespaceLifeId life = fixture::fixtureLife(kNs); + + CurrentEpochFixture() + { + PoolConfig config; + config.pool_prefix = "p"; + config.server_root_id = "test"; + config.manifest_sweep_list_budget_keys = 1000; + config.manifest_sweep_delete_budget_keys = 100; + config.gc_fold_max_defer_rounds = 0; + store = Pool::open(backend, config); + const Layout & layout = store->layout(); + casAdmitEntry(*backend, layout, kNs); + publishAt(*backend, layout, kNs, RefTxnId{2, 1}, "live1", /*build_sequence=*/101, DB::UInt128(0x7001), /*birth=*/true); + publishAt(*backend, layout, kNs, RefTxnId{2, 2}, "live2", 102, DB::UInt128(0x7002)); + publishAt(*backend, layout, kNs, RefTxnId{2, 3}, "live3", 103, DB::UInt128(0x7003)); + for (uint64_t seq = 1; seq <= kDebrisManifests; ++seq) + writeManifestRaw(*backend, layout, kNs, ManifestRef{.writer_epoch = 2, .build_sequence = seq, .manifest_ordinal = 1}, + {blobEntryFor("a", DB::UInt128(0x100 + seq))}); + writeRecoverableCkptForRawFixture(*backend, layout, kNs, RefCkpt{ + .life_epoch = 2, .committed_through = RefTxnId{2, 3}, + .checkpoint_snapshot_id = std::nullopt, .last_epoch_seal = std::nullopt}); + seedFoldCursorForTest(*backend, layout, kNs, RefTxnId{2, 1}); + setWatermarkMinActive(*backend, layout, "test", /*writer_epoch=*/2, /*min_active=*/1000); + life = NamespaceLifeId::fromCatalogEntry(kNs, catalogLifeIdForTest(*backend, layout, kNs)); + } + + ManifestSweepResult page(GcRoundWorkBudget & budget) + { + backend->resetCounts(); + return planManifestCursorPage(*store, "", /*list_budget=*/1000, /*nomination_budget=*/100, + /*catalog_recovery_authoritative=*/true, &budget); + } + + uint64_t streamGets() const + { + const String prefix = store->layout().namespaceStreamPrefix(life); + uint64_t gets = 0; + for (const String & key : backend->touchedKeys()) + if (key.starts_with(prefix)) + gets += backend->getCount(key); + return gets; + } + + uint64_t ckptGets() const { return backend->getCount(store->layout().refCkptKey(life)); } +}; + +} + +/// The `UnconsumedSeal` check refuses every build of the cursor's own epoch, owned or not, so a page whose keys are all +/// of that epoch must not pay for the namespace's protection view. +TEST(CASOrphanSweepRequests, CurrentEpochPageBuildsNoProtectionView) +{ + CurrentEpochFixture f; + GcRoundWorkBudget budget; + const ManifestSweepResult result = f.page(budget); + + constexpr uint64_t kListed = 3 + kDebrisManifests; + EXPECT_EQ(result.listed, kListed); + EXPECT_EQ(result.retained_before_view, kListed); + EXPECT_EQ(result.skipped, kListed); + EXPECT_TRUE(result.nominations.empty()); + EXPECT_EQ(result.retained_unconsumed_seal, 0u) << "ownership is unknown, so no key counts as retained debris"; + EXPECT_EQ(result.topRetainReason().second, 0u); + EXPECT_EQ(f.ckptGets(), 0u); + EXPECT_EQ(f.streamGets(), 0u) << "no ref log or snapshot may be read"; + EXPECT_EQ(budget.sweep_namespaces_used, 0u); + EXPECT_EQ(budget.sweep_recovery_ops_used, 0u); +} + +/// One build below the cursor's epoch passes the `UnconsumedSeal` check, so the view is built once and the page decides +/// every later key of the namespace with it. +TEST(CASOrphanSweepRequests, OlderEpochKeyBuildsTheViewOnce) +{ + CurrentEpochFixture f; + const String old_key = f.store->layout().manifestKey( + writeManifestRaw(*f.backend, f.store->layout(), kNs, build(1), {blobEntryFor("a", DB::UInt128(0x99))})); + GcRoundWorkBudget budget; + const ManifestSweepResult result = f.page(budget); + + EXPECT_EQ(result.listed, 4 + kDebrisManifests); + ASSERT_EQ(result.nominations.size(), 1u); + EXPECT_EQ(result.nominations[0].key, old_key); + EXPECT_EQ(result.retained_before_view, 0u) << "the older-epoch key sorts first and builds the view"; + EXPECT_EQ(result.retained_unconsumed_seal, kDebrisManifests) << "unowned bodies of the cursor's epoch"; + EXPECT_EQ(result.skipped, 3 + kDebrisManifests); + EXPECT_EQ(budget.sweep_namespaces_used, 1u); + EXPECT_GE(f.ckptGets(), 1u); + EXPECT_GT(f.streamGets(), 0u); +} diff --git a/src/Disks/tests/gtest_cas_ref_writer.cpp b/src/Disks/tests/gtest_cas_ref_writer.cpp index 71ccc60d8e246..662fc6f09af52 100644 --- a/src/Disks/tests/gtest_cas_ref_writer.cpp +++ b/src/Disks/tests/gtest_cas_ref_writer.cpp @@ -6791,6 +6791,283 @@ TEST(CASRefWriterRemount, PromoteStalledAcrossARemountAfterTheStaleSweepIsRefuse namespace { +/// Arms `build` so that its next `precommitAdd`, after the entry check and before the append, runs `between` +/// once. Returns the flag the hook sets when it ran. +std::shared_ptr> beforePrecommitAppend(const PartWriteTxnPtr & build, std::function between) +{ + auto ran = std::make_shared>(false); + build->setPrecommitBeforeAppendHookForTest([ran, run = std::move(between)] + { + if (!ran->exchange(true)) + run(); + }); + return ran; +} + +/// A durable fence-out and a synchronous self-remount, run to completion. +std::function remountOf(const std::shared_ptr & backend, const PoolPtr & store) +{ + return [backend, store] + { + fenceOutRefMount(*backend, store->layout().mountKey("test")); + ASSERT_TRUE(store->tryRemountOnce()); + }; +} + +/// The message of the typed refusal `call` throws, or `nullopt` when it throws nothing or something else. +std::optional admissionRefusalOf(const std::function & call) +{ + try + { + call(); + } + catch (const RefAdmissionRefusedException & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::NETWORK_ERROR); + return e.message(); + } + catch (...) + { + ADD_FAILURE() << "unexpected exception: " << DB::getCurrentExceptionMessage(false); + return std::nullopt; + } + return std::nullopt; +} + +/// `+1` edges naming `manifest` in the namespace's chain, in any epoch. +size_t grantsOf(const std::shared_ptr & backend, const Layout & layout, const RootNamespace & ns, + const ManifestRef & manifest) +{ + size_t grants = 0; + for (const ListedKey & listed : listForTest(backend, layout.namespaceStreamPrefix(DB::Cas::tests::fixture::fixtureLife(ns)), "", 1000).keys) + { + const auto parsed = layout.parseRefObjectKey(listed.key); + if (!parsed || parsed->kind != RefObjectKind::Log) + continue; + const auto got = readOf(backend, listed.key); + if (!got) + continue; + for (const RefManifestEdge & edge : manifestEdgesOfTxn( + decodeRefLogTxn(openObject(FormatId::RefLog, got->bytes), ns.string(), parsed->txn_id))) + if (edge.manifest_id.ref == manifest && edge.change > 0) + ++grants; + } + return grants; +} + +void expectSameIntent(const PartWriteTxn::PrecommitIntentForTest & actual, const PartWriteTxn::PrecommitIntentForTest & expected) +{ + EXPECT_EQ(actual.target_ns.string(), expected.target_ns.string()); + EXPECT_EQ(actual.final_ref, expected.final_ref); + EXPECT_TRUE(actual.manifest == expected.manifest); + EXPECT_EQ(actual.state, expected.state); +} + +constexpr std::string_view kSupersededPrecommit = "self-remounted before its precommit was appended"; + +} + +/// A precommit passes its entry check, stalls across a whole self-remount, and reaches the append lane of the +/// new mount: the grant of the old epoch's manifest must not land in the new epoch. +TEST(CASRefWriterRemount, PrecommitStalledAcrossARemountIsRefused) +{ + auto backend = std::make_shared(); + auto store = openPool(backend); + const RootNamespace ns{"srv1/precommit_stalled_across_remount"}; + publishEmptyPart(store, ns, "owned"); + auto build = startBuildFor(store, ns, "late"); + const ManifestId id = build->stageManifest({}); + const uint64_t epoch_before = store->liveWriterEpoch(); + const auto remounted = beforePrecommitAppend(build, remountOf(backend, store)); + + const std::optional refusal = admissionRefusalOf([&] { build->precommitAdd(ns, "late", id); }); + ASSERT_TRUE(remounted->load()); + ASSERT_NE(store->liveWriterEpoch(), epoch_before); + ASSERT_TRUE(refusal.has_value()) << "the precommit was appended"; + EXPECT_NE(refusal->find(kSupersededPrecommit), String::npos) << *refusal; + EXPECT_EQ(grantsOf(backend, store->layout(), ns, id.ref), 0u); +} + +/// The refused call leaves no precommit duty: its intent is rolled back, `abandon` refuses as for any +/// superseded build, and destroying the build transfers no cleanup duty and pins no build sequence. +TEST(CASRefWriterRemount, RefusedStalledPrecommitLeavesNoDuty) +{ + auto backend = std::make_shared(); + auto store = openPool(backend); + const RootNamespace ns{"srv1/precommit_refused_leaves_no_duty"}; + publishEmptyPart(store, ns, "owned"); + auto build = startBuildFor(store, ns, "late"); + const ManifestId id = build->stageManifest({}); + const auto before = build->precommitIntentForTest(); + beforePrecommitAppend(build, remountOf(backend, store)); + + EXPECT_TRUE(admissionRefusalOf([&] { build->precommitAdd(ns, "late", id); }).has_value()); + expectSameIntent(build->precommitIntentForTest(), before); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "superseded mount incarnation", [&] { build->abandon(); }); + + build.reset(); + EXPECT_FALSE(store->writerCleanupDutiesPendingForTest()); + EXPECT_EQ(store->minActive(), store->peekNextBuildSeq()) << "the refused build's sequence stays pinned"; +} + +/// A refusal restores the duty an earlier call of the same build recorded, whether that one was durable +/// or uncertain. +TEST(CASRefWriterRemount, RefusedStalledPrecommitKeepsAnEarlierDuty) +{ + { + auto backend = std::make_shared(); + auto store = openPool(backend); + const RootNamespace ns{"srv1/precommit_refused_keeps_durable"}; + publishEmptyPart(store, ns, "owned"); + auto build = startBuildFor(store, ns, "first"); + const ManifestId first = build->stageManifest({}); + build->precommitAdd(ns, "first", first); + ASSERT_EQ(build->precommitState(), PartWriteTxn::PrecommitState::Durable); + const auto before = build->precommitIntentForTest(); + const ManifestId second = build->stageManifest({}); + beforePrecommitAppend(build, remountOf(backend, store)); + + EXPECT_TRUE(admissionRefusalOf([&] { build->precommitAdd(ns, "second", second); }).has_value()); + expectSameIntent(build->precommitIntentForTest(), before); + EXPECT_EQ(grantsOf(backend, store->layout(), ns, second.ref), 0u); + } + { + auto backend = std::make_shared(); + CasRequestBudget budget; + budget.attempt_timeout_ms = 100; + budget.lease_safety_margin_ms = 100; + auto store = openPool(backend, budget); + const RootNamespace ns{"srv1/precommit_refused_keeps_uncertain"}; + publishEmptyPart(store, ns, "owned"); + auto build = startBuildFor(store, ns, "first"); + const ManifestId first = build->stageManifest({}); + const ManifestId second = build->stageManifest({}); + /// A mount deadline too short for the append leaves the first precommit `Uncertain`; the remount + /// in the hook below re-arms the fence for the second call. + store->setMountDeadline(100); + expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { build->precommitAdd(ns, "first", first); }); + ASSERT_EQ(build->precommitState(), PartWriteTxn::PrecommitState::Uncertain); + const auto before = build->precommitIntentForTest(); + beforePrecommitAppend(build, remountOf(backend, store)); + + EXPECT_TRUE(admissionRefusalOf([&] { build->precommitAdd(ns, "second", second); }).has_value()); + expectSameIntent(build->precommitIntentForTest(), before); + EXPECT_EQ(grantsOf(backend, store->layout(), ns, second.ref), 0u); + } +} + +/// The refused item fails alone: a healthy precommit of the live epoch carved into the same batch is +/// appended, and the namespace keeps accepting appends. +TEST(CASRefWriterRemount, RefusedStalledPrecommitFailsAloneInItsBatch) +{ + auto backend = std::make_shared(); + auto store = openPool(backend); + const RootNamespace ns{"srv1/precommit_refused_in_batch"}; + publishEmptyPart(store, ns, "owned"); + auto stale = startBuildFor(store, ns, "stale"); + const ManifestId stale_id = stale->stageManifest({}); + + struct Sync + { + std::mutex m; + std::condition_variable cv; + bool entered = false; + size_t pending_at_carve = 0; + }; + auto sync = std::make_shared(); + PartWriteTxnPtr healthy; + ManifestId healthy_id; + std::future healthy_done; + SCOPE_EXIT({ store->setRefPreCarveHookForTest(nullptr); }); + + /// After the remount, a build of the live epoch leads the lane and waits in the pre-carve window until + /// the stale item is queued behind it, so one carve holds both. + beforePrecommitAppend(stale, [&, remount = remountOf(backend, store)] + { + remount(); + healthy = startBuildFor(store, ns, "healthy"); + healthy_id = healthy->stageManifest({}); + store->setRefPreCarveHookForTest([sync, store, ns] + { + { + std::lock_guard lk(sync->m); + if (sync->entered) + return; + sync->entered = true; + } + sync->cv.notify_all(); + /// Nothing signals an enqueue, so wait for the stale item by polling the queue, bounded. + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (store->refQueuePendingForTest(ns) < 2 && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + std::lock_guard lk(sync->m); + sync->pending_at_carve = store->refQueuePendingForTest(ns); + }); + healthy_done = std::async(std::launch::async, [&] { healthy->precommitAdd(ns, "healthy", healthy_id); }); + std::unique_lock lk(sync->m); + ASSERT_TRUE(sync->cv.wait_for(lk, std::chrono::seconds(10), [&] { return sync->entered; })); + }); + + EXPECT_TRUE(admissionRefusalOf([&] { stale->precommitAdd(ns, "stale", stale_id); }).has_value()); + ASSERT_TRUE(healthy_done.valid()); + ASSERT_EQ(healthy_done.wait_for(std::chrono::seconds(10)), std::future_status::ready); + EXPECT_NO_THROW(healthy_done.get()); + EXPECT_EQ(sync->pending_at_carve, 2u) << "both items were in the carved batch"; + EXPECT_EQ(healthy->precommitState(), PartWriteTxn::PrecommitState::Durable); + EXPECT_EQ(grantsOf(backend, store->layout(), ns, healthy_id.ref), 1u); + EXPECT_EQ(grantsOf(backend, store->layout(), ns, stale_id.ref), 0u); + + EXPECT_NO_THROW(healthy->promote(ns, "healthy", healthy->buildId(), healthy_id)); + EXPECT_TRUE(store->resolveRef(ns, "healthy").has_value()); +} + +/// Without a remount the precommit appends as before, once, across a request retry. +TEST(CASRefWriterRemount, PrecommitWithoutARemountAppendsOnce) +{ + auto backend = std::make_shared(); + auto store = openPool(backend); + const RootNamespace ns{"srv1/precommit_without_remount"}; + publishEmptyPart(store, ns, "owned"); + auto build = startBuildFor(store, ns, "late"); + const ManifestId id = build->stageManifest({}); + + backend->fault_key_substr = "/_log/"; + backend->fault_count = 1; + backend->clearRequestJournal(); + build->precommitAdd(ns, "late", id); + const std::vector journal = backend->requestJournal(); + backend->fault_key_substr.clear(); + + EXPECT_EQ(backend->fault_count, 0) << "the append was not retried"; + EXPECT_EQ(build->precommitState(), PartWriteTxn::PrecommitState::Durable); + EXPECT_EQ(grantsOf(backend, store->layout(), ns, id.ref), 1u); + String rendered; + for (const String & entry : journal) + rendered += entry + "\n"; + RecordProperty("journal", rendered); +} + +/// The test seam that publishes an epoch without a remount is refused too: the closure compares epochs and +/// nothing else. Production publishes an epoch only through a remount. +TEST(CASRefWriterRemount, EpochPublishedWithoutARemountRefusesTheStalledPrecommit) +{ + auto backend = std::make_shared(); + auto store = openPool(backend); + const RootNamespace ns{"srv1/precommit_epoch_seam"}; + publishEmptyPart(store, ns, "owned"); + auto build = startBuildFor(store, ns, "late"); + const ManifestId id = build->stageManifest({}); + beforePrecommitAppend(build, [store] { store->setLiveWriterEpochForTest(store->liveWriterEpoch() + 1); }); + + const std::optional refusal = admissionRefusalOf([&] { build->precommitAdd(ns, "late", id); }); + ASSERT_TRUE(refusal.has_value()) << "the precommit was appended"; + EXPECT_NE(refusal->find(kSupersededPrecommit), String::npos) << *refusal; + EXPECT_EQ(grantsOf(backend, store->layout(), ns, id.ref), 0u); +} + +namespace +{ + /// Commits ref `owned`, turns the row `Removing` from outside and remounts, so the next caller builds a /// fresh runtime for a `Removing` row. Returns the life. NamespaceLifeId removingRowAfterRemount( diff --git a/src/Disks/tests/gtest_cas_settings.cpp b/src/Disks/tests/gtest_cas_settings.cpp index 864ce810d82d4..fd32505de682d 100644 --- a/src/Disks/tests/gtest_cas_settings.cpp +++ b/src/Disks/tests/gtest_cas_settings.cpp @@ -346,7 +346,7 @@ TEST(CASContentAddressedSettings, InvalidBoundsDiagnosticNamesExternalConfigKeys "srv10", ErrorCodes::BAD_ARGUMENTS, "content_addressed disk: cas_gc_interval_sec, cas_gc_shards and cas_gc_io_concurrency must be >= 1 " - "(got 60, 0, 16)"); + "(got 60, 0, 48)"); /// The GC I/O pool is refused at zero for the same reason the shard count is: a zero would be a /// silently disabled subsystem rather than a configuration the pool can honour. One is the way to /// run the covered GC I/O sequentially. diff --git a/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp b/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp index 09bcba8b31d14..3f7157b32e444 100644 --- a/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp +++ b/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp @@ -310,7 +310,7 @@ TEST(CASSweepDeletionPremise, TheCursorPageRetainsDebrisOfANamespaceThatFoldedNo const ManifestSweepResult page = sweepManifestCursorPageForTest(*f.store, "", /*list_budget*/100, /*delete_budget*/10); EXPECT_EQ(page.deleted, 0u); - EXPECT_EQ(page.retained_unconsumed_seal, 1u); + EXPECT_EQ(page.retained_before_view, 1u); EXPECT_TRUE(f.orphanExists()); std::vector warnings; @@ -328,10 +328,14 @@ TEST(CASSweepDeletionPremise, ConsecutiveRoundsSurviveAnOrphanOfAnEmptyRefStream uint64_t now_ms = 1000; Gc gc(f.store, hexToU128("00000000000000000000000000000001"), [&] { return now_ms; }); uint64_t pages_listed = 0; + uint64_t retained_before_view = 0; gc.setPhaseSink([&](const GcPhaseRecord & phase) { if (phase.phase == "orphan_sweep") + { pages_listed += phase.metrics.at("orphan_manifest_sweep_page_listed"); + retained_before_view += phase.metrics.at("retained_before_view"); + } }); const RoundReport first = runRegularRoundReclaiming(gc); @@ -343,12 +347,13 @@ TEST(CASSweepDeletionPremise, ConsecutiveRoundsSurviveAnOrphanOfAnEmptyRefStream EXPECT_NO_THROW(runRegularRoundReclaiming(gc)) << "round " << i + 2; } EXPECT_EQ(pages_listed, 3u); + EXPECT_EQ(retained_before_view, 3u) << "each page refuses the orphan before building a view"; EXPECT_TRUE(f.orphanExists()); /// Positive control: the adopted seal carries a zero cursor and the manifest is eligible, so the /// rounds above reached the premise rather than skipping the sweep. const ManifestSweepResult page = sweepManifestCursorPageForTest(*f.store, "", /*list_budget*/100, /*delete_budget*/10); - EXPECT_EQ(page.retained_unconsumed_seal, 1u); + EXPECT_EQ(page.retained_before_view, 1u); } /// The retention summary's total covers every class the "most of them" figure ranks, the work-budget class @@ -359,30 +364,48 @@ TEST(CASSweepDeletionPremise, TheRetentionSummaryAndPhaseRowCountTheWorkBudgetCl auto store = Pool::open(backend, PoolConfig{.pool_prefix = "p", .server_root_id = "test", .gc_round_sweep_namespace_budget = 1, .gc_fold_max_defer_rounds = 0}); const Layout & layout = store->layout(); - setWatermarkMinActive(*backend, layout, kServerRoot, kBuildEpoch, /*min_active_build_sequence*/6); + setWatermarkMinActive(*backend, layout, kServerRoot, kBuildEpoch + 1, /*min_active_build_sequence*/6); + /// Each chain crosses into the next epoch, so the first round seals a cursor there and the debris of + /// the build epoch passes the `UnconsumedSeal` check in the second round, which is the one that needs a view. for (const char * name : {"00/aa@cas@", "00/bb@cas@", "00/cc@cas@"}) { const RootNamespace ns{name}; - casAdmitRecoverableEntry(*backend, layout, ns); + casAdmitEntry(*backend, layout, ns); + publishAt(*backend, layout, ns, RefTxnId{kBuildEpoch, 1}, "live", /*build_sequence=*/100, DB::UInt128(0x7001), /*birth=*/true); + writeSealAt(*backend, layout, ns, RefTxnId{kBuildEpoch, 2}); + publishAt(*backend, layout, ns, RefTxnId{kBuildEpoch + 1, 1}, "live2", /*build_sequence=*/200, DB::UInt128(0x7002), + /*birth=*/false, /*prev_epoch_seal=*/RefTxnId{kBuildEpoch, 2}); + writeRecoverableCkptForRawFixture(*backend, layout, ns, RefCkpt{ + .life_epoch = kBuildEpoch, .committed_through = RefTxnId{kBuildEpoch + 1, 1}, + .checkpoint_snapshot_id = std::nullopt, .last_epoch_seal = RefTxnId{kBuildEpoch, 2}}); writeManifestRaw(*backend, layout, ns, ref(5, 0xAB), {blobEntryFor("a", DB::UInt128(1))}); } + /// Retained after the view, by the `UnconsumedSeal` check: an unowned build of the cursor's own epoch. + writeManifestRaw(*backend, layout, RootNamespace{"00/aa@cas@"}, + ManifestRef{.writer_epoch = kBuildEpoch + 1, .build_sequence = 5, .manifest_ordinal = 0xAC}, + {blobEntryFor("a", DB::UInt128(2))}); + + uint64_t now_ms = 1000; + Gc gc(store, hexToU128("00000000000000000000000000000001"), [&] { return now_ms; }); + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + now_ms += store->poolConfig().orphan_manifest_sweep_interval_sec * 1000; ScopedLogCapture capture("CasGc", "information"); - Gc gc(store, hexToU128("00000000000000000000000000000001")); std::vector phases; gc.setPhaseSink([&](const GcPhaseRecord & phase) { phases.push_back(phase); }); const RoundReport report = runRegularRoundReclaiming(gc); ASSERT_TRUE(report.acquired_lease); ASSERT_FALSE(report.deferred); - /// One namespace gets a view and is retained for lack of coverage; the two beyond the cap are - /// retained on the work budget, and the phase row carries both counts. + /// One namespace gets the view, deletes its older debris and retains the build of the cursor's epoch; + /// the two beyond the cap are retained on the work budget, and the phase row carries both counts. const auto sweep_phase = std::find_if(phases.begin(), phases.end(), [](const GcPhaseRecord & phase) { return phase.phase == "orphan_sweep"; }); ASSERT_NE(sweep_phase, phases.end()); ASSERT_TRUE(sweep_phase->metrics.contains("retained_work_budget")); EXPECT_EQ(sweep_phase->metrics.at("retained_work_budget"), 2u); - EXPECT_EQ(sweep_phase->metrics.at("retained_no_coverage"), 1u); + EXPECT_EQ(sweep_phase->metrics.at("retained_unconsumed_seal"), 1u); + EXPECT_EQ(sweep_phase->metrics.at("retained_before_view"), 0u); EXPECT_EQ(capture.count("retained 3 manifest body(ies) this pass, most of them (2 of 3) for 'work_budget_exhausted'"), 1u) << capture.captured(); } @@ -483,49 +506,61 @@ TEST(CASSweepDeletionPremise, DebrisUnderANamespaceTheFoldNeverWalksIsRetainedIn /// have to leave the process as COUNTERS or not at all. In Stage A that is nearly the whole story of /// the sweep, because rule (1) is satisfiable only for a closed-and-folded epoch. /// -/// Non-vacuous by construction: two namespaces on ONE page are retained for DIFFERENT reasons, so a -/// counter wired to the wrong class, or one bucket catching everything, changes the answer. A -/// single-reason page would pass against a single mislabelled counter. +/// Non-vacuous by construction: three namespaces on ONE page are retained for DIFFERENT reasons, so a +/// counter wired to the wrong class, or one bucket catching everything, changes the answer. TEST(CASSweepDeletionPremise, DistinctRetainReasonsLandInDistinctCounters) { auto backend = std::make_shared(); auto store = openPoolForTest(backend); const Layout & layout = store->layout(); + const ManifestRef current_epoch_ref{.writer_epoch = kBuildEpoch + 1, .build_sequence = 5, .manifest_ordinal = 0xA2}; - /// Namespace A: a cursor still INSIDE the build's epoch -> rule (1), `unconsumed_seal`. + /// Namespace A: an older build passes the `UnconsumedSeal` check and builds the view, which then retains an unowned + /// build of the cursor's own epoch -> `unconsumed_seal`. The older build is deleted. const RootNamespace ns_a{"00/aa@cas@"}; - const ManifestRef ref_a = ref(5, 0xA1); casAdmitRecoverableEntry(*backend, layout, ns_a); - writeManifestRaw(*backend, layout, ns_a, ref_a, {blobEntryFor("a", DB::UInt128(1))}); - seedCursorAt(*backend, layout, ns_a, RefTxnId{kBuildEpoch, 3}); + writeManifestRaw(*backend, layout, ns_a, ref(5, 0xA1), {blobEntryFor("a", DB::UInt128(1))}); + writeManifestRaw(*backend, layout, ns_a, current_epoch_ref, {blobEntryFor("a2", DB::UInt128(3))}); + seedCursorAt(*backend, layout, ns_a, RefTxnId{kBuildEpoch + 1, 1}); - /// Namespace B: a HELD row whose cursor is well above the build's epoch, so rule (1) is satisfied - /// and the hold is demonstrably what retained it. + /// Namespace B: a HELD row whose cursor is above the build's epoch. The hold is decidable without + /// the view, so the key is refused before it and counts in no class. const RootNamespace ns_b{"00/bb@cas@"}; - const ManifestRef ref_b = ref(5, 0xB1); casAdmitRecoverableEntry(*backend, layout, ns_b); - writeManifestRaw(*backend, layout, ns_b, ref_b, {blobEntryFor("b", DB::UInt128(2))}); + writeManifestRaw(*backend, layout, ns_b, ref(5, 0xB1), {blobEntryFor("b", DB::UInt128(2))}); const RefHold hold{.reason = HoldReason::BodyUndecodable, .offending_position = RefTxnId{kBuildEpoch + 1, 9}, .retry_count = 1, .next_retry_round = 4}; seedCursorAt(*backend, layout, ns_b, RefTxnId{kBuildEpoch + 1, 8}, hold); - setWatermarkMinActive(*backend, layout, kServerRoot, kBuildEpoch, /*min_active_build_sequence*/6); + /// Namespace C: passes the `UnconsumedSeal` check, but namespace A spent the page's only view -> `work_budget`. + const RootNamespace ns_c{"00/cc@cas@"}; + casAdmitRecoverableEntry(*backend, layout, ns_c); + writeManifestRaw(*backend, layout, ns_c, ref(5, 0xC1), {blobEntryFor("c", DB::UInt128(4))}); + seedCursorAt(*backend, layout, ns_c, RefTxnId{kBuildEpoch + 1, 1}); - const ManifestSweepResult result = sweepManifestCursorPageForTest(*store, "", /*list_budget*/100, /*delete_budget*/10); + setWatermarkMinActive(*backend, layout, kServerRoot, kBuildEpoch + 1, /*min_active_build_sequence*/6); - EXPECT_EQ(result.deleted, 0u); - EXPECT_EQ(result.retained_unconsumed_seal, 1u) << "namespace A's cursor is inside its build's epoch"; - EXPECT_EQ(result.retained_hold, 1u) << "namespace B is held"; + GcRoundWorkBudget budget; + budget.max_sweep_namespaces = 1; + const ManifestSweepResult result + = sweepManifestCursorPageForTest(*store, "", /*list_budget*/100, /*delete_budget*/10, &budget); + + EXPECT_EQ(result.deleted, 1u) << "namespace A's older build"; + EXPECT_EQ(result.retained_unconsumed_seal, 1u) << "namespace A's build of the cursor's epoch"; + EXPECT_EQ(result.retained_before_view, 1u) << "namespace B is held"; + EXPECT_EQ(result.retained_work_budget, 1u) << "namespace C got no view"; + EXPECT_EQ(result.retained_hold, 0u); EXPECT_EQ(result.retained_no_coverage, 0u); EXPECT_EQ(result.retained_tail_removal, 0u); - EXPECT_GE(result.skipped, 2u) << "both retentions are also ordinary skips"; + EXPECT_EQ(result.skipped, 3u) << "every retention is also an ordinary skip"; + EXPECT_EQ(budget.sweep_namespaces_used, 1u) << "namespace B was refused before it could spend the budget"; /// The rollup an operator reads. The two classes tie at one each and the tie resolves by enum /// order, which is what keeps an unchanged pool reporting an unchanged verdict pass after pass. const auto top = result.topRetainReason(); EXPECT_EQ(top.second, 1u); - EXPECT_EQ(top.first, SweepRetainClass::Hold); + EXPECT_EQ(top.first, SweepRetainClass::UnconsumedSeal); EXPECT_EQ(String{sweepRetainClassName(SweepRetainClass::UnconsumedSeal)}, "unconsumed_seal"); /// A page with no candidates reports nothing: the counters carry the premise's own refusals, not @@ -610,7 +645,9 @@ TEST(CASSweepDeletionPremise, RecoveryWorkBudgetRetainsAndConvergesWithoutWedgin constexpr int kTailSize = 200; for (int i = 0; i < kTailSize; ++i) publishCommittedTransition(*backend, layout, ns, "tail" + std::to_string(i), std::nullopt, ref(2000 + i, 1)); - seedFoldCursorForTest(*backend, layout, ns, RefTxnId{kBuildEpoch, 1}); + /// A cursor in the next epoch lets the candidates pass the `UnconsumedSeal` check, so the page starts the owner + /// recovery, which runs out of budget before the cursor is ever resolved. + seedFoldCursorForTest(*backend, layout, ns, RefTxnId{kBuildEpoch + 1, 1}); uint64_t total_retained_work_budget = 0; uint64_t total_skipped = 0; @@ -833,6 +870,78 @@ TEST(CASSweepDeletionPremise, NamespaceWorkBudgetCapsDistinctViewsPerPage) EXPECT_EQ(surviving, 1u) << "exactly one candidate remains -- the one whose namespace had no budget left"; } +/// The namespace budget is charged where a view is built. A first namespace whose keys are all refused +/// before the view takes no slot, so the second namespace gets the only view and its orphan is deleted. +TEST(CASSweepDeletionPremise, NamespaceRefusedBeforeTheViewSpendsNoBudget) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Layout & layout = store->layout(); + + const RootNamespace ns_a{"00/aa@cas@"}; + const RootNamespace ns_b{"00/bb@cas@"}; + casAdmitRecoverableEntry(*backend, layout, ns_a); + casAdmitRecoverableEntry(*backend, layout, ns_b); + writeManifestRaw(*backend, layout, ns_a, ref(5, 0xA1), {blobEntryFor("a", DB::UInt128(1))}); + writeManifestRaw(*backend, layout, ns_b, ref(5, 0xB1), {blobEntryFor("b", DB::UInt128(2))}); + /// A's cursor is inside the build's epoch, so the `UnconsumedSeal` check refuses its key before any view. + seedCursorAt(*backend, layout, ns_a, RefTxnId{kBuildEpoch, 3}); + seedCursorAt(*backend, layout, ns_b, RefTxnId{kBuildEpoch + 1, 1}); + setWatermarkMinActive(*backend, layout, kServerRoot, kBuildEpoch, /*min_active_build_sequence*/6); + + GcRoundWorkBudget budget; + budget.max_sweep_namespaces = 1; + const ManifestSweepResult result + = sweepManifestCursorPageForTest(*store, "", /*list_budget*/100, /*delete_budget*/10, &budget); + + EXPECT_EQ(result.retained_before_view, 1u); + EXPECT_EQ(result.retained_work_budget, 0u); + EXPECT_EQ(result.deleted, 1u) << "namespace B got the page's only view"; + EXPECT_EQ(budget.sweep_namespaces_used, 1u); + OperationForTest op(*backend); + EXPECT_TRUE((*op).head(layout.manifestKey(ManifestId{ns_a, ref(5, 0xA1)}), Retry::once()).has_value()); + EXPECT_FALSE((*op).head(layout.manifestKey(ManifestId{ns_b, ref(5, 0xB1)}), Retry::once()).has_value()); +} + +/// An uncatalogued namespace has no premise and no view, and is charged the namespace budget at its first +/// key, as before: ahead of a catalogued namespace it takes the slot, and behind one it finds none. +TEST(CASSweepDeletionPremise, UncataloguedNamespaceIsChargedTheBudgetAtItsFirstKey) +{ + const RootNamespace catalogued{"00/bb@cas@"}; + const auto run = [&](const RootNamespace & uncatalogued) + { + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Layout & layout = store->layout(); + casAdmitRecoverableEntry(*backend, layout, catalogued); + writeManifestRaw(*backend, layout, catalogued, ref(5, 0xB1), {blobEntryFor("b", DB::UInt128(2))}); + seedCursorAt(*backend, layout, catalogued, RefTxnId{kBuildEpoch + 1, 1}); + writeManifestRaw(*backend, layout, uncatalogued, ref(5, 0xC1), {blobEntryFor("c", DB::UInt128(3))}); + setWatermarkMinActive(*backend, layout, kServerRoot, kBuildEpoch, /*min_active_build_sequence*/6); + + GcRoundWorkBudget budget; + budget.max_sweep_namespaces = 1; + const ManifestSweepResult result + = sweepManifestCursorPageForTest(*store, "", /*list_budget*/100, /*delete_budget*/10, &budget); + EXPECT_EQ(budget.sweep_namespaces_used, 1u); + EXPECT_EQ(result.retained_before_view, 0u); + EXPECT_EQ(result.retained_work_budget, 1u); + EXPECT_EQ(result.deleted, 1u); + OperationForTest op(*backend); + return std::pair{ + (*op).head(layout.manifestKey(ManifestId{uncatalogued, ref(5, 0xC1)}), Retry::once()).has_value(), + (*op).head(layout.manifestKey(ManifestId{catalogued, ref(5, 0xB1)}), Retry::once()).has_value()}; + }; + + const auto [first_uncatalogued_kept, first_catalogued_kept] = run(RootNamespace{"00/aa@cas@"}); + EXPECT_FALSE(first_uncatalogued_kept) << "the uncatalogued namespace listed first takes the slot and is decided"; + EXPECT_TRUE(first_catalogued_kept) << "the catalogued namespace finds the budget spent"; + + const auto [second_uncatalogued_kept, second_catalogued_kept] = run(RootNamespace{"00/cc@cas@"}); + EXPECT_TRUE(second_uncatalogued_kept) << "the uncatalogued namespace listed after the budget is spent is retained"; + EXPECT_FALSE(second_catalogued_kept); +} + namespace {