diff --git a/docs/en/antalya/cas/architecture/blob-protocol.md b/docs/en/antalya/cas/architecture/blob-protocol.md index abf9c644159ea..eefb18431ef73 100644 --- a/docs/en/antalya/cas/architecture/blob-protocol.md +++ b/docs/en/antalya/cas/architecture/blob-protocol.md @@ -96,10 +96,11 @@ Ordered steps in `PartWriteTxn::ensureBlobPresent`: 7. `BlobSource::beginPublication` consumes the shared, monotonic `publication_attempted` state before backend I/O. A lost response cannot re-enable verbatim copy on a later attempt. 8. Retryable or ambiguous failures restart at `HEAD`: up to 8 attempts, each with a fresh envelope. - The engine starts no new attempt after the configured request window (`cas_request_window_ms`, - default 120 s), but an attempt already started can run longer: each creating request waits up to - the disk's `request_timeout_ms`, and multipart part uploads keep their own retries. A write can - therefore take longer than the request window before it fails with a retryable error. No + Each `HEAD` and intent `GET` has its own request window (`cas_request_window_ms`, default 120 s); + the loop has no time limit of its own; 8 attempts are its count. An attempt already started can run longer: each creating + request waits up to the disk's `request_timeout_ms`, and multipart part uploads keep their own + retries. A write can therefore take longer than one request window before it fails with a + retryable error. No dependency proof is recorded until the body was adopted or the publication completed. **Reads go to the store.** The `HEAD` is sent after the precommit edge is durable, and the intent diff --git a/docs/en/antalya/cas/architecture/garbage-collection.md b/docs/en/antalya/cas/architecture/garbage-collection.md index c7a76e8ae8444..eed248b17f949 100644 --- a/docs/en/antalya/cas/architecture/garbage-collection.md +++ b/docs/en/antalya/cas/architecture/garbage-collection.md @@ -59,11 +59,11 @@ follower or a deferred round execution returns before that commit. | 15 | `manifest_deletes` | post-`CAS` | Delete manifest bodies whose owner-removal minus-one edge the `CAS` in phase 13 just adopted | | 16 | `namespace_cleanup` | leader; suppressed on `DEFER` | Pages of the perpetual namespace janitor under a 20 s soft budget, reclaiming dead-life debris | | 17 | `ref_object_cleanup` | post-`CAS` | Prune ref logs and snapshots once both fold coverage and a live snapshot make them safe to delete | -| 18 | `orphan_sweep` | post-`CAS` | Exact-token deletion for the [orphan-manifest sweep](/antalya/cas/architecture/manifests-and-refs#orphan-sweep), after phase 13 adopted each candidate's blob-source retirements and the cursor | +| 18 | `orphan_sweep` | post-`CAS`, right after phase 15 | Exact-token deletion for the [orphan-manifest sweep](/antalya/cas/architecture/manifests-and-refs#orphan-sweep), after phase 13 adopted each candidate's blob-source retirements and the cursor | Phases 2 through 4 run on every leader round; a follower returns after phase 1. Phases 5–15 and -17–18 run only when phase 4 decides to fold (phase 9 only when the round does not suppress destruction); phase 16 runs after phase 15 on a fold and right after -phase 4 on a `DEFER`. A `DEFER` verdict is therefore not a bare no-op: it still runs one bounded +17–18 run only when phase 4 decides to fold (phase 9 only when the round does not suppress destruction). On a fold, phase 18 runs +right after phase 15, then phases 16 and 17; on a `DEFER`, phase 16 runs right after phase 4. A `DEFER` verdict is therefore not a bare no-op: it still runs one bounded namespace-janitor page with `suppress_destructive = true` — listing and classification only, no deletes and no cursor advance — and then returns, publishing no fold artifact and no commit `CAS`. Its lease `CAS` may already have created or renewed the lease in phase 1: @@ -109,7 +109,7 @@ that object. - **Runs on:** always — the only phase a `NotALeader` round emits - **Reads:** `gc/state`; `gc/hb` (only when another GC owns the lease) - **Writes / deletes:** one successful `CAS` on `gc/state` (acquire, renew or steal); a conflict is - re-observed and re-decided by the request engine within the configured request window (`cas_request_window_ms`, default 120 s); no + re-observed and re-decided by the request engine, at most 100 times, each request within its own window (`cas_request_window_ms`, default 120 s); no deletes - **Safety:** the lease is *work de-duplication, not mutual exclusion* — see below - **Fails the round if:** this `Gc` instance saw `gc/state` before and it has since disappeared, or @@ -186,9 +186,8 @@ evidence from the fold running now. - **Retry order:** when an erase is refused because the catalog changed, the drain pauses first (full-jitter backoff, growing to 5 s), then re-reads the catalog, then sends the next erase against that fresh read. A catalog write that lands during the pause therefore cannot refuse the next erase. - A permanently contended catalog ends the drain with `NETWORK_ERROR` at the request deadline or after - 100 erase attempts on one row, whichever comes first; the deadline is one frozen window shared by - every attempt on that row. + A permanently contended catalog ends the drain with `NETWORK_ERROR` after + 100 erases on one row, with no pause after the last. Each erase request has its own window. - **Observability:** phase row `pre_fold_ref_drain`; metric `deleted` (erases the store acknowledged, counted before the resolution read so a drain that throws still reports them, plus erases a resolution read proved); metric `cancelled_creating` (the `Creating` rows the drain cancelled; @@ -625,10 +624,13 @@ role as the coverage record. ### Post-commit failures {#post-commit-failures} After a `Committed` result the round is committed — an exception in phases 14–18 does not un-commit -it. Those phases tolerate the object outcomes they name (`NotFound`, `TokenMismatch`), but only -phase 16 is wrapped in a catch-all; a backend or decode exception in phases 14, 15, 17 or 18 -propagates, and `system.cas_gc_log` then records an `Aborted` or `Error` finish (see -[round outcomes](#round-outcomes)) for a round whose new `gc/state` is already durable. Read such a +it. Those phases tolerate the object outcomes they name (`NotFound`, `TokenMismatch`). Phase 16 logs +any other failure and goes on, unless the round was asked to stop. A backend or decode exception in +phases 14, 15, 17 or 18 propagates. Phase 18 runs before phases 16 and 17, so its exception also skips +them for that round. A propagated exception makes `system.cas_gc_log` record an +`Aborted`, `Stopped` or `Error` finish (see +[round outcomes](#round-outcomes)) for a round whose new `gc/state` is already durable. A manual round +whose query is killed or timed out in these phases is recorded as `Stopped`. Read such a row as "committed round, failed tail": the next round starts from the committed state, and what the tail did not delete is picked up later — by the orphan sweep for phase 15's leftovers, by phase 17's recomputed plan, and for phase 18 only once the sweep cursor (already advanced by phase @@ -702,8 +704,9 @@ nothing ends the pass. A pool without debris costs one `LIST` per round. page and checked again before the cursor is published; the incarnation segment in every key makes an old life's objects structurally unreachable from a reborn same-name namespace, so a missed key can only leak storage, never expose it -- **Fails the round if:** nothing — the whole phase is wrapped in a catch-all ("namespace janitor - stopped this round"). A failed batch `DELETE` leaks its keys and the cursor still advances. A failed +- **Fails the round if:** the round was asked to stop and a request of the phase fails or leaves its + cursor write's outcome unknown. Any other failure is logged ("namespace janitor stopped this round") + and the round goes on. A failed batch `DELETE` leaks its keys and the cursor still advances. A failed `LIST` resets the cursor to the stream start only on the first page of the phase; on a later page the cursor the previous page published stays - **Observability:** phase row `namespace_cleanup`; metrics `janitor_pages`, `janitor_keys`, @@ -761,7 +764,8 @@ from the catalog. ## Phase 18 — orphan sweep {#phase-18-orphan-sweep} -The last phase: executes the [orphan-manifest sweep](/antalya/cas/architecture/manifests-and-refs#orphan-sweep) +Runs right after phase 15, before the janitor and the ref object cleanup, because the committed cursor +has already moved past its nominations. Executes the [orphan-manifest sweep](/antalya/cas/architecture/manifests-and-refs#orphan-sweep) planned in phase 10 and adopted by phase 13's `CAS`. Planning runs only when the schedule requests it and the destructive gate permits it. The default wait before starting another traversal is one hour, subject to the clock-skew rule below. Successful pages of an active traversal continue @@ -1296,8 +1300,11 @@ A `Finish` row of `system.cas_gc_log` carries one of: `Success` (folded and comm (phase 4 chose not to fold), `NotALeader` (returned after phase 1), `Aborted` (the round threw a *transient* error — `S3_ERROR`, `NETWORK_ERROR`, `TIMEOUT_EXCEEDED`, `SOCKET_TIMEOUT`, `ABORTED`, `MEMORY_LIMIT_EXCEEDED` — and this `Gc` keeps its leadership and heartbeat, so the next round simply -retries), `Stopped` (a transient error while the disk was being torn down), or `Error` (any other -error code, notably `CORRUPTED_DATA` and `LOGICAL_ERROR`; leadership is dropped). The `error_code` +retries), `Stopped` (the round was stopped: a manual round whose query was killed or timed out ended +with `QUERY_WAS_CANCELLED` or a transient error, or a round ended with a transient error after the disk +began tearing down or after it saw `SYSTEM CAS GC STOP`), or `Error` (any other +error code, notably `CORRUPTED_DATA` and `LOGICAL_ERROR`; leadership is dropped). A `Stopped` round +may already have committed its `gc/state`: see [post-commit failures](#post-commit-failures). The `error_code` column carries the code on `Aborted`, `Stopped` and `Error` and is `0` otherwise; every unrecognised code is `Error` by omission, never silently transient. diff --git a/docs/en/antalya/cas/configuration.md b/docs/en/antalya/cas/configuration.md index 0e0ec0aa4f66c..2b9bd3ac43700 100644 --- a/docs/en/antalya/cas/configuration.md +++ b/docs/en/antalya/cas/configuration.md @@ -108,7 +108,7 @@ entirely before release. Treat this table as a snapshot of the current build, no | `cas_manifest_decode_cache_bytes` | 128 MiB | Manifest decode cache byte budget (`0` disables) | | `cas_gc_io_concurrency` | `16` | Bounded pool size for GC object-storage requests that run in parallel: the fold's read-ahead (checkpoints, ref logs, manifests, zero-candidate HEADs), the fold's deletion-intent creates, the orphan-manifest sweep planning reads, the `SYSTEM CAS GC REBUILD` read-ahead, the `pending_deletes` conditional blob `DELETE` fan-out, and the namespace janitor's batch deletes of dead ref logs and snapshots. Not covered: all other GC requests, which run on the round thread. `1` runs the covered requests sequentially. `cas_gc_read_concurrency` is rejected without an alias; use `cas_gc_io_concurrency` instead | | `cas_attempt_timeout_ms` | `5000` | Budget for one HTTP attempt of a writable Native mount's control-plane requests (read, head, list, remove, conditional write, the mount-time bucket-versioning probe), at least 1. Together with the connect cap it forms the attempt envelope (`cas_attempt_timeout_ms + 2 × cap`; the cap is `cas_attempt_timeout_ms` itself when the disk's `connect_timeout_ms` is `0`, else `min(connect_timeout_ms, cas_attempt_timeout_ms)`) that the lease arithmetic reserves: one TCP connect and one TLS handshake under the cap each, send/receive bounded per socket operation by `cas_attempt_timeout_ms`. With background renewal the cadence check requires `cas_mount_renew_period_ms + 2 × envelope + cas_lease_safety_margin_ms < cas_mount_lease_ttl_ms`, which puts an effective ceiling on the frozen connect cap: under the defaults (TTL 40000, period 10000, margin 2000) the envelope must stay under 14000, so with the default attempt timeout a disk `connect_timeout_ms` of `0` or of 4500 ms or more refuses to open writable — lower the connect timeout or raise the TTL if you hit this. Blob body publication does not use this budget: its object-creating request is sent once under the disk's `request_timeout_ms`, with the connect timeout under the same cap | -| `cas_request_window_ms` | `120000` | How long a failing request keeps retrying before it gives up, measured from the start of the call. It applies to control-plane requests and to the blob publication loop. At the limit the request gives up with a retryable `NETWORK_ERROR`. When a query loads a part's metadata and neither cache holds it, a `MEMORY_LIMIT_EXCEEDED` from the manifest read is not retried: the query fails at once with its own code. Another query waiting for the same part is not failed by that error: it reads the manifest again under its own memory limit. Every other manifest read, including the fresh read a write makes of a part it changes, still retries that error for the whole window. A writable disk refuses to open unless the window is larger than twice the attempt envelope (a write reserves its attempt and the read that settles it); a read-only disk, unless it is larger than the envelope. On a writable disk every attempt also needs room left in the mount lease, so while renewals fail a request stops when the lease runs out, even inside a longer window. The ref-table recovery retry budget is derived as twice this value: 240 s by default, so a recovery attempt that spends one whole window inside a single write still has room for a second try. `90000` gives a 90 s window and a 180 s recovery budget | +| `cas_request_window_ms` | `120000` | How long one failing request keeps starting attempts, measured from the start of that request. Every request has its own window, so a series of requests is not bounded by it; the deadlines that successive requests share are the mount lease and the `--timeout` of an offline tool. The same value bounds, on its own, the wait in the catalog queue and the time after which a copy-source confirm starts no new poll pass (a pass already started, and its wait for the table's lock, finish). The read that settles an unclear write has its own window. A conditional update is decided at most 100 times, and a catalog update is submitted at most 100 times: see [updates that keep losing races](#contention-bound). A blob publication is tried at most 8 times, and its upload is under no window. Recovery of a table walks at most 8 times. At the limit the request gives up with a retryable `NETWORK_ERROR`, except when the eighth recovery walk fails: the table load then fails with that walk's own error. When a query loads a part's metadata and neither cache holds it, a `MEMORY_LIMIT_EXCEEDED` from the manifest read is not retried: the query fails at once with its own code. Another query waiting for the same part is not failed by that error: it reads the manifest again under its own memory limit. Every other manifest read, including the fresh read a write makes of a part it changes, still retries that error for the whole window. A writable disk refuses to open unless the window is larger than twice the attempt envelope (a write reserves its attempt and the read that settles it); a read-only disk, unless it is larger than the envelope. On a writable disk, the requests that tables make run under this server's mount lease, and each of their attempts also needs room left in it, so while renewals fail such a request stops when the lease runs out, even inside a longer window. Background lease renewal does not need that room. `90000` gives a 90 s window. `SYSTEM CAS GC STOP` prevents the next attempt of the catalog drain that a scheduled `GC` round runs before its fold, server shutdown that of the namespace removal of an `Atomic` table, and a killed or timed-out query prevents the next retry of a failed attempt, so a stopped request can end before its window does; an attempt in flight runs to its end: see [stopping CAS work](/antalya/cas/operations/troubleshooting#stopping-cas-work) | | `cas_lease_safety_margin_ms` | `2000` | Startup-only margin validated against the mount lease TTL: the attempt envelope + `cas_lease_safety_margin_ms` must be strictly less than the mount lease TTL, and `cas_mount_renew_period_ms` + 2 × envelope + `cas_lease_safety_margin_ms` too, or the disk refuses to open writable | | `cas_unsafe_remount_no_delay` | `0` | Reclaim a mount slot that carries this server's own uuid at once after a hard restart, without observing the slot's token for the lease TTL. Unsafe whenever two processes can hold the same `server_uuid` (a copied uuid file, a stalled predecessor). After such a reclaim the predecessor can still start conditional writes until its own cutoff (`confirmed deadline − cas_lease_safety_margin_ms − 2 × envelope`) or until its next renewal meets the token guard, and a request it already sent may still materialize later. That is not a data hazard: ref-log keys carry `(writer_epoch, sequence)` and creates are conditional, so two writers can never commit different bodies to one key, and recovery's tombstone settles any straggler (recovery fails closed after 64 successive tombstone-create attempts in one epoch displaced by newly materializing old-epoch transactions). The exposure is availability, not data. Intended for test stands and deployments that guarantee one process per uuid | | `cas_staging_backend` | `local` | Blob staging backend (`local` \| `s3`); `s3` is opt-in and requires native same-store copy on writable mount. A transaction deletes its staging objects on commit and on abort; mount start removes leftovers of the same `server_root_id`. Neither can see a multipart upload that was never completed, so add an `AbortIncompleteMultipartUpload` lifecycle rule on the bucket to reclaim those | @@ -139,6 +139,29 @@ The `expires_at_ms` stamped into the mount object is a writer-stamped diagnostic authorizes a reclaim or a GC fence-out. Local fencing is derived instead from the confirmed request's pre-I/O `CLOCK_BOOTTIME` anchor plus the TTL. +### Updates that keep losing races {#contention-bound} + +An update of a shared object that keeps losing races to other writers is retried at most 100 times, then fails with +`NETWORK_ERROR` and a message containing `did not converge`. Examples are the ref catalog under many concurrent +`CREATE` and `DROP` statements, and a hot ref. There is no total time budget for this loop: each attempt has its own +request window. + +- **One lost race** on a healthy store costs one conditional write, a pause, and one read before the next attempt. + The first lost race is retried at once. After that the pause grows by 40 ms with each race the same update loses in + a row, up to a base of 750 ms, plus a random addition of up to a quarter of the base, so one pause lasts at most 937 ms. + Five lost races in a row cost 400 to 500 ms of pauses. A race lost on a transport fault is paced like a fault + instead, and the next lost race counts as a first one again. +- **A loss on a cached value:** an update may start from the last catalog this server knows, without a read. When + that value is out of date, its write is refused and the update reads and writes again at once, with no pause and + without counting it as a lost race. So 100 attempts can send 101 conditional writes. +- **Total at the limit:** 100 lost races cost about 100 conditional writes, about 100 reads, and 98 pauses (the first + retry is not paced) of 66.8 s to 83.5 s in all, about 75.2 s on average. While lease renewals succeed, the count of 100 ends the loop, not the + mount lease. +- **Worst case:** 100 slow answers, each inside its own window: about 100 request windows, more than 3 hours at the + default `cas_request_window_ms`. +- **Earlier exits:** `KILL QUERY` or `max_execution_time` ends the loop at the next failed answer from the store. + `SYSTEM CAS GC STOP` ends `GC`'s own catalog updates at their next attempt. + ### Lease TTL: 30 s, 40 s and 120 s {#mount-lease-costs} The write reserve is `2 × envelope + cas_lease_safety_margin_ms` (16 s with defaults, `envelope` as @@ -360,8 +383,8 @@ Builds that include this change move these defaults: - `cas_mount_lease_ttl_ms` moves from `30000` to `40000`. The wait after a hard restart grows with it, from about 43 s to 47 s plus the start time (see [the lease costs](#mount-lease-costs)). -- The request window moves from a fixed 90 s to `cas_request_window_ms`, default `120000`. The ref-table - recovery budget moves from a fixed 120 s to twice the window, 240 s. +- The request window moves from a fixed 90 s to `cas_request_window_ms`, default `120000`. Recovery of a + ref table no longer has a time budget: it walks at most 8 times. - The four `cas_gc_round_redelete_budget`, `cas_gc_round_ref_cleanup_budget`, `cas_gc_round_handoff_prefix_wholesale_budget` and `cas_gc_round_outcome_entry_budget` caps move from `5000` to `0` (unbounded). The first rounds of an diff --git a/docs/en/antalya/cas/operations/troubleshooting.md b/docs/en/antalya/cas/operations/troubleshooting.md index 240eb16591c77..dc37b19025b8b 100644 --- a/docs/en/antalya/cas/operations/troubleshooting.md +++ b/docs/en/antalya/cas/operations/troubleshooting.md @@ -17,7 +17,7 @@ tools. | Symptom | Diagnosis | Action | |---|---|---| | A server keeps losing its mount lease and self-remounting | Check `system.cas_mounts` for the server's own `state`/`expires_at`, then correlate `watermark_renew` and `mount_remount` in `system.cas_log`; losing the lease trips a local fence and latches a remount generation | Read the failed renewal's `classification` before changing anything — it alone now says why (see [the decision flow](#mount-renewal-remount-flow)). Look for object-store latency consuming the confirmed lease or BOOTTIME advancement; see [the mount lease](/antalya/cas/architecture/mounts-and-leases#mount-lease) | -| Writes slow down or stall under load, with no exception reaching the client | S3 `SlowDown`/`ServiceUnavailable`/`RequestTimeout`/`InternalError` (5xx) responses are not on the request engine's `isDefinitelyRefusedWrite` definite-failure list (only malformed-request, entity-too-large, and access-denied that no credential refresh can fix are), so they classify as ambiguous and are retried automatically. Confirm with `sum(ProfileEvents['CASConditionalWriteUnresolved'])` rising alongside `sum(ProfileEvents['CASConditionalWriteAttempts'])` over `system.query_log` for the affected window (or `ProfileEvent_CASConditionalWriteUnresolved` in `system.metric_log` for a cumulative view across queries), and check `system.blob_storage_log` for `disk_name = ''` rows with a nonzero `error_code` around the same window | Nothing to configure per-request: the request engine retries the same `(key, bytes)` with capped-exponential backoff (200ms initial, capped at 5s, full jitter) until the configured request window (`cas_request_window_ms`, default 120 s) ends — for these conditional writes there is no separate attempts ceiling, only the deadline. A blob body upload is different: it is never resent as is after an ambiguous outcome, and each retry publishes a fresh envelope, up to 8 attempts, and no new attempt starts after the request window ends. An attempt already started can run longer: each creating request waits up to the disk's `request_timeout_ms`, and multipart part uploads keep their own retries. `CASBlobPublishAttemptFailed` counts failed attempts; `CASBlobPublishGaveUp` counts uploads that failed at least once and then ended with an exception, at the attempt cap or the deadline. Meanwhile the mount-lease renewer keeps extending the fence across the disruption — this is the "blips, throttling, partial outages" case the write path is built to survive. Confirm the mount lease itself is still renewing (`system.cas_mounts.expires_at` moving forward, `last_success_age_seconds` not climbing; it is `NULL` until this server's GC completes its first round as leader) — if it is, this is expected and self-resolving. If `SlowDown` responses are sustained rather than transient, check the bucket's request-rate limits against the pool's actual PUT/GET rate (see [bucket requirements](/antalya/cas/bucket-requirements)) and consider lowering `cas_blob_upload_pool_size` to reduce concurrent upload traffic; a write only surfaces a client-visible `NETWORK_ERROR` if the request window passes before the store recovers (an attempt started before the deadline can finish after it), and that error is retried by the ordinary merge/insert backoff, not silently dropped | +| Writes slow down or stall under load, with no exception reaching the client | S3 `SlowDown`/`ServiceUnavailable`/`RequestTimeout`/`InternalError` (5xx) responses are not on the request engine's `isDefinitelyRefusedWrite` definite-failure list (only malformed-request, entity-too-large, and access-denied that no credential refresh can fix are), so they classify as ambiguous and are retried automatically. Confirm with `sum(ProfileEvents['CASConditionalWriteUnresolved'])` rising alongside `sum(ProfileEvents['CASConditionalWriteAttempts'])` over `system.query_log` for the affected window (or `ProfileEvent_CASConditionalWriteUnresolved` in `system.metric_log` for a cumulative view across queries), and check `system.blob_storage_log` for `disk_name = ''` rows with a nonzero `error_code` around the same window | Nothing to configure per-request: the request engine retries the same `(key, bytes)` with capped-exponential backoff (200ms initial, capped at 5s, full jitter) while attempts keep starting inside the request's window (`cas_request_window_ms`, default 120 s, measured from the start of the request) — for one conditional write there is no separate attempts ceiling, only that window. An update that a busy table keeps refusing is decided at most 100 times, then fails with `NETWORK_ERROR` and a message containing `did not converge after 100 decisions`. A blob body upload is different: it is never resent as is after an ambiguous outcome, and each retry publishes a fresh envelope, up to 8 attempts in total; the request window bounds each `HEAD` and intent `GET`. An attempt already started can run longer: each creating request waits up to the disk's `request_timeout_ms`, and multipart part uploads keep their own retries. `CASBlobPublishAttemptFailed` counts each failed attempt that counts toward the 8, the eighth included, although no attempt follows it; a failure after the query stopped, and a failure that no retry can cure, are not counted. `CASBlobPublishGaveUp` counts uploads with at least one such failed attempt that then ended with an exception, at the attempt cap, or when a `HEAD` or intent `GET` gave up at its own request window. Meanwhile the mount-lease renewer keeps extending the fence across the disruption — this is the "blips, throttling, partial outages" case the write path is built to survive. Confirm the mount lease itself is still renewing (`system.cas_mounts.expires_at` moving forward) — if it is, this is expected and self-resolving. If `SlowDown` responses are sustained rather than transient, check the bucket's request-rate limits against the pool's actual PUT/GET rate (see [bucket requirements](/antalya/cas/bucket-requirements)) and consider lowering `cas_blob_upload_pool_size` to reduce concurrent upload traffic; a write surfaces a client-visible `NETWORK_ERROR` when a request's window passes before the store recovers, after 8 failed blob publication attempts, or when an update has not converged after 100 decisions or 100 catalog submissions, however fast each failure was; the ordinary merge/insert backoff retries that error, it is not silently dropped | | A write fails with a message containing `CAS ref-log txn`, `is durable but was not acknowledged`, `outcome is unknown`, `nothing is durable` or `CLOSED by a successor's` | The phrase says whether the write can still take effect. A write blocked behind an earlier unresolved transaction (a wedged or needs-recovery lane) was never attempted, and its message names the earlier transaction's outcome with the same phrase. Errors that name no earlier transaction carry no phrase, for example an admission refusal before the write is queued (`the operation is no longer admitted`), a failed ref-table recovery, a lost mount lease, a table superseded by a self-remount, and a lane in a terminal state (`INVALID_STATE`, "terminal lane state") | Read [CAS commit errors](#cas-commit-errors) before retrying: some outcomes can duplicate on retry | | `GC` never seems to reclaim space after tables are dropped | `SELECT * FROM system.cas_gc_log WHERE event_type='Finish' ORDER BY event_time DESC LIMIT 5` — check `outcome`; also `SELECT is_leader FROM system.cas_mounts` on this node | If `outcome != 'Success'`/`'Deferred'`, see [reading GC health](/antalya/cas/operations/monitoring#gc-health); if this node is not the leader (`is_leader = 0`), it never reclaims for this disk — check the peer holding leadership. Reclamation also needs at least two full rounds past condemnation by design (the grace period is rounds, not acks) — a single manual `SYSTEM CAS GC RUN` will not finish it, and it does nothing on a node that is not the leader | | A dangling-access exception or `CORRUPTED_DATA` on read | Run `clickhouse-disks cas-fsck --detail` and check `dangling` specifically — it is the one class that means data loss, distinct from `unreachable`/`awaiting-gc`, which are just waiting for the rounds that delete them | A nonzero `dangling` count is a real incident: collect the `--detail` output (see [what to collect before filing a bug](/antalya/cas/operations/debugging#filing-a-bug)) before taking any destructive action | @@ -33,6 +33,7 @@ tools. | `SYSTEM CAS DROP POOL MEMBER` returns `member_retired = 0` or a non-empty `warnings` column | The run stopped before its verified mark: a drain step failed, the admin lost its claim, or the farewell could not be confirmed; the owner keeps an unverified tombstone as the resume anchor. Only a claim lost before the drain started rolls the tombstone back, with the warning `the tombstone was rolled back`; nothing was removed then. After `the admin claim was lost during the drain` part of the member's data may be gone: the tombstone stays and the member does not start until a rerun verifies the retirement. A warning `the owner moved on to life N` means the owner was un-retired after this run's tombstone, by a rejoin or by another run's rollback | Rerun the same command only under the [rerun rule](/antalya/cas/operations/migration#rejoin-rerun-rule); it resumes over its own tombstone. A rerun refused as alive or contended waits until GC fences the previous run's slot: about one `cas_mount_lease_ttl_ms` plus 5 % plus one `cas_mount_renew_period_ms` (about 52 s with the defaults), plus up to two GC intervals, with a GC leader running. `namespaces_pending_gc` alone is not a reason to rerun | | `SYSTEM CAS DROP POOL MEMBER` refuses with `alive or contended` although the member is down | The claim trusts no wall clock: `expired` in `system.cas_mounts` is not a certificate of death; only a terminal slot (`terminated` or `fenced`) is reclaimable | Wait until the member's row shows `state = 'terminated'` (clean stop) or `state = 'fenced'` (the disk's GC leader fences the stale lease at the start of a GC round, once it has seen it unchanged for about one `cas_mount_lease_ttl_ms` plus one `cas_mount_renew_period_ms`, about 52 s with the default 40 s lease (40 s + 2 s for the 5 % term + 10 s for one renewal period, from the formula, not measured), so the wait can be up to two GC intervals longer; `SYSTEM CAS GC RUN` on the leader, `is_leader = 1` in `system.cas_mounts`, can trigger the fence, but the run that fences must come at least that long after the first run that saw the lease), then rerun | | The log repeats `CAS GC namespace removal is stuck … cleanup evidence is absent because terminal has not folded` and `CASGCStuckRemovals` grows | A removal turned the namespace's catalog row `Removing` and did not write its terminal record. Four operations remove a namespace: `DROP TABLE`, the source side of a table rename that moves the data, `SYSTEM UNFREEZE` and `SYSTEM CAS DROP POOL MEMBER`. While the row is `Removing`, writes to the table are refused and reads see no data after a restart or a remount, after a retried `DROP`, and on the GC leader after its next GC round; until then a server that kept the table open can still serve it. A server that closes such a table logs `its catalog row is Removing, so this server closes it`; that line alone also follows a table dropped on another server or before a restart, until GC erases its row. The data stays on the store, and the namespace's objects are reclaimed only after its removal completes. The warning starts after 10 GC rounds, a built-in value and not a setting, and repeats every GC round | The remedy depends on the operation, and no tool returns the row to `Live`. `DROP TABLE` in an `Atomic` database: the server retries the drop and logs `Cannot drop table … Will retry later.`; a retry that succeeds finishes the removal, and a warning that persists means the retry keeps failing, so read its error. `DROP TABLE` in an `Ordinary` database: the failed drop re-attaches the table under its name, and running `DROP TABLE` again finishes the removal. `SYSTEM CAS DROP POOL MEMBER`: rerunning it under the [rerun rule](/antalya/cas/operations/migration#rejoin-rerun-rule) finishes the removal. A table rename that moved the data (the log has `RENAME TABLE move was only partially applied`): the table stays attached under its old name, its parts are already in the new name's namespace, and no statement finishes the removal and keeps those parts reachable. A retried `RENAME TABLE` is refused with `DIRECTORY_ALREADY_EXISTS`; a retried rename from an `Ordinary` to an `Atomic` database targets a new uuid, completes with an empty table and leaves the moved parts in a namespace no table references. Do not retry the rename or drop the table; [file a bug](/antalya/cas/operations/debugging#filing-a-bug). `SYSTEM UNFREEZE WITH NAME`: a rerun finishes the removal only while another namespace under that backup name still has a part. Once every namespace left under it is `Removing`, the backup directory reads as absent and the rerun does nothing; no statement finishes the removal then, so file a bug | +| Writes to a table fail with `a removal write may still land` after a `DROP TABLE` failed | The `DROP` sent its `Live -> Removing` catalog write and failed before it learned whether that write applied. The write can still land, so the table stays closed for writes until the `DROP` is retried, even while its catalog row reads `Live`. The server logs `the outcome of its Live -> Removing catalog write is unknown` | Retry the `DROP TABLE`; a retry that succeeds finishes the removal. If the retry fails with the same error, restart the server, then retry the `DROP TABLE`. A restart reopens the table for writes but does not cancel the removal write; see [removal](/antalya/cas/architecture/namespaces#removal) | | `clickhouse-disks cas-migrate-pool` refuses with `changed during the migration` or `moved during the migration` | A server of the pool renewed its mount slot or its GC lease while the tool ran | Stop the server the message names and run the tool again; see [the refusals](/antalya/cas/operations/migration#migrate-generation-4-refusals) | | `clickhouse-disks cas-migrate-pool` refuses with `identities are not comparable`, `leaves no room for blob intent keys` or `cannot serve as a blob identity` | The disk's token dialect differs from the pool's, the pool prefix is too long, or the store's tokens cannot name a body | See [the refusals](/antalya/cas/operations/migration#migrate-generation-4-refusals) | | `clickhouse-disks cas-migrate-pool` fails with `could not be confirmed` | An intent create got no usable answer; the tool wrote nothing after the intents | Run the tool again | @@ -132,3 +133,36 @@ The default-level log policy is intentionally bounded: one warning on the first then one recovery info or terminal fence warning, plus one final line per whole-chain remount attempt. Use `system.cas_log` and counter deltas to reconstruct the incident; `DEBUG` contains individual physical retries when that extra transport detail is necessary. + +## Stopping CAS work {#stopping-cas-work} + +A query that is killed with `KILL QUERY` or hits its time limit stops `CAS` work only where stopping leaves the state a storage failure there would leave: + +- A retry after a failed request. The retry is not sent. When a read or a blob upload failed before the stop, the query fails with that request's error, or with a retry-later `NETWORK_ERROR` (210) that names a credential refusal, not with the stop's own error. That request's error can itself be `TIMEOUT_EXCEEDED` (159), when the failed attempt timed out. When a metadata write failed before the stop, the query fails with a retry-later `NETWORK_ERROR` (210) that says the write is unresolved and what a read of the key found; it does not carry the store's error. A metadata write that the store refused, with no earlier attempt left unanswered, keeps the store's error. When such a write was refused for its credentials and the stop cancels its resend with fresh credentials, it fails with a retry-later `NETWORK_ERROR` (210) that names the refusal. When the request fails after the stop, the S3 client reports the stop itself (see below). The pause before a retry notices the stop within 200 ms. A pause inside cleanup that the operation owes after a send runs to its end, and the request is sent once more unless the mount fence, the mount lease or a deadline stops it; if that attempt fails after the stop, it is not retried. +- The next step of work that `CAS` can resume later: the catalog cleanup of a manual `SYSTEM CAS GC RUN`, the drain of `SYSTEM CAS DROP POOL MEMBER`, and the upload of a blob body the writer has to publish, because the store does not hold the blob or holds one the writer cannot reuse. The query fails with `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED`. When an earlier upload attempt of the same blob failed, the check before the next upload fails the query with that attempt's error instead. The drain checks the stop before each of the member's namespaces, before the listing of its manifests and after each page of that listing arrives, before each group of its manifests and before each key it deletes. A `SYSTEM CAS DROP POOL MEMBER` stopped after its drain began leaves the member retired; rerun it to finish. Stopped before that, it can leave the member as it was. + +Everywhere else the `CAS` requests of a stopped query run as on a plain S3 disk. This covers the first attempt of every request, a new decision after another writer won a race before the stop, waits for other callers, cleanup after a failed write, transaction rollback, dropping a table or a temporary table, `SYSTEM CAS FORGET`, and the scan of `SYSTEM CAS FSCK`. + +The S3 client reports a stopped query's error in place of any failed answer from the store, as on a plain S3 disk. This includes an expected answer of a healthy store, such as `404` for a key that does not exist. So the query can still fail with `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED` when the store answers with an error after the stop. A bulk delete that the store answers successfully, with an error for one of its keys, keeps that key's error. Writes of several queries to one table's metadata can be sent together by one of them. When that query is stopped, such a failed answer can fail the other queries' writes in the same request too. + +A metadata write that loses a race to another writer after the stop fails the query with `ABORTED` (236) and a message that says "conflict": the S3 client reports the stop in place of the store's refusal, and a read of the key shows the other writer's object. A write that lost its race before the stop reads the key again before its next attempt. When that read fails after the stop, the query fails with the read's error, which the S3 client reports as `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED`. The exception is a write decided on the server's cached copy of the key: that read settles its refusal, and the query fails with `ABORTED` (236) and "conflict". + +Two background owners stop `CAS` work at its next step, with their own error: + +- `SYSTEM CAS GC STOP`, for the catalog drain that a scheduled `GC` round runs before its fold. +- Server shutdown, for the namespace removal of an `Atomic` table. The removal is requeued and finishes after the restart. + +A `GC` round that `SYSTEM CAS GC STOP` ends is recorded as `Stopped` in `system.cas_gc_log`. A manual round whose query is killed or timed out is recorded as `Stopped` when it ends with `QUERY_WAS_CANCELLED`, or with one of the transient errors `S3_ERROR`, `NETWORK_ERROR`, `SOCKET_TIMEOUT`, `TIMEOUT_EXCEEDED`, `ABORTED` or `MEMORY_LIMIT_EXCEEDED`. It is recorded as `Error` when it ends with any other error, for example `READONLY`. A stop that comes after the round's last check leaves the round's own outcome. + +No stop interrupts: + +- A request already in flight. +- The first attempt of a read, and a read that only waits for another reader's result. +- A recovery walk that is already running. On S3 the walk of a stopped query still fails at the first error answer. A walk that looks for a record after its last one ends with such an answer, the `404` for that key; a walk that ends at the table's final removal record looks for none. The failed read is not retried. When the stop cuts short the read that follows a refused write of the walk, the walk ends with a retry-later `NETWORK_ERROR` (210) instead of starting again. +- Cleanup that the operation owes after a send, and merges. + +If the stop lands after a metadata write whose outcome is unknown, the error is the retry-later `NETWORK_ERROR` (210), and its message says the write is unresolved or its outcome is unknown. Check the table before you repeat the write. + +A stop does not mean that no further request is sent. It ends the retries of a failed request and the scans listed above at their next check. Other work in progress can still send requests up to its own limits, for example another recovery walk up to the limit on walks. When a stop comes together with a lost mount lease or a refused credential, the error can name the less specific of the two causes. + +There is no bound on how long the call takes to return after a stop. diff --git a/docs/en/operations/system-tables/cas_gc_log.md b/docs/en/operations/system-tables/cas_gc_log.md index 5427b8c1fe9db..68e76dbb294a5 100644 --- a/docs/en/operations/system-tables/cas_gc_log.md +++ b/docs/en/operations/system-tables/cas_gc_log.md @@ -38,7 +38,7 @@ specified (it is enabled by default in the shipped `config.xml`). - `gc_id` ([String](/sql-reference/data-types/string)) — The GC scheduler instance id (which mounter ran the round). - `trigger` ([Enum8](/sql-reference/data-types/enum)) — `Scheduled` (background tick) or `Manual` (`SYSTEM` command). - `round` ([UInt64](/sql-reference/data-types/int-uint)) — The GC round number (`0` on a `Start` row). -- `outcome` ([Enum8](/sql-reference/data-types/enum)) — `Unknown` (on a `Start` row), `Success` (led, folded, and completed), `NotALeader` (another replica holds the GC lease), `Deferred` (led but took the skip-unchanged fast path — no fold ran, because no changed shard reached the fold threshold and no deletion was due), `Aborted` (the round threw a transient error — backend unavailability, a lost lease, a concurrent leader; the next scheduled round retries it), `Stopped` (a transient error observed after the disk began shutting down: the round was cut short so the shutdown need not wait for it, and the next start re-derives its work), or `Error` (the round threw a non-transient error — investigate). +- `outcome` ([Enum8](/sql-reference/data-types/enum)) — `Unknown` (on a `Start` row), `Success` (led, folded, and completed), `NotALeader` (another replica holds the GC lease), `Deferred` (led but took the skip-unchanged fast path — no fold ran, because no changed shard reached the fold threshold and no deletion was due), `Aborted` (the round threw a transient error — backend unavailability, a lost lease, a concurrent leader; the next scheduled round retries it), `Stopped` (the round was cut short on request: the disk began shutting down, `SYSTEM CAS GC STOP` was issued, or the query of a manual round was killed or timed out), or `Error` (the round threw a non-transient error — investigate). A round stopped before its closing compare-and-swap adopted nothing, and the next round re-derives its work. A round stopped after it, for example a manual round killed during its post-commit cleanup, keeps its commit and has `round != 0`. Later rounds pick up most of the cleanup it skipped, but not a generation the hand-off reclaim did not finish: that is left to `cas-fsck`. See [post-commit failures](/antalya/cas/architecture/garbage-collection#post-commit-failures). - `candidates_marked` ([UInt64](/sql-reference/data-types/int-uint)) — Objects retired (marked) this round. - `objects_deleted` ([UInt64](/sql-reference/data-types/int-uint)) — Objects physically deleted this round. - `objects_absent` ([UInt64](/sql-reference/data-types/int-uint)) — Retire candidates found already absent. @@ -52,8 +52,8 @@ specified (it is enabled by default in the shipped `config.xml`). - `fence_outs` ([UInt64](/sql-reference/data-types/int-uint)) — Expired mounts fenced out by this round's heartbeat floor. - `anomalies` ([UInt64](/sql-reference/data-types/int-uint)) — Fold clamps surfaced (and survived) this round. A steady non-zero value warrants a look at the round log details. - `duration_ms` ([UInt64](/sql-reference/data-types/int-uint)) — The round wall-clock duration (on a `Finish` row). -- `error` ([String](/sql-reference/data-types/string)) — The exception text when `outcome = 'Aborted'`, `'Stopped'` or `'Error'`. On a `Stopped` row it names the request the shutdown refused, not the shutdown itself. -- `error_code` ([Int32](/sql-reference/data-types/int-uint)) — The exception code when `outcome = 'Aborted'`, `'Stopped'` or `'Error'`; `0` otherwise. Key monitoring on this column rather than on the `error` text. On an `Aborted`, `Stopped` or `Error` row the counters still report everything the round completed before it threw, and `round != 0` on such a row means the round's closing compare-and-swap committed and the failure hit only post-commit cleanup. +- `error` ([String](/sql-reference/data-types/string)) — The exception text when `outcome = 'Aborted'`, `'Stopped'` or `'Error'`. On a `Stopped` row it is the message of the exception that ended the round: for example `CAS GC round stopped by its scheduler` for `SYSTEM CAS GC STOP`, the query's own message for a killed or timed-out manual round, or an unresolved-write message when the stop landed after a write whose outcome is unknown. After a shutdown it names the request the shutdown refused, not the shutdown itself. +- `error_code` ([Int32](/sql-reference/data-types/int-uint)) — The exception code when `outcome = 'Aborted'`, `'Stopped'` or `'Error'`; `0` otherwise. Key monitoring on this column rather than on the `error` text. On a `Stopped` row it is the code the round ended with. That is usually `ABORTED` for `SYSTEM CAS GC STOP` and `QUERY_WAS_CANCELLED` or `TIMEOUT_EXCEEDED` for a killed or timed-out manual round, but any transient code can appear, such as `NETWORK_ERROR` when the stop landed after a write whose outcome is unknown. After a shutdown it is the refused request's code. On an `Aborted`, `Stopped` or `Error` row the counters still report everything the round completed before it threw, and `round != 0` on such a row means the round's closing compare-and-swap committed and the failure hit only post-commit cleanup. - `ProfileEvents` ([Map(LowCardinality(String), UInt64)](/sql-reference/data-types/map)) — On a `Start`/`Finish` row, the per-round `ProfileEvents` delta (the `CAS*` counters and S3/disk events for this round). On a `Phase` row, **that phase's** delta, so `GROUP BY phase` over `ProfileEvents['S3ListObjects']` attributes the round's `LIST` budget to the phase that spent it. - `round_id` ([String](/sql-reference/data-types/string)) — The correlator for every row of one round attempt: its `Start`, each of its `Phase` rows, and its `Finish`. Minted per attempt, so unlike `round` it exists even for a round that never committed and for a round that never led. Group by this column to reconstruct one round. - `phase` ([LowCardinality(String)](/sql-reference/data-types/lowcardinality)) — The GC phase this row describes; empty on `Start`/`Finish`. See [Per-phase rows](#per-phase-rows) for the phase list. @@ -92,15 +92,15 @@ The phases, in execution order: | `fold_seal_read` | The adopted fold seal, read twice at the same generation and attempt. | two fold-seal `GET`s | | `fold_ref_intake` | Read and fold every new ref log and the manifest bodies its edges name. `phase_metrics` carries five keys per source family, with the prefix `ckpt_` (namespace checkpoints), `reflog_` (ref logs) or `manifest_` (manifest bodies): `reads_issued` (reads started, ahead of time or at the moment the fold needs the result; a retry is not counted again), `takes` (results the fold consumed, absent ones included), `awaited` (takes whose result was not ready when the fold asked for it: every read made at that moment, and a read started ahead that had not finished; a sample at one instant), `wait_us` (time the GC thread spent in those takes, from that moment to the result) and `apply_us` (time from a take's result to the next take, or to the end of the checkpoint reads or of one namespace's walk: decoding, folding, and anything else the thread did meanwhile). `cursor_resolves` and `cursor_resolve_us` count and time the namespaces whose next ref log had to be found by reading from the stored fold cursor, because this process does not remember it, for example after a restart. `cursor_resolves` counts calls of the resolver, not reads: a cursor at or above the checkpoint's snapshot reads its own record, one below it in the snapshot's epoch needs no read, and one in an older epoch reads one ref log head per epoch it steps through. Those reads are not made ahead of time and are not in `reflog_reads_issued`; `cursor_resolve_us` is the time of the whole call. | one `GET` per new log, one `GET` per manifest edge | | `intent_sweep_list` | List one page of `blob-intents/` from the stored cursor to find deletion intents that have no row. Absent from a round whose destruction is suppressed. `phase_metrics` carries `listed`, `nominated`, `unparsed`, `wrapped` (`1` when the listing reached its end) and `list_budget_keys`. | one `LIST` page | -| `fold_reduce` | The per-shard in-degree merge: condemn and create intents, spare, decide deletes, adopt orphan intents. `phase_metrics` carries `condemned`, `intents_confirmed` (rows committed `pending`), `spared`, `body_deletes_decided` (body deletes decided), `adopted`, `nominations_waiting` (nominated intents left for a later fold: see [orphan intents](/antalya/cas/architecture/garbage-collection#orphan-intents)), `read_ahead_blobs` (blobs the fold holds in memory to read the `HEAD`s of `pending` and `standing` rows ahead; 0 when no parent row is `pending` or `standing`), `suppress_destructive` (`1` when the round deleted no body or intent: an anomaly, a held namespace, an incomplete reference frontier, a stop request seen before the end of the ref intake, or `parent_unconfirmed`), `frontier_complete` (`0` when the round could not prove its reference frontier complete, which suppresses deletes), `parent_unconfirmed` (`1` when the `HEAD` of `gc/state` after the intake did not show the leased version, so the round deleted nothing), `condemned_rows` (rows the round leaves on file: `candidate`, `pending` and `standing`) and `pending_rows` (the `pending` and `standing` rows among them). | prior-run streaming `GET`s, one `HEAD` per blob that needs a decision, one intent `PUT` per intent created, run `PUT`s | +| `fold_reduce` | The per-shard in-degree merge: condemn and create intents, spare, decide deletes, adopt orphan intents. `phase_metrics` carries `condemned`, `intents_confirmed` (rows committed `pending`), `spared`, `body_deletes_decided` (body deletes decided), `adopted`, `nominations_waiting` (nominated intents left for a later fold: see [orphan intents](/antalya/cas/architecture/garbage-collection#orphan-intents)), `read_ahead_blobs` (blobs the fold holds in memory to read the `HEAD`s of `pending` and `standing` rows ahead; 0 when no parent row is `pending` or `standing`), `suppress_destructive` (`1` when the round deleted no body or intent: an anomaly, a held namespace, an incomplete reference frontier, a stop request seen before the end of the ref intake, or `parent_unconfirmed`), `frontier_complete` (`0` when the round could not prove its reference frontier complete, which suppresses deletes), `parent_unconfirmed` (`1` when the `HEAD` of `gc/state` after the intake did not show the leased version, so the round deleted nothing), `condemned_rows` (rows the round leaves on file: `candidate`, `pending` and `standing`) and `pending_rows` (the `pending` and `standing` rows among them). | prior-run streaming `GET`s, one `HEAD` per blob that needs a decision, one intent `PUT` per intent created, run `PUT`s; when the orphan-manifest sweep is planned, its manifest `LIST` page and the `GET`s that decide its nominations | | `fold_seal_write` | Publish the new fold seal. | one `PUT` | | `pending_deletes` | The single content-delete site: exact-token deletes of bodies whose rows were `pending` in the adopted state, then the deletion-intent deletes, plus the outcome logs. `phase_metrics` carries `bodies_deleted` (body deletes answered this round), `jobs_scheduled` (bodies sent to the GC I/O pool; `0` for no candidates, sequential execution, singleton batches, or refusal before the first submission), `jobs_failed` and `intents_deleted`. | one `DELETE` per body, intent deletes in batch requests, one outcome-log `PUT` per shard with rows | | `round_commit` | The generation-retention prune and the round's single `gc/state` compare-and-swap. | prune `LIST`s and deletes, one compare-and-swap | | `handoff_reclaim` | Wholesale-reclaim generations a moved run ref stranded below the retention cursor. | prefix `LIST`s and deletes | -| `manifest_deletes` | Exact-token deletes of owner-removed manifest bodies, after their decrements were adopted. | one `DELETE` per body | +| `manifest_deletes` | Deletes of owner-removed manifest bodies, after their decrements were adopted. The keys are write-once, so the deletes carry no token. | batch `DELETE` requests of up to `cas_gc_bulk_delete_chunk_keys` keys; one `DELETE` per key on a storage without a batch delete | +| `orphan_sweep` | Deletes the orphan part manifests that `fold_reduce` nominated and the round's commit adopted. | one `HEAD` per nomination, one exact-token `DELETE` per nomination still present at its token | | `namespace_cleanup` | Run `cas/ns/` pages across the stream and state subtrees for the perpetual dead-life janitor, under a 20 s soft budget; `budget_exhausted` is 1 when the budget stopped the phase, `delete_requests` counts the phase's delete calls, which run on the GC I/O pool and are missing from this row's `ProfileEvents`. This phase is physical reclamation, not a lifecycle gate. | per page: one namespace-root page `LIST`, catalog cut, batch deletes of dead ref logs and snapshots, exact-token deletes of the rest | -| `ref_object_cleanup` | Delete ref logs covered by both the durable fold cursor and a durable snapshot, plus superseded snapshots. | one `HEAD` + one `DELETE` per deletable object | -| `orphan_sweep` | The budgeted, cursor-paced orphan part-manifest backstop. | budgeted `LIST` and deletes | +| `ref_object_cleanup` | Delete ref logs covered by both the durable fold cursor and a durable snapshot, plus superseded snapshots. | per planned namespace, the `GET`s that validate its recovery base; per chunk, up to one ref catalog and one `gc/state` `GET` and one batch `DELETE` of up to `cas_gc_bulk_delete_chunk_keys` write-once keys (one `DELETE` per key on a storage without a batch delete) | Which phase dominates a round: diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasBackend.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasBackend.h index 951efdab36567..4da87153c7009 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasBackend.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasBackend.h @@ -37,6 +37,10 @@ extern const int CORRUPTED_DATA; namespace DB::Cas { +/// Neither a store or transport answer nor a stopped query's stored cause: a bug or a resource report, which +/// request loops and backend adapters surface unchanged. +bool isLocalFault(const std::exception_ptr & e); + /// Typed erasure evidence for one key or one prefix. Ordinary `head`/`read` answer only two things /// for a plain caller: the object, or nullopt for the store's own authoritative "key not found" (see /// `isObjectNotFound`) -- every other fault (a missing bucket/container, a permission failure, a @@ -297,8 +301,9 @@ class Backend /// Authoritative, cache-bypassing probe of one key -- see `ProbeOutcome`. DEFAULT (used by every /// backend without sharper raw-error evidence, e.g. `InMemoryBackend`): derived from `head`/`read` - /// alone, so it can only distinguish `Present` from `KeyAbsent`, and ANY exception from either - /// call is `Indeterminate` -- never promoted to `KeyAbsent`. A backend able to surface real + /// alone, so it can only distinguish `Present` from `KeyAbsent`, and any other answer from either + /// call is `Indeterminate` -- never promoted to `KeyAbsent`. A local fault propagates (`isLocalFault`), in + /// every override too. A backend able to surface real /// container/permission evidence (the S3-native and Local paths of `ObjectStorageBackend`) /// overrides this to sharpen the classification. virtual SentinelProbeResult probeSentinelRaw(const String & key, TransportAccess & access) @@ -316,6 +321,8 @@ class Backend } catch (...) { + if (isLocalFault(std::current_exception())) + throw; return {ProbeOutcome::Indeterminate, std::nullopt}; } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp index 81b7096808608..9720672200643 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -32,13 +33,9 @@ namespace GaveUp::Source sourceFor(const Retry::Bound & bound) { - return bound.lease_bound ? GaveUp::Source::Lease : GaveUp::Source::Policy; + return bound.source == Retry::Bound::Source::Lease ? GaveUp::Source::Lease : GaveUp::Source::Policy; } -/// The wait slice: how late, at most, a waiter notices its own fence or deadline. A handover wakes it -/// at once through the lane's condition variable. -constexpr auto kWaitSlice = std::chrono::milliseconds(200); - } CasHotKeys::CasHotKeys(uint64_t cache_budget_bytes_) @@ -59,12 +56,11 @@ CasHotKeys::~CasHotKeys() chassert(lanes.empty()); } -WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide) +WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide, Start start, + OnLoss on_loss) { - /// Frozen here so that the queue wait and the write share one deadline; a policy already frozen - /// by the caller's loop is returned unchanged. - const Retry frozen = op.freeze(policy); - const Retry::Bound bound = op.owner.bindPolicy(frozen); + /// The wait has its own end, taken here; each request after it binds its own window. + const Retry::Bound wait_end = op.owner.bindPolicy(policy); const uint64_t entered_ms = op.owner.now_ms(); Item item{}; @@ -101,7 +97,7 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr ~Leave() noexcept { owner.leave(key, item, entered_hold, entered_ms, op); } } guard{*this, key, item, entered_hold, entered_ms, op}; - for (;;) + for (bool waited = false;; waited = true) { /// Outside the mutex: the engine's own admission in the engine's order (the fence generation, /// the lease budget, then the caller's liveness, which the engine reports as a lost fence), @@ -112,7 +108,7 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr switch (op.gate(0)) { case CasOperation::Gate::FenceLost: - leaving = op.gaveUp(GaveUp::Why::FenceLost, sourceFor(bound), nothing_sent); + leaving = op.gaveUp(GaveUp::Why::FenceLost, sourceFor(wait_end), nothing_sent); break; case CasOperation::Gate::NoBudget: leaving = op.gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, nothing_sent); @@ -120,8 +116,11 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr case CasOperation::Gate::Ok: break; } - if (!leaving && !op.fits(0, bound)) - leaving = op.gaveUp(GaveUp::Why::Deadline, sourceFor(bound), nothing_sent); + if (!leaving && !op.fits(0, wait_end)) + leaving = op.gaveUp(GaveUp::Why::Deadline, sourceFor(wait_end), nothing_sent); + /// The front caller gets its first read. Waiters check their background owner after fence admission. + if (waited && !leaving) + throwIfBackgroundStopped(); /// Read outside the mutex, as `leave` already does: the mutex is a leaf that calls nothing, /// and `now_ms` is a closure the pool injects, not a fixed clock. @@ -136,10 +135,11 @@ WriteResult CasHotKeys::submit(const String & key, CasOperation & op, const Retr entered_hold = true; break; } - lane.cv.wait_for(lock, kWaitSlice); + /// The slice also bounds how late the waiter notices its own fence or deadline; a handover wakes it at once. + lane.cv.wait_for(lock, kOwnerStopSlice); } ProfileEvents::increment(ProfileEvents::CASHotKeyQueueWaitMicroseconds, (op.owner.now_ms() - entered_ms) * 1000); - return hold(key, op, frozen, bound, decide); + return hold(key, op, policy, decide, start, on_loss); } void CasHotKeys::leave(const String & key, Item & item, bool entered_hold, uint64_t entered_ms, CasOperation & op) noexcept @@ -194,15 +194,16 @@ void CasHotKeys::leave(const String & key, Item & item, bool entered_hold, uint6 } } -WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry & policy, const Retry::Bound & bound, - const Decide & decide) +WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry & policy, const Decide & decide, Start start, + OnLoss on_loss) { + /// Every write of this hold, and its base read, are one submission's: they share one record of what was sent. CasOperation::WriteState state; std::optional base; bool from_cache = false; /// A single-attempt submission never starts from a hint: its one attempt is on fresh state, as /// the engine's own verb reads before it. - if (!policy.single_attempt) + if (!policy.single_attempt && start == Start::CacheOrRead) { if (auto remembered = cached(key)) { @@ -214,13 +215,13 @@ WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry const auto read_base = [&]() -> std::optional { ProfileEvents::increment(ProfileEvents::CASHotKeyReadStarts); - CasOperation::Resolved resolved = op.observe(key, policy, bound); + CasOperation::Resolved resolved = op.observe(key, policy); state.last_seen = resolved.seen; base.reset(); if (const auto * object = std::get_if(&state.last_seen)) base = *object; else if (!std::holds_alternative(state.last_seen)) - return op.gaveUpAfterFailedObservation(resolved.stop, state, bound); + return op.gaveUpAfterFailedObservation(resolved, state); return std::nullopt; }; if (!from_cache) @@ -229,6 +230,7 @@ WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry std::optional candidate; bool verdict_on_hint = false; + throwIfBackgroundStopped(); try { candidate = decide(base); @@ -238,6 +240,12 @@ WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry { if (!from_cache) throw; + /// A stopped background owner's exception says nothing about the hint, so it is not worth a reread. A + /// lost admission `decide` may have thrown on goes first: the reread's own gate reports it. A killed + /// query rereads, as a healthy read is never refused. + if (op.admitted()) + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(stop); verdict_on_hint = true; } if (verdict_on_hint) @@ -250,32 +258,65 @@ WriteResult CasHotKeys::hold(const String & key, CasOperation & op, const Retry if (auto refused = read_base()) return *refused; from_cache = false; + throwIfBackgroundStopped(); candidate = decide(base); } - if (!candidate) + const auto declined = [&] { if (base) remember(key, *base); return Declined{state.last_seen}; - } - - WriteResult result = [&] + }; + const bool retried_after_a_pause = on_loss == OnLoss::SubmitAgain && !policy.single_attempt; + const auto write = [&] { + /// A loss on a hint is settled: the retry below decides on that read. A loss on a fresh read that the + /// caller retries is repaid by its pause and a read after it, so a settling read would go unused. + const auto on_clean_refusal = from_cache || !retried_after_a_pause + ? CasOperation::OnCleanRefusal::Settle : CasOperation::OnCleanRefusal::ReturnUnobserved; try { - return base ? op.replace(key, *candidate, base->etag, policy) : op.create(key, *candidate, policy); + return op.writeLoop(key, *candidate, base ? std::optional(base->etag) : std::nullopt, policy, + state, CasOperation::ResolveWith::Body, on_clean_refusal); } catch (...) { forget(key); throw; } - }(); + }; + if (!candidate) + return declined(); + WriteResult result = write(); + + /// A clean loss on a hint says only that the hint was old, not that the key is contended: decide + /// again on the resolve read and write at once, so nothing waits between that read and the write. + if (const auto * conflict = std::get_if(&result); from_cache && conflict && !conflict->any_ambiguous + && !conflict->observed_stop + && (std::holds_alternative(conflict->seen) || std::holds_alternative(conflict->seen))) + { + forget(key); + state.last_seen = conflict->seen; + base.reset(); + if (const auto * object = std::get_if(&state.last_seen)) + base = *object; + from_cache = false; + throwIfBackgroundStopped(); + candidate = decide(base); + if (!candidate) + return declined(); + result = write(); + } + std::visit(detail::Overload{ [&](const Committed & committed) { remember(key, Object{*candidate, committed.etag}); }, [&](const Conflict & conflict) { - if (const auto * object = std::get_if(&conflict.seen)) + /// A caller that retries a `Conflict` pauses first, and a body read before that pause would + /// refuse its next write once anyone commits during it: the next hold reads instead. + const bool retried = retried_after_a_pause && !conflict.observed_stop; + const auto * object = std::get_if(&conflict.seen); + if (object && !retried) remember(key, *object); else forget(key); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h index d41ec95e16525..3adef679851e1 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasHotKeys.h @@ -26,16 +26,18 @@ class CasOperation; /// growing sleep. `submit` takes a FIFO ticket for the key, waits its turn re-checking the caller's /// own fence, lease and deadline, obtains a base (the cache's object, else the engine's own read), /// runs the caller's `decide` on it, lands the candidate through the engine's `replace` or `create` -/// on the caller's own operation and thread, and returns the engine's result unchanged. The caller -/// keeps the retry loop: a `Conflict` is a lost race against another server, and the caller submits -/// again after `Retry::conflictBackoff`. +/// on the caller's own operation and thread, and returns the engine's result. The caller keeps the +/// retry loop: a `Conflict` is a lost race against another server, and the caller submits again after +/// `Retry::conflictBackoff` with `Start::Read`. Such a `Conflict` on a fresh read is returned unsettled +/// (`NotObserved`) and leaves no cached body, since the read after the pause replaces both. /// /// The cache is a hint and never a source of truth: every write against it is conditional on its -/// etag, so a stale entry costs one 412 and one resolve read; and a verdict a `decide` renders on it +/// etag, so a stale entry costs one 412 and one resolve read, on which the hold decides and writes +/// again at once (unless the 412 settled a transport fault); and a verdict a `decide` renders on it /// (a refusal by exception, or "nothing to write") is never delivered, because a refusal without a /// write is the one thing a 412 cannot correct -- the entry is dropped, the key is read, and the -/// `decide` runs again on the read. The store's answer to a write decided on a hint is delivered -/// whatever it is: it is a fact about the store, and the caller's ordinary retry learns the rest. +/// `decide` runs again on the read. Any other answer to a write decided on a hint is delivered as it +/// is: it is a fact about the store, and the caller's ordinary retry learns the rest. /// /// One instance per pool, shared by its three request planes; a `CasRequests` built without one owns /// a private instance with no cache. Every callback (`decide`, a `Liveness` closure, a backend hook) @@ -56,11 +58,21 @@ class CasHotKeys /// its reads go through `op`; it reads `base->bytes` and never `base->etag`. using Decide = std::function(const std::optional &)>; - /// One hold on `key`: wait for the turn, obtain a base, run `decide`, one engine write, remember. - /// `policy` is frozen at entry, so time in the queue spends the caller's window. Returns the - /// engine's own result for that write, in class and content, and propagates a `decide`'s - /// exception as `readModifyWrite` does, never from a cached base. - WriteResult submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide); + /// One hold on `key`: wait for the turn, obtain a base, run `decide`, one engine write, remember; a + /// clean `Conflict` on a cached base adds one more `decide` and write on the resolve read. + /// The wait ends at the window of `policy`, or its earlier lease, taken at entry; the base read and + /// the write each bind their own. Returns the engine's own result for that write, except that a clean + /// `Conflict` on a fresh read that the caller retries (`OnLoss::SubmitAgain`, not a single attempt) is not + /// settled and carries `NotObserved`; it + /// propagates a `decide`'s exception as `readModifyWrite` does, never from a cached base. + /// `Start::Read` skips the cache: a caller that paused since its last submission must not write on a + /// body another holder remembered during that pause. + enum class Start : uint8_t { CacheOrRead, Read }; + /// `OnLoss::End`: the caller will not submit again after a lost race, so a refusal is settled, as under a + /// single attempt, and the caller learns what won. + enum class OnLoss : uint8_t { SubmitAgain, End }; + WriteResult submit(const String & key, CasOperation & op, const Retry & policy, const Decide & decide, + Start start = Start::CacheOrRead, OnLoss on_loss = OnLoss::SubmitAgain); /// Items in the key's queue, the holder included; 0 for a key with no lane. size_t queueDepthForTest(const String & key) const; @@ -104,8 +116,7 @@ class CasHotKeys }; using Cache = CacheBase, RememberedWeight>; - WriteResult hold(const String & key, CasOperation & op, const Retry & policy, const Retry::Bound & bound, - const Decide & decide); + WriteResult hold(const String & key, CasOperation & op, const Retry & policy, const Decide & decide, Start start, OnLoss on_loss); void leave(const String & key, Item & item, bool entered_hold, uint64_t entered_ms, CasOperation & op) noexcept; std::optional cached(const String & key) const; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp index f0cbdf2e4dc90..ad32d87eeda5c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasObjectStorageBackend.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -264,6 +265,9 @@ detail::ConditionalWriteOutcome detail::finalizeConditionalWrite(WriteBuffer & b } catch (const S3Exception & e) { + /// A stopped query's stored cause can be a `412` and says nothing about the write; any other `412` is the store's. + if (isQueryStoredCause(std::current_exception())) + throw; if (e.isPreconditionFailed() || e.getExceptionName() == "NoSuchKey" || e.getS3ErrorCode() == Aws::S3::S3Errors::NO_SUCH_KEY) @@ -355,6 +359,10 @@ std::expected ObjectStorageBackend::nativeConditio /// Any other error (network, auth, throttle, corruption) propagates unchanged — fail-closed. static bool isObjectNotFound(const std::exception & e) { + /// A stopped query's stored cause can carry a not-found code and says nothing about the key. Any other miss + /// is the store's answer: the S3 client replaces a miss it sees under a killed query with the query's exception. + if (isQueryStoredCause(std::current_exception())) + return false; #if USE_AWS_S3 if (const auto * s3e = dynamic_cast(&e)) return s3e->getS3ErrorCode() == Aws::S3::S3Errors::NO_SUCH_KEY @@ -765,6 +773,9 @@ SentinelProbeResult ObjectStorageBackend::probeSentinelUnder(const String & key, #if USE_AWS_S3 catch (const S3Exception & e) { + /// A stopped query's stored cause says nothing about the key; any other error is the store's answer. + if (isQueryStoredCause(std::current_exception())) + return {ProbeOutcome::Indeterminate, std::nullopt}; /// `read` already answers the key-absent half of the store's 404 family (see /// `isObjectNotFound`), so what reaches here is what it deliberately does not flatten. /// The limit of the one-read shape: every case below classifies an error a GET raised, so @@ -784,6 +795,8 @@ SentinelProbeResult ObjectStorageBackend::probeSentinelUnder(const String & key, #endif catch (...) { + if (isLocalFault(std::current_exception())) + throw; return {ProbeOutcome::Indeterminate, std::nullopt}; } } @@ -803,6 +816,8 @@ SentinelProbeResult ObjectStorageBackend::probeSentinelUnder(const String & key, } catch (...) { + if (isLocalFault(std::current_exception())) + throw; return {ProbeOutcome::Indeterminate, std::nullopt}; } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp new file mode 100644 index 0000000000000..7fe8fde5bf080 --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.cpp @@ -0,0 +1,238 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace DB::ErrorCodes +{ + extern const int CANNOT_SCHEDULE_TASK; + extern const int LOGICAL_ERROR; +} + +namespace DB::Cas +{ + +thread_local OwnerScope::State OwnerScope::current; + +namespace +{ + +/// The exception `check` throws, or null. +template +std::exception_ptr exceptionOf(Check && check) +{ + try + { + check(); + } + catch (...) + { + return std::current_exception(); + } + return nullptr; +} + +} + +std::exception_ptr ownerStopRequested() +{ + const auto & owner = OwnerScope::current; + if (owner.shared) + return nullptr; + return exceptionOf([&] + { + CurrentThread::checkIfNotCancelled(); + if (owner.background) + owner.background(); + }); +} + +bool queryStopRequested() +{ + return !OwnerScope::current.shared && exceptionOf([] { CurrentThread::checkIfNotCancelled(); }) != nullptr; +} + +void throwIfBackgroundStopped() +{ + const auto & owner = OwnerScope::current; + if (!owner.owed && !owner.shared && owner.background) + owner.background(); +} + +void throwIfQueryStopped() +{ + const auto & owner = OwnerScope::current; + if (!owner.owed && !owner.shared) + CurrentThread::checkIfNotCancelled(); +} + +bool insideOwed() +{ + return OwnerScope::current.owed; +} + +std::exception_ptr backgroundStopRequested() +{ + const auto & owner = OwnerScope::current; + if (owner.shared || !owner.background) + return nullptr; + return exceptionOf(owner.background); +} + +namespace +{ + +/// The throwing check builds a new exception on each call for a query killed without a stored cause, so it runs only +/// after the kill flag that check reads is set. +bool isStoredCauseOfThisThreadsQuery(const std::exception_ptr & e) +{ + if (!e) + return false; + const ContextPtr query = CurrentThread::tryGetQueryContext(); + if (!query || !query->isCurrentQueryKilled()) + return false; + return e == exceptionOf([] { CurrentThread::checkIfNotCancelled(); }); +} + +} + +bool isQueryStoredCause(const std::exception_ptr & e) +{ + return !OwnerScope::current.shared && isStoredCauseOfThisThreadsQuery(e); +} + +void addMessageUnlessQueryStoredCause(Exception & e, const std::string & message) +{ + if (!isStoredCauseOfThisThreadsQuery(std::current_exception())) + e.addMessage(message); +} + +void rethrowOwnCopy(const std::exception_ptr & e) +{ + if (!e) + throw Exception(ErrorCodes::LOGICAL_ERROR, "rethrowOwnCopy: no exception to rethrow"); + if (isStoredCauseOfThisThreadsQuery(e)) + std::rethrow_exception(e); + try + { + std::rethrow_exception(e); + } + catch (const Poco::Exception & shared) + { + /// The copy allocates; a receiver at its memory limit must still get the shared failure. + LockMemoryExceptionInThread lock_memory_tracker(VariableContext::Global); + shared.rethrow(); + } +} + +void rethrowIfStoppedOwnersFailure() +{ + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(std::move(stop)); + if (queryStopRequested()) + throw; +} + +void throwUnlessInThreadGroup(const ThreadGroupPtr & expected, std::string_view worker) +{ + if (expected && CurrentThread::getGroup() != expected) + throw Exception(ErrorCodes::CANNOT_SCHEDULE_TASK, + "{} could not join its thread group, so it sends nothing", worker); +} + +bool sleepUnlessQueryStops(uint64_t ms, const std::function & sleep) +{ + if (insideOwed() || !CurrentThread::getGroup()) + { + sleep(ms); + return true; + } + constexpr auto slice_ms = static_cast(kOwnerStopSlice.count()); + uint64_t left = ms; + do + { + if (queryStopRequested()) + return false; + const uint64_t slice = std::min(left, slice_ms); + sleep(slice); + left -= slice; + } while (left > 0); + return !queryStopRequested(); +} + +void waitStoppable(std::condition_variable & cv, std::unique_lock & lock, const std::function & ready) +{ + /// Only a background owner is polled; without one in effect a notification is the only way out. + if (!OwnerScope::effectiveCheck()) + { + cv.wait(lock, ready); + return; + } + while (true) + { + /// The predicate is leaf-locked by contract (`OwnerScope::background`); unlocking keeps the caller's mutex + /// free while it builds its exception. + lock.unlock(); + std::exception_ptr verdict = backgroundStopRequested(); + lock.lock(); + if (verdict) + std::rethrow_exception(std::move(verdict)); + if (ready()) + return; + cv.wait_for(lock, kOwnerStopSlice); + } +} + +OwnerScope::OwnerScope(State next) + : saved(std::exchange(current, std::move(next))) +{ +} + +OwnerScope::OwnerScope(OwnerScope && other) noexcept + : saved(std::move(other.saved)) + , active(std::exchange(other.active, false)) +{ +} + +OwnerScope::~OwnerScope() +{ + if (active) + current = std::move(saved); +} + +OwnerScope OwnerScope::background(std::function throw_if_stopped) +{ + if (current.background) + throw_if_stopped = [outer = current.background, inner = std::move(throw_if_stopped)] + { + outer(); + inner(); + }; + return OwnerScope(State{current.owed, current.shared, std::move(throw_if_stopped)}); +} + +OwnerScope OwnerScope::owed() +{ + return OwnerScope(State{true, current.shared, current.background}); +} + +OwnerScope OwnerScope::shared() +{ + return OwnerScope(State{current.owed, true, current.background}); +} + +std::function OwnerScope::effectiveCheck() +{ + if (current.owed || current.shared) + return {}; + return current.background; +} + +} diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h new file mode 100644 index 0000000000000..fab5f4478f5f9 --- /dev/null +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasOwner.h @@ -0,0 +1,173 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace DB +{ +class Exception; +class ThreadGroup; +using ThreadGroupPtr = std::shared_ptr; +} + +namespace DB::Cas +{ + +/// Lets the owner of CAS work stop it: the query, or a background owner. The background owners are the GC scheduler's +/// stop and server shutdown's removal of an `Atomic` table's namespace. Pool teardown is not one: it ends work through +/// the operation's liveness and the detached-work stop token. +/// +/// Decision points, where work may end. Inside `owed` or `shared` they do nothing, except that the catch helper +/// still acts inside `owed` and the thread-group guard throws in every scope: +/// +/// | Point in the code | Helper | +/// |----------------------------------------------------|---------------------------------------------------------| +/// | Before more work: a retry, a decision, a next page | `throwIfBackgroundStopped` | +/// | Head of a CAS-owned resumable scan | `throwIfQueryStopped`, then `throwIfBackgroundStopped` | +/// | A pause after a failure | `sleepUnlessQueryStops` | +/// | A wait on a condition variable | `waitStoppable` | +/// | A worker that switched to the submitter's group | `throwUnlessInThreadGroup` | +/// | A catch that would swallow, convert or retry | `rethrowIfStoppedOwnersFailure`, also inside `owed` | +/// +/// Facts, for code that classifies a failure. They hold inside `owed` too and decide nothing: +/// +/// | Question | Helper | +/// |----------------------------------------------------|---------------------------------------------------------| +/// | Did an owner ask to stop, and with what verdict | `ownerStopRequested`, `queryStopRequested`, `backgroundStopRequested` | +/// | Is this exception the query's stored cause | `isQueryStoredCause` | +/// | Annotating or rethrowing a caught exception | `addMessageUnlessQueryStoredCause`, `rethrowOwnCopy` | +/// +/// A query is consulted only where stopping leaves the state a storage failure there would leave: after a failed +/// attempt (its retry, its pause, a catch that would swallow or convert it) and at a scan head. It does not end a first +/// attempt, a decision after an accepted conflict, a wait, compensation, `abandon`, namespace removal, `FORGET`, or +/// recovery's first walk. The `SYSTEM CAS FSCK` scan has no scan head. +/// +/// What a stop ends with: +/// - A stopped owner's exception is not a store answer: neither absence, nor a refusal, nor a local fault. A local +/// fault is surfaced unchanged. +/// - A vetoed retry of a read or a blob publication ends with the failed attempt's exception, whatever its code: a +/// timed-out attempt's `TIMEOUT_EXCEEDED` is that attempt's own. A vetoed retry after a credential refusal ends as +/// a retry-later `NETWORK_ERROR` carrying the refusal, unless the read already refreshed after an earlier failure. +/// - A vetoed resend of a conditional write ends as the retry-later `NETWORK_ERROR` "unresolved", naming what its +/// settling read saw, not the store's error. With no earlier attempt unanswered, a refusal keeps the store's error, +/// except that a vetoed resend with refreshed credentials ends as a retry-later `NETWORK_ERROR` carrying the +/// refusal. A scan head throws the query's verdict. +/// - A killed query's conditional write that loses a race can end as `ABORTED` "conflict": the S3 client replaces the +/// 412 with the query's exception, and the settling read shows the other writer's object. +/// - An unresolved sent write keeps its "outcome unknown" exit; a later owner verdict does not overwrite it. +/// - `OwnerScope::owed` removes the checks before work and the query's cut of a pause: the pause runs to its end, and +/// the next attempt is sent unless the fence, the lease or a deadline refuses it after the pause. A failure after a +/// stop is still not retried, and a background owner's verdict still replaces it. `OwnerScope::shared` removes the +/// owner. Neither hides a query from the S3 client, which replaces a failed request's answer with the query's +/// verdict; a bulk delete that succeeds with an error for one key keeps that key's error. +/// - Code above the engine may still do follow-up work its own counts bound, such as another recovery walk. With a +/// lease loss or a credential refusal at the same time, the error can be the less specific of the two. + +/// How late a waiter that nobody notifies notices its owner's stop. +inline constexpr std::chrono::milliseconds kOwnerStopSlice{200}; + +/// The verdict of the owner of this thread's work if it asked to stop: the query's +/// (`CurrentThread::checkIfNotCancelled`), then the background owners' in scope. Null inside `shared`. +std::exception_ptr ownerStopRequested(); + +/// True when the thread's query, not a background owner, asked to stop. False inside `shared`. +/// The S3 client throws the query's verdict in place of a failed request's answer, but not of one key's error in a +/// bulk delete that succeeded, and it cannot see a background owner. +bool queryStopRequested(); + +/// Rethrows the verdict of the background owners in scope, except inside `owed` or `shared`. Ignores the query. +void throwIfBackgroundStopped(); + +/// Rethrows the query's verdict, except inside `owed` or `shared`. Ignores background owners. For a scan head only. +void throwIfQueryStopped(); + +/// True inside `owed`: owner checks do not throw, and `observe` reports a stopped owner's failed read as not observed. +bool insideOwed(); + +/// The background owners' verdict, also inside `owed`; ignores the query. Null inside `shared`. +std::exception_ptr backgroundStopRequested(); + +/// True when `e` is the query's stored cancellation cause, the one verdict rethrown as the same object to every thread +/// the query stops; false inside `shared`. A kill or timeout without a stored cause and every background owner's verdict +/// are built anew on each check, so they never match. Such a cause is neither a store answer nor a local fault, +/// whatever its code or type. +bool isQueryStoredCause(const std::exception_ptr & e); + +/// Adds `message` to `e`, the exception being handled, unless `e` is the query's stored cause, whatever the scope: +/// several threads may hold that one object, so annotating it would race. +void addMessageUnlessQueryStoredCause(Exception & e, const std::string & message); + +/// Rethrows `e`, which several threads may hold, as this thread's own copy made by `Poco::Exception::rethrow`, so a +/// caller that annotates what it catches races with nobody. The query's stored cause and an exception that is not a +/// `Poco::Exception` are rethrown as they are. A memory limit does not replace the copy. +[[noreturn]] void rethrowOwnCopy(const std::exception_ptr & e); + +/// For a catch about to swallow, convert or retry the exception being handled: rethrows the background owners' +/// verdict, or the exception being handled when the query stopped. A killed query keeps the error of its own failure. +void rethrowIfStoppedOwnersFailure(); + +/// For work that switched to `expected`, such as a pool worker joining the group that submitted it: throws +/// `CANNOT_SCHEDULE_TASK` unless the thread is in it; no check when it is null. `ThreadGroupSwitcher` swallows its own +/// failure, and a request sent outside the intended group sees the wrong query. +void throwUnlessInThreadGroup(const ThreadGroupPtr & expected, std::string_view worker); + +/// Sleeps `ms` through `sleep`. Outside `owed`, on a thread with a thread group, sleeps in `kOwnerStopSlice` slices and +/// checks the query before each slice and after the last; false when it stopped, leaving the rest unslept. +bool sleepUnlessQueryStops(uint64_t ms, const std::function & sleep); + +/// Waits until `ready` holds, throwing as `throwIfBackgroundStopped` does. Checks the owners with `lock` released +/// before each evaluation of `ready`; with no background owner in effect it is a plain `cv.wait`. Returns and throws +/// with `lock` held. +void waitStoppable(std::condition_variable & cv, std::unique_lock & lock, const std::function & ready); + +/// Thread-scoped like query cancellation, so no owner parameter crosses the request engine. Scopes nest; +/// a nested scope never lifts an enclosing `owed` or `shared`. Destruction restores the enclosing scope. +class OwnerScope +{ +public: + /// An owner with no thread group predicate; `throw_if_stopped` throws its verdict. It runs under CAS + /// mutexes, so it is lock-free or takes a leaf lock. Enclosing background owners stay checked first. + static OwnerScope background(std::function throw_if_stopped); + /// Work owed to a possibly-sent write, a failed commit or a claimed resource: no throwing check. + static OwnerScope owed(); + /// Work for several callers: CAS owner checks see no owner. The S3 client still replaces a failed answer with the + /// exception of the thread's query. + static OwnerScope shared(); + + /// This thread's background owner check, to keep calling inside a later `shared` scope. Valid only while the + /// scope that installed it is alive. Empty without a background owner and inside `owed` or `shared`. + static std::function effectiveCheck(); + + OwnerScope(OwnerScope && other) noexcept; + ~OwnerScope(); + +private: + struct State + { + bool owed = false; + bool shared = false; + std::function background; + }; + + explicit OwnerScope(State next); + + friend std::exception_ptr ownerStopRequested(); + friend bool queryStopRequested(); + friend bool insideOwed(); + friend void throwIfBackgroundStopped(); + friend void throwIfQueryStopped(); + friend std::exception_ptr backgroundStopRequested(); + friend bool isQueryStoredCause(const std::exception_ptr & e); + static thread_local State current; + + State saved; + bool active = true; +}; + +} diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.cpp index a0cc03c1c113a..7fe6e68aa8f4f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.cpp @@ -31,9 +31,6 @@ uint64_t CasRequestBudget::attemptEnvelopeMs() const void setCasRequestWindow(CasRequestBudget & budget, uint64_t window_ms) { budget.request_window_ms = window_ms; - budget.recovery_retry_budget_ms = window_ms > std::numeric_limits::max() / 2 - ? std::numeric_limits::max() - : 2 * window_ms; } void validateCasRequestWindow(const CasRequestBudget & budget) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.h index f87bcfc01692d..eb2139f3338ff 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequestBudget.h @@ -11,7 +11,7 @@ inline constexpr uint64_t kDefaultRequestWindowMs = 120000; /// The limits a writable mount is configured with. `CasMountRuntime::admit` measures a request against /// `lease_safety_margin_ms` plus a caller-supplied need expressed in attempt envelopes (one for an /// ordinary attempt, TWO for a ref-log append's write-plus-settlement-read -- see -/// `CasMountRuntime::refAppendFenceOk`), and the three `recovery_retry_*` fields bound a whole +/// `CasMountRuntime::refAppendFenceOk`), and the `recovery_retry_*` backoff fields pace a whole /// ref-table recovery; see `validateCasRequestBudget` for the relationship a writable mount enforces /// at startup. struct CasRequestBudget @@ -42,19 +42,14 @@ struct CasRequestBudget /// Recovery-level retry (`CasRefLedger::ensureRefTableRecovered`): a whole ref-table recovery /// attempt (LIST + snapshot/log GETs + seal PUT) that fails with a transient NETWORK_ERROR is - /// retried, with capped-exponential backoff, until this total wall-clock budget is spent — then the - /// error propagates and the table's load fails for this touch (the `lazy_load_tables` database - /// setting makes the NEXT touch retry). This sits ON TOP of each write's own `Retry` policy window - /// (`request_window_ms`): one recovery attempt may itself burn that long inside a single seal PUT, so the - /// storage layer sets this to twice the window. Not part of the inequality set validated in + /// retried, with capped-exponential backoff, until `kCasMaxRecoveryWalks` walks have started — then + /// the error propagates and the table's load fails for this touch (the `lazy_load_tables` database + /// setting makes the NEXT touch retry). Not part of the inequality set validated in /// `validateCasRequestBudget`. - uint64_t recovery_retry_budget_ms = 2 * kDefaultRequestWindowMs; uint64_t recovery_retry_initial_backoff_ms = 1000; uint64_t recovery_retry_max_backoff_ms = 30000; }; -/// Sets `request_window_ms` and derives `recovery_retry_budget_ms` as twice the window, saturating: one -/// recovery attempt can spend a whole window inside a single write. void setCasRequestWindow(CasRequestBudget & budget, uint64_t window_ms); /// Throws `BAD_ARGUMENTS` unless `attemptEnvelopeMs() < request_window_ms`: the bound of a read-only open, diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp index d8d5474334646..7456d4824ceb2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -24,6 +25,7 @@ #include #include #include +#include #include namespace ProfileEvents @@ -100,6 +102,11 @@ void logCasWriteRetryLater(const String & why) throw Exception(ErrorCodes::NETWORK_ERROR, "CAS write could not be committed ({}); retrying later", why); } +[[noreturn]] void throwDidNotConverge(std::string_view what, uint32_t count, std::string_view unit) +{ + throwCasWriteRetryLater(fmt::format("{}: did not converge after {} {}", what, count, unit)); +} + [[noreturn]] void throwCasRequestRetryLater(const String & why) { LogSeriesLimiter log(getLogger("CasRequestRetryLater"), /*allowed_count=*/1, /*interval_s=*/30); @@ -107,11 +114,15 @@ void logCasWriteRetryLater(const String & why) throw Exception(ErrorCodes::NETWORK_ERROR, "CAS request did not complete ({}); retrying later", why); } -std::exception_ptr makeCasWriteRetryLaterExceptionPtr(const String & why) +Exception makeCasWriteRetryLaterException(const String & why) { logCasWriteRetryLater(why); - return std::make_exception_ptr( - Exception(ErrorCodes::NETWORK_ERROR, "CAS write could not be committed ({}); retrying later", why)); + return Exception(ErrorCodes::NETWORK_ERROR, "CAS write could not be committed ({}); retrying later", why); +} + +std::exception_ptr makeCasWriteRetryLaterExceptionPtr(const String & why) +{ + return std::make_exception_ptr(makeCasWriteRetryLaterException(why)); } [[noreturn]] void throwCasTransientUnavailable(const String & subject, const String & condition) @@ -200,7 +211,7 @@ bool isAuthoritativeAbsence([[maybe_unused]] const std::exception & e) GaveUp::Source sourceFor(const Retry::Bound & bound) { - return bound.lease_bound ? GaveUp::Source::Lease : GaveUp::Source::Policy; + return bound.source == Retry::Bound::Source::Lease ? GaveUp::Source::Lease : GaveUp::Source::Policy; } /// Could the precondition this write was built with still be met by what the resolve read saw? A @@ -317,6 +328,24 @@ bool isStoreAnswer(const std::exception & e) return dynamic_cast(&e) && !(db && isDeterministicLocalFailure(db->code())); } +bool isLocalFault(const std::exception_ptr & e) +{ + if (isQueryStoredCause(e)) + return false; + try + { + std::rethrow_exception(e); + } + catch (const std::exception & ex) + { + return !isStoreAnswer(ex); + } + catch (...) + { + return true; + } +} + String describeRequestFailure(std::string_view verb, const String & key, const std::exception & e) { const auto & poco = dynamic_cast(e); @@ -332,6 +361,12 @@ String describeRequestFailure(std::string_view verb, const String & key, const s return fmt::format("{} {}: {} {} {}", verb, key, isDefinitelyRefusedWrite(e) ? "refused" : "transport", code, poco.message()); } +void detail::throwVetoedCredentialRetry(std::string_view verb, const String & subject, const std::exception & e) +{ + throwCasRequestRetryLater(fmt::format("the query stopped before the credential retry; {}", + describeRequestFailure(verb, subject, e))); +} + CasRequests::CasRequests(BackendPtr backend_, Fence fence_, std::function now_ms_, std::function sleep_ms_, CasHotKeys * hot_keys_, uint64_t default_window_ms_) @@ -478,13 +513,27 @@ CasOperation::Gate CasOperation::gate(uint64_t needed_ms) const case Fence::Admit::NoBudget: return Gate::NoBudget; case Fence::Admit::Ok: break; } - /// The caller's own facts are the second half of admission, and the engine does not need to know - /// which of the two refused: a stopping task and a lost lease end the operation the same way. + /// The caller's authority facts and pool teardown are the second half of admission, and the engine + /// does not need to know which of the two refused. A query's or a background owner's stop never feeds it. if (liveness && !liveness()) return Gate::FenceLost; return Gate::Ok; } +std::optional CasOperation::refusedReadAttempt(const Retry::Bound & bound) const +{ + const uint64_t reservation = reservedFor(0, 1); + switch (gate(reservation)) + { + case Gate::FenceLost: return ReadStop::FenceLost; + case Gate::NoBudget: return ReadStop::NoBudgetLease; + case Gate::Ok: break; + } + if (!fits(reservation, bound)) + return ReadStop::PolicyExhausted; + return std::nullopt; +} + uint64_t CasOperation::reservedFor(uint64_t sleep_ms, uint32_t envelopes) const { uint64_t total = sleep_ms; @@ -493,30 +542,79 @@ uint64_t CasOperation::reservedFor(uint64_t sleep_ms, uint32_t envelopes) const return total; } -Retry CasOperation::freeze(const Retry & policy) const +bool CasOperation::oneAttemptFits(const Retry & policy) const { - if (policy.policy_deadline_ms) - return policy; - Retry frozen = policy; - frozen.policy_deadline_ms = saturatingAdd(owner.now_ms(), policy.window_ms.value_or(owner.default_window_ms)); - return frozen; + return fits(reservedFor(0, 1), owner.bindPolicy(policy)); } bool CasOperation::oneAttemptFitsBefore(uint64_t deadline_ms) const { - return fits(reservedFor(0, 1), Retry::Bound{.deadline_ms = deadline_ms, .lease_bound = false}); + return fits(reservedFor(0, 1), Retry::Bound{.deadline_ms = deadline_ms, .source = Retry::Bound::Source::OutsideCap}); } -std::optional CasOperation::pauseBeforeRedecide(uint64_t ms, const GaveUp & unresolved, const Retry & policy) +std::optional CasOperation::pauseAfterUnresolvedWrite(uint64_t ms, const GaveUp & unresolved, const Retry & policy) { WriteState state; state.attempts_sent = unresolved.attempts_sent; state.sent_any = unresolved.sent_any; state.last_seen = unresolved.last_seen; - /// Room for the next decision's two requests: its catalog read and its write. - constexpr uint32_t envelopes_for_next_decision = 2; - return gatedPause(ms, envelopes_for_next_decision, state, owner.bindPolicy(policy), detail::recordReissue, - /*should_sleep=*/true); + return pauseBetweenDecisions(ms, state, policy, PauseAfter::Failure); +} + +std::optional CasOperation::pauseUnderPolicy(uint64_t ms, const Retry & policy, PauseAfter after, + void (*record)(), bool zero_is_no_pause) +{ + /// Admission for `needed_ms` of pause, so a pause never outlives the mount lease. A window belongs to + /// one request and the next request binds its own when it is sent, so only the policy's absolute limits + /// can refuse a pause. The owner is checked last, so a lost fence or lease stays the typed outcome. + auto check_pause = [&](uint64_t needed_ms) -> std::optional + { + switch (gate(needed_ms)) + { + case Gate::FenceLost: return PauseStop::FenceLost; + case Gate::NoBudget: return PauseStop::NoBudget; + case Gate::Ok: break; + } + if (policy.lease_deadline_ms && !fits(needed_ms, {.deadline_ms = *policy.lease_deadline_ms, .source = Retry::Bound::Source::Lease})) + return PauseStop::Lease; + if (policy.outside_cap_ms && !fits(needed_ms, {.deadline_ms = *policy.outside_cap_ms, .source = Retry::Bound::Source::OutsideCap})) + return PauseStop::OutsideCap; + throwIfBackgroundStopped(); + if (after == PauseAfter::Failure && !insideOwed() && queryStopRequested()) + return PauseStop::QueryStopped; + return std::nullopt; + }; + if (auto stop = check_pause(ms)) + return stop; + if (ms == 0 && zero_is_no_pause) + return std::nullopt; + record(); + /// A query cut short here is reported by the check below, after the typed bounds. + if (after == PauseAfter::Failure) + sleepUnlessQueryStops(ms, [this](uint64_t slice_ms) { sleep(slice_ms); }); + else + sleep(ms); + /// A sleep can end on or past a limit it fitted before, and `decide` must not run after it. + return check_pause(0); +} + +std::optional CasOperation::pauseBetweenDecisions(uint64_t ms, WriteState & state, const Retry & policy, + PauseAfter after, void (*record)(), bool zero_is_no_pause) +{ + const std::optional stop = pauseUnderPolicy(ms, policy, after, record, zero_is_no_pause); + if (!stop) + return std::nullopt; + switch (*stop) + { + /// Named the way every request names a lost fence: by the bound the policy would get now. + case PauseStop::FenceLost: return gaveUp(GaveUp::Why::FenceLost, sourceFor(owner.bindPolicy(policy)), state); + case PauseStop::NoBudget: return gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, state); + case PauseStop::Lease: return gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, state); + case PauseStop::OutsideCap: return gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Policy, state); + /// The failure the pause followed stays unresolved; no decision follows it. + case PauseStop::QueryStopped: return gaveUp(GaveUp::Why::Unresolved, sourceFor(owner.bindPolicy(policy)), state); + } + UNREACHABLE(); } bool CasOperation::fits(uint64_t needed_ms, const Retry::Bound & bound) const @@ -532,12 +630,9 @@ bool CasOperation::fits(uint64_t needed_ms, const Retry::Bound & bound) const bool CasOperation::refreshAndClassifyReadFault(const std::exception & e, bool & refresh_attempted, bool & refreshed) { - if (const auto * db_e = dynamic_cast(&e); db_e && isDeterministicLocalFailure(db_e->code())) - return true; /// A local failure -- a bad allocation, a logic error raised inside the attempt -- is not a - /// transport fault, and reissuing it would spend the whole deadline replaying the same bug. Every - /// exception the transport raises is a `Poco::Exception`, `DB::Exception` included. - if (!dynamic_cast(&e)) + /// transport fault, and reissuing it would spend the whole deadline replaying the same bug. + if (!isStoreAnswer(e)) return true; /// A credential failure gets ONE refresh per call -- the storage hands back a fresh client every /// time it is asked, so refreshing per attempt would reissue a permanent denial to the deadline. @@ -570,17 +665,16 @@ void CasOperation::giveUpReadNoBudget(std::string_view verb, const String & subj } void CasOperation::giveUpReadDeadline(std::string_view verb, const String & subject, - const Retry::Bound & bound, uint32_t attempts_made) + GaveUp::Source source, uint32_t attempts_made) { last_read_stop = ReadStop::PolicyExhausted; throwCasRequestRetryLater(fmt::format("{} of '{}': gave up at the {} deadline after {} attempt(s)", - verb, subject, bound.lease_bound ? "lease" : "policy", attempts_made)); + verb, subject, source == GaveUp::Source::Lease ? "lease" : "policy", attempts_made)); } -std::optional CasOperation::readUnder( - const String & key, const Retry & policy, const Retry::Bound & bound, OnMemoryLimit on_memory_limit) +std::optional CasOperation::readUnder(const String & key, const Retry & policy, OnMemoryLimit on_memory_limit) { - return readLoop("read", key, policy, bound, [&](auto & access) -> std::optional + return readLoop("read", key, policy, [&](auto & access) -> std::optional { auto raw = owner.backend->read(key, access); if (!raw) @@ -589,9 +683,9 @@ std::optional CasOperation::readUnder( }, on_memory_limit); } -std::optional CasOperation::headUnder(const String & key, const Retry & policy, const Retry::Bound & bound) +std::optional CasOperation::headUnder(const String & key, const Retry & policy) { - return readLoop("head", key, policy, bound, [&](auto & access) -> std::optional + return readLoop("head", key, policy, [&](auto & access) -> std::optional { auto raw = owner.backend->head(key, access); if (!raw) @@ -600,10 +694,9 @@ std::optional CasOperation::headUnder(const String & key, const Retry & po }); } -ListPage CasOperation::listUnder(const String & prefix, const String & cursor, size_t limit, - const Retry & policy, const Retry::Bound & bound) +ListPage CasOperation::listUnder(const String & prefix, const String & cursor, size_t limit, const Retry & policy) { - return readLoop("list", prefix, policy, bound, [&](auto & access) + return readLoop("list", prefix, policy, [&](auto & access) { Backend::RawListPage raw = owner.backend->list(prefix, cursor, limit, access); ListPage page; @@ -620,10 +713,11 @@ ListPage CasOperation::listUnder(const String & prefix, const String & cursor, s }); } -Removal CasOperation::removeUnder(const String & key, const String & expected_value, - const Retry & policy, const Retry::Bound & bound) +Removal CasOperation::removeUnder(const String & key, const String & expected_value, const Retry & policy) { - const Backend::RawRemoval raw = readLoop("remove", key, policy, bound, [&](auto & access) + /// A mutation, so unlike a read it does not start for a stopped background owner. + throwIfBackgroundStopped(); + const Backend::RawRemoval raw = readLoop("remove", key, policy, [&](auto & access) { return owner.backend->remove(key, expected_value, access); }); @@ -643,17 +737,17 @@ Removal CasOperation::removeUnder(const String & key, const String & expected_va std::optional CasOperation::read(const String & key, const Retry & policy, OnMemoryLimit on_memory_limit) { - return readUnder(key, policy, owner.bindPolicy(policy), on_memory_limit); + return readUnder(key, policy, on_memory_limit); } std::optional CasOperation::head(const String & key, const Retry & policy) { - return headUnder(key, policy, owner.bindPolicy(policy)); + return headUnder(key, policy); } ListPage CasOperation::list(const String & prefix, const String & cursor, size_t limit, const Retry & policy) { - return listUnder(prefix, cursor, limit, policy, owner.bindPolicy(policy)); + return listUnder(prefix, cursor, limit, policy); } void CasOperation::forEachListedKey(const String & prefix, const ListedKeyFn & fn, const Retry & per_page, @@ -682,9 +776,9 @@ void CasOperation::removeManyWriteOnce(const std::vector & keys, c keys.size(), kBulkDeleteMaxKeys); if (keys.empty()) return; - const Retry::Bound bound = owner.bindPolicy(policy); + throwIfBackgroundStopped(); const String subject = fmt::format("{} (+{} keys)", keys.front().str(), keys.size() - 1); - readLoop("removeManyWriteOnce", subject, policy, bound, [&](auto & access) + readLoop("removeManyWriteOnce", subject, policy, [&](auto & access) { owner.backend->removeManyWriteOnce(keys, access); return true; @@ -693,18 +787,17 @@ void CasOperation::removeManyWriteOnce(const std::vector & keys, c Removal CasOperation::remove(const String & key, const Etag & seen, const Retry & policy) { - return removeUnder(key, owner.valueFor(key, seen), policy, owner.bindPolicy(policy)); + return removeUnder(key, owner.valueFor(key, seen), policy); } Removal CasOperation::removeCurrent(const String & key, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); for (uint32_t attempt = 1;; ++attempt) { - const std::optional seen = headUnder(key, policy, bound); + const std::optional seen = headUnder(key, policy); if (!seen) return Removal::Gone; - const Removal removed = removeUnder(key, owner.valueFor(key, seen->etag), policy, bound); + const Removal removed = removeUnder(key, owner.valueFor(key, seen->etag), policy); if (removed != Removal::Mismatch) return removed; @@ -715,20 +808,33 @@ Removal CasOperation::removeCurrent(const String & key, const Retry & policy) throwCasRequestRetryLater(fmt::format( "removeCurrent of '{}': the observed incarnation was replaced and the policy allows no reissue", key)); - /// Another incarnation became current between the observation and the delete. Re-observe, paced - /// like every other reissue: the reservation covers the next `head` and the `remove` after it. - const uint64_t pause_ms = Retry::backoff(attempt); - const uint64_t needed = reservedFor(pause_ms, 2); - switch (gate(needed)) + if (attempt == kCasMaxDecisions) { - case Gate::FenceLost: giveUpReadFenceLost("removeCurrent", key, "before the reissue"); - case Gate::NoBudget: giveUpReadNoBudget("removeCurrent", key, "for the reissue"); - case Gate::Ok: break; + if (const std::optional lost = lostAdmission()) + { + if (*lost == AdmissionLoss::Fence) + giveUpReadFenceLost("removeCurrent", key, "at the decision cap"); + giveUpReadNoBudget("removeCurrent", key, "at the decision cap"); + } + throwDidNotConverge(fmt::format("CAS remove of '{}'", key), kCasMaxDecisions, "decisions"); + } + + /// Another incarnation became current between the observation and the delete: a lost race. Re-observe + /// after the conflict pause; the next `head` and `remove` bind their own windows. + if (const std::optional stop + = pauseUnderPolicy(Retry::conflictBackoff(attempt), policy, PauseAfter::Conflict, detail::recordReissue, + /*zero_is_no_pause=*/true)) + { + switch (*stop) + { + case PauseStop::FenceLost: giveUpReadFenceLost("removeCurrent", key, "before the reissue"); + case PauseStop::NoBudget: giveUpReadNoBudget("removeCurrent", key, "for the reissue"); + case PauseStop::Lease: giveUpReadDeadline("removeCurrent", key, GaveUp::Source::Lease, attempt); + case PauseStop::OutsideCap: giveUpReadDeadline("removeCurrent", key, GaveUp::Source::Policy, attempt); + /// Only a pause after a failure reports a stopped query, and this one follows a conflict. + case PauseStop::QueryStopped: UNREACHABLE(); + } } - if (!fits(needed, bound)) - giveUpReadDeadline("removeCurrent", key, bound, attempt); - detail::recordReissue(); - sleep(pause_ms); } } @@ -739,6 +845,9 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry std::optional last_probe; for (uint32_t attempt = 1;; ++attempt) { + /// Not before the first probe: a healthy probe is never refused. + if (attempt > 1) + throwIfBackgroundStopped(); const uint64_t reservation = reservedFor(0, 1); switch (gate(reservation)) { @@ -752,11 +861,12 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry /// answer; before the first one the caller is told no request happened. if (last_probe) return *last_probe; - giveUpReadDeadline("probeSentinel", key, bound, attempt - 1); + giveUpReadDeadline("probeSentinel", key, sourceFor(bound), attempt - 1); } detail::recordAttempt(); SentinelProbeResult result{ProbeOutcome::Indeterminate, std::nullopt}; + std::exception_ptr cause; try { result = owner.withTransportAccess(attempt, [&](auto & access) @@ -766,6 +876,12 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry } catch (const std::exception & e) { + /// A local fault surfaces unchanged, as in the write loop; a query's stored cause can carry any code. + if (!isStoreAnswer(e) && !isQueryStoredCause(std::current_exception())) + throw; + /// A stopped owner's failure is no store answer: neither reissued nor a credential refresh. A stopped + /// query keeps the failure. + rethrowIfStoppedOwnersFailure(); /// The probe never counts a fuse, so whether this fault was a credential reissue is not /// interesting here -- only the write and read loops guard a counter with it. bool refreshed = false; @@ -773,6 +889,22 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry throw; /// The probe reports every transport failure as `Indeterminate` rather than by throwing, so /// a decorator that does throw is folded onto the same inconclusive outcome. + cause = std::current_exception(); + } + + /// The native and default backends fold a stopped owner's exception into `Indeterminate`, so the + /// background verdict is recovered here. A stopped query gets the inconclusive outcome itself, or its cause, + /// and no reissue. An authoritative outcome stays a store answer. + if (result.outcome == ProbeOutcome::Indeterminate) + { + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(stop); + if (queryStopRequested()) + { + if (cause) + std::rethrow_exception(cause); + return result; + } } /// The reissue is driven by the OUTCOME: this is the one primitive whose failures never reach a @@ -797,14 +929,18 @@ SentinelProbeResult CasOperation::probeSentinel(const String & key, const Retry return result; last_probe = std::move(result); detail::recordReissue(); - sleep(pause_ms); + if (!sleepUnlessQueryStops(pause_ms, [this](uint64_t slice_ms) { sleep(slice_ms); })) + { + if (cause) + std::rethrow_exception(cause); + return *last_probe; + } } } std::unique_ptr CasOperation::stream(const String & key, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); - std::unique_ptr body = readLoop("stream", key, policy, bound, [&](auto & access) + std::unique_ptr body = readLoop("stream", key, policy, [&](auto & access) { return owner.backend->stream(key, access); }); @@ -817,95 +953,124 @@ std::unique_ptr CasOperation::stream(const String & key, const Retry void CasOperation::publish(const BlobPublishRequest & request, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); - readLoop("publish", request.destination_key, policy, bound, [&](auto & access) + throwIfBackgroundStopped(); + readLoop("publish", request.destination_key, policy, [&](auto & access) { owner.backend->publish(request, access); }); } -CasOperation::Resolved CasOperation::observe(const String & key, const Retry & policy, const Retry::Bound & bound) +CasOperation::Resolved CasOperation::observe(const String & key, const Retry & policy, ResolveWith what) { last_read_stop.reset(); try { - auto got = readUnder(key, policy, bound); - if (!got) - return {ProvenAbsent{}, std::nullopt}; - return {std::move(*got), std::nullopt}; - } - catch (const Exception & e) - { - /// A local bug replays identically on every reissue, so it is never swallowed into "nothing - /// observed". Anything else settled nothing -- and `last_read_stop` says whether a bound - /// refused the read or the transport itself failed, which the exception cannot. - if (isDeterministicLocalFailure(e.code())) - throw; - return {NotObserved{}, last_read_stop}; + if (what == ResolveWith::Presence) + { + if (auto meta = headUnder(key, policy)) + return {std::move(*meta), std::nullopt}; + } + else if (auto object = readUnder(key, policy)) + return {std::move(*object), std::nullopt}; + return {ProvenAbsent{}, std::nullopt}; } catch (const std::exception & e) { - /// A failure that is not the transport's is not an observation: it is the same local bug the - /// read loop refuses to reissue, and swallowing it here would hide it just as thoroughly. - if (!dynamic_cast(&e)) - throw; - return {NotObserved{}, last_read_stop}; - } -} - -CasOperation::Resolved CasOperation::observePresence(const String & key, const Retry & policy, const Retry::Bound & bound) -{ - last_read_stop.reset(); - try - { - auto got = headUnder(key, policy, bound); - if (!got) - return {ProvenAbsent{}, std::nullopt}; - return {std::move(*got), std::nullopt}; - } - catch (const Exception & e) - { - if (isDeterministicLocalFailure(e.code())) + /// A local bug replays identically on every reissue, so it is never swallowed into "nothing + /// observed". A stopped owner's failure is not a store answer: it is reported only when a bound + /// refused the read or the read is owed. `last_read_stop` says which bound refused it. + bool observed_stop = false; + if (!isStoreAnswer(e) && !isQueryStoredCause(std::current_exception())) throw; - return {NotObserved{}, last_read_stop}; - } - catch (const std::exception & e) - { - if (!dynamic_cast(&e)) + if (auto stop = backgroundStopRequested()) + { + /// The verdict, not `e`: the stop can land after the read's own check classified `e`. + if (!last_read_stop && !insideOwed()) + std::rethrow_exception(stop); + } + else if (queryStopRequested()) + { + observed_stop = true; + if (!last_read_stop && !insideOwed()) + throw; + } + else if (!isStoreAnswer(e)) throw; - return {NotObserved{}, last_read_stop}; + return {NotObserved{}, last_read_stop, last_read_source, observed_stop}; } } -WriteResult CasOperation::gaveUp(GaveUp::Why why, GaveUp::Source source, WriteState & state) const +GaveUp CasOperation::gaveUp(GaveUp::Why why, GaveUp::Source source, WriteState & state) const { ProfileEvents::increment(ProfileEvents::CASRequestGaveUp); return GaveUp{why, source, state.sent_any, state.last_seen, state.attempts_sent}; } -WriteResult CasOperation::gaveUpForReadStop(ReadStop stop, WriteState & state, const Retry::Bound & bound) const +WriteResult CasOperation::gaveUpForReadStop(ReadStop stop, GaveUp::Source source, WriteState & state) const { switch (stop) { case ReadStop::FenceLost: - return gaveUp(GaveUp::Why::FenceLost, sourceFor(bound), state); + return gaveUp(GaveUp::Why::FenceLost, source, state); case ReadStop::NoBudgetLease: /// The fence's budget IS the mount lease, so the lease is the bound that ended this call. return gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, state); case ReadStop::PolicyExhausted: - return gaveUp(GaveUp::Why::Deadline, sourceFor(bound), state); + return gaveUp(GaveUp::Why::Deadline, source, state); } UNREACHABLE(); } -WriteResult CasOperation::gaveUpAfterFailedObservation(std::optional stop, WriteState & state, - const Retry::Bound & bound) const +WriteResult CasOperation::gaveUpAfterFailedObservation(const Resolved & resolved, WriteState & state) const { - if (stop) - return gaveUpForReadStop(*stop, state, bound); + if (resolved.stop) + return gaveUpForReadStop(*resolved.stop, resolved.source, state); /// No bound refused; the read itself failed. That is what `Unresolved` names, and it is the honest /// answer -- claiming a deadline the clock never reached would misreport which bound to widen. - return gaveUp(GaveUp::Why::Unresolved, sourceFor(bound), state); + return gaveUp(GaveUp::Why::Unresolved, resolved.source, state); +} + +std::optional CasOperation::lostAdmission() const +{ + switch (gate(0)) + { + case Gate::FenceLost: return AdmissionLoss::Fence; + case Gate::NoBudget: return AdmissionLoss::Lease; + case Gate::Ok: return std::nullopt; + } + UNREACHABLE(); +} + +WriteResult CasOperation::gaveUpAfterDecisionCap(WriteState & state, const Retry & policy) const +{ + if (const std::optional lost = lostAdmission()) + return *lost == AdmissionLoss::Fence + ? gaveUp(GaveUp::Why::FenceLost, sourceFor(owner.bindPolicy(policy)), state) + : gaveUp(GaveUp::Why::Deadline, GaveUp::Source::Lease, state); + return gaveUp(GaveUp::Why::Attempts, GaveUp::Source::Policy, state); +} + +CasOperation::OnCleanRefusal CasOperation::onCleanRefusalBefore(uint32_t decisions, const Retry & policy) +{ + /// A decision that another follows after a conflict pause reads again after that pause; the last + /// one, and a single attempt, report what the settling read saw. + return policy.single_attempt || decisions == kCasMaxDecisions ? OnCleanRefusal::Settle : OnCleanRefusal::ReturnUnobserved; +} + +std::optional CasOperation::pauseAfterConflict(uint32_t decisions, WriteState & state, const Retry & policy) +{ + if (decisions == kCasMaxDecisions) + return gaveUpAfterDecisionCap(state, policy); + /// A clean conflict is paced by the call's run of consecutive clean ones, which a conflict that settled a + /// transport fault ends; that one is paced by the fault schedule. Either way the conflict is an answer, so the + /// pause does not consult the query. The first clean conflict of a run is retried at once, after the same checks. + if (state.any_ambiguous) + { + state.clean_conflicts = 0; + return pauseBetweenDecisions(reissuePause(state, Retry::backoff(++state.reissues)), state, policy, PauseAfter::Conflict); + } + return pauseBetweenDecisions(reissuePause(state, Retry::conflictBackoff(++state.clean_conflicts)), state, policy, + PauseAfter::Conflict, detail::recordConflictPause, /*zero_is_no_pause=*/true); } WriteResult CasOperation::postCommit(Etag inc, bool resolved_by_read, WriteState & state, const Retry::Bound & bound) @@ -926,7 +1091,7 @@ WriteResult CasOperation::postCommit(Etag inc, bool resolved_by_read, WriteState return Committed{std::move(inc), state.attempts_sent, resolved_by_read}; } -std::optional CasOperation::gatedPause(uint64_t pause_ms, uint32_t envelopes, WriteState & state, +CasOperation::PauseOutcome CasOperation::gatedPause(uint64_t pause_ms, uint32_t envelopes, WriteState & state, const Retry::Bound & bound, void (*record)(), bool should_sleep) { const uint64_t needed = reservedFor(pause_ms, envelopes); @@ -941,12 +1106,15 @@ std::optional CasOperation::gatedPause(uint64_t pause_ms, uint32_t record(); /// `should_sleep` is false ONLY for the fuse's zero-pause reissue: that pause is not "zero /// milliseconds", it is NO PAUSE AT ALL, so it must not call `sleep_ms` even with a zero argument. - /// The three ordinary callers always sleep, even when a drawn jitter happens to be exactly zero -- - /// `Retry::backoff`'s full jitter includes zero -- so their call to `sleep_ms(0)` is kept - /// unconditional here to leave their observable behaviour exactly as it was before this collapse. - if (should_sleep) - sleep(pause_ms); - return std::nullopt; + /// The two ordinary callers always sleep, even when a drawn jitter happens to be exactly zero -- + /// `Retry::backoff`'s full jitter includes zero. + const bool query_stopped = should_sleep + ? !sleepUnlessQueryStops(pause_ms, [this](uint64_t slice_ms) { sleep(slice_ms); }) + : !insideOwed() && queryStopRequested(); + if (!query_stopped) + return ResumeAfterPause{}; + state.observed_stop = true; + return QueryVetoedResend{}; } uint64_t CasOperation::reissuePause(const WriteState & state, uint64_t unspaced_ms) const @@ -956,35 +1124,170 @@ uint64_t CasOperation::reissuePause(const WriteState & state, uint64_t unspaced_ return Retry::pauseAfterAttempt(state.spacing->spacing_ms, state.spacing->attempt_started_ms, owner.now_ms()); } -std::optional CasOperation::pauseAndReissue(WriteState & state, const Retry::Bound & bound) +CasOperation::PauseOutcome CasOperation::pauseAndReissue(WriteState & state, const Retry::Bound & bound) { const uint64_t pause_ms = reissuePause(state, Retry::backoff(++state.reissues)); return gatedPause(pause_ms, 2, state, bound, detail::recordReissue, /*should_sleep=*/true); } -std::optional CasOperation::pauseForConflict(WriteState & state, const Retry::Bound & bound) -{ - return gatedPause(reissuePause(state, Retry::conflictBackoff()), 2, state, bound, detail::recordConflictPause, - /*should_sleep=*/true); -} - /// A flat pause before reissuing an attempt whose failure text named a failed connection. static constexpr uint64_t kConnectHintPauseMs = 50; -std::optional CasOperation::pauseFlat(WriteState & state, const Retry::Bound & bound) +CasOperation::PauseOutcome CasOperation::pauseFlat(WriteState & state, const Retry::Bound & bound) { return gatedPause(reissuePause(state, kConnectHintPauseMs), 2, state, bound, detail::recordReissue, /*should_sleep=*/true); } -std::optional CasOperation::reissueAtOnce(WriteState & state, const Retry::Bound & bound) +CasOperation::PauseOutcome CasOperation::reissueAtOnce(WriteState & state, const Retry::Bound & bound) { return gatedPause(0, 2, state, bound, detail::recordReissue, /*should_sleep=*/false); } +CasOperation::Resolved CasOperation::settlingRead(const String & key, const Retry & policy, const WriteState & state, + ResolveWith resolve_refusal_with) +{ + ProfileEvents::increment(ProfileEvents::CASRequestResolveRead); + /// Owed to the write: a stopped owner must not lose the proof of what its attempt did. + const auto owed = OwnerScope::owed(); + return observe(key, policy, state.any_ambiguous ? ResolveWith::Body : resolve_refusal_with); +} + +std::optional CasOperation::adjudicate(const Resolved & resolved, const String & bytes, + const std::optional & expected, WriteState & state, + const Retry::Bound & write_bound) +{ + state.last_seen = resolved.seen; + state.observed_stop = state.observed_stop || resolved.observed_stop; + /// A bound of the resolve read refused it, so say WHICH. Erasing it here is what let a lost + /// fence be reported as an ordinary conflict and a lease refusal as a policy deadline. + if (resolved.stop) + return gaveUpForReadStop(*resolved.stop, resolved.source, state); + + /// No attempt of this inner write is unresolved, so the refused precondition IS the answer. + /// Identical bytes here are somebody else's object, and the caller that owns the key's meaning + /// decides what that means. + if (!state.any_ambiguous) + return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous, state.observed_stop}; + + if (!preconditionStillSatisfiable(state.last_seen, expected)) + { + /// The precondition has MOVED, and THAT is what makes byte equality a proof: an attempt + /// that never applied leaves the key exactly as it found it, so under an incarnation that + /// did not move our own bytes cannot be told from the bytes already there. A create reaches + /// here for every object it sees -- an occupied key never satisfies its precondition. + if (const auto * obj = std::get_if(&state.last_seen); obj && obj->bytes == bytes) + return postCommit(obj->etag, /*resolved_by_read=*/true, state, write_bound); + /// Nothing of this inner write's is at the key, and a reissue would be refused too. + return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous, state.observed_stop}; + } + return std::nullopt; +} + +namespace +{ + +/// What one conditional write attempt proved, from its reply alone. +enum class AttemptKind : uint8_t +{ + Committed, + /// The precondition was refused: this attempt wrote nothing. + Conflict, + /// Refused before anything was written, the same way on every resend. + Refused, + /// Refused before anything was written; fresh credentials may let a resend through. + CredentialRefused, + /// No proof either way: the attempt may have landed. + Ambiguous, + /// The query's stored verdict replaced the store's answer, which may have landed. + QueryStoredCause, + /// Not a store answer: surfaced unchanged. + LocalFault, +}; + +struct WriteAttempt +{ + explicit WriteAttempt(AttemptKind kind_) : kind(kind_) {} + + AttemptKind kind; + /// For `Committed`. + std::optional landed; + /// For every thrown kind. + std::exception_ptr error; + /// For `Refused` and `CredentialRefused`. + int refusal_code = 0; + String refusal_message; + /// An owner had asked to stop when the attempt failed. + bool failed_after_stop = false; + /// For a thrown store answer: the text named a failed connection. + bool connect_hint = false; + /// For `Ambiguous`: the first attempt met the adaptive timeout. + bool fuse = false; +}; + +/// Only the transport can have landed anything, and every exception it raises is a `Poco::Exception`; a local fault +/// settled by a read would bury the bug behind an outcome the store never gave. +WriteAttempt classifyWriteFailure(const std::exception & e, size_t attempt_no) +{ + WriteAttempt attempt(AttemptKind::Ambiguous); + attempt.error = std::current_exception(); + attempt.failed_after_stop = ownerStopRequested() != nullptr; + if (isQueryStoredCause(attempt.error)) + attempt.kind = AttemptKind::QueryStoredCause; + else if (!isStoreAnswer(e)) + attempt.kind = AttemptKind::LocalFault; + else + { + attempt.connect_hint = isConnectFailureHint(e); + if (isDefinitelyRefusedWrite(e)) + { + attempt.kind = isRefreshableCredentialError(e) ? AttemptKind::CredentialRefused : AttemptKind::Refused; + const auto & refusal = dynamic_cast(e); + attempt.refusal_code = refusal.code(); + attempt.refusal_message = refusal.message(); + } + else + { + /// False when the text is also a hint: such an attempt stays a hint. + attempt.fuse = isFirstAttemptFuseTimeout(e, attempt_no); + } + } + return attempt; +} + +/// `on_failure` takes the exception object, which only a rethrow recovers from an `exception_ptr`. +void reportWriteFailure(const RequestObserver & observer, const String & key, const std::exception_ptr & error) +{ + if (!observer.on_failure) + return; + try + { + std::rethrow_exception(error); + } + catch (const std::exception & e) + { + observer.on_failure("PUT", key, e); + } +} + +[[noreturn]] void throwVetoedCredentialRetryOfWrite(const String & key, const std::exception_ptr & refusal) +{ + try + { + std::rethrow_exception(refusal); + } + catch (const std::exception & e) + { + detail::throwVetoedCredentialRetry("PUT", key, e); + } +} + +} + WriteResult CasOperation::writeLoop(const String & key, const String & bytes, const std::optional & expected, - const Retry & policy, const Retry::Bound & bound, WriteState & state, - ResolveWith resolve_refusal_with) + const Retry & policy, WriteState & state, ResolveWith resolve_refusal_with, + OnCleanRefusal on_clean_refusal) { + const Retry::Bound bound = owner.bindPolicy(policy); std::optional expected_value; if (expected) expected_value = owner.valueFor(key, *expected); @@ -993,11 +1296,54 @@ WriteResult CasOperation::writeLoop(const String & key, const String & bytes, co /// write of the same call sent DIFFERENT bytes and ended in a conflict, which proved its attempts /// dead -- carrying its ambiguity forward is how a competitor's identical object gets claimed. state.any_ambiguous = false; + /// False while an ambiguous attempt awaits its settling read: a connect hint resends before reading. + bool latest_attempt_settled = true; + /// A stopped owner gets its latest attempt settled instead of a reissue. + const auto settle_for_stopped_owner = [&]() -> WriteResult + { + if (!latest_attempt_settled) + if (auto settled = adjudicate(settlingRead(key, policy, state, ResolveWith::Body), bytes, expected, state, bound)) + return *settled; + return gaveUp(GaveUp::Why::Unresolved, sourceFor(bound), state); + }; + + const auto send_attempt = [&]() -> WriteAttempt + { + std::optional> reply; + try + { + reply = owner.withTransportAccess(state.attempts_sent + policy.attempts_already_sent, [&](auto & access) + { + return owner.backend->write(key, bytes, expected_value, access); + }); + } + catch (const std::exception & e) + { + return classifyWriteFailure(e, state.attempts_sent + policy.attempts_already_sent); + } + if (!reply->has_value()) + return WriteAttempt(AttemptKind::Conflict); + /// A 2xx carrying a value no grammar accepts may well have landed: an ambiguity, never a corruption verdict. + std::optional landed = owner.tryMint(key, std::move(**reply)); + WriteAttempt attempt(landed ? AttemptKind::Committed : AttemptKind::Ambiguous); + attempt.landed = std::move(landed); + return attempt; + }; for (;;) { - /// A write reserves TWO envelopes: the attempt, and the exact read that settles it. That is - /// what keeps "every conflict is settled by one read" true at the deadline edge. + /// A query that stopped during a failure pause gets the latest attempt settled instead of a reissue. + if (state.observed_stop) + return settle_for_stopped_owner(); + /// Once an attempt may have landed, a stopped background owner gets that attempt settled instead of its + /// verdict. A stopped query is consulted only on the failure path below, which records what it saw. + if (!state.any_ambiguous) + throwIfBackgroundStopped(); + else if (!insideOwed() && backgroundStopRequested()) + return settle_for_stopped_owner(); + + /// An attempt starts only with room for TWO envelopes: itself and the read that settles it. This + /// bounds when the attempt starts, not when it lands or whether its settling read completes. const uint64_t reservation = reservedFor(0, 2); switch (gate(reservation)) { @@ -1016,307 +1362,182 @@ WriteResult CasOperation::writeLoop(const String & key, const String & bytes, co if (observer.on_write_attempt) observer.on_write_attempt(state.attempts_sent); - /// Disengaged means the attempt threw: its fate is unproven, and nothing may be read out of it. - std::optional> outcome; - /// A credential answer is given BEFORE the store applies anything, so the attempt provably did - /// not land. It is the one failure that is neither a commit nor an ambiguity, and keeping it out - /// of `any_ambiguous` is what lets a second credential failure of this inner write be refused - /// instead of resolved by a read and reissued to the deadline. - bool credential_answer = false; - bool refreshed = false; - /// Set once `refreshed` is known: true only when the credential-owned reissue below (the one - /// guarded by this exact expression) is what will actually resend this attempt. An earlier - /// ambiguity of this inner write routes the reissue through the ordinary hint/fuse/backoff - /// mechanisms instead -- the credential answer never gets to skip their read or their pacing -- - /// so a hint or fuse counter must still count in that case even though credentials were refreshed. - bool refresh_owns_reissue = false; - bool connect_hint = false; - bool fuse = false; - try + /// "This attempt did not land" says nothing about an earlier attempt of this write whose reply was lost. + const bool earlier_attempt_unanswered = state.any_ambiguous; + WriteAttempt attempt = send_attempt(); + const bool refused = attempt.kind == AttemptKind::Refused || attempt.kind == AttemptKind::CredentialRefused; + + if (attempt.kind == AttemptKind::LocalFault) + std::rethrow_exception(attempt.error); + if (attempt.kind == AttemptKind::Committed) + return postCommit(std::move(*attempt.landed), /*resolved_by_read=*/false, state, bound); + + /// Nothing is resent after the owner stopped: a failure that may have landed, or a refusal that cannot answer + /// for an earlier unanswered attempt, is settled and ends the call. A refusal with nothing unanswered is kept. + if (attempt.failed_after_stop && !(refused && !earlier_attempt_unanswered)) { - outcome = owner.withTransportAccess(state.attempts_sent + policy.attempts_already_sent, [&](auto & access) - { - return owner.backend->write(key, bytes, expected_value, access); - }); + state.any_ambiguous = true; + latest_attempt_settled = false; + state.observed_stop = state.observed_stop || queryStopRequested(); + return settle_for_stopped_owner(); } - catch (const Exception & e) + + if (attempt.error) + reportWriteFailure(observer, key, attempt.error); + bool refreshed = false; + if (refused) { - if (isDeterministicLocalFailure(e.code())) - throw; - if (observer.on_failure) - observer.on_failure("PUT", key, e); - /// ONE refresh per call, only for the class a credential could explain, and only when a - /// reissue could sign with what it installs. So an oversized entity never triggers a - /// re-acquisition, a denial fresh credentials do not fix is refused on the second look - /// rather than reissued to the deadline (the storage hands back a new client every time it - /// is asked), and under a single-attempt policy the refusal below is literally "no refresh - /// installed credentials and no earlier ambiguity". - credential_answer = isRefreshableCredentialError(e); - if (credential_answer && !state.refresh_attempted && !policy.single_attempt) + /// One refresh per call, and only when a resend could sign with what it installs. + if (attempt.kind == AttemptKind::CredentialRefused && !attempt.failed_after_stop && !state.refresh_attempted + && !policy.single_attempt) { state.refresh_attempted = true; refreshed = owner.backend->refreshCredentials(); } - /// Mirrors the condition guarding the credential-owned reissue below exactly, so the two - /// can never drift: `state.any_ambiguous` here is still this attempt's INCOMING value, - /// because the update below only fires when `!credential_answer`, which `refreshed` implies - /// false for. `!policy.single_attempt` is redundant today -- `refreshed` can only be set - /// above under `!policy.single_attempt` already -- but it is kept so this stays an exact - /// copy of the reissue branch's condition rather than a hand-simplified one that could - /// silently stop matching it. - refresh_owns_reissue = refreshed && !policy.single_attempt && !state.any_ambiguous; - /// A refusal that FOLLOWS an ambiguous attempt of this inner write proves nothing about that - /// attempt, so it is settled by the read below instead of ending the call here. - const bool definitely_refused = !refreshed && isDefinitelyRefusedWrite(e); - if (definitely_refused && !state.any_ambiguous) + /// With an earlier attempt unanswered the refusal proves nothing about it, so the read below settles it. + if (!earlier_attempt_unanswered) { + if (refreshed) + { + PauseOutcome paused = pauseAndReissue(state, bound); + if (auto * ended = std::get_if(&paused)) + return std::move(*ended); + /// The store refused this attempt, so a vetoed resend leaves no outcome unknown. + if (std::holds_alternative(paused)) + throwVetoedCredentialRetryOfWrite(key, attempt.error); + continue; + } ProfileEvents::increment(ProfileEvents::CASRequestRefused); - return Refused{e.code(), e.message(), state.attempts_sent}; + return Refused{attempt.refusal_code, std::move(attempt.refusal_message), state.attempts_sent}; } - /// A refusal-class exception is never a hint, even when an earlier ambiguity of this inner - /// write kept it from ending the call above: that earlier attempt's fate is what the read - /// below must settle, and a hint reissue would skip it. Both counters below are recorded - /// here, at classification, regardless of `policy.single_attempt` (`Retry::once` never acts - /// on either, but the attempt's transport error still named what it named) -- except when - /// the credential answer OWNS the reissue: a credential answer whose text happens to also - /// match a hint or fuse text is a credential reissue, not a hint or fuse one, and must not - /// inflate these counts. When an earlier ambiguity of this inner write keeps the credential - /// answer from owning the reissue, the hint/fuse mechanism reissues it instead, exactly as - /// if credentials had never been refreshed, so the counter must still count it. - connect_hint = !definitely_refused && isConnectFailureHint(e); - if (connect_hint && !refresh_owns_reissue) - ProfileEvents::increment(ProfileEvents::CASRequestConnectFailureHint); - /// Checked AFTER the hint, so a hinted attempt stays hinted (reissued before its read); a - /// fuse timeout is reissued after the settle read runs below. - fuse = isFirstAttemptFuseTimeout(e, state.attempts_sent + policy.attempts_already_sent); - if (fuse && !refresh_owns_reissue) - ProfileEvents::increment(ProfileEvents::CASRequestFirstAttemptFuse); - } - catch (const std::exception & e) - { - /// Only the transport can have landed anything, and every exception it raises is a - /// `Poco::Exception`. A local fault -- a bad allocation, a logic error raised inside the - /// attempt -- is not a store answer, and settling it by a read would bury the bug behind an - /// outcome the store never gave. What is left is an unmodeled transport failure that may - /// still have landed, so `outcome` stays disengaged and the read below settles it. - if (!dynamic_cast(&e)) - throw; - if (observer.on_failure) - observer.on_failure("PUT", key, e); } - - if (outcome && outcome->has_value()) + else if (attempt.kind != AttemptKind::Conflict) { - if (auto inc = owner.tryMint(key, std::move(**outcome))) - return postCommit(std::move(*inc), /*resolved_by_read=*/false, state, bound); - /// A 2xx carrying a value no grammar accepts: the write may well have landed, so this is an - /// ambiguity to settle by reading, never a corruption verdict about the object. - outcome.reset(); - } - if (!outcome && !credential_answer) state.any_ambiguous = true; - - /// Nothing for a read to settle: this attempt did not apply, and no EARLIER attempt of this - /// inner write is unresolved either. Re-send it under the credentials the refresh installed. - if (refresh_owns_reissue) - { - if (auto given_up = pauseAndReissue(state, bound)) - return *given_up; - continue; + latest_attempt_settled = false; } - /// The failure text named a failed CONNECTION -- counted above, at classification, whether or - /// not this policy or the deadline/fence gates below let the reissue actually happen. A read now - /// would meet the same broken condition, so the reissue itself is the cheaper probe: the attempt - /// stays ambiguous (`any_ambiguous` is set above), and if the reissue meets a refused precondition - /// the read below settles it. + /// A refusal that fresh credentials may cure is resent like an ambiguity. Counted whether or not the policy + /// or the gates let the resend happen. + const bool connect_hint = attempt.connect_hint && (attempt.kind == AttemptKind::Ambiguous || refreshed); + if (connect_hint) + ProfileEvents::increment(ProfileEvents::CASRequestConnectFailureHint); + if (attempt.fuse) + ProfileEvents::increment(ProfileEvents::CASRequestFirstAttemptFuse); + /// A read now would meet the same broken connection, so the resend is the cheaper probe; a refused + /// precondition it meets is settled by the read below. if (connect_hint && !policy.single_attempt && policy.resend_unresolved) { - if (auto given_up = pauseFlat(state, bound)) - return *given_up; + PauseOutcome paused = pauseFlat(state, bound); + if (auto * ended = std::get_if(&paused)) + return std::move(*ended); + if (std::holds_alternative(paused)) + return settle_for_stopped_owner(); continue; } - /// Every refused precondition, and every ambiguous attempt that was not reissued on a - /// connect-failure hint, is settled by ONE exact read, under every policy: a refused - /// precondition does not say WHO holds the key, and a 404 and a 412 reach here as the same - /// answer. A hinted attempt reaches this read after a reissue that met a refused - /// precondition, or at once under a policy that never resends it (`single_attempt`, - /// `resend_unresolved = false`). A refused precondition needs only to know WHAT is there, so a presence-only - /// caller settles it with a HEAD; proving an ambiguous attempt landed needs the bytes, and there - /// the body read is unavoidable. - ProfileEvents::increment(ProfileEvents::CASRequestResolveRead); - const Resolved resolved = resolve_refusal_with == ResolveWith::Presence && !state.any_ambiguous - ? observePresence(key, policy, bound) - : observe(key, policy, bound); - state.last_seen = resolved.seen; - /// A bound refused the resolve, so say WHICH. Erasing it here is what let a lost fence be - /// reported as an ordinary conflict and a lease refusal as a policy deadline. - if (resolved.stop) - return gaveUpForReadStop(*resolved.stop, state, bound); - - /// No attempt of this inner write is unresolved, so the refused precondition IS the answer. - /// Identical bytes here are somebody else's object, and the caller that owns the key's meaning - /// decides what that means. - if (!state.any_ambiguous) - return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous}; - - if (!preconditionStillSatisfiable(state.last_seen, expected)) + if (attempt.kind == AttemptKind::Conflict && !earlier_attempt_unanswered + && on_clean_refusal == OnCleanRefusal::ReturnUnobserved) { - /// The precondition has MOVED, and THAT is what makes byte equality a proof: an attempt - /// that never applied leaves the key exactly as it found it, so under an incarnation that - /// did not move our own bytes cannot be told from the bytes already there. A create reaches - /// here for every object it sees -- an occupied key never satisfies its precondition. - if (const auto * obj = std::get_if(&state.last_seen); obj && obj->bytes == bytes) - return postCommit(obj->etag, /*resolved_by_read=*/true, state, bound); - /// Nothing of this inner write's is at the key, and a reissue would be refused too. - return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous}; + state.last_seen = NotObserved{}; + /// The skipped read would have bound its own window and been refused by these, before any pause the + /// caller takes; they are reported as that read reports them. + const Retry::Bound read_bound = owner.bindPolicy(policy); + if (const std::optional read_refused = refusedReadAttempt(read_bound)) + return gaveUpForReadStop(*read_refused, sourceFor(read_bound), state); + return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous, state.observed_stop}; } - /// Unresolved but repeatable: the precondition would still be met -- or nothing was observed at - /// all, which proves neither way and leaves this write's ambiguity alive. A reissue is what - /// settles it, and re-sending the same bytes under the same precondition is safe: it ends at - /// the store's own answer. A policy with no reissue has to say it settled nothing. + /// One exact read settles every other refused precondition and every ambiguity: a refused precondition does + /// not say WHO holds the key. A presence-only caller settles a refusal with a HEAD; proving + /// an ambiguous attempt landed needs the bytes. + if (auto settled = adjudicate(settlingRead(key, policy, state, resolve_refusal_with), bytes, expected, state, bound)) + return *settled; + latest_attempt_settled = true; + + /// Unresolved: the precondition would still be met, or the read observed nothing. Re-sending the same bytes + /// under the same precondition is safe: it ends at the store's own answer. if (policy.single_attempt || !policy.resend_unresolved) return gaveUp(GaveUp::Why::Unresolved, sourceFor(bound), state); - /// The first attempt met the adaptive first-attempt timeout: a connection-quality answer, not a - /// store fault. The read above settled nothing new about it, so re-send at once as attempt 2 - /// under the full attempt budget; the backoff index is untouched because no store fault was - /// seen yet. - if (fuse) - { - if (auto given_up = reissueAtOnce(state, bound)) - return *given_up; - continue; - } - if (auto given_up = pauseAndReissue(state, bound)) - return *given_up; + /// A stop during the settling read ends the call here instead of after a pause. + if (state.observed_stop || (!insideOwed() && ownerStopRequested())) + return gaveUp(GaveUp::Why::Unresolved, sourceFor(bound), state); + /// A first-attempt timeout is a connection-quality answer, not a store fault: resend at once. + PauseOutcome paused = attempt.fuse ? reissueAtOnce(state, bound) : pauseAndReissue(state, bound); + if (auto * ended = std::get_if(&paused)) + return std::move(*ended); + if (std::holds_alternative(paused)) + return settle_for_stopped_owner(); } } WriteResult CasOperation::create(const String & key, const String & bytes, const Retry & policy) { WriteState state; - return writeLoop(key, bytes, std::nullopt, policy, owner.bindPolicy(policy), state, ResolveWith::Body); + return writeLoop(key, bytes, std::nullopt, policy, state, ResolveWith::Body); } WriteResult CasOperation::replace(const String & key, const String & bytes, const Etag & seen, const Retry & policy) { WriteState state; - return writeLoop(key, bytes, seen, policy, owner.bindPolicy(policy), state, ResolveWith::Body); + return writeLoop(key, bytes, seen, policy, state, ResolveWith::Body); } -WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObject & decide, const Retry & policy) +template +WriteResult CasOperation::readModifyWriteImpl( + const String & key, const std::function(const std::optional &)> & decide, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); + constexpr bool presence_only = std::is_same_v; + constexpr ResolveWith observe_with = presence_only ? ResolveWith::Presence : ResolveWith::Body; + /// Proving an ambiguous attempt landed needs the bytes even here; a presence-only verb reports metadata only. + const auto reported = [](auto value) + { + if constexpr (presence_only) + return withoutBody(std::move(value)); + else + return value; + }; + WriteState state; + for (uint32_t decisions = 1;; ++decisions) + { + /// A decision after the first is reached only through the conflict pause, and reads after it: a write + /// landing during the pause would refuse a decision taken on any read before it. + if (decisions > 1) + if (const std::optional given_up = pauseAfterConflict(decisions - 1, state, policy)) + return *given_up; - Resolved resolved = observe(key, policy, bound); - state.last_seen = resolved.seen; - std::optional current; - if (const auto * obj = std::get_if(&state.last_seen)) - current = *obj; - else if (!std::holds_alternative(state.last_seen)) - return gaveUpAfterFailedObservation(resolved.stop, state, bound); + const Resolved resolved = observe(key, policy, observe_with); + state.last_seen = resolved.seen; + std::optional current; + if (const auto * seen = std::get_if(&state.last_seen)) + current = *seen; + else if (!std::holds_alternative(state.last_seen)) + return gaveUpAfterFailedObservation(resolved, state); - for (;;) - { + throwIfBackgroundStopped(); /// Outside every classification: `decide` is the caller's own control flow, and an exception /// from it is theirs to see unchanged. const std::optional next = decide(current); if (!next) return Declined{state.last_seen}; - WriteResult result = writeLoop(key, *next, - current ? std::optional(current->etag) : std::nullopt, policy, bound, state, - ResolveWith::Body); - if (!std::holds_alternative(result)) - return result; - - /// The write's own resolve read IS this iteration's read: a hot key never costs a second GET - /// per conflict. - if (const auto * obj = std::get_if(&state.last_seen)) - current = *obj; - else if (std::holds_alternative(state.last_seen)) - current.reset(); - - if (policy.single_attempt) - return result; - /// A clean lost race is settled: the resolve read holds the fresh object and the next - /// iteration decides on it. Only a conflict that settled a transport fault is paced by the - /// growing schedule. - if (auto given_up = state.any_ambiguous ? pauseAndReissue(state, bound) : pauseForConflict(state, bound)) - return *given_up; - - /// Only when the resolve settled nothing is a fresh read owed; otherwise `current` already is - /// what the store held. - if (std::holds_alternative(state.last_seen)) - { - resolved = observe(key, policy, bound); - state.last_seen = resolved.seen; - if (const auto * obj = std::get_if(&state.last_seen)) - current = *obj; - else if (std::holds_alternative(state.last_seen)) - current.reset(); - else - return gaveUpAfterFailedObservation(resolved.stop, state, bound); - } + WriteResult result = writeLoop(key, *next, current ? std::optional(current->etag) : std::nullopt, policy, state, + observe_with, onCleanRefusalBefore(decisions, policy)); + state.last_seen = reported(std::move(state.last_seen)); + if (!std::holds_alternative(result) || policy.single_attempt || state.observed_stop) + return reported(std::move(result)); } } -WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const DecideOnMeta & decide, const Retry & policy) +WriteResult CasOperation::readModifyWrite(const String & key, const DecideOnObject & decide, const Retry & policy) { - const Retry::Bound bound = owner.bindPolicy(policy); - WriteState state; - - Resolved resolved = observePresence(key, policy, bound); - state.last_seen = resolved.seen; - std::optional current; - if (const auto * meta = std::get_if(&state.last_seen)) - current = *meta; - else if (!std::holds_alternative(state.last_seen)) - return gaveUpAfterFailedObservation(resolved.stop, state, bound); - - for (;;) - { - const std::optional next = decide(current); - if (!next) - return Declined{state.last_seen}; - - WriteResult result = writeLoop(key, *next, - current ? std::optional(current->etag) : std::nullopt, policy, bound, state, - ResolveWith::Presence); - /// A refused precondition was settled by a HEAD, but proving an ambiguous attempt landed needs - /// the bytes; this loop is presence-only by contract, so that body stops here. - state.last_seen = withoutBody(std::move(state.last_seen)); - if (!std::holds_alternative(result)) - return withoutBody(std::move(result)); - - if (const auto * meta = std::get_if(&state.last_seen)) - current = *meta; - else if (std::holds_alternative(state.last_seen)) - current.reset(); + return readModifyWriteImpl(key, decide, policy); +} - if (policy.single_attempt) - return Conflict{state.last_seen, state.attempts_sent, state.any_ambiguous}; - /// A clean lost race is settled: the resolve read holds the fresh object and the next - /// iteration decides on it. Only a conflict that settled a transport fault is paced by the - /// growing schedule. - if (auto given_up = state.any_ambiguous ? pauseAndReissue(state, bound) : pauseForConflict(state, bound)) - return *given_up; - - if (std::holds_alternative(state.last_seen)) - { - resolved = observePresence(key, policy, bound); - state.last_seen = resolved.seen; - if (const auto * meta = std::get_if(&state.last_seen)) - current = *meta; - else if (std::holds_alternative(state.last_seen)) - current.reset(); - else - return gaveUpAfterFailedObservation(resolved.stop, state, bound); - } - } +WriteResult CasOperation::readModifyWriteOnPresence(const String & key, const DecideOnMeta & decide, const Retry & policy) +{ + return readModifyWriteImpl(key, decide, policy); } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h index c318187262bef..998878396c3d2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRequests.h @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -122,11 +123,17 @@ String describeRequestFailure(std::string_view verb, const String & key, const s /// commit: a read, a probe, a delete, or recovery and maintenance work. [[noreturn]] void throwCasRequestRetryLater(const String & why); +/// For a loop that capped its own iterations and has no `WriteResult` to carry `GaveUp::Why::Attempts`. +/// Same class as `throwCasWriteRetryLater`; `unit` names what `count` counts. +[[noreturn]] void throwDidNotConverge(std::string_view what, uint32_t count, std::string_view unit); + /// Same classification as `throwCasWriteRetryLater`, but returns the exception as a /// `std::exception_ptr` for call sites that fail a pending future/promise rather than throw directly. /// Both entry points route through the SAME construction internally, so the error code / message shape /// has exactly one place that decides it. std::exception_ptr makeCasWriteRetryLaterExceptionPtr(const String & why); +/// The same exception by value, for a caller that throws it as a subclass. +Exception makeCasWriteRetryLaterException(const String & why); /// Throw `CAS_OWNERSHIP_CONFLICT`: the committed ref a caller read moved, dropped or changed owner before the /// caller's write landed; the caller must re-resolve the part before trying again. Counted in @@ -201,6 +208,9 @@ void recordAttempt(); void recordReissue(); void recordConflictPause(); void recordFirstAttemptFuse(); +/// For a credential refusal whose retry a stopped query vetoed: the retry-later class carrying it, so the refusal is +/// not read as damage. +[[noreturn]] void throwVetoedCredentialRetry(std::string_view verb, const String & subject, const std::exception & e); } class CasOperation; @@ -250,7 +260,7 @@ class CasRequests /// A caller's own inter-iteration wait, paced through the same clock the engine's own sleeps use -- /// so a test that replaces the sleep sees no real time pass in either. `CasOperation` carries the /// same call for the loops that hold an operation rather than the plane it was admitted on. - void pause(uint64_t ms) { sleep_ms(ms); } + void sleepFor(uint64_t ms) { sleep_ms(ms); } void setNowFnForTest(std::function now_ms_); void setSleepFnForTest(std::function sleep_ms_); @@ -329,30 +339,31 @@ class CasOperation Dialect backendDialect() const; /// A caller's own inter-iteration wait, paced through the same clock the engine's own sleeps use -- /// so a test that replaces the sleep sees no real time pass in either. For the hand-written loops - /// that reissue something the engine must not reissue for them. - void pause(uint64_t ms) { sleep(ms); } - /// The pause before a loop re-decides after `unresolved`, gated like the engine's own reissue - /// pause. Returns the give-up instead of sleeping when the fence is lost or the pause plus two - /// attempt reservations (the re-read and the write) do not fit in `policy`. - std::optional pauseBeforeRedecide(uint64_t ms, const GaveUp & unresolved, const Retry & policy); + /// that reissue something the engine must not reissue for them. It only sleeps: no owner, fence or deadline check. + void sleepFor(uint64_t ms) { sleep(ms); } + /// The pause before a loop re-decides after `unresolved`. Returns the give-up instead of sleeping + /// when the fence is lost, the mount lease has no room for the pause, or the pause does not fit before `policy`'s + /// lease or absolute deadline; and after sleeping when any of these holds at wake-up, or when the query stopped + /// during it. No window is consulted: the next decision's requests bind their own. + std::optional pauseAfterUnresolvedWrite(uint64_t ms, const GaveUp & unresolved, const Retry & policy); /// The verdict point: is this operation still admitted? For the sites that guard a decision rather /// than a request. bool admitted() const { return gate(0) == Gate::Ok; } + enum class AdmissionLoss : uint8_t { Fence, Lease }; + /// Why this operation is no longer admitted, or nullopt while it is. A loop asks at its count cap: a + /// fence lost or a lease spent during the last request is the answer, not the count. + std::optional lostAdmission() const; void observeRequests(RequestObserver observer_) { observer = std::move(observer_); } /// The write lane for keys several writers of this pool share. CasHotKeys & hotKeys() const { return *owner.hot_keys; } - /// `policy` with its window turned into an absolute deadline on this operation's clock, taken NOW. - /// A hand-written loop freezes its policy once before it starts and passes the frozen value to - /// every call it makes, so the loop ends when the window it was given ends -- rather than granting - /// each verb of each iteration a fresh one, which is how a bounded document promise became hours - /// of paced retrying. A policy that already carries a deadline is returned unchanged, so freezing - /// twice cannot extend it. - Retry freeze(const Retry & policy) const; - /// Would a read verb start its first attempt now under a policy frozen to `deadline_ms`? The same test the - /// verb applies before it sends, without any lease bound. A caller with a deadline of its own asks first, so - /// its running out of time is its own error and not the verb's retry-later give-up. + /// Would a read verb (one envelope; a conditional write reserves two) start its first attempt now under + /// `policy`? The same deadline test the verb applies before it sends, lease bound included, not its + /// fence check. A caller with a deadline of its own asks first, so its running out of time is its own + /// error and not the verb's retry-later give-up. + bool oneAttemptFits(const Retry & policy) const; + /// The same, before an absolute `deadline_ms` and without any lease bound. bool oneAttemptFitsBefore(uint64_t deadline_ms) const; /// `OnMemoryLimit::Propagate` makes a `MEMORY_LIMIT_EXCEEDED` from an admitted attempt escape at once: the @@ -393,8 +404,8 @@ class CasOperation WriteResult create(const String & key, const String & bytes, const Retry & policy); WriteResult replace(const String & key, const String & bytes, const Etag & seen, const Retry & policy); - /// Read, decide, write, and re-decide on conflict against what the write's own resolve read - /// already observed. `decide` returning nullopt is `Declined`. + /// Read, decide, write; on a conflict, pause, read again and re-decide on that read. `decide` + /// returning nullopt is `Declined`. WriteResult readModifyWrite(const String & key, const DecideOnObject & decide, const Retry & policy); /// The same loop over `head`, settling a refused precondition with a `head` too. Proving that an /// ambiguous attempt landed needs the bytes, so that one path does read a body; either way the verb @@ -436,7 +447,12 @@ class CasOperation bool any_ambiguous = false; Observation last_seen = NotObserved{}; uint32_t reissues = 0; + /// The current run of consecutive clean lost races, which sets the length of the conflict pause. + uint32_t clean_conflicts = 0; bool refresh_attempted = false; + /// An operation of this call failed and saw its query stopped: a write attempt, its settling read, or the + /// pause before a reissue. The call starts no further discretionary request, also after a settled conflict. + bool observed_stop = false; /// Under `Retry::attempt_spacing_ms`: that spacing, and when the latest attempt was sent. struct Spacing { @@ -450,31 +466,36 @@ class CasOperation /// `NETWORK_ERROR`, so a caller that SWALLOWS the exception -- only the resolve read does -- cannot /// recover from it which bound refused, and reporting a lease refusal as a policy deadline is the /// confusion `GaveUp::Source` exists to prevent. `PolicyExhausted` names the `Retry` bound, whose - /// own source is `Bound::lease_bound`. + /// own source is `Bound::source`. enum class ReadStop : uint8_t { FenceLost, NoBudgetLease, PolicyExhausted }; + /// What refuses the next attempt of a read-class request bound to `bound`, if anything: the fence, the lease + /// budget for one request envelope, then the bound itself. + std::optional refusedReadAttempt(const Retry::Bound & bound) const; /// What the resolve read saw, and why it stopped when it saw nothing. `stop` is set ONLY when a /// bound refused; a read that failed at the transport leaves it empty, and that is the one case - /// `NotObserved` is still the whole story. + /// `NotObserved` is still the whole story. `source` is the source of the read's own bound. struct Resolved { Observation seen; std::optional stop; + GaveUp::Source source = GaveUp::Source::Policy; + /// The read failed and saw its query stopped. + bool observed_stop = false; }; - /// One read-class request under the policy: admission, attempt, classification, jittered reissue. - /// Returns whatever `once` returns, or throws -- the read surface reports failure by exception. + /// One read-class request under the policy: admission, attempt, classification, jittered reissue, + /// all within the window it binds at its start. Returns whatever `once` returns, or throws -- the + /// read surface reports failure by exception. template auto readLoop(std::string_view verb, const String & subject, const Retry & policy, - const Retry::Bound & bound, Fn && once, OnMemoryLimit on_memory_limit = OnMemoryLimit::Reissue); + Fn && once, OnMemoryLimit on_memory_limit = OnMemoryLimit::Reissue); - std::optional readUnder(const String & key, const Retry & policy, const Retry::Bound & bound, + std::optional readUnder(const String & key, const Retry & policy, OnMemoryLimit on_memory_limit = OnMemoryLimit::Reissue); - std::optional headUnder(const String & key, const Retry & policy, const Retry::Bound & bound); - ListPage listUnder(const String & prefix, const String & cursor, size_t limit, - const Retry & policy, const Retry::Bound & bound); - Removal removeUnder(const String & key, const String & expected_value, - const Retry & policy, const Retry::Bound & bound); + std::optional headUnder(const String & key, const Retry & policy); + ListPage listUnder(const String & prefix, const String & cursor, size_t limit, const Retry & policy); + Removal removeUnder(const String & key, const String & expected_value, const Retry & policy); /// How a write settles a REFUSED PRECONDITION, which needs only to know what is at the key. An /// ambiguous attempt always reads the body, whichever this says, because only the bytes can prove @@ -484,46 +505,84 @@ class CasOperation /// The write engine: one call, any policy. `Committed` and `Conflict` are proven by an exact read /// or by the reissue's own 2xx before they are reported; an attempt whose transport error named a /// failed connection is reissued before its read. `Refused`, `Declined` and `GaveUp` report what - /// the store or the bounds said. + /// the store or the bounds said. The window bound at entry governs every send of these bytes; the + /// read that settles an attempt is a request of its own and binds its own window from `policy`. + /// What a clean refused precondition (no attempt of this call left unanswered) returns. `ReturnUnobserved` + /// skips the settling read and returns `Conflict{NotObserved}`, for a caller that pauses and reads again + /// before its next decision, which would overwrite that read unused. + enum class OnCleanRefusal : uint8_t { Settle, ReturnUnobserved }; + WriteResult writeLoop(const String & key, const String & bytes, const std::optional & expected, - const Retry & policy, const Retry::Bound & bound, WriteState & state, - ResolveWith resolve_refusal_with); - /// The resolve read: an exact read under the same policy and deadline, reporting what it saw and, - /// when it saw nothing, which bound stopped it. - Resolved observe(const String & key, const Retry & policy, const Retry::Bound & bound); - /// The presence-only sibling, for the one loop that must not fetch a body. - Resolved observePresence(const String & key, const Retry & policy, const Retry::Bound & bound); + const Retry & policy, WriteState & state, ResolveWith resolve_refusal_with, + OnCleanRefusal on_clean_refusal = OnCleanRefusal::Settle); + /// The resolve read: an exact read (a `HEAD` for `Presence`) under its own window from `policy`, reporting + /// what it saw and, when it saw nothing, which of its bounds stopped it. A stopped owner's failure is + /// `NotObserved` only when a bound refused the read or inside `owed`; otherwise it propagates. + Resolved observe(const String & key, const Retry & policy, ResolveWith what = ResolveWith::Body); + /// The read that settles this inner write's latest attempt, run `owed`. A body read once an attempt is ambiguous. + Resolved settlingRead(const String & key, const Retry & policy, const WriteState & state, ResolveWith resolve_refusal_with); + /// What the settling read proves: `Committed`, `Conflict` or the bound that refused it. Nullopt + /// when a resend under the same precondition could still apply. + std::optional adjudicate(const Resolved & resolved, const String & bytes, const std::optional & expected, + WriteState & state, const Retry::Bound & write_bound); WriteResult postCommit(Etag inc, bool resolved_by_read, WriteState & state, const Retry::Bound & bound); - WriteResult gaveUp(GaveUp::Why why, GaveUp::Source source, WriteState & state) const; + GaveUp gaveUp(GaveUp::Why why, GaveUp::Source source, WriteState & state) const; /// The bound that refused the resolve read, reported as the outcome it actually is. - WriteResult gaveUpForReadStop(ReadStop stop, WriteState & state, const Retry::Bound & bound) const; + WriteResult gaveUpForReadStop(ReadStop stop, GaveUp::Source source, WriteState & state) const; /// A resolve read that produced nothing. The fence is NOT resampled: a second sample reports a /// state the read never saw, which is how a lease refusal used to be reported as a policy deadline. - WriteResult gaveUpAfterFailedObservation(std::optional stop, WriteState & state, - const Retry::Bound & bound) const; + WriteResult gaveUpAfterFailedObservation(const Resolved & resolved, WriteState & state) const; + /// The loops' answer after their last allowed decision lost its race. + WriteResult gaveUpAfterDecisionCap(WriteState & state, const Retry & policy) const; + + /// Why a pause between decisions ended the call. + /// `QueryStopped` follows only `PauseAfter::Failure`. + enum class PauseStop : uint8_t { FenceLost, NoBudget, Lease, OutsideCap, QueryStopped }; + /// What the pause follows. A query's stop is consulted only after a failure: a conflict is an answer, + /// and the work after it proceeds for a killed query as on plain S3. + enum class PauseAfter : uint8_t { Conflict, Failure }; + /// The pause between two decisions: admission for the pause, then the policy's explicit lease and outside cap, + /// then the sleep, then admission, lease and cap again so no `decide` runs past them. It consults + /// no window: the next decision's requests bind their own when they are sent. With `zero_is_no_pause`, a + /// pause of 0 ms runs the checks once and neither records nor sleeps. + std::optional pauseUnderPolicy(uint64_t ms, const Retry & policy, PauseAfter after, void (*record)(), + bool zero_is_no_pause = false); + /// `pauseUnderPolicy` reported as a give-up. A value means the call ended; nullopt means + /// `decide` may run again. + std::optional pauseBetweenDecisions(uint64_t ms, WriteState & state, const Retry & policy, PauseAfter after, + void (*record)() = detail::recordReissue, bool zero_is_no_pause = false); + /// The read-modify-write loops' step after a lost decision: the decision cap, else the pause before the next + /// decision. A value means the call ended. + std::optional pauseAfterConflict(uint32_t decisions, WriteState & state, const Retry & policy); + /// The loop behind `readModifyWrite` (`Seen = Object`, GET) and `readModifyWriteOnPresence` (`Seen = Meta`, HEAD). + template + WriteResult readModifyWriteImpl(const String & key, const std::function(const std::optional &)> & decide, + const Retry & policy); + /// How the read-modify-write loops' write of decision number `decisions` answers a clean refusal. + static OnCleanRefusal onCleanRefusalBefore(uint32_t decisions, const Retry & policy); + /// The caller may send another attempt. + struct ResumeAfterPause {}; + /// A query stopped in the pause and vetoes the next attempt; the pause also set `state.observed_stop`. + struct QueryVetoedResend {}; + /// How a gated pause ended: resume, a query's veto, or the call's outcome. + using PauseOutcome = std::variant; /// The shared shape behind every gated pause below: admission for `envelopes` attempt reservations /// plus `pause_ms`, the deadline check, the counter this pause records itself under, then the sleep /// -- called even with a zero `pause_ms` UNLESS `should_sleep` is false, which is reserved for the - /// fuse's zero-pause reissue (a pace of "no pause", not "a zero-length one"). A value means the call - /// ended during it; nullopt means the caller may send another attempt. - std::optional gatedPause(uint64_t pause_ms, uint32_t envelopes, WriteState & state, - const Retry::Bound & bound, void (*record)(), bool should_sleep); - /// Admission, then the jittered sleep. A value means the call ended during it; nullopt means the - /// caller may send another attempt. Under `WriteState::spacing` this and the two siblings below - /// sleep `reissuePause` instead. - std::optional pauseAndReissue(WriteState & state, const Retry::Bound & bound); - /// The sibling for a clean lost race: the same admission and the same reservation, a flat - /// `Retry::conflictBackoff` sleep, and `state.reissues` untouched, so a transport fault that follows - /// starts its own schedule at the beginning. - std::optional pauseForConflict(WriteState & state, const Retry::Bound & bound); + /// fuse's zero-pause reissue (a pace of "no pause", not "a zero-length one"). + PauseOutcome gatedPause(uint64_t pause_ms, uint32_t envelopes, WriteState & state, + const Retry::Bound & bound, void (*record)(), bool should_sleep); + /// Admission, then the jittered sleep. Under `WriteState::spacing` this and the two siblings below + /// sleep `reissuePause` instead. Only a write's own reissues use these, with the write's own bound. + PauseOutcome pauseAndReissue(WriteState & state, const Retry::Bound & bound); /// The sibling for a failure text that named a failed connection. The same admission and the same /// reservation, a flat `kConnectHintPauseMs` sleep, and `state.reissues` untouched. - std::optional pauseFlat(WriteState & state, const Retry::Bound & bound); + PauseOutcome pauseFlat(WriteState & state, const Retry::Bound & bound); /// The sibling for a first-attempt fuse timeout: the same admission and the same reservation, NO /// sleep at all, and `state.reissues` untouched -- the fuse is a connection-quality answer about a /// fresh connection, not a store fault, so nothing here is paced against it. - std::optional reissueAtOnce(WriteState & state, const Retry::Bound & bound); + PauseOutcome reissueAtOnce(WriteState & state, const Retry::Bound & bound); /// The pause before a write reissue: `unspaced_ms`, or `Retry::pauseAfterAttempt` under `state.spacing`. uint64_t reissuePause(const WriteState & state, uint64_t unspaced_ms) const; @@ -545,7 +604,7 @@ class CasOperation [[noreturn]] void giveUpReadFenceLost(std::string_view verb, const String & subject, std::string_view when); [[noreturn]] void giveUpReadNoBudget(std::string_view verb, const String & subject, std::string_view what); [[noreturn]] void giveUpReadDeadline(std::string_view verb, const String & subject, - const Retry::Bound & bound, uint32_t attempts_made); + GaveUp::Source source, uint32_t attempts_made); CasRequests & owner; uint64_t admitted_generation; @@ -554,31 +613,39 @@ class CasOperation /// Written immediately before a read-class give-up throws, cleared and read only by the resolve /// read that swallows it. Every other caller lets the exception carry the verdict. std::optional last_read_stop; + /// The source of the bound the latest read-class request was given, for the same reader. + GaveUp::Source last_read_source = GaveUp::Source::Policy; RequestObserver observer; }; template auto CasOperation::readLoop(std::string_view verb, const String & subject, const Retry & policy, - const Retry::Bound & bound, Fn && once, OnMemoryLimit on_memory_limit) + Fn && once, OnMemoryLimit on_memory_limit) { + const Retry::Bound bound = owner.bindPolicy(policy); + const GaveUp::Source source = bound.source == Retry::Bound::Source::Lease ? GaveUp::Source::Lease : GaveUp::Source::Policy; + last_read_source = source; bool refresh_attempted = false; uint64_t attempt_started_ms = 0; /// Two counters, deliberately kept separate: `attempt_no` is the PHYSICAL attempt count handed to /// the transport (so a reissue is seen as attempt >= 2); `ordinary_reissues` is the /// exponential-backoff index. They advance together on an ordinary failure, but the first-attempt - /// fuse below advances `attempt_no` alone (via `continue`, skipping the backoff pause) so a - /// following ordinary failure's backoff still starts from `backoff(1)`, undisturbed. + /// fuse below advances `attempt_no` alone (no backoff pause) so a following ordinary failure's + /// backoff still starts from `backoff(1)`, undisturbed. for (uint32_t attempt_no = 1, ordinary_reissues = 0;; ++attempt_no) { - const uint64_t reservation = reservedFor(0, 1); - switch (gate(reservation)) + /// Not before the first attempt: a healthy read is never refused, as on a plain S3 disk. + if (attempt_no > 1) + throwIfBackgroundStopped(); + if (const std::optional refused = refusedReadAttempt(bound)) { - case Gate::FenceLost: giveUpReadFenceLost(verb, subject, "before the request"); - case Gate::NoBudget: giveUpReadNoBudget(verb, subject, "for one more request"); - case Gate::Ok: break; + switch (*refused) + { + case ReadStop::FenceLost: giveUpReadFenceLost(verb, subject, "before the request"); + case ReadStop::NoBudgetLease: giveUpReadNoBudget(verb, subject, "for one more request"); + case ReadStop::PolicyExhausted: giveUpReadDeadline(verb, subject, source, attempt_no - 1); + } } - if (!fits(reservation, bound)) - giveUpReadDeadline(verb, subject, bound, attempt_no - 1); if (policy.attempt_spacing_ms) attempt_started_ms = owner.now_ms(); @@ -589,6 +656,20 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const } catch (const std::exception & e) { + /// A local fault surfaces unchanged, as in the write loop; a query's stored cause can carry any code. + if (!isStoreAnswer(e) && !isQueryStoredCause(std::current_exception())) + throw; + /// Checked even inside `owed`, before classifying: a stopped owner's failure is not reissued. A background + /// owner reports its verdict; a stopped query keeps the failure, as on a plain S3 disk. + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(stop); + if (queryStopRequested()) + { + if (!refresh_attempted && !policy.single_attempt && isRefreshableCredentialError(e) + && !isQueryStoredCause(std::current_exception())) + detail::throwVetoedCredentialRetry(verb, subject, e); + throw; + } if (observer.on_failure && verb == "read" && isStoreAnswer(e)) observer.on_failure("GET", subject, e); if (on_memory_limit == OnMemoryLimit::Propagate && isMemoryLimitExceeded(e)) @@ -606,13 +687,10 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const detail::recordFirstAttemptFuse(); if (policy.single_attempt) throw; - /// A first-attempt fuse is a connection-quality answer, not a store fault: re-check - /// admission for the reissue alone and send it at once. `ordinary_reissues` stays put, so a - /// following ordinary failure's backoff starts at `backoff(1)`, exactly as if this attempt - /// had never happened. - if (fuse) + + const auto admit_reissue = [&](uint64_t pause_ms) { - const uint64_t needed = reservedFor(0, 1); + const uint64_t needed = reservedFor(pause_ms, 1); switch (gate(needed)) { case Gate::FenceLost: giveUpReadFenceLost(verb, subject, "before the reissue"); @@ -620,27 +698,31 @@ auto CasOperation::readLoop(std::string_view verb, const String & subject, const case Gate::Ok: break; } if (!fits(needed, bound)) - giveUpReadDeadline(verb, subject, bound, attempt_no); + giveUpReadDeadline(verb, subject, source, attempt_no); detail::recordReissue(); + }; + /// A first-attempt fuse is a connection-quality answer, not a store fault: re-check + /// admission for the reissue alone and send it at once. `ordinary_reissues` stays put, so a + /// following ordinary failure's backoff starts at `backoff(1)`, exactly as if this attempt + /// had never happened. + if (fuse) + { + admit_reissue(0); continue; } - } - ++ordinary_reissues; - const uint64_t pause_ms = policy.attempt_spacing_ms - ? Retry::pauseAfterAttempt(*policy.attempt_spacing_ms, attempt_started_ms, owner.now_ms()) - : Retry::backoff(ordinary_reissues); - const uint64_t needed = reservedFor(pause_ms, 1); - switch (gate(needed)) - { - case Gate::FenceLost: giveUpReadFenceLost(verb, subject, "before the reissue"); - case Gate::NoBudget: giveUpReadNoBudget(verb, subject, "for the reissue"); - case Gate::Ok: break; + ++ordinary_reissues; + const uint64_t pause_ms = policy.attempt_spacing_ms + ? Retry::pauseAfterAttempt(*policy.attempt_spacing_ms, attempt_started_ms, owner.now_ms()) + : Retry::backoff(ordinary_reissues); + admit_reissue(pause_ms); + if (!sleepUnlessQueryStops(pause_ms, [this](uint64_t ms) { sleep(ms); })) + { + if (refreshed) + detail::throwVetoedCredentialRetry(verb, subject, e); + throw; + } } - if (!fits(needed, bound)) - giveUpReadDeadline(verb, subject, bound, attempt_no); - detail::recordReissue(); - sleep(pause_ms); } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp index 5ccf6ecc1de79..62fd37252a572 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.cpp @@ -17,6 +17,13 @@ uint64_t Retry::backoff(uint32_t attempt) return thread_local_rng() % (ceiling + 1); /// full jitter: uniform(0, ceiling) } +uint64_t Retry::conflictBackoff(uint32_t loss) +{ + const uint64_t steps = loss > 0 ? loss - 1 : 0; + const uint64_t base = std::min(kCasConflictPauseCeilingMs, kCasConflictPauseStepMs * steps); + return base + thread_local_rng() % (base / 4 + 1); +} + uint64_t Retry::spacedPause(uint64_t spacing_draw_ms, uint64_t attempt_started_ms, uint64_t now_ms) { const uint64_t taken_ms = now_ms > attempt_started_ms ? now_ms - attempt_started_ms : 0; @@ -36,14 +43,16 @@ uint64_t Retry::drawSpacing(uint64_t attempt_spacing_ms_) Retry::Bound Retry::bind(uint64_t now_ms, uint64_t default_window_ms) const { const uint64_t effective_window_ms = window_ms.value_or(default_window_ms); - const uint64_t own_deadline_ms = policy_deadline_ms - ? *policy_deadline_ms - : (now_ms > std::numeric_limits::max() - effective_window_ms - ? std::numeric_limits::max() - : now_ms + effective_window_ms); - if (lease_deadline_ms && *lease_deadline_ms < own_deadline_ms) - return {*lease_deadline_ms, true}; - return {own_deadline_ms, false}; + Bound bound{ + .deadline_ms = now_ms > std::numeric_limits::max() - effective_window_ms + ? std::numeric_limits::max() + : now_ms + effective_window_ms, + .source = Bound::Source::RequestWindow}; + if (outside_cap_ms && *outside_cap_ms < bound.deadline_ms) + bound = {*outside_cap_ms, Bound::Source::OutsideCap}; + if (lease_deadline_ms && *lease_deadline_ms < bound.deadline_ms) + bound = {*lease_deadline_ms, Bound::Source::Lease}; + return bound; } } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h index c5e30b29df3cc..73fd6514854f2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasRetry.h @@ -6,13 +6,43 @@ namespace DB::Cas { -/// A retry policy for one logical CAS write, expressed WITHOUT touching a clock: `window_ms` is the -/// policy's own budget measured from the call's start (empty: the default window of the request plane), -/// and `lease_deadline_ms` (already reduced by the caller's safety margin) is an absolute bound on -/// whatever clock the caller's mount lease is tracked against. Binding a policy to an absolute deadline -/// is deferred to `bind`, which takes the caller's own `now_ms` -- `CasRequests` runs on an injected clock in tests, so a `Retry` built at -/// construction time from the real clock could never be exercised deterministically, and `GaveUp` -/// could not tell a lease-caused deadline from a policy-caused one without recording which bound won. +/// Caps on a hand-written loop's own iterations, independent of any clock: a loop that keeps +/// deciding again on fresh reads must end even when every iteration is quick. +/// An update of a shared object that keeps losing races fails at this count with `NETWORK_ERROR` "did not converge"; +/// there is no total time budget, and each request has its own window. +inline constexpr uint32_t kCasMaxDecisions = 100; +/// How much the pause grows with each further consecutive clean lost race of one call: enough to desynchronise competitors, +/// short enough not to wait long when a race is brief. +inline constexpr uint64_t kCasConflictPauseStepMs = 40; +/// The ceiling of the pause's base: 100 lost races cost about 67 to 84 s of pauses, under the waits other parts of +/// the server put on these loops. A pause adds up to a quarter of its base. +inline constexpr uint64_t kCasConflictPauseCeilingMs = 750; +/// The walk that fails at this count propagates its own error; a restart at it fails as "did not converge". +inline constexpr uint32_t kCasMaxRecoveryWalks = 8; + +/// A retry policy for one logical CAS request, expressed WITHOUT touching a clock. +/// +/// Every request gets its OWN window, measured from the entry of the engine call that sends it: `window_ms` +/// if set, else the default window of the plane it runs on. A window bounds one request or one local wait +/// (the hot-key queue wait), so `cas_request_window_ms` means one step. +/// +/// A loop that runs too long gets a smaller count, an owner's stop, or a time budget that decides only whether its +/// next pass starts (the copy-source confirm poll, the GC janitor's pages, the GC ref intake), never a deadline of its +/// own shared between its requests: a shared one leaves a later request no time after a slow early one and can refuse +/// the read that settles a write already sent. The only shared deadlines are absolute bounds from outside the loop, +/// below. Accepted cost: a conflict loop on a slow store can run about 100 windows. Two have neither: a paged listing +/// (`CasOperation::forEachListedKey`) runs until its callback stops it, and a request under `untilDefinitive` has no +/// window. +/// +/// Two things can end a request earlier, and `bind` takes the minimum of all three: +/// - `lease_deadline_ms`: an absolute bound (already reduced by the caller's safety margin) on the clock +/// the mount lease is tracked against; `GaveUp` reports it as the lease's, and an expired window or cap as the +/// policy's. +/// - `outside_cap_ms`: an absolute bound from a caller that has a deadline of its own (an offline tool's +/// `--timeout`). Successive requests under it share it. Set it only through `cappedAt`, never by hand, and +/// never to carry a loop's own budget: a cap never lengthens a window. +/// Binding is deferred to `bind`, which takes the caller's `now_ms`: `CasRequests` runs on an injected clock +/// in tests, and `GaveUp` must tell the lease's bound from the others. struct Retry { std::optional window_ms; @@ -26,14 +56,10 @@ struct Retry /// `GaveUp::Unresolved` so the caller decides new bytes. For namespace-create step 1, whose catalog /// row must differ per attempt. A clean conflict and a credential reissue are unaffected. Read /// paths ignore it. Clear it only in a loop that decides again on a fresh read (`casUpdateImpl` - /// with `CasOperation::pauseBeforeRedecide`); any other caller gets a bare `GaveUp::Unresolved`. + /// with `CasOperation::pauseAfterUnresolvedWrite`); any other caller gets a bare `GaveUp::Unresolved`. bool resend_unresolved = true; - /// An ABSOLUTE bound on the caller's own clock, replacing `window_ms` in `bind`. A hand-written - /// loop freezes one before it starts (`CasOperation::freeze`) and shares it across every call it - /// makes, so the loop as a whole ends when that deadline does instead of granting each of its - /// iterations a fresh window. Empty for a single verb, which gets its window from where it is - /// called. - std::optional policy_deadline_ms = std::nullopt; + /// An absolute bound on the caller's clock that can only shorten the request. See `cappedAt`. + std::optional outside_cap_ms = std::nullopt; /// When set, a reissue in `CasOperation`'s write and read loops waits until a draw from [0.8, 1.2] /// of this has passed since the failed attempt started, instead of the growing backoff. A /// first-attempt fuse timeout is still reissued at once. @@ -45,23 +71,23 @@ struct Retry /// `attempt == 0` returns 0. static uint64_t backoff(uint32_t attempt); - /// The flat pause after a clean lost race: `backoff(1)`, uniform over [0, 200] ms. It does not grow - /// with the writer's loss count, because a settled conflict has nothing to wait for but - /// desynchronisation from its competitors, and growing it with the loss count made the oldest - /// loser the slowest and the likeliest to lose again. A conflict that settled a transport fault - /// keeps `backoff(attempt)`: the fault is what must pace the loop. - static uint64_t conflictBackoff() { return backoff(1); } + /// The pause after the `loss`-th consecutive clean lost race of one call (1-based): `base` plus uniform(0, base / 4), + /// `base = min(kCasConflictPauseCeilingMs, kCasConflictPauseStepMs * (loss - 1))`, so the first is 0. The next decision + /// reads after the pause, so its length does not change that decision's chance; it grows only to + /// lower the contention a repeated loss shows, and the jitter keeps competitors from retrying in step. + /// A conflict that settled a transport fault keeps `backoff(attempt)`: the fault is what must pace it. + static uint64_t conflictBackoff(uint32_t loss); /// A policy with `ms` milliseconds of its own budget and no lease bound. static Retry within(uint64_t ms) { return {.window_ms = ms, .lease_deadline_ms = std::nullopt, .single_attempt = false}; } /// The default write policy: the window of the request plane it runs on. static Retry standard() { return {.window_ms = std::nullopt, .lease_deadline_ms = std::nullopt, .single_attempt = false}; } - /// A policy bound by the mount lease: `lease_deadline_ms` minus `margin`, clamped at 0 -- never - /// risk a write landing after this node's fence may already be gone. `window_ms` defaults to the - /// window of the request plane; a caller whose own budget is deliberately much smaller (the - /// graceful-shutdown farewell, whose window is derived from what ONE write costs, not from the - /// standard policy) passes its own window explicitly, and `bind` still takes whichever of the two - /// bounds is smaller. + /// A policy bound by the mount lease: an attempt starts only if its reserved time ends before + /// `lease_deadline_ms` minus `margin`, clamped at 0. That bounds when attempts start, not when they + /// land. `window_ms` defaults to the window of the request plane; a caller whose own budget is + /// deliberately much smaller (the graceful-shutdown farewell, whose window is derived from what ONE + /// write costs, not from the standard policy) passes its own window explicitly, and `bind` still + /// takes whichever of the two bounds is smaller. static Retry untilLeaseSafe(uint64_t lease_deadline_ms, uint64_t margin, std::optional window_ms = std::nullopt) { @@ -89,35 +115,24 @@ struct Retry return spacedPause(drawSpacing(attempt_spacing_ms_), attempt_started_ms, now_ms); } - /// This policy, made single-attempt. A frozen loop policy keeps its absolute deadline through it, - /// which is what lets a loop send an unrepeatable request under the same bound as the rest. - Retry asSingleAttempt() const - { - Retry copy = *this; - copy.single_attempt = true; - return copy; - } - - /// This policy ending no later than `deadline_ms` on the caller's clock. The deadline replaces `window_ms` as a - /// frozen one does; an earlier frozen deadline stays. + /// This policy ending no later than `deadline_ms` on the caller's clock; the window and the lease bound + /// still apply, and an earlier cap stays. Retry cappedAt(uint64_t deadline_ms) const { Retry copy = *this; - copy.policy_deadline_ms = policy_deadline_ms && *policy_deadline_ms < deadline_ms ? *policy_deadline_ms : deadline_ms; + copy.outside_cap_ms = outside_cap_ms && *outside_cap_ms < deadline_ms ? *outside_cap_ms : deadline_ms; return copy; } - /// A policy bound to an absolute deadline on the caller's own clock, plus which bound produced - /// it -- the caller's own budget, or the (smaller) lease bound. + /// A policy bound to an absolute deadline on the caller's own clock, plus which bound produced it. struct Bound { + enum class Source : uint8_t { RequestWindow, OutsideCap, Lease }; uint64_t deadline_ms; - bool lease_bound; + Source source; }; - /// Bind this policy to `now_ms`: `deadline_ms = min(policy_deadline_ms ?: now_ms + (window_ms ?: - /// default_window_ms), lease_deadline_ms)`, `lease_bound` true exactly when the lease bound was the - /// smaller of the two. Called once at call entry with the owner's `now_ms()`. A frozen policy therefore keeps - /// the lease bound honest: the smaller of the two still wins, and still says so. + /// `deadline_ms = min(now_ms + (window_ms ?: default_window_ms), outside_cap_ms, lease_deadline_ms)`. A bound + /// is the `source` only when strictly smaller than the ones before it in that order. Bound bind(uint64_t now_ms, uint64_t default_window_ms) const; }; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h index 722c6c2aa7449..65eeb8bcabbca 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Backend/CasWriteResult.h @@ -1,5 +1,6 @@ #pragma once #include +#include #include #include @@ -48,10 +49,12 @@ struct Declined { Observation seen; }; /// carry: an operator's attempt counters sum over ALL the endings of a write, and losing the key is /// one an operator wants counted rather than dropped. `any_ambiguous` is true when an attempt of the /// inner write ended without proof of whether it applied before the resolve read settled the race: a -/// caller outside the engine paces such a conflict on the growing schedule, as the engine's own -/// loops do, and a clean lost race on the flat one. `attempts_sent` cannot stand in for it: a +/// caller outside the engine paces such a conflict on the fault schedule (`Retry::backoff`), as the +/// engine's own loops do, and a clean lost race on `Retry::conflictBackoff`. `attempts_sent` cannot stand in for it: a /// throttled first attempt whose resolve read finds the key moved is one attempt, ambiguous. -struct Conflict { Observation seen; uint32_t attempts_sent = 0; bool any_ambiguous = false; }; +/// `observed_stop` is true when an operation of the call failed and saw its query stopped: a loop takes the +/// conflict as the answer and starts no further decision. +struct Conflict { Observation seen; uint32_t attempts_sent = 0; bool any_ambiguous = false; bool observed_stop = false; }; /// The store itself refused the request (not a lost precondition) -- `store_error` is a ClickHouse /// error code and `message` explains it. `attempts_sent` is the same count `Conflict` carries, for /// the same reason. @@ -59,7 +62,7 @@ struct Refused { int store_error; String message; uint32_t attempts_sent = 0; /// No attempt landed and none can be proven safe to keep making. struct GaveUp { - enum class Why : uint8_t { Deadline, FenceLost, Unresolved }; + enum class Why : uint8_t { Deadline, FenceLost, Unresolved, Attempts }; enum class Source : uint8_t { Policy, Lease }; Why why; Source deadline_source; bool sent_any; Observation last_seen; /// The HTTP attempts this call made, the same count `Committed` carries. Operator counters -- the @@ -120,6 +123,8 @@ inline std::optional orThrow(WriteResult && result, std::string_view what) throwCasTransientUnavailable(String(what), "mount fence tripped: the durable write is refused because this node no longer holds the mount incarnation it was admitted under"); case GaveUp::Why::Deadline: throwCasWriteRetryLater(fmt::format("{}: gave up at the {} deadline after {} attempt(s)", what, g.deadline_source == GaveUp::Source::Lease ? "lease" : "policy", g.sent_any ? "one or more" : "zero")); + case GaveUp::Why::Attempts: + throwCasWriteRetryLater(fmt::format("{}: did not converge after {} decisions", what, kCasMaxDecisions)); case GaveUp::Why::Unresolved: throwCasWriteRetryLater(g.sent_any ? fmt::format("{}: the write is unresolved (sent, resolve read found {})", what, renderObservation(g.last_seen)) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp index 7933094762862..59ec17f6724d5 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedSettings.cpp @@ -91,7 +91,7 @@ constexpr std::string_view CAS_KEY_PREFIX = "cas_"; DECLARE(UInt64, gc_io_concurrency, 16, "Maximum number of threads in the GC I/O pool. Used for fold and rebuild read-ahead, deletion-intent creates, orphan-manifest sweep planning reads, pending_deletes HEAD plus conditional DELETE, and namespace janitor batch deletes. Other GC requests run on the round thread. 1 disables parallel GC I/O", 0) \ DECLARE(UInt64, gc_bulk_delete_chunk_keys, 1000, "Most keys per batch delete request in GC's write-once families (owner-removed manifest bodies, covered ref logs and snapshots, the namespace janitor's dead ref logs and snapshots), capped by the storage's batch-delete limit; 1 to 1000", 0) \ DECLARE(UInt64, attempt_timeout_ms, 5000, "Budget for one HTTP attempt of a writable Native mount's control-plane requests (read, head, list, remove, conditional write), at least 1. With the connect cap it forms the attempt envelope the lease arithmetic reserves", 0) \ - DECLARE(UInt64, request_window_ms, 120000, "How long a failing request, including the blob publication loop, keeps retrying before it gives up with a retryable error, in milliseconds, measured from the call's start. Must exceed twice the attempt envelope for a writable disk and the envelope for a read-only one, or the disk refuses to open. The ref-table recovery budget is twice this value", 0) \ + DECLARE(UInt64, request_window_ms, 120000, "How long one failing request keeps starting attempts before it gives up with a retryable error, in milliseconds, measured from the start of that request. The same value bounds, on its own, the wait in the catalog queue and the time after which a copy-source confirm starts no new poll pass. The read that settles an unclear write has its own window. Loops are capped by count: a conditional update is decided at most 100 times, a catalog update submitted at most 100 times, a blob publication tried at most 8 times, and recovery of a table walks at most 8 times. Must exceed twice the attempt envelope for a writable disk and the envelope for a read-only one, or the disk refuses to open", 0) \ DECLARE(UInt64, lease_safety_margin_ms, 2000, "Startup-only margin validated against the mount lease TTL: attempt envelope + this must be strictly less than the TTL, and renew period + 2 × envelope + this too", 0) \ DECLARE(String, staging_backend, "local", "Blob staging backend (local | s3); s3 is opt-in", 0) \ diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp index 130c3222ee058..f5d8324765240 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/ContentAddressedTransaction.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -16,6 +17,8 @@ #include #include #include +#include +#include #include #include #include @@ -29,6 +32,7 @@ #include #include #include +#include #include #include @@ -38,6 +42,11 @@ namespace ProfileEvents extern const Event CASBlobUploadFanoutTasks; } +namespace CurrentMetrics +{ + extern const Metric IsServerShuttingDown; +} + namespace fs = std::filesystem; namespace DB @@ -63,6 +72,13 @@ bool hasSuffix(std::string_view s, std::string_view suffix) return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix; } +/// True when the removal is retried after a restart, so server shutdown may stop it: today only the catalog's drop +/// worker removes an `Atomic` table directory without a query. A new such caller must requeue a failed removal. +bool tableRemovalResumesAfterRestart(const std::string & path) +{ + return endsWithTableUuidPair(path) && !CurrentThread::tryGetQueryContext(); +} + } std::unique_ptr openLocalStagedBlobPayload(const std::string & path, uint64_t payload_size) @@ -707,6 +723,8 @@ void ContentAddressedTransaction::commit(const TransactionCommitOptionsVariant & /// dropped. `dropRefIfMatches` additionally guards against a concurrent repoint of the SAME ref /// since this call's own publish: it removes the ref only if it still names the exact /// `manifest_ref` this commit bound, leaving a newer binding untouched. + /// Owed to the failed commit: a stopped owner must not leave a ref of that commit live. + const auto owed = Cas::OwnerScope::owed(); for (const auto & oc : part_outcomes) if (oc && oc->created) metadata_storage.partAccess()->dropRefIfMatches({oc->ns, oc->ref}, oc->manifest_ref); @@ -1317,6 +1335,13 @@ void ContentAddressedTransaction::removeRecursive(const std::string & path, cons /// file go in one dropNamespace. if (auto uuid = Cas::parseTableUuid(path)) { + std::optional shutdown_owner; + if (Cas::tableRemovalResumesAfterRestart(path)) + shutdown_owner.emplace(Cas::OwnerScope::background([] + { + if (CurrentMetrics::get(CurrentMetrics::IsServerShuttingDown)) + throw Exception(ErrorCodes::ABORTED, "CAS table namespace removal stopped by server shutdown"); + })); metadata_storage.partAccess()->dropNamespace(metadata_storage.liveNamespace(*uuid)); return; } @@ -1768,6 +1793,8 @@ void ContentAddressedTransaction::moveFile(const std::string & path_from, const /// attach via moveFile): delegate to moveDirectory, which owns directory shapes. if (src && dst && !src->ref.empty() && src->file.empty() && !dst->ref.empty() && dst->file.empty()) { + /// Owed to the reserved name: only the undo reaches here, and SQL rejects a part left under it. + const auto owed = Cas::OwnerScope::owed(); moveDirectory(path_from, path_to); return; } @@ -2044,6 +2071,8 @@ void fanOutBlobUploads( size_t idx = 0; for (const auto & [ref, req] : grouped) { + /// The drain guard still joins the tasks already dispatched. + throwIfBackgroundStopped(); std::optional * slot = &result_slots[idx++]; BlobUploadRequest task_req = req; const BlobUploadFanoutHooksForTest * task_hooks = hooks; @@ -2052,8 +2081,10 @@ void fanOutBlobUploads( /// Schedule and track in ONE no-throw step: `enqueueAndGiveOwnership` returns the handle (the /// task is now runnable) and the pre-reserved `emplace_back` records it without allocating, so /// there is no window in which a scheduled task is untracked. - handles.emplace_back(runner.enqueueAndGiveOwnership([slot, txn, req_by_value = std::move(task_req), task_hooks] + handles.emplace_back(runner.enqueueAndGiveOwnership([slot, txn, req_by_value = std::move(task_req), task_hooks, + group = CurrentThread::getGroup()] { + throwUnlessInThreadGroup(group, "CAS blob upload worker"); if (task_hooks && task_hooks->in_task) task_hooks->in_task(req_by_value.ref); *slot = txn->uploadBlobDetached(req_by_value); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasBlobInDegree.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasBlobInDegree.cpp index c97c7dad14322..6367f70a28a3d 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasBlobInDegree.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasBlobInDegree.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -213,7 +214,8 @@ bool AdoptedRunReader::reportingRefusal(Read && read) } catch (const Exception & e) { - if (e.code() != ErrorCodes::CORRUPTED_DATA) + /// A query's stored cause is no finding about the run, whatever its code. + if (e.code() != ErrorCodes::CORRUPTED_DATA || isQueryStoredCause(std::current_exception())) throw; refused = Refusal{.run_key = next_run > 0 ? currentRun().key : String{}, .message = e.message()}; view.reset(); @@ -242,8 +244,9 @@ bool AdoptedRunReader::nextInRunChecked(SourceEdgeRecord & rec) } catch (Exception & e) { + /// The row read refills from the store, so this can be a stopped query's shared exception. if (e.code() == ErrorCodes::CORRUPTED_DATA) - e.addMessage(fmt::format("in CAS source-edge run `{}` of GC shard {}", currentRun().key, shard)); + addMessageUnlessQueryStoredCause(e, fmt::format("in CAS source-edge run `{}` of GC shard {}", currentRun().key, shard)); throw; } if (!got) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp index 39c2b289ad513..61e50cc27e750 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -19,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -150,6 +152,8 @@ struct WriteOnceJobResult uint64_t leaked = 0; uint64_t requests = 0; String error; + /// The failure of a job whose query had stopped: the caller propagates it rather than publishing the page. + std::exception_ptr stopped_query_failure; }; /// Deletes `chunk` as one request. A storage that refuses the batch gets one request per key, each @@ -165,7 +169,8 @@ void removeChunkWriteOnceCountingKeys(CasOperation & op, const std::vectoropenRequests().resume(admitted_generation, [this] { return authority_held; }); @@ -558,6 +570,8 @@ void Gc::removeWriteOnceOnIoPool(CasOperation & op, const std::vectorleaked = chunk->size() - result->deleted; result->error = getCurrentExceptionMessage(false); + if (queryStopRequested()) + result->stopped_query_failure = std::current_exception(); } })); } @@ -580,6 +594,9 @@ void Gc::removeWriteOnceOnIoPool(CasOperation & op, const std::vector & catch (Exception & e) { /// A refusal carries the store's text only; the round's error must name what it failed to delete. - e.addMessage("while deleting {} blob intents starting at '{}'", chunk.size(), chunk.front().str()); + addMessageUnlessQueryStoredCause(e, fmt::format("while deleting {} blob intents starting at '{}'", chunk.size(), + chunk.front().str())); throw; } } @@ -762,8 +781,10 @@ void Gc::redeleteBlobs( body_delete = entries[scheduled], layout_ptr = &layout, pool_store = store, - admitted_generation] + admitted_generation, + group = CurrentThread::getGroup()] { + throwUnlessInThreadGroup(group, "CAS GC re-delete worker"); CasOperation job_op = pool_store->openRequests().resume(admitted_generation); *slot = performRedeleteIo(body_delete, *layout_ptr, job_op); })); @@ -825,6 +846,7 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al RoundReport local_report; RoundReport & report = progress ? *progress : local_report; report = RoundReport{}; + round_stop_observed = false; GcState state; std::optional state_etag; @@ -880,8 +902,19 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al /// The helping barrier precedes heartbeat work, DEFER, the hot stream LIST, and every successor /// artifact. A deferred invocation therefore cannot leave a row the adopted parent already proved /// complete, and a folding invocation takes its catalog cut only after the deletion settles. + const auto throw_if_round_stopped = [this] + { + if (!stop_signal || !stop_signal()) + return; + round_stop_observed = true; + throw Exception(ErrorCodes::ABORTED, "CAS GC round stopped by its scheduler"); + }; { GcPhaseTimer t(phase_sink, "pre_fold_ref_drain"); + /// The scheduler owns the drain as a background owner: every background check in the drain throws on its stop. + std::optional scheduler_owner; + if (stop_signal) + scheduler_owner.emplace(OwnerScope::background(throw_if_round_stopped)); uint64_t completed_erases = 0; uint64_t cancelled_creating = 0; /// Declared after `t`, so it runs before the timer emits its record, on a throw too. @@ -973,6 +1006,7 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al store->poolConfig().manifest_sweep_list_budget_keys, orphan_manifest_sweep_decision_at_ms); const bool run_orphan_manifest_sweep = orphan_manifest_sweep_decision == OrphanManifestSweepDecision::StartSweep || orphan_manifest_sweep_decision == OrphanManifestSweepDecision::ContinueSweep; + throw_if_round_stopped(); { GcPhaseTimer t(phase_sink, "defer_decision"); const bool row_decision_due = rowDecisionDue(state, new_round); @@ -1466,176 +1500,156 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al /// a crash between the CAS and here leaks the prefix to fsck (single-crash window, no permanent leak — /// but note the cursor already advanced, so a plain retry will NOT re-attempt it; fsck is the backstop). /// - /// Phase `handoff_reclaim`. - { - GcPhaseTimer t(phase_sink, "handoff_reclaim"); - uint64_t objects_reclaimed = 0; - std::set new_referenced_generations; - for (const RunRef & r : folded.fold_seal.blob_target_runs) - new_referenced_generations.insert(r.key_generation); - - std::set handed_off; /// dedupe: multiple parent refs can share one generation - /// GATED like every other destructive site, and it is also the FIRST destructive site of the - /// post-CAS tail -- which is why the gate is read before the tail begins rather than partway - /// down it. - /// - /// UNLIKE EVERY OTHER GATED SITE, SUPPRESSION HERE LOSES THE WORK RATHER THAN POSTPONING IT. - /// The hand-off is a one-shot DIFFERENCE between the parent seal's runs and the new seal's, and - /// a suppressed round still FOLDS -- only the irreversible half stops -- so the ref moves off - /// the old generation on this very round and the next round's parent seal no longer names it. - /// Nothing revisits it: `snap_pruned_through` is already past that generation and the wholesale - /// prune only walks forward. The prefix is left to `fsck`, which is the same outcome this site - /// already documents for a crash in this window (see the `handoff_reclaim` comment above). Bounded -- - /// one small run per shard per occurrence of a suppressed round that also folded a delta -- and - /// not a correctness problem, but it is the one place where the gate costs something permanent, - /// so it is asserted rather than left to be discovered. - static const std::vector kNoRuns; - const std::vector & handoff_candidates = - suppress_destructive ? kNoRuns : parent_seal_runs; - for (const RunRef & old_ref : handoff_candidates) + /// Phase `handoff_reclaim`, then phase `manifest_deletes`, both owed: the round committed, and nothing revisits + /// what it handed off. A stop that skipped the manifest deletes would leave them to the orphan sweep, the only + /// backstop. + { + const auto owed = OwnerScope::owed(); { - /// Only generations the wholesale prune already passed AND that no live ref still pins. - if (old_ref.key_generation > state.snap_pruned_through) - continue; /// not yet pruned-through: the normal prune will reclaim it when it ages out - if (new_referenced_generations.contains(old_ref.key_generation)) - continue; /// still referenced by a (possibly different-shard) live ref: keep it - if (!handed_off.insert(old_ref.key_generation).second) - continue; /// already reclaimed this round via another shard's ref - /// `bounded_remaining` draws from the hand-off's OWN reserve, never `UINT64_MAX` and never - /// `pruneSupersededGenerations`' shared remainder: this hand-off is a ONE-SHOT event (see the - /// `handoff_reclaim` comment above) -- a generation this call reclaims only PARTIALLY is left - /// exactly like a crash in this window already is -- to `fsck`, never revisited by a later - /// round's hand-off (the parent-seal difference that triggers it does not recur once the ref - /// has moved). The prune, by contrast, safely retries an under-served generation next round - /// via its cursor, so sharing one pool would let a prune-heavy round strand this one-shot - /// reclaim at zero every time; the separate reserve makes that impossible. - const uint64_t remaining = round_work_budget.handoffPrefixWholesaleRemaining(); - if (remaining == 0) - break; - const uint64_t reclaimed = deletePrefixWholesale( - op, layout.gcGenPrefix(old_ref.key_generation), remaining); - round_work_budget.handoff_prefix_wholesale_objects_used += reclaimed; - objects_reclaimed += reclaimed; - LOG_TRACE(logger, - "CAS GC hand-off: generation {} moved out of the live seal below the retention cursor " - "({} objects) — post-CAS wholesale reclaim (the prune had skipped it while referenced)", - old_ref.key_generation, reclaimed); + GcPhaseTimer t(phase_sink, "handoff_reclaim"); + uint64_t objects_reclaimed = 0; + std::set new_referenced_generations; + for (const RunRef & r : folded.fold_seal.blob_target_runs) + new_referenced_generations.insert(r.key_generation); + + std::set handed_off; /// dedupe: multiple parent refs can share one generation + /// GATED like every other destructive site, and it is also the FIRST destructive site of the + /// post-CAS tail -- which is why the gate is read before the tail begins rather than partway + /// down it. + /// + /// UNLIKE EVERY OTHER GATED SITE, SUPPRESSION HERE LOSES THE WORK RATHER THAN POSTPONING IT. + /// The hand-off is a one-shot DIFFERENCE between the parent seal's runs and the new seal's, and + /// a suppressed round still FOLDS -- only the irreversible half stops -- so the ref moves off + /// the old generation on this very round and the next round's parent seal no longer names it. + /// Nothing revisits it: `snap_pruned_through` is already past that generation and the wholesale + /// prune only walks forward. The prefix is left to `fsck`, which is the same outcome this site + /// already documents for a crash in this window (see the `handoff_reclaim` comment above). Bounded -- + /// one small run per shard per occurrence of a suppressed round that also folded a delta -- and + /// not a correctness problem, but it is the one place where the gate costs something permanent, + /// so it is asserted rather than left to be discovered. + static const std::vector kNoRuns; + const std::vector & handoff_candidates = + suppress_destructive ? kNoRuns : parent_seal_runs; + for (const RunRef & old_ref : handoff_candidates) + { + /// Only generations the wholesale prune already passed AND that no live ref still pins. + if (old_ref.key_generation > state.snap_pruned_through) + continue; /// not yet pruned-through: the normal prune will reclaim it when it ages out + if (new_referenced_generations.contains(old_ref.key_generation)) + continue; /// still referenced by a (possibly different-shard) live ref: keep it + if (!handed_off.insert(old_ref.key_generation).second) + continue; /// already reclaimed this round via another shard's ref + /// `bounded_remaining` draws from the hand-off's OWN reserve, never `UINT64_MAX` and never + /// `pruneSupersededGenerations`' shared remainder: this hand-off is a ONE-SHOT event (see the + /// `handoff_reclaim` comment above) -- a generation this call reclaims only PARTIALLY is left + /// exactly like a crash in this window already is -- to `fsck`, never revisited by a later + /// round's hand-off (the parent-seal difference that triggers it does not recur once the ref + /// has moved). The prune, by contrast, safely retries an under-served generation next round + /// via its cursor, so sharing one pool would let a prune-heavy round strand this one-shot + /// reclaim at zero every time; the separate reserve makes that impossible. + const uint64_t remaining = round_work_budget.handoffPrefixWholesaleRemaining(); + if (remaining == 0) + break; + const uint64_t reclaimed = deletePrefixWholesale( + op, layout.gcGenPrefix(old_ref.key_generation), remaining); + round_work_budget.handoff_prefix_wholesale_objects_used += reclaimed; + objects_reclaimed += reclaimed; + LOG_TRACE(logger, + "CAS GC hand-off: generation {} moved out of the live seal below the retention cursor " + "({} objects) — post-CAS wholesale reclaim (the prune had skipped it while referenced)", + old_ref.key_generation, reclaimed); + } + t.metric("generations_reclaimed", handed_off.size()); + t.metric("objects_reclaimed", objects_reclaimed); + t.metric("suppressed", suppress_destructive ? 1 : 0); } - t.metric("generations_reclaimed", handed_off.size()); - t.metric("objects_reclaimed", objects_reclaimed); - t.metric("suppressed", suppress_destructive ? 1 : 0); - } - /// Post-CAS: owner-removed manifest bodies — deleted ONLY now, after their decrements were - /// ADOPTED by the round CAS (delete-after-sealed-decrements). NOT durable across rounds: the - /// ref-log intake cursor that discovered each `-1` edge is committed by THIS round's CAS above, - /// so a log already folded is never re-visited and never re-populates `mf_cleanup`. This phase is - /// deliberately unbudgeted: a cap would leave a declined entry unreachable from any live ref AND - /// never re-derived by this pipeline, converting a bounded burst into a permanent leak. It drains - /// the whole of `folded.mf_cleanup` every round it runs; only a crash (or the destructive-suppression - /// gate below) leaves an entry for the orphan-manifest sweep to reclaim later. - /// The bodies go in batch requests of write-once keys; see the block. - /// - /// Phase `manifest_deletes`. - { - GcPhaseTimer t(phase_sink, "manifest_deletes"); - const uint64_t manifests_deleted_before = report.manifests_deleted; - /// GATED. A manifest body is content the ref graph still describes until its decrements are both - /// sealed AND taken on a round that could prove its frontier -- an unprovable round's `-1` may - /// itself be the observation that is missing an owner elsewhere, so deleting the body on it is - /// exactly the irreversible step the gate exists to withhold. - static const std::map kNoManifestCleanup; - const std::map & mf_cleanup_now = - suppress_destructive ? kNoManifestCleanup : folded.mf_cleanup; - - /// Chunks of write-once keys, one request each, with no per-key precondition: a manifest key is - /// never written twice, so the body at it is the one the fold observed or nothing. The engine - /// reissues a failed chunk whole; a chunk that exhausts its policy throws here, and the chunks - /// before it are already recorded below. A key that one of the exhausted chunk's own attempts - /// did delete is not recorded either: deletion and recording are all-or-nothing per request, - /// never per key, so the next round's fold sees that key as already gone. The etag the fold - /// observed rides the event as information only. - const size_t chunk_keys = std::clamp(store->poolConfig().gc_bulk_delete_chunk_keys, 1, kBulkDeleteMaxKeys); - const size_t request_keys = bulkDeleteChunkKeys(); - uint64_t attempted = 0; - uint64_t requests = 0; - std::vector chunk; - std::vector *> chunk_entries; - const auto flush = [&] + /// Post-CAS: owner-removed manifest bodies — deleted ONLY now, after their decrements were + /// ADOPTED by the round CAS (delete-after-sealed-decrements). NOT durable across rounds: the + /// ref-log intake cursor that discovered each `-1` edge is committed by THIS round's CAS above, + /// so a log already folded is never re-visited and never re-populates `mf_cleanup`. This phase is + /// deliberately unbudgeted: a cap would leave a declined entry unreachable from any live ref AND + /// never re-derived by this pipeline, converting a bounded burst into a permanent leak. It drains + /// the whole of `folded.mf_cleanup` every round it runs; only a crash (or the destructive-suppression + /// gate below) leaves an entry for the orphan-manifest sweep to reclaim later. + /// The bodies go in batch requests of write-once keys; see the block. + /// + /// Phase `manifest_deletes`. { - if (chunk.empty()) - return; - /// A backend without `DeleteObjects` (GCS) falls back to one admitted delete per key here; - /// `chunk_entries`' per-key bookkeeping below is unaffected either way -- it counts objects - /// that are gone after this call returns, not how many requests it took to get them there. - requests += removeCohortWriteOnce(op, chunk, request_keys, Retry::standard()); - for (const auto * entry : chunk_entries) + GcPhaseTimer t(phase_sink, "manifest_deletes"); + const uint64_t manifests_deleted_before = report.manifests_deleted; + /// GATED. A manifest body is content the ref graph still describes until its decrements are both + /// sealed AND taken on a round that could prove its frontier -- an unprovable round's `-1` may + /// itself be the observation that is missing an owner elsewhere, so deleting the body on it is + /// exactly the irreversible step the gate exists to withhold. + static const std::map kNoManifestCleanup; + const std::map & mf_cleanup_now = + suppress_destructive ? kNoManifestCleanup : folded.mf_cleanup; + + /// Chunks of write-once keys, one request each, with no per-key precondition: a manifest key is + /// never written twice, so the body at it is the one the fold observed or nothing. The engine + /// reissues a failed chunk whole; a chunk that exhausts its policy throws here, and the chunks + /// before it are already recorded below. A key that one of the exhausted chunk's own attempts + /// did delete is not recorded either: deletion and recording are all-or-nothing per request, + /// never per key, so the next round's fold sees that key as already gone. The etag the fold + /// observed rides the event as information only. + const size_t chunk_keys = std::clamp(store->poolConfig().gc_bulk_delete_chunk_keys, 1, kBulkDeleteMaxKeys); + const size_t request_keys = bulkDeleteChunkKeys(); + uint64_t attempted = 0; + uint64_t requests = 0; + std::vector chunk; + std::vector *> chunk_entries; + const auto flush = [&] { - ++report.manifests_deleted; - EventEmitter{*store}.emit([&](CasEvent & e) + if (chunk.empty()) + return; + /// A backend without `DeleteObjects` (GCS) falls back to one admitted delete per key here; + /// `chunk_entries`' per-key bookkeeping below is unaffected either way -- it counts objects + /// that are gone after this call returns, not how many requests it took to get them there. + requests += removeCohortWriteOnce(op, chunk, request_keys, Retry::standard()); + for (const auto * entry : chunk_entries) { - e.type = CasEventType::ManifestDelete; - e.namespace_ = entry->first.root_namespace.string(); - e.object_kind = CasEventObjectKind::Manifest; - e.object_hash = manifestRefDebugString(entry->first.ref); - e.token = entry->second.render(); - e.round = new_round; - e.gen = generation; - e.outcome = "deleted_or_absent"; - e.reason = "owner-removed manifest body; batch delete of a write-once key after decrements adopted"; - }); + ++report.manifests_deleted; + EventEmitter{*store}.emit([&](CasEvent & e) + { + e.type = CasEventType::ManifestDelete; + e.namespace_ = entry->first.root_namespace.string(); + e.object_kind = CasEventObjectKind::Manifest; + e.object_hash = manifestRefDebugString(entry->first.ref); + e.token = entry->second.render(); + e.round = new_round; + e.gen = generation; + e.outcome = "deleted_or_absent"; + e.reason = "owner-removed manifest body; batch delete of a write-once key after decrements adopted"; + }); + } + chunk.clear(); + chunk_entries.clear(); + }; + for (const auto & entry : mf_cleanup_now) + { + ++attempted; + chunk.push_back(layout.writeOnceManifestKey(entry.first)); + chunk_entries.push_back(&entry); + if (chunk.size() >= chunk_keys) + flush(); } - chunk.clear(); - chunk_entries.clear(); - }; - for (const auto & entry : mf_cleanup_now) - { - ++attempted; - chunk.push_back(layout.writeOnceManifestKey(entry.first)); - chunk_entries.push_back(&entry); - if (chunk.size() >= chunk_keys) - flush(); + flush(); + t.metric("attempted", attempted); + t.metric("accepted", report.manifests_deleted - manifests_deleted_before); + t.metric("requests", requests); + t.metric("suppressed", suppress_destructive ? 1 : 0); } - flush(); - t.metric("attempted", attempted); - t.metric("accepted", report.manifests_deleted - manifests_deleted_before); - t.metric("requests", requests); - t.metric("suppressed", suppress_destructive ? 1 : 0); } /// Removal completion has no physical pass. The terminal fold placed positive evidence in the /// life row; a later invocation's catalog-only pre-fold drain owns lifecycle deletion, while the /// perpetual janitor owns dead-life bytes. - uint64_t cleanup_evidence_rows = 0; - for (const auto & [life_id, ref_life_state] : folded.fold_seal.ref_lives) - cleanup_evidence_rows += ref_life_state.cleanup_evidence ? 1 : 0; - runNamespaceJanitor(state, suppress_destructive, cleanup_evidence_rows); - /// Phase `ref_object_cleanup`. Emitted even when the whole pass is skipped (`trim_enabled` is - /// a test seam, `suppressed` gates the deletes), because "this phase did nothing and why" is exactly - /// what a reader of a round that reclaimed nothing needs to see. - { - GcPhaseTimer t(phase_sink, "ref_object_cleanup"); - RefCleanupPassStats cleanup_stats; - /// Runs before `t` emits its row, also when a delete chunk throws: the pass has then already - /// deleted objects that the row must account for. - SCOPE_EXIT_SAFE({ - t.metric("suppressed", suppress_destructive ? 1 : 0); - t.metric("trim_enabled", trim_enabled ? 1 : 0); - t.metric("namespaces_planned", folded.ref_tables.size()); - t.metric("objects_planned", cleanup_stats.objects_planned); - t.metric("objects_deleted", cleanup_stats.objects_deleted); - t.metric("namespaces_skipped", cleanup_stats.namespaces_skipped); - t.metric("stopped_lease_moved", cleanup_stats.stopped_lease_moved ? 1 : 0); - t.metric("stopped_authority_unverified", cleanup_stats.stopped_authority_unverified ? 1 : 0); - t.metric("chunks_under_catalog_change", cleanup_stats.chunks_under_catalog_change); - }); - if (trim_enabled) - cleanupRefObjects(folded, state.lease, suppress_destructive, round_work_budget, cleanup_stats); - } /// Bounded orphan-manifest backstop. The fold already exact-read each candidate, retired its exact /// source edges into the adopted runs and placed cursor progress in the SAME `gc/state` CAS above. - /// Only this post-CAS tail may delete candidate bodies. + /// Only this post-CAS tail may delete candidate bodies. It runs before the janitor and the ref cleanup: + /// those resume next round, while the commit moved the sweep cursor past these nominations. /// Phase `orphan_sweep`. { GcPhaseTimer t(phase_sink, "orphan_sweep"); @@ -1695,6 +1709,33 @@ RoundReport Gc::runRegularRound(std::function on_lease_acquired, bool al t.metric("retained_work_budget", sweep.retained_work_budget); } + uint64_t cleanup_evidence_rows = 0; + for (const auto & [life_id, ref_life_state] : folded.fold_seal.ref_lives) + cleanup_evidence_rows += ref_life_state.cleanup_evidence ? 1 : 0; + runNamespaceJanitor(state, suppress_destructive, cleanup_evidence_rows); + /// Phase `ref_object_cleanup`. Emitted even when the whole pass is skipped (`trim_enabled` is + /// a test seam, `suppressed` gates the deletes), because "this phase did nothing and why" is exactly + /// what a reader of a round that reclaimed nothing needs to see. + { + GcPhaseTimer t(phase_sink, "ref_object_cleanup"); + RefCleanupPassStats cleanup_stats; + /// Runs before `t` emits its row, also when a delete chunk throws: the pass has then already + /// deleted objects that the row must account for. + SCOPE_EXIT_SAFE({ + t.metric("suppressed", suppress_destructive ? 1 : 0); + t.metric("trim_enabled", trim_enabled ? 1 : 0); + t.metric("namespaces_planned", folded.ref_tables.size()); + t.metric("objects_planned", cleanup_stats.objects_planned); + t.metric("objects_deleted", cleanup_stats.objects_deleted); + t.metric("namespaces_skipped", cleanup_stats.namespaces_skipped); + t.metric("stopped_lease_moved", cleanup_stats.stopped_lease_moved ? 1 : 0); + t.metric("stopped_authority_unverified", cleanup_stats.stopped_authority_unverified ? 1 : 0); + t.metric("chunks_under_catalog_change", cleanup_stats.chunks_under_catalog_change); + }); + if (trim_enabled) + cleanupRefObjects(folded, state.lease, suppress_destructive, round_work_budget, cleanup_stats); + } + return report; } @@ -4267,9 +4308,11 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, catch (const Exception & e) { /// A read verb that gives up throws `NETWORK_ERROR`; any other failure fails the round, as elsewhere. - /// A lost fence or a spent lease budget throws the same code. + /// A lost fence or a spent lease budget throws the same code. A stopped owner's failure was not retried, + /// so it says nothing about the leased version. if (e.code() != ErrorCodes::NETWORK_ERROR) throw; + rethrowIfStoppedOwnersFailure(); seen = "no answer (" + e.message() + ")"; } result.parent_unconfirmed = !seen.empty(); @@ -4604,7 +4647,7 @@ Gc::FoldResult Gc::fold(GcState & state, std::optional & state_etag, { /// The parent runs this merge streams are what a newer leader's retention removes. An absent run was /// classified by its own probe; a second probe could contradict it. - if (e.code() == ErrorCodes::CORRUPTED_DATA && !absence_classified) + if (e.code() == ErrorCodes::CORRUPTED_DATA && !absence_classified && !isQueryStoredCause(std::current_exception())) throwIfStateMoved(op, state_etag, e.message()); throw; } @@ -5251,17 +5294,30 @@ bool Gc::rowDecisionDue(const GcState & state, uint64_t current_round) /// FAIL-CLOSED: a missing / undecodable seal, or a summary that is not TOTAL over gc_shards, is /// corrupt GC bookkeeping — force a FOLD so the round's own fail-closed path surfaces it, never a /// silent defer (matching the fold's throw-on-missing-adopted-seal treatment). + std::optional seal_bytes; + try + { + CasOperation op = store->openRequests().admit(); + seal_bytes = op.read(store->layout().foldSealKey(state.snap_generation, state.snap_attempt), Retry::standard()); + } + catch (...) + { + /// A read that failed for a killed query says nothing about the seal. + if (queryStopRequested()) + throw; + return true; + } + if (!seal_bytes) + return true; std::optional seal; try { - seal = readFoldSeal(state.snap_generation, state.snap_attempt); + seal = decodeFoldSeal(seal_bytes->bytes, store->layout(), store->poolConfig().gc_shards, state.snap_generation); } catch (...) { return true; /// undecodable seal => fail-closed force-fold } - if (!seal) - return true; for (uint64_t shard = 0; shard < state.gc_shards; ++shard) { const auto it = seal->condemned_summary.find(shard); @@ -5440,6 +5496,7 @@ RebuildReport Gc::rebuildBaseline(bool force) } catch (const Exception & e) { + rethrowIfStoppedOwnersFailure(); throw Exception(ErrorCodes::CORRUPTED_DATA, "CAS GC rebuild: the prior fold seal (generation {}, attempt {}) is UNDECODABLE " "({}), so the holds it carries cannot be read. A rebuild that dropped them would " @@ -5498,6 +5555,7 @@ RebuildReport Gc::rebuildBaseline(bool force) } catch (const Exception & e) { + rethrowIfStoppedOwnersFailure(); throw Exception(ErrorCodes::CORRUPTED_DATA, "CAS GC rebuild: gc/state names no adopted baseline and the newest fold seal " "(generation {}, attempt {}) is UNDECODABLE ({}), so the holds this pool carries " @@ -6040,6 +6098,7 @@ void Gc::refreshAuthority(uint64_t admitted_generation, const Retry & policy) } catch (...) { + rethrowIfStoppedOwnersFailure(); tryLogCurrentException(logger, "CAS gc: the leader-authority probe failed; this round's destructive operations treat the " "lease as lost"); @@ -6071,9 +6130,9 @@ bool Gc::acquireOrRenewLease(GcState & state, std::optional & state_etag, CasOperation op = store->openRequests().admit(); const String key = store->layout().gcStateKey(); - /// What the decision that actually landed wrote. `readModifyWrite` re-decides on every conflict - /// against what the losing write's own resolve read observed, so the last decision is the committed - /// one, and a competing leader's write makes the next decision see a moved lease tuple. + /// What the decision that actually landed wrote. `readModifyWrite` re-decides after every conflict + /// on a read taken after its pause, so the last decision is the committed one, and a competing + /// leader's write makes the next decision see a moved lease tuple. GcState decided; bool decided_never_held = false; const std::optional committed = orThrow(op.readModifyWrite(key, diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h index b1bc1a2db24ec..35c85aaddf9fa 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGc.h @@ -535,14 +535,15 @@ class Gc /// instance, and the scheduler holds `gc_round_mutex` across both the install and the round. void setPhaseSink(GcPhaseSink sink) { phase_sink = std::move(sink); } - /// Install (or clear) the stop signal of the rounds that follow. Planning asks it before each read, the walk - /// before each step, and the intake once more after its last walk. Once it answers true, the intake reads no - /// further ref log, every namespace it has not finished stays unproven, and the round deletes nothing; the - /// reduce and the commit still run. A stop after the final intake poll does not affect the round. Not asked: - /// the pre-fold drain of catalog rows, the checkpoint reads before planning, and a cold cursor's resolution, - /// which may follow one backlink per epoch. Installed and cleared like `setPhaseSink`. + /// Install (or clear) the stop signal of the rounds that follow, like `setPhaseSink`. The drain and pre-listing + /// poll throw `ABORTED` and set `roundStopObserved`. During intake, a stop ends reads and suppresses deletion. + /// Reduce and commit still run. Checkpoint reads and cold cursor resolution do not poll. The callback may run + /// under a CAS mutex, so it must be lock-free or take only a leaf lock. void setStopSignal(std::function signal) { stop_signal = std::move(signal); } + /// Whether the current or last `runRegularRound` found the stop signal true before its hot listing. + bool roundStopObserved() const { return round_stop_observed; } + /// Keys per GC write-once delete request: `gc_bulk_delete_chunk_keys` capped by the storage's batch /// limit, clamped to [1, `kBulkDeleteMaxKeys`] because an empty request would never advance. size_t bulkDeleteChunkKeys() const; @@ -1091,6 +1092,7 @@ class Gc GcPhaseSink phase_sink; /// See `setStopSignal`. Empty: the intake is never stopped. std::function stop_signal; + bool round_stop_observed = false; UInt128 gc_id{}; /// this leader's identity (random u128, never 0) /// Every round-engine log line goes through this logger (see the constructor's `log_` doc /// comment) so multi-disk processes can attribute GC logs to the disk/srid that produced them. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp index 857acd6ad131a..c3faf732d4515 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcReadAhead.cpp @@ -1,7 +1,11 @@ #include +#include #include +#include +#include #include +#include #include #include @@ -17,6 +21,21 @@ namespace ProfileEvents namespace DB::Cas { +namespace +{ + +/// Runs `fn` in `group` and leaves it on return or unwind, before the caller publishes the answer: the round may end its +/// query once it takes the answer. +template +auto runInGroup(const ThreadGroupPtr & group, Fn && fn) +{ + ThreadGroupSwitcher switcher(group, ThreadName::UNKNOWN); + throwUnlessInThreadGroup(group, "CAS GC read-ahead worker"); + return fn(); +} + +} + GcReadAhead::GcReadAhead(CasOperation & op_, CasRequests & requests_, ThreadPool & pool_, size_t concurrency_) : op(op_), requests(requests_), pool(pool_), concurrency(concurrency_), generation(op_.generation()) { @@ -54,18 +73,25 @@ void GcReadAhead::hint(Slots & slots, const String & key, Request request, Re slots.emplace(key, slot); try { - pool.scheduleOrThrowOnError([slot, key, requests_ptr = &requests, gen = generation, request] + /// The worker joins a manual round's query, so the query's stop vetoes the worker's retry of a failed request. + /// A scheduled round has no query group, and the switch does nothing. + pool.scheduleOrThrowOnError([slot, key, requests_ptr = &requests, gen = generation, request, + group = CurrentThread::getGroup()] { try { - CasOperation worker = requests_ptr->resume(gen); - slot->result = request(worker, key); - slot->promise.set_value(); + slot->result = runInGroup(group, [&] + { + CasOperation worker = requests_ptr->resume(gen); + return request(worker, key); + }); } catch (...) { slot->promise.set_exception(std::current_exception()); + return; } + slot->promise.set_value(); }); } catch (...) @@ -193,7 +219,8 @@ std::function GcReadAhead::startCreate(std::function>(); - auto job = [promise, fn = std::move(request), requests_ptr = &requests, gen = generation, failure = create_failure] + auto job = [promise, fn = std::move(request), requests_ptr = &requests, gen = generation, failure = create_failure, + group = CurrentThread::getGroup()] { if (failure->failed.load()) { @@ -201,21 +228,28 @@ std::function GcReadAhead::startCreate(std::functionset_exception(failure->first); return; } + IntentCreateResult answer; try { - CasOperation worker = requests_ptr->resume(gen); - promise->set_value(fn(worker)); + answer = runInGroup(group, [&] + { + CasOperation worker = requests_ptr->resume(gen); + return fn(worker); + }); } catch (...) { + const auto error = std::current_exception(); { std::lock_guard lock(failure->mutex); if (!failure->first) - failure->first = std::current_exception(); + failure->first = error; } failure->failed.store(true); - promise->set_exception(std::current_exception()); + promise->set_exception(error); + return; } + promise->set_value(std::move(answer)); }; const uint64_t id = next_create++; /// Registered before the worker exists, so the destructor waits for every worker that was scheduled. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp index 6a057b0156f63..a618e257fcac2 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -20,6 +21,7 @@ namespace DB::ErrorCodes extern const int NETWORK_ERROR; extern const int ABORTED; extern const int TIMEOUT_EXCEEDED; + extern const int QUERY_WAS_CANCELLED; extern const int SOCKET_TIMEOUT; extern const int MEMORY_LIMIT_EXCEEDED; extern const int FAULT_INJECTED; @@ -344,11 +346,16 @@ Cas::RoundReport CasGcScheduler::runRoundLogged(Cas::Gc & round_gc, GcRoundLogRe catch (...) { fin.error_code = getCurrentExceptionCode(); - /// Non-transient first, so a bug that coincides with a restart is never masked; then the - /// teardown flag, the only witness of a refused teardown fence (see `Outcome::Stopped`). - fin.outcome = !isTransientGcRoundError(fin.error_code) ? Rec::Outcome::Failed - : store->teardownBegun() ? Rec::Outcome::Stopped - : Rec::Outcome::Aborted; + /// A stopped query ends a manual round with its verdict or with a transient code it caused, such as a + /// sent write left unresolved. Scheduler stops use the round's recorded observation. Non-transient before + /// the stop and teardown flags, so a bug that coincides with a stop or restart is never masked; the + /// teardown flag is the only witness of a refused teardown fence (see `Outcome::Stopped`). + const bool query_stopped = fin.error_code == ErrorCodes::QUERY_WAS_CANCELLED + || (isTransientGcRoundError(fin.error_code) && Cas::queryStopRequested()); + fin.outcome = query_stopped ? Rec::Outcome::Stopped + : !isTransientGcRoundError(fin.error_code) ? Rec::Outcome::Failed + : store->teardownBegun() || round_gc.roundStopObserved() ? Rec::Outcome::Stopped + : Rec::Outcome::Aborted; fin.error = getCurrentExceptionMessage(false); fill_counters(rep); fin.duration_ms = std::chrono::duration_cast( @@ -415,6 +422,8 @@ void CasGcScheduler::loop() return; if (before_tick_lock_hook_for_test) before_tick_lock_hook_for_test(); + /// Read under the round mutex: a manual round resets the observation as soon as the mutex is free. + bool round_stopped_by_scheduler = false; try { /// LOW/benign: if stop() flips `scheduler_state` while we're blocked here (a concurrent manual @@ -445,6 +454,9 @@ void CasGcScheduler::loop() if (store->teardownBegun() && isTransientGcRoundError(getCurrentExceptionCode())) LOG_INFO(log, "CA GC cleanup of this mount's own `Creating` rows stopped by the disk's teardown: {}", getCurrentExceptionMessage(false)); + else if (stopRequested() && isTransientGcRoundError(getCurrentExceptionCode())) + LOG_INFO(log, "CA GC cleanup of this mount's own `Creating` rows stopped by the scheduler's stop: {}", + getCurrentExceptionMessage(false)); else tryLogCurrentException(log, "CA GC cleanup of this mount's own `Creating` rows failed (will retry next tick)"); } @@ -467,7 +479,18 @@ void CasGcScheduler::loop() /// Only the background round: a manual round runs on a stopped scheduler too. gc.setStopSignal(stop_requested); SCOPE_EXIT({ gc.setStopSignal({}); }); - const Cas::RoundReport report = runRoundLogged(gc, GcRoundLogRecord::Trigger::Scheduled, [this] { onLeaseAcquired(); }); + const Cas::RoundReport report = [&] + { + try + { + return runRoundLogged(gc, GcRoundLogRecord::Trigger::Scheduled, [this] { onLeaseAcquired(); }); + } + catch (...) + { + round_stopped_by_scheduler = gc.roundStopObserved(); + throw; + } + }(); i_am_leader.store(report.acquired_lease, std::memory_order_relaxed); if (report.acquired_lease) { @@ -503,6 +526,8 @@ void CasGcScheduler::loop() } catch (...) { + if (tick_failure_hook_for_test) + tick_failure_hook_for_test(); if (store->teardownBegun() && isTransientGcRoundError(getCurrentExceptionCode())) { /// The disk is being torn down and the round was cut at its next request: expected, @@ -510,6 +535,12 @@ void CasGcScheduler::loop() LOG_INFO(log, "CA GC round stopped by the disk's teardown: {}", getCurrentExceptionMessage(false)); continue; } + if (round_stopped_by_scheduler && isTransientGcRoundError(getCurrentExceptionCode())) + { + /// `SYSTEM CAS GC STOP` ended the round, as asked; `runRoundLogged` recorded it as `Stopped`. + LOG_INFO(log, "CA GC round stopped by the scheduler's stop: {}", getCurrentExceptionMessage(false)); + continue; + } /// Idempotent round - the next tick retries; failures must never kill the pacing thread. /// runRoundLogged already emitted the classified (Aborted/Failed) Finish row before rethrowing. /// diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h index 4eb8381146f7f..b788e6ffb6aa8 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasGcScheduler.h @@ -33,7 +33,9 @@ struct GcRoundLogRecord /// nothing durable is wrong. `Stopped`: the same transient class, observed after the pool's /// teardown began -- a correlation, not a cause: the engine reports a refused teardown fence /// exactly like a lost mount fence, so the flag is the only witness, and the row says so honestly - /// rather than reading a clean restart as a backend incident. `Failed` is reserved for everything + /// rather than reading a clean restart as a backend incident. `Stopped` also names a round that ended + /// at a scheduler stop it observed itself (`Gc::roundStopObserved`), and a manual round that ended with + /// `QUERY_WAS_CANCELLED` or with a transient code while its query was stopped. `Failed` is reserved for everything /// else (a logic error, corrupted data, an unclassified code): fail-closed, an unrecognised /// failure reads as real -- during a teardown too. enum class Outcome { Unknown, Success, NotALeader, Failed, Deferred, Aborted, Stopped }; @@ -181,6 +183,10 @@ class CasGcScheduler /// Set it before `start`. void setBeforeTickLockHookForTest(std::function hook) { before_tick_lock_hook_for_test = std::move(hook); } + /// Runs `hook` on the round worker when a tick fails, after the round mutex is released and before the + /// failure is logged. Set it before `start`. + void setTickFailureHookForTest(std::function hook) { tick_failure_hook_for_test = std::move(hook); } + private: enum class SchedulerState { @@ -259,6 +265,8 @@ class CasGcScheduler std::condition_variable terminal_exit_cv; /// See `setBeforeTickLockHookForTest`. Empty in production. std::function before_tick_lock_hook_for_test; + /// See `setTickFailureHookForTest`. Empty in production. + std::function tick_failure_hook_for_test; /// Cumulative condemned entries minus exact-token deletes completed by this scheduler while it /// led. It is an approximate health gauge, not durable GC state. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp index 0a8857f714799..a8fd3d48f0241 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasNamespaceJanitor.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -76,9 +77,16 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven } catch (...) { - if (first_page_of_pass) - (void)casGcMaintenanceState(op, layout, progress.etag, GcMaintenanceState{}, Retry::once()); - throw; + /// A stopped query's failed `LIST` keeps the scan's progress: the reset is optional, and the stop vetoed + /// every further request. + if (!first_page_of_pass || queryStopRequested()) + throw; + const std::exception_ptr list_failure = std::current_exception(); + WriteResult reset = casGcMaintenanceState(op, layout, progress.etag, GcMaintenanceState{}, Retry::once()); + /// A reset that may still land outranks the listing error. + if (const auto * gave_up = std::get_if(&reset); gave_up && gave_up->why == GaveUp::Why::Unresolved && gave_up->sent_any) + (void)orThrow(std::move(reset), "CAS GC janitor cursor reset after a failed LIST"); + std::rethrow_exception(list_failure); } result.pages = 1; result.keys = page.keys.size(); @@ -105,6 +113,8 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven /// themselves prevent progress. bool page_decided = !ambiguous && !suppress_deletes; std::vector dead_stream_keys; + /// A request that failed for a stopped query ends the page with that failure, unpublished. + std::exception_ptr stopped_query_failure; for (const ListedKey & listed : page.keys) { @@ -164,6 +174,11 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven ++result.leaked; result.anomalies.push_back( "leaked dead-life object '" + listed.key + "': exact HEAD failed: " + e.what()); + if (queryStopRequested()) + { + stopped_query_failure = std::current_exception(); + break; + } continue; } } @@ -183,8 +198,15 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven ++result.leaked; result.anomalies.push_back( "leaked dead-life object '" + listed.key + "': exact delete failed: " + e.what()); + if (queryStopRequested()) + { + stopped_query_failure = std::current_exception(); + break; + } } } + if (stopped_query_failure) + std::rethrow_exception(stopped_query_failure); if (page_decided && !dead_stream_keys.empty() && op.admitted()) remove_write_once_keys(op, dead_stream_keys, result); @@ -199,21 +221,30 @@ NamespaceJanitorResult NamespaceJanitor::runOnePage(bool suppress_deletes, Liven if (page_decided) { const GcMaintenanceState next{.janitor_cursor = page.next_cursor}; + std::optional outcome; try { - const WriteResult outcome = casGcMaintenanceState(op, layout, progress.etag, next, Retry::standard()); - if (std::holds_alternative(outcome) || std::holds_alternative(outcome)) - result.anomalies.push_back("cursor publication did not commit"); - else if (std::holds_alternative(outcome)) - { - published = true; - result.more = result.deleted > 0 && !(cursor.empty() && page.next_cursor.empty()); - } + outcome = casGcMaintenanceState(op, layout, progress.etag, next, Retry::standard()); } catch (const std::exception & e) { + if (queryStopRequested()) + throw; result.anomalies.push_back("cursor publication failed: " + String(e.what())); } + /// A stopped query's caller must learn that the cursor write may still land, or that the store refused it. + const auto * gave_up = outcome ? std::get_if(&*outcome) : nullptr; + const bool unresolved = gave_up && gave_up->why == GaveUp::Why::Unresolved && gave_up->sent_any; + const bool refused = outcome && std::holds_alternative(*outcome); + if ((unresolved || refused) && queryStopRequested()) + (void)orThrow(std::move(*outcome), "CAS GC janitor cursor publication"); + if (outcome && (std::holds_alternative(*outcome) || std::holds_alternative(*outcome))) + result.anomalies.push_back("cursor publication did not commit"); + else if (outcome && std::holds_alternative(*outcome)) + { + published = true; + result.more = result.deleted > 0 && !(cursor.empty() && page.next_cursor.empty()); + } } /// An unpublished page is listed again, so its failed keys are not leaked yet. if (!published) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp index 0611bd15ad43e..525ee36411b26 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -636,6 +637,8 @@ uint64_t sweepNamespace(Pool & store, const RootNamespace & ns, const BuildPrefi } catch (const Exception & e) { + /// Skipped with a warning, a stopped owner's failure would let the drain go on after the stop. + rethrowIfStoppedOwnersFailure(); LOG_WARNING(getLogger("CasOrphanManifestSweep"), "CAS orphan sweep: namespace {} protection view unavailable ({}); skipping its deletions", ns.string(), e.message()); @@ -653,6 +656,8 @@ uint64_t sweepNamespace(Pool & store, const RootNamespace & ns, const BuildPrefi uint64_t deleted = 0; op.forEachListedKey(prefix_key, [&](const ListedKey & listed) { + throwIfQueryStopped(); + throwIfBackgroundStopped(); if (protection.active.contains(listed.key)) return true; /// owned by a committed or precommit owner — never sweep @@ -676,7 +681,7 @@ uint64_t sweepNamespace(Pool & store, const RootNamespace & ns, const BuildPrefi /// already reclaimed it" race, not a failure. A THROWN exception (a transient backend hiccup) /// is the one thing `warnings` changes: opted-in (non-null), it is recorded and the sweep moves /// to the next key; opted-out (nullptr, every pre-existing caller), it propagates exactly as - /// before (fail-close). + /// before (fail-close). A failure after an owner stopped propagates either way. try { const std::optional head = op.head(listed.key, Retry::standard()); @@ -687,6 +692,7 @@ uint64_t sweepNamespace(Pool & store, const RootNamespace & ns, const BuildPrefi } catch (...) { + rethrowIfStoppedOwnersFailure(); if (!warnings) throw; warnings->push_back("CAS orphan sweep: " + listed.key + " delete failed: " diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h index a6b12402eb416..aea312ffb55f3 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CasOrphanManifestSweep.h @@ -189,7 +189,8 @@ struct ManifestSweepResult /// below) also pushes a "cannot confirm emptiness" warning, not just a `LOG_WARNING`. `warnings == /// nullptr` (the default, every pre-existing caller) preserves the original behaviour exactly: a /// per-key failure propagates as an exception (fail-close default), and the protection-view skip is -/// log-only. `Gone`/`Mismatch` delete outcomes stay silently spared either way — those are the +/// log-only. A stopped owner ends the sweep at the next key with its verdict, and a failure after the stop propagates +/// either way. `Gone`/`Mismatch` delete outcomes stay silently spared either way — those are the /// normal "a fresh owner reclaimed it" race the periodic sweep expects, not a failure to warn about. /// This direct decommission path relies on the caller's held server-root claim/fence: while that claim /// is held, a same-server-root rebirth cannot become live between its catalog cut and exact-token delete. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.cpp index 090650a1a68bf..95fea3f15ee2f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -39,6 +40,7 @@ bool CatalogLifecycleReconciler::isCreatorTerminal(const CreatorFence & creator) const auto [it, inserted] = creator_slots.try_emplace({creator.server_root_id, creator.writer_epoch}); if (!inserted) return it->second == CreatorSlotStatus::Terminal; + throwIfBackgroundStopped(); try { it->second = probe_creator_slot(creator); @@ -47,6 +49,7 @@ bool CatalogLifecycleReconciler::isCreatorTerminal(const CreatorFence & creator) { if (e.code() == ErrorCodes::LOGICAL_ERROR) throw; + rethrowIfStoppedOwnersFailure(); /// A deposed leader's read fails too; the drain's own verdict reports that, not this creator. if (op.admitted()) LOG_WARNING(getLogger("CatalogLifecycleReconciler"), @@ -91,6 +94,7 @@ std::optional CatalogLifecycleReconciler::selectEligible( { for (const CatalogEntry & entry : catalog.catalog.entries) { + throwIfQueryStopped(); if (entry.state == NsState::Creating) { /// The probe reads the creator's mount slot, which a deposed leader may not do; the verdict @@ -141,6 +145,8 @@ CatalogLifecycleReconcileResult CatalogLifecycleReconciler::reconcile( for (;;) { + throwIfQueryStopped(); + throwIfBackgroundStopped(); const std::optional eligible = selectEligible(catalog); if (!eligible) { diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.h index 2221c7957b36e..709779447eb9c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Gc/CatalogLifecycleReconciler.h @@ -58,7 +58,7 @@ class CatalogLifecycleReconciler /// every erase is authorised by a reading taken in its own attempt, and it is run once more before /// the drain-complete verdict, which would otherwise report from the reading its last erase left. /// It is a refresh, not a verdict: the verdict stays `op.admitted()`. Each call receives the policy that - /// bounds its reads: a cancel's own frozen policy inside the catalog lane, `Retry::standard` elsewhere. + /// bounds its reads: the cancel's policy inside the catalog lane, `Retry::standard` elsewhere. /// /// `before_erase` is called with each `Removing` life before its first erase attempt, so the caller /// can record the retirement while the row still exists; the erase may not follow. A `Creating` life diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp index 3c8f4e4542bc9..a4497837b0b86 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -256,6 +257,9 @@ std::shared_ptr CachedPartFolderAccess::buildView( if (freshness != Freshness::CachedForLoad) return PartFolderView::make(key, resolved, store->readManifestShared(resolved.manifest_id)); + /// A cold build's leader stopped: its followers build again rather than share the leader's verdict. + struct LeaderStopped {}; + const String cache_key = key.cacheKey(); /// Readers that resolved different manifests of one ref must not share a build. const String build_key = cache_key + '\0' + resolved.manifest_id.root_namespace.string() + '\0' @@ -287,11 +291,15 @@ std::shared_ptr CachedPartFolderAccess::buildView( { return future.get(); /// Rethrows the leader's exception, if any. } + catch (const LeaderStopped &) + { + continue; + } catch (const std::exception & e) { /// The leader ran out of its own query's memory, which says nothing about this query's budget. if (!isMemoryLimitExceeded(e)) - throw; + rethrowOwnCopy(std::current_exception()); continue; } } @@ -311,8 +319,9 @@ std::shared_ptr CachedPartFolderAccess::buildView( catch (...) { retire(); - promise.set_exception(std::current_exception()); - throw; + /// The followers copy the published failure, so the leader leaves it untouched and throws its own copy. + promise.set_exception(ownerStopRequested() ? std::make_exception_ptr(LeaderStopped{}) : std::current_exception()); + rethrowOwnCopy(std::current_exception()); } promise.set_value(view); retire(); @@ -814,6 +823,11 @@ void CachedPartFolderAccess::dropRefIfPresent(const PartRefKey & key) { if (e.code() != ErrorCodes::FILE_DOESNT_EXIST) throw; + /// A stopped background owner's miss is its verdict. A query's stored cause is no miss; a real one is. + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(stop); + if (isQueryStoredCause(std::current_exception())) + throw; eraseView(key); return; /// Raced away between the gate and dropRef; nothing was actually dropped here. } diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.h index 2f990d088e927..5a5562818faaf 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Parts/PartFolderAccess.h @@ -323,7 +323,8 @@ class CachedPartFolderAccess /// committed map alone could be a drop that is durable but not yet applied. Reads the pinned table only, then /// reads the mount slot when the ledger confirms. Anything but `Yes` is a refusal: `No` when the source is /// not the current binding, `Unknown` when it cannot be shown to be before the request deadline. A transient - /// transport failure of the slot read is reissued until that deadline; any other failure propagates at once. + /// transport failure of the slot read is reissued until the end of the read's own request window; + /// any other failure propagates at once. /// Call it with no ledger lock held. ConfirmAnswer confirmCopySource(const CopySource & source) const; /// Moves a committed ref by publishing the source entries at `dst` and then dropping `src` only while it still diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp index ecc586c4454e8..8f0f4ec4f87ca 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -80,8 +81,8 @@ bool readBlobIntent(CasOperation & op, const Layout & layout, const BlobRef & re } catch (Exception & e) { - e.addMessage("while reading the deletion intent `{}`; a writer needs GET and LIST on `{}`, and a store that denies " - "LIST answers 403 for an absent intent", key, layout.blobIntentsPrefix()); + addMessageUnlessQueryStoredCause(e, fmt::format("while reading the deletion intent `{}`; a writer needs GET and LIST on `{}`, " + "and a store that denies LIST answers 403 for an absent intent", key, layout.blobIntentsPrefix())); throw; } } @@ -122,6 +123,22 @@ void recordFailedPublicationAttempt( LOG_WARNING(log, "Publication of CAS blob {} ({}) failed, attempt {} of {}: {}", key, transport_name, attempt + 1, max_attempts, error); } +/// The failure that a stopped query's veto of the next publication ends with. A credential refusal becomes retry-later +/// carrying it, so it does not read as damage. +[[noreturn]] void rethrowVetoedPublicationFailure(const String & key, const std::exception_ptr & failure) +{ + try + { + std::rethrow_exception(failure); + } + catch (const std::exception & e) + { + if (isRefreshableCredentialError(e) && !isQueryStoredCause(failure)) + detail::throwVetoedCredentialRetry("publish", key, e); + throw; + } +} + bool isDeterministicBlobPublicationFailure(const std::exception & error) { /// A refused write, EXCEPT the class a fresh credential fixes: the engine refreshes once before it @@ -239,6 +256,16 @@ void PartWriteTxn::requireAlive() const "the mount was fenced out and self-remounted; restart the build", epoch, live)); } +void PartWriteTxn::requireAdoptable(std::string_view where) const +{ + requireAlive(); + throwIfBackgroundStopped(); + if (!store->mountRequests().resume(txn_generation).admitted()) + throwCasTransientUnavailable( + fmt::format("PartWriteTxn::{}", where), + "the mount no longer admits the generation this build began under, so its upload results are not adopted"); +} + PutBlobResult PartWriteTxn::putBlob(const BlobRef & ref, BlobSource source) { /// Serial API preserved for existing callers: run the transaction-detached primitive, then fold its @@ -248,6 +275,9 @@ PutBlobResult PartWriteTxn::putBlob(const BlobRef & ref, BlobSource source) /// the request's `declared_size` mirrors it. const uint64_t declared_size = source.size; const BlobUploadResult r = uploadBlobDetached(BlobUploadRequest{ref, std::move(source), declared_size}); + if (adoption_hook_for_test) + adoption_hook_for_test(1); + requireAdoptable("putBlob"); deps.insert_or_assign(r.ref, r.dep); return PutBlobResult{r.ref, r.dep.size}; } @@ -284,7 +314,7 @@ void PartWriteTxn::mergeBlobUploadResults(std::span resu /// Build-and-swap: apply every result into a COPY of the live `deps`. The live member is touched /// ONLY by the final `swap` below, which runs after every result has applied -- so a mid-loop - /// exception (a `bad_alloc` from map-node allocation, or one injected by `setMergeHookForTest`'s + /// exception (a `bad_alloc` from map-node allocation, or one injected by `setAdoptionHookForTest`'s /// hook) leaves `deps` byte-for-byte as it was before this call. Applying an already-validated /// duplicate a second time is idempotent (identical value, same key). std::map candidate = deps; @@ -293,9 +323,10 @@ void PartWriteTxn::mergeBlobUploadResults(std::span resu { candidate.insert_or_assign(r.ref, r.dep); ++applied; - if (merge_hook_for_test) - merge_hook_for_test(applied); + if (adoption_hook_for_test) + adoption_hook_for_test(applied); } + requireAdoptable("mergeBlobUploadResults"); deps.swap(candidate); } @@ -323,17 +354,6 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// a dependency under an incarnation the precommit never saw. The build's own facts -- cancellation /// and a superseded writer epoch -- stay in `requireAlive`, where each states which one refused. CasOperation op = store->mountRequests().resume(txn_generation); - /// ONE bound for the whole publication loop, frozen before it starts: every HEAD and intent read - /// below shares this deadline, so a body whose publication keeps coming back ambiguous is refused - /// as retry-later inside one standard window instead of spending a fresh window per verb across - /// eight iterations. The paced retry is a bare sleep that does not consult the deadline, so the - /// loop can sleep one backoff (at most 5 s) past it before the next verb refuses to start. The - /// attempt cap below is the secondary bound. - const Retry policy = op.freeze(Retry::standard()); - /// The unrepeatable publication, under the SAME bound: the engine may never reissue an envelope - /// (see the publication call below), but the loop's deadline still governs whether one may start. - const Retry publication_policy = policy.asSingleAttempt(); - const BlobRef & ref = req.ref; const BlobSource & source = req.source; const String key = store->layout().blobKey(ref); @@ -366,9 +386,10 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) }; constexpr int max_publication_attempts = 8; - /// Every exit by exception after a failed attempt gave up on the blob, the attempt cap and the - /// loop's deadline alike. + /// Every exit by exception after a failed attempt gave up on the blob. int failed_attempts = 0; + /// The latest failed publication: what a query stopped before the next one ends with. + std::exception_ptr last_failure; const int exceptions_at_entry = std::uncaught_exceptions(); SCOPE_EXIT({ if (failed_attempts > 0 && std::uncaught_exceptions() > exceptions_at_entry) @@ -380,10 +401,11 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// Pace the reissues the way the request engine paces its own, and through the engine's own /// clock: an ambiguous publication is most often a store under load, and a large body /// republished eight times back to back is what makes that worse. After `requireAlive`, so a - /// cancelled or superseded build fails closed instead of spending a backoff first. - if (attempt > 0) - op.pause(Retry::backoff(attempt)); - const std::optional present = op.head(key, policy); + /// cancelled or superseded build fails closed instead of spending a backoff first. A query stopped in the + /// pause ends the upload with the failed publication's own error. + if (attempt > 0 && !sleepUnlessQueryStops(Retry::backoff(attempt), [&op](uint64_t ms) { op.sleepFor(ms); })) + rethrowVetoedPublicationFailure(key, last_failure); + const std::optional present = op.head(key, Retry::standard()); BlobPublicationReason reason = BlobPublicationReason::Absent; if (present) @@ -409,7 +431,7 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// Sent after this `HEAD` answered. A 404 does not prove no round condemned this incarnation: a transition /// deletes the old intent after condemning. Adopting is safe because the edge was durable before the /// `HEAD`, so the next destructive cut counts it. - if (readBlobIntent(op, store->layout(), ref, *identity, policy)) + if (readBlobIntent(op, store->layout(), ref, *identity, Retry::standard())) { reason = BlobPublicationReason::IntentPresent; ProfileEvents::increment(ProfileEvents::CASBlobReuseIntentPresent); @@ -456,6 +478,11 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) } } + /// A stop before a publication ends the upload: with the previous publication's failure if there is one. + if (!last_failure) + throwIfQueryStopped(); + else if (queryStopRequested()) + rethrowVetoedPublicationFailure(key, last_failure); const bool first_publication = source.beginPublication(); BlobPublicationTransport transport; @@ -488,36 +515,33 @@ BlobUploadResult PartWriteTxn::ensureBlobPresent(const BlobUploadRequest & req) /// each iteration of this loop builds one. The verbatim staged copy is additionally /// once-only per staging object: `beginPublication` spends a flag that the caller shares /// among every source over that object. - op.publish(BlobPublishRequest{key, std::move(publication)}, publication_policy); + op.publish(BlobPublishRequest{key, std::move(publication)}, Retry::once()); } - catch (const std::exception & error) + catch (...) { + /// A stopped owner's failure is no store answer and is not retried: a landed body stays debris, never adopted. + /// The background verdict first; a query's veto converts a credential refusal as the pause does. + if (auto stop = backgroundStopRequested()) + std::rethrow_exception(std::move(stop)); + if (queryStopRequested()) + rethrowVetoedPublicationFailure(key, std::current_exception()); /// A publication this build is no longer admitted to make is not an ambiguity to retry: /// every further request of this operation refuses the same way. - if (isDeterministicBlobPublicationFailure(error) || !op.admitted()) + if (const auto * error = current_exception_cast(); + error && (isDeterministicBlobPublicationFailure(*error) || !op.admitted())) throw; ++failed_attempts; - recordFailedPublicationAttempt(key, transport, attempt, max_publication_attempts, error.what()); + last_failure = std::current_exception(); + /// `Poco::Exception::what` is only the class name; the message carries the cause. + const String message = getCurrentExceptionMessage(/*with_stacktrace=*/false); + recordFailedPublicationAttempt(key, transport, attempt, max_publication_attempts, message); if (attempt + 1 == max_publication_attempts) throwCasWriteRetryLater(fmt::format( "PartWriteTxn::ensureBlobPresent: publication of {} remained ambiguous after {} " "attempts: {}", key, max_publication_attempts, - error.what())); - continue; - } - catch (...) - { - ++failed_attempts; - recordFailedPublicationAttempt( - key, transport, attempt, max_publication_attempts, getCurrentExceptionMessage(/*with_stacktrace=*/false)); - if (attempt + 1 == max_publication_attempts) - throwCasWriteRetryLater(fmt::format( - "PartWriteTxn::ensureBlobPresent: publication of {} remained ambiguous after {} " - "attempts", - key, - max_publication_attempts)); + message)); continue; } @@ -600,11 +624,17 @@ String describeManifestPutGiveUp(const GaveUp & gave_up) if (lease) return "was not sent: the mount lease has too little time left, so writes are paused"; return "was not sent: the request window ran out before the first attempt"; + case GaveUp::Why::Attempts: + throw Exception(ErrorCodes::LOGICAL_ERROR, "A single part write is never capped by a decision count"); case GaveUp::Why::Unresolved: - if (gave_up.sent_any) + if (gave_up.sent_any && std::holds_alternative(gave_up.last_seen)) return fmt::format( "is UNCERTAIN: {} attempt(s) sent and the resolving read did not complete ({}); the body may have landed", gave_up.attempts_sent, detail::renderObservation(gave_up.last_seen)); + if (gave_up.sent_any) + return fmt::format( + "is UNCERTAIN: {} attempt(s) sent and not sent again after the resolving read found {}; the body may " + "have landed", gave_up.attempts_sent, detail::renderObservation(gave_up.last_seen)); return fmt::format( "was not sent: a read of the current object did not complete ({})", detail::renderObservation(gave_up.last_seen)); @@ -781,62 +811,79 @@ void PartWriteTxn::precommitAdd(const RootNamespace & target_ns, const String & /// live precommit with no cleanup owner and no body. Same discipline, and same reason, as the ref /// lane's preconstructed wedge. The three fields are plain assignments of already-materialized /// values, so this cannot throw between the record and the append. + /// A refusal restores what an earlier invocation of this transaction recorded, including its duty. + RootNamespace previous_target_ns = precommit_target_ns; + String previous_final_ref = precommit_final_ref; + const ManifestRef previous_manifest = precommit_manifest; + const PrecommitState previous_state = precommit_state; precommit_target_ns = target_ns; precommit_final_ref = final_ref_name; precommit_manifest = id.ref; precommit_state = PrecommitState::Uncertain; - store->appendRefOps(target_ns, MutationScope::ref(final_ref_name), - /// Capture everything the closure reads BY VALUE (the `store` handle, target namespace, ref name, - /// and manifest id) rather than `[&]`: defense-in-depth so a closure that ever outlives this - /// stack frame (e.g. if the append lane stranded its item) never dereferences a dead stack. The - /// ref-lane leadership guard is the real fix; this makes the closure self-contained regardless. - [pool = store, target_ns, final_ref_name, id, id_staged_by_this_txn, txn_build_id = build_id](const RefTableState & state) -> std::vector - { - /// Idempotent re-add: the target ref is ALREADY committed to this EXACT manifest_ref (a - /// legitimate re-drive calling precommitAdd+promote again for content that is already - /// live -- see `promote`'s matching no-op guard). Nothing to append: re-adding a precommit - /// for an already-owned manifest would violate "no conflicting owner may name the same - /// manifest", which the state machine enforces for every OTHER case. - /// - /// A3 mint-tightening's enforcement lives HERE, gated on this SAME live-state read, rather - /// than unconditionally before the closure: a legitimate re-drive can be handed an id that - /// this exact `PartWriteTxn` object never staged (e.g. a fresh build re-precommitting - /// content a PRIOR, since-destroyed build already promoted -- `CasPromoteRepublish. - /// PromoteSameManifestIsIdempotent`). That case is not a fresh ownership grant: the manifest - /// is already `final_ref_name`'s live, currently-protected binding, so re-affirming it - /// creates no new ABA surface. Checking membership-or-committed-match atomically under the - /// SAME state read (rather than a separate pre-check against a possibly-stale resolve) is - /// what keeps this race-free: a snapshot taken before the closure could see "already - /// committed to id.ref" and let a later closure invocation append a fresh owner_transition - /// after a concurrent repoint moved the ref away from id.ref in between -- exactly the - /// re-ownership of a dropped identity this check exists to prevent. - if (const auto it = state.getCommitted().find(final_ref_name); - it != state.getCommitted().end() && it->second.manifest_ref == id.ref) - return {}; - if (!id_staged_by_this_txn) - throw Exception(ErrorCodes::LOGICAL_ERROR, - "precommitAdd: manifest '{}' was not staged by this transaction (build {}) and is not the current " - "committed manifest of ref '{}' in namespace '{}' -- refusing to re-own a foreign or previously-dropped identity", - manifestRefDebugString(id.ref), u128ToHex(txn_build_id), final_ref_name, target_ns.string()); - - std::vector ops; - if (state.getLifecycle() != RefLifecycle::Live) + try + { + store->appendRefOps(target_ns, MutationScope::ref(final_ref_name), + /// Capture everything the closure reads BY VALUE (the `store` handle, target namespace, ref name, + /// and manifest id) rather than `[&]`: defense-in-depth so a closure that ever outlives this + /// stack frame (e.g. if the append lane stranded its item) never dereferences a dead stack. The + /// ref-lane leadership guard is the real fix; this makes the closure self-contained regardless. + [pool = store, target_ns, final_ref_name, id, id_staged_by_this_txn, txn_build_id = build_id](const RefTableState & state) -> std::vector { - /// Reaching an empty runtime here means catalog resolution admitted a new life. A - /// predecessor still `Removing` was refused before recovery, so rebirth needs no - /// physical marker or empty-prefix proof. - RefOp birth; - birth.kind = RefOpKind::NamespaceBirth; - ops.push_back(birth); - } - RefOp add; - add.kind = RefOpKind::OwnerTransition; - add.new_binding = RefOwnerBinding{RefOwnerKind::Precommit, final_ref_name, id.ref}; - ops.push_back(add); - return ops; - }, - RootMutationOrigin::Writer, RootMutationKind::Precommit); + /// Idempotent re-add: the target ref is ALREADY committed to this EXACT manifest_ref (a + /// legitimate re-drive calling precommitAdd+promote again for content that is already + /// live -- see `promote`'s matching no-op guard). Nothing to append: re-adding a precommit + /// for an already-owned manifest would violate "no conflicting owner may name the same + /// manifest", which the state machine enforces for every OTHER case. + /// + /// A3 mint-tightening's enforcement lives HERE, gated on this SAME live-state read, rather + /// than unconditionally before the closure: a legitimate re-drive can be handed an id that + /// this exact `PartWriteTxn` object never staged (e.g. a fresh build re-precommitting + /// content a PRIOR, since-destroyed build already promoted -- `CasPromoteRepublish. + /// PromoteSameManifestIsIdempotent`). That case is not a fresh ownership grant: the manifest + /// is already `final_ref_name`'s live, currently-protected binding, so re-affirming it + /// creates no new ABA surface. Checking membership-or-committed-match atomically under the + /// SAME state read (rather than a separate pre-check against a possibly-stale resolve) is + /// what keeps this race-free: a snapshot taken before the closure could see "already + /// committed to id.ref" and let a later closure invocation append a fresh owner_transition + /// after a concurrent repoint moved the ref away from id.ref in between -- exactly the + /// re-ownership of a dropped identity this check exists to prevent. + if (const auto it = state.getCommitted().find(final_ref_name); + it != state.getCommitted().end() && it->second.manifest_ref == id.ref) + return {}; + if (!id_staged_by_this_txn) + throw Exception(ErrorCodes::LOGICAL_ERROR, + "precommitAdd: manifest '{}' was not staged by this transaction (build {}) and is not the current " + "committed manifest of ref '{}' in namespace '{}' -- refusing to re-own a foreign or previously-dropped identity", + manifestRefDebugString(id.ref), u128ToHex(txn_build_id), final_ref_name, target_ns.string()); + + std::vector ops; + if (state.getLifecycle() != RefLifecycle::Live) + { + /// Reaching an empty runtime here means catalog resolution admitted a new life. A + /// predecessor still `Removing` was refused before recovery, so rebirth needs no + /// physical marker or empty-prefix proof. + RefOp birth; + birth.kind = RefOpKind::NamespaceBirth; + ops.push_back(birth); + } + RefOp add; + add.kind = RefOpKind::OwnerTransition; + add.new_binding = RefOwnerBinding{RefOwnerKind::Precommit, final_ref_name, id.ref}; + ops.push_back(add); + return ops; + }, + RootMutationOrigin::Writer, RootMutationKind::Precommit); + } + catch (const RefAdmissionRefusedException &) + { + /// Refused before the lane queued the append: this invocation created no binding and owes no duty. + precommit_target_ns = std::move(previous_target_ns); + precommit_final_ref = std::move(previous_final_ref); + precommit_manifest = previous_manifest; + precommit_state = previous_state; + throw; + } /// The append returned: the precommit binding is durably this build's, so the duty settles from /// `Uncertain` to `Durable` and `ensureBlobPresent`'s materialization gate opens. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h index c6b0aeb75609d..2e026a87048c6 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPartWriteTxn.h @@ -177,18 +177,18 @@ class PartWriteTxn /// `BlobRef` must carry an identical dep record; a conflict -- most /// commonly a conflicting size -- means the fan-out's one-task-per-unique-ref invariant was /// violated) -- BEFORE any result is applied. Application then runs against a COPY of `deps` (a - /// "build"), so a mid-application exception (including one raised by `setMergeHookForTest`'s hook, or + /// "build"), so a mid-application exception (including one raised by `setAdoptionHookForTest`'s hook, or /// a `bad_alloc` from map-node allocation) never touches the live `deps`; the copy is committed by a /// single no-throw `swap` only after every result has applied. The build is therefore either fully /// merged or byte-for-byte untouched -- never partially merged. void mergeBlobUploadResults(std::span results); - /// Test-only fault-injection seam (inert in production): invoked after each result has applied to - /// the in-progress merge copy, with the count of results applied so far (1-based). A hook that - /// throws (e.g. to model a `bad_alloc` mid-merge) aborts `mergeBlobUploadResults` before its final - /// swap, so the live `deps` stays untouched -- the seam exists to prove that all-or-nothing property - /// under injected failure at every application point, not just the first or the last. - void setMergeHookForTest(std::function hook) { merge_hook_for_test = std::move(hook); } + /// Test-only fault-injection seam (inert in production), run before results are adopted into `deps` + /// with the count prepared so far (1-based): in `mergeBlobUploadResults` after each result has applied + /// to the merge copy, and in `putBlob` once after the upload. A hook that throws mid-merge aborts + /// `mergeBlobUploadResults` before its final swap, so the live `deps` stays untouched -- the seam + /// exists to prove that all-or-nothing property at every application point. + void setAdoptionHookForTest(std::function hook) { adoption_hook_for_test = std::move(hook); } /// Test-only: runs in `promote` after its liveness checks and before its append. Set before `promote`. void setPromoteBeforeAppendHookForTest(std::function hook) { promote_before_append_hook_for_test = std::move(hook); } @@ -362,6 +362,9 @@ class PartWriteTxn /// Reject operations after `abandon`, namespace cancellation, or writer-epoch fencing. These checks happen /// before backend work so a stale transaction cannot publish a new owner or stage more debris. void requireAlive() const; + /// Before an upload result enters `deps`: the build is alive, its owner has not stopped, and the mount + /// still admits the generation the build began under. + void requireAdoptable(std::string_view where) const; /// Best-effort exact-token delete of THIS build's staged `_manifests` debris; the precommit body (if /// any) is SKIPPED -- left for GC's delete-after-sealed-decrements. Never throws (the namespace-scoped orphan /// sweep is the durable backstop). Shared by the normal and the namespace-removal-cancelled `abandon` @@ -409,8 +412,8 @@ class PartWriteTxn std::map deps; /// dependencies recorded by this build (blobs only) - /// Backing state for `setMergeHookForTest`; empty (no-op) in production. - std::function merge_hook_for_test; + /// Backing state for `setAdoptionHookForTest`; empty (no-op) in production. + std::function adoption_hook_for_test; /// Backing state for `setPromoteBeforeAppendHookForTest`; empty in production. std::function promote_before_append_hook_for_test; }; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp index e7b054599ca19..e4cb097f195de 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -1288,7 +1289,7 @@ void Pool::cancelIdleOwnCreatingRows(const std::function & stop_requeste /// The pass keeps the mount fence but backs off on the open plane's sleep, which `beginTeardown` wakes; /// the mount plane's sleep would hold a scheduler join for a whole pause. ref_ledger.cancelIdleOwnCreatingRows( - [this] { return !teardownBegun(); }, [this](uint64_t ms) { gc_requests.pause(ms); }, stop_requested); + [this] { return !teardownBegun(); }, [this](uint64_t ms) { gc_requests.sleepFor(ms); }, stop_requested); } void Pool::beginTeardown() noexcept @@ -1872,14 +1873,24 @@ bool Pool::writerCleanupDutiesPending() const [](const auto & item) { return !item.second.pending.empty(); }); } +bool Pool::writerCleanupDrainingForTest(const RootNamespace & ns) const +{ + std::lock_guard lock(writer_cleanup_mutex); + const auto it = writer_cleanup_queues.find(ns); + return it != writer_cleanup_queues.end() && it->second.draining; +} + void Pool::drainWriterCleanupDuties(const RootNamespace & ns) { { std::unique_lock lock(writer_cleanup_mutex); - writer_cleanup_cv.wait(lock, [&] + Cas::waitStoppable(writer_cleanup_cv, lock, [&] { const auto it = writer_cleanup_queues.find(ns); - return it == writer_cleanup_queues.end() || !it->second.draining; + const bool ready = it == writer_cleanup_queues.end() || !it->second.draining; + if (!ready && writer_cleanup_wait_hook_for_test) + writer_cleanup_wait_hook_for_test(); + return ready; }); const auto it = writer_cleanup_queues.find(ns); @@ -1905,6 +1916,8 @@ void Pool::drainWriterCleanupDuties(const RootNamespace & ns) } duty = it->second.pending.front(); } + /// Before each duty, so a stop never falls between a settled duty and its retirement. + Cas::throwIfBackgroundStopped(); ref_ledger.appendRefOps( ns, @@ -2202,6 +2215,11 @@ void Pool::setRefRecoveryRetrySleepForTest( ref_ledger.setRefRecoveryRetrySleepForTest(std::move(sleep_fn)); } +void Pool::setRefRecoveryRetrySliceSleepForTest(std::function sleep_fn) +{ + ref_ledger.setRefRecoveryRetrySliceSleepForTest(std::move(sleep_fn)); +} + std::optional Pool::resolveRef(const RootNamespace & ns, const String & ref_name, bool allow_stale, ResolveAudit audit) { return ref_ledger.resolveRef(ns, ref_name, allow_stale, audit); @@ -2273,24 +2291,29 @@ ConfirmAnswer Pool::confirmPinnedRef(const CasRefLedger::TablePin & table, const /// Every pass repeats the ownership capture, the ledger snapshot and the slot read. The destination's reference is durable /// before the first pass and GC deletes a body only on an untouched zero of a complete cut, so a later full pass proves the /// same ownership overlap as an earlier one. An exact name and token may legitimately reappear after a move away and back. - const Retry slot_read_policy = Retry::standard().cappedAt(deadline_ms); + const Retry slot_read_policy = Retry::standard(); for (uint32_t pass = 1;; ++pass) { throwIfConfirmTornDown(ns, ref_name); const ConfirmVerdict verdict = confirmUnderSlot( ns, ref_name, [&] { return ref_ledger.confirmPinnedRef(table, ns, ref_name, manifest_ref, deadline_ms); }, slot_read_policy); - if (verdict.answer != ConfirmAnswer::Unknown || verdict.refusal == ConfirmVerdict::Refusal::OneWay - || ref_ledger.pinnedTableRetired(table, ns)) + if (verdict.answer != ConfirmAnswer::Unknown) + return verdict.answer; + /// A stopped background owner gets its own verdict instead of any `Unknown`, so `republishRef` never reads the + /// destination for it. + Cas::throwIfBackgroundStopped(); + if (verdict.refusal == ConfirmVerdict::Refusal::OneWay || ref_ledger.pinnedTableRetired(table, ns)) return verdict.answer; const uint64_t now_ms = bootMsNow(); if (now_ms >= deadline_ms) return verdict.answer; throwIfConfirmTornDown(ns, ref_name); - /// Teardown does not wake this pause, and no query cancellation reaches this layer. - mount_requests.pause(std::min(Retry::backoff(pass), deadline_ms - now_ms)); - /// A pass whose slot read could not finish by the deadline would fail on the read instead of refusing. - if (!mount_requests.admit().oneAttemptFitsBefore(deadline_ms)) + /// Teardown does not wake this pause; the owner is asked before and after it. + mount_requests.sleepFor(std::min(Retry::backoff(pass), deadline_ms - now_ms)); + Cas::throwIfBackgroundStopped(); + /// A pass starts only before the poll's end; a started pass finishes, its slot read binds its own window. + if (bootMsNow() >= deadline_ms) return verdict.answer; } } @@ -2328,7 +2351,9 @@ ConfirmVerdict Pool::confirmUnderSlot(const RootNamespace & ns, const String & r catch (...) { throwIfConfirmTornDown(ns, ref_name); - ProfileEvents::increment(ProfileEvents::CASRelinkConfirmRefusedSlotUnreadable); + /// The owner's verdict is not a slot that could not be read; the counter is diagnostic, so a race here goes uncounted. + if (!Cas::ownerStopRequested()) + ProfileEvents::increment(ProfileEvents::CASRelinkConfirmRefusedSlotUnreadable); throw; } /// A read that finished after teardown began answers for a mount that is going away. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h index ed020b7b3c1c6..0a326138d792f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasPool.h @@ -469,7 +469,7 @@ class Pool : public std::enable_shared_from_this void beginTeardown() noexcept; bool teardownBegun() const noexcept; /// The GC scheduler's per-tick cleanup of this mount's own idle `Creating` catalog rows; stops at teardown - /// or once `stop_requested` returns true. + /// or once `stop_requested` returns true, with `ABORTED` when that happens inside a cancel. void cancelIdleOwnCreatingRows(const std::function & stop_requested = {}); bool stopAndDrainDetachedWork(uint64_t deadline_ms); uint64_t detachedWorkInFlight() const; @@ -637,13 +637,15 @@ class Pool : public std::enable_shared_from_this /// throws, and the storage layer answers `Unknown`. Any other ledger answer issues no request. ConfirmAnswer confirmExactRef(const RootNamespace & ns, const String & ref_name, const ManifestRef & manifest_ref) const; /// The same gate for an in-process copy, on the table runtime `table` pinned when the source was resolved - /// (`CasRefLedger::confirmPinnedRef`). One deadline, the request window from the call's start, decides whether the - /// ledger waits for a held state lock again and bounds the mount-slot read, which reissues a transient transport failure until then; - /// any other failure propagates at once. One wait for the lock is not bounded. - /// A pass that answers `Unknown` is asked again, paced by `Retry::backoff`, until `Yes`, `No`, the deadline, a + /// (`CasRefLedger::confirmPinnedRef`). The poll's end, the request window from the call's start, decides whether the + /// ledger waits for a held state lock again and whether another pass starts. The mount-slot read of a pass binds its own + /// request window when it starts, and reissues a transient transport failure until that window ends; any other failure + /// propagates at once. + /// One wait for the lock is not bounded. + /// A pass that answers `Unknown` is asked again, paced by `Retry::backoff`, until `Yes`, `No`, the poll's end, a /// refusal of a state the pinned runtime cannot leave, or a pin that can never confirm - /// (`CasRefLedger::pinnedTableRetired`). No ledger lock is held between passes. Throws `ABORTED` once the pool's - /// teardown has begun. + /// (`CasRefLedger::pinnedTableRetired`). A started pass finishes, even past the poll's end. + /// No ledger lock is held between passes. Throws `ABORTED` once the pool's teardown has begun. ConfirmAnswer confirmPinnedRef(const CasRefLedger::TablePin & table, const RootNamespace & ns, const String & ref_name, const ManifestRef & manifest_ref) const; /// TEST SEAM: runs between the ownership capture and the ledger snapshot. @@ -1033,6 +1035,7 @@ class Pool : public std::enable_shared_from_this std::optional lastEpochSealForTest(const RootNamespace & ns); /// Test seam: this table's append lane state. RefLaneState laneStateForTest(const RootNamespace & ns); + CasRefLedger::RemovalFlagsForTest removalFlagsForTest(const RootNamespace & ns) { return ref_ledger.removalFlagsForTest(ns); } /// Whether this resident table still owes a stale-precommit sweep (armed by recovery; re-armed by a /// failed attempt; cleared permanently only by a verified-clean sweep). @@ -1081,6 +1084,11 @@ class Pool : public std::enable_shared_from_this /// the direct signal that a settlement failure retained its duty for retry, independent of any /// build-floor side effect that could have the same shape for an unrelated reason. bool writerCleanupDutiesPendingForTest() const { return writerCleanupDutiesPending(); } + /// Test seam: whether a caller is draining the writer cleanup duties of `ns`. + bool writerCleanupDrainingForTest(const RootNamespace & ns) const; + /// TEST SEAM: runs under the cleanup-duty mutex each time a caller finds another drainer and waits for it. + /// Must not take that mutex. Set only while no drain runs. + void setWriterCleanupWaitHookForTest(std::function hook) { writer_cleanup_wait_hook_for_test = std::move(hook); } /// Test-only hook: called by `flushRefBatch` /// right before it carves a batch, i.e. AFTER the table is already recovered -- the one otherwise @@ -1089,6 +1097,9 @@ class Pool : public std::enable_shared_from_this /// caller's item join `rt->pending` before the carve, forcing deterministic co-batching. void setRefPreCarveHookForTest(std::function hook) { ref_ledger.setRefPreCarveHookForTest(std::move(hook)); } + /// Test-only: fires on a queued ref-log follower at each evaluation of its wait condition. + void setRefFollowerWaitHookForTest(std::function hook) { ref_ledger.setRefFollowerWaitHookForTest(std::move(hook)); } + /// Test-only: pre-tenure fault seam for the append-lane leadership acquisition; forwards to /// `CasRefLedger::setRefPreTenureHookForTest` (see it for the baton-safety contract). void setRefPreTenureHookForTest(std::function hook) { ref_ledger.setRefPreTenureHookForTest(std::move(hook)); } @@ -1189,6 +1200,9 @@ class Pool : public std::enable_shared_from_this void setRefRecoveryRetrySleepForTest( std::function &)> sleep_fn); + /// Test-only: replace the single-slice sleep inside the default recovery retry delay. Same rule. + void setRefRecoveryRetrySliceSleepForTest(std::function sleep_fn); + /// Queue depth for the ref-append-lane tests (mirrors `shardQueuePendingForTest`): how many /// `appendRefOps` callers are enqueued for `ns` right now. size_t refQueuePendingForTest(const RootNamespace & ns) { return ref_ledger.refQueuePendingForTest(ns); } @@ -1377,6 +1391,8 @@ class Pool : public std::enable_shared_from_this /// pool_layout so it is constructed after every dependency it is injected with. CasMountRuntime mount_runtime; + /// TEST SEAM for `setWriterCleanupWaitHookForTest`. + std::function writer_cleanup_wait_hook_for_test = {}; /// TEST SEAM for `setConfirmAfterOwnershipCaptureHookForTest`; set only while no confirm runs. std::function confirm_after_ownership_capture_hook_for_test = {}; /// TEST SEAM for `setConfirmAfterLedgerSnapshotHookForTest`; set only while no confirm runs. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp index 2a2d0b3fe020a..5b64c56596c2f 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -137,23 +138,20 @@ struct CatalogFenceMovedMarker : std::exception {}; struct CatalogEntryMismatchMarker : std::exception {}; struct CatalogCreatorStillLiveMarker : std::exception {}; -/// Live-lock brake for the ONE loop below that is written by hand rather than driven by the engine: -/// the catalog is a single object mutated by every lifecycle transition of every namespace in the -/// pool, so persistent contention is a real, not theoretical, exit condition to plan for. -/// -/// It bounds ATTEMPTS, and is the SECONDARY bound: the loop freezes one `Retry` before it starts and -/// every verb of every iteration shares that absolute deadline, so wall-clock time is already bounded -/// by one standard window. This cap exists so a call that somehow converges on neither still ends. -constexpr size_t kMaxCatalogCasAttempts = 100; - /// Proven absence of the catalog, for a caller that takes it as an answer rather than as corruption. struct CatalogAbsentMarker : std::exception {}; +/// What `decide` threw, which `casUpdateImpl` delivers unchanged: a decision is not a sent write. +struct CatalogDecisionFailure : std::exception +{ + explicit CatalogDecisionFailure(std::exception_ptr error_) : error(std::move(error_)) {} + std::exception_ptr error; +}; + /// Shared body of `casUpdate`/`casAdmitEntry`. `encode` turns a freshly `mutate`d candidate into the /// bytes to write: the plain path just grammar-checks (`encodeRefCatalog`), the admitting path also /// runs both admission predicates (`checkCatalogAdmission`) first. A refused precondition re-runs -/// `mutate` against the resolve read's fresh body -- the one the pool's hot-key lane remembers and -/// the next hold starts from -- never re-encoding the stale candidate. +/// `mutate` against a fresh read, never re-encoding the stale candidate. RefCatalog casUpdateImpl( CasOperation & op, const Layout & layout, const std::function & mutate, @@ -161,70 +159,140 @@ RefCatalog casUpdateImpl( const Retry & policy = Retry::standard(), bool absence_is_an_answer = false) { const String key = layout.refCatalogKey(); + const String what = fmt::format("CAS ref catalog '{}' update", key); /// The candidate the LAST `decide` produced, which is the one the engine wrote: every earlier one /// belongs to an attempt whose precondition was refused. std::optional written; const auto decide = [&](const std::optional & current) -> std::optional { - /// Absence of the mandatory catalog is corruption, not a fresh bootstrap. Refusing here is - /// what stops any mutation from replacing every other namespace with a one-update catalog. - if (!current) + try { - if (absence_is_an_answer) - throw CatalogAbsentMarker{}; - throwMandatoryCatalogAbsent(key); + /// Absence of the mandatory catalog is corruption, not a fresh bootstrap. Refusing here is + /// what stops any mutation from replacing every other namespace with a one-update catalog. + if (!current) + { + if (absence_is_an_answer) + throw CatalogAbsentMarker{}; + throwMandatoryCatalogAbsent(key); + } + const RefCatalog durable = decodeRefCatalog(current->bytes); + CatalogLifeIndex(durable).throwIfAmbiguous("CAS ref catalog mutation"); + RefCatalog candidate = mutate(durable); + String bytes = encode(candidate); + written = std::move(candidate); + return bytes; + } + catch (...) + { + throw CatalogDecisionFailure(std::current_exception()); } - const RefCatalog durable = decodeRefCatalog(current->bytes); - CatalogLifeIndex(durable).throwIfAmbiguous("CAS ref catalog mutation"); - RefCatalog candidate = mutate(durable); - String bytes = encode(candidate); - written = std::move(candidate); - return bytes; }; - /// One hold at a time per pool on this key, from the pool's last known catalog when the lane holds - /// one. The loop is this function's: a `Conflict` is a lost race against another server (the lane - /// never conflicts with itself), repaid after the flat jitter, or after the growing schedule when - /// the conflict settled a transport fault. Under a single-attempt policy the first `Conflict` is - /// the answer, as the engine's own verb answers it. - const Retry frozen = op.freeze(policy); - /// Under `resend_unresolved = false` the engine returns an attempt whose fate is unknown instead of - /// resending its bytes, and this loop decides again on a fresh read. Attempt numbering continues, - /// so the next write is not a first attempt with the adaptive timeout again. - Retry attempt_policy = frozen; - uint32_t settled_faults = 0; - for (;;) - { - WriteResult result = op.hotKeys().submit(key, op, attempt_policy, decide); - /// A write decided on a cached body can be refused by a deletion; its settling read already proved it. - if (const auto * conflict = std::get_if(&result); - absence_is_an_answer && conflict && std::holds_alternative(conflict->seen)) - throw CatalogAbsentMarker{}; - if (const auto * unresolved = std::get_if(&result); - unresolved && unresolved->why == GaveUp::Why::Unresolved && unresolved->sent_any - && !frozen.resend_unresolved && !frozen.single_attempt) + /// Set once a submission sent a write whose outcome stayed unresolved. That write can still land, so every exit + /// below but a commit, the typed outcomes, a failed decision and a local fault reports it. + bool sent_unresolved = false; + try + { + /// One hold at a time per pool on this key, from the pool's last known catalog when the lane holds + /// one; the lane itself retries a clean loss on that cached catalog at once. The loop is this + /// function's: a `Conflict` is a lost race against another server (the lane never conflicts with + /// itself), repaid after `Retry::conflictBackoff` of the run of consecutive clean losses, or after the fault + /// schedule when the conflict settled a transport fault; the next submission reads after the pause. + /// Under a single-attempt policy the first `Conflict` is the answer, as the engine's own verb answers + /// it. Each request binds its own window, so the count of submissions is what ends a loop that keeps + /// losing; one submission may run `decide` twice on a cached catalog, so `decide` calls are not counted. + /// + /// Under `resend_unresolved = false` the engine returns an attempt whose fate is unknown instead of + /// resending its bytes, and this loop decides again on a fresh read. Attempt numbering continues, + /// so the next write is not a first attempt with the adaptive timeout again. + Retry attempt_policy = policy; + uint32_t settled_faults = 0; + uint32_t clean_losses = 0; + for (uint32_t submissions = 1;; ++submissions) { - attempt_policy.attempts_already_sent += unresolved->attempts_sent; - auto given_up = op.pauseBeforeRedecide(Retry::backoff(++settled_faults), *unresolved, frozen); - if (!given_up) + /// Every submission after the first follows a pause, so it reads rather than start from a body + /// another holder of this pool remembered during that pause. + if (submissions > 1) + throwIfBackgroundStopped(); + WriteResult result = op.hotKeys().submit(key, op, attempt_policy, decide, + submissions > 1 ? CasHotKeys::Start::Read : CasHotKeys::Start::CacheOrRead, + submissions < kCasMaxDecisions ? CasHotKeys::OnLoss::SubmitAgain : CasHotKeys::OnLoss::End); + if (std::holds_alternative(result)) + return std::move(*written); + + /// Every other final outcome ends the call here, so the cap below never meets an operation that must end. + const auto * conflict = std::get_if(&result); + const auto * gave_up = std::get_if(&result); + /// A write decided on a cached body can be refused by a deletion; its settling read already proved it. + if (absence_is_an_answer && conflict && std::holds_alternative(conflict->seen)) + throw CatalogAbsentMarker{}; + /// The fence can be lost in two places and both mean the same to a lifecycle caller: inside + /// `decide`, which throws the marker itself, and between two attempts, where the engine + /// notices it first and no further `decide` runs. Normalising the second onto the first is + /// what keeps "the fence moved" a returned outcome rather than an exception. + if (gave_up && gave_up->why == GaveUp::Why::FenceLost) + throw CatalogFenceMovedMarker{}; + + /// The only two reasons to submit again: another writer won the race, or the policy decides again + /// after a write whose outcome is unknown. + const bool lost_race = conflict && !conflict->observed_stop && !policy.single_attempt; + const bool decide_again_on_unresolved = gave_up && gave_up->why == GaveUp::Why::Unresolved + && gave_up->sent_any && !policy.resend_unresolved && !policy.single_attempt; + if (!lost_race && !decide_again_on_unresolved) + throwCatalogWriteFailure(std::move(result), what); + sent_unresolved = sent_unresolved || decide_again_on_unresolved; + + if (submissions == kCasMaxDecisions) + { + const std::optional lost = op.lostAdmission(); + if (!lost) + throwDidNotConverge(what, kCasMaxDecisions, "submissions"); + if (*lost == CasOperation::AdmissionLoss::Fence) + throw CatalogFenceMovedMarker{}; + throwCasWriteRetryLater(fmt::format("{}: gave up at the lease deadline after {} submissions", what, kCasMaxDecisions)); + } + if (lost_race) + { + /// The pause follows the run of consecutive clean losses; a settled fault ends that run. + if (conflict->any_ambiguous) + { + clean_losses = 0; + op.sleepFor(Retry::backoff(++settled_faults)); + } + else if (const uint64_t pause_ms = Retry::conflictBackoff(++clean_losses); pause_ms > 0) + op.sleepFor(pause_ms); continue; - result = std::move(*given_up); - } - if (const auto * conflict = std::get_if(&result); conflict && !frozen.single_attempt) - { - op.pause(conflict->any_ambiguous ? Retry::backoff(++settled_faults) : Retry::conflictBackoff()); - continue; + } + clean_losses = 0; + attempt_policy.attempts_already_sent += gave_up->attempts_sent; + std::optional stopped = op.pauseAfterUnresolvedWrite(Retry::backoff(++settled_faults), *gave_up, policy); + if (!stopped) + continue; + if (stopped->why == GaveUp::Why::FenceLost) + throw CatalogFenceMovedMarker{}; + throwCatalogWriteFailure(std::move(*stopped), what); } - /// The fence can be lost in two places and both mean the same to a lifecycle caller: inside - /// `decide`, which throws the marker itself, and between two attempts, where the engine - /// notices it first and no further `decide` runs. Normalising the second onto the first is - /// what keeps "the fence moved" a returned outcome rather than an exception. - if (const auto * gave_up = std::get_if(&result); gave_up && gave_up->why == GaveUp::Why::FenceLost) - throw CatalogFenceMovedMarker{}; - if (!std::holds_alternative(result)) - throwCatalogWriteFailure(std::move(result), fmt::format("CAS ref catalog '{}' update", key)); - return std::move(*written); + } + catch (const CatalogDecisionFailure & failure) + { + std::rethrow_exception(failure.error); + } + catch (const CatalogFenceMovedMarker &) + { + throw; + } + catch (const CatalogAbsentMarker &) + { + throw; + } + catch (...) + { + if (!sent_unresolved || isLocalFault(std::current_exception())) + throw; + throwCasWriteRetryLater(fmt::format("{}: a sent write's outcome is unresolved; the call ended with: {}", what, + getCurrentExceptionMessage(/*with_stacktrace=*/false, /*check_embedded_stacktrace=*/false, + /*with_extra_info=*/false, /*with_version=*/false))); } } @@ -504,19 +572,16 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov .catalog_snapshot = std::move(catalog_snapshot)}; }; - /// ONE bound for the whole loop, frozen before the first iteration: every erase and every - /// resolution read below shares this deadline, so a permanently contended catalog gives up - /// retry-later within one standard window rather than spending a fresh window per verb per - /// iteration. The pause after a refused erase is a bare sleep that does not consult the deadline; - /// the read that follows it does, so a pause that crosses the deadline ends the call before the - /// next erase is sent. - const Retry policy = op.freeze(Retry::standard()); + const Retry policy = Retry::standard(); bool retirement_announced = false; - for (size_t attempt = 0; attempt < kMaxCatalogCasAttempts; ++attempt) + uint32_t clean_losses = 0; + /// Each request binds its own window, so only the count ends a loop that keeps losing the catalog. + for (uint32_t attempt = 0; attempt < kCasMaxDecisions; ++attempt) { - /// So the admission consulted below is not one reading taken before the first attempt. - if (refresh_authority) + /// So the admission consulted below is not one reading taken before the first attempt. A later + /// attempt refreshes right after its pause, below. + if (refresh_authority && attempt == 0) refresh_authority(); catalog_snapshot.life_index.throwIfAmbiguous("CAS completed-removal deletion"); @@ -545,11 +610,27 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov if (erase_acknowledged && std::holds_alternative(erase)) erase_acknowledged(old_life); + /// The erase saw its query stop on a failure: no further erase follows it. + const auto * conflict = std::get_if(&erase); + const bool erase_again = conflict && !conflict->observed_stop; /// Pause before the read: that read is the snapshot the next erase is conditioned on, and a /// write landing during a pause taken after it would refuse that erase every time. - /// The argument counts reissues so far: `backoff(0)` is no wait at all. - if (std::holds_alternative(erase)) - op.pause(Retry::backoff(static_cast(attempt) + 1)); + /// A clean refusal is paced by the run of consecutive clean ones, which a refusal that settled a transport + /// fault ends; that one is paced by the fault schedule. No erase follows the last attempt, so nothing waits for it. + /// The next attempt's refresh follows the pause and precedes the read, so no request sits between + /// that read and the erase on it. A stopped background owner makes no next attempt, so it skips it. + if (erase_again && attempt + 1 < kCasMaxDecisions) + { + if (conflict->any_ambiguous) + { + clean_losses = 0; + op.sleepFor(Retry::backoff(attempt + 1)); + } + else if (const uint64_t pause_ms = Retry::conflictBackoff(++clean_losses); pause_ms > 0) + op.sleepFor(pause_ms); + if (refresh_authority && !backgroundStopRequested()) + refresh_authority(); + } /// An operation whose admission is gone cannot issue the resolution read either, so the call /// ends HERE and reports the cut it was given rather than a fresh one. There is nothing further @@ -560,7 +641,23 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov /// The response to a conditional erase is not authority for what became durable. Resolve every /// attempted erase through one complete catalog read. This snapshot is also the next /// retry/selection cut, so no second read separates them. - catalog_snapshot = read(op, layout, policy); + try + { + /// Owed to the attempted erase: a landed erase must be observed. + const auto owed = OwnerScope::owed(); + catalog_snapshot = read(op, layout, policy); + } + catch (...) + { + /// The erase may still land, so a stopped owner's failed read keeps its "outcome unknown" exit. A local + /// fault says nothing about the erase and propagates unchanged. + const auto * gave_up = std::get_if(&erase); + if (gave_up && gave_up->why == GaveUp::Why::Unresolved && gave_up->sent_any && ownerStopRequested() + && !isLocalFault(std::current_exception())) + throwCatalogWriteFailure(std::move(erase), fmt::format( + "CAS ref catalog erase for namespace '{}'", observed.ns.string())); + throw; + } const auto current_it = findEntry(catalog_snapshot.catalog, observed.ns); const bool old_life_still_cataloged = current_it != catalog_snapshot.catalog.entries.end() @@ -573,7 +670,7 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov /// The row survived the attempt. Only a refused precondition may be tried again against the /// mandatory resolution snapshot above; every other alternative is terminal for this call, and /// a commit the resolution read contradicts is reported rather than believed. - if (!std::holds_alternative(erase)) + if (!erase_again) { if (std::holds_alternative(erase)) throwCasWriteRetryLater(fmt::format( @@ -583,11 +680,10 @@ CasRefCatalog::CompletedRemovingDeleteResult CasRefCatalog::deleteCompletedRemov throwCatalogWriteFailure(std::move(erase), fmt::format( "CAS ref catalog erase for namespace '{}'", observed.ns.string())); } + throwIfBackgroundStopped(); } - throwCasWriteRetryLater(fmt::format( - "CAS ref catalog erase for namespace '{}' did not converge after {} attempts", - observed.ns.string(), kMaxCatalogCasAttempts)); + throwDidNotConverge(fmt::format("CAS ref catalog erase for namespace '{}'", observed.ns.string()), kCasMaxDecisions, "attempts"); } CasRefCatalog::StalledCreatingCancelOutcome CasRefCatalog::cancelStalledCreating( @@ -601,13 +697,10 @@ CasRefCatalog::StalledCreatingCancelOutcome CasRefCatalog::cancelStalledCreating "creator fence", observed.ns.string()); - /// One deadline for the cancel and its in-lane authority check, so a slow check cannot hold the lane - /// after the cancel could no longer write. - const Retry frozen = op.freeze(policy); const auto mutate = [&](const RefCatalog & cur) -> RefCatalog { /// Inside the lane: a leader deposed while it queued must not write on a reading taken before. - refresh_authority(frozen); + refresh_authority(policy); if (!op.admitted()) throw CatalogFenceMovedMarker{}; @@ -626,7 +719,7 @@ CasRefCatalog::StalledCreatingCancelOutcome CasRefCatalog::cancelStalledCreating /// unfinished life. try { - casUpdateImpl(op, layout, mutate, [](const RefCatalog & c) { return encodeRefCatalog(c); }, frozen, + casUpdateImpl(op, layout, mutate, [](const RefCatalog & c) { return encodeRefCatalog(c); }, policy, /*absence_is_an_answer=*/catalog_absent != nullptr); } catch (const CatalogAbsentMarker &) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h index d6c154b8f61ed..6e15435ca72f7 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCatalog.h @@ -68,9 +68,8 @@ class CasRefCatalog /// re-encoding the stale candidate. `mutate` must return a canonically ordered, grammar-valid /// candidate; `encodeRefCatalog` (called internally) enforces that. /// - /// The engine's own policy is the bound: persistent conflict ends at the write deadline with the - /// typed retryable error `throwCasWriteRetryLater`, rather than spinning forever against a - /// pathologically busy catalog. + /// Persistent conflict ends after `kCasMaxDecisions` submissions with the typed retryable error + /// `throwCasWriteRetryLater`, rather than spinning forever against a pathologically busy catalog. /// /// A read that finds the object ABSENT is corruption, not a fresh bootstrap -- `mutate` is never /// offered an absent catalog to build a replacement authority from, so no mutation can replace @@ -156,8 +155,9 @@ class CasRefCatalog /// `catalog_snapshot`, and the mandatory resolution snapshot is returned in the result so a /// catalog-only drain can select the next row without an intervening read. /// - /// `refresh_authority` runs at the top of every attempt, before the checks that decide whether to - /// send one. It is not a verdict -- the verdict stays `op.admitted()` -- but that liveness may be + /// `refresh_authority` runs once before every attempt: before the first one's checks, and for each + /// later one right after its pause, before the catalog read that attempt is conditioned on, unless + /// a background owner stopped during that pause. It is not a verdict -- the verdict stays `op.admitted()` -- but that liveness may be /// a cached flag its holder refreshes from a fact this loop cannot see, and one reading taken /// before the first erase must not authorise the rest. A caller whose liveness needs no refresh /// passes a no-op and says so. @@ -193,8 +193,8 @@ class CasRefCatalog /// `_ckpt` or other physical cleanup; debris belongs to the janitor. /// `refresh_authority` runs in every attempt, inside the catalog's hot-key lane and before `op`'s /// admission is checked, for a caller whose liveness is a cached flag; a caller whose liveness needs - /// no refresh passes a no-op. Its reads hold the lane, so it receives the cancel's own frozen policy to - /// bound them; a refresh that cannot finish in time must leave `op` unadmitted. The predicate runs + /// no refresh passes a no-op. Its reads hold the lane, so it receives the cancel's policy to bound + /// them; a refresh that cannot finish in time must leave `op` unadmitted. The predicate runs /// there too, on the catalog the attempt writes over. /// A cancel whose response is lost returns `Cancelled` while the catalog still holds the bytes it wrote, /// and `EntryChanged` once a later write replaced them. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.cpp index 84872f6173970..7b7682fe8116d 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.cpp @@ -175,9 +175,11 @@ CkptStampResult stampCkptGeneration3(CasOperation & op, const Layout & layout, c return CkptStampResult{.outcome = CkptStampOutcome::Stamped, .stamped = CkptSample{.ckpt = std::move(stamped), .etag = committed->etag}}; } - if (std::holds_alternative(result)) - return CkptStampResult{.outcome = CkptStampOutcome::TokenMismatch, .stamped = std::nullopt}; - return CkptStampResult{.outcome = CkptStampOutcome::Unresolved, .stamped = std::nullopt}; + if (const auto * conflict = std::get_if(&result)) + return CkptStampResult{.outcome = CkptStampOutcome::TokenMismatch, .stamped = std::nullopt, + .observed_stop = conflict->observed_stop}; + const auto * gave_up = std::get_if(&result); + return CkptStampResult{.outcome = CkptStampOutcome::Unresolved, .stamped = std::nullopt, .sent_any = gave_up && gave_up->sent_any}; } MissingBaseVerdict classifyMissingSampledBase(const Etag & sampled, const std::optional & current) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.h index eb0d1dba32253..d070a46d4ad6b 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefCkpt.h @@ -90,6 +90,10 @@ struct CkptStampResult CkptStampOutcome outcome; /// Set iff `Stamped`: the body now durable and the token it was written under. std::optional stamped; + /// True only for an `Unresolved` write that was sent and may still land; false when nothing that may land was sent. + bool sent_any = false; + /// For `TokenMismatch`: the query stopped and cut short the read that settles the refusal. + bool observed_stop = false; }; /// One conditional replace on `accepted.etag` with `{life_epoch, checkpoint_snapshot_id}` at generation 3. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp index 384d7ef16a011..b7b9374a85725 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -284,22 +285,34 @@ CasRefLedger::CasRefLedger( , cancel_inflight_builds(std::move(cancel_inflight_builds_)) , recovery_pre_first_request_hook_for_test(std::move(recovery_pre_first_request_hook_for_test_)) { - /// Default backoff sleep for the recovery retry loop (`ensureRefTableRecovered`): sleep in short - /// slices and stop early if the mount fence drops (shutdown / lease loss), so teardown never waits - /// out a full 30s backoff. This is deliberate, bounded backoff against external object-store I/O - /// failure -- NOT masking a race -- exactly like the request engine's own inter-attempt sleep; the - /// slice loop additionally makes it interruptible, which that one is not. - recovery_retry_sleep_fn = [this](uint64_t total_ms, const std::optional & token) + recovery_retry_slice_sleep_fn = [](uint64_t ms) { sleepForMilliseconds(ms); }; +} + +void CasRefLedger::pauseBeforeRecoveryRetry(uint64_t total_ms, const std::optional & token) +{ + /// A test's whole-pause sleep is one slice, so the checks below run before it as before every slice. + const uint64_t slice_ms = recovery_retry_pause_sleep_for_test ? total_ms : static_cast(Cas::kOwnerStopSlice.count()); + uint64_t slept = 0; + do { - constexpr uint64_t slice_ms = 200; - uint64_t slept = 0; - while (slept < total_ms && fence_ok_fn() && !(token && token->stopping())) + if (!fence_ok_fn() || (token && token->stopping())) + return; + /// A stopped owner ends the pause before a new walk, as it ends the pause before an S3 reissue: a + /// background owner with its verdict, a query by returning early to the caller's veto. + Cas::throwIfBackgroundStopped(); + if (!Cas::insideOwed() && Cas::queryStopRequested()) + return; + if (recovery_retry_pause_sleep_for_test) { - const uint64_t chunk = std::min(slice_ms, total_ms - slept); - sleepForMilliseconds(chunk); - slept += chunk; + recovery_retry_pause_sleep_for_test(total_ms, token); + return; } - }; + if (total_ms == 0) + return; + const uint64_t chunk = std::min(slice_ms, total_ms - slept); + recovery_retry_slice_sleep_fn(chunk); + slept += chunk; + } while (slept < total_ms); } WriteResult CasRefLedger::stagingPutIfAbsent(const String & key, const String & bytes) @@ -329,7 +342,7 @@ void CasRefLedger::throwNotAdmitted(std::string_view what) const void CasRefLedger::setCasRetrySleepForTest(std::function sleep_fn) { mount_requests.setSleepFnForTest(sleep_fn); - recovery_retry_sleep_fn = [recovery_sleep_fn = std::move(sleep_fn)]( + recovery_retry_pause_sleep_for_test = [recovery_sleep_fn = std::move(sleep_fn)]( uint64_t total_ms, const std::optional &) { recovery_sleep_fn(total_ms); @@ -339,7 +352,12 @@ void CasRefLedger::setCasRetrySleepForTest(std::function sleep_f void CasRefLedger::setRefRecoveryRetrySleepForTest( std::function &)> sleep_fn) { - recovery_retry_sleep_fn = std::move(sleep_fn); + recovery_retry_pause_sleep_for_test = std::move(sleep_fn); +} + +void CasRefLedger::setRefRecoveryRetrySliceSleepForTest(std::function sleep_fn) +{ + recovery_retry_slice_sleep_fn = std::move(sleep_fn); } @@ -754,6 +772,14 @@ void CasRefLedger::cancelIdleOwnCreatingRows( const auto stopped = [&] { return stop_requested && stop_requested(); }; if (stopped()) return; + /// The stop also ends a cancel that keeps losing the catalog, at its next submission. + std::optional stop_owner; + if (stop_requested) + stop_owner.emplace(Cas::OwnerScope::background([&] + { + if (stopped()) + throw Exception(ErrorCodes::ABORTED, "CAS cleanup of this mount's own `Creating` rows stopped by its scheduler"); + })); /// The order `Pool::captureMountIncarnation` uses: a generation that holds across the epoch read dates it. const uint64_t generation = fence_generation_fn(); const uint64_t epoch = live_epoch_fn(); @@ -765,7 +791,7 @@ void CasRefLedger::cancelIdleOwnCreatingRows( { LOG_ERROR(getLogger("CasRefLedger"), "CAS ref catalog '{}': mandatory catalog absent; skipping owner cleanup", key); }; - const Retry policy = op.freeze(Retry::standard()); + const Retry policy = Retry::standard(); const std::optional got = op.read(key, policy); if (!got) { @@ -1162,7 +1188,7 @@ void CasRefLedger::checkRecoveryStillAdmitted(const RootNamespace & ns, RefTable std::optional CasRefLedger::runRecoveryWalkOnce( const RootNamespace & ns, RefTableRuntime & rt, uint64_t admitted_generation, const LiveEpochPair & live, const std::optional & retained_attempt, std::optional & hole_detail, - bool & cancelled, const std::optional & token) + bool & cancelled, bool & unresolved_sent, const std::optional & token) { /// One attempt. Runs with NO lock held: everything below is either read-only I/O or a conditional /// write at a key this namespace owns, and the replayed candidate is PRIVATE until the caller @@ -1181,13 +1207,15 @@ std::optional CasRefLedger::runRecoveryWalkOnce( /// is the fence's. The predicate is a bool where the poll throws, so the poll still runs at the /// boundaries: it turns each of these facts into the right exception and LATCHES a cancellation for /// the caller's retry classification. - CasOperation op = mount_requests.resume(admitted_generation, [&rt, &token] + /// An admission check, not an owner: its terms hold inside an owed walk too. + const auto recovery_request_still_admitted = [&rt, &token] { return !(token && token->stopping()) && !rt.recovery_cancel_requested.load(std::memory_order_acquire) && !rt.catalog_life_invalidated.load(std::memory_order_acquire) && !rt.superseded_by_remount.load(std::memory_order_acquire); - }); + }; + CasOperation op = mount_requests.resume(admitted_generation, recovery_request_still_admitted); /// ---- The checkpoint and the base ---- /// The runtime was admitted for this exact life before entering recovery, so this walk takes no @@ -1224,7 +1252,8 @@ std::optional CasRefLedger::runRecoveryWalkOnce( } catch (const Exception & e) { - if (!failureJudgedAgainstCkpt(e.code())) + /// A query's stored cause says nothing about the checkpoint, whatever its code. + if (!failureJudgedAgainstCkpt(e.code()) || Cas::isQueryStoredCause(std::current_exception())) throw; /// A newer checkpoint may have re-anchored recovery while cleanup retired this old anchor's @@ -1301,6 +1330,13 @@ std::optional CasRefLedger::runRecoveryWalkOnce( return true; }; + /// Marks the error of a sent write that may still land, so a later owner stop does not replace it. + const auto throwUnresolved = [&unresolved_sent](bool sent_any, const String & message) + { + unresolved_sent = sent_any; + throwCasRequestRetryLater(message); + }; + /// The walk never re-reads `_ckpt` itself: the re-read after the last read or write of this attempt /// covers its end and every tombstone create. RefChainOrigin origin{ @@ -1359,10 +1395,15 @@ std::optional CasRefLedger::runRecoveryWalkOnce( { checkRecoveryStillAdmitted(ns, rt, cancelled, token); CkptStampResult stamp = stampCkptGeneration3(op, layout, life, accepted); + /// The 412 proves the stamp did not land; the stop ends this walk rather than starting another. + if (stamp.outcome == CkptStampOutcome::TokenMismatch && stamp.observed_stop) + throwCasRequestRetryLater(fmt::format( + "CAS ref-table recovery for namespace '{}': the query stopped after its refused generation 3 stamp " + "of `_ckpt`; nothing is installed", ns.string())); if (stamp.outcome == CkptStampOutcome::TokenMismatch) return std::nullopt; if (stamp.outcome == CkptStampOutcome::Unresolved) - throwCasRequestRetryLater(fmt::format( + throwUnresolved(stamp.sent_any, fmt::format( "CAS ref-table recovery for namespace '{}': the generation 3 stamp of its `_ckpt` is " "unresolved; nothing is installed", ns.string())); accepted = std::move(*stamp.stamped); @@ -1436,7 +1477,7 @@ std::optional CasRefLedger::runRecoveryWalkOnce( } if (const auto * gave_up = std::get_if(&created)) - throwCasRequestRetryLater(fmt::format( + throwUnresolved(gave_up->sent_any, fmt::format( "CAS ref-table recovery for namespace '{}': the tombstone at {}-{} is UNRESOLVED ({}); the " "table stays unrecovered", ns.string(), id.writer_epoch, id.ref_sequence, gave_up->sent_any ? "the outcome of the attempt is unknown" : "nothing was sent")); @@ -1484,27 +1525,25 @@ NamespaceLifeId CasRefLedger::resolveNamespaceLife( const RootNamespace & ns, uint64_t admitted_generation, uint64_t live_epoch, bool * lifecycle_refusal) { - /// The SECONDARY bound. Wall-clock time is already bounded by the frozen policy below, which - /// every verb of every iteration shares; this cap exists so a sequence that somehow converges on - /// neither a resolution nor the deadline still ends. A duel between two openers (one creating, one - /// reconciling a stale creator) converges in a handful of rounds. + /// A duel between two openers (one creating, one reconciling a stale creator) converges in a + /// handful of rounds. static constexpr size_t kMaxResolveAttempts = 32; const CreatorFence our_fence{server_root_id, live_epoch, admitted_generation}; CasOperation op = mount_requests.resume(admitted_generation); + const Retry policy = Retry::standard(); - /// ONE bound for the whole loop, frozen before the first iteration: every read and every protocol - /// call below shares this deadline, so a namespace whose catalog entry keeps moving gives up - /// retry-later within one standard window rather than spending a fresh window per verb per - /// iteration. The paced re-read below is a bare sleep that does not consult the deadline, so the - /// loop can sleep one backoff (at most 5 s) past it before the next read refuses to start. - const Retry policy = op.freeze(Retry::standard()); - + uint32_t collisions = 0; for (size_t attempt = 0; attempt < kMaxResolveAttempts; ++attempt) { - /// Paces ONLY the re-reads a competing actor forced. A `Live` outcome is this open's own - /// success and its single confirming re-read is not contention, so it is never delayed. The - /// argument is the number of collisions so far, so the first one waits the shortest draw. - const auto paceReRead = [&] { op.pause(Retry::backoff(static_cast(attempt) + 1)); }; + /// Paces ONLY the re-reads a competing actor forced, by the count of those collisions. A `Live` + /// outcome is this open's own success and its single confirming re-read is not contention, so it + /// is never delayed. The last attempt is followed by no re-read, so nothing waits for it. + const auto paceReRead = [&] + { + ++collisions; + if (const uint64_t pause_ms = Retry::conflictBackoff(collisions); pause_ms > 0 && attempt + 1 < kMaxResolveAttempts) + op.sleepFor(pause_ms); + }; const CasRefCatalog::Snapshot snap = CasRefCatalog::read(op, layout, policy); const auto it = std::find_if(snap.catalog.entries.begin(), snap.catalog.entries.end(), @@ -1632,14 +1671,15 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( return RefRecoveryOutcome::Recovered; /// A concurrent second caller waits here rather than racing an independent walk against the first - /// caller's unlocked I/O. + /// caller's unlocked I/O. The walk belongs to another caller, so this caller's query does not end the wait. while (rt.recovery_in_progress) { if (token && token->stopping()) throw Exception(ErrorCodes::ABORTED, "CAS ref recovery: teardown began while waiting for a concurrent recovery"); + Cas::throwIfBackgroundStopped(); ++rt.recovery_waiters_for_test; - rt.recovery_cv.wait_for(lock, std::chrono::milliseconds(200)); + rt.recovery_cv.wait_for(lock, Cas::kOwnerStopSlice); --rt.recovery_waiters_for_test; } if (rt.recovered && !needs_rerecovery()) @@ -1667,7 +1707,7 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// /// Captured for the WHOLE call, not per attempt, for the same reason: the transient-retry loop below /// exists for object-store blips, and a generation that moved is not one. The loop refuses to - /// re-drive under a moved generation (below), so the budget is never burned on a doomed retry. + /// re-drive under a moved generation (below), so no walk is spent on a doomed retry. const uint64_t admitted_generation = rt.admitted_fence_generation; refuseUnlessAdmitted(mount_requests.resume(admitted_generation), "ref recovery walk admission"); /// Preserve this runtime's exact writer identity across the unlocked walk. The runtime stays in @@ -1681,13 +1721,68 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// Outer transient-retry loop, so a blip does not fail a table load for good: a whole recovery attempt that /// fails with a TRANSIENT object-store transport error (`isTransientRecoveryError` -- `S3_ERROR`/ /// socket/timeout from the direct LIST/GET backend calls, or a controller `NETWORK_ERROR`) is retried - /// with capped-exponential backoff until `recovery_retry_budget_ms` is spent, instead of propagating - /// and failing this table's async load permanently. Non-transient errors (corruption, decode, a moved - /// fence, logic, resource limits) fail fast; so do the latched terminal cases below. - const uint64_t recovery_start_ms = boot_ms_now_fn(); + /// with capped-exponential backoff until `kCasMaxRecoveryWalks` walks have started, instead of + /// propagating and failing this table's async load permanently. Non-transient errors (corruption, + /// decode, a moved fence, logic, resource limits) fail fast; so do the latched terminal cases below. uint64_t recovery_retry_num = 0; + /// Walks started so far, retried or restarted alike. + uint32_t walks_started = 0; bool vanish_brake_tripped = false; bool cancelled = false; + /// Only a walk that threw lets a stopped owner end recovery: a restart after a successful walk and the + /// structural exits keep their answers. + bool walk_failed = false; + std::exception_ptr unresolved_error; + /// After a failed walk a stopped background owner ends recovery with its verdict, an unresolved write's error first. + const auto rethrowIfBackgroundStoppedAfterFailedWalk = [&] + { + if (!walk_failed) + return; + if (std::exception_ptr stop = Cas::backgroundStopRequested()) + std::rethrow_exception(unresolved_error ? unresolved_error : stop); + }; + /// The same, then a stopped query ends recovery with `failure`, the error recovery already has. + const auto rethrowIfOwnerStoppedAfterFailedWalk = [&](const std::exception_ptr & failure) + { + rethrowIfBackgroundStoppedAfterFailedWalk(); + if (walk_failed && Cas::queryStopRequested()) + std::rethrow_exception(unresolved_error ? unresolved_error : failure); + }; + /// Whether the catalog still names the recovering life. A failed catalog read is a third answer. + struct LifeCheck + { + enum class Answer : uint8_t { Exists, Removed, Unknown }; + Answer answer; + std::exception_ptr failure; + }; + const auto checkLifeStillCataloged = [&]() -> LifeCheck + { + try + { + if (confirmRecoveredLifeOrDetach(rt, admitted_generation)) + return {LifeCheck::Answer::Exists, nullptr}; + return {LifeCheck::Answer::Removed, nullptr}; + } + catch (...) + { + return {LifeCheck::Answer::Unknown, std::current_exception()}; + } + }; + const auto throwIfTeardown = [&token] + { + if (token && token->stopping()) + throw Exception(ErrorCodes::ABORTED, "CAS ref recovery: teardown began during recovery"); + }; + /// Throws `ABORTED` on teardown. False when the mount fence is lost, this runtime is retired or superseded by a + /// self-remount, or the admitting generation has moved: retrying under a stale generation can only be refused at the install. + const auto mayRetry = [&] + { + throwIfTeardown(); + return fence_ok_fn() + && !rt.catalog_life_invalidated.load(std::memory_order_acquire) + && !rt.superseded_by_remount.load(std::memory_order_acquire) + && fence_generation_fn() == admitted_generation; + }; for (;;) { try @@ -1700,7 +1795,7 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( if (attempt > kRefRecoveryMaxRestarts) { /// Terminal, NOT a transient object-store outage: latch so the outer retry loop - /// rethrows immediately instead of re-driving this brake for the whole budget. + /// rethrows immediately instead of re-driving this brake for the remaining walks. vanish_brake_tripped = true; if (hole_detail) throw Exception(ErrorCodes::CORRUPTED_DATA, @@ -1721,16 +1816,25 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// selected-base vanish after the next attempt takes a different path. hole_detail.reset(); + if (walk_failed) + Cas::throwIfBackgroundStopped(); + walk_failed = false; + /// The whole walk runs UNLOCKED. Nothing it touches is shared: the candidate is private /// and `rt` is read only through atomics the poll consults. Unlocking is what keeps a /// recovery's full I/O envelope from stalling every reader of this table -- and what lets /// the self-remount barrier take the lock promptly to JOIN us. + ++walks_started; lock.unlock(); std::optional walked; + bool unresolved_sent = false; try { + /// Owed so that CAS's own checks do not cut a started walk. On S3 a stopped query's walk still + /// fails at its first error answer, the `404` that ends every walk included. + const auto owed = Cas::OwnerScope::owed(); walked = runRecoveryWalkOnce( - ns, rt, admitted_generation, live, retained_attempt, hole_detail, cancelled, token); + ns, rt, admitted_generation, live, retained_attempt, hole_detail, cancelled, unresolved_sent, token); /// The admission's catalog read precedes the walk, and another server's GC may have /// erased the life and deleted its objects under it. if (walked) @@ -1738,6 +1842,9 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( } catch (...) { + walk_failed = true; + if (unresolved_sent) + unresolved_error = std::current_exception(); /// Re-acquire BEFORE letting anything propagate: the SCOPE_EXIT above mutates /// `recovery_in_progress` and notifies `recovery_cv`, and it MUST run with /// `state_mutex` held -- unwinding through it unlocked would be a data race on the @@ -1748,7 +1855,20 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( lock.lock(); if (!walked) + { + /// When the structural brake also trips on the next pass, it reports the more specific cause. + if (walks_started >= kCasMaxRecoveryWalks && attempt < kRefRecoveryMaxRestarts) + { + /// A fence lost during the last walk is the answer, not the count. + refuseUnlessAdmitted(mount_requests.resume(admitted_generation), "ref recovery restart"); + throwCasRequestRetryLater(fmt::format( + "CAS ref-table recovery for namespace '{}': did not converge after {} walks ({})", + ns.string(), walks_started, + hole_detail ? "last walk found: " + *hole_detail + : String("the last walk restarted because the checkpoint or its base moved"))); + } continue; /// restart requested (vanished base, or a hole worth one more reading) + } if (life_removed) break; @@ -1792,34 +1912,37 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// a `catch (const Exception &)` would not even see. `getCurrentExceptionCode()` normalises /// every exception (DB, Poco, std) to a code so the transient classifier can decide. const int code = getCurrentExceptionCode(); - /// Corruption of a life the catalog no longer names is the janitor's work, not damage. - if (code == ErrorCodes::CORRUPTED_DATA) + /// Corruption of a life the catalog no longer names is the janitor's work, not damage. The confirmation + /// is no retry, so a stopped query reaches it as a live one does; a query's stored cause is no corruption. + const bool confirm_corruption + = code == ErrorCodes::CORRUPTED_DATA && !Cas::isQueryStoredCause(std::current_exception()); + if (!confirm_corruption) + rethrowIfOwnerStoppedAfterFailedWalk(std::current_exception()); + else { + rethrowIfBackgroundStoppedAfterFailedWalk(); lock.unlock(); - bool confirmed = true; - try - { - confirmed = confirmRecoveredLifeOrDetach(rt, admitted_generation); - } - catch (...) // NOLINT(bugprone-empty-catch) - { - /// Without a confirmation the walk's own error is the answer. - } + const LifeCheck life = checkLifeStillCataloged(); lock.lock(); - if (!confirmed) + if (life.answer == LifeCheck::Answer::Removed) { life_removed = true; break; } + /// A stop during the confirmation must not surface as corruption. + rethrowIfOwnerStoppedAfterFailedWalk(life.failure ? life.failure : std::current_exception()); + /// Nor may a failed confirmation: it did not establish that the catalog still names the life. + if (life.answer == LifeCheck::Answer::Unknown) + std::rethrow_exception(unresolved_error ? unresolved_error : life.failure); } /// `cancelled` is latched by the poll itself: a self-remount's cancellation uses the /// retry-later class (the caller should retry, against the FRESH incarnation), so without the /// latch this loop would read it as a transient blip and re-drive the very work the remount /// just stopped. Detached teardown is independently terminal even when the in-flight /// exception happened to carry a transient transport code. - if (vanish_brake_tripped || cancelled || (token && token->stopping()) - || !isTransientRecoveryError(code)) + if (vanish_brake_tripped || cancelled || !isTransientRecoveryError(code)) throw; /// a latched terminal case, or a non-transient failure -- fail fast + throwIfTeardown(); /// A cancellation now ends the walk through the operation's liveness, which refuses /// silently -- so the exception that arrives here carries a transport code and `cancelled` @@ -1828,16 +1951,12 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( if (rt.recovery_cancel_requested.load(std::memory_order_acquire)) checkRecoveryStillAdmitted(ns, rt, cancelled, token); - const uint64_t elapsed_ms = boot_ms_now_fn() - recovery_start_ms; - /// Fail closed BEFORE sleeping: budget spent, mount fence lost, this runtime superseded by a - /// self-remount, or the incarnation that admitted this recovery has moved (retrying under a - /// generation that is already stale can only ever be refused at the install). - if (elapsed_ms >= cas_request_budget.recovery_retry_budget_ms - || (token && token->stopping()) - || !fence_ok_fn() - || rt.catalog_life_invalidated.load(std::memory_order_acquire) - || rt.superseded_by_remount.load(std::memory_order_acquire) - || fence_generation_fn() != admitted_generation) + /// Fail closed BEFORE sleeping. + if (!mayRetry()) + throw; + + /// The walk cap ends the loop without a pause; the original error propagates like the exits above. + if (walks_started >= kCasMaxRecoveryWalks) throw; /// Saturating `initial << recovery_retry_num`: `initial > cap >> n` implies the unshifted @@ -1852,9 +1971,9 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( ProfileEvents::increment(ProfileEvents::CASRefRecoveryRetries); LOG_WARNING(getLogger("CasRefLedger"), "CAS ref-table recovery for namespace '{}' hit a transient object-store error " - "(code {}: {}); retry #{} after {}ms backoff (elapsed {}ms / budget {}ms)", + "(code {}: {}); retry #{} after {}ms backoff", ns.string(), code, getCurrentExceptionMessage(/*with_stacktrace=*/false), - recovery_retry_num, backoff_ms, elapsed_ms, cas_request_budget.recovery_retry_budget_ms); + recovery_retry_num, backoff_ms); lock.unlock(); /// Re-acquire the lock before letting any exception from the sleep unwind, so the SCOPE_EXIT @@ -1862,24 +1981,26 @@ RefRecoveryOutcome CasRefLedger::ensureRefTableRecovered( /// `state_mutex`) never runs unlocked -- same obligation as the walk's window above. try { - recovery_retry_sleep_fn(backoff_ms, token); + /// Only a walk that threw makes the next walk a reissue the owner may stop. + std::optional pause_owed; + if (!walk_failed) + pause_owed.emplace(Cas::OwnerScope::owed()); + pauseBeforeRecoveryRetry(backoff_ms, token); } catch (...) { lock.lock(); + if (unresolved_error) + std::rethrow_exception(unresolved_error); throw; } lock.lock(); - /// The fence/supersession/budget can all change during the unlocked sleep -- re-check before - /// starting the next full attempt so we never re-drive recovery on an orphaned runtime, past - /// the budget, or under a lost or moved fence (the sliced sleep may have woken early on fence - /// loss). - if (boot_ms_now_fn() - recovery_start_ms >= cas_request_budget.recovery_retry_budget_ms - || (token && token->stopping()) - || !fence_ok_fn() - || rt.catalog_life_invalidated.load(std::memory_order_acquire) - || rt.superseded_by_remount.load(std::memory_order_acquire) - || fence_generation_fn() != admitted_generation) + /// A query stopped in the pause vetoes the next walk. + if (walk_failed && Cas::queryStopRequested()) + std::rethrow_exception(unresolved_error ? unresolved_error : std::current_exception()); + /// The fence and supersession can change during the unlocked sleep, which may also have woken + /// early on fence loss. + if (!mayRetry()) throw; /// loop: re-run recovery from a fresh checkpoint read, exact replay and walk } @@ -2208,6 +2329,15 @@ RefLaneState CasRefLedger::laneStateForTest(const RootNamespace & ns) return rt->lane_state; } +CasRefLedger::RemovalFlagsForTest CasRefLedger::removalFlagsForTest(const RootNamespace & ns) +{ + const auto rt = lookupRefTableRuntime(ns); + if (!rt) + return {}; + std::lock_guard lock(ref_queue_mutex); + return {.attempt_active = rt->removal_attempt_active, .admission_closed = rt->removal_admission_closed}; +} + bool CasRefLedger::needsStalePrecommitSweepForTest(const RootNamespace & ns) { const auto rt = lookupRefTableRuntime(ns); @@ -2323,31 +2453,37 @@ namespace { /// The row may still be `Live` here, so the text must not claim `Removing`. -[[noreturn]] void throwRemovalWriteMayLand(const RootNamespace & ns) +String removalWriteMayLandReason(const RootNamespace & ns) { - throwCasWriteRetryLater(fmt::format( - "CAS namespace '{}': a removal write may still land, so positive ref mutation admission is " - "closed until a retried removal completes or the disk is remounted; retry later", ns.string())); + return fmt::format( + "CAS namespace '{}': a removal write may still land, so writes are refused until a retried removal " + "completes or the disk is remounted; retry the `DROP TABLE` or other operation that removed it", ns.string()); } /// True whether the removal is still running, done and waiting for GC to erase the row, or stuck; the /// remedy for a stuck one depends on the operation that started it, so the text names none. -[[noreturn]] void throwRemovingObserved(const RootNamespace & ns) +String removingObservedReason(const RootNamespace & ns) { - throwCasWriteRetryLater(fmt::format( + return fmt::format( "CAS namespace '{}' is Removing in the catalog: writes are refused and reads see no data until its removal " "completes and GC erases the row; retry later, and if it stays Removing see the CAS troubleshooting page", - ns.string())); + ns.string()); +} + +/// Only for a caller that has not queued its mutation yet. +[[noreturn]] void throwAdmissionRefused(const String & reason) +{ + throw RefAdmissionRefusedException(makeCasWriteRetryLaterException(reason)); } /// Flags read under `ref_queue_mutex`. [[noreturn]] void throwPositiveAdmissionClosed(const RootNamespace & ns, bool removing_observed, bool write_may_land) { if (write_may_land) - throwRemovalWriteMayLand(ns); + throwAdmissionRefused(removalWriteMayLandReason(ns)); if (removing_observed) - throwRemovingObserved(ns); - throwCasWriteRetryLater(fmt::format( + throwAdmissionRefused(removingObservedReason(ns)); + throwAdmissionRefused(fmt::format( "CAS namespace '{}' is Removing: positive ref mutation admission is closed while its " "terminal fold and catalog removal complete; retry later", ns.string())); } @@ -2433,6 +2569,8 @@ RefTxnId CasRefLedger::appendRefOpsOnRuntime( catch (...) { std::erase(rt->pending, item); + /// The queue may now be drained, and a removal waits for that without a timeout. + rt->cv.notify_all(); throw; } @@ -2461,7 +2599,7 @@ RefTxnId CasRefLedger::appendRefOpsOnRuntime( } else { - rt->cv.wait(lk); + waitAsFollower(rt, item, lk); } } lk.unlock(); @@ -2469,16 +2607,50 @@ RefTxnId CasRefLedger::appendRefOpsOnRuntime( ProfileEvents::increment(ProfileEvents::CASRefQueueWaitMicroseconds, std::chrono::duration_cast( std::chrono::steady_clock::now() - enqueued_at).count()); + /// One failure can complete several items, each rethrown on its own caller's thread. if (item->error) - std::rethrow_exception(item->error); + rethrowOwnCopy(item->error); return item->committed_id; } +void CasRefLedger::waitAsFollower( + const std::shared_ptr & rt, const std::shared_ptr & item, std::unique_lock & lk) +{ + try + { + Cas::waitStoppable(rt->cv, lk, [&] + { + runRefFollowerWaitHook(FollowerWaitPhase::Queued); + return item->done || !rt->leader_active; + }); + } + catch (...) + { + /// A queued item still belongs to its caller and is withdrawn. Otherwise a leader owns it (or it is + /// done) and completes it, so the caller leaves only with that result; this wait has no owner check. + if (std::erase(rt->pending, item) > 0) + { + rt->cv.notify_all(); + throw; + } + rt->cv.wait(lk, [&] + { + runRefFollowerWaitHook(FollowerWaitPhase::Carved); + return item->done; + }); + } +} + void CasRefLedger::runRefQueueLeader(const RootNamespace & ns, const std::shared_ptr & rt, const std::shared_ptr & own, std::vector> & owned_items) { + /// Captured before `shared`, which leaves no owner to ask. + const std::function owner_check = Cas::OwnerScope::effectiveCheck(); + /// One caller's owner must not decide work done for several callers. + const auto shared = Cas::OwnerScope::shared(); + /// Fairness baton pass: serve flushes only until the caller's OWN item is done, then hand off to a /// woken waiter. while (true) @@ -2488,7 +2660,9 @@ void CasRefLedger::runRefQueueLeader(const RootNamespace & ns, const std::shared if (own->done) return; } - flushRefBatch(ns, rt, owned_items); + if (owner_check) + owner_check(); + flushRefBatch(ns, rt, owned_items, own, owner_check); } } @@ -3422,7 +3596,8 @@ bool CasRefLedger::ensureEpochOpenForAppend(const RootNamespace & ns, const std: } void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr & rt, - std::vector> & owned_items) + std::vector> & owned_items, + const std::shared_ptr & own, const std::function & owner_check) { /// One flush = one carved batch through one attempted append. Contract: every ORDINARY outcome /// (validation reject, DefiniteFailure, Unresolved/wedge, Committed) lands in the affected items so @@ -3446,12 +3621,18 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr } rt->cv.notify_all(); }; - auto carve_all_pending = [&]() -> std::vector> + /// Takes the error already built and allocates nothing, so no failure can leave a taken item neither queued + /// nor completed. + auto fail_all_pending = [&](const std::exception_ptr & e) { std::lock_guard g(ref_queue_mutex); - std::vector> all(rt->pending.begin(), rt->pending.end()); + for (const auto & it : rt->pending) + { + it->error = e; + it->done = true; + } rt->pending.clear(); - return all; + rt->cv.notify_all(); }; RefRecoveryOutcome recovery_outcome = RefRecoveryOutcome::Recovered; @@ -3461,13 +3642,12 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr } catch (...) { - complete_error(carve_all_pending(), std::current_exception()); + fail_all_pending(std::current_exception()); return; } if (recovery_outcome == RefRecoveryOutcome::LifeRemoved) { - complete_error(carve_all_pending(), - makeCasWriteRetryLaterExceptionPtr(recoveredLifeRemovedMessage(ns, rt->life))); + fail_all_pending(makeCasWriteRetryLaterExceptionPtr(recoveredLifeRemovedMessage(ns, rt->life))); return; } @@ -3475,7 +3655,7 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr /// Fails the WHOLE queue -- every caller would have gotten the same refusal alone. if (!may_mutate()) { - complete_error(carve_all_pending(), makeCasWriteRetryLaterExceptionPtr(fmt::format( + fail_all_pending(makeCasWriteRetryLaterExceptionPtr(fmt::format( "CAS mount lost / lease expired — refusing to append ref-log transactions for server_root '{}'", config.server_root_id))); return; @@ -3489,7 +3669,7 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr /// reaching this AFTER passing `mayMutate` above proves the swap happened. if (rt->superseded_by_remount.load(std::memory_order_acquire)) { - complete_error(carve_all_pending(), makeCasWriteRetryLaterExceptionPtr(fmt::format( + fail_all_pending(makeCasWriteRetryLaterExceptionPtr(fmt::format( "CAS ref-log append for server_root '{}': this cached table was superseded by a self-remount — " "retry against the fresh mount incarnation", config.server_root_id))); @@ -3518,7 +3698,7 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr case WedgeResolution::Rejected: case WedgeResolution::StillWedged: case WedgeResolution::Corrupted: - complete_error(carve_all_pending(), resolution.survivor_error); + fail_all_pending(resolution.survivor_error); return; } } @@ -3558,7 +3738,7 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr /// `CORRUPTED_DATA` about a stale premise this lane was never entitled to use. if (rt->superseded_by_remount.load(std::memory_order_acquire)) { - complete_error(carve_all_pending(), makeCasWriteRetryLaterExceptionPtr(fmt::format( + fail_all_pending(makeCasWriteRetryLaterExceptionPtr(fmt::format( "CAS ref-log append for server_root '{}': this cached table was superseded by a self-remount " "before its batch was carved — retry against the fresh mount incarnation", config.server_root_id))); @@ -3584,6 +3764,10 @@ void CasRefLedger::flushRefBatch(const RootNamespace & ns, const std::shared_ptr std::vector> batch; { std::lock_guard g(ref_queue_mutex); + /// Until carved, the leader's own item is still its caller's to withdraw; the leadership exit guard + /// removes it from `pending`. Outside the prelude's catch, which would fail the whole queue for one caller's stop. + if (owner_check && std::find(rt->pending.begin(), rt->pending.end(), own) != rt->pending.end()) + owner_check(); const size_t cap = table_live ? kMaxRefBatch : 1; /// --- PLAN --- @@ -5511,10 +5695,10 @@ NamespaceLifeId CasRefLedger::namespaceLife(const RootNamespace & ns) write_may_land = rt->removal_write_may_land; } if (write_may_land) - throwRemovalWriteMayLand(ns); + throwAdmissionRefused(removalWriteMayLandReason(ns)); if (removing_observed) - throwRemovingObserved(ns); - throwCasWriteRetryLater(fmt::format( + throwAdmissionRefused(removingObservedReason(ns)); + throwAdmissionRefused(fmt::format( "CAS namespace '{}' is Removing: creation waits for its terminal fold and catalog " "removal to complete; retry later", ns.string())); } @@ -5570,6 +5754,9 @@ NamespaceLifeId CasRefLedger::namespaceLife(const RootNamespace & ns) return rt->life; } invalidateRemovedCatalogLife(rt->life); + /// A stopped caller starts no work on a successor life. + if (recovery_error && Cas::ownerStopRequested()) + std::rethrow_exception(recovery_error); } } } @@ -5583,7 +5770,7 @@ NamespaceLifeId CasRefLedger::namespaceLife(const RootNamespace & ns) const auto entry_it = std::find_if(catalog.catalog.entries.begin(), catalog.catalog.entries.end(), [&](const CatalogEntry & entry) { return entry.ns == ns; }); if (entry_it != catalog.catalog.entries.end() && entry_it->state == NsState::Removing) - throwRemovingObserved(ns); + throwAdmissionRefused(removingObservedReason(ns)); const NamespaceLifeId life = entry_it != catalog.catalog.entries.end() && entry_it->state == NsState::Live @@ -5749,9 +5936,7 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( /// check (it only ever shrinks state; see `flushRefBatch`'s `state_growing` filter). ColdAdmission admission = beginColdAdmission(ns); CasOperation initial_op = mount_requests.admit(); - /// One deadline for every request that leads to the removal decision. The wait for the lane to - /// drain and for another removal attempt counts against it but is never cut short. - const Retry policy = initial_op.freeze(Retry::standard()); + const Retry policy = Retry::standard(); const CasRefCatalog::Snapshot initial_catalog = CasRefCatalog::read(initial_op, layout, policy); const auto initial_it = std::find_if(initial_catalog.catalog.entries.begin(), initial_catalog.catalog.entries.end(), [&](const CatalogEntry & entry) { return entry.ns == ns; }); @@ -5813,7 +5998,7 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( return {}; /// as for a name without a row { std::unique_lock queue_lock(ref_queue_mutex); - rt->cv.wait(queue_lock, [&] + Cas::waitStoppable(rt->cv, queue_lock, [&] { return !rt->removal_attempt_active; }); @@ -5834,22 +6019,6 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( return {}; } - /// Close the local positive lane BEFORE publishing `Removing`. Calls already admitted ahead of - /// this point drain first; later positive callers observe the flag in the same queue critical - /// section as enqueue and receive the typed retry-later refusal. The terminal item below is the one - /// deliberate exception. - { - std::unique_lock queue_lock(ref_queue_mutex); - rt->removal_admission_closed = true; - rt->cv.wait(queue_lock, [&] - { - return !rt->leader_active && rt->pending.empty(); - }); - } - - if (removal_attempt_hook_for_test) - removal_attempt_hook_for_test(); - /// Admitted under the runtime this drop closed and drained, not under the current generation: after a /// remount another runtime of this name may be open, and `Removing` must not land under it. const auto runtime_live = [&rt] @@ -5857,16 +6026,68 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( return !rt->catalog_life_invalidated.load(std::memory_order_acquire) && !rt->superseded_by_remount.load(std::memory_order_acquire); }; - CasOperation removal_op = mount_requests.resume(rt->admitted_fence_generation, runtime_live); std::optional observed_live; if (initial_it->state == NsState::Live) observed_live = *initial_it; bool removing_durable = false; bool removal_write_outcome_unknown = false; + + /// Resolves the removal state from a fresh catalog read. Returns true when the row is the durable + /// `Removing` of this life. Reopens the lane only when the row is exactly the observed `Live` one, + /// the mount fence is still admitted, and no `Removing` write may still land: that is, + /// `removal_write_outcome_unknown`, `rt->removal_write_may_land` and `rt->removing_observed` are all + /// clear. Every other case leaves the lane closed. + const auto resolveRemovalState = [&](CasOperation & op) + { + /// Owed to the closed lane: a stopped owner must not leave a proven `Live` lane closed. + const auto owed = Cas::OwnerScope::owed(); + const CasRefCatalog::Snapshot fresh = CasRefCatalog::read(op, layout, policy); + if (removal_reopen_read_hook_for_test) + removal_reopen_read_hook_for_test(); + const auto fresh_it = std::find_if(fresh.catalog.entries.begin(), fresh.catalog.entries.end(), + [&](const CatalogEntry & entry) { return entry.ns == ns; }); + if (observed_live + && fresh_it != fresh.catalog.entries.end() + && fresh_it->incarnation == observed_live->incarnation + && fresh_it->state == NsState::Removing) + { + return true; + } + if (observed_live && fresh_it != fresh.catalog.entries.end() && *fresh_it == *observed_live) + { + refuseUnlessAdmitted(op, "reopening the removal lane"); + std::lock_guard queue_lock(ref_queue_mutex); + if (!removal_write_outcome_unknown && !rt->removal_write_may_land && !rt->removing_observed) + { + rt->removal_admission_closed = false; + rt->cv.notify_all(); + } + } + return false; + }; + + std::optional removal_op; try { - refuseUnlessAdmitted(removal_op, "beginning removal"); - const CasRefCatalog::Snapshot snapshot = CasRefCatalog::read(removal_op, layout, policy); + /// Close the local positive lane BEFORE publishing `Removing`. Calls already admitted ahead of + /// this point drain first; later positive callers observe the flag in the same queue critical + /// section as enqueue and receive the typed retry-later refusal. The terminal item below is the one + /// deliberate exception. + { + std::unique_lock queue_lock(ref_queue_mutex); + rt->removal_admission_closed = true; + Cas::waitStoppable(rt->cv, queue_lock, [&] + { + return !rt->leader_active && rt->pending.empty(); + }); + } + + if (removal_attempt_hook_for_test) + removal_attempt_hook_for_test(); + + removal_op.emplace(mount_requests.resume(rt->admitted_fence_generation, runtime_live)); + refuseUnlessAdmitted(*removal_op, "beginning removal"); + const CasRefCatalog::Snapshot snapshot = CasRefCatalog::read(*removal_op, layout, policy); const auto entry_it = std::find_if(snapshot.catalog.entries.begin(), snapshot.catalog.entries.end(), [&](const CatalogEntry & entry) { return entry.ns == ns; }); if (entry_it == snapshot.catalog.entries.end()) @@ -5888,18 +6109,20 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( { observed_live = *entry_it; uint64_t removal_started_round = 0; - if (const auto got = removal_op.read(layout.gcStateKey(), policy)) + if (const auto got = removal_op->read(layout.gcStateKey(), policy)) removal_started_round = decodeGcState(got->bytes).round; /// The flag turns on at the first sent attempt of the `Live -> Removing` write. Before it nothing /// can land, so a failure may reopen the lane. After it every exception, `FencedOut` and - /// `EntryChanged` may follow an attempt that can still land. - removal_op.observeRequests(RequestObserver{ + /// `EntryChanged` may follow an attempt that can still land: a later refusal does not prove + /// that an earlier send cannot land, because the row has no revision field and, on a store + /// with content-derived ETags, unrelated churn can restore that send's precondition. + removal_op->observeRequests(RequestObserver{ .on_write_attempt = [&removal_write_outcome_unknown](uint32_t) { removal_write_outcome_unknown = true; }, .on_failure = {}, }); switch (CasRefCatalog::beginRemoving( - removal_op, layout, *observed_live, removal_started_round, policy)) + *removal_op, layout, *observed_live, removal_started_round, policy)) { case CasRefCatalog::BeginRemovingOutcome::Transitioned: case CasRefCatalog::BeginRemovingOutcome::AlreadyRemoving: @@ -5925,35 +6148,16 @@ DropNamespaceStats CasRefLedger::dropNamespaceImpl( } catch (...) { - /// Resolve an ambiguous transition before deciding whether this lane may reopen. `Removing` - /// under the same life is conclusive success. Reopening also needs a fresh exact `Live` row, the - /// same mount fence and no `Removing` observation of this runtime, which may land after the read; - /// every other case stays closed and propagates the original error. + /// An ambiguous transition is resolved before the lane may reopen; otherwise the original error propagates. + /// A failure before the removal operation exists sent nothing: its error propagates even if the row reads `Removing`. try { - /// A fresh standard window, not `policy`: an expired policy would fail this read at once and - /// leave a healthy table closed. - const CasRefCatalog::Snapshot fresh = CasRefCatalog::read(removal_op, layout); - if (removal_reopen_read_hook_for_test) - removal_reopen_read_hook_for_test(); - const auto fresh_it = std::find_if(fresh.catalog.entries.begin(), fresh.catalog.entries.end(), - [&](const CatalogEntry & entry) { return entry.ns == ns; }); - if (observed_live - && fresh_it != fresh.catalog.entries.end() - && fresh_it->incarnation == observed_live->incarnation - && fresh_it->state == NsState::Removing) - { - removing_durable = true; - } - else if (observed_live && fresh_it != fresh.catalog.entries.end() && *fresh_it == *observed_live) + if (removal_op) + removing_durable = resolveRemovalState(*removal_op); + else { - refuseUnlessAdmitted(removal_op, "reopening the removal lane"); - std::lock_guard queue_lock(ref_queue_mutex); - if (!removal_write_outcome_unknown && !rt->removal_write_may_land && !rt->removing_observed) - { - rt->removal_admission_closed = false; - rt->cv.notify_all(); - } + CasOperation reopen_op = mount_requests.resume(rt->admitted_fence_generation, runtime_live); + resolveRemovalState(reopen_op); } } catch (...) // NOLINT(bugprone-empty-catch) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h index b8df5f5484ade..70f38f82d8606 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefLedger.h @@ -36,6 +36,22 @@ namespace DB::Cas /// re-validating anything. enum class ResolveAudit : uint8_t { Emit, Deferred }; +/// Where a queued ref-log follower evaluates its wait condition: `Queued` while it waits stoppably, `Carved` once +/// its owner stopped and a leader owns its item, a wait it must not leave before the item is done. +enum class FollowerWaitPhase : uint8_t { Queued, Carved }; + +/// Thrown when a namespace's positive ref-mutation admission is closed for a removal: the call was refused +/// before its mutation was queued, so it wrote nothing and bound nothing. Catch sites match by type; the code +/// and text are those of `throwCasWriteRetryLater`. +class RefAdmissionRefusedException : public Exception +{ +public: + explicit RefAdmissionRefusedException(const Exception & retry_later) : Exception(retry_later) {} + + RefAdmissionRefusedException * clone() const override { return new RefAdmissionRefusedException(*this); } + void rethrow() const override { throw *this; } // NOLINT +}; + /// The complete state of one table's append lane. It is guarded by `RefTableRuntime::state_mutex`; /// there is no independent apply marker or durable-id floor whose combinations form a second, /// implicit state machine. @@ -332,7 +348,8 @@ class CasRefLedger /// name has no cold admission in flight here; the check is repeated inside the catalog lane. One scan /// read per call; each cancel may add its own catalog reads and conditional writes. `pause` replaces /// the mount plane's retry sleep. `stop_requested` is checked before the read and before each cancel, and - /// ends the call when true. An absent catalog is logged and ends the call; other failures throw. + /// returns when true; inside a cancel it is the owner check, which throws `ABORTED`. An absent catalog is + /// logged and ends the call; other failures throw. void cancelIdleOwnCreatingRows(const Liveness & alive, std::function pause, const std::function & stop_requested = {}); @@ -401,10 +418,13 @@ class CasRefLedger /// leave it untouched. void setCasRetrySleepForTest(std::function sleep_fn); - /// Replaces only ref-table recovery's token-aware retry delay seam for deterministic tests. + /// Replaces the sleep of a whole recovery retry pause; the pause's stop checks still run before it. void setRefRecoveryRetrySleepForTest( std::function &)> sleep_fn); + /// Replaces the sleep of one slice of a recovery retry pause, keeping its slicing and stop checks. + void setRefRecoveryRetrySliceSleepForTest(std::function sleep_fn); + /// Test-only observability and fault-injection seams for recovery, wedges, cleanup, and publication. /// The counters expose recovery and publication progress; wedge methods create and inspect the /// unresolved-`PUT` state; cleanup methods expose sweep eligibility; publication methods expose @@ -442,6 +462,12 @@ class CasRefLedger std::optional lastEpochSealForTest(const RootNamespace & ns); /// Returns the append lane state of `ns` without forcing recovery. RefLaneState laneStateForTest(const RootNamespace & ns); + struct RemovalFlagsForTest + { + bool attempt_active = false; + bool admission_closed = false; + }; + RemovalFlagsForTest removalFlagsForTest(const RootNamespace & ns); /// Reports whether recovery or a prior incomplete sweep requires stale-precommit cleanup. bool needsStalePrecommitSweepForTest(const RootNamespace & ns); /// Waits until all background snapshot publications for `ns` have completed. @@ -530,6 +556,10 @@ class CasRefLedger /// Installs the pre-tenure fault seam (see `ref_pre_tenure_hook_for_test`). void setRefPreTenureHookForTest(std::function hook) { ref_pre_tenure_hook_for_test = std::move(hook); } + /// Runs on a queued follower each time it evaluates its wait condition, under the queue mutex. It must not + /// lock anything, and it runs as `noexcept`: a throw terminates rather than unwinding out of the `Carved` wait. + void setRefFollowerWaitHookForTest(std::function hook) { ref_follower_wait_hook_for_test = std::move(hook); } + /// Pauses an ordinary append after it captured an exact runtime but before recovery or enqueue. void setAppendAfterRuntimeCaptureHookForTest(std::function hook) { @@ -840,10 +870,14 @@ class CasRefLedger std::function cancel_inflight_builds; std::function recovery_pre_first_request_hook_for_test; - /// Backoff sleep used by `ensureRefTableRecovered`'s transient-retry loop. Default is an - /// interruptible slice-sleep (bails early if `fence_ok_fn` drops or detached teardown starts); - /// `setCasRetrySleepForTest` overrides it (a unit test injects a clock-advancing no-op). - std::function &)> recovery_retry_sleep_fn; + /// The sleep of one slice of `pauseBeforeRecoveryRetry`. + std::function recovery_retry_slice_sleep_fn; + /// When set, `pauseBeforeRecoveryRetry` sleeps the whole pause through it, after the same checks. + std::function &)> recovery_retry_pause_sleep_for_test; + + /// The backoff of `ensureRefTableRecovered`'s retry loop, in `kOwnerStopSlice` slices. Returns early on fence + /// loss, teardown, or a stopped query outside `owed`; throws a stopped background owner's verdict. + void pauseBeforeRecoveryRetry(uint64_t total_ms, const std::optional & token); /// One queued append caller. `build_ops` is invoked at most once by the flush leader and returns the /// caller's operations rather than mutating storage directly. Completion fields are synchronized by @@ -1139,6 +1173,12 @@ class CasRefLedger /// idle (baton un-taken, the caller's item un-enqueued), never a permanently non-idle namespace with /// no live leader. Null in production. See `appendRefOps`. std::function ref_pre_tenure_hook_for_test; + std::function ref_follower_wait_hook_for_test; + void runRefFollowerWaitHook(FollowerWaitPhase phase) const noexcept + { + if (ref_follower_wait_hook_for_test) + ref_follower_wait_hook_for_test(phase); + } /// Test-only hook fired at each carve/validation phase point (see `CarvePhaseForTest`); null in /// production. @@ -1275,10 +1315,8 @@ class CasRefLedger /// Every `createNamespace`/`completeCreation`/`reconcileStaleCreator` outcome that writes nothing /// (`FencedOut`, `Superseded`, a reconciled entry, `EntryChanged`) re-reads the catalog and loops; /// `CreatorFenceStillLive` throws the retry-later class, which this function's caller (the transient - /// retry loop) or a higher one re-drives. One `Retry` is frozen before the loop and shared by every - /// read and every protocol call it makes, so the whole resolution ends within one standard window; - /// a re-read forced by a competing actor is paced by a jittered sleep, and an iteration cap is the - /// secondary bound. + /// retry loop) or a higher one re-drives. A re-read forced by a competing actor is paced by a + /// jittered sleep, and a cap on rounds ends the loop. NamespaceLifeId resolveNamespaceLife( const RootNamespace & ns, uint64_t admitted_generation, uint64_t live_epoch, bool * lifecycle_refusal = nullptr); @@ -1298,10 +1336,12 @@ class CasRefLedger /// reported through the retry-later class (the caller should retry, against the FRESH incarnation), /// so without it the transient loop reads the stop as a blip and re-drives the very work the remount /// just stopped -- while the barrier blocks waiting for that recovery to finish. + /// `unresolved_sent` is set when the walk throws because its stamp or tombstone was sent and stays + /// unresolved, so the caller can keep that exit after its owner stops. std::optional runRecoveryWalkOnce( const RootNamespace & ns, RefTableRuntime & rt, uint64_t admitted_generation, const LiveEpochPair & live, const std::optional & retained_attempt, std::optional & hole_detail, - bool & cancelled, const std::optional & token = std::nullopt); + bool & cancelled, bool & unresolved_sent, const std::optional & token = std::nullopt); /// The I/O-boundary poll of the walk: is this recovery still entitled to continue? Detached /// teardown, self-remount cancellation, and a runtime already detached by self-remount each @@ -1335,10 +1375,17 @@ class CasRefLedger /// Every item this leader becomes responsible for -- its own `own` plus each item a flush removes /// from `pending` to form a batch -- is recorded into `owned_items`, so the caller's leadership guard /// can complete + de-pend any that a flush leaves unfinished on an exceptional exit. + /// Every leader flushes in its caller's thread group under `OwnerScope::shared`. Its own item stays withdrawable by + /// its background owner until carved. void runRefQueueLeader(const RootNamespace & ns, const std::shared_ptr & rt, const std::shared_ptr & own, std::vector> & owned_items); + /// Waits, with `lk` held on return and on throw, until `item` is done or the lane needs a leader. + /// A stopped follower withdraws its queued item or waits for its carved result. + void waitAsFollower(const std::shared_ptr & rt, const std::shared_ptr & item, + std::unique_lock & lk); + /// Validates, durably appends, and applies one compatible batch while preserving copy-before-commit /// and apply-after-commit ordering -- the LIVE state is still only ever advanced once the object is /// durable; `commitRefChunk`'s pre-`PUT` apply targets a private candidate that nothing else can @@ -1348,7 +1395,8 @@ class CasRefLedger /// `ref_txn_max_ops`, the validation loop emits SEVERAL ref-log transactions in one tenure via /// `commitRefChunk` -- each a complete commit boundary. void flushRefBatch(const RootNamespace & ns, const std::shared_ptr & rt, - std::vector> & owned_items); + std::vector> & owned_items, + const std::shared_ptr & own, const std::function & owner_check); /// The lane's tombstone step, run by `flushRefBatch` before the batch copies its working state. /// True: the chain epoch equals the live epoch, or the stream is terminal, and the batch may proceed. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.cpp index ef4288fc22c72..0ccaad782a09a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -139,7 +140,9 @@ bool failureJudgedAgainstCkpt(int error_code) bool restartsOnMovedBase(int error_code, CasOperation & op, const Layout & layout, const NamespaceLifeId & life, const Etag & token) { - return failureJudgedAgainstCkpt(error_code) && ckptTokenMoved(op, layout, life, token); + /// A query's stored cause says nothing about the chain, whatever its code. + return failureJudgedAgainstCkpt(error_code) && !isQueryStoredCause(std::current_exception()) + && ckptTokenMoved(op, layout, life, token); } RefTxnId RefTableState::chainNextId(uint64_t life_epoch) const diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.h index 1c3f496ea542a..7a774aa783664 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasRefProtocol.h @@ -78,8 +78,9 @@ bool ckptTokenMoved(CasOperation & op, const Layout & layout, const NamespaceLif /// Whether a failure with this code is judged against `_ckpt` at all: only `CORRUPTED_DATA` is. bool failureJudgedAgainstCkpt(int error_code); -/// For a failure caught while reading a chain grounded on `_ckpt` `token`: true asks the reader to restart, -/// false to rethrow. Only `CORRUPTED_DATA` restarts, and only when `_ckpt` moved or is absent, because +/// For a failure caught while reading a chain grounded on `_ckpt` `token`, called inside its handler: true asks the +/// reader to restart, false to rethrow. Only `CORRUPTED_DATA` restarts, never a query's stored cause, and only when +/// `_ckpt` moved or is absent, because /// cleanup may then have emptied keys the reader relied on; any other code returns false without a /// request. When the `_ckpt` re-read itself throws, its store error replaces the caught exception: the /// caller fails closed as retry-later and this attempt reports no corruption verdict. diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp index aba6503d21a38..e9f4110f18d2a 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Pool/CasServerRoot.cpp @@ -1968,7 +1968,7 @@ Observation MountLeaseRenewer::readUntilObserved( uint64_t pause_ms = Retry::pauseAfterAttempt(*policy.attempt_spacing_ms, write_started_boot_ms, boot_clock()); while (op.admitted()) { - op.pause(pause_ms); + op.sleepFor(pause_ms); try { std::optional got = op.read(key, policy); @@ -2080,7 +2080,7 @@ MountRenewResult MountLeaseRenewer::renewOn( { break; } - op.pause(pause_ms); + op.sleepFor(pause_ms); written = op.replace(key, body, expected, policy); } } @@ -2176,6 +2176,8 @@ MountRenewResult MountLeaseRenewer::renewOn( case GaveUp::Why::Unresolved: classification = MountRenewTerminalClassification::Unresolved; break; + case GaveUp::Why::Attempts: + throw Exception(ErrorCodes::LOGICAL_ERROR, "A mount renewal write is never capped by a decision count"); } markMountRenewTermination(classification); result.failure = makeCasWriteRetryLaterExceptionPtr(fmt::format( diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasBoundedRun.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasBoundedRun.h index af193e425faad..9414c3a036953 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasBoundedRun.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Primitives/CasBoundedRun.h @@ -1,5 +1,7 @@ #pragma once +#include #include +#include #include #include #include @@ -57,12 +59,13 @@ void runBounded(ThreadPool & pool, ThreadName thread_name, size_t count, const J { if constexpr (HasBeforeSubmit) job.beforeSubmit(i); - handles.emplace_back(runner.enqueueAndGiveOwnership([&job, &failed, i] + handles.emplace_back(runner.enqueueAndGiveOwnership([&job, &failed, i, group = CurrentThread::getGroup()] { if (failed.load()) return; try { + throwUnlessInThreadGroup(group, "CAS tool worker"); job(i); } catch (...) diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasDecommission.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasDecommission.cpp index 973d6de56c331..b13f3c5f50e5c 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasDecommission.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasDecommission.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -54,13 +55,16 @@ std::string_view removalName(Removal r) /// /// A per-object failure — a backend exception, a `Mismatch` or `Gone` outcome, or an object /// disappearing between `LIST` and `HEAD` — is recorded as a warning and does not prevent the remaining -/// objects from being attempted while `op` is still admitted. Returns only the objects whose -/// exact-incarnation delete was reported as `Removed`. +/// objects from being attempted while `op` is still admitted. A stopped owner ends the drain at the next object with +/// its verdict; a delete that failed after its query stopped ends it with that failure. +/// Returns only the objects whose exact-incarnation delete was reported as `Removed`. uint64_t deleteListedPrefix(CasOperation & op, const String & prefix, std::vector & warnings) { uint64_t deleted = 0; op.forEachListedKey(prefix, [&](const ListedKey & listed) { + throwIfQueryStopped(); + throwIfBackgroundStopped(); try { std::optional etag = listed.etag; @@ -84,6 +88,7 @@ uint64_t deleteListedPrefix(CasOperation & op, const String & prefix, std::vecto } catch (...) { + rethrowIfStoppedOwnersFailure(); warnings.push_back("decommission drain: " + listed.key + " delete failed: " + getCurrentExceptionMessage(/*with_stacktrace=*/false)); return op.admitted(); @@ -350,6 +355,7 @@ void drainVictim(Pool & admin, const CasRefCatalog::Snapshot & catalog_cut, cons std::vector> owned_lives; for (const CatalogEntry & entry : catalog_cut.catalog.entries) { + throwIfQueryStopped(); if (entry.ns.string() != victim_srid && !entry.ns.string().starts_with(victim_namespace_prefix)) continue; const auto life = catalog_cut.life_index.resolve(entry.incarnation); @@ -361,6 +367,7 @@ void drainVictim(Pool & admin, const CasRefCatalog::Snapshot & catalog_cut, cons for (const auto & [selected_entry, life] : owned_lives) { + throwIfQueryStopped(); const RootNamespace & ns = life.ns; const String & ns_str = ns.string(); @@ -428,15 +435,24 @@ void drainVictim(Pool & admin, const CasRefCatalog::Snapshot & catalog_cut, cons { const String debris_prefix = admin.layout().casManifestsServerPrefix(victim_srid); std::set> groups; /// (namespace, writer epoch, build sequence) - op.forEachListedKey(debris_prefix, [&](const ListedKey & listed) + /// Checked before each page is requested and again once it arrives, for a kill that landed during the fetch. + String cursor; + do { - if (const auto parsed = admin.layout().parseManifestKey(listed.key)) - groups.emplace(parsed->root_namespace.string(), parsed->ref.writer_epoch, parsed->ref.build_sequence); - return true; - }, Retry::standard()); + throwIfQueryStopped(); + ListPage page = op.list(debris_prefix, cursor, CasOperation::kCasListPageKeys, Retry::standard()); + throwIfQueryStopped(); + for (const ListedKey & listed : page.keys) + if (const auto parsed = admin.layout().parseManifestKey(listed.key)) + groups.emplace(parsed->root_namespace.string(), parsed->ref.writer_epoch, parsed->ref.build_sequence); + cursor = std::move(page.next_cursor); + } while (!cursor.empty()); for (const auto & [ns_str, writer_epoch, build_sequence] : groups) + { + throwIfQueryStopped(); report.manifest_debris_removed += sweepNamespace( admin, RootNamespace(ns_str), BuildPrefix{writer_epoch, build_sequence}, &report.warnings); + } } /// Drain the victim's own `/staging//` area. The live-mount staging helper uses diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasFsck.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasFsck.cpp index e47d61b8e1c1f..352e831528260 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasFsck.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasFsck.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -490,7 +491,8 @@ std::optional walkRefStream( } catch (const Exception & e) { - if (e.code() == ErrorCodes::TIMEOUT_EXCEEDED) + /// A query's stored cause is no finding about the chain, whatever its code. + if (e.code() == ErrorCodes::TIMEOUT_EXCEEDED || isQueryStoredCause(std::current_exception())) throw; deadline.rethrowIfOutOfTime(op, e, kWalkingRefs); record_failure(e.code() == ErrorCodes::CORRUPTED_DATA, e.message()); @@ -2041,7 +2043,8 @@ LegacyMarkerRemoval removeLegacyMarkers(Pool & pool, const std::vector & { if (on_progress) on_progress(deleted.load()); - e.addMessage(fmt::format("{} legacy marker(s) deleted before the stop; run again to continue", deleted.load())); + addMessageUnlessQueryStoredCause(e, fmt::format("{} legacy marker(s) deleted before the stop; run again to continue", + deleted.load())); throw; } return {deleted.load(), changed.load()}; diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasMigratePool.cpp b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasMigratePool.cpp index bd4493b87ffb7..14ee8473bd902 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasMigratePool.cpp +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasMigratePool.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -544,7 +545,7 @@ class Migration uint64_t last_progress_ms = pool.bootMsNow(); while (!watched.empty()) { - op.pause(options.poll_step_ms); + op.sleepFor(options.poll_step_ms); /// Taken before the reads: it can confirm that a token held, never date a sighting. const uint64_t sample_ms = pool.bootMsNow(); if (sample_ms >= last_progress_ms + kProgressEveryMs) @@ -577,7 +578,7 @@ class Migration } say(fmt::format("M2: waiting {} ms in which no mount slot and no GC lease may move", grace_ms)); - op.pause(grace_ms); + op.sleepFor(grace_ms); checkUnchanged(tokens, pairs, Window::BeforeFloor); say(fmt::format("M2: {} mount slot(s), {} fenced; no slot and no GC lease moved in {} ms", slot_keys.size(), fenced, grace_ms)); @@ -705,8 +706,8 @@ class Migration { if (e.code() != ErrorCodes::CORRUPTED_DATA) throw; - e.addMessage("M3: GC of this build refuses a source-edge run of the fold seal that gc/state adopts. The run " - "stopped before the floor was raised to 4"); + addMessageUnlessQueryStoredCause(e, "M3: GC of this build refuses a source-edge run of the fold seal that " + "gc/state adopts. The run stopped before the floor was raised to 4"); throw; } } @@ -836,8 +837,8 @@ class Migration } catch (Exception & e) { - e.addMessage("an intent create failed; nothing was written after the intents, and a rerun passes only once the " - "store accepts the create"); + addMessageUnlessQueryStoredCause(e, "an intent create failed; nothing was written after the intents, and a rerun " + "passes only once the store accepts the create"); throw; } if (!result.confirmed()) @@ -965,8 +966,8 @@ class Migration } catch (Exception & e) { - e.addMessage("M9: {} marker(s) removed in earlier pages; the pool is migrated, and a rerun or `cas-fsck --fix " - "legacy-markers` removes the rest", report.legacy_markers_deleted); + addMessageUnlessQueryStoredCause(e, fmt::format("M9: {} marker(s) removed in earlier pages; the pool is migrated, and " + "a rerun or `cas-fsck --fix legacy-markers` removes the rest", report.legacy_markers_deleted)); throw; } meter.add(page.size()); diff --git a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasToolDeadline.h b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasToolDeadline.h index 995e38f68a0b3..ed7815fc2efc1 100644 --- a/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasToolDeadline.h +++ b/src/Disks/DiskObjectStorage/MetadataStorages/ContentAddressed/Tools/CasToolDeadline.h @@ -66,8 +66,8 @@ class ToolDeadline check(phase); if (!requests) return Retry::standard(); - const Retry chosen = op.freeze(Retry::standard()).cappedAt(deadline_ms); - if (!op.oneAttemptFitsBefore(*chosen.policy_deadline_ms)) + const Retry chosen = Retry::standard().cappedAt(deadline_ms); + if (!op.oneAttemptFits(chosen)) throwExceeded(phase); return chosen; } diff --git a/src/Disks/tests/cas_killable_query.h b/src/Disks/tests/cas_killable_query.h new file mode 100644 index 0000000000000..a4b3157ce5ec1 --- /dev/null +++ b/src/Disks/tests/cas_killable_query.h @@ -0,0 +1,219 @@ +#pragma once + +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace DB::ErrorCodes +{ +extern const int ABORTED; +} + +/// Skips a test that enables a fail point in a build without libfiu, where enabling one throws `SUPPORT_IS_DISABLED`. +#define CAS_SKIP_WITHOUT_FAILPOINTS() \ + do \ + { \ + if constexpr (!::DB::Cas::tests::kFailPointsAvailable) \ + GTEST_SKIP() << "built without libfiu, so fail points are unavailable"; \ + } while (false) + +namespace DB::Cas::tests +{ + +inline constexpr bool kFailPointsAvailable = USE_LIBFIU; + +/// A query registered in the process list, so a kill reaches CAS code through the thread group as it +/// does in the server. Construct it on a thread that has a `ThreadStatus`; the constructing +/// thread stays attached. Destroy it after every worker thread joined. +struct CasKillableQuery +{ + explicit CasKillableQuery(ContextPtr global); + ~CasKillableQuery(); + + CasKillableQuery(const CasKillableQuery &) = delete; + CasKillableQuery & operator=(const CasKillableQuery &) = delete; + + /// For a worker thread with its own `ThreadStatus`, as a query's thread pool attaches its workers. + void attachCurrentThread(); + + /// `KILL QUERY`; with `cause`, the query throws that exception instead of `QUERY_WAS_CANCELLED`. + void kill(std::exception_ptr cause = nullptr); + + ContextMutablePtr context; + ThreadGroupPtr group; + ProcessList::EntryPtr entry; + QueryStatusPtr status; +}; + +/// Runs `body` on a fresh thread, with a `ThreadStatus` when `with_thread_status`, joins it, and rethrows on the calling +/// thread an exception that left `body`, which would otherwise terminate the test process. Thread-local owner +/// state and the gtest main thread's missing `ThreadStatus` make a raw thread the only clean starting point. +template +void onThread(bool with_thread_status, Body && body) +{ + std::exception_ptr error; + std::thread worker([&] + { + std::optional thread_status; + if (with_thread_status) + thread_status.emplace(); + try + { + body(); + } + catch (...) + { + error = std::current_exception(); + } + }); + worker.join(); + if (error) + std::rethrow_exception(error); +} + +/// Runs `body(query)` on a fresh thread with a `ThreadStatus`, attached to a fresh query registered in the process +/// list as a SQL query's thread is, and joins it. +template +void onKillableQueryThread(Body && body) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + body(query); + }); +} + +enum class StoppedBy : uint8_t { Background, Query }; + +inline const char * nameOf(StoppedBy owner) +{ + return owner == StoppedBy::Background ? "background owner" : "killed query"; +} + +/// A background owner on the calling thread whose check throws `ABORTED` once `*stopped` is set. +inline OwnerScope backgroundOwnerStoppedBy(const std::shared_ptr> & stopped) +{ + return OwnerScope::background([stopped] + { + if (stopped->load()) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); +} + +/// The stop of `owner`: kills `query`, or sets `*background_stopped`. +inline std::function stopperOf(StoppedBy owner, CasKillableQuery & query, + const std::shared_ptr> & background_stopped) +{ + if (owner == StoppedBy::Query) + return [&query] { query.kill(); }; + return [background_stopped] { *background_stopped = true; }; +} + +namespace client_like_detail +{ + +template +auto checkedOnThrow(Call && call) +{ + try + { + return call(); + } + catch (...) + { + CurrentThread::checkIfNotCancelled(); + throw; + } +} + +template +auto checkedUnless(Call && call, Succeeded && succeeded) +{ + auto answer = checkedOnThrow(std::forward(call)); + if (!succeeded(answer)) + CurrentThread::checkIfNotCancelled(); + return answer; +} + +} + +/// Forwards to `inner` and, as the S3 client does after every unsuccessful response, checks the current +/// thread's query on each miss, conflict or failure before answering. Success is never checked. The +/// sentinel probe stays the base default, which goes through the decorated `head` and `read`. +class CasClientLikeBackend final : public Backend +{ +public: + explicit CasClientLikeBackend(BackendPtr inner_) : inner(std::move(inner_)) {} + + std::optional read(const String & key, TransportAccess & access) override + { + return client_like_detail::checkedUnless([&] { return inner->read(key, access); }, [](const auto & r) { return r.has_value(); }); + } + + std::optional head(const String & key, TransportAccess & access) override + { + return client_like_detail::checkedUnless([&] { return inner->head(key, access); }, [](const auto & r) { return r.has_value(); }); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + return client_like_detail::checkedOnThrow([&] { return inner->list(prefix, cursor, limit, access); }); + } + + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + return client_like_detail::checkedUnless( + [&] { return inner->remove(key, expected_value, access); }, [](RawRemoval r) { return r == RawRemoval::Removed; }); + } + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + return client_like_detail::checkedUnless( + [&] { return inner->write(key, bytes, expected_value, access); }, [](const auto & r) { return r.has_value(); }); + } + + std::unique_ptr stream(const String & key, TransportAccess & access) override + { + return client_like_detail::checkedUnless([&] { return inner->stream(key, access); }, [](const auto & r) { return r != nullptr; }); + } + + void publish(const BlobPublishRequest & request, TransportAccess & access) override + { + client_like_detail::checkedOnThrow([&] { inner->publish(request, access); }); + } + + void removeManyWriteOnce(const std::vector & keys, TransportAccess & access) override + { + client_like_detail::checkedOnThrow([&] { inner->removeManyWriteOnce(keys, access); }); + } + + Dialect dialect() const override { return inner->dialect(); } + bool supportsListTokens() const override { return inner->supportsListTokens(); } + uint64_t attemptTimeoutMs() const override { return inner->attemptTimeoutMs(); } + uint64_t attemptEnvelopeMs() const override { return inner->attemptEnvelopeMs(); } + size_t bulkDeleteKeyLimit() const override { return inner->bulkDeleteKeyLimit(); } + bool refreshCredentials() override { return inner->refreshCredentials(); } + void checkPoolPreconditions() override { inner->checkPoolPreconditions(); } + void checkSkipAccessCheckSupport() override { inner->checkSkipAccessCheckSupport(); } + void checkConditionalWriteSingleAttemptSupport() override { inner->checkConditionalWriteSingleAttemptSupport(); } + +private: + BackendPtr inner; +}; + +} diff --git a/src/Disks/tests/cas_test_helpers.h b/src/Disks/tests/cas_test_helpers.h index 84faee2796fae..d2afab191288c 100644 --- a/src/Disks/tests/cas_test_helpers.h +++ b/src/Disks/tests/cas_test_helpers.h @@ -132,6 +132,24 @@ inline String tokenText(const std::optional & token) namespace DB::Cas::tests { +/// The `DB::Exception` code `call` throws, -1 for any other exception, 0 when it returns. +inline int exceptionCodeOf(const std::function & call) +{ + try + { + call(); + } + catch (const DB::Exception & e) + { + return e.code(); + } + catch (...) + { + return -1; + } + return 0; +} + /// A `CasRequests` over an always-open fence, for a fixture that has a backend but no mounted pool. /// Every operation admitted from it holds a reference to it, so it must be named and outlive them. inline DB::Cas::CasRequests openRequestsForTest(DB::Cas::BackendPtr backend) @@ -2387,6 +2405,49 @@ class CountingBackend : public DB::Cas::InMemoryBackend uint64_t publish_total = 0; }; +/// Whether `ms` is a pause after the `n`-th clean lost race of one call: `base <= ms <= base + base / 4`, with +/// `base = min(750, 40 * (n - 1))`, so the first is exactly 0. +inline ::testing::AssertionResult isConflictPause(uint64_t ms, uint32_t n) +{ + const uint64_t base = std::min(750, 40ull * (n - 1)); + if (ms >= base && ms <= base + base / 4) + return ::testing::AssertionSuccess(); + return ::testing::AssertionFailure() << ms << " ms is not the pause after clean loss " << n << ": expected [" + << base << ", " << base + base / 4 << "]"; +} + +/// The requests on `key` as one letter each (`R` read, `H` head, `W` write), with a mark labelled +/// `pause` as `P`. Requests between a `rival{` mark and the next `}rival` mark are left out, so a test +/// sees only its own caller's requests and where a competitor's commits fell among them. +inline String renderOwnRequests(const CountingBackend & backend, const String & key) +{ + String out; + bool in_rival = false; + for (const JournalEntry & entry : backend.journal()) + { + if (entry.verb == JournalVerb::Mark) + { + if (entry.detail == "rival{") + in_rival = true; + else if (entry.detail == "}rival") + in_rival = false; + else if (entry.detail == "pause" && !in_rival) + out += 'P'; + continue; + } + if (in_rival || entry.keys != std::vector{key}) + continue; + switch (entry.verb) + { + case JournalVerb::Read: out += 'R'; break; + case JournalVerb::Head: out += 'H'; break; + case JournalVerb::Write: out += 'W'; break; + default: out += '?'; break; + } + } + return out; +} + /// Runs a hook once, on the first HEAD of one key after `armOnHead`, before that HEAD is served and with no /// backend lock held. A writer that commits there lands after the round's cut and before the redelete /// observes the blob. diff --git a/src/Disks/tests/cas_time_taking_backend.h b/src/Disks/tests/cas_time_taking_backend.h new file mode 100644 index 0000000000000..5ff2e92e992d2 --- /dev/null +++ b/src/Disks/tests/cas_time_taking_backend.h @@ -0,0 +1,257 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace DB::Cas::tests +{ + +/// A clock a test moves by exact amounts. A sleep moves it by one millisecond more than it was asked +/// for, because a jittered pause can be zero and a clock that stands still never closes a window. +/// Held by `shared_ptr`: a pool keeps the closures and can outlive the test's frame. +class ManualClock +{ +public: + explicit ManualClock(uint64_t start_ms = 1'000'000) : now_ms(start_ms) {} + + uint64_t now() const { return now_ms.load(); } + void advance(uint64_t ms) { now_ms.fetch_add(ms); } + + static std::function nowFnOf(std::shared_ptr owned) + { + return [clock = std::move(owned)] { return clock->now(); }; + } + static std::function sleepFnOf(std::shared_ptr owned) + { + return [clock = std::move(owned)](uint64_t ms) { clock->advance(ms + 1); }; + } + +private: + std::atomic now_ms; +}; + +/// A store in which a chosen request takes time: the clock the request engine reads moves INSIDE the +/// request, after the engine bound its policy and before the answer comes back. An instantaneous store +/// cannot show a deadline that was fixed before a long step and is consulted after it. +class TimeTakingBackend final : public CountingBackend +{ +public: + enum class Verb : uint8_t { Read, Head, List, Write, Remove, Publish, Stream }; + enum class Ending : uint8_t + { + Answered, + /// The request fails with a timeout and changes nothing. + LostBeforeLanding, + /// The request takes effect and its response is lost. + LostAfterLanding, + }; + + /// One request as the store received it. + struct Seen + { + Verb verb; + String key; + uint64_t at_ms; + }; + + void useClock(std::shared_ptr clock_) + { + std::lock_guard lock(rules_mutex); + clock = std::move(clock_); + } + + /// The clock the journal stamps requests with. + void stampWith(std::function now_ms_) + { + std::lock_guard lock(rules_mutex); + now_ms = std::move(now_ms_); + } + + /// Each of the next `times` matching requests takes `takes_ms` and then ends as `ending`. + void arm(Verb verb, std::function matches, uint64_t takes_ms, size_t times = 1, + Ending ending = Ending::Answered) + { + armWith(verb, std::move(matches), [this, takes_ms] + { + std::shared_ptr current; + { + std::lock_guard lock(rules_mutex); + current = clock; + } + if (current && takes_ms) + current->advance(takes_ms); + }, times, ending); + } + + /// `while_in_flight` runs inside each of the next `times` matching requests, on the requesting + /// thread and with no lock of this backend held: it is what happens elsewhere while the request + /// is in flight, and it may send requests of its own. + void armWith(Verb verb, std::function matches, std::function while_in_flight, + size_t times = 1, Ending ending = Ending::Answered) + { + std::lock_guard lock(rules_mutex); + rules.push_back(Rule{verb, std::move(matches), std::move(while_in_flight), times, ending}); + } + + /// The keys of the requests a rule applied to, in order. + std::vector slowedKeys() const + { + std::lock_guard lock(rules_mutex); + return slowed_keys; + } + + /// Every request received, in order, a refused or failed one included. + std::vector seen() const + { + std::lock_guard lock(rules_mutex); + return seen_requests; + } + + /// Requests of `verb` to `key` received at or after position `from` of the journal. + size_t seenSince(size_t from, Verb verb, const String & key) const + { + std::lock_guard lock(rules_mutex); + size_t count = 0; + for (size_t i = from; i < seen_requests.size(); ++i) + if (seen_requests[i].verb == verb && seen_requests[i].key == key) + ++count; + return count; + } + + size_t seenCount() const + { + std::lock_guard lock(rules_mutex); + return seen_requests.size(); + } + + /// Publications REQUESTED for `key`, whether or not they stored anything. + uint64_t publicationsOf(const String & key) const + { + std::lock_guard lock(rules_mutex); + const auto it = publications.find(key); + return it == publications.end() ? 0 : it->second; + } + + uint64_t serverSideCopiesOf(const String & key) const + { + std::lock_guard lock(rules_mutex); + const auto it = server_side_copies.find(key); + return it == server_side_copies.end() ? 0 : it->second; + } + + std::optional read(const String & key, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::Read, key), "read"); + return CountingBackend::read(key, access); + } + + std::optional head(const String & key, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::Head, key), "head"); + return CountingBackend::head(key, access); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::List, prefix), "list"); + return CountingBackend::list(prefix, cursor, limit, access); + } + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + const Ending ending = spend(Verb::Write, key).value_or(Ending::Answered); + failIfLostBeforeLanding(ending, "write"); + auto answer = CountingBackend::write(key, bytes, expected_value, access); + if (ending == Ending::LostAfterLanding) + throw Poco::TimeoutException("TimeTakingBackend: the write was applied and its response was lost"); + return answer; + } + + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::Remove, key), "remove"); + return CountingBackend::remove(key, expected_value, access); + } + + std::unique_ptr stream(const String & key, TransportAccess & access) override + { + failIfLostBeforeLanding(spend(Verb::Stream, key), "stream"); + return CountingBackend::stream(key, access); + } + + void publish(const BlobPublishRequest & request, TransportAccess & access) override + { + { + std::lock_guard lock(rules_mutex); + ++publications[request.destination_key]; + if (std::holds_alternative(request.publication)) + ++server_side_copies[request.destination_key]; + } + const Ending ending = spend(Verb::Publish, request.destination_key).value_or(Ending::Answered); + if (ending == Ending::LostBeforeLanding) + throw Poco::TimeoutException("TimeTakingBackend: the publication timed out and stored nothing"); + CountingBackend::publish(request, access); + if (ending == Ending::LostAfterLanding) + throw Poco::TimeoutException("TimeTakingBackend: the publication was stored and its response was lost"); + } + +private: + struct Rule + { + Verb verb; + std::function matches; + std::function while_in_flight; + size_t remaining; + Ending ending; + }; + + static void failIfLostBeforeLanding(std::optional ending, const char * verb) + { + if (ending == Ending::LostBeforeLanding) + throw Poco::TimeoutException(String("TimeTakingBackend: the ") + verb + " timed out"); + } + + std::optional spend(Verb verb, const String & key) + { + std::function while_in_flight; + Ending ending = Ending::Answered; + { + std::lock_guard lock(rules_mutex); + seen_requests.push_back(Seen{verb, key, now_ms ? now_ms() : 0}); + auto rule = rules.begin(); + for (; rule != rules.end(); ++rule) + if (rule->verb == verb && rule->remaining != 0 && rule->matches(key)) + break; + if (rule == rules.end()) + return std::nullopt; + --rule->remaining; + slowed_keys.push_back(key); + while_in_flight = rule->while_in_flight; + ending = rule->ending; + } + while_in_flight(); + return ending; + } + + mutable std::mutex rules_mutex; + std::shared_ptr clock; + std::function now_ms; + std::vector rules; + std::vector slowed_keys; + std::vector seen_requests; + std::map publications; + std::map server_side_copies; +}; + +} diff --git a/src/Disks/tests/gtest_cas_blob_indegree.cpp b/src/Disks/tests/gtest_cas_blob_indegree.cpp index 29f3dcf8450dd..8ba90b78f60b6 100644 --- a/src/Disks/tests/gtest_cas_blob_indegree.cpp +++ b/src/Disks/tests/gtest_cas_blob_indegree.cpp @@ -10,9 +10,11 @@ #if USE_AWS_S3 #include #endif +#include #include #include #include +#include #include #include #include @@ -1145,6 +1147,96 @@ TEST(CASSourceEdgeRun, OnlyAnAbsentRunReachesTheHook) } } +namespace +{ + +/// Serves the run's header line, then on the next refill calls `on_refill` and throws the query's stored +/// exception, as an S3 body whose next `GET` fails after a kill does. +class HeaderThenStoppedReadBuffer : public DB::ReadBuffer +{ +public: + HeaderThenStoppedReadBuffer(String header_, std::function on_refill_) + : DB::ReadBuffer(nullptr, 0), header(std::move(header_)), on_refill(std::move(on_refill_)) + { + } + +private: + bool nextImpl() override + { + if (!served) + { + served = true; + BufferBase::set(header.data(), header.size(), 0); + return true; + } + on_refill(); + DB::CurrentThread::checkIfNotCancelled(); + return false; + } + + String header; + std::function on_refill; + bool served = false; +}; + +class HeaderThenStoppedBackend : public InMemoryBackend +{ +public: + std::unique_ptr stream(const String & key, TransportAccess & access) override + { + auto raw = InMemoryBackend::read(key, access); + if (!raw) + return nullptr; + return std::make_unique(raw->bytes.substr(0, raw->bytes.find('\n') + 1), on_refill); + } + + std::function on_refill; +}; + +} + +/// A run row read whose stream refill fails with the query's stored exception must not annotate it: the query +/// rethrows that one object to every thread it stops. The stored code is `CORRUPTED_DATA`, the code the row catch +/// annotates. +TEST(CASSourceEdgeRun, RowReadLeavesTheStoredQueryExceptionUnchanged) +{ + const String stored_text = "the query's stored corruption"; + for (const auto mode : {AdoptedRunReader::OnRefusal::Throw, AdoptedRunReader::OnRefusal::Report}) + { + SCOPED_TRACE(mode == AdoptedRunReader::OnRefusal::Report ? "Report" : "Throw"); + HeaderThenStoppedBackend backend; + const Layout layout{"pool"}; + const RunRef run = writeSourceEdgeRun(backend, layout, 1, 0, 0, {}, {{b(1), s(1)}}); + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "{}", stored_text)); + int code = 0; + DB::Cas::tests::onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + backend.on_refill = [&] { query.kill(cause); }; + DB::Cas::tests::OperationForTest op(backend); + const std::vector runs{run}; + AdoptedRunReader reader(*op, runs, 0, AdoptedRunContext{.gc_shards = 1, .parent_round = 1, .summary = {}}, mode); + SourceEdgeRecord rec; + try + { + reader.next(rec); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + EXPECT_EQ(code, DB::ErrorCodes::CORRUPTED_DATA) << "the refill failure did not reach the caller"; + try + { + std::rethrow_exception(cause); + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.message(), stored_text) << "the row read annotated the query's stored exception"; + } + } +} + /// ==== schema 3 key codec (Phase 3 T3, mixed-algo pools) ==== TEST(CASSourceEdgeKeySchema3, MixedWidthKeysOrderAlgoFirst) diff --git a/src/Disks/tests/gtest_cas_confirm_exact_ref.cpp b/src/Disks/tests/gtest_cas_confirm_exact_ref.cpp index 3d59d1b37a577..b1fd11d47cda4 100644 --- a/src/Disks/tests/gtest_cas_confirm_exact_ref.cpp +++ b/src/Disks/tests/gtest_cas_confirm_exact_ref.cpp @@ -2442,6 +2442,9 @@ class TimingOutSlotReadBackend : public CountingBackend std::vector read_times; }; +/// What one read reserves with default settings (`cas_attempt_timeout_ms` 5000 and a connect cap of 1000, twice). +constexpr uint64_t kDefaultAttemptEnvelopeMs = 7000; + constexpr uint64_t kSlotReadFailsForever = std::numeric_limits::max(); PoolPtr openPoolOnClock(const std::shared_ptr & backend, tests::FakeClock & clock, @@ -2534,24 +2537,27 @@ TEST(CASConfirmExactRef, CopyConfirmPropagatesAPersistentSlotReadFailureCountedO EXPECT_EQ(slotMovedCount() - moved_before, 0u) << "a failed read is not a moved slot"; } -/// The retries end at the deadline the confirm took at its start, not at a fresh window from the read: half the -/// window is spent before the read, so a fresh window would keep reading past the caller's deadline. -TEST(CASConfirmExactRef, CopyConfirmStopsRetryingTheSlotReadAtTheCallersDeadline) +/// The slot read binds its own window when it starts, not the poll's: half the poll's window is spent before the read, +/// and the retries still run a full window from the read's start. +TEST(CASConfirmExactRef, CopyConfirmStopsRetryingTheSlotReadAtItsOwnWindow) { tests::FakeClock clock; auto backend = std::make_shared(); - /// A lease far longer than the window, so the policy deadline and not the lease ends the retries. + /// A lease far longer than the window, so the read's window and not the lease ends the retries. auto store = openPoolOnClock(backend, clock, std::chrono::minutes(10)); + store->mountRequests().setAttemptReservationForTest(kDefaultAttemptEnvelopeMs); const RootNamespace ns{"srv1/confirm_copy_slot_deadline"}; const ManifestId id = publishEmptyPart(store, ns, "x"); const auto pinned = store->resolveRefPinned(ns, "x"); ASSERT_TRUE(pinned.has_value()); const uint64_t window_ms = PoolConfig{}.cas_request_budget.request_window_ms; - const uint64_t deadline_ms = clock.now.load() + window_ms; + const uint64_t poll_deadline_ms = clock.now.load() + window_ms; + uint64_t read_started_ms = 0; store->setConfirmAfterLedgerSnapshotHookForTest([&] { clock.now.fetch_add(window_ms / 2); + read_started_ms = clock.now.load(); }); backend->watched_key = mountSlotKey(store); backend->failures_left = kSlotReadFailsForever; @@ -2561,12 +2567,13 @@ TEST(CASConfirmExactRef, CopyConfirmStopsRetryingTheSlotReadAtTheCallersDeadline EXPECT_FALSE(outcome.answer.has_value()); EXPECT_EQ(outcome.error_code, std::optional(DB::ErrorCodes::NETWORK_ERROR)) << outcome.error_message; - EXPECT_NE(outcome.error_message.find("policy deadline"), String::npos) << outcome.error_message; const std::vector times = backend->slotReadTimes(); ASSERT_GT(times.size(), 1u) << "the failure was retried"; - EXPECT_LT(times.back(), deadline_ms) << "a read was sent at or after the caller's deadline"; + const uint64_t read_deadline_ms = read_started_ms + window_ms; + EXPECT_GT(times.back(), poll_deadline_ms) << "the retries stopped at the poll's end instead of the read's own window"; + EXPECT_LT(times.back(), read_deadline_ms) << "a read was sent at or after its own window's end"; /// The loop stops only when the next pause plus attempt no longer fits; a pause is at most 5000 ms. - EXPECT_GE(clock.now.load() + 5000 + backend->attemptEnvelopeMs(), deadline_ms) << "the retries stopped short of the deadline"; + EXPECT_GE(clock.now.load() + 5000 + kDefaultAttemptEnvelopeMs, read_deadline_ms) << "the retries stopped short of the window"; } /// The confirm a peer asks for makes one attempt at the slot read: the peer times out and retries from its own queue. @@ -2700,7 +2707,7 @@ TEST(CASConfirmExactRef, CopyConfirmReconfirmsOnceAMutationNamingTheSourceComple } /// The mutation stays queued: the confirm keeps asking until the deadline it took at its start and then refuses. It -/// neither gives up while a pass still fits nor starts one that could not finish by the deadline. +/// does not give up before the poll's end and starts no pass at or after it. TEST(CASConfirmExactRef, CopyConfirmRefusesAtItsDeadlineWhileAMutationNamingTheSourceStaysQueued) { tests::FakeClock clock; @@ -2734,8 +2741,117 @@ TEST(CASConfirmExactRef, CopyConfirmRefusesAtItsDeadlineWhileAMutationNamingTheS ASSERT_GT(pass_times.size(), 1u) << "the confirm did not ask again"; EXPECT_EQ(inFlightRefusals() - in_flight_before, pass_times.size()) << "every pass refused for the queued mutation"; EXPECT_LE(answered_at, deadline_ms) << "the confirm answered after its deadline"; - EXPECT_GE(answered_at + backend->attemptEnvelopeMs(), deadline_ms) << "the confirm gave up while a pass still fit"; - EXPECT_LT(pass_times.back() + backend->attemptEnvelopeMs(), deadline_ms) << "a pass started that could not finish"; + EXPECT_EQ(answered_at, deadline_ms) << "the poll stopped before its end"; + EXPECT_LT(pass_times.back(), deadline_ms) << "a pass started at or after the poll's end"; +} + +/// A pass starts whenever the poll's end is still ahead, even with less than one attempt envelope left: its slot read +/// binds its own window. +TEST(CASConfirmExactRef, APassWithLessThanOneEnvelopeLeftStillStarts) +{ + tests::FakeClock clock; + auto backend = std::make_shared(); + auto on_pause = std::make_shared>(); + auto store = openPoolOnFakeClock(backend, clock, on_pause); + store->mountRequests().setAttemptReservationForTest(kDefaultAttemptEnvelopeMs); + const RootNamespace ns{"srv1/confirm_copy_short_tail"}; + const ManifestId id = publishEmptyPart(store, ns, "x"); + const auto pinned = store->resolveRefPinned(ns, "x"); + ASSERT_TRUE(pinned.has_value()); + + LeaderLatch latch; + latch.arm(store); + std::thread appender([&] { appendPrecommitPairNaming(store, ns, "x"); }); + SCOPE_EXIT({ + latch.release(); + appender.join(); + store->setRefPreCarveHookForTest(nullptr); + }); + latch.awaitEntered(); + + const uint64_t deadline_ms = clock.now.load() + store->poolConfig().cas_request_budget.request_window_ms; + const uint64_t left_ms = kDefaultAttemptEnvelopeMs / 2; + size_t pauses = 0; + *on_pause = [&] + { + if (++pauses == 1) + clock.now.store(deadline_ms - left_ms); + }; + std::vector pass_times; + store->setConfirmAfterOwnershipCaptureHookForTest([&] { pass_times.push_back(clock.now.load()); }); + SCOPE_EXIT({ store->setConfirmAfterOwnershipCaptureHookForTest(nullptr); }); + const ConfirmOutcome outcome = confirmPinned(store, *pinned, ns, id); + + EXPECT_FALSE(outcome.error_code.has_value()) << "the confirm threw: " << outcome.error_message; + EXPECT_EQ(outcome.answer, std::optional(ConfirmAnswer::Unknown)); + ASSERT_GT(pass_times.size(), 1u) << "no pass started with less than one envelope left"; + EXPECT_EQ(pass_times[1], deadline_ms - left_ms); +} + +/// The poll's end stops only new passes: a ledger check that crosses it still sends the slot read. +TEST(CASConfirmExactRef, ALedgerCheckThatCrossesThePollEndStillSendsItsSlotRead) +{ + tests::FakeClock clock; + auto backend = std::make_shared(); + auto store = openPoolOnClock(backend, clock, std::chrono::minutes(10)); + const RootNamespace ns{"srv1/confirm_copy_check_crosses_end"}; + const ManifestId id = publishEmptyPart(store, ns, "x"); + const auto pinned = store->resolveRefPinned(ns, "x"); + ASSERT_TRUE(pinned.has_value()); + + const uint64_t window_ms = PoolConfig{}.cas_request_budget.request_window_ms; + const uint64_t deadline_ms = clock.now.load() + window_ms; + store->setConfirmAfterLedgerSnapshotHookForTest([&] { clock.now.fetch_add(window_ms + 1); }); + backend->watched_key = mountSlotKey(store); + const ConfirmOutcome outcome = confirmPinned(store, *pinned, ns, id); + store->setConfirmAfterLedgerSnapshotHookForTest(nullptr); + + EXPECT_FALSE(outcome.error_code.has_value()) << "the confirm threw: " << outcome.error_message; + EXPECT_EQ(outcome.answer, std::optional(ConfirmAnswer::Yes)); + const std::vector times = backend->slotReadTimes(); + ASSERT_EQ(times.size(), 1u); + EXPECT_GT(times.front(), deadline_ms) << "the slot read was sent before the poll's end"; +} + +/// A pause that reaches the poll's end starts no pass. +TEST(CASConfirmExactRef, APauseThatReachesThePollEndStartsNoPass) +{ + tests::FakeClock clock; + auto backend = std::make_shared(); + auto on_pause = std::make_shared>(); + auto store = openPoolOnFakeClock(backend, clock, on_pause); + const RootNamespace ns{"srv1/confirm_copy_pause_reaches_end"}; + const ManifestId id = publishEmptyPart(store, ns, "x"); + const auto pinned = store->resolveRefPinned(ns, "x"); + ASSERT_TRUE(pinned.has_value()); + + LeaderLatch latch; + latch.arm(store); + std::thread appender([&] { appendPrecommitPairNaming(store, ns, "x"); }); + SCOPE_EXIT({ + latch.release(); + appender.join(); + store->setRefPreCarveHookForTest(nullptr); + }); + latch.awaitEntered(); + + const uint64_t deadline_ms = clock.now.load() + store->poolConfig().cas_request_budget.request_window_ms; + size_t passes = 0; + store->setConfirmAfterOwnershipCaptureHookForTest([&] { ++passes; }); + /// The first pause ends exactly at the poll's end, whatever length the jitter gave it. + size_t pauses = 0; + *on_pause = [&] + { + if (++pauses == 1) + clock.now.store(deadline_ms); + }; + SCOPE_EXIT({ store->setConfirmAfterOwnershipCaptureHookForTest(nullptr); }); + const ConfirmOutcome outcome = confirmPinned(store, *pinned, ns, id); + + EXPECT_FALSE(outcome.error_code.has_value()) << "the confirm threw: " << outcome.error_message; + EXPECT_EQ(outcome.answer, std::optional(ConfirmAnswer::Unknown)); + EXPECT_EQ(passes, 1u); + EXPECT_EQ(clock.now.load(), deadline_ms) << "the pause was not clamped to the poll's end"; } /// `No` says the source is no longer the binding the copy read; no later pass can change that, so it is answered at once. diff --git a/src/Disks/tests/gtest_cas_deadline_gaps.cpp b/src/Disks/tests/gtest_cas_deadline_gaps.cpp new file mode 100644 index 0000000000000..f34d51ad3c0d1 --- /dev/null +++ b/src/Disks/tests/gtest_cas_deadline_gaps.cpp @@ -0,0 +1,483 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace DB::Cas; +using DB::Cas::tests::OperationForTest; +using DB::Cas::tests::TimeTakingBackend; +using DB::Cas::tests::VirtualRetryClock; +using DB::Cas::tests::idOf; + +namespace +{ + +constexpr uint64_t kTenMinutesMs = 10 * 60 * 1000; + +using Verb = TimeTakingBackend::Verb; +using Ending = TimeTakingBackend::Ending; + +struct OpenedPool +{ + PoolPtr store; + std::shared_ptr clock; +}; + +/// Every request plane of the pool and the backend's own delays share one virtual clock. +OpenedPool openPoolOn(const std::shared_ptr & backend) +{ + /// A pool closed while a build still owes its cleanup leaves no clean farewell; the reopen must not + /// spend a lease TTL of real time observing the slot. + PoolPtr store = Pool::open( + backend, PoolConfig{.pool_prefix = "p", .server_root_id = "test", .unsafe_remount_no_delay = true}); + auto clock = VirtualRetryClock::installOn(store); + backend->useClock(clock); + return {std::move(store), std::move(clock)}; +} + +PartWriteTxnPtr startBuildFor(const PoolPtr & store, const RootNamespace & ns, const String & ref) +{ + PartWriteInfo info; + info.intended_ref = ns.string() + "/" + ref; + return store->beginPartWrite(info); +} + +ManifestEntry blobManifestEntry(const String & path, const String & payload) +{ + ManifestEntry entry; + entry.path = path; + entry.placement = EntryPlacement::Blob; + entry.ref = idOf(payload); + entry.blob_size = payload.size(); + return entry; +} + +std::function exactly(const String & wanted) +{ + return [wanted](const String & key) { return key == wanted; }; +} + +enum class BodyTransport : uint8_t { Streaming, ServerSideCopy }; + +const char * transportName(BodyTransport transport) +{ + return transport == BodyTransport::Streaming ? "Streaming" : "ServerSideCopy"; +} + +/// A re-readable source of `payload`. For a server-side copy it also stores the staging object the +/// copy publishes verbatim: the pool's fixed-length envelope followed by the payload. +BlobSource sourceOf(BodyTransport transport, TimeTakingBackend & backend, const PoolPtr & store, const String & payload) +{ + BlobSource source; + source.size = payload.size(); + source.open = [payload]() -> std::unique_ptr + { + return std::make_unique(payload); + }; + if (transport == BodyTransport::ServerSideCopy) + { + const String staging_key = "p/staging/test/" + payload; + OperationForTest seed(backend); + const WriteResult seeded + = (*seed).create(staging_key, String(store->poolMeta().blob_header_len, 'h') + payload, Retry::once()); + EXPECT_TRUE(std::holds_alternative(seeded)); + source.server_side_copy_from = staging_key; + } + return source; +} + +/// Runs `step` and returns the text of whatever it threw, or nothing. +std::optional failureOf(const std::function & step) +{ + try + { + step(); + } + catch (...) + { + return DB::getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + return std::nullopt; +} + +void publishOnePart(const PoolPtr & store, const RootNamespace & ns, const String & ref, const String & payload) +{ + auto build = startBuildFor(store, ns, ref); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, ref, id); + build->putBlob(idOf(payload), BlobSource::fromString(payload)); + build->promote(ns, ref, build->buildId(), id); +} + +/// A pool reopened over a table with two committed parts, so the table's ref state is not in memory. +struct ColdTable +{ + std::shared_ptr backend = std::make_shared(); + RootNamespace ns{"srv/tbl"}; + OpenedPool pool; + + ColdTable() + { + { + const OpenedPool first = openPoolOn(backend); + publishOnePart(first.store, ns, "part_a", "payload-a"); + publishOnePart(first.store, ns, "part_b", "payload-b"); + } + pool = openPoolOn(backend); + } + + /// The first read of the removal that is not the catalog read belongs to the table's recovery. + void armSlowRecovery() const + { + backend->arm(Verb::Read, [catalog = pool.store->layout().refCatalogKey()](const String & key) { return key != catalog; }, + kTenMinutesMs); + } +}; + +} + +/// --------------------------------------------------------------------------------------------- +/// A publication that takes longer than the request window. +/// --------------------------------------------------------------------------------------------- + +class CASDeadlineGapsLongPublication : public ::testing::TestWithParam +{ +}; + +INSTANTIATE_TEST_SUITE_P(CASTransport, CASDeadlineGapsLongPublication, + ::testing::Values(BodyTransport::Streaming, BodyTransport::ServerSideCopy), + [](const ::testing::TestParamInfo & param) { return String(transportName(param.param)); }); + +/// The transfer of a body is bounded by its own send and receive timeouts only, so a publication five +/// times the request window long must still end in a committed part: no request that follows it may be +/// measured against a deadline taken before it started. +TEST_P(CASDeadlineGapsLongPublication, Commits) +{ + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-that-takes-ten-minutes"; + const String key = pool.store->layout().blobKey(idOf(payload)); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + backend->arm(Verb::Publish, exactly(key), kTenMinutesMs); + const uint64_t started_ms = pool.clock->nowMs(); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload), sourceOf(GetParam(), *backend, pool.store, payload)); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(backend->slowedKeys(), std::vector{key}) << "the publication never ran slowly"; + ASSERT_GT(pool.clock->nowMs() - started_ms, kDefaultRequestWindowMs); + ASSERT_FALSE(failure.has_value()) << *failure; + EXPECT_EQ(backend->publicationsOf(key), 1u); + EXPECT_EQ(backend->serverSideCopiesOf(key), GetParam() == BodyTransport::ServerSideCopy ? 1u : 0u); + EXPECT_TRUE(pool.store->resolveRef(ns, "part").has_value()); +} + +namespace +{ + +struct LostPublication +{ + BodyTransport transport; + bool landed; +}; + +class CASDeadlineGapsLostLongPublication : public ::testing::TestWithParam +{ +}; + +} + +INSTANTIATE_TEST_SUITE_P(CASTransport, CASDeadlineGapsLostLongPublication, + ::testing::Values( + LostPublication{BodyTransport::Streaming, false}, LostPublication{BodyTransport::Streaming, true}, + LostPublication{BodyTransport::ServerSideCopy, false}, LostPublication{BodyTransport::ServerSideCopy, true}), + [](const ::testing::TestParamInfo & param) + { + return String(transportName(param.param.transport)) + (param.param.landed ? "Landed" : "NotLanded"); + }); + +/// The publication loop allows eight attempts. A first attempt that ran for ten minutes before its +/// response was lost has used none of the time a reissue needs: the next observation of the key, and the +/// publication after it when the body did not land, must still be sent. +TEST_P(CASDeadlineGapsLostLongPublication, IsReissuedInPlaceAndCommits) +{ + const LostPublication lost = GetParam(); + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-whose-first-response-is-lost"; + const String key = pool.store->layout().blobKey(idOf(payload)); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + backend->arm(Verb::Publish, exactly(key), kTenMinutesMs, /*times=*/1, + lost.landed ? Ending::LostAfterLanding : Ending::LostBeforeLanding); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload), sourceOf(lost.transport, *backend, pool.store, payload)); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(backend->slowedKeys(), std::vector{key}) << "the publication never ran slowly"; + ASSERT_FALSE(failure.has_value()) + << "after " << backend->publicationsOf(key) << " publication(s) the build failed: " << *failure; + /// A stored body has no deletion intent, so the reissue adopts it; an absent one is published again. + EXPECT_EQ(backend->publicationsOf(key), lost.landed ? 1u : 2u); + EXPECT_TRUE(pool.store->resolveRef(ns, "part").has_value()); +} + +/// A part of sixteen bodies whose last upload takes ten minutes. The fifteen dependency proofs taken +/// before it are consumed by the promote ten minutes later, and nothing may re-measure them against +/// the time they were taken at. +TEST(CASDeadlineGaps, BodiesPublishedBeforeASlowOneAreStillAcceptedAtPromote) +{ + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + constexpr size_t bodies = 16; + + std::vector payloads; + std::vector entries; + for (size_t i = 0; i < bodies; ++i) + { + payloads.push_back(fmt::format("body-{}-of-a-wide-part", i)); + entries.push_back(blobManifestEntry(fmt::format("column_{}.bin", i), payloads.back())); + } + const String slow_key = pool.store->layout().blobKey(idOf(payloads.back())); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest(entries); + build->precommitAdd(ns, "part", id); + + backend->arm(Verb::Publish, exactly(slow_key), kTenMinutesMs); + std::vector results; + const auto failure = failureOf([&] + { + /// The order of the upload fan-out's join: every result is kept until the slowest task ends. + for (const String & payload : payloads) + results.push_back(build->uploadBlobDetached( + BlobUploadRequest{idOf(payload), BlobSource::fromString(payload), payload.size()})); + build->mergeBlobUploadResults(results); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(backend->slowedKeys(), std::vector{slow_key}) << "the last publication never ran slowly"; + ASSERT_FALSE(failure.has_value()) << *failure; + for (const String & payload : payloads) + EXPECT_EQ(backend->publicationsOf(pool.store->layout().blobKey(idOf(payload))), 1u); + EXPECT_TRUE(pool.store->resolveRef(ns, "part").has_value()); +} + +/// GC rounds run while a body uploads for ten minutes. The build's precommit was durable before the +/// upload started, so neither the manifest it staged nor the sibling body it already published may be +/// reclaimed, and the promote that follows must find its precommit. +TEST(CASDeadlineGaps, GcRoundsDuringALongPublicationSpareTheBuild) +{ + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + const String payload_a = "body-a-published-before-the-long-upload"; + const String payload_b = "body-b-uploads-for-ten-minutes"; + const String key_a = pool.store->layout().blobKey(idOf(payload_a)); + const String key_b = pool.store->layout().blobKey(idOf(payload_b)); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload_a), blobManifestEntry("b.bin", payload_b)}); + build->precommitAdd(ns, "part", id); + build->putBlob(idOf(payload_a), BlobSource::fromString(payload_a)); + + Gc gc(pool.store, hexToU128("00000000000000000000000000000001")); + size_t rounds_during_upload = 0; + backend->armWith(Verb::Publish, exactly(key_b), [&] + { + for (size_t i = 0; i < 3; ++i) + { + pool.clock->advance(kTenMinutesMs / 3); + /// What the renewal thread does every period while the upload runs. + pool.store->renewWatermarkOnce(); + (void)DB::Cas::tests::runRegularRoundReclaiming(gc); + ++rounds_during_upload; + } + }); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload_b), BlobSource::fromString(payload_b)); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(rounds_during_upload, 3u) << "no GC round ran during the publication"; + ASSERT_FALSE(failure.has_value()) << *failure; + for (size_t i = 0; i < 3; ++i) + { + pool.store->renewWatermarkOnce(); + (void)DB::Cas::tests::runRegularRoundReclaiming(gc); + } + EXPECT_EQ(backend->publicationsOf(key_a), 1u); + EXPECT_EQ(backend->publicationsOf(key_b), 1u); + EXPECT_TRUE(DB::Cas::tests::objectPresent(*backend, key_a)); + EXPECT_TRUE(DB::Cas::tests::objectPresent(*backend, key_b)); + ASSERT_TRUE(pool.store->resolveRef(ns, "part").has_value()); + EXPECT_EQ(pool.store->readManifest(id).entries.size(), 2u); +} + +/// One upload outlives twenty mount lease TTLs. The lease is renewed every period by its own thread +/// and a renewal does not move the fence generation, so the build admitted before the upload is still +/// admitted after it and commits. +TEST(CASDeadlineGaps, ABuildSurvivesAnUploadLongerThanManyLeaseTtls) +{ + auto backend = std::make_shared(); + /// One clock for the lease and for every request window, as on a server. + auto boot_ms = std::make_shared>(1'000'000); + const PoolPtr store = Pool::open(backend, PoolConfig{ + .pool_prefix = "p", .server_root_id = "test", + .boot_ms_fn = [boot_ms] { return boot_ms->load(); }}); + store->setCasRetrySleepForTest([boot_ms](uint64_t ms) { boot_ms->fetch_add(ms + 1); }); + const uint64_t ttl_ms = static_cast(store->poolConfig().mount_lease_ttl_ms.count()); + const uint64_t period_ms = static_cast(store->poolConfig().mount_renew_period.count()); + + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-that-outlives-the-lease"; + const String key = store->layout().blobKey(idOf(payload)); + auto build = startBuildFor(store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + const uint64_t generation_before = store->fenceGeneration(); + const uint64_t started_ms = boot_ms->load(); + backend->armWith(Verb::Publish, exactly(key), [&] + { + for (uint64_t elapsed_ms = 0; elapsed_ms < kTenMinutesMs; elapsed_ms += period_ms) + { + boot_ms->fetch_add(period_ms); + store->renewWatermarkOnce(); + } + }); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload), BlobSource::fromString(payload)); + build->promote(ns, "part", build->buildId(), id); + }); + + ASSERT_EQ(backend->slowedKeys(), std::vector{key}) << "the publication never ran slowly"; + ASSERT_GE(boot_ms->load() - started_ms, 20 * ttl_ms); + ASSERT_FALSE(failure.has_value()) << *failure; + EXPECT_EQ(store->fenceGeneration(), generation_before); + EXPECT_EQ(backend->publicationsOf(key), 1u); + EXPECT_TRUE(store->resolveRef(ns, "part").has_value()); +} + +/// The eighth publication is the last the loop makes. When its response is lost after the body landed +/// the loop does not observe the key again: the write fails and the caller's retry adopts the body. +TEST(CASDeadlineGaps, ABodyThatLandsOnTheEighthLostPublicationStillFails) +{ + auto backend = std::make_shared(); + const OpenedPool pool = openPoolOn(backend); + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-landing-on-the-last-attempt"; + const String key = pool.store->layout().blobKey(idOf(payload)); + + auto build = startBuildFor(pool.store, ns, "part"); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + size_t journal_at_eighth = 0; + backend->arm(Verb::Publish, exactly(key), /*takes_ms=*/0, /*times=*/7, Ending::LostBeforeLanding); + backend->armWith(Verb::Publish, exactly(key), [&] { journal_at_eighth = backend->seenCount(); }, /*times=*/1, + Ending::LostAfterLanding); + const auto failure = failureOf([&] { build->putBlob(idOf(payload), BlobSource::fromString(payload)); }); + + ASSERT_TRUE(failure.has_value()) << "the loop must not commit a body whose last publication was lost"; + EXPECT_NE(failure->find("remained ambiguous"), String::npos) << *failure; + EXPECT_EQ(backend->publicationsOf(key), 8u); + EXPECT_TRUE(DB::Cas::tests::objectPresent(*backend, key)); + EXPECT_EQ(backend->seenSince(journal_at_eighth, Verb::Head, key), 0u) << "the loop observed the key after its last publication"; +} + +/// --------------------------------------------------------------------------------------------- +/// A table removal whose ref-table recovery takes longer than the request window. +/// --------------------------------------------------------------------------------------------- + +/// Recovery of a table reads its checkpoint, snapshot and log tail, and its length grows with the +/// table. The removal's catalog read and its `Live -> Removing` write come after it and are single +/// requests, so they need a window of their own. +TEST(CASDeadlineGaps, RemovalOfATableWhoseRecoveryOutlastsTheWindowCompletes) +{ + const ColdTable table; + const PoolPtr & store = table.pool.store; + ASSERT_FALSE(store->refTableRecoveredForTest(table.ns)) << "the table must be recovered by the removal itself"; + + table.armSlowRecovery(); + const uint64_t started_ms = table.pool.clock->nowMs(); + std::optional recovery_took_ms; + store->setRemovalAttemptHookForTest([&] { recovery_took_ms = table.pool.clock->nowMs() - started_ms; }); + const auto failure = failureOf([&] { store->dropNamespace(table.ns); }); + store->setRemovalAttemptHookForTest({}); + + ASSERT_EQ(table.backend->slowedKeys().size(), 1u) << "no read of the recovery ran slowly"; + ASSERT_TRUE(recovery_took_ms.has_value()) << "the removal never reached its first request"; + ASSERT_GT(*recovery_took_ms, kDefaultRequestWindowMs); + ASSERT_FALSE(failure.has_value()) << *failure; + EXPECT_FALSE(store->resolveRef(table.ns, "part_a").has_value()); + EXPECT_FALSE(store->resolveRef(table.ns, "part_b").has_value()); +} + +/// The recovery a failed removal paid for stays in memory, so the next removal of the same table has +/// nothing long in front of its requests. The first removal fails at its `gc/state` read, after the +/// recovery and before any catalog write. +TEST(CASDeadlineGaps, RepeatedRemovalAfterASlowRecoveryCompletes) +{ + const ColdTable table; + const PoolPtr & store = table.pool.store; + const String gc_state_key = store->layout().gcStateKey(); + const String catalog_key = store->layout().refCatalogKey(); + + table.armSlowRecovery(); + auto gc_state_fails = std::make_shared>(false); + table.backend->arm(Verb::Read, [gc_state_fails, gc_state_key](const String & key) + { + return gc_state_fails->load() && key == gc_state_key; + }, /*takes_ms=*/0, std::numeric_limits::max(), TimeTakingBackend::Ending::LostBeforeLanding); + store->setRemovalAttemptHookForTest([gc_state_fails] { gc_state_fails->store(true); }); + const size_t requests_before = table.backend->seenCount(); + const auto first_failure = failureOf([&] { store->dropNamespace(table.ns); }); + store->setRemovalAttemptHookForTest({}); + gc_state_fails->store(false); + + ASSERT_TRUE(first_failure.has_value()) << "the first removal must fail"; + EXPECT_GT(table.backend->seenSince(requests_before, Verb::Read, gc_state_key), 0u) << "the gc/state read was never sent"; + ASSERT_EQ(table.backend->seenSince(requests_before, Verb::Write, catalog_key), 0u) << "a catalog write was sent"; + const std::vector slowed = table.backend->slowedKeys(); + ASSERT_EQ(std::count_if(slowed.begin(), slowed.end(), [&](const String & key) { return key != gc_state_key; }), 1) + << "no read of the recovery ran slowly"; + + ASSERT_TRUE(store->refTableRecoveredForTest(table.ns)) << "the first removal left the table unrecovered"; + const uint64_t recoveries_before = store->recoveryInstallCountForTest(); + const auto failure = failureOf([&] { store->dropNamespace(table.ns); }); + ASSERT_FALSE(failure.has_value()) << *failure; + EXPECT_EQ(store->recoveryInstallCountForTest(), recoveries_before) << "the repeated removal recovered the table again"; + EXPECT_FALSE(store->resolveRef(table.ns, "part_a").has_value()); + EXPECT_FALSE(store->resolveRef(table.ns, "part_b").has_value()); +} diff --git a/src/Disks/tests/gtest_cas_decommission.cpp b/src/Disks/tests/gtest_cas_decommission.cpp index 66c9aa395142b..0b6605847b9fa 100644 --- a/src/Disks/tests/gtest_cas_decommission.cpp +++ b/src/Disks/tests/gtest_cas_decommission.cpp @@ -1,12 +1,16 @@ #include "cas_test_helpers.h" #include +#include #include #include #include #include +#include #include #include #include +#include +#include #include #include #include @@ -14,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +36,8 @@ namespace DB::ErrorCodes extern const int ABORTED; extern const int BAD_ARGUMENTS; extern const int CORRUPTED_DATA; + extern const int NETWORK_ERROR; + extern const int QUERY_WAS_CANCELLED; } using namespace DB; @@ -1613,6 +1620,249 @@ TEST_F(CASDecommission, ResumesOverItsOwnTombstone) namespace { +/// Runs `on_first_staging_delete` before the first delete under the victim's staging prefix, and counts the +/// listings of each prefix. +class StopOnFirstStagingDeleteBackend : public InMemoryBackend +{ +public: + using InMemoryBackend::list; + + std::function on_first_staging_delete; + + size_t listingsOf(const String & prefix) const + { + std::lock_guard lock(mutex); + return static_cast(std::count(listed_prefixes.begin(), listed_prefixes.end(), prefix)); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + { + std::lock_guard lock(mutex); + listed_prefixes.push_back(prefix); + } + return InMemoryBackend::list(prefix, cursor, limit, access); + } + + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + if (on_first_staging_delete && key.starts_with("p/staging/victim/")) + std::exchange(on_first_staging_delete, {})(); + return InMemoryBackend::remove(key, expected_value, access); + } + +private: + mutable std::mutex mutex; + std::vector listed_prefixes; +}; + +} + +/// A decommission whose owner stops during the staging drain deletes nothing more and lists no further prefix: +/// the stop ends the run instead of becoming a warning per remaining object. +TEST_F(CASDecommission, OwnerStopDuringTheDrainEndsTheRun) +{ + auto backend = startVictim(std::make_shared()); + seed("p/staging/victim/a_first.tmp"); + seed("p/staging/victim/b_second.tmp"); + seed("p/roots/victim/c_third"); + std::atomic stopped = false; + size_t roots_listings_at_stop = 0; + backend->on_first_staging_delete = [&] + { + roots_listings_at_stop = backend->listingsOf("p/roots/victim/"); + stopped = true; + }; + + { + const auto owner = OwnerScope::background([&stopped] + { + if (stopped) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); + expectThrowsCode(ErrorCodes::ABORTED, [&] { (void)run("admin"); }); + } + + ASSERT_TRUE(stopped) << "premise: the drain reached the staging prefix"; + EXPECT_FALSE(exists("p/staging/victim/a_first.tmp")) << "the delete the stop landed in"; + EXPECT_TRUE(exists("p/staging/victim/b_second.tmp")); + EXPECT_TRUE(exists("p/roots/victim/c_third")); + EXPECT_EQ(backend->listingsOf("p/roots/victim/"), roots_listings_at_stop) << "the stopped drain listed the roots"; +} + +/// A killed query ends the key drain at the next key with its own error, and a delete that failed after the kill ends +/// it with that delete's error, not with a warning: the next staging key and the roots stay. +TEST_F(CASDecommission, KilledQueryEndsTheKeyDrainAtTheNextKey) +{ + for (const bool delete_fails : {false, true}) + { + SCOPED_TRACE(delete_fails ? "the delete fails after the kill" : "the delete succeeds after the kill"); + auto backend = startVictim(std::make_shared()); + seed("p/staging/victim/a_first.tmp"); + seed("p/staging/victim/b_second.tmp"); + seed("p/roots/victim/c_third"); + size_t roots_listings_at_kill = 0; + int code = 0; + String message; + std::thread killed([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + backend->on_first_staging_delete = [&] + { + roots_listings_at_kill = backend->listingsOf("p/roots/victim/"); + query.kill(); + if (delete_fails) + throw Exception(ErrorCodes::NETWORK_ERROR, "injected staging delete failure"); + }; + try + { + (void)run("admin"); + } + catch (const Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + killed.join(); + + EXPECT_EQ(code, delete_fails ? ErrorCodes::NETWORK_ERROR : ErrorCodes::QUERY_WAS_CANCELLED) << message; + EXPECT_EQ(exists("p/staging/victim/a_first.tmp"), delete_fails) << "the delete the kill landed in"; + EXPECT_TRUE(exists("p/staging/victim/b_second.tmp")) << "the drain deleted a key after the kill"; + EXPECT_TRUE(exists("p/roots/victim/c_third")); + EXPECT_EQ(backend->listingsOf("p/roots/victim/"), roots_listings_at_kill) << "the killed drain listed the roots"; + } +} + +namespace +{ + +/// Runs `on_list` once, before the first listing whose prefix `matches` accepts, and records every listed prefix. +class HookFirstListingBackend : public InMemoryBackend +{ +public: + using InMemoryBackend::list; + + std::function matches; + std::function on_list; + /// When set, a page holds at most this many keys, as a store with a small `list_object_keys_size` answers. + size_t page_cap = 0; + + size_t listingsOf(const String & prefix) const + { + std::lock_guard lock(mutex); + return static_cast(std::count(listed_prefixes.begin(), listed_prefixes.end(), prefix)); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + std::function hook; + { + std::lock_guard lock(mutex); + listed_prefixes.push_back(prefix); + if (on_list && matches && matches(prefix)) + hook = std::exchange(on_list, {}); + } + if (hook) + hook(); + return InMemoryBackend::list(prefix, cursor, page_cap ? std::min(limit, page_cap) : limit, access); + } + +private: + mutable std::mutex mutex; + std::vector listed_prefixes; +}; + +/// Staged manifests of one build no ref names: several keys in one manifest group of `ns_str`. Returns their keys. +std::vector seedOrphanManifestGroup(Pool & victim, const String & ns_str, uint32_t keys) +{ + std::vector out; + for (uint32_t ordinal = 1; ordinal <= keys; ++ordinal) + { + const ManifestRef ref{.writer_epoch = victim.writerEpoch(), .build_sequence = 99, .manifest_ordinal = ordinal}; + const ManifestId id = writeManifestRaw(*victim.poolBackendPtr(), victim.layout(), RootNamespace(ns_str), ref, {}); + out.push_back(victim.layout().manifestKey(id)); + } + return out; +} + +} + +/// A killed query ends the drain at the next scan head with its own error: before the first namespace, at the +/// next page of the manifest listing, or at the next key of a group that holds several. The tombstone stays, and a rerun resumes. +TEST_F(CASDecommission, KilledQueryEndsTheDrainAtTheNextScanHead) +{ + enum class KillAt : uint8_t { BeforeTheRun, DebrisListing, GroupListing }; + for (const KillAt kill_at : {KillAt::BeforeTheRun, KillAt::DebrisListing, KillAt::GroupListing}) + { + SCOPED_TRACE(kill_at == KillAt::BeforeTheRun ? "before the run" + : kill_at == KillAt::DebrisListing ? "at the debris listing" : "at the group's key listing"); + std::vector group_keys; + auto backend = startVictim(std::make_shared(), [&](Pool & victim) + { + oneTable(victim); + group_keys = seedOrphanManifestGroup(victim, "victim/db/t1", 3); + }); + const String group_prefix = group_keys.front().substr(0, group_keys.front().rfind('/') + 1); + const String debris_prefix = layout.casManifestsServerPrefix("victim"); + + int code = 0; + size_t listings_at_kill = 0; + std::thread killed([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + if (kill_at == KillAt::BeforeTheRun) + query.kill(); + else + { + if (kill_at == KillAt::DebrisListing) + backend->page_cap = 1; + const String watched = kill_at == KillAt::DebrisListing ? debris_prefix : group_prefix; + backend->matches = [watched](const String & prefix) { return prefix == watched; }; + backend->on_list = [&query, &listings_at_kill, watched, &backend] + { + listings_at_kill = backend->listingsOf(watched); + query.kill(); + }; + } + try + { + (void)run("admin"); + } + catch (const Exception & e) + { + code = e.code(); + } + }); + killed.join(); + + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(backend->listingsOf("p/staging/victim/"), 0u) << "the stopped drain went on to the staging area"; + OperationForTest op(*victim_backend); + const CasRefCatalog::Snapshot catalog = CasRefCatalog::read(*op, layout); + ASSERT_EQ(catalog.catalog.entries.size(), 1u); + EXPECT_EQ(catalog.catalog.entries.front().state, kill_at == KillAt::BeforeTheRun ? NsState::Live : NsState::Removing); + EXPECT_EQ(backend->listingsOf(group_prefix), kill_at == KillAt::GroupListing ? 1u : 0u); + if (kill_at == KillAt::DebrisListing) + { + ASSERT_GT(listings_at_kill, 0u) << "premise: the kill landed in the debris listing"; + EXPECT_EQ(backend->listingsOf(debris_prefix), listings_at_kill) << "the killed listing requested another page"; + } + expectOwner(2, true, false); + + const auto rerun = run("admin"); + EXPECT_EQ(rerun.namespaces_removed + rerun.namespaces_already_removed, 1u); + EXPECT_GT(backend->listingsOf("p/staging/victim/"), 0u) << "the rerun drained the staging area"; + } +} + +namespace +{ + /// The first roots delete under the victim lets the admin's local lease deadline pass (the fake clock jumps a /// TTL); every delete admitted on the mount plane after it is refused. Optionally also GC-fences the body. class ExpireLeaseOnFirstRootsDeleteBackend : public InMemoryBackend diff --git a/src/Disks/tests/gtest_cas_detached_work.cpp b/src/Disks/tests/gtest_cas_detached_work.cpp index dc81efb83fbb2..cb78a0881b9d0 100644 --- a/src/Disks/tests/gtest_cas_detached_work.cpp +++ b/src/Disks/tests/gtest_cas_detached_work.cpp @@ -17,6 +17,7 @@ #include #include #include +#include using namespace DB::Cas; @@ -25,6 +26,11 @@ namespace ProfileEvents extern const Event CASDetachedWorkDrainTimeouts; } +namespace DB::ErrorCodes +{ +extern const int ABORTED; +} + namespace { @@ -1029,3 +1035,89 @@ TEST(CASDetachedWork, StopAfterRecoveryMaterializationPreventsFinalInstall) << "recovery installed a materialized result after detached stop was latched"; EXPECT_EQ(fixture.ledger.laneStateForTest(ns), RefLaneState::NeedsRecovery); } + +namespace +{ + +/// Parks the first read of the armed key, then loses its reply, so the read's reissue meets whatever +/// was latched while it was parked. +class ParkThenLoseReadBackend : public DB::Cas::tests::OrderedFaultBackend +{ +public: + void arm(String key_, std::shared_ptr parked_, std::shared_ptr release_) + { + key = std::move(key_); + parked = std::move(parked_); + release = std::move(release_); + armed.store(true); + } + + std::optional read(const String & read_key, TransportAccess & access) override + { + if (read_key == key && armed.exchange(false)) + { + parked->open(); + release->wait("release_parked_read"); + throw Poco::TimeoutException("test: the read's reply is lost"); + } + return DB::Cas::tests::OrderedFaultBackend::read(read_key, access); + } + +private: + String key; + std::shared_ptr parked; + std::shared_ptr release; + std::atomic armed{false}; +}; + +struct PublishErrorCodes +{ + std::mutex mutex; + std::vector codes; +}; + +} + +/// Teardown during a detached recovery walk ends the recovery with `ABORTED`, not with the error of the +/// request that teardown refused. +TEST(CASRefWriterRecoveryRetry, TeardownDuringWalkThrowsAborted) +{ + auto backend = std::make_shared(); + auto errors = std::make_shared(); + PoolConfig config; + config.snapshot_publish_backoff_initial_ms = 0; + config.snapshot_publish_backoff_max_ms = 0; + config.publish_error_hook_for_test = [errors] + { + std::lock_guard lock(errors->mutex); + errors->codes.push_back(DB::getCurrentExceptionCode()); + }; + auto store = openPublishingPool(backend, config); + const RootNamespace ns{"srv1/teardown_during_walk"}; + + auto first_publisher_captured = std::make_shared(); + auto release_first_publisher = std::make_shared(); + String ckpt_key; + preparePendingRecoveryPublisher( + store, backend, ns, first_publisher_captured, release_first_publisher, ckpt_key); + + auto read_parked = std::make_shared(); + auto release_read = std::make_shared(); + backend->arm(ckpt_key, read_parked, release_read); + { + std::lock_guard lock(errors->mutex); + errors->codes.clear(); + } + release_first_publisher->open(); + GateOpenedOnExit read_released{*release_read}; + read_parked->wait("read_parked"); + + auto drain = std::async(std::launch::async, [&store] { return store->stopAndDrainDetachedWork(/*deadline_ms=*/5000); }); + awaitStopLatched(store); + release_read->open(); + EXPECT_TRUE(drain.get()); + store->waitForSnapshotPublishSettleForTest(ns); + + std::lock_guard lock(errors->mutex); + EXPECT_EQ(errors->codes, std::vector{DB::ErrorCodes::ABORTED}); +} diff --git a/src/Disks/tests/gtest_cas_forget.cpp b/src/Disks/tests/gtest_cas_forget.cpp index 1e04789d2a259..2a181586d0fad 100644 --- a/src/Disks/tests/gtest_cas_forget.cpp +++ b/src/Disks/tests/gtest_cas_forget.cpp @@ -7,8 +7,11 @@ #include #include #include +#include #include #include +#include +#include #include #include @@ -19,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -359,6 +363,42 @@ TEST(CASForget, ForgetCleanFarewellGatedOnDrain) } } +/// FORGET run by a killed query on a healthy store still drains and writes its clean farewell: every request it +/// sends succeeds, so the kill stops none of them. +TEST(CASForget, KilledQuerysForgetLandsTheFarewell) +{ + using DB::Cas::decodeMountLease; + constexpr uint64_t kTerminated = std::numeric_limits::max(); + auto backend = std::make_shared(); + auto store = DB::Cas::tests::openPoolForTest(backend); + const String mount_key = store->layout().mountKey(kSrid); + + String failure; + std::thread killed([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + try + { + store->forgetDisk([] {}, kForgetReason); + } + catch (...) + { + failure = getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + }); + killed.join(); + + EXPECT_TRUE(failure.empty()) << failure; + EXPECT_EQ(store->lifecycle(), PoolLifecycle::VanishedForgotten); + DB::Cas::tests::OperationForTest op(*backend); + const auto got = (*op).read(mount_key, DB::Cas::Retry::once()); + ASSERT_TRUE(got.has_value()); + EXPECT_EQ(decodeMountLease(got->bytes).min_active_build_sequence, kTerminated) << "the clean farewell did not land"; +} + /// (b1) BOUNDED COMPLETION: FORGET racing an ACTIVE persistent remount worker joins it without deadlock. Here the /// faulting backend keeps every attempt at `StayTransient` (it never reaches `armMountFence`), so this /// isolates the join/no-deadlock property; the fence re-arm path is covered by (b2) below. Uses a diff --git a/src/Disks/tests/gtest_cas_fsck.cpp b/src/Disks/tests/gtest_cas_fsck.cpp index 9941a729dde24..c5b73f503c8b0 100644 --- a/src/Disks/tests/gtest_cas_fsck.cpp +++ b/src/Disks/tests/gtest_cas_fsck.cpp @@ -13,12 +13,15 @@ #include #include #include +#include "cas_killable_query.h" #include "cas_test_helpers.h" #include "config.h" #if USE_AWS_S3 #include #endif +#include +#include #include #include #include @@ -1208,6 +1211,71 @@ TEST(CASFsckAuthority, CheckpointBaseTransportFailureIsUnchecked) } #endif +/// A query's stored cause with the `CORRUPTED_DATA` code is no finding about the chain: a killed `SYSTEM CAS FSCK` +/// whose base read fails with it leaves the namespace unchecked instead of reporting `ChainBroken`. +TEST(CASFsckAuthority, StoredCorruptedDataIsNotChainBroken) +{ + class StoredCauseOnGetBackend final : public InMemoryBackend + { + public: + String key; + std::function on_get; + + std::optional read(const String & requested_key, TransportAccess & access) override + { + if (requested_key == key && on_get) + on_get(); + return InMemoryBackend::read(requested_key, access); + } + }; + + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Layout & layout = store->layout(); + const RootNamespace ns{"00/stored_corruption@cas@"}; + fixture::admitLive(*backend, layout, ns); + + const RefTxnId base{1, 1}; + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + CasOperation op = requests.admit(); + const NamespaceLifeId life = *CasRefCatalog::lifeIfCataloged(op, layout, ns); + fixture::writeRefLogRaw(*backend, layout, RefLogTxn{ + .ns = ns.string(), .txn_id = base, .ops = {namespaceBirthOp()}, .prev_epoch_seal = std::nullopt}); + RefTableState state; + applyRefLogTxn(state, RefLogTxn{ + .ns = ns.string(), .txn_id = base, .ops = {namespaceBirthOp()}, .prev_epoch_seal = std::nullopt}); + writeRefSnapshotRaw(*backend, layout, snapshotOf(state, ns.string())); + writeFsckCheckpointWithBase(*backend, layout, ns, base); + backend->key = layout.refSnapshotKey(life, base); + + std::optional report; + std::exception_ptr error; + std::thread worker([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + /// The store fails the base read the way the S3 client does for a killed query: with the query's cause. + backend->on_get = [&] + { + query.kill(std::make_exception_ptr(DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "the query's stored cause"))); + DB::CurrentThread::checkIfNotCancelled(); + }; + try + { + report = runFsck(*store, /*detail=*/true); + } + catch (...) + { + error = std::current_exception(); + } + backend->on_get = {}; + }); + worker.join(); + ASSERT_TRUE(report.has_value()) << DB::getExceptionMessage(error, false); + EXPECT_EQ(report->chain_broken, 0u); + EXPECT_EQ(report->unchecked, 1u); +} + /// Cleanup may advance `_ckpt` after fsck sampled it and retire the old base before fsck exact-reads it. /// The miss is authority instability, so fsck walks again from the new `_ckpt`, which here names no base. /// Mutation caught: classifying `CORRUPTED_DATA` without rechecking the sampled checkpoint token. diff --git a/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp b/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp index f25858508d8a4..29f3846b26711 100644 --- a/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp +++ b/src/Disks/tests/gtest_cas_gc_frontier_gate.cpp @@ -1,18 +1,25 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include #include #include +#include #include +#include "cas_killable_query.h" #include "cas_test_helpers.h" +#include +#include +#include #include #include @@ -35,8 +42,19 @@ namespace DB::ErrorCodes { + extern const int ABORTED; extern const int NETWORK_ERROR; + extern const int NOT_IMPLEMENTED; + extern const int TIMEOUT_EXCEEDED; extern const int CORRUPTED_DATA; + extern const int QUERY_WAS_CANCELLED; + extern const int READONLY; + extern const int CANNOT_SCHEDULE_TASK; +} + +namespace DB::FailPoints +{ + extern const char thread_group_switcher_post_attach_failure[]; } /// THE DESTRUCTIVE-ROUND FRONTIER PROOF (spec 2026-07-27 "ref chain complete cut" §5). @@ -3590,7 +3608,7 @@ TEST(CASCatalogLifecycleReconciler, ALeaderDeposedWhileQueuedForTheCatalogLaneSe std::thread other_writer([&] { CasOperation other_op = requests.admit(); - (void)other_op.hotKeys().submit(catalog_key, other_op, other_op.freeze(Retry::standard()), + (void)other_op.hotKeys().submit(catalog_key, other_op, Retry::standard(), [&](const std::optional &) -> std::optional { holding.count_down(); @@ -3628,10 +3646,11 @@ TEST(CASCatalogLifecycleReconciler, ALeaderDeposedWhileQueuedForTheCatalogLaneSe EXPECT_EQ(catalogRow(op, layout, stalled.ns), std::optional{stalled}); } -/// The leader reaches the catalog lane with a quarter of its cancel's window left, and every read of -/// `gc/state` fails retryably. The authority check ends by the cancel's deadline: no cancel is sent, the -/// row stays, and the writer queued behind gets the lane by then. -TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsByTheCancelDeadline) +/// The leader reaches the catalog lane after three quarters of a window in the queue, and every read +/// of `gc/state` fails retryably. The authority check in the lane gets a window of its own, measured +/// from its start: no cancel is sent, the row stays, and the writer queued behind gets the lane once +/// that window ends. +TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsOneWindowAfterItsStart) { auto backend = std::make_shared(); auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); @@ -3646,14 +3665,19 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy const CatalogEntry stalled = seedStalledCreating(op, store, "00/slow-authority@cas@", hexToU128("000000000000000000000000000000d5"), CreatorFence{.server_root_id = "gone", .writer_epoch = 1, .fence_generation = 1}); backend->clearJournal(); - backend->afterReadOf(gc_state_key, [] { throw Poco::TimeoutException("injected timeout of the gc/state read"); }); + std::atomic last_authority_read_at = 0; + backend->afterReadOf(gc_state_key, [&] + { + last_authority_read_at = clock.now.load(); + throw Poco::TimeoutException("injected timeout of the gc/state read"); + }); std::latch holding(1); std::latch release(1); std::thread other_writer([&] { CasOperation other_op = requests.admit(); - (void)other_op.hotKeys().submit(catalog_key, other_op, other_op.freeze(Retry::standard()), + (void)other_op.hotKeys().submit(catalog_key, other_op, Retry::standard(), [&](const std::optional &) -> std::optional { holding.count_down(); @@ -3665,8 +3689,10 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy /// Fail-closed like the GC leader's own refresh: authority is held only after a completed read. std::atomic authority_held = true; + std::atomic last_check_started_at = 0; const auto refresh = [&](const Retry & bound) { + last_check_started_at = clock.now.load(); authority_held = false; try { @@ -3680,8 +3706,9 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy } }; CasOperation leader_op = requests.admit([&] { return authority_held.load(); }); - /// The cancel freezes `Retry::standard` before it queues; no fake time passes before that. - const uint64_t cancel_deadline = clock.now.load() + DB::Cas::kDefaultRequestWindowMs; + /// The end a window shared by the queue wait and the check would have; no fake time passes before + /// the leader queues. + const uint64_t shared_deadline = clock.now.load() + DB::Cas::kDefaultRequestWindowMs; const CasFoldSeal parent; CatalogLifecycleReconciler reconciler(leader_op, layout, parent, everyCreatorTerminal); CatalogLifecycleReconcileResult result; @@ -3705,7 +3732,7 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy { CasOperation queued_op = requests.admit(); (void)queued_op.hotKeys().submit(catalog_key, queued_op, - queued_op.freeze(Retry::within(10 * DB::Cas::kDefaultRequestWindowMs)), + Retry::within(10 * DB::Cas::kDefaultRequestWindowMs), [&](const std::optional &) -> std::optional { lane_reached_at = clock.now.load(); @@ -3731,8 +3758,11 @@ TEST(CASCatalogLifecycleReconciler, AnAuthorityReadFailingInTheCatalogLaneEndsBy EXPECT_EQ(reconciler.cancelledCreating(), 0u); EXPECT_EQ(catalogRow(op, layout, stalled.ns), std::optional{stalled}); ASSERT_NE(lane_reached_at.load(), 0u) << "the writer queued behind the leader got the lane"; - EXPECT_LE(lane_reached_at.load(), cancel_deadline) - << "the lane was held " << lane_reached_at.load() - cancel_deadline << " ms past the cancel's deadline"; + EXPECT_GT(last_authority_read_at.load(), shared_deadline) << "the check in the lane was cut at the shared deadline"; + /// One envelope and the longest backoff past the check's own window. + const uint64_t check_end = last_check_started_at.load() + DB::Cas::kDefaultRequestWindowMs; + EXPECT_LE(lane_reached_at.load(), check_end + requests.attemptReservationMs() + 5'000) + << "the lane was held " << lane_reached_at.load() - check_end << " ms past the check's own window"; } /// One creator root has rows at two writer epochs, and its slot is live at the later one. The earlier @@ -5060,7 +5090,7 @@ TEST(CASOwnCreatingCancel, AnAdmissionStartingInsideTheLaneKeepsTheRow) std::thread holder([&] { CasOperation holder_op = store->mountRequests().admit(); - (void)holder_op.hotKeys().submit(catalog_key, holder_op, holder_op.freeze(Retry::standard()), + (void)holder_op.hotKeys().submit(catalog_key, holder_op, Retry::standard(), [&](const std::optional &) -> std::optional { holding.count_down(); @@ -5822,3 +5852,1250 @@ TEST(CASGCFrontierGate, ACreatingOnlyCatalogRegainsAProvenFrontier) EXPECT_TRUE(after.frontier_complete); EXPECT_FALSE(after.suppress_destructive); } + +namespace +{ + +/// Kills `kill` once a conditional write moves `gc/state` to `generation` or beyond: the round has just +/// committed, and the post-commit tail has not started. +class KillAtRoundCommitBackend final : public CountingBackend +{ +public: + String gc_state_key; + uint64_t generation = 0; + std::function kill; + std::atomic fired{false}; + + std::expected write( + const String & key, const String & bytes, const std::optional & expected_value, + TransportAccess & access) override + { + std::expected result = CountingBackend::write(key, bytes, expected_value, access); + if (kill && result.has_value() && expected_value && key == gc_state_key + && decodeGcState(bytes).snap_generation >= generation && !fired.exchange(true)) + kill(); + return result; + } +}; + +} + +/// A manual round whose query is killed right after the round commit still reclaims the hand-off +/// prefix: the hand-off is one-shot, so the stop must not cost it. +TEST(CASGCFrontierGate, StoppedManualRoundStillReclaimsHandoffPrefix) +{ + auto backend = std::make_shared(); + auto store = Pool::open(backend, + PoolConfig{.pool_prefix = "p", .server_root_id = "test", + .gc_snapshot_generations_to_keep = 2, .gc_fold_max_defer_rounds = 0}); + const Layout & layout = store->layout(); + const RootNamespace ns{"00/aa@cas@"}; + const ManifestRef r1 = publish(*backend, layout, ns, "tbl", 1, DB::UInt128(0xa1)); + + Gc gc(store, kGc); + runRegularRoundReclaiming(gc); + store->renewWatermarkOnce(); + OperationForTest raw_op(*backend); + const uint64_t old_gen = decodeGcState((*raw_op).read(layout.gcStateKey(), Retry::once())->bytes).snap_generation; + const String old_prefix = layout.gcGenPrefix(old_gen); + for (int i = 0; i < 6; ++i) + { + runRegularRoundReclaiming(gc); + store->renewWatermarkOnce(); + } + const GcState before = decodeGcState((*raw_op).read(layout.gcStateKey(), Retry::once())->bytes); + ASSERT_GT(before.snap_pruned_through, old_gen) << "the generation must be behind the retention cursor"; + ASSERT_FALSE((*raw_op).list(old_prefix, "", 1000, Retry::once()).keys.empty()) << "a live ref still pins it"; + + const ManifestRef r2{.writer_epoch = 1, .build_sequence = 2, .manifest_ordinal = 1}; + writeBlobBody(*backend, layout, DB::UInt128(0xb2)); + writeManifestRaw(*backend, layout, ns, r2, {blobEntryFor("data.bin", DB::UInt128(0xb2))}); + publishCommittedTransition(*backend, layout, ns, "tbl", r1, r2); + + backend->gc_state_key = layout.gcStateKey(); + backend->generation = before.snap_generation + 1; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->kill = [&query] { query.kill(); }; + try + { + runRegularRoundReclaiming(gc); + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::QUERY_WAS_CANCELLED) << e.message(); + } + backend->kill = {}; + }); + + ASSERT_TRUE(backend->fired) << "the query was not killed at the round commit"; + EXPECT_TRUE((*raw_op).list(old_prefix, "", 1000, Retry::once()).keys.empty()) + << "the hand-off prefix is reclaimed by the stopped round"; +} + +/// The catalog reconciler of a stopped manual round (driven directly, not through a full round) resolves +/// its attempted erase of a completed `Removing` row by a complete catalog read, even when its owner stops +/// during the backoff after that read's first attempt failed. The drain then stops before its next selection. +TEST(CASGCFrontierGate, StoppedDrainReconcilerStillResolvesAttemptedErase) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + const Layout & layout = store->layout(); + CasRequests seed_requests = openRequestsForTest(backend); + CasOperation seed_op = seed_requests.admit(); + const CompletedRemovingFixture fixture = seedCompletedRemoving(seed_op, store, kGc); + + size_t catalog_reads = 0; + std::atomic resolution_read_failed{false}; + backend->afterReadOf(layout.refCatalogKey(), [&] + { + if (++catalog_reads == 2) + { + resolution_read_failed = true; + throw Poco::TimeoutException("the erase's resolution read is lost"); + } + }); + + uint64_t completed_erases = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + if (resolution_read_failed) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + CasOperation op = requests.admit(); + const auto parent_object = op.read(layout.foldSealKey(1, 1), Retry::once()); + ASSERT_TRUE(parent_object); + const CasFoldSeal parent = decodeFoldSeal(parent_object->bytes); + CatalogLifecycleReconciler reconciler(op, layout, parent, noCreatorProvedTerminal); + expectThrowsCode(DB::ErrorCodes::QUERY_WAS_CANCELLED, + [&] { reconciler.reconcile(noAuthorityRefresh, noRetirementRecord); }); + completed_erases = reconciler.completedErases(); + EXPECT_TRUE(query.status->isKilled()) << "the owner stopped before the reissue"; + }); + backend->afterReadOf(layout.refCatalogKey(), {}); + + ASSERT_TRUE(resolution_read_failed); + EXPECT_EQ(catalog_reads, 3u) << "selection, the failed resolution read and its reissue"; + EXPECT_EQ(completed_erases, 1u); + EXPECT_FALSE(CasRefCatalog::lifeIfCataloged(seed_op, layout, fixture.ns)) << "the erase landed and was observed"; +} + +namespace +{ + +/// A gate the test opens on every exit, so a failed assertion cannot strand a parked round thread. +class OpenOnExitGate +{ +public: + ~OpenOnExitGate() { open(); } + + void open() + { + std::lock_guard lock(mutex); + opened = true; + cv.notify_all(); + } + + bool wait() + { + std::unique_lock lock(mutex); + return cv.wait_for(lock, std::chrono::seconds(30), [&] { return opened; }); + } + +private: + std::mutex mutex; + std::condition_variable cv; + bool opened = false; +}; + +/// A lease nobody holds, so a scheduler with its own random identity claims it on its first round. +void freeGcLease(Backend & backend, const Layout & layout) +{ + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + const auto got = op.read(layout.gcStateKey(), Retry::once()); + ASSERT_TRUE(got); + GcState state = decodeGcState(got->bytes); + state.lease = GcLease{.owner = UInt128(0), .seq = 0}; + ASSERT_TRUE(std::holds_alternative( + op.replace(layout.gcStateKey(), encodeGcState(state), got->etag, Retry::once()))); +} + +/// Calls `stop` from another thread, because it joins the round thread that asks for it, and returns once +/// the stop is visible to the round. +std::future requestSchedulerStop(CasGcScheduler & scheduler) +{ + auto stopping = std::async(std::launch::async, [&scheduler] { scheduler.stop(); }); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (!scheduler.stopRequested() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + EXPECT_TRUE(scheduler.stopRequested()); + return stopping; +} + +std::vector journalAfter(const std::vector & journal, size_t from, const String & except_key) +{ + std::vector tail; + for (size_t i = from; i < journal.size(); ++i) + if (!journal[i].ends_with(" " + except_key)) + tail.push_back(journal[i]); + return tail; +} + +} + +/// A scheduled round stopped between two erases of its pre-fold drain: the first erase and its resolution +/// read complete, nothing follows them, and the round ends `Stopped` without its listing or commit. The +/// next activation drains the row left. +TEST(CASGCFrontierGate, StopBetweenErasesSkipsSecondAndFold) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemovingBatch(op, store, kGc, /*count=*/2); + freeGcLease(*backend, layout); + const std::vector seeded{ + RootNamespace{"00/drain-batch-0@cas@"}, RootNamespace{"00/drain-batch-1@cas@"}}; + const uint64_t catalog_writes_before = backend->putOverwriteCount(layout.refCatalogKey()); + + OwnerRoundSink sink; + ScopedCasGcLogCapture scheduler_log("test::gc"); + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + OpenOnExitGate parked; + OpenOnExitGate release; + std::atomic fired = false; + size_t journal_at_stop = 0; + uint64_t state_writes_at_stop = 0; + /// The first catalog read with an erase behind it is that erase's resolution read. + backend->afterReadOf(layout.refCatalogKey(), [&] + { + if (backend->putOverwriteCount(layout.refCatalogKey()) == catalog_writes_before || fired.exchange(true)) + return; + journal_at_stop = backend->journalSnapshot().size(); + state_writes_at_stop = backend->putOverwriteCount(layout.gcStateKey()); + parked.open(); + release.wait(); + }); + scheduler.start(); + scheduler.requestRoundSoon(); + ASSERT_TRUE(parked.wait()) << "the round never resolved its first erase"; + std::future stopping = requestSchedulerStop(scheduler); + release.open(); + const std::optional finish = sink.waitForFinish(); + ASSERT_EQ(stopping.wait_for(std::chrono::seconds(30)), std::future_status::ready); + backend->afterReadOf(layout.refCatalogKey(), {}); + + ASSERT_TRUE(finish); + EXPECT_EQ(finish->outcome, GcRoundLogRecord::Outcome::Stopped) << finish->error; + EXPECT_EQ(finish->error_code, DB::ErrorCodes::ABORTED) << finish->error; + EXPECT_EQ(scheduler_log.captured().find("round failed"), String::npos) << scheduler_log.captured(); + EXPECT_EQ(backend->putOverwriteCount(layout.refCatalogKey()), catalog_writes_before + 1); + const std::vector tail = journalAfter(backend->journalSnapshot(), journal_at_stop, layout.gcHbKey()); + EXPECT_TRUE(tail.empty()) << "first request after the resolution read: " << tail.front(); + EXPECT_EQ(backend->putOverwriteCount(layout.gcStateKey()), state_writes_at_stop) << "the round committed"; + size_t still_cataloged = 0; + for (const RootNamespace & ns : seeded) + if (CasRefCatalog::lifeIfCataloged(op, layout, ns)) + ++still_cataloged; + EXPECT_EQ(still_cataloged, 1u); + + const auto finishes = [&] + { + std::vector rows; + for (const GcRoundLogRecord & r : sink.all()) + if (r.event_type == GcRoundLogRecord::EventType::Finish) + rows.push_back(r); + return rows; + }; + scheduler.start(); + scheduler.requestRoundSoon(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (finishes().size() < 2 && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + scheduler.stop(); + ASSERT_EQ(finishes().size(), 2u) << "the next activation ran no round"; + EXPECT_EQ(finishes()[1].outcome, GcRoundLogRecord::Outcome::Success) << finishes()[1].error; + for (const RootNamespace & ns : seeded) + EXPECT_FALSE(CasRefCatalog::lifeIfCataloged(op, layout, ns)) << ns.string(); +} + +/// A scheduled round stopped after its erase's reply was lost settles that erase by a read and sends it +/// once; the drain then stops before anything else. +TEST(CASGCFrontierGate, StopAfterLostEraseSettlesWithoutResend) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemovingBatch(op, store, kGc, /*count=*/2); + const String catalog_key = layout.refCatalogKey(); + const uint64_t catalog_writes_before = backend->putOverwriteCount(catalog_key); + backend->clearJournal(); + backend->loseNextCatalogCasResponse(catalog_key); + + Gc gc(store, kGc); + gc.setStopSignal([&] + { + const std::vector journal = backend->journalSnapshot(); + return std::find(journal.begin(), journal.end(), "cas_response_lost " + catalog_key) != journal.end(); + }); + expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { gc.runRegularRound(); }); + gc.setStopSignal({}); + + const std::vector journal = backend->journalSnapshot(); + EXPECT_EQ(std::count(journal.begin(), journal.end(), "cas_begin " + catalog_key), 1) << "the lost erase was resent"; + EXPECT_EQ(std::count(journal.begin(), journal.end(), "cas_response_lost " + catalog_key), 1); + EXPECT_EQ(backend->putOverwriteCount(catalog_key), catalog_writes_before + 1); + ASSERT_FALSE(journal.empty()); + EXPECT_EQ(journal.back(), "get " + catalog_key) << "the drain sent more after resolving the lost erase"; + const auto row_count = CasRefCatalog::read(op, layout).catalog.entries.size(); + EXPECT_EQ(row_count, 1u) << "the settled erase landed; the second row stays"; +} + +/// A drain whose owner stopped during the first of several creator probes probes no other creator. A +/// failed probe of a stopped owner is not reported as an unreadable creator slot. +TEST(CASGCFrontierGate, StopAfterFirstOfSeveralCreatorProbesProbesNoMore) +{ + for (const bool probe_fails : {false, true}) + { + SCOPED_TRACE(probe_fails ? "the probe fails" : "the probe answers"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + std::vector rows; + for (size_t i = 0; i < 3; ++i) + rows.push_back(seedStalledCreating(op, store, fmt::format("00/probe-{}@cas@", i), UInt128{0xc0 + i}, + CreatorFence{.server_root_id = fmt::format("creator-{}", i), .writer_epoch = 1, .fence_generation = 1})); + + bool stopped = false; + size_t probes = 0; + const CasFoldSeal parent; + CatalogLifecycleReconciler reconciler(op, layout, parent, [&](const CreatorFence &) + { + ++probes; + stopped = true; + if (probe_fails) + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected mount slot read failure"); + return CreatorSlotStatus::Live; + }); + ScopedCasGcLogCapture capture("CatalogLifecycleReconciler"); + { + const auto owner = OwnerScope::background([&] + { + if (stopped) + throw DB::Exception(DB::ErrorCodes::ABORTED, "test owner stopped"); + }); + expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { reconciler.reconcile(noAuthorityRefresh, noRetirementRecord); }); + } + + EXPECT_EQ(probes, 1u); + EXPECT_EQ(capture.captured().find("could not be read"), String::npos) << capture.captured(); + for (const CatalogEntry & row : rows) + EXPECT_EQ(catalogRow(op, layout, row.ns), std::optional{row}) << row.ns.string(); + } +} + +/// A manual round's drain whose query is killed while the first of several creator probes answers ends at the next +/// row with the query's own error: nothing failed, so there is no failure to keep, and no other creator is probed. +TEST(CASGCFrontierGate, KilledQueryEndsTheDrainAtTheNextRow) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + std::vector rows; + for (size_t i = 0; i < 3; ++i) + rows.push_back(seedStalledCreating(op, store, fmt::format("00/killed-probe-{}@cas@", i), UInt128{0xd0 + i}, + CreatorFence{.server_root_id = fmt::format("killed-creator-{}", i), .writer_epoch = 1, .fence_generation = 1})); + + size_t probes = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + const CasFoldSeal parent; + CatalogLifecycleReconciler reconciler(op, layout, parent, [&](const CreatorFence &) + { + ++probes; + query.kill(); + return CreatorSlotStatus::Live; + }); + expectThrowsCode(DB::ErrorCodes::QUERY_WAS_CANCELLED, + [&] { reconciler.reconcile(noAuthorityRefresh, noRetirementRecord); }); + }); + + EXPECT_EQ(probes, 1u); + for (const CatalogEntry & row : rows) + EXPECT_EQ(catalogRow(op, layout, row.ns), std::optional{row}) << row.ns.string(); +} + +/// A scheduled round deposed inside its drain, with the stop requested only after the drain's last owner +/// check, ends `Aborted`: the scheduler reports a stop the round observed, never one it samples afterwards. +TEST(CASGCFrontierGate, DepositionDuringStopIsNotStopped) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + const CompletedRemovingFixture fixture = seedCompletedRemoving(op, store, kGc); + freeGcLease(*backend, layout); + const String seal_key = layout.foldSealKey(1, 1); + const uint64_t seal_reads_before = backend->getCount(seal_key); + + OwnerRoundSink sink; + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + /// The drain reads its parent seal, then `gc/state` for its authority, then `gc/state` again before the + /// erase. The first of these deposes the leader; the second, which reads the deposition, requests the stop. + bool in_hook = false; + bool deposed = false; + std::optional> stopping; + backend->afterReadOf(layout.gcStateKey(), [&] + { + if (in_hook || stopping || backend->getCount(seal_key) == seal_reads_before) + return; + in_hook = true; + if (!deposed) + { + transferGcLease(*backend, layout, hexToU128("00000000000000000000000000000099")); + deposed = true; + } + else + { + stopping = requestSchedulerStop(scheduler); + } + in_hook = false; + }); + scheduler.start(); + scheduler.requestRoundSoon(); + const std::optional finish = sink.waitForFinish(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (!scheduler.stopRequested() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + scheduler.stop(); + backend->afterReadOf(layout.gcStateKey(), {}); + + ASSERT_TRUE(finish); + ASSERT_TRUE(stopping) << "the round never reached the erase's authority read"; + EXPECT_EQ(finish->outcome, GcRoundLogRecord::Outcome::Aborted) << finish->error; + EXPECT_NE(finish->error_code, DB::ErrorCodes::ABORTED) << finish->error; + EXPECT_TRUE(CasRefCatalog::lifeIfCataloged(op, layout, fixture.ns)); +} + +/// A manual round on a stopped scheduler that meets corruption is `Failed`: a stopped scheduler names no +/// stop of a round it did not run. +TEST(CASGCFrontierGate, CorruptionOnStoppedSchedulerManualRoundIsFailed) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + GcState state; + state.round = 1; + state.gc_shards = store->poolConfig().gc_shards; + state.snap_generation = 1; + state.snap_attempt = 1; + ASSERT_TRUE(std::holds_alternative(op.create(layout.gcStateKey(), encodeGcState(state), Retry::once()))); + + OwnerRoundSink sink; + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + scheduler.start(); + scheduler.stop(); + ASSERT_TRUE(scheduler.stopRequested()); + expectThrowsCode(DB::ErrorCodes::CORRUPTED_DATA, + [&] { (void)scheduler.runOneRoundNow(GcRoundLogRecord::Trigger::Manual); }); + + const std::optional finish = sink.waitForFinish(); + ASSERT_TRUE(finish); + EXPECT_EQ(finish->outcome, GcRoundLogRecord::Outcome::Failed) << finish->error; + EXPECT_EQ(finish->error_code, DB::ErrorCodes::CORRUPTED_DATA); +} + +/// A scheduled round whose drain saw no stop still stops before the hot listing: on a fresh pool the drain +/// reads nothing, and the round lists nothing. +TEST(CASGCFrontierGate, StopBeforeTheHotListingListsNothing) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + Gc gc(store, kGc); + gc.setStopSignal([] { return true; }); + expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { gc.runRegularRound(); }); + gc.setStopSignal({}); + EXPECT_EQ(backend->listCount(store->layout().casRefsPrefix()), 0u); +} + +namespace +{ + +/// Runs `fail` once, in place of the answer to the first read or listing whose name `matches` accepts. +class FailOneRequestBackend final : public CountingBackend +{ +public: + using CountingBackend::list; + + void failFirst(std::function matches_, std::function fail_) + { + std::lock_guard lock(mutex); + matches = std::move(matches_); + fail = std::move(fail_); + } + + bool fired() const + { + std::lock_guard lock(mutex); + return did_fire; + } + + std::optional read(const String & key, TransportAccess & access) override + { + failIfArmed(key); + return CountingBackend::read(key, access); + } + + RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override + { + failIfArmed(prefix); + return CountingBackend::list(prefix, cursor, limit, access); + } + +private: + void failIfArmed(const String & name) + { + std::function now; + { + std::lock_guard lock(mutex); + if (fail && matches(name)) + { + now = std::move(fail); + fail = {}; + did_fire = true; + } + } + if (now) + now(); + } + + mutable std::mutex mutex; + std::function matches; + std::function fail; + bool did_fire = false; +}; + +} + +/// A killed manual round whose authority read fails reports that failure, not a lost lease. +TEST(CASGCFrontierGate, StoppedOwnersFailedAuthorityReadIsNotALostLease) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + const String seal_key = layout.foldSealKey(1, 1); + const uint64_t seal_reads_before = backend->getCount(seal_key); + + ScopedCasGcLogCapture capture; + onKillableQueryThread([&](CasKillableQuery & query) + { + /// The drain reads its parent seal, then `gc/state` for its authority. + backend->failFirst( + [&](const String & name) { return name == layout.gcStateKey() && backend->getCount(seal_key) > seal_reads_before; }, + [&] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected gc/state read failure"); + }); + Gc gc(store, kGc); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "injected gc/state read failure", [&] { gc.runRegularRound(); }); + }); + + ASSERT_TRUE(backend->fired()); + EXPECT_EQ(capture.captured().find("leader-authority probe failed"), String::npos) << capture.captured(); +} + +/// A manual round killed while the namespace janitor lists fails with the listing's failure; the janitor does not +/// report it as a stopped page of a successful round. +TEST(CASGCFrontierGate, KilledManualRoundIsNotSwallowedByTheJanitor) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + + ScopedCasGcLogCapture capture; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->failFirst( + [&](const String & name) { return name == layout.namespaceRootPrefix(); }, + [&] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected janitor listing failure"); + }); + Gc gc(store, kGc); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "injected janitor listing failure", [&] { gc.runRegularRound(); }); + }); + + ASSERT_TRUE(backend->fired()) << "the round never ran its janitor"; + EXPECT_EQ(capture.captured().find("janitor stopped this round"), String::npos) << capture.captured(); +} + +/// The deferral decision reads the adopted fold seal. A read that fails for a killed manual round ends the round with +/// its failure, reading the seal no more; under a live query the same failure forces a fold instead of a deferral. +TEST(CASGCFrontierGate, KilledRoundsFailedDeferralSealReadEndsTheRound) +{ + struct Run + { + int code = 0; + String message; + std::optional report; + uint64_t seal_reads_at_decision = 0; + uint64_t seal_reads = 0; + }; + enum class Arm { Control, Live, Killed }; + const auto run = [](Arm arm, uint64_t fail_after_reads) + { + Run out; + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + const String seal_key = layout.foldSealKey(1, 1); + onKillableQueryThread([&](CasKillableQuery & query) + { + Gc gc(store, kGc); + /// The decision's read is the last seal read before the hot scan's catalog read. + gc.setRoundPointHookForTest([&](const Gc::RoundPointSiteForTest & site) + { + if (site.point == Gc::RoundPointForTest::AfterCatalogRead && out.seal_reads_at_decision == 0) + out.seal_reads_at_decision = backend->getCount(seal_key); + }); + if (arm != Arm::Control) + backend->failFirst( + [&](const String & name) { return name == seal_key && backend->getCount(seal_key) == fail_after_reads; }, + [&, arm] + { + if (arm == Arm::Killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected seal read refusal"); + }); + try + { + out.report = gc.runRegularRound(); + } + catch (const DB::Exception & e) + { + out.code = e.code(); + out.message = e.message(); + } + }); + out.seal_reads = backend->getCount(seal_key); + return out; + }; + + const Run control = run(Arm::Control, 0); + ASSERT_TRUE(control.report) << control.message; + ASSERT_TRUE(control.report->deferred) << "the fixture's round must be eligible for deferral"; + ASSERT_GE(control.seal_reads_at_decision, 1u); + const uint64_t reads_before_decision = control.seal_reads_at_decision - 1; + + const Run live = run(Arm::Live, reads_before_decision); + ASSERT_TRUE(live.report) << live.message; + EXPECT_FALSE(live.report->deferred) << "a live query's failed seal read forces the fold"; + + const Run killed = run(Arm::Killed, reads_before_decision); + EXPECT_FALSE(killed.report.has_value()); + EXPECT_EQ(killed.code, DB::ErrorCodes::READONLY) << killed.message; + EXPECT_NE(killed.message.find("injected seal read refusal"), String::npos) << killed.message; + EXPECT_EQ(killed.seal_reads, reads_before_decision) << "the killed round read the seal again"; +} + +/// A killed manual round whose janitor batch delete fails ends with that failure and leaves the janitor's cursor +/// where it was; under a live query the same failure is a recorded leak and the round succeeds. +TEST(CASGCFrontierGate, KilledRoundsFailedJanitorBatchDeletePublishesNoPage) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + /// An authoritative universe must not be empty for the destructive gate to open. + const RootNamespace live_namespace{"live/janitor-kill@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + ASSERT_TRUE(std::holds_alternative(op.create( + layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, + .last_epoch_seal = std::nullopt}, 1), + Retry::once()))); + const String dead_log = layout.refLogKey( + NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-kill"}, UInt128{0xDB}), RefTxnId{1, 1}); + ASSERT_TRUE(std::holds_alternative(op.create(dead_log, "dead residue", Retry::once()))); + const GcMaintenanceReadResult progress_before = readGcMaintenanceState(op, layout); + + std::map namespace_cleanup; + int code = 0; + String message; + std::atomic fired{false}; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->onBeforeBulkRemove([&] + { + if (fired.exchange(true)) + return; + if (killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected batch delete refusal"); + }); + Gc gc(store, kGc); + gc.setPhaseSink([&](const GcPhaseRecord & record) + { + if (record.phase == "namespace_cleanup") + namespace_cleanup = record.metrics; + }); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + backend->onBeforeBulkRemove({}); + }); + + ASSERT_TRUE(fired.load()) << "the round sent no janitor batch delete"; + EXPECT_TRUE(op.head(dead_log, Retry::once()).has_value()); + if (killed) + { + EXPECT_EQ(code, DB::ErrorCodes::READONLY) << message; + EXPECT_NE(message.find("injected batch delete refusal"), String::npos) << message; + const GcMaintenanceReadResult progress_after = readGcMaintenanceState(op, layout); + EXPECT_EQ(progress_after.etag.has_value(), progress_before.etag.has_value()); + if (progress_after.etag && progress_before.etag) + EXPECT_TRUE(sameVersion(*progress_after.etag, *progress_before.etag)) << "the janitor published the page"; + } + else + { + EXPECT_EQ(code, 0) << message; + ASSERT_FALSE(namespace_cleanup.empty()); + EXPECT_EQ(namespace_cleanup["leaked"], 1u); + } + } +} + +/// A store without batch delete makes the janitor delete one key at a time. A killed manual round whose first such +/// delete fails sends no further delete and leaves the janitor's cursor where it was; under a live query the failure is +/// a recorded leak and the next key is still deleted. +TEST(CASGCFrontierGate, KilledRoundsFailedJanitorSingleKeyFallbackPublishesNoPage) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + /// An authoritative universe must not be empty for the destructive gate to open. + const RootNamespace live_namespace{"live/janitor-fallback-kill@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + ASSERT_TRUE(std::holds_alternative(op.create( + layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, + .last_epoch_seal = std::nullopt}, 1), + Retry::once()))); + const NamespaceLifeId dead_life + = NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-fallback-kill"}, UInt128{0xDD}); + const std::vector dead_logs{layout.refLogKey(dead_life, RefTxnId{1, 1}), layout.refLogKey(dead_life, RefTxnId{1, 2})}; + for (const String & key : dead_logs) + ASSERT_TRUE(std::holds_alternative(op.create(key, "dead residue", Retry::once()))); + const GcMaintenanceReadResult progress_before = readGcMaintenanceState(op, layout); + + std::map namespace_cleanup; + int code = 0; + String message; + std::atomic janitor_deletes{0}; + std::atomic calls_at_failure{0}; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->onBeforeBulkRemove([&] + { + const int n = ++janitor_deletes; + if (n == 1) + throw DB::Exception(DB::ErrorCodes::NOT_IMPLEMENTED, "injected: no batch delete"); + if (n != 2) + return; + calls_at_failure = backend->bulkRemoveCalls(); + if (killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected single-key delete refusal"); + }); + Gc gc(store, kGc); + gc.setPhaseSink([&](const GcPhaseRecord & record) + { + if (record.phase == "namespace_cleanup") + namespace_cleanup = record.metrics; + }); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + backend->onBeforeBulkRemove({}); + }); + + ASSERT_GE(janitor_deletes.load(), 2) << "the round never fell back to single-key deletes"; + size_t remaining = 0; + for (const String & key : dead_logs) + remaining += op.head(key, Retry::once()).has_value() ? 1 : 0; + if (killed) + { + EXPECT_EQ(code, DB::ErrorCodes::READONLY) << message; + EXPECT_NE(message.find("injected single-key delete refusal"), String::npos) << message; + EXPECT_EQ(backend->bulkRemoveCalls(), calls_at_failure.load()) << "a delete was sent after the failed one"; + EXPECT_EQ(remaining, 2u); + const GcMaintenanceReadResult progress_after = readGcMaintenanceState(op, layout); + EXPECT_EQ(progress_after.etag.has_value(), progress_before.etag.has_value()) << "the janitor published the page"; + if (progress_after.etag && progress_before.etag) + EXPECT_TRUE(sameVersion(*progress_after.etag, *progress_before.etag)) << "the janitor published the page"; + } + else + { + EXPECT_EQ(code, 0) << message; + EXPECT_EQ(remaining, 1u) << "the key after the failed one is still deleted"; + ASSERT_FALSE(namespace_cleanup.empty()); + EXPECT_EQ(namespace_cleanup["leaked"], 1u); + } + } +} + +/// A janitor delete worker that fails to join the manual round's query sends nothing: outside the query its request +/// would not see the query's stop. The janitor stops with that failure and its cursor stays where it was; a janitor +/// failure under a live query does not fail the round. +TEST(CASGCFrontierGate, JanitorWorkerOutsideTheRoundsQueryDeletesNothing) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + for (const bool attach_fails : {false, true}) + { + SCOPED_TRACE(attach_fails ? "worker attach fails" : "control"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + /// An authoritative universe must not be empty for the destructive gate to open. + const RootNamespace live_namespace{"live/janitor-group@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + ASSERT_TRUE(std::holds_alternative(op.create( + layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, + .last_epoch_seal = std::nullopt}, 1), + Retry::once()))); + const String dead_log = layout.refLogKey( + NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-group"}, UInt128{0xDE}), RefTxnId{1, 1}); + ASSERT_TRUE(std::holds_alternative(op.create(dead_log, "dead residue", Retry::once()))); + const GcMaintenanceReadResult progress_before = readGcMaintenanceState(op, layout); + + int code = 0; + String message; + std::optional deletes_at_arming; + ScopedCasGcLogCapture capture; + onKillableQueryThread([&](CasKillableQuery &) + { + /// Armed at the janitor's listing, after the round's own attach, so a janitor worker's switch fails. + backend->failFirst( + [&](const String & name) { return attach_fails && name == layout.namespaceRootPrefix(); }, + [&] + { + deletes_at_arming = backend->bulkRemoveCalls(); + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + }); + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + Gc gc(store, kGc); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + + if (!attach_fails) + { + EXPECT_EQ(code, 0) << message; + EXPECT_FALSE(op.head(dead_log, Retry::once()).has_value()) << "positive control: the janitor deletes the residue"; + continue; + } + ASSERT_TRUE(deletes_at_arming.has_value()) << "the round never listed the namespace roots"; + EXPECT_EQ(code, 0) << message; + EXPECT_NE(capture.captured().find("janitor delete worker could not join"), String::npos) << capture.captured(); + EXPECT_EQ(backend->bulkRemoveCalls(), *deletes_at_arming) << "a janitor worker outside the query sent a delete"; + EXPECT_TRUE(op.head(dead_log, Retry::once()).has_value()); + const GcMaintenanceReadResult progress_after = readGcMaintenanceState(op, layout); + EXPECT_EQ(progress_after.etag.has_value(), progress_before.etag.has_value()) << "the janitor published the page"; + if (progress_after.etag && progress_before.etag) + EXPECT_TRUE(sameVersion(*progress_after.etag, *progress_before.etag)) << "the janitor published the page"; + } +} + +namespace +{ + +/// Runs `on_remove` once, before the first `DELETE` of `target` reaches the store. +class RemoveHookBackend final : public CountingBackend +{ +public: + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + std::function hook; + if (key == target) + hook = std::exchange(on_remove, {}); + if (hook) + hook(); + return CountingBackend::remove(key, expected_value, access); + } + + String target; + std::function on_remove; +}; + +} + +/// A killed manual round whose janitor exact delete of one key fails ends with that failure and leaves the janitor's +/// cursor where it was; under a live query the same failure is a recorded leak and the round succeeds. +TEST(CASGCFrontierGate, KilledRoundsFailedJanitorExactDeletePublishesNoPage) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + /// An authoritative universe must not be empty for the destructive gate to open. + const RootNamespace live_namespace{"live/janitor-exact-kill@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + ASSERT_TRUE(std::holds_alternative(op.create( + layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, + .last_epoch_seal = std::nullopt}, 1), + Retry::once()))); + /// A dead life's checkpoint is mutable, so the janitor deletes it exactly, one key at a time. + const String dead_ckpt = layout.refCkptKey( + NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-exact-kill"}, UInt128{0xDC})); + ASSERT_TRUE(std::holds_alternative(op.create(dead_ckpt, "dead checkpoint", Retry::once()))); + const GcMaintenanceReadResult progress_before = readGcMaintenanceState(op, layout); + + std::map namespace_cleanup; + int code = 0; + String message; + bool fired = false; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->target = dead_ckpt; + backend->on_remove = [&] + { + fired = true; + if (killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected exact delete refusal"); + }; + Gc gc(store, kGc); + gc.setPhaseSink([&](const GcPhaseRecord & record) + { + if (record.phase == "namespace_cleanup") + namespace_cleanup = record.metrics; + }); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + + ASSERT_TRUE(fired) << "the round sent no janitor delete of the dead checkpoint"; + EXPECT_TRUE(op.head(dead_ckpt, Retry::once()).has_value()); + if (killed) + { + EXPECT_EQ(code, DB::ErrorCodes::READONLY) << message; + EXPECT_NE(message.find("injected exact delete refusal"), String::npos) << message; + const GcMaintenanceReadResult progress_after = readGcMaintenanceState(op, layout); + EXPECT_EQ(progress_after.etag.has_value(), progress_before.etag.has_value()) << "the janitor published the page"; + if (progress_after.etag && progress_before.etag) + EXPECT_TRUE(sameVersion(*progress_after.etag, *progress_before.etag)) << "the janitor published the page"; + } + else + { + EXPECT_EQ(code, 0) << message; + ASSERT_FALSE(namespace_cleanup.empty()); + EXPECT_EQ(namespace_cleanup["leaked"], 1u); + } + } +} + +/// A manual round stopped by its query is `Stopped`, for a kill and for `max_execution_time`, and ends with the +/// failure that observed the stop. A 159 while the query is live is not a query stop, so that round stays `Aborted`. +TEST(CASGCFrontierGate, QueryStopOfAManualRoundIsStopped) +{ + enum class Stop { Kill, QueryTimeout, LiveQueryTimeout }; + for (const Stop how : {Stop::Kill, Stop::QueryTimeout, Stop::LiveQueryTimeout}) + { + SCOPED_TRACE(how == Stop::Kill ? "kill" : how == Stop::QueryTimeout ? "query timeout" : "159 under a live query"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + freeGcLease(*backend, layout); + + OwnerRoundSink sink; + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + /// A 159 that is not the query's: the query stays live while another owner reports a timeout. + std::atomic timed_out{false}; + const auto other_owner = OwnerScope::background([&] + { + if (timed_out) + throw DB::Exception(DB::ErrorCodes::TIMEOUT_EXCEEDED, "Timeout exceeded"); + }); + backend->failFirst( + [&](const String & name) { return name == layout.foldSealKey(1, 1); }, + [&] + { + if (how == Stop::LiveQueryTimeout) + timed_out = true; + else if (how == Stop::QueryTimeout) + query.kill(std::make_exception_ptr(DB::Exception(DB::ErrorCodes::TIMEOUT_EXCEEDED, "Timeout exceeded"))); + else + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected seal read failure"); + }); + try + { + (void)scheduler.runOneRoundNow(GcRoundLogRecord::Trigger::Manual); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_TRUE(backend->fired()); + EXPECT_EQ(code, how == Stop::LiveQueryTimeout ? DB::ErrorCodes::TIMEOUT_EXCEEDED : DB::ErrorCodes::NETWORK_ERROR); + const std::optional finish = sink.waitForFinish(); + ASSERT_TRUE(finish); + EXPECT_EQ(finish->error_code, code) << finish->error; + EXPECT_EQ(finish->outcome, how == Stop::LiveQueryTimeout ? GcRoundLogRecord::Outcome::Aborted : GcRoundLogRecord::Outcome::Stopped) + << finish->error; + } +} + +/// A manual round that runs after a scheduled round ended at `SYSTEM CAS GC STOP`, but before the scheduler +/// classified that failure, does not turn the stop into a failed round in the log. +TEST(CASGCFrontierGate, ManualRoundBeforeTheStopIsClassifiedKeepsTheStop) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + + OwnerRoundSink sink; + ScopedCasGcLogCapture scheduler_log("test::gc", "information"); + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + std::future stopping; + std::promise stop_issued; + std::atomic tick_seen = false; + /// The stop is visible before the round starts, so the round's pre-listing poll ends it. + scheduler.setBeforeTickLockHookForTest([&] + { + if (tick_seen.exchange(true)) + return; + stopping = requestSchedulerStop(scheduler); + stop_issued.set_value(); + }); + std::atomic manual_ran = false; + scheduler.setTickFailureHookForTest([&] + { + if (manual_ran.exchange(true)) + return; + try + { + (void)scheduler.runOneRoundNow(GcRoundLogRecord::Trigger::Manual); + } + catch (...) + { + ADD_FAILURE() << "the manual round failed: " << DB::getCurrentExceptionMessage(false); + } + }); + scheduler.start(); + scheduler.requestRoundSoon(); + ASSERT_EQ(stop_issued.get_future().wait_for(std::chrono::seconds(60)), std::future_status::ready) << "no tick ran"; + ASSERT_EQ(stopping.wait_for(std::chrono::seconds(60)), std::future_status::ready); + + ASSERT_TRUE(manual_ran) << "the scheduled round did not fail"; + std::vector finishes; + for (const GcRoundLogRecord & r : sink.all()) + if (r.event_type == GcRoundLogRecord::EventType::Finish) + finishes.push_back(r); + ASSERT_EQ(finishes.size(), 2u); + EXPECT_EQ(finishes[0].trigger, GcRoundLogRecord::Trigger::Scheduled); + EXPECT_EQ(finishes[0].outcome, GcRoundLogRecord::Outcome::Stopped) << finishes[0].error; + EXPECT_EQ(finishes[1].trigger, GcRoundLogRecord::Trigger::Manual); + EXPECT_NE(finishes[1].outcome, GcRoundLogRecord::Outcome::Stopped) << finishes[1].error; + const String captured = scheduler_log.captured(); + EXPECT_NE(captured.find("stopped by the scheduler's stop"), String::npos) << captured; + EXPECT_EQ(captured.find("round failed"), String::npos) << captured; +} + +namespace +{ + +/// Fails the round's `gc/state` commit on a killable query thread: the query is killed inside the commit's +/// write, which then either loses to a competing `gc/state` write or loses its reply with a failed settling read. +class KilledCommitBackend final : public CountingBackend +{ +public: + enum class Fault : uint8_t { CompetingWrite, LostReplyUnreadable }; + + void arm(const Layout & layout_, uint64_t round_before_, Fault fault_, std::function kill_) + { + layout.emplace(layout_); + round_before = round_before_; + fault = fault_; + kill = std::move(kill_); + } + + bool fired() const { return did_fire; } + + std::optional read(const String & key, TransportAccess & access) override + { + if (fail_state_reads && layout && key == layout->gcStateKey()) + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected gc/state read failure"); + return CountingBackend::read(key, access); + } + + std::expected write( + const String & key, const String & bytes, const std::optional & expected_value, + TransportAccess & access) override + { + if (!kill || in_hook || !layout || key != layout->gcStateKey() || !expected_value + || decodeGcState(bytes).round <= round_before) + return CountingBackend::write(key, bytes, expected_value, access); + did_fire = true; + const std::function kill_now = std::exchange(kill, {}); + if (fault == Fault::CompetingWrite) + moveLeaseAway(); + kill_now(); + if (fault == Fault::CompetingWrite) + return CountingBackend::write(key, bytes, expected_value, access); + fail_state_reads = true; + throw Poco::TimeoutException("injected lost gc/state commit reply"); + } + +private: + /// Through this backend, so the commit write that follows is conditioned on a moved incarnation. + void moveLeaseAway() + { + in_hook = true; + SCOPE_EXIT({ in_hook = false; }); + auto requests = openRequestsForTest(*this); + auto op = requests.admit(); + const auto got = op.read(layout->gcStateKey(), Retry::once()); + ASSERT_TRUE(got); + GcState state = decodeGcState(got->bytes); + state.lease.owner = hexToU128("00000000000000000000000000000099"); + ++state.lease.seq; + ASSERT_TRUE(std::holds_alternative( + op.replace(layout->gcStateKey(), encodeGcState(state), got->etag, Retry::once()))); + } + + std::optional layout; + uint64_t round_before = 0; + Fault fault = Fault::CompetingWrite; + std::function kill; + bool in_hook = false; + bool did_fire = false; + bool fail_state_reads = false; +}; + +} + +/// A manual round whose query is stopped is `Stopped` also when the stop surfaces as another transient code: +/// `ABORTED` from a commit that lost to a competing write after the kill, or the unresolved commit's 210. +TEST(CASGCFrontierGate, KilledManualRoundIsStoppedWhateverTransientCodeEndsIt) +{ + using Fault = KilledCommitBackend::Fault; + for (const Fault fault : {Fault::CompetingWrite, Fault::LostReplyUnreadable}) + { + SCOPED_TRACE(fault == Fault::CompetingWrite ? "competing write" : "lost reply, unreadable settlement"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout & layout = store->layout(); + seedCompletedRemoving(op, store, kGc); + freeGcLease(*backend, layout); + const auto state = op.read(layout.gcStateKey(), Retry::once()); + ASSERT_TRUE(state); + + OwnerRoundSink sink; + CasGcScheduler scheduler(store, std::chrono::seconds(3600), "test::gc", "ca", sink.logger()); + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->arm(layout, decodeGcState(state->bytes).round, fault, [&query] { query.kill(); }); + try + { + (void)scheduler.runOneRoundNow(GcRoundLogRecord::Trigger::Manual); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_TRUE(backend->fired()) << "the round never sent its commit"; + EXPECT_EQ(code, fault == Fault::CompetingWrite ? DB::ErrorCodes::ABORTED : DB::ErrorCodes::NETWORK_ERROR); + const std::optional finish = sink.waitForFinish(); + ASSERT_TRUE(finish); + EXPECT_EQ(finish->error_code, code) << finish->error; + EXPECT_EQ(finish->outcome, GcRoundLogRecord::Outcome::Stopped) << finish->error; + } +} diff --git a/src/Disks/tests/gtest_cas_gc_intents.cpp b/src/Disks/tests/gtest_cas_gc_intents.cpp index 683f37243523e..396ac94959b6a 100644 --- a/src/Disks/tests/gtest_cas_gc_intents.cpp +++ b/src/Disks/tests/gtest_cas_gc_intents.cpp @@ -1,6 +1,7 @@ #include #include "cas_test_helpers.h" +#include "cas_killable_query.h" #include #include @@ -4652,9 +4653,13 @@ class PausedLeaderBackend : public GetHookBackend Absent, Unanswered, Refused, + /// A retryable store answer, as the S3 client gives for a failed connection. + NetworkError, }; std::atomic state_head{StateHead::Store}; + /// Runs at every `HEAD` of `gc/state`, before its answer. + std::function on_state_head; /// Every token of `gc/state` is a weak ETag: a valid precondition with no canonical identity. std::atomic weak_state_tokens{false}; @@ -4697,6 +4702,8 @@ class PausedLeaderBackend : public GetHookBackend return meta; if (meta && weakened(key)) meta->value = weak(meta->value); + if (on_state_head) + on_state_head(); switch (state_head.load()) { case StateHead::Store: @@ -4707,6 +4714,8 @@ class PausedLeaderBackend : public GetHookBackend throw Poco::TimeoutException("the gc/state HEAD was never answered"); case StateHead::Refused: throw std::runtime_error("the store refused the gc/state HEAD"); + case StateHead::NetworkError: + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "the gc/state HEAD failed"); } return meta; } @@ -5277,6 +5286,114 @@ TEST(CASGcIntents, UnconfirmedLeasedStateSuppressesTheRound) } } +/// A killed round's intent delete that fails with the query's stored cause propagates it unannotated: the query +/// rethrows that one object to every thread it stops. +TEST(CASGcIntents, IntentDeleteLeavesTheStoredQueryExceptionUnchanged) +{ + IntentPool<> pool(std::make_shared()); + ASSERT_NO_FATAL_FAILURE(pool.makePending({1})); + pool.round(); + ASSERT_TRUE(pool.row(1) && pool.row(1)->standing) << "the body is deleted, its intent is next"; + const String stored_text = "the query's stored network failure"; + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "{}", stored_text)); + bool fired = false; + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + pool.backend->onBeforeBulkRemove([&] + { + if (std::exchange(fired, true)) + return; + query.kill(cause); + std::rethrow_exception(cause); + }); + try + { + pool.gc->runRegularRound({}, /*allow_steal*/ true, UniversePolicy::Authoritative); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + pool.backend->onBeforeBulkRemove({}); + }); + + ASSERT_TRUE(fired) << "the round sent no intent delete"; + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR); + try + { + std::rethrow_exception(cause); + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.message(), stored_text) << "the intent delete annotated the query's stored exception"; + } +} + +/// The validation read of `gc/state` fails with a retryable error. A live round retries, gives up, records +/// `parent_unconfirmed` and commits; a killed round's retry is vetoed, so it ends with that failure and writes nothing +/// after the read. +TEST(CASGcIntents, AKilledRoundsFailedValidationReadEndsTheRoundBeforeItsWrites) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + IntentPool pool(std::make_shared()); + ASSERT_NO_FATAL_FAILURE(pool.makePending({1})); + std::map reduce; + pool.gc->setPhaseSink([&reduce](const GcPhaseRecord & record) + { + if (record.phase == "fold_reduce") + reduce = record.metrics; + }); + + pool.backend->state_head = StateHead::NetworkError; + pool.backend->clearJournal(); + int code = 0; + String message; + onKillableQueryThread([&](CasKillableQuery & query) + { + pool.backend->on_state_head = [&] + { + if (killed) + query.kill(); + }; + try + { + pool.gc->runRegularRound({}, /*allow_steal*/ true, UniversePolicy::Authoritative); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + pool.backend->on_state_head = {}; + }); + pool.backend->state_head = StateHead::Store; + + const auto journal = pool.backend->journal(); + const std::vector heads = stateHeadIndices(journal); + ASSERT_FALSE(heads.empty()) << "positive control: the round sent its validation read"; + const size_t writes_after = static_cast(std::count_if(journal.begin() + heads.back(), journal.end(), + [](const JournalEntry & entry) { return entry.verb == JournalVerb::Write; })); + if (killed) + { + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << message; + EXPECT_NE(message.find("the gc/state HEAD failed"), String::npos) << message; + EXPECT_EQ(heads.size(), 1u) << "the killed round retried the read"; + EXPECT_EQ(writes_after, 0u) << "the killed round wrote after its failed validation read"; + } + else + { + EXPECT_EQ(code, 0) << message; + EXPECT_GT(heads.size(), 1u) << "the live round retried the read"; + EXPECT_EQ(metricOr(reduce, "parent_unconfirmed"), 1u); + EXPECT_GT(writes_after, 0u) << "the live round committed"; + } + EXPECT_TRUE(pool.bodyMeta(1).has_value()); + } +} + /// A round whose destructive work is suppressed takes no redelete slot, so it keeps the position the previous round /// left: the round after it still starts behind the carried row. TEST(CASGcIntents, ASuppressedRoundKeepsTheRedeletePosition) diff --git a/src/Disks/tests/gtest_cas_gc_log.cpp b/src/Disks/tests/gtest_cas_gc_log.cpp index 75667566f0566..34bdc9b97f58f 100644 --- a/src/Disks/tests/gtest_cas_gc_log.cpp +++ b/src/Disks/tests/gtest_cas_gc_log.cpp @@ -942,7 +942,7 @@ TEST(CASGCLog, FoldingRoundEmitsEveryPhaseInOrder) "fold_ref_group", "fold_seal_read", "fold_ref_intake", "intent_sweep_list", "fold_reduce", "fold_seal_write", "pending_deletes", "round_commit", "handoff_reclaim", - "manifest_deletes", "namespace_cleanup", "ref_object_cleanup", "orphan_sweep"}; + "manifest_deletes", "orphan_sweep", "namespace_cleanup", "ref_object_cleanup"}; EXPECT_EQ(phaseNames(rows, 0), expected); /// Every phase row is a Phase row of THIS round and carries a duration field (0 is a legitimate diff --git a/src/Disks/tests/gtest_cas_gc_read_ahead.cpp b/src/Disks/tests/gtest_cas_gc_read_ahead.cpp index 542dcde870025..39e3846ee61b7 100644 --- a/src/Disks/tests/gtest_cas_gc_read_ahead.cpp +++ b/src/Disks/tests/gtest_cas_gc_read_ahead.cpp @@ -11,10 +11,17 @@ #include #include #include +#include #include #include +#include +#include #include +#include +#include +#include +#include #include #include @@ -27,11 +34,17 @@ #include #include #include +#include #include #include #include #include +namespace DB::FailPoints +{ + extern const char thread_group_switcher_post_attach_failure[]; +} + namespace DB::ErrorCodes { extern const int CANNOT_SCHEDULE_TASK; @@ -199,6 +212,145 @@ TEST(CASGCReadAhead, WindowIsFourTimesConcurrency) EXPECT_EQ(reads.window(), 32u); } +/// A manual round's workers run in its query: a worker whose first request fails after the kill sends no second +/// one, and the take gets that request's own failure. Under a live query the same worker retries and answers. +TEST(CASGCReadAhead, KilledRoundsWorkerDoesNotReissueAFailedRequest) +{ + enum class Worker : uint8_t { Read, Head, Create }; + for (const Worker worker : {Worker::Read, Worker::Head, Worker::Create}) + { + for (const bool killed : {true, false}) + { + SCOPED_TRACE(fmt::format("worker {}, {}", static_cast(worker), killed ? "killed query" : "live query")); + ReadAheadRig rig; + rig.put("k", "v"); + rig.backend->resetCounts(); + bool answered = false; + String failure; + std::thread round([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + if (killed) + query.kill(); + const auto timeout = std::make_exception_ptr(Poco::TimeoutException("injected request timeout")); + if (worker == Worker::Head) + rig.backend->failNextHeadWith("k", timeout); + else + rig.backend->failNextReadWith("k", timeout); + GcReadAhead reads(rig.op, rig.requests, rig.pool, 4); + try + { + switch (worker) + { + case Worker::Read: + reads.hintRead("k"); + answered = reads.takeRead("k").has_value(); + break; + case Worker::Head: + reads.hintHead("k"); + answered = reads.takeHead("k").has_value(); + break; + case Worker::Create: + { + auto take = reads.startCreate([](CasOperation & op) + { + EXPECT_TRUE(op.read("k", Retry::standard()).has_value()); + return IntentCreateResult{}; + }); + (void)take(); + answered = true; + break; + } + } + } + catch (...) + { + failure = DB::getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + }); + round.join(); + + const size_t requests = worker == Worker::Head ? rig.backend->headCount("k") : rig.backend->getCount("k"); + if (killed) + { + EXPECT_FALSE(answered); + EXPECT_NE(failure.find("injected request timeout"), String::npos) << failure; + EXPECT_EQ(requests, 1u) << "the failed request was reissued after the kill"; + } + else + { + EXPECT_TRUE(answered) << failure; + EXPECT_EQ(requests, 2u) << "positive control: a live query's worker retries"; + } + } + } +} + +/// A manual round's worker that fails to join the round's query sends nothing: outside the query its request would +/// not see the query's stop. The take gets the worker's failure. +TEST(CASGCReadAhead, WorkerOutsideTheRoundsQuerySendsNothing) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + enum class Worker : uint8_t { Read, Head, Create }; + for (const Worker worker : {Worker::Read, Worker::Head, Worker::Create}) + { + SCOPED_TRACE(fmt::format("worker {}", static_cast(worker))); + ReadAheadRig rig; + rig.put("k", "v"); + rig.backend->resetCounts(); + bool answered = false; + int code = 0; + String failure; + std::thread round([&] + { + DB::ThreadStatus thread_status; + CasKillableQuery query(getContext().context); + GcReadAhead reads(rig.op, rig.requests, rig.pool, 4); + /// Armed after the round's own attach, so the worker's switch is the one that fails. + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + try + { + switch (worker) + { + case Worker::Read: + reads.hintRead("k"); + answered = reads.takeRead("k").has_value(); + break; + case Worker::Head: + reads.hintHead("k"); + answered = reads.takeHead("k").has_value(); + break; + case Worker::Create: + { + auto take = reads.startCreate([](CasOperation & op) + { + EXPECT_TRUE(op.read("k", Retry::standard()).has_value()); + return IntentCreateResult{}; + }); + (void)take(); + answered = true; + break; + } + } + } + catch (const DB::Exception & e) + { + code = e.code(); + failure = e.message(); + } + }); + round.join(); + + EXPECT_FALSE(answered); + EXPECT_EQ(code, DB::ErrorCodes::CANNOT_SCHEDULE_TASK) << failure; + const size_t requests = worker == Worker::Head ? rig.backend->headCount("k") : rig.backend->getCount("k"); + EXPECT_EQ(requests, 0u) << "a worker outside the round's query sent a request"; + } +} + /// A create's state is released when its answer is taken, so a site that keeps a window of creates in flight holds /// at most that window, however many creates it sends. TEST(CASGCReadAhead, TakenCreateIsReleased) diff --git a/src/Disks/tests/gtest_cas_gc_rebuild.cpp b/src/Disks/tests/gtest_cas_gc_rebuild.cpp index fa8cae8ded6b1..c580bcca69ad1 100644 --- a/src/Disks/tests/gtest_cas_gc_rebuild.cpp +++ b/src/Disks/tests/gtest_cas_gc_rebuild.cpp @@ -13,8 +13,12 @@ #include #include #include +#include "cas_killable_query.h" #include "cas_sweep_test_support.h" #include "cas_test_helpers.h" +#include +#include +#include using namespace DB::Cas; using namespace DB::Cas::tests; @@ -28,6 +32,7 @@ namespace DB::ErrorCodes { extern const int CORRUPTED_DATA; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; } namespace @@ -1081,6 +1086,104 @@ TEST(CASGCRebuild, FailingLeaseGiveBackLeavesTheRefusalToTheCaller) << "a failed give-back leaves the claim in place"; } +/// A rebuild whose query is killed after its lease claim still gives the claim back: the give-back is owed +/// to the claimed resource, so the next rebuild is not refused as a competing leader. +TEST(CASGCRebuild, KilledRebuildGivesBackClaimedLease) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Layout & layout = store->layout(); + const ManifestId missing = seedLostStateWithMissingCommittedManifest(*backend, store); + ASSERT_FALSE(readObj(*backend, layout.gcStateKey()).has_value()); + + std::thread rebuild_thread([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + backend->arm(layout.manifestKey(missing), 1, [&] { query.kill(); }); + Gc killed(store, hexToU128("00000000000000000000000000000026")); + try + { + const RebuildReport refused = killed.rebuildBaseline(/*force*/ false); + EXPECT_FALSE(refused.performed); + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::QUERY_WAS_CANCELLED) << e.message(); + } + }); + rebuild_thread.join(); + + ASSERT_TRUE(backend->didFire()) << "the query was not killed after the lease claim"; + const auto given_back = readObj(*backend, layout.gcStateKey()); + ASSERT_TRUE(given_back.has_value()) << "the claim created gc/state"; + EXPECT_EQ(decodeGcState(given_back->bytes).lease.owner, DB::UInt128(0)) << "the claim was given back"; + + Gc next(store, hexToU128("00000000000000000000000000000027")); + const RebuildReport rep = next.rebuildBaseline(/*force*/ true); + EXPECT_EQ(rep.refusal.find("another GC leader holds the lease"), String::npos) << rep.refusal; +} + +/// A rebuild whose query is killed while it reads a fold seal reports the read's own failure, not an undecodable +/// seal that tells the operator to recreate the pool: for the adopted seal, and for the newest one found by +/// listing when `gc/state` is gone. +TEST(CASGCRebuild, KilledRebuildIsNotUndecodableSeal) +{ + for (const bool state_lost : {false, true}) + { + SCOPED_TRACE(state_lost ? "newest listed seal" : "adopted seal"); + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Layout & layout = store->layout(); + const RootNamespace ns{"00/aa@cas@"}; + writeBlobBody(*backend, layout, DB::UInt128(1)); + writeManifestRaw(*backend, layout, ns, ref(1, 0xAA), {blobEntryFor("a", DB::UInt128(1))}); + publishCommittedTransition(*backend, layout, ns, "tbl", std::nullopt, ref(1, 0xAA)); + Gc gc(store, kGc); + gc.runRegularRound(); + const GcState st = decodeGcState(readObj(*backend, layout.gcStateKey())->bytes); + ASSERT_GT(st.snap_generation, 0u); + if (state_lost) + { + const auto state_meta = headObj(*backend, layout.gcStateKey()); + ASSERT_TRUE(state_meta); + ASSERT_EQ(removeExact(*backend, layout.gcStateKey(), state_meta->etag), Removal::Removed); + } + + std::optional code; + String message; + std::thread rebuild_thread([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + backend->arm(layout.foldSealKey(st.snap_generation, st.snap_attempt), 1, [&] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected fold seal read failure"); + }); + try + { + Gc rebuild(store, hexToU128("00000000000000000000000000000028")); + (void)rebuild.rebuildBaseline(/*force*/ true); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + rebuild_thread.join(); + + ASSERT_TRUE(backend->didFire()) << "the rebuild never read the fold seal"; + ASSERT_TRUE(code) << "the killed rebuild returned normally"; + EXPECT_EQ(*code, DB::ErrorCodes::NETWORK_ERROR) << message; + EXPECT_NE(message.find("injected fold seal read failure"), String::npos) << message; + EXPECT_EQ(message.find("UNDECODABLE"), String::npos) << message; + } +} + /// The refusal is a wait, not a verdict: once the manifest is readable, a rebuild with a fresh GC identity, /// as each run of `clickhouse-disks cas-gc-rebuild` takes, counts the precommit. TEST(CASGCRebuild, RebuildRefusedForAnUnreadableManifestSucceedsOnceItIsReadable) diff --git a/src/Disks/tests/gtest_cas_gc_redelete_concurrency.cpp b/src/Disks/tests/gtest_cas_gc_redelete_concurrency.cpp index a4f03fb3c12b8..04facd6e733af 100644 --- a/src/Disks/tests/gtest_cas_gc_redelete_concurrency.cpp +++ b/src/Disks/tests/gtest_cas_gc_redelete_concurrency.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -25,6 +26,7 @@ #include #include #include +#include "cas_killable_query.h" #include "cas_test_helpers.h" namespace ProfileEvents @@ -37,6 +39,11 @@ namespace DB::ErrorCodes extern const int CANNOT_SCHEDULE_TASK; } +namespace DB::FailPoints +{ +extern const char thread_group_switcher_post_attach_failure[]; +} + using namespace DB::Cas; using namespace DB::Cas::tests; @@ -855,6 +862,61 @@ TEST(CASGCRedeleteConcurrency, SchedulingFailureAttemptsNothingAndTheNextRoundRe EXPECT_TRUE(allBlobsAbsent(*backend, *store)); } +/// A re-delete worker that fails to join the manual round's query deletes nothing: outside the query its request would +/// not see the query's stop. Its job fails and the round fails before its commit. The failpoint fails one switch only, +/// so the other jobs run in the query and delete. +TEST(CASGCRedeleteConcurrency, WorkerOutsideTheRoundsQueryDeletesNothing) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + auto backend = std::make_shared(); + auto store = openPoolWithIoConcurrency(backend, 4); + Gc gc(store, kGc); + publishThenDrop(*backend, store, gc); + ASSERT_NO_FATAL_FAILURE(driveUntilAllGraduated(*backend, gc, store, kFaultedBlob)); + + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + std::atomic armed{false}; + gc.setPhaseSink([&](const GcPhaseRecord & rec) + { + /// Armed after the round's own attach and its read-ahead, so a re-delete worker's switch is the one that fails. + if (rec.phase == "fold_seal_write") + { + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + armed = true; + } + else if (rec.phase == "pending_deletes") + { + DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + } + }); + + RoundReport progress; + int code = 0; + String message; + onKillableQueryThread([&](CasKillableQuery &) + { + try + { + gc.runRegularRound({}, /*allow_steal*/ true, UniversePolicy::Authoritative, &progress); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + gc.setPhaseSink({}); + + ASSERT_TRUE(armed.load()) << "the round never reached its fold seal"; + EXPECT_EQ(code, DB::ErrorCodes::CANNOT_SCHEDULE_TASK) << message; + EXPECT_EQ(progress.body_delete_failed, 1u); + EXPECT_EQ(progress.bodies_deleted, kBlobs - 1); + size_t present = 0; + for (uint64_t blob = 1; blob <= kBlobs; ++blob) + present += blobAbsent(*backend, store->layout(), numberedBlobHash(blob)) ? 0 : 1; + EXPECT_EQ(present, 1u) << "the worker outside the query deleted its blob"; +} + TEST(CASGCRedeleteConcurrency, EnqueueRefusalYieldsToLowerIndexWorkerFailure) { auto backend = std::make_shared(); diff --git a/src/Disks/tests/gtest_cas_gc_stop_start.cpp b/src/Disks/tests/gtest_cas_gc_stop_start.cpp index daad78bcdfca0..62652c7bdbee1 100644 --- a/src/Disks/tests/gtest_cas_gc_stop_start.cpp +++ b/src/Disks/tests/gtest_cas_gc_stop_start.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -373,6 +374,7 @@ TEST(CASGCStopStart, StopClearsLeadershipAfterManualRoundWithoutStart) TEST(CASGCStopStart, StartFailureRollsBackAndCanBeRetried) { + CAS_SKIP_WITHOUT_FAILPOINTS(); for (const char * failpoint : {FailPoints::cas_gc_scheduler_fail_before_heartbeat_worker_start, FailPoints::cas_gc_scheduler_fail_before_worker_start}) diff --git a/src/Disks/tests/gtest_cas_gc_teardown_stop.cpp b/src/Disks/tests/gtest_cas_gc_teardown_stop.cpp index 421cdb9764e7c..35c0a2178fb7f 100644 --- a/src/Disks/tests/gtest_cas_gc_teardown_stop.cpp +++ b/src/Disks/tests/gtest_cas_gc_teardown_stop.cpp @@ -278,14 +278,14 @@ TEST(CASGCTeardownStop, OpenPlaneSleepReturnsAtOnceOnceTeardownBegan) auto store = openPlainPool(backend); store->beginTeardown(); - auto paused = std::async(std::launch::async, [&store] { store->openRequests().pause(60'000); }); + auto paused = std::async(std::launch::async, [&store] { store->openRequests().sleepFor(60'000); }); ASSERT_EQ(paused.wait_for(std::chrono::seconds(10)), std::future_status::ready) << "the open plane's sleep must observe the arm; a plain sleep holds for the full minute"; /// Clearing the seam must put the interruptible sleep back, not the engine's plain one. store->setCasRetrySleepForTest([](uint64_t) {}); store->setCasRetrySleepForTest({}); - auto paused_again = std::async(std::launch::async, [&store] { store->openRequests().pause(60'000); }); + auto paused_again = std::async(std::launch::async, [&store] { store->openRequests().sleepFor(60'000); }); EXPECT_EQ(paused_again.wait_for(std::chrono::seconds(10)), std::future_status::ready) << "resetting the retry-sleep seam left the open plane on the plain sleep"; } diff --git a/src/Disks/tests/gtest_cas_hot_keys.cpp b/src/Disks/tests/gtest_cas_hot_keys.cpp index e0a48872fac9f..437b161486665 100644 --- a/src/Disks/tests/gtest_cas_hot_keys.cpp +++ b/src/Disks/tests/gtest_cas_hot_keys.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "cas_test_helpers.h" #include @@ -16,7 +17,10 @@ #include #include +#include +#include #include +#include #include #include #include @@ -33,6 +37,11 @@ namespace ProfileEvents extern const Event CASRequestGaveUp; } +namespace DB::ErrorCodes +{ + extern const int ABORTED; +} + using namespace DB::Cas; using DB::Cas::tests::CountingBackend; @@ -127,7 +136,7 @@ TEST(CASHotKeys, SubmissionsOfOneKeyAreSerializedInArrivalOrder) { go[i].wait(); auto op = requests.admit(); - results[i] = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(i + 1)); + results[i] = hot_keys.submit("k", op, Retry::standard(), appendTicket(i + 1)); }); } /// The first holder is released into its write and parked there; every later thread is released @@ -173,7 +182,7 @@ TEST(CASHotKeys, ADecideRunsWithTheLaneMutexReleased) /// `queueDepthForTest` takes the lane's mutex; a `decide` run under it would deadlock this test, /// which hangs the whole `CAS*` gate rather than being reported by a per-test timeout. The call is /// the assertion. - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), + WriteResult result = hot_keys.submit("k", op, Retry::standard(), [&](const std::optional &) -> std::optional { EXPECT_EQ(hot_keys.queueDepthForTest("k"), 1u); @@ -190,11 +199,11 @@ TEST(CASHotKeys, AFailedEnqueueLeavesNoEmptyLaneBehind) CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto op = requests.admit(); hot_keys.enter_after_lane_hook_for_test = [] { throw std::bad_alloc(); }; - EXPECT_THROW(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)), std::bad_alloc); + EXPECT_THROW(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)), std::bad_alloc); EXPECT_EQ(hot_keys.laneCountForTest(), 0u); EXPECT_EQ(backend->writeCount("k"), 0u); hot_keys.enter_after_lane_hook_for_test = {}; - EXPECT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + EXPECT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); } TEST(CASHotKeys, ResultsAreTheEnginesOwn) @@ -205,32 +214,42 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) CasHotKeys hot_keys(0); CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto op = requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); #if USE_AWS_S3 /// The store refuses the bytes: the caller gets that `Refused`, at once. backend->failNextWriteWith("k", s3Error(Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)); + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); ASSERT_TRUE(std::holds_alternative(result)); } #endif - /// A clean refused precondition with the store unchanged: `Conflict` carrying the occupant. + /// A clean refused precondition with the store unchanged, under a single attempt: `Conflict` carrying the occupant. backend->refuseNextWrite("k"); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(3)); + WriteResult result = hot_keys.submit("k", op, Retry::once(), appendTicket(3)); const auto * conflict = std::get_if(&result); ASSERT_NE(conflict, nullptr); EXPECT_TRUE(std::holds_alternative(conflict->seen)); EXPECT_FALSE(conflict->any_ambiguous); } + /// The same refusal of a write decided on a fresh read, for a caller that retries: it pauses and reads before its + /// next decision, so the refusal is returned unsettled. + backend->refuseNextWrite("k"); + { + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(3), CasHotKeys::Start::Read); + const auto * conflict = std::get_if(&result); + ASSERT_NE(conflict, nullptr); + EXPECT_TRUE(std::holds_alternative(conflict->seen)); + EXPECT_FALSE(conflict->any_ambiguous); + } /// The resolve read fails at the transport under `once`: nothing observed. The failure is armed /// from a one-shot write hook, not up front, so it lands on the write's own resolve read rather /// than on the hold's base read, which must succeed for this sub-case to reach the write at all. backend->refuseNextWrite("k"); backend->onBeforeWrite("k", [&] { backend->failNextReadWith("k", std::make_exception_ptr(Poco::TimeoutException("resolve"))); }); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::once()), appendTicket(4)); + WriteResult result = hot_keys.submit("k", op, Retry::once(), appendTicket(4)); const auto * conflict = std::get_if(&result); ASSERT_NE(conflict, nullptr); EXPECT_TRUE(std::holds_alternative(conflict->seen)); @@ -241,7 +260,7 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) backend->injectAmbiguousWrite("k"); backend->onBeforeWrite("k", [&] { backend->failNextReadWith("k", std::make_exception_ptr(Poco::TimeoutException("resolve"))); }); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::once()), appendTicket(5)); + WriteResult result = hot_keys.submit("k", op, Retry::once(), appendTicket(5)); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); @@ -252,7 +271,7 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) bool alive = true; auto fenced = requests.admit([&] { return alive; }); { - WriteResult result = hot_keys.submit("k", fenced, fenced.freeze(Retry::standard()), + WriteResult result = hot_keys.submit("k", fenced, Retry::standard(), [&](const std::optional & current) -> std::optional { alive = false; @@ -267,7 +286,7 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) alive = true; backend->onWriteCommitted("k", [&] { alive = false; }); { - WriteResult result = hot_keys.submit("k", fenced, fenced.freeze(Retry::standard()), appendTicket(7)); + WriteResult result = hot_keys.submit("k", fenced, Retry::standard(), appendTicket(7)); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); @@ -277,9 +296,9 @@ TEST(CASHotKeys, ResultsAreTheEnginesOwn) backend->onWriteCommitted("k", [] {}); /// The engine call throws a local fault: it reaches the caller and the key is handed over. backend->failNextWriteWith("k", std::make_exception_ptr(std::logic_error("local"))); - EXPECT_THROW(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(8)), std::logic_error); + EXPECT_THROW(hot_keys.submit("k", op, Retry::standard(), appendTicket(8)), std::logic_error); EXPECT_EQ(hot_keys.laneCountForTest(), 0u); - EXPECT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(9)))); + EXPECT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(9)))); } TEST(CASHotKeys, ABaseReadThatFailsGivesUpAsReadModifyWriteDoes) @@ -295,7 +314,7 @@ TEST(CASHotKeys, ABaseReadThatFailsGivesUpAsReadModifyWriteDoes) /// Enough armed failures to outlast a standard window: the read loop gives up at its deadline. for (int i = 0; i < 64; ++i) backend->failNextReadWith("k", std::make_exception_ptr(Poco::TimeoutException("read"))); - WriteResult lane = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)); + WriteResult lane = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); for (int i = 0; i < 64; ++i) backend->failNextReadWith("k", std::make_exception_ptr(Poco::TimeoutException("read"))); WriteResult verb = op.readModifyWrite("k", appendTicket(2), Retry::standard()); @@ -319,7 +338,7 @@ TEST(CASHotKeys, ABaseReadThatFailsGivesUpAsReadModifyWriteDoes) CasRequests fenced_requests(backend, fence, clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto fenced = fenced_requests.admit(); refuse_reservations = true; - WriteResult result = hot_keys.submit("k", fenced, fenced.freeze(Retry::standard()), appendTicket(3)); + WriteResult result = hot_keys.submit("k", fenced, Retry::standard(), appendTicket(3)); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); @@ -342,7 +361,7 @@ TEST(CASHotKeys, WaitersLeaveOnTheirOwnFenceLeaseAndDeadline) std::thread holder([&] { auto op = requests.admit(); - (void)hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)); + (void)hot_keys.submit("k", op, Retry::standard(), appendTicket(1)); }); park.parked.wait(); @@ -352,7 +371,7 @@ TEST(CASHotKeys, WaitersLeaveOnTheirOwnFenceLeaseAndDeadline) std::thread deadline_waiter([&] { auto op = requests.admit(); - by_deadline = hot_keys.submit("k", op, op.freeze(Retry::within(500)), appendTicket(2)); + by_deadline = hot_keys.submit("k", op, Retry::within(500), appendTicket(2)); }); /// A waiter whose task stops. std::atomic alive{true}; @@ -360,7 +379,7 @@ TEST(CASHotKeys, WaitersLeaveOnTheirOwnFenceLeaseAndDeadline) std::thread liveness_waiter([&] { auto op = requests.admit([&] { return alive.load(); }); - by_liveness = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(3)); + by_liveness = hot_keys.submit("k", op, Retry::standard(), appendTicket(3)); }); while (hot_keys.queueDepthForTest("k") < 3) std::this_thread::yield(); @@ -392,7 +411,7 @@ TEST(CASHotKeys, WaitersLeaveOnTheirOwnFenceLeaseAndDeadline) std::thread lease_waiter([&] { auto op = requests.admit([&] { return alive.load(); }); - by_lease = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(4)); + by_lease = hot_keys.submit("k", op, Retry::standard(), appendTicket(4)); }); lease_waiter.join(); { @@ -441,7 +460,7 @@ TEST(CASHotKeys, AThrottledHolderKeepsTheWaitersQueuedThroughItsBackoff) threads.emplace_back([&] { auto op = requests.admit(); - results[0] = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)); + results[0] = hot_keys.submit("k", op, Retry::standard(), appendTicket(1)); }); parked.wait(); /// Each waiter is spawned only once the previous one is seen queued, so arrival order -- and so @@ -451,7 +470,7 @@ TEST(CASHotKeys, AThrottledHolderKeepsTheWaitersQueuedThroughItsBackoff) threads.emplace_back([&, i] { auto op = requests.admit(); - results[i] = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(i + 1)); + results[i] = hot_keys.submit("k", op, Retry::standard(), appendTicket(i + 1)); }); while (hot_keys.queueDepthForTest("k") < static_cast(i + 1)) std::this_thread::yield(); @@ -478,14 +497,14 @@ TEST(CASHotKeys, TheNextHoldStartsFromTheLandedObjectWithoutARead) auto op = requests.admit(); const auto cache_starts_before = counter(ProfileEvents::CASHotKeyCacheStarts); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); EXPECT_EQ(backend->getCount("k"), 1u); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(2)))); EXPECT_EQ(backend->getCount("k"), 1u) << "the second hold started from the cache"; EXPECT_EQ(counter(ProfileEvents::CASHotKeyCacheStarts) - cache_starts_before, 1u); /// Under `once` the one attempt is on fresh state: a read, no cached start. - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::once()), appendTicket(3)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::once(), appendTicket(3)))); EXPECT_EQ(backend->getCount("k"), 2u); /// `expectBytes` issues its own read, so it comes after every count assertion, not between them. DB::Cas::tests::expectBytes(*backend, "k", "1,2,3"); @@ -500,20 +519,20 @@ TEST(CASHotKeys, AnExternalWriterCostsOneResolveReadAndOneRetry) auto op = requests.admit(); CasRequests external_requests = DB::Cas::tests::openRequestsForTest(backend); auto external = external_requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); const auto current = external.read("k", Retry::standard()); (void)orThrow(external.replace("k", "E", current->etag, Retry::standard()), "external"); const uint64_t gets_before = backend->getCount("k"); const uint64_t writes_before = backend->writeCount("k"); - /// The caller's loop: submit, and on a conflict submit again after the flat pause. + /// The caller's loop: submit, and on a conflict submit again after the conflict pause. std::optional result; - for (int i = 0; i < 3 && !result; ++i) + for (uint32_t i = 0; i < 3 && !result; ++i) { - WriteResult attempt = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)); + WriteResult attempt = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); if (std::holds_alternative(attempt)) - op.pause(Retry::conflictBackoff()); + op.sleepFor(Retry::conflictBackoff(i + 1)); else result = std::move(attempt); } @@ -521,12 +540,159 @@ TEST(CASHotKeys, AnExternalWriterCostsOneResolveReadAndOneRetry) EXPECT_EQ(backend->getCount("k") - gets_before, 1u) << "one resolve read"; EXPECT_EQ(backend->writeCount("k") - writes_before, 2u) << "one refused write, one that landed"; /// The submission after that starts from the cache. - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(3)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(3)))); EXPECT_EQ(backend->getCount("k") - gets_before, 1u); /// `expectBytes` issues its own read, so it comes after every count assertion, not between them. DB::Cas::tests::expectBytes(*backend, "k", "E,2,3"); } +namespace +{ + +/// Records the physical attempt number the engine hands the transport for each write of `key`. +struct AttemptNumberingBackend : CountingBackend +{ + std::vector write_attempts; + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (key == "k") + write_attempts.push_back(access.attemptNo()); + return CountingBackend::write(key, bytes, expected_value, access); + } +}; + +} + +/// The refused write on a hint and the write on its resolve read are attempts of one submission: they are +/// counted and numbered together, and a give-up between them reports the first. +TEST(CASHotKeys, BothWritesOfOneHoldAreAttemptsOfOneSubmission) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + auto op = requests.admit(); + CasRequests external_requests = DB::Cas::tests::openRequestsForTest(backend); + auto external = external_requests.admit(); + const auto move_externally = [&](const String & bytes) + { + const auto current = external.read("k", Retry::standard()); + (void)orThrow(external.replace("k", bytes, current->etag, Retry::standard()), "external"); + }; + + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); + move_externally("E"); + backend->write_attempts.clear(); + { + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); + const auto * committed = std::get_if(&result); + ASSERT_NE(committed, nullptr); + EXPECT_EQ(committed->attempts_sent, 2u); + EXPECT_EQ(backend->write_attempts, (std::vector{1, 2})); + } + + /// The fence trips in the decision on the resolve read, so the second write is never sent. + move_externally("F"); + bool alive = true; + auto fenced = requests.admit([&] { return alive; }); + int decisions = 0; + WriteResult result = hot_keys.submit("k", fenced, Retry::standard(), + [&](const std::optional & current) -> std::optional + { + if (++decisions == 2) + alive = false; + return current->bytes + ",3"; + }); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(gave_up->attempts_sent, 1u); + const auto * seen = std::get_if(&gave_up->last_seen); + ASSERT_NE(seen, nullptr) << "the resolve read of the refused write"; + EXPECT_EQ(seen->bytes, "F"); +} + +/// A retrying caller's refusal on a fresh read is returned unsettled, but only when the read it skips would +/// have been admitted: the same lease budget and the same bounds decide, and report what that read would. +TEST(CASHotKeys, AnUnsettledRefusalStillMeetsTheBoundsOfTheReadItSkips) +{ + { + SCOPED_TRACE("the lease has room for less than one more request"); + SyncClock clock; + auto backend = std::make_shared(); + uint64_t lease_left_ms = 10'000; + Fence fence = Fence::open(); + fence.admit = [&lease_left_ms](uint64_t, uint64_t needed_ms) + { + return needed_ms <= lease_left_ms ? Fence::Admit::Ok : Fence::Admit::NoBudget; + }; + CasHotKeys hot_keys(0); + CasRequests requests(backend, fence, clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + requests.setAttemptReservationForTest(1'000); + auto op = requests.admit(); + (void)orThrow(op.create("k", "1", Retry::standard()), "seed"); + backend->refuseNextWrite("k"); + backend->onBeforeWrite("k", [&] { lease_left_ms = 500; }); + + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2), CasHotKeys::Start::Read); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << "index " << result.index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Lease); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(clock.sleepCount(), 0u); + } + { + SCOPED_TRACE("an absolute cap leaves less than one request envelope once the write returns"); + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(0); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + requests.setAttemptReservationForTest(1'000); + auto op = requests.admit(); + (void)orThrow(op.create("k", "1", Retry::standard()), "seed"); + const Retry capped = Retry::standard().cappedAt(clock.nowFn()() + 10'000); + backend->refuseNextWrite("k"); + backend->onBeforeWrite("k", [&] { clock.advance(9'500); }); + + WriteResult result = hot_keys.submit("k", op, capped, appendTicket(2), CasHotKeys::Start::Read); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << "index " << result.index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(clock.sleepCount(), 0u); + } +} + +/// A loss on a cached body says only that the cache was old: the hold decides again on the resolve +/// read and writes at once, with no pause, in the same submission. +TEST(CASHotKeys, ALossOnACachedBodyRetriesAtOnce) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + auto op = requests.admit(); + CasRequests external_requests = DB::Cas::tests::openRequestsForTest(backend); + auto external = external_requests.admit(); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); + const auto current = external.read("k", Retry::standard()); + (void)orThrow(external.replace("k", "E", current->etag, Retry::standard()), "external"); + backend->clearJournal(); + + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); + + ASSERT_TRUE(std::holds_alternative(result)); + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*backend, "k"), "WRW") << "refused on the cache, the resolve read, the write on it"; + EXPECT_EQ(clock.sleepCount(), 0u); + DB::Cas::tests::expectBytes(*backend, "k", "E,2"); +} + TEST(CASHotKeys, MalformedBytesRepairedExternallyRaiseNoCorruptionVerdict) { SyncClock clock; @@ -543,27 +709,33 @@ TEST(CASHotKeys, MalformedBytesRepairedExternallyRaiseNoCorruptionVerdict) throw DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "not a ticket list"); return current ? current->bytes + ",9" : String("9"); }; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), strict))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), strict))); - auto current = external.read("k", Retry::standard()); - const Etag garbage = *orThrow(external.replace("k", "garbage", current->etag, Retry::standard()), "break"); - /// The lane's next hold starts from its cache, loses to the garbage, and remembers the garbage - /// its resolve read saw; the caller pauses and submits again. - WriteResult first = hot_keys.submit("k", op, op.freeze(Retry::standard()), strict); + /// A single-attempt hold reads, and the garbage lands between that read and its write: the write + /// loses, and the lane remembers the garbage its resolve read saw, as nobody retries that conflict. + std::optional garbage; + backend->onBeforeWrite("k", [&] + { + backend->onBeforeWrite("k", [] {}); + auto current = external.read("k", Retry::standard()); + garbage = *orThrow(external.replace("k", "garbage", current->etag, Retry::standard()), "break"); + }); + WriteResult first = hot_keys.submit("k", op, Retry::once(), strict); ASSERT_TRUE(std::holds_alternative(first)); - (void)orThrow(external.replace("k", "9", garbage, Retry::standard()), "repair"); + ASSERT_TRUE(garbage.has_value()); + (void)orThrow(external.replace("k", "9", *garbage, Retry::standard()), "repair"); const auto reread_before = counter(ProfileEvents::CASHotKeyCacheVerdictsReread); /// The verdict on the cached garbage is not delivered: one read, and the decide lands on the repair. - WriteResult second = hot_keys.submit("k", op, op.freeze(Retry::standard()), strict); + WriteResult second = hot_keys.submit("k", op, Retry::standard(), strict); ASSERT_TRUE(std::holds_alternative(second)); EXPECT_EQ(counter(ProfileEvents::CASHotKeyCacheVerdictsReread) - reread_before, 1u); DB::Cas::tests::expectBytes(*backend, "k", "9,9"); - /// And when the read is garbage too, that is the real corruption. - current = external.read("k", Retry::standard()); + /// And when the read is garbage too, that is the real corruption: the hold loses on its cache and + /// decides again on a resolve read that is garbage. + const auto current = external.read("k", Retry::standard()); (void)orThrow(external.replace("k", "garbage", current->etag, Retry::standard()), "break again"); - (void)hot_keys.submit("k", op, op.freeze(Retry::standard()), strict); /// conflict: the cache now holds garbage DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::CORRUPTED_DATA, - [&] { (void)hot_keys.submit("k", op, op.freeze(Retry::standard()), strict); }); + [&] { (void)hot_keys.submit("k", op, Retry::standard(), strict); }); } TEST(CASHotKeys, ADeclineOnAHintIsRerenderedOnARead) @@ -582,10 +754,10 @@ TEST(CASHotKeys, ADeclineOnAHintIsRerenderedOnARead) return std::nullopt; return String("1"); }; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), idempotent))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), idempotent))); /// On a fresh read the decline is the caller's answer. { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::once()), idempotent); + WriteResult result = hot_keys.submit("k", op, Retry::once(), idempotent); const auto * declined = std::get_if(&result); ASSERT_NE(declined, nullptr); EXPECT_TRUE(std::holds_alternative(declined->seen)); @@ -595,12 +767,12 @@ TEST(CASHotKeys, ADeclineOnAHintIsRerenderedOnARead) const auto current = external.read("k", Retry::standard()); (void)orThrow(external.replace("k", "0", current->etag, Retry::standard()), "external"); const uint64_t gets_before = backend->getCount("k"); - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), idempotent); + WriteResult result = hot_keys.submit("k", op, Retry::standard(), idempotent); ASSERT_TRUE(std::holds_alternative(result)); EXPECT_EQ(backend->getCount("k") - gets_before, 1u); DB::Cas::tests::expectBytes(*backend, "k", "1"); /// On an absent key the decline names absence. - WriteResult absent = hot_keys.submit("missing", op, op.freeze(Retry::standard()), + WriteResult absent = hot_keys.submit("missing", op, Retry::standard(), [](const std::optional &) -> std::optional { return std::nullopt; }); const auto * declined = std::get_if(&absent); ASSERT_NE(declined, nullptr); @@ -615,16 +787,16 @@ TEST(CASHotKeys, TheCacheForgetsWhatItCannotVouchFor) CasHotKeys hot_keys(16ULL << 20); CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto op = requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); const auto reads = [&] { return backend->getCount("k"); }; uint64_t before = reads(); #if USE_AWS_S3 /// Refused: dropped, the next hold reads. backend->failNextWriteWith("k", s3Error(Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(2)))); EXPECT_EQ(reads(), before); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(2)))); EXPECT_EQ(reads(), before + 1); #endif @@ -646,39 +818,39 @@ TEST(CASHotKeys, TheCacheForgetsWhatItCannotVouchFor) }); before = reads(); { - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::once()), appendTicket(3)); + WriteResult result = hot_keys.submit("k", op, Retry::once(), appendTicket(3)); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); EXPECT_TRUE(gave_up->sent_any); } backend->onBeforeWrite("k", [] {}); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(3)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(3)))); EXPECT_EQ(reads(), before + 3); /// the base read, the failed resolve read, the next hold's read after the entry was dropped /// An exception out of the write: dropped. backend->failNextWriteWith("k", std::make_exception_ptr(std::logic_error("local"))); before = reads(); - EXPECT_THROW(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(4)), std::logic_error); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(4)))); + EXPECT_THROW(hot_keys.submit("k", op, Retry::standard(), appendTicket(4)), std::logic_error); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(4)))); EXPECT_EQ(reads(), before + 1); /// A give-up that sent nothing leaves the entry as it was: the next hold starts from it. bool alive = true; auto fenced = requests.admit([&] { return alive; }); before = reads(); - WriteResult nothing_sent = hot_keys.submit("k", fenced, fenced.freeze(Retry::standard()), + WriteResult nothing_sent = hot_keys.submit("k", fenced, Retry::standard(), [&](const std::optional & current) -> std::optional { alive = false; return current->bytes + ",5"; }); ASSERT_TRUE(std::holds_alternative(nothing_sent)); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(5)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(5)))); EXPECT_EQ(reads(), before); /// A fill that throws after a landed write: the result stands, the next hold reads. hot_keys.cache_fill_hook_for_test = [] { throw std::bad_alloc(); }; before = reads(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(6)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(6)))); hot_keys.cache_fill_hook_for_test = {}; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(7)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(7)))); EXPECT_EQ(reads(), before + 1); DB::Cas::tests::expectBytes(*backend, "k", kFinalBytes); } @@ -698,18 +870,18 @@ TEST(CASHotKeys, TheBudgetBoundsBytesAndEntries) auto op = requests.admit(); const CasHotKeys::Decide one_byte = [](const std::optional &) -> std::optional { return String("x"); }; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("a", op, op.freeze(Retry::standard()), one_byte))); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("b", op, op.freeze(Retry::standard()), one_byte))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("a", op, Retry::standard(), one_byte))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("b", op, Retry::standard(), one_byte))); EXPECT_EQ(hot_keys.cacheEntriesForTest(), 1u) << "the older entry was evicted"; const uint64_t gets_a = backend->getCount("a"); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("a", op, op.freeze(Retry::standard()), one_byte))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("a", op, Retry::standard(), one_byte))); EXPECT_EQ(backend->getCount("a"), gets_a + 1) << "the evicted key reads"; /// An object above the budget is not stored. const CasHotKeys::Decide big = [&](const std::optional &) -> std::optional { return String(one_entry * 2, 'y'); }; - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("c", op, op.freeze(Retry::standard()), big))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("c", op, Retry::standard(), big))); const uint64_t gets_c = backend->getCount("c"); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("c", op, op.freeze(Retry::standard()), big))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("c", op, Retry::standard(), big))); EXPECT_EQ(backend->getCount("c"), gets_c + 1); /// Empty objects weigh their key and their allowance: N of them stay bounded by the budget. @@ -718,7 +890,7 @@ TEST(CASHotKeys, TheBudgetBoundsBytesAndEntries) auto small_op = small_requests.admit(); const CasHotKeys::Decide empty = [](const std::optional &) -> std::optional { return String(); }; for (int i = 0; i < 40; ++i) - ASSERT_TRUE(std::holds_alternative(small.submit("e" + std::to_string(i), small_op, small_op.freeze(Retry::standard()), empty))); + ASSERT_TRUE(std::holds_alternative(small.submit("e" + std::to_string(i), small_op, Retry::standard(), empty))); EXPECT_LE(small.cacheEntriesForTest(), 4u); } @@ -730,12 +902,12 @@ TEST(CASHotKeys, ACachedStartPastTheDeadlineSendsNothing) CasHotKeys hot_keys(16ULL << 20); CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); auto op = requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); /// The window fits the wait's zero reservation but not the write's two attempt envelopes. int decided = 0; const uint64_t writes_before = backend->writeCount("k"); - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::within(500)), + WriteResult result = hot_keys.submit("k", op, Retry::within(500), [&](const std::optional & current) -> std::optional { ++decided; return current->bytes + ",2"; }); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); @@ -754,7 +926,7 @@ TEST(CASHotKeys, AnIdenticalCandidateLandedByAnotherServerIsTheEnginesCommit) auto op = requests.admit(); CasRequests external_requests = DB::Cas::tests::openRequestsForTest(backend); auto external = external_requests.admit(); - ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(1)))); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); /// Another server lands exactly the candidate this hold will compute from its stale hint, and this /// hold's own refused write loses its answer. The resolve read finds the candidate's bytes under @@ -762,10 +934,177 @@ TEST(CASHotKeys, AnIdenticalCandidateLandedByAnotherServerIsTheEnginesCommit) const auto current = external.read("k", Retry::standard()); const Etag theirs = *orThrow(external.replace("k", "1,2", current->etag, Retry::standard()), "identical"); backend->injectAmbiguousWrite("k"); - WriteResult result = hot_keys.submit("k", op, op.freeze(Retry::standard()), appendTicket(2)); + WriteResult result = hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); const auto * committed = std::get_if(&result); ASSERT_NE(committed, nullptr); EXPECT_TRUE(committed->resolved_by_read); EXPECT_TRUE(identicalToken(committed->etag, theirs)); DB::Cas::tests::expectBytes(*backend, "k", "1,2"); } + +/// A waiter whose owner stops while the holder is parked leaves the queue at once, and the waiter +/// behind it takes its turn in order. +TEST(CASHotKeys, CancelledWaiterWithdrawsWhileHolderIsParked) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(0); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + ParkFirstWrite park; + park.install(*backend, "k"); + std::atomic stop{false}; + std::atomic released{false}; + + std::optional holder_result; + std::thread holder([&] + { + auto op = requests.admit(); + holder_result = hot_keys.submit("k", op, Retry::standard(), appendTicket(1)); + }); + park.parked.wait(); + + std::promise cancelled_code; + auto cancelled_returned = cancelled_code.get_future(); + bool returned_while_parked = false; + std::thread cancelled([&] + { + auto owner = OwnerScope::background([&stop] + { + if (stop) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + auto op = requests.admit(); + int code = 0; + try + { + (void)hot_keys.submit("k", op, Retry::standard(), appendTicket(2)); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + returned_while_parked = !released; + cancelled_code.set_value(code); + }); + while (hot_keys.queueDepthForTest("k") < 2) + std::this_thread::yield(); + + std::optional next_result; + std::thread next([&] + { + auto op = requests.admit(); + next_result = hot_keys.submit("k", op, Retry::standard(), appendTicket(3)); + }); + while (hot_keys.queueDepthForTest("k") < 3) + std::this_thread::yield(); + + stop = true; + const bool in_time = cancelled_returned.wait_for(std::chrono::seconds(30)) == std::future_status::ready; + EXPECT_TRUE(in_time) << "the cancelled waiter stayed queued behind the parked holder"; + if (in_time) + EXPECT_EQ(hot_keys.queueDepthForTest("k"), 2u) << "the cancelled item left the queue"; + released = true; + park.release.count_down(); + holder.join(); + cancelled.join(); + next.join(); + + EXPECT_EQ(cancelled_returned.get(), DB::ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_parked); + ASSERT_TRUE(holder_result && std::holds_alternative(*holder_result)); + ASSERT_TRUE(next_result && std::holds_alternative(*next_result)); + EXPECT_EQ(backend->writeCount("k"), 2u) << "the cancelled waiter wrote nothing"; + DB::Cas::tests::expectBytes(*backend, "k", "1,3"); + EXPECT_EQ(hot_keys.laneCountForTest(), 0u); +} + +/// A decision on a cached hint that ends because its owner stopped is no verdict on the hint: the +/// stop is thrown, with no reread and no second decision. +TEST(CASHotKeys, CancelledHintDecisionDoesNotReread) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); + const uint64_t gets_before = backend->getCount("k"); + const uint64_t writes_before = backend->writeCount("k"); + const auto reread_before = counter(ProfileEvents::CASHotKeyCacheVerdictsReread); + + std::atomic stop{false}; + auto owner = OwnerScope::background([&stop] + { + if (stop) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + int decisions = 0; + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::ABORTED, [&] + { + (void)hot_keys.submit("k", op, Retry::standard(), [&](const std::optional & current) -> std::optional + { + ++decisions; + /// The owner stops while the decision runs, and the code it calls asks the owner. + stop = true; + throwIfBackgroundStopped(); + return current->bytes + ",2"; + }); + }); + EXPECT_EQ(decisions, 1); + EXPECT_EQ(backend->getCount("k") - gets_before, 0u) << "no reread"; + EXPECT_EQ(backend->writeCount("k") - writes_before, 0u); + EXPECT_EQ(counter(ProfileEvents::CASHotKeyCacheVerdictsReread) - reread_before, 0u); +} + +namespace +{ + +/// Runs `on_read` before each read. +class ReadHookBackend final : public CountingBackend +{ +public: + std::function on_read; + + std::optional read(const String & key, TransportAccess & access) override + { + if (on_read) + on_read(); + return CountingBackend::read(key, access); + } +}; + +} + +/// A decline on a cached hint is reread; when the owner stops during that read, the decision on it does +/// not run. +TEST(CASHotKeys, StopDuringHintRereadSkipsTheSecondDecision) +{ + SyncClock clock; + auto backend = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), &hot_keys, DB::Cas::kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(hot_keys.submit("k", op, Retry::standard(), appendTicket(1)))); + const uint64_t gets_before = backend->getCount("k"); + const auto reread_before = counter(ProfileEvents::CASHotKeyCacheVerdictsReread); + + std::atomic stop{false}; + auto owner = OwnerScope::background([&stop] + { + if (stop) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + backend->on_read = [&stop] { stop = true; }; + int decisions = 0; + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::ABORTED, [&] + { + (void)hot_keys.submit("k", op, Retry::standard(), [&](const std::optional &) -> std::optional + { + ++decisions; + return std::nullopt; + }); + }); + EXPECT_EQ(decisions, 1) << "the decision on the reread did not run"; + EXPECT_EQ(backend->getCount("k") - gets_before, 1u); + EXPECT_EQ(counter(ProfileEvents::CASHotKeyCacheVerdictsReread) - reread_before, 1u); +} diff --git a/src/Disks/tests/gtest_cas_killable_query.cpp b/src/Disks/tests/gtest_cas_killable_query.cpp new file mode 100644 index 0000000000000..506a966670e61 --- /dev/null +++ b/src/Disks/tests/gtest_cas_killable_query.cpp @@ -0,0 +1,42 @@ +#include + +#include +#include + +namespace DB::Cas::tests +{ + +CasKillableQuery::CasKillableQuery(ContextPtr global) + : context(Context::createCopy(global)) +{ + context->setCurrentQueryId(""); + group = std::make_shared(context, 0); + attachCurrentThread(); + /// The process list binds the query to the group of the inserting thread, so attach first. + entry = context->getProcessList().insert( + /*query_=*/"", /*normalized_query_hash=*/0, /*ast=*/nullptr, context, + /*watch_start_nanoseconds=*/clock_gettime_ns(), /*is_internal=*/true); + status = entry->getQueryStatus(); + context->setProcessListElement(status); +} + +CasKillableQuery::~CasKillableQuery() +{ + /// `ThreadStatus` checks on destruction that an attached query's context is still alive. + if (group && CurrentThread::getGroup() == group) + CurrentThread::detachFromGroupIfNotDetached(); + context->setProcessListElement(nullptr); + entry.reset(); +} + +void CasKillableQuery::attachCurrentThread() +{ + CurrentThread::attachToGroup(group); +} + +void CasKillableQuery::kill(std::exception_ptr cause) +{ + status->cancelQuery(CancelReason::CANCELLED_BY_USER, cause); +} + +} diff --git a/src/Disks/tests/gtest_cas_migrate_pool.cpp b/src/Disks/tests/gtest_cas_migrate_pool.cpp index 2ca32c91f094a..40e1dca74081f 100644 --- a/src/Disks/tests/gtest_cas_migrate_pool.cpp +++ b/src/Disks/tests/gtest_cas_migrate_pool.cpp @@ -27,7 +27,9 @@ #include #include #include +#include #include +#include "cas_killable_query.h" #include "cas_test_helpers.h" #include @@ -42,11 +44,17 @@ extern const int BAD_ARGUMENTS; extern const int CANNOT_SCHEDULE_TASK; extern const int CORRUPTED_DATA; extern const int INVALID_STATE; +extern const int NETWORK_ERROR; extern const int NOT_IMPLEMENTED; extern const int READONLY; extern const int UNKNOWN_FORMAT_VERSION; } +namespace DB::FailPoints +{ +extern const char thread_group_switcher_post_attach_failure[]; +} + namespace ProfileEvents { extern const Event CASGCIntentConfirmedExisting; @@ -60,6 +68,34 @@ namespace /// The in-memory store with a switchable dialect, `HEAD`s that answer a weak token, injected write and delete /// refusals, and hooks after a write lands and before a `HEAD`. +/// Serves `header`, then on the next refill runs `on_refill` and the cancellation check a store client makes. +class HeaderThenStoppedReadBuffer : public DB::ReadBuffer +{ +public: + HeaderThenStoppedReadBuffer(String header_, std::function on_refill_) + : DB::ReadBuffer(nullptr, 0), header(std::move(header_)), on_refill(std::move(on_refill_)) + { + } + +private: + bool nextImpl() override + { + if (!served) + { + served = true; + BufferBase::set(header.data(), header.size(), 0); + return true; + } + on_refill(); + DB::CurrentThread::checkIfNotCancelled(); + return false; + } + + String header; + std::function on_refill; + bool served = false; +}; + class MigrationBackend : public CountingBackend { public: @@ -117,6 +153,30 @@ class MigrationBackend : public CountingBackend after_write = std::move(hook); } + /// The stream of `key` serves its first line, then runs `hook` and fails as a stopped query's read does. + void stopStreamAfterHeader(const String & key, std::function hook) + { + std::lock_guard lock(mutex); + stopped_stream_key = key; + stopped_stream_hook = std::move(hook); + } + + std::unique_ptr stream(const String & key, TransportAccess & access) override + { + std::function hook; + { + std::lock_guard lock(mutex); + if (key == stopped_stream_key) + hook = stopped_stream_hook; + } + if (!hook) + return CountingBackend::stream(key, access); + const auto raw = CountingBackend::read(key, access); + if (!raw) + return nullptr; + return std::make_unique(raw->bytes.substr(0, raw->bytes.find('\n') + 1), hook); + } + /// Runs `hook` once, before the first `HEAD` of `key` is served. void beforeHead(const String & key, std::function hook) { @@ -259,6 +319,8 @@ class MigrationBackend : public CountingBackend std::function before_head; String after_head_key; std::function after_head; + String stopped_stream_key; + std::function stopped_stream_hook; }; /// A live holder's slot body declaring a 30 s lease. @@ -2893,3 +2955,126 @@ TEST(CASBoundedRun, FailedSubmissionJoinsTheQueuedJobs) ASSERT_EQ(finished.load(), 3u) << "a submitted job was not joined before the failure left the run"; } } + +/// A job whose thread fails to join the submitting query's thread group does not run: outside the query its requests +/// would not see the query's stop. The failpoint fails one switch only, so the other job may run in the query. +TEST(CASBoundedRun, JobOutsideTheQueryDoesNotRun) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + std::mutex mutex; + std::vector ran_in_query; + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + /// Armed after the query's own attach, so a job's switch is the one that fails. + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + try + { + runBounded(*makeBoundedPool(2), DB::ThreadName::UNKNOWN, 2, [&](size_t) + { + const bool in_query = DB::CurrentThread::getGroup() == query.group; + std::lock_guard lock(mutex); + ran_in_query.push_back(in_query); + }); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + EXPECT_EQ(code, DB::ErrorCodes::CANNOT_SCHEDULE_TASK); + EXPECT_LE(ran_in_query.size(), 1u) << "both jobs ran although one could not join the query"; + for (const bool in_query : ran_in_query) + EXPECT_TRUE(in_query) << "a job ran outside the query"; +} + +namespace +{ + +/// The message of the stored cause after `run` killed its query with it. +String storedMessageAfter(const std::exception_ptr & cause) +{ + try + { + std::rethrow_exception(cause); + } + catch (const DB::Exception & e) + { + return e.message(); + } +} + +} + +/// A marker removal that fails with a killed query's stored cause reaches the caller unannotated, through the +/// removal's own catch and the M9 page's: the query rethrows that one object to every thread it stops. +TEST(CASMigratePool, MarkerRemovalLeavesTheStoredQueryExceptionUnchanged) +{ + Fixture f(3); + seedMixedPool(f); + const String stored_text = "the query's stored network failure"; + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "{}", stored_text)); + bool fired = false; + int code = 0; + std::vector lines; + onKillableQueryThread([&](CasKillableQuery & query) + { + f.backend->beforeHead(*f.markers().begin(), [&] + { + fired = true; + query.kill(cause); + std::rethrow_exception(cause); + }); + MigratePoolOptions one_at_a_time; + one_at_a_time.concurrency = 1; + try + { + f.run(one_at_a_time, &lines); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_TRUE(fired) << "the run never removed a marker"; + EXPECT_TRUE(contains(lines, "M8")) << "the kill landed before the marker removal"; + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR); + EXPECT_EQ(storedMessageAfter(cause), stored_text) << "a marker removal annotated the query's stored exception"; +} + +/// An inherited run whose refill fails with a killed query's stored `CORRUPTED_DATA` reaches the caller unannotated +/// through M3's catch, which annotates that code otherwise. +TEST(CASMigratePool, InheritedRunReadLeavesTheStoredQueryExceptionUnchanged) +{ + Fixture f(3); + f.body(1); + f.rows({f.row(1, /*pending*/ true)}); + const std::vector run_keys = adoptedRunKeysOf(f); + ASSERT_FALSE(run_keys.empty()); + const String stored_text = "the query's stored corruption"; + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "{}", stored_text)); + bool fired = false; + int code = 0; + onKillableQueryThread([&](CasKillableQuery & query) + { + f.backend->stopStreamAfterHeader(run_keys.front(), [&] + { + fired = true; + query.kill(cause); + }); + try + { + f.run(); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_TRUE(fired) << "the run never refilled the inherited run"; + EXPECT_EQ(code, DB::ErrorCodes::CORRUPTED_DATA); + EXPECT_EQ(storedMessageAfter(cause), stored_text) << "M3 annotated the query's stored exception"; +} diff --git a/src/Disks/tests/gtest_cas_namespace_janitor.cpp b/src/Disks/tests/gtest_cas_namespace_janitor.cpp index 5ce77394a95d0..5df4369eafe26 100644 --- a/src/Disks/tests/gtest_cas_namespace_janitor.cpp +++ b/src/Disks/tests/gtest_cas_namespace_janitor.cpp @@ -2,6 +2,12 @@ #include #include #include +#include +#include +#include + +#include +#include using namespace DB::Cas; using namespace DB::Cas::tests; @@ -9,6 +15,7 @@ using namespace DB::Cas::tests; namespace DB::ErrorCodes { extern const int NETWORK_ERROR; + extern const int READONLY; } namespace @@ -698,6 +705,94 @@ TEST(CASNamespaceJanitor, CursorPublicationFailureIsLeakOnly) EXPECT_FALSE(readObj(*backend, dead).has_value()); } +namespace +{ + +/// The first cursor write loses its reply without landing; `on_settle` runs in the read that settles it. +class LostCursorWriteBackend : public CountingBackend +{ +public: + std::function on_settle; + bool write_failed = false; + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (key.ends_with("/gc/maintenance_state") && !write_failed) + { + write_failed = true; + throw Poco::TimeoutException("LostCursorWriteBackend: the cursor write timed out"); + } + return CountingBackend::write(key, bytes, expected_value, access); + } + + std::optional read(const String & key, DB::Cas::TransportAccess & access) override + { + if (key.ends_with("/gc/maintenance_state") && write_failed && on_settle) + std::exchange(on_settle, nullptr)(); + return CountingBackend::read(key, access); + } +}; + +} + +/// A cursor write whose outcome stays unknown because the query stopped in its settling read ends the page with the +/// unresolved 210 instead of an anomaly. A live owner resends the cursor and publishes it. +TEST(CASNamespaceJanitor, UnresolvedCursorWriteOfAStoppedQueryPropagates) +{ + for (const bool kill : {true, false}) + { + SCOPED_TRACE(kill ? "killed in the settling read" : "live"); + auto backend = std::make_shared(); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, DB::Cas::kDefaultRequestWindowMs); + const Layout layout("p"); + seedCatalog(*backend, layout); + const String dead = layout.refCkptKey(life("dead", 145)); + createObj(*backend, dead, "bytes"); + + int code = 0; + String message; + std::optional result; + std::thread caller([&] + { + DB::ThreadStatus thread_status; + CasKillableQuery query(::getContext().context); + if (kill) + backend->on_settle = [&query] + { + query.kill(); + throw Poco::TimeoutException("LostCursorWriteBackend: the settling read timed out"); + }; + try + { + result = NamespaceJanitor(requests, layout, 100).runOnePage(false, [] { return true; }); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + caller.join(); + + EXPECT_FALSE(readObj(*backend, dead).has_value()); + if (kill) + { + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << message; + EXPECT_NE(message.find("unresolved"), String::npos) << message; + EXPECT_FALSE(result.has_value()); + } + else + { + EXPECT_EQ(code, 0) << message; + ASSERT_TRUE(result.has_value()); + EXPECT_TRUE(result->anomalies.empty()); + EXPECT_TRUE(readState(requests, layout).state.has_value()) << "the resent cursor was published"; + } + } +} + /// The write inside `catch (...)` (the reset after a LIST failure) is admitted `once`: an unmodeled, /// unresolvable write attempt must give up after its one exact resolve read rather than looping through /// `Retry::standard()`'s backoff. `write_attempts == 1` is the discriminator: under `standard`, the same @@ -719,6 +814,153 @@ TEST(CASGcMaintenanceState, CatchPathWriteIsOnce) << "the catch-path reset settles by its one resolve read and gives up rather than reissuing"; } +namespace +{ + +/// Every `LIST` runs `on_list`, then fails with a transport error. +class FailingListBackend : public CountingBackend +{ +public: + std::function on_list; + + DB::Cas::Backend::RawListPage list(const String &, const String &, size_t, DB::Cas::TransportAccess &) override + { + if (on_list) + on_list(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "list failed"); + } +}; + +} + +/// A stopped query's failed first `LIST` ends the page with that failure and keeps the scan's cursor: the stop vetoed +/// the optional reset. A live owner's failed first `LIST` resets the cursor. +TEST(CASNamespaceJanitor, StoppedQuerysFailedListKeepsTheCursor) +{ + for (const bool kill : {true, false}) + { + SCOPED_TRACE(kill ? "killed in the LIST" : "live"); + auto backend = std::make_shared(); + FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + const Layout layout("p"); + createObj(*backend, layout.gcMaintenanceStateKey(), encodeGcMaintenanceState({.janitor_cursor = "kept"})); + const uint64_t writes_before = backend->writeCount(layout.gcMaintenanceStateKey()); + + int code = 0; + String message; + onKillableQueryThread([&](CasKillableQuery & query) + { + if (kill) + backend->on_list = [&query] { query.kill(); }; + try + { + (void)NamespaceJanitor(requests, layout, 100).runOnePage(false, [] { return true; }, /*first_page_of_pass=*/true); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + }); + + EXPECT_NE(code, 0); + if (kill) + { + EXPECT_EQ(backend->writeCount(layout.gcMaintenanceStateKey()), writes_before) << "a reset was sent: " << message; + EXPECT_EQ(readState(requests, layout).state->janitor_cursor, "kept"); + } + else + { + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << message; + EXPECT_TRUE(readState(requests, layout).state->janitor_cursor.empty()) << "the live owner reset the cursor"; + } + } +} + +/// A cursor reset after a failed `LIST` that may still land is what the caller learns, not the listing error. +TEST(CASNamespaceJanitor, AnUnresolvedResetAfterAFailedListIsReported) +{ + auto backend = std::make_shared(); + FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + const Layout layout("p"); + + const String message = DB::Cas::tests::messageOf(DB::ErrorCodes::NETWORK_ERROR, + [&] { (void)NamespaceJanitor(requests, layout, 100).runOnePage(false, [] { return true; }, /*first_page_of_pass=*/true); }); + EXPECT_NE(message.find("cursor reset after a failed LIST: the write is unresolved"), String::npos) << message; +} + +namespace +{ + +/// The janitor's cursor write: refused as `READONLY`, after killing the query when `kill`. +struct RefusedCursorRound +{ + int code = 0; + String message; + std::set phases; +}; + +RefusedCursorRound runRoundWithARefusedCursorWrite(bool kill) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend, /*gc_fold_max_defer_rounds=*/0); + const Layout & layout = store->layout(); + const RootNamespace live_namespace{"00/live@cas@"}; + fixture::admitLive(*backend, layout, live_namespace); + createObj(*backend, layout.refCkptKey(fixture::fixtureLife(live_namespace)), + encodeRefCkptAtGeneration(RefCkpt{.life_epoch = std::optional{1}, + .checkpoint_snapshot_id = std::nullopt, .last_epoch_seal = std::nullopt}, 1)); + createObj(*backend, layout.refCkptKey(life("dead", 153)), "checkpoint"); + + RefusedCursorRound out; + Gc gc(store, UInt128{154}); + gc.setPhaseSink([&](const GcPhaseRecord & record) { out.phases.insert(record.phase); }); + onKillableQueryThread([&](CasKillableQuery & query) + { + backend->onBeforeWrite(layout.gcMaintenanceStateKey(), [&query, kill] + { + if (kill) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "the store is read-only"); + }); + try + { + (void)runRegularRoundReclaiming(gc); + } + catch (const DB::Exception & e) + { + out.code = e.code(); + out.message = e.message(); + } + }); + gc.setPhaseSink({}); + return out; +} + +} + +/// A stopped query's refused cursor write ends the round with the refusal, before ref cleanup starts. A live owner +/// records an anomaly and goes on to ref cleanup. +TEST(CASNamespaceJanitorIntegration, RefusedCursorWriteOfAStoppedQueryEndsTheRound) +{ + { + SCOPED_TRACE("killed in the cursor write"); + const auto out = runRoundWithARefusedCursorWrite(/*kill=*/true); + EXPECT_EQ(out.code, DB::ErrorCodes::READONLY) << out.message; + EXPECT_NE(out.message.find("the store is read-only"), String::npos) << out.message; + EXPECT_TRUE(out.phases.contains("namespace_cleanup")); + EXPECT_FALSE(out.phases.contains("ref_object_cleanup")) << "ref cleanup started"; + } + { + SCOPED_TRACE("live"); + const auto out = runRoundWithARefusedCursorWrite(/*kill=*/false); + EXPECT_EQ(out.code, 0) << out.message; + EXPECT_TRUE(out.phases.contains("ref_object_cleanup")); + } +} + TEST(CASNamespaceJanitorIntegration, RegularGcRoundDeletesDeadNamespaceBytes) { auto backend = std::make_shared(); diff --git a/src/Disks/tests/gtest_cas_operation_gate.cpp b/src/Disks/tests/gtest_cas_operation_gate.cpp index 2dbddf6c5f54a..5e9f84a74bc4b 100644 --- a/src/Disks/tests/gtest_cas_operation_gate.cpp +++ b/src/Disks/tests/gtest_cas_operation_gate.cpp @@ -4,17 +4,32 @@ #include #include #include +#include #include +#include #include #include +#include #include +#include +#include +#include +#include + +#include #include +#include #include #include +#include #include +#include +#include #include #include +#include +#include /// Task 8 (rev.7 spec §1): the central six-class operation gate (`checkOpAdmitted`), the `Vanished` truth /// semantics, and the [D5] per-reason typed messages. These tests build a real @@ -28,8 +43,14 @@ /// captured handle -- the SAME object the metadata storage's `cas_store` points at -- rather than calling /// `store()` again after forcing a terminal state. +namespace CurrentMetrics +{ +extern const Metric IsServerShuttingDown; +} + namespace DB::ErrorCodes { +extern const int ABORTED; extern const int INVALID_STATE; extern const int NETWORK_ERROR; extern const int FILE_DOESNT_EXIST; @@ -58,15 +79,15 @@ std::shared_ptr openGateStorage() /// Commit one real part (tmp -> final rename -> commit), leaving `kPartFile` durable and `kPartDir`/ /// `kTableDir` non-empty. Every op below runs against this committed state. -void commitOnePart(ContentAddressedMetadataStorage & storage) +void commitOnePart(ContentAddressedMetadataStorage & storage, const std::string & table_dir = kTableDir) { auto tx = storage.createTransaction(); auto & ca_tx = dynamic_cast(*tx); - auto buf = ca_tx.writeFile(kTableDir + "/tmp_insert_all_1_1_0/data.bin", 65536, WriteMode::Rewrite, {}); + auto buf = ca_tx.writeFile(table_dir + "/tmp_insert_all_1_1_0/data.bin", 65536, WriteMode::Rewrite, {}); const std::string bytes = "content-of-the-part"; buf->write(bytes.data(), bytes.size()); buf->finalize(); - tx->moveDirectory(kTableDir + "/tmp_insert_all_1_1_0", kPartDir); + tx->moveDirectory(table_dir + "/tmp_insert_all_1_1_0", table_dir + "/all_1_1_0"); tx->commit(NoCommitOptions{}); } @@ -435,3 +456,248 @@ TEST(CASOperationGate, RemoveThrowsDuringTransientAndDrainsAfterRecovery) << "the re-queued removal must drain (really remove the part) once the disk recovers to Live"; EXPECT_FALSE(storage->existsFile(kPartFile)); } + +namespace +{ + +constexpr auto SHUTDOWN_WATCHDOG = std::chrono::seconds(30); + +/// The table dir shape of an `Atomic` database, which the catalog's drop worker removes. +const std::string kAtomicTableDir = "store/a80/a80a80a8-0808-4808-8808-080808080808"; +const std::string kAtomicPartDir = kAtomicTableDir + "/all_1_1_0"; + +/// Server shutdown as the drop worker sees it; restored when the test ends, also on a failed assertion. +struct ServerShuttingDown +{ + ServerShuttingDown() = default; + ServerShuttingDown(const ServerShuttingDown &) = delete; + ServerShuttingDown & operator=(const ServerShuttingDown &) = delete; + ~ServerShuttingDown() { CurrentMetrics::set(CurrentMetrics::IsServerShuttingDown, 0); } + static void begin() { CurrentMetrics::set(CurrentMetrics::IsServerShuttingDown, 1); } +}; + +/// The code of removing `table_dir` in one committed transaction on the calling thread, 0 on success. +int removeTableDir(ContentAddressedMetadataStorage & storage, const std::string & table_dir) +{ + return DB::Cas::tests::exceptionCodeOf([&] + { + auto tx = storage.createTransaction(); + tx->removeRecursive(table_dir, /*should_remove_objects=*/nullptr); + tx->commit(NoCommitOptions{}); + }); +} + +/// Local object storage whose next catalog write is lost before it lands, as a timed-out PUT. The first +/// catalog probe after that loss runs `on_settlement_probe`. +class LosingCatalogWriteObjectStorage : public LocalObjectStorage +{ +public: + using LocalObjectStorage::LocalObjectStorage; + + std::unique_ptr writeObject( + const StoredObject & object, WriteMode mode, std::optional attributes, + size_t buf_size, const WriteSettings & write_settings) override + { + if (object.remote_path.ends_with(catalog_key)) + { + ++catalog_writes; + if (lose_next_catalog_write.exchange(false)) + { + lost = true; + throw Poco::TimeoutException("catalog write lost before it landed"); + } + } + return LocalObjectStorage::writeObject(object, mode, attributes, buf_size, write_settings); + } + + bool exists(const StoredObject & object) const override + { + if (lost && object.remote_path.ends_with(catalog_key) && on_settlement_probe) + std::exchange(on_settlement_probe, nullptr)(); + return LocalObjectStorage::exists(object); + } + + String catalog_key; + std::atomic lose_next_catalog_write{false}; + std::atomic lost{false}; + std::atomic catalog_writes{0}; + mutable std::function on_settlement_probe; +}; + +} + +/// A drop worker's table removal waiting for another removal's attempt leaves at server shutdown with 236. +/// The holder, a query, keeps its claim and completes. +TEST(CASOperationGate, ServerShutdownStopsTableRemovalFollowerWithoutTouchingOwner) +{ + auto storage = openGateStorage(); + commitOnePart(*storage, kAtomicTableDir); + auto pool = storage->store(); + const Cas::RootNamespace ns = storage->liveNamespace(*Cas::parseTableUuid(kAtomicTableDir)); + ServerShuttingDown shutdown; + + std::mutex mutex; + std::condition_variable cv; + bool holder_parked = false; + bool follower_returned = false; + bool holder_left = false; + std::atomic holder_entered{false}; + pool->setRemovalAttemptHookForTest([&] + { + if (holder_entered.exchange(true)) + return; + std::unique_lock lock(mutex); + holder_parked = true; + cv.notify_all(); + cv.wait_for(lock, SHUTDOWN_WATCHDOG, [&] { return follower_returned; }); + holder_left = true; + }); + SCOPE_EXIT({ pool->setRemovalAttemptHookForTest({}); }); + + std::future holder = std::async(std::launch::async, [&] + { + std::optional thread_status; + thread_status.emplace(); + Cas::tests::CasKillableQuery query(getContext().context); + return removeTableDir(*storage, kAtomicTableDir); + }); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, SHUTDOWN_WATCHDOG, [&] { return holder_parked; })); + } + + int follower_code = 0; + bool returned_while_holder_parked = false; + Cas::CasRefLedger::RemovalFlagsForTest flags_on_return; + std::thread follower([&] + { + std::optional thread_status; + thread_status.emplace(); + /// The holder passed this hook before it parked, so shutdown begins while only the follower is in it. + pool->setRemovalRuntimeAcquiredHookForTest([] { ServerShuttingDown::begin(); }); + follower_code = removeTableDir(*storage, kAtomicTableDir); + pool->setRemovalRuntimeAcquiredHookForTest(nullptr); + flags_on_return = pool->removalFlagsForTest(ns); + std::lock_guard lock(mutex); + follower_returned = true; + returned_while_holder_parked = !holder_left; + cv.notify_all(); + }); + follower.join(); + ASSERT_EQ(holder.wait_for(SHUTDOWN_WATCHDOG), std::future_status::ready); + + EXPECT_EQ(follower_code, ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_holder_parked) << "the stopped follower waited for the holder's attempt"; + EXPECT_TRUE(flags_on_return.attempt_active) << "the holder's attempt must stay claimed"; + EXPECT_TRUE(flags_on_return.admission_closed) << "the holder's closed lane must stay closed"; + EXPECT_EQ(holder.get(), 0) << "a removal with a query attached is not stopped by server shutdown"; + EXPECT_FALSE(storage->existsDirectory(kAtomicPartDir)); +} + +/// Shutdown begins while the drop worker settles a lost `Live -> Removing` write. The write is not resent, +/// the worker gets the unresolved retry-later exit, and the lane stays closed against the write that may land. +/// A retry without shutdown completes the removal. +TEST(CASOperationGate, ServerShutdownAfterPossibleRemovingWriteRetainsClosure) +{ + static std::atomic counter{0}; + const std::string unique = std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)); + const auto root = (std::filesystem::temp_directory_path() / ("ca_op_gate_lost_write_" + unique)).string(); + std::filesystem::remove_all(root); + std::filesystem::create_directories(root); + auto object_storage = Cas::tests::ownedByDirectory( + std::make_shared(LocalObjectStorageSettings("test", root, /*read_only_=*/false)), root); + const auto scratch = std::filesystem::temp_directory_path() / ("ca_op_gate_lost_write_scratch_" + unique); + auto storage = Cas::tests::ownedByDirectory(std::make_shared( + object_storage, "pool", "srv1", "", nullptr, Cas::tests::makeSettingsForTest("test", scratch)), scratch); + storage->startup(); + commitOnePart(*storage, kAtomicTableDir); + auto pool = storage->store(); + ServerShuttingDown shutdown; + + object_storage->catalog_key = pool->layout().refCatalogKey(); + object_storage->on_settlement_probe = [] { ServerShuttingDown::begin(); }; + object_storage->lose_next_catalog_write = true; + const int catalog_writes_before = object_storage->catalog_writes; + + std::thread worker([&] + { + std::optional thread_status; + thread_status.emplace(); + EXPECT_EQ(removeTableDir(*storage, kAtomicTableDir), ErrorCodes::NETWORK_ERROR); + }); + worker.join(); + + EXPECT_TRUE(object_storage->lost) << "the Removing write was never sent"; + EXPECT_FALSE(object_storage->on_settlement_probe) << "the lost write was never settled by a read"; + EXPECT_EQ(object_storage->catalog_writes - catalog_writes_before, 1) << "a stopped worker resends nothing"; + const auto flags = pool->removalFlagsForTest(storage->liveNamespace(*Cas::parseTableUuid(kAtomicTableDir))); + EXPECT_FALSE(flags.attempt_active); + EXPECT_TRUE(flags.admission_closed) << "the lane must stay closed against the write that may land"; + + CurrentMetrics::set(CurrentMetrics::IsServerShuttingDown, 0); + EXPECT_EQ(removeTableDir(*storage, kAtomicTableDir), 0) << "the retried removal must complete"; + EXPECT_FALSE(storage->existsDirectory(kAtomicPartDir)); +} + +/// Shutdown that begins after the terminal record does not stop the removal: no owner check runs between +/// that record and the return. Does not hold a publisher in flight. +TEST(CASOperationGate, ShutdownAfterTerminalRecordDoesNotStopRemoval) +{ + auto storage = openGateStorage(); + commitOnePart(*storage, kAtomicTableDir); + auto pool = storage->store(); + ServerShuttingDown shutdown; + + std::atomic removing{false}; + std::atomic shutdown_after_terminal{false}; + pool->setCarveHookForTest([&](Cas::CasRefLedger::CarvePhaseForTest phase) + { + if (phase == Cas::CasRefLedger::CarvePhaseForTest::PostDurableInstall && removing && !shutdown_after_terminal.exchange(true)) + ServerShuttingDown::begin(); + }); + SCOPE_EXIT({ pool->setCarveHookForTest({}); }); + + int code = -1; + std::thread worker([&] + { + std::optional thread_status; + thread_status.emplace(); + removing = true; + code = removeTableDir(*storage, kAtomicTableDir); + }); + worker.join(); + + EXPECT_TRUE(shutdown_after_terminal) << "the terminal record was never appended"; + EXPECT_EQ(code, 0); + EXPECT_FALSE(storage->existsDirectory(kAtomicPartDir)); +} + +/// A non-Atomic table directory, such as a temporary table's, is removed by a caller that never retries it, +/// so server shutdown does not stop its removal. +TEST(CASOperationGate, ShutdownDoesNotStopNonAtomicTableRemoval) +{ + const std::string table_dir = "data/_temporary_and_external_tables/_tmp_0a1b2c3d-0a1b-4c2d-8e3f-0a1b2c3d4e5f"; + auto storage = openGateStorage(); + commitOnePart(*storage, table_dir); + auto pool = storage->store(); + const auto table_id = Cas::parseTableUuid(table_dir); + ASSERT_TRUE(table_id); + ASSERT_FALSE(Cas::endsWithTableUuidPair(table_dir)); + const Cas::RootNamespace ns = storage->liveNamespace(*table_id); + ASSERT_TRUE(pool->namespaceStillLogicallyPresent(ns)); + ServerShuttingDown shutdown; + ServerShuttingDown::begin(); + + int code = -1; + std::thread remover([&] + { + std::optional thread_status; + thread_status.emplace(); + code = removeTableDir(*storage, table_dir); + }); + remover.join(); + + EXPECT_EQ(code, 0); + EXPECT_FALSE(storage->existsDirectory(table_dir + "/all_1_1_0")); + EXPECT_FALSE(pool->namespaceStillLogicallyPresent(ns)); +} diff --git a/src/Disks/tests/gtest_cas_own_creating_cleanup.cpp b/src/Disks/tests/gtest_cas_own_creating_cleanup.cpp index 369ed5cbf831a..371b16faa731e 100644 --- a/src/Disks/tests/gtest_cas_own_creating_cleanup.cpp +++ b/src/Disks/tests/gtest_cas_own_creating_cleanup.cpp @@ -7,9 +7,15 @@ #include +#include #include #include +namespace DB::ErrorCodes +{ +extern const int ABORTED; +} + namespace ProfileEvents { extern const Event CASOwnCreatingCancelled; @@ -109,3 +115,43 @@ TEST(CASOwnCreatingCleanup, AStopRequestBeforeThePassSendsNothing) EXPECT_EQ(requestTotal(*backend) - before, 0u); EXPECT_EQ(ownCreatingRows(op, store), 3u); } + +/// A stop request that lands while the first row's cancel loses the catalog to another writer ends the pass at +/// that cancel's next submission, before any further catalog write. +TEST(CASOwnCreatingCleanup, AStopRequestDuringARowsConflictEndsThePass) +{ + auto backend = std::make_shared(); + PoolConfig config{.pool_prefix = "p", .server_root_id = "test", .gc_fold_max_defer_rounds = 0}; + config.mount_renew_period = std::chrono::milliseconds{3'600'000}; + config.retry_sleep_fn = [](uint64_t) {}; + PoolPtr store = Pool::open(backend, config); + CasRequests requests = openRequestsForTest(backend); + CasOperation op = requests.admit(); + seedThreeOwnRows(op, store); + const String key = store->layout().refCatalogKey(); + + std::atomic stop = false; + size_t catalog_writes = 0; + bool in_hook = false; + /// Every catalog write of the pass meets an incarnation another writer just moved, as on a hot catalog. + backend->onBeforeWrite(key, [&] + { + if (in_hook) + return; + in_hook = true; + ++catalog_writes; + CasRequests other_requests = openRequestsForTest(backend); + CasOperation other = other_requests.admit(); + const auto current = other.read(key, Retry::once()); + EXPECT_TRUE(current && std::holds_alternative(other.replace(key, current->bytes, current->etag, Retry::once()))); + in_hook = false; + stop = true; + }); + + const uint64_t cancels = ownCancels(); + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { store->cancelIdleOwnCreatingRows([&] { return stop.load(); }); }); + backend->onBeforeWrite(key, {}); + EXPECT_EQ(catalog_writes, 1u) << "the stopped cancel submitted again"; + EXPECT_EQ(ownCancels() - cancels, 0u); + EXPECT_EQ(ownCreatingRows(op, store), 3u); +} diff --git a/src/Disks/tests/gtest_cas_owner_stop.cpp b/src/Disks/tests/gtest_cas_owner_stop.cpp new file mode 100644 index 0000000000000..9b338ad82da04 --- /dev/null +++ b/src/Disks/tests/gtest_cas_owner_stop.cpp @@ -0,0 +1,3968 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#if USE_AWS_S3 +#include +#endif + +namespace DB::ErrorCodes +{ + extern const int ABORTED; + extern const int BAD_ARGUMENTS; + extern const int CORRUPTED_DATA; + extern const int FILE_DOESNT_EXIST; + extern const int MEMORY_LIMIT_EXCEEDED; + extern const int NETWORK_ERROR; + extern const int NOT_IMPLEMENTED; + extern const int QUERY_WAS_CANCELLED; + extern const int READONLY; + extern const int S3_ERROR; + extern const int TIMEOUT_EXCEEDED; +} + +using namespace DB; +using namespace DB::Cas; +using DB::Cas::tests::CasClientLikeBackend; +using DB::Cas::tests::CasKillableQuery; +using DB::Cas::tests::StoppedBy; +using DB::Cas::tests::nameOf; +using DB::Cas::tests::onThread; +using DB::Cas::tests::CountingBackend; +using DB::Cas::tests::ManualClock; +using DB::Cas::tests::TimeTakingBackend; +using DB::Cas::tests::openRequestsForTest; + +namespace +{ + +constexpr auto WATCHDOG = std::chrono::seconds(30); + +/// 0 for no exception. +int codeOf(const std::exception_ptr & e) +{ + if (!e) + return 0; + try + { + std::rethrow_exception(e); + } + catch (const Exception & ex) + { + return ex.code(); + } + catch (...) + { + return -1; + } +} + +/// Empty for no exception. +String messageOf(const std::exception_ptr & e) +{ + if (!e) + return {}; + try + { + std::rethrow_exception(e); + } + catch (const std::exception & ex) + { + return ex.what(); + } + catch (...) + { + return {}; + } +} + +/// The query's verdict, then the background owners': both checks, in the order a scan head runs them. +std::exception_ptr checkOnce() +{ + try + { + throwIfQueryStopped(); + throwIfBackgroundStopped(); + } + catch (...) + { + return std::current_exception(); + } + return nullptr; +} + +/// A background owner that throws a fresh `ABORTED` once `stop` is set. +OwnerScope backgroundStoppedBy(const std::atomic & stop) +{ + return OwnerScope::background([&stop] + { + if (stop.load()) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); +} + +/// Wakes `cv` once, after its waiter released `mutex` to wait. Start it while the waiter holds the lock. +std::thread wakeOnceWaiting(std::mutex & mutex, std::condition_variable & cv) +{ + return std::thread([&mutex, &cv] + { + std::lock_guard lock(mutex); + cv.notify_all(); + }); +} + +} + +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_move_constructible_v); + +/// An exception that leaves the body of `onThread` fails the calling test instead of terminating the test process. +TEST(CASOwnerScope, OnThreadRethrowsTheBodysExceptionOnTheCallingThread) +{ + EXPECT_THROW(onThread(false, [] { throw Exception(ErrorCodes::ABORTED, "thrown on the raw thread"); }), Exception); +} + +TEST(CASOwnerScope, NoScopeNoQueryIsANoOp) +{ + for (bool with_thread_status : {false, true}) + { + onThread(with_thread_status, [&] + { + EXPECT_EQ(ownerStopRequested(), nullptr); + EXPECT_NO_THROW(throwIfQueryStopped()); + EXPECT_NO_THROW(throwIfBackgroundStopped()); + EXPECT_FALSE(insideOwed()); + EXPECT_FALSE(OwnerScope::effectiveCheck()); + }); + } +} + +TEST(CASOwnerScope, BackgroundStopIsThrown) +{ + onThread(false, [&] + { + std::atomic stop{false}; + { + auto scope = backgroundStoppedBy(stop); + EXPECT_EQ(checkOnce(), nullptr); + stop = true; + auto verdict = checkOnce(); + ASSERT_NE(verdict, nullptr); + EXPECT_EQ(codeOf(verdict), ErrorCodes::ABORTED); + EXPECT_EQ(codeOf(ownerStopRequested()), ErrorCodes::ABORTED); + } + EXPECT_EQ(checkOnce(), nullptr); + EXPECT_EQ(ownerStopRequested(), nullptr); + }); +} + +TEST(CASOwnerScope, OwedSuppressesTheThrowButNotTheVerdict) +{ + onThread(false, [&] + { + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + { + auto owed = OwnerScope::owed(); + EXPECT_TRUE(insideOwed()); + EXPECT_EQ(checkOnce(), nullptr); + EXPECT_EQ(codeOf(ownerStopRequested()), ErrorCodes::ABORTED); + } + EXPECT_FALSE(insideOwed()); + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::ABORTED); + }); +} + +TEST(CASOwnerScope, SharedHidesEveryOwner) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + query.kill(); + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::QUERY_WAS_CANCELLED); + { + auto shared = OwnerScope::shared(); + EXPECT_EQ(ownerStopRequested(), nullptr); + EXPECT_EQ(checkOnce(), nullptr); + EXPECT_FALSE(insideOwed()); + auto inner_background = backgroundStoppedBy(stop); + EXPECT_EQ(ownerStopRequested(), nullptr); + } + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::QUERY_WAS_CANCELLED); + }); +} + +TEST(CASOwnerScope, ScopesNestAndRestore) +{ + onThread(false, [&] + { + std::atomic outer_stop{false}; + std::atomic inner_stop{false}; + auto outer = OwnerScope::background([&] + { + if (outer_stop.load()) + throw Exception(ErrorCodes::ABORTED, "outer"); + }); + { + auto inner = OwnerScope::background([&] + { + if (inner_stop.load()) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "inner"); + }); + inner_stop = true; + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::BAD_ARGUMENTS); + outer_stop = true; + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::ABORTED) << "an enclosing owner is checked first"; + { + auto owed = OwnerScope::owed(); + auto background_in_owed = backgroundStoppedBy(inner_stop); + EXPECT_TRUE(insideOwed()) << "a nested scope never lifts an enclosing owed"; + EXPECT_EQ(checkOnce(), nullptr); + { + auto shared = OwnerScope::shared(); + EXPECT_EQ(ownerStopRequested(), nullptr); + } + EXPECT_TRUE(insideOwed()); + EXPECT_NE(ownerStopRequested(), nullptr); + } + EXPECT_FALSE(insideOwed()); + outer_stop = false; + EXPECT_EQ(codeOf(checkOnce()), ErrorCodes::BAD_ARGUMENTS); + } + EXPECT_EQ(checkOnce(), nullptr) << "the inner owner left with its scope"; + + /// A moved-from scope restores nothing; the moved-to one restores once. + std::optional first; + first.emplace(OwnerScope::owed()); + { + OwnerScope second(std::move(*first)); + EXPECT_TRUE(insideOwed()); + } + EXPECT_FALSE(insideOwed()); + { + auto owed = OwnerScope::owed(); + first.reset(); + EXPECT_TRUE(insideOwed()) << "destroying a moved-from scope must not restore"; + } + }); +} + +TEST(CASOwnerScope, EffectiveCheckIsEmptyInsideOwedAndShared) +{ + onThread(false, [&] + { + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + { + auto owed = OwnerScope::owed(); + EXPECT_FALSE(OwnerScope::effectiveCheck()); + } + { + auto shared = OwnerScope::shared(); + EXPECT_FALSE(OwnerScope::effectiveCheck()); + } + auto check = OwnerScope::effectiveCheck(); + ASSERT_TRUE(check); + EXPECT_THROW(check(), Exception); + }); +} + +/// The captured check carries the background owner to another thread and leaves the query behind: a shared +/// flush run for a killed leader proceeds as the leader's own requests would on plain S3. +TEST(CASOwnerScope, EffectiveCheckCapturesOnlyTheBackgroundOwner) +{ + onThread(true, [&] + { + std::atomic stop{false}; + auto background = backgroundStoppedBy(stop); + auto check = OwnerScope::effectiveCheck(); + ASSERT_TRUE(check); + + std::exception_ptr seen; + std::thread other([&] + { + stop = true; + try + { + check(); + } + catch (...) + { + seen = std::current_exception(); + } + }); + other.join(); + EXPECT_EQ(codeOf(seen), ErrorCodes::ABORTED); + }); + + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + query.kill(); + EXPECT_FALSE(OwnerScope::effectiveCheck()) << "a killed query is not a background owner"; + }); +} + +/// Each check consults its own owner only; `owed` and `shared` silence both. +TEST(CASOwnerScope, BackgroundAndQueryChecksAreSeparate) +{ + const auto thrownBy = [](void (*check)()) -> int + { + try + { + check(); + } + catch (...) + { + return codeOf(std::current_exception()); + } + return 0; + }; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + std::atomic stop{true}; + { + auto background = backgroundStoppedBy(stop); + EXPECT_EQ(thrownBy(throwIfBackgroundStopped), ErrorCodes::ABORTED); + EXPECT_EQ(thrownBy(throwIfQueryStopped), 0) << "a live query is not stopped by a background owner"; + } + query.kill(); + EXPECT_EQ(thrownBy(throwIfQueryStopped), ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(thrownBy(throwIfBackgroundStopped), 0) << "a killed query is not a background owner"; + auto background = backgroundStoppedBy(stop); + { + auto owed = OwnerScope::owed(); + EXPECT_EQ(thrownBy(throwIfBackgroundStopped), 0); + EXPECT_EQ(thrownBy(throwIfQueryStopped), 0); + } + { + auto shared = OwnerScope::shared(); + EXPECT_EQ(thrownBy(throwIfBackgroundStopped), 0); + EXPECT_EQ(thrownBy(throwIfQueryStopped), 0); + } + }); +} + +/// A killed query's wait ends when the condition holds, as a wait on plain S3 would; only a background owner +/// ends it early. +TEST(CASOwnerScope, WaitStoppableIgnoresAKilledQuery) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + query.kill(); + std::mutex mutex; + std::condition_variable cv; + std::unique_lock lock(mutex); + int evaluations = 0; + std::thread waker = wakeOnceWaiting(mutex, cv); + EXPECT_NO_THROW(waitStoppable(cv, lock, [&] { return ++evaluations >= 2; })); + EXPECT_EQ(evaluations, 2); + EXPECT_TRUE(lock.owns_lock()); + lock.unlock(); + waker.join(); + }); +} + +TEST(CASOwnerScope, RealQueryKillIsThrown) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + EXPECT_EQ(checkOnce(), nullptr); + query.kill(); + auto verdict = checkOnce(); + EXPECT_EQ(codeOf(verdict), ErrorCodes::QUERY_WAS_CANCELLED); + + std::exception_ptr worker_verdict; + std::thread worker([&] + { + ThreadStatus worker_status; + query.attachCurrentThread(); + worker_verdict = checkOnce(); + }); + worker.join(); + EXPECT_EQ(codeOf(worker_verdict), ErrorCodes::QUERY_WAS_CANCELLED) << "an attached worker sees the kill"; + }); +} + +TEST(CASOwnerScope, RealQueryStoredCauseIsThrown) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto cause = std::make_exception_ptr(Exception(ErrorCodes::BAD_ARGUMENTS, "stored cause")); + query.kill(cause); + auto verdict = checkOnce(); + EXPECT_EQ(codeOf(verdict), ErrorCodes::BAD_ARGUMENTS); + EXPECT_EQ(verdict, cause) << "the query's own exception, not a copy"; + }); +} + +TEST(CASOwnerScope, WaitStoppableChecksBeforeReturningWhenAlreadyReady) +{ + onThread(false, [&] + { + std::mutex mutex; + std::condition_variable cv; + std::atomic stop{false}; + auto background = backgroundStoppedBy(stop); + + std::unique_lock lock(mutex); + EXPECT_NO_THROW(waitStoppable(cv, lock, [] { return true; })); + EXPECT_TRUE(lock.owns_lock()); + + stop = true; + try + { + waitStoppable(cv, lock, [] { return true; }); + ADD_FAILURE() << "a stopped owner must be reported even when the wait is already satisfied"; + } + catch (...) + { + EXPECT_EQ(codeOf(std::current_exception()), ErrorCodes::ABORTED); + } + EXPECT_TRUE(lock.owns_lock()); + }); +} + +TEST(CASOwnerScope, WaitStoppableHoldsTheLockOnThrow) +{ + std::mutex mutex; + std::condition_variable cv; + std::atomic stop{false}; + std::promise waiting; + std::promise done; + std::atomic held_on_throw{false}; + std::atomic asked_owner_while_locked{false}; + std::atomic give_up{false}; + std::atomic code{0}; + + std::thread waiter([&] + { + std::unique_lock lock(mutex); + auto background = OwnerScope::background([&] + { + if (lock.owns_lock()) + asked_owner_while_locked = true; + if (stop.load()) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); + bool announced = false; + try + { + /// Nobody ever notifies: only the slice timeout can bring the stop to the waiter. + waitStoppable(cv, lock, [&] + { + if (!announced) + { + announced = true; + waiting.set_value(); + } + return give_up.load(); + }); + } + catch (...) + { + held_on_throw = lock.owns_lock(); + code = codeOf(std::current_exception()); + } + done.set_value(); + }); + + const bool started = waiting.get_future().wait_for(WATCHDOG) == std::future_status::ready; + stop = true; + const bool returned = done.get_future().wait_for(WATCHDOG) == std::future_status::ready; + if (!returned) + { + /// Release a waiter that ignores the stop, so the test fails instead of hanging. + { + std::lock_guard lock(mutex); + give_up = true; + } + cv.notify_all(); + } + waiter.join(); + ASSERT_TRUE(started) << "the waiter never evaluated its condition"; + ASSERT_TRUE(returned) << "a stopped waiter did not leave within the watchdog"; + EXPECT_EQ(code.load(), ErrorCodes::ABORTED); + EXPECT_TRUE(held_on_throw.load()); + EXPECT_FALSE(asked_owner_while_locked.load()) << "the owner is asked with the lock released"; +} + +TEST(CASOwnerScope, WaitStoppableSatisfyingWakeRaceStillChecks) +{ + std::mutex mutex; + std::condition_variable cv; + bool ready = false; + std::atomic stop{false}; + std::promise waiting; + std::promise done; + std::atomic code{0}; + + std::thread waiter([&] + { + auto background = backgroundStoppedBy(stop); + std::unique_lock lock(mutex); + bool announced = false; + try + { + waitStoppable(cv, lock, [&] + { + if (!announced) + { + announced = true; + waiting.set_value(); + } + return ready; + }); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + done.set_value(); + }); + + const bool started = waiting.get_future().wait_for(WATCHDOG) == std::future_status::ready; + { + /// The waiter holds the mutex from its first `ready` until it waits, so this wake meets a waiter. + std::lock_guard lock(mutex); + ready = true; + stop = true; + } + cv.notify_all(); + const bool returned = done.get_future().wait_for(WATCHDOG) == std::future_status::ready; + waiter.join(); + ASSERT_TRUE(started) << "the waiter never evaluated its condition"; + ASSERT_TRUE(returned) << "a woken waiter did not leave within the watchdog"; + EXPECT_EQ(code.load(), ErrorCodes::ABORTED) << "the wake that satisfied the wait must not hide the stop"; +} + +TEST(CASOwnerScope, WaitStoppableInsideOwedDoesNotThrow) +{ + onThread(false, [&] + { + std::mutex mutex; + std::condition_variable cv; + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + auto owed = OwnerScope::owed(); + std::unique_lock lock(mutex); + int evaluations = 0; + std::thread waker = wakeOnceWaiting(mutex, cv); + EXPECT_NO_THROW(waitStoppable(cv, lock, [&] { return ++evaluations >= 2; })) << "owed work finishes its wait"; + EXPECT_EQ(evaluations, 2); + EXPECT_TRUE(lock.owns_lock()); + lock.unlock(); + waker.join(); + }); +} + +/// With no background owner to ask, nothing but a notification can end the wait, so it does not wake on a timer. +TEST(CASOwnerScope, WaitStoppableWithNoOwnerToAskWaitsForANotification) +{ + enum class Scope : uint8_t { None, OwedOverBackground, SharedOverBackground }; + for (const Scope scope : {Scope::None, Scope::OwedOverBackground, Scope::SharedOverBackground}) + { + SCOPED_TRACE(static_cast(scope)); + onThread(false, [&] + { + std::atomic stop{false}; + std::optional background; + std::optional inner; + if (scope != Scope::None) + { + background.emplace(backgroundStoppedBy(stop)); + inner.emplace(scope == Scope::OwedOverBackground ? OwnerScope::owed() : OwnerScope::shared()); + } + std::mutex mutex; + std::condition_variable cv; + bool ready = false; + int evaluations = 0; + std::unique_lock lock(mutex); + /// Three owner-stop slices: a waiter that polls evaluates `ready` at least once per slice. + std::thread notifier([&] + { + std::this_thread::sleep_for(3 * kOwnerStopSlice); + { + std::lock_guard notifier_lock(mutex); + ready = true; + } + cv.notify_all(); + }); + waitStoppable(cv, lock, [&] + { + ++evaluations; + return ready; + }); + EXPECT_TRUE(ready) << "the wait returned before the notification"; + lock.unlock(); + notifier.join(); + EXPECT_LE(evaluations, 2) << "the wait woke on a timer"; + inner.reset(); + }); + } +} + +TEST(CASOwnerScope, ClientLikeBackendThrowsTheKillOnlyOnAnUnsuccessfulAnswer) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(std::make_shared()); + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("present", "v", Retry::once()))); + EXPECT_FALSE(op.read("absent", Retry::once()).has_value()); + + query.kill(); + EXPECT_TRUE(op.read("present", Retry::once()).has_value()) << "a successful answer is not checked"; + try + { + op.read("absent", Retry::once()); + ADD_FAILURE() << "a miss of a killed query must surface the kill"; + } + catch (...) + { + EXPECT_EQ(codeOf(std::current_exception()), ErrorCodes::QUERY_WAS_CANCELLED); + } + }); +} + +TEST(CASOwnerScope, OwedInsideSharedStaysShared) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + query.kill(); + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + auto shared = OwnerScope::shared(); + auto owed = OwnerScope::owed(); + EXPECT_TRUE(insideOwed()); + EXPECT_EQ(ownerStopRequested(), nullptr) << "owed work inside shared work still has no owner"; + EXPECT_FALSE(OwnerScope::effectiveCheck()); + }); +} + +TEST(CASOwnerScope, ScopesStayOnTheirThread) +{ + std::promise scope_open; + std::promise peer_checked; + std::thread holder([&] + { + std::atomic stop{true}; + auto background = backgroundStoppedBy(stop); + auto owed = OwnerScope::owed(); + scope_open.set_value(); + peer_checked.get_future().wait_for(WATCHDOG); + }); + + const bool opened = scope_open.get_future().wait_for(WATCHDOG) == std::future_status::ready; + onThread(false, [&] + { + EXPECT_EQ(ownerStopRequested(), nullptr) << "another thread's background owner is not this thread's"; + EXPECT_FALSE(insideOwed()) << "another thread's owed scope is not this thread's"; + EXPECT_EQ(checkOnce(), nullptr); + }); + peer_checked.set_value(); + holder.join(); + ASSERT_TRUE(opened) << "the holder never opened its scope"; +} + +namespace +{ + +/// The first write of `key` stores its bytes and loses the response; the first read of `key` fails. +class LostWriteThenLostReadBackend final : public InMemoryBackend +{ +public: + explicit LostWriteThenLostReadBackend(String key_) : key(std::move(key_)) {} + + std::atomic writes{0}; + std::atomic reads{0}; + + std::expected write(const String & k, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + if (k == key && writes.fetch_add(1) == 0) + { + (void)InMemoryBackend::write(k, bytes, expected_value, access); + throw Poco::TimeoutException("LostWriteThenLostReadBackend: stored, response lost"); + } + return InMemoryBackend::write(k, bytes, expected_value, access); + } + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key && reads.fetch_add(1) == 0) + throw Poco::TimeoutException("LostWriteThenLostReadBackend: read response lost"); + return InMemoryBackend::read(k, access); + } + +private: + const String key; +}; + +} + +/// The settling read of a possibly-sent write is owed to that write: when its first attempt fails while +/// the owner is live and the owner stops during the backoff, the read is still reissued and proves the +/// write landed. +TEST(CASOwnerStop, OwedSettlingReadReissuesAfterAFailure) +{ + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared("settled"); + std::atomic pauses{0}; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + if (backend->reads.load() > 0 && pauses.fetch_add(1) == 0) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + + std::optional written; + EXPECT_NO_THROW(written = op.create("settled", "bytes", Retry::standard())); + + ASSERT_TRUE(written.has_value()); + EXPECT_TRUE(std::holds_alternative(*written)) << "the reissued settling read proves the write landed"; + EXPECT_EQ(backend->writes.load(), 1) << "a landed write is not resent"; + EXPECT_EQ(backend->reads.load(), 2) << "the failed settling read was reissued"; + EXPECT_EQ(pauses.load(), 1); + EXPECT_NE(codeOf(ownerStopRequested()), 0) << "the owner stopped before the reissue"; + }); +} + +namespace +{ + +/// Fails the first read or head of `key` with `failure`, and counts the requests to `key` and the +/// credential refreshes. Wrapped in `CasClientLikeBackend`, a stopped query's verdict replaces the +/// failure, as the S3 client does. +class FailFirstRequestBackend final : public InMemoryBackend +{ +public: + explicit FailFirstRequestBackend(String key_) : key(std::move(key_)) {} + + std::exception_ptr failure = std::make_exception_ptr(Exception(ErrorCodes::TIMEOUT_EXCEEDED, "the read timed out")); + std::atomic fail_next{true}; + std::atomic requests{0}; + std::atomic refreshes{0}; + + std::optional read(const String & k, TransportAccess & access) override + { + countAndMaybeFail(k); + return InMemoryBackend::read(k, access); + } + + std::optional head(const String & k, TransportAccess & access) override + { + countAndMaybeFail(k); + return InMemoryBackend::head(k, access); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } + +private: + void countAndMaybeFail(const String & k) + { + if (k != key) + return; + ++requests; + if (fail_next.exchange(false)) + std::rethrow_exception(failure); + } + + const String key; +}; + +enum class ReadSurface { Read, ReadModifyWrite, ReadModifyWriteOnPresence }; + +struct FailedFirstRequest +{ + ReadSurface surface = ReadSurface::Read; + /// What the first request to the key throws when no verdict replaces it. + std::exception_ptr failure; + /// Stops the query before the call; empty leaves the owner live. + std::function stop; + /// Runs the call under a stopped background owner instead. + bool stopped_background = false; + /// Runs during the pause before a reissue. + std::function during_pause; +}; + +struct FailedFirstRequestOutcome +{ + int code = 0; + String message; + bool has_value = false; + bool gave_up = false; + int requests = 0; + int refreshes = 0; + int pauses = 0; +}; + +/// One call whose first request to an existing key fails. The single-attempt surfaces would turn a +/// failed observation into `GaveUp` with `NotObserved`. +FailedFirstRequestOutcome runFailedFirstRequest(const FailedFirstRequest & arm) +{ + FailedFirstRequestOutcome out; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared("k"); + if (arm.failure) + inner->failure = arm.failure; + auto backend = std::make_shared(inner); + std::atomic pauses{0}; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + ++pauses; + if (arm.during_pause) + arm.during_pause(query); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("k", "v", Retry::once()))); + inner->requests = 0; + + std::optional background; + if (arm.stopped_background) + background.emplace(OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); })); + if (arm.stop) + arm.stop(query); + try + { + switch (arm.surface) + { + case ReadSurface::Read: + out.has_value = op.read("k", Retry::standard()).has_value(); + break; + case ReadSurface::ReadModifyWrite: + out.gave_up = std::holds_alternative( + op.readModifyWrite("k", [](const std::optional &) { return std::optional{}; }, Retry::once())); + break; + case ReadSurface::ReadModifyWriteOnPresence: + out.gave_up = std::holds_alternative( + op.readModifyWriteOnPresence("k", [](const std::optional &) { return std::optional{}; }, Retry::once())); + break; + } + } + catch (...) + { + out.code = codeOf(std::current_exception()); + out.message = getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + out.requests = inner->requests.load(); + out.refreshes = inner->refreshes.load(); + out.pauses = pauses.load(); + }); + return out; +} + +/// `LocalObjectStorage` whose next small-object read fails the way the S3 client fails a request of a +/// stopped query: it asks the query first, so the query's verdict replaces the failure. +class ClientLikeLocalObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + mutable std::atomic fail_next{false}; + mutable std::atomic reads{0}; + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, + const DB::ReadSettings & read_settings, + size_t max_size_bytes, + std::optional read_hint) const override + { + ++reads; + if (fail_next.exchange(false)) + { + CurrentThread::checkIfNotCancelled(); + throw Poco::TimeoutException("ClientLikeLocalObjectStorage: the read timed out"); + } + return DB::LocalObjectStorage::readSmallObjectAndGetObjectMetadata(object, read_settings, max_size_bytes, read_hint); + } +}; + +template +std::shared_ptr makeLocalObjectStorageOf() +{ + static std::atomic counter{0}; + const auto root = (std::filesystem::temp_directory_path() + / ("cas_owner_stop_unit_" + std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)))).string(); + std::filesystem::remove_all(root); + std::filesystem::create_directories(root); + DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); + return DB::Cas::tests::ownedByDirectory(std::make_shared(std::move(settings)), root); +} + +std::shared_ptr makeClientLikeLocalObjectStorage() +{ + return makeLocalObjectStorageOf(); +} + +/// `LocalObjectStorage` whose small-object reads and container checks first run a hook, which may throw. +class HookedReadLocalObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + std::function on_read; + std::function on_exists; + mutable std::atomic reads{0}; + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, + const DB::ReadSettings & read_settings, + size_t max_size_bytes, + std::optional read_hint) const override + { + ++reads; + if (on_read) + on_read(); + return DB::LocalObjectStorage::readSmallObjectAndGetObjectMetadata(object, read_settings, max_size_bytes, read_hint); + } + + bool existsOrHasAnyChild(const std::string & path) const override + { + if (on_exists) + on_exists(); + return DB::LocalObjectStorage::existsOrHasAnyChild(path); + } +}; + +#if USE_AWS_S3 +/// `LocalObjectStorage` that answers every small-object read with the store's own `NoSuchKey`. +class NoSuchKeyLocalObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + mutable std::atomic reads{0}; + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, const DB::ReadSettings &, size_t, std::optional) const override + { + ++reads; + throw DB::S3Exception("the store answered NoSuchKey for " + object.remote_path, Aws::S3::S3Errors::NO_SUCH_KEY, "NoSuchKey"); + } +}; +#endif + +std::exception_ptr storedCause(int code) +{ + return std::make_exception_ptr(Exception(code, "the query's stored cause")); +} + +} + +/// A stopped owner's exception after a failed first attempt is not a store answer: it is not reissued, +/// refreshed or paced, is never read as absence, and a single-attempt observation surfaces it rather +/// than reporting `NotObserved`. A live owner's same failure is reissued. +TEST(CASOwnerStop, StoppedOwnersFailedReadIsNotReissued) +{ + struct Stop + { + const char * name; + std::function stop; + int code; + }; + const std::vector stops = { + {"timeout", [](CasKillableQuery & q) { q.kill(storedCause(ErrorCodes::TIMEOUT_EXCEEDED)); }, ErrorCodes::TIMEOUT_EXCEEDED}, + {"kill", [](CasKillableQuery & q) { q.kill(); }, ErrorCodes::QUERY_WAS_CANCELLED}, + {"stored BAD_ARGUMENTS", [](CasKillableQuery & q) { q.kill(storedCause(ErrorCodes::BAD_ARGUMENTS)); }, ErrorCodes::BAD_ARGUMENTS}, + {"stored FILE_DOESNT_EXIST", [](CasKillableQuery & q) { q.kill(storedCause(ErrorCodes::FILE_DOESNT_EXIST)); }, + ErrorCodes::FILE_DOESNT_EXIST}, + }; + for (const auto & stop : stops) + { + for (const auto surface : {ReadSurface::Read, ReadSurface::ReadModifyWrite, ReadSurface::ReadModifyWriteOnPresence}) + { + SCOPED_TRACE(fmt::format("{}, surface {}", stop.name, static_cast(surface))); + FailedFirstRequest arm; + arm.surface = surface; + arm.stop = stop.stop; + const auto out = runFailedFirstRequest(arm); + EXPECT_EQ(out.code, stop.code) << "the owner's verdict surfaces"; + EXPECT_FALSE(out.has_value); + EXPECT_FALSE(out.gave_up) << "a stopped owner's failed observation is not NotObserved"; + EXPECT_EQ(out.requests, 1) << "no reissue"; + EXPECT_EQ(out.refreshes, 0); + EXPECT_EQ(out.pauses, 0); + } + } + +#if USE_AWS_S3 + { + SCOPED_TRACE("background owner, credential failure"); + FailedFirstRequest arm; + arm.failure = std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); + arm.stopped_background = true; + const auto out = runFailedFirstRequest(arm); + EXPECT_EQ(out.code, ErrorCodes::ABORTED); + EXPECT_EQ(out.refreshes, 0) << "a stopped owner's failure is not a credential answer"; + EXPECT_EQ(out.requests, 1); + } +#endif + + { + SCOPED_TRACE("live owner"); + const auto out = runFailedFirstRequest({}); + EXPECT_EQ(out.code, 0); + EXPECT_TRUE(out.has_value) << "a live owner's timeout is reissued"; + EXPECT_EQ(out.requests, 2); + EXPECT_EQ(out.pauses, 1); + } + + { + SCOPED_TRACE("stored FILE_DOESNT_EXIST through the native backend"); + auto storage = makeClientLikeLocalObjectStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "present"); + { + auto out = storage->writeObject(DB::StoredObject(key), DB::WriteMode::Rewrite); + DB::writeString(String("body"), *out); + out->finalize(); + } + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + int code = 0; + bool read_absent = false; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + query.kill(storedCause(ErrorCodes::FILE_DOESNT_EXIST)); + storage->reads = 0; + storage->fail_next = true; + try + { + read_absent = !op.read(key, Retry::standard()).has_value(); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_FALSE(read_absent) << "a stopped owner's stored FILE_DOESNT_EXIST is never absence"; + EXPECT_EQ(code, ErrorCodes::FILE_DOESNT_EXIST); + EXPECT_EQ(storage->reads.load(), 1); + } +} + +/// A stop during the pause before a reissue starts no further request, even one that would succeed. The read ends +/// with its own failure, which came before the kill, so the client-like backend did not replace it. +TEST(CASOwnerStop, StopDuringBackoffStartsNoReissue) +{ + FailedFirstRequest arm; + arm.during_pause = [](CasKillableQuery & q) { q.kill(); }; + const auto out = runFailedFirstRequest(arm); + EXPECT_EQ(out.code, ErrorCodes::TIMEOUT_EXCEEDED); + EXPECT_FALSE(out.has_value); + EXPECT_EQ(out.pauses, 1); + EXPECT_EQ(out.requests, 1) << "the reissue, configured to succeed, never starts"; +} + +namespace +{ + +/// The first write of `key` stores its bytes, runs `on_lost_response` and loses the response; the first +/// read of `key` runs `on_failed_read` and fails. +class LostResponseBackend final : public InMemoryBackend +{ +public: + explicit LostResponseBackend(String key_) : key(std::move(key_)) {} + + std::function on_lost_response; + std::function on_failed_read; + std::atomic writes{0}; + std::atomic reads{0}; + std::atomic refreshes{0}; + + std::expected write(const String & k, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + if (k == key && writes.fetch_add(1) == 0) + { + (void)InMemoryBackend::write(k, bytes, expected_value, access); + if (on_lost_response) + on_lost_response(); + throw Poco::TimeoutException("LostResponseBackend: stored, response lost"); + } + return InMemoryBackend::write(k, bytes, expected_value, access); + } + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key && reads.fetch_add(1) == 0) + { + if (on_failed_read) + on_failed_read(); + throw Poco::TimeoutException("LostResponseBackend: read response lost"); + } + return InMemoryBackend::read(k, access); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } + +private: + const String key; +}; + +Retry withoutResend() +{ + Retry policy = Retry::standard(); + policy.resend_unresolved = false; + return policy; +} + +} + +/// Inside `owed`, a stopped owner's failed settling read is neither refreshed nor reissued, and the +/// observation reports `NotObserved`: no local-bug rethrow for a stored `BAD_ARGUMENTS` either. +TEST(CASOwnerStop, OwedFailedReadBecomesNotObserved) +{ + const auto run_arm = [](int stored) + { + std::optional written; + int code = 0; + int reads = 0; + int refreshes = 0; + int pauses = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared("settled"); + /// After the write's failure, so only the settling read sees the stop. + inner->on_failed_read = [&] { query.kill(stored ? storedCause(stored) : nullptr); }; + auto backend = std::make_shared(inner); + std::atomic pause_count{0}; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) { ++pause_count; }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + written = op.create("settled", "bytes", withoutResend()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + reads = inner->reads.load(); + refreshes = inner->refreshes.load(); + pauses = pause_count.load(); + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + const auto * gave_up = std::get_if(&*written); + ASSERT_NE(gave_up, nullptr) << "the settling read proved nothing"; + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved) << "no bound refused the read"; + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_TRUE(std::holds_alternative(gave_up->last_seen)); + EXPECT_EQ(reads, 1) << "the failed settling read was not reissued"; + EXPECT_EQ(refreshes, 0); + EXPECT_EQ(pauses, 0); + }; + for (const int stored : {0, ErrorCodes::BAD_ARGUMENTS}) + { + SCOPED_TRACE(stored ? "stored BAD_ARGUMENTS" : "kill"); + run_arm(stored); + } +} + +/// A fence refusal recorded by the settling read survives the owed observation of a stopped owner: +/// the write reports the lost fence, not an unresolved outcome. +TEST(CASOwnerStop, FenceRefusalSurvivesOwedObservation) +{ + std::optional written; + int reads = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared("fenced"); + std::atomic fence_lost{false}; + backend->on_lost_response = [&] + { + fence_lost = true; + query.kill(); + }; + Fence fence = Fence::open(); + fence.admit = [&fence_lost](uint64_t, uint64_t) { return fence_lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }; + CasRequests requests(backend, fence, {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + written = op.create("fenced", "bytes", withoutResend()); + reads = backend->reads.load(); + }); + ASSERT_TRUE(written.has_value()); + const auto * gave_up = std::get_if(&*written); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(reads, 0) << "the fence refused the settling read before it was sent"; +} + +/// The first attempt of a read is sent for an owner that already stopped, and a healthy answer is returned. +TEST(CASOwnerStop, HealthyFirstReadIsNotRefused) +{ + for (const bool background : {false, true}) + { + SCOPED_TRACE(background ? "background owner" : "killed query"); + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(); + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("present", "v", Retry::once()))); + + std::optional scope; + if (background) + scope.emplace(OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); })); + else + query.kill(); + ASSERT_NE(ownerStopRequested(), nullptr); + + const auto present = op.read("present", Retry::standard()); + ASSERT_TRUE(present.has_value()); + EXPECT_EQ(present->bytes, "v"); + EXPECT_FALSE(op.read("absent", Retry::standard()).has_value()); + EXPECT_TRUE(op.head("present", Retry::standard()).has_value()); + EXPECT_FALSE(op.head("absent", Retry::standard()).has_value()); + }); + } + +#if USE_AWS_S3 + { + /// The S3 client never sees a background owner, so the store's own 404 reaches the backend. + SCOPED_TRACE("background owner, the store's NoSuchKey through the native backend"); + auto storage = makeLocalObjectStorageOf(); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + onThread(false, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + auto scope = OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); }); + ASSERT_NE(ownerStopRequested(), nullptr); + std::optional got; + EXPECT_NO_THROW(got = op.read(DB::Cas::tests::nativeKeyUnder(storage, "absent"), Retry::standard())); + EXPECT_FALSE(got.has_value()) << "a healthy 404 is absence"; + }); + EXPECT_EQ(storage->reads.load(), 1); + } +#endif +} + +/// A stopped owner's catalog update whose base read the fence refuses keeps the typed fence outcome. +TEST(CASOwnerStop, StoppedOwnersFencedCatalogReadIsFencedOut) +{ + onThread(false, [&] + { + auto backend = std::make_shared(); + const Layout layout("p"); + const CatalogEntry observed{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(1)}; + { + /// A plane of its own, so the update below reads the catalog rather than starting from a cached hint. + auto setup_requests = openRequestsForTest(backend); + auto setup = setup_requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + CasRefCatalog::casAdmitEntry(setup, layout, 1, observed); + } + auto requests = openRequestsForTest(backend); + /// Admitted at the hot-key lane's own check, refused from the base read on. + int admissions = 0; + auto op = requests.admit([&admissions] { return admissions++ == 0; }); + auto scope = OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); }); + + std::optional outcome; + EXPECT_NO_THROW(outcome = CasRefCatalog::beginRemoving(op, layout, observed, /*removal_started_round*/ 13)); + ASSERT_TRUE(outcome.has_value()); + EXPECT_EQ(*outcome, CasRefCatalog::BeginRemovingOutcome::FencedOut); + EXPECT_GE(admissions, 2) << "the base read reached its own admission"; + }); +} + +namespace +{ + +enum class DecisionLoop : uint8_t { BodyReadModifyWrite, PresenceReadModifyWrite, Catalog }; + +struct ConflictPauseArm +{ + DecisionLoop loop; + /// 50 writes that each take 500 ms on the manual clock and lose their precondition, the stop in the + /// third pause; otherwise every write loses and the stop comes in the first pause. + bool slow; +}; + +class CASOwnerStopLoop : public ::testing::TestWithParam +{ +}; + +enum class PauseOwner : uint8_t { Background, Query }; + +struct ConflictPauseRun +{ + std::exception_ptr error; + /// The read-modify-write loops' answer; the catalog loop returns none. + std::optional result; + int decisions = 0; + int decisions_at_stop = -1; + uint64_t writes = 0; + uint64_t writes_at_stop = 0; +}; + +/// Runs `arm`'s loop against lost races and stops `who` in the first pause, or in the third on the slow schedule. A +/// background owner sees every write lose; a query sees only the writes before its kill lose, since an unsuccessful +/// answer after it would carry the kill. +ConflictPauseRun runConflictPause(const ConflictPauseArm & arm, PauseOwner who) +{ + const int stop_at_pause = arm.slow ? 3 : 1; + ConflictPauseRun run; + onThread(who == PauseOwner::Query, [&] + { + std::optional query; + if (who == PauseOwner::Query) + query.emplace(getContext().context); + auto backend = std::make_shared(); + auto clock = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + const Layout layout("p"); + const String key = arm.loop == DecisionLoop::Catalog ? layout.refCatalogKey() : String("k"); + std::atomic stop{false}; + int pauses = 0; + const auto sleep_on_clock = ManualClock::sleepFnOf(clock); + const BackendPtr engine_backend = who == PauseOwner::Query + ? BackendPtr(std::make_shared(backend)) : BackendPtr(backend); + CasRequests requests(engine_backend, Fence::open(), ManualClock::nowFnOf(clock), [&](uint64_t ms) + { + sleep_on_clock(ms); + if (++pauses == stop_at_pause) + { + stop = true; + if (query) + query->kill(); + run.decisions_at_stop = run.decisions; + run.writes_at_stop = backend->writeCount(key); + } + }, &hot_keys, kDefaultRequestWindowMs); + auto op = requests.admit(); + if (arm.loop == DecisionLoop::Catalog) + { + CasRefCatalog::initializeEmptyForNewPool(op, layout); + CasRefCatalog::casAdmitEntry(op, layout, 1, + CatalogEntry{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(1)}); + } + else + { + ASSERT_TRUE(std::holds_alternative(op.create(key, "v0", Retry::once()))); + } + ASSERT_EQ(pauses, 0); + + int conflicts_left = arm.slow ? 50 : 1000; + backend->onBeforeWrite(key, [&] + { + const bool lose = who == PauseOwner::Query ? !stop.load() : conflicts_left-- > 0; + if (lose) + backend->refuseNextWrite(key); + }); + if (arm.slow) + backend->armWith(TimeTakingBackend::Verb::Write, [key](const String & k) { return k == key; }, + [clock] { clock->advance(500); }, 50); + + std::optional owner; + if (who == PauseOwner::Background) + owner.emplace(backgroundStoppedBy(stop)); + try + { + switch (arm.loop) + { + case DecisionLoop::BodyReadModifyWrite: + run.result = op.readModifyWrite(key, [&](const std::optional & current) + { + ++run.decisions; + return std::optional(current ? current->bytes + "+" : String("v")); + }, Retry::standard()); + break; + case DecisionLoop::PresenceReadModifyWrite: + run.result = op.readModifyWriteOnPresence(key, [&](const std::optional &) + { + ++run.decisions; + return std::optional("v" + std::to_string(run.decisions)); + }, Retry::standard()); + break; + case DecisionLoop::Catalog: + (void)CasRefCatalog::casUpdate(op, layout, [&](const RefCatalog & current) + { + ++run.decisions; + return current; + }); + break; + } + } + catch (...) + { + run.error = std::current_exception(); + } + run.writes = backend->writeCount(key); + }); + return run; +} + +/// Decisions before the stopping pause: one per lost race, plus the first lost race, which is retried at once +/// without a pause, plus, for the catalog, the first decision on the lane's cached catalog, whose loss is retried at +/// once on its resolve read. +int decisionsBeforeStop(const ConflictPauseArm & arm) +{ + return (arm.slow ? 3 : 1) + 1 + (arm.loop == DecisionLoop::Catalog ? 1 : 0); +} + +} + +/// A stop during the pause after a lost race ends the loop: no decision and no write after it. +TEST_P(CASOwnerStopLoop, StopDuringConflictPauseSkipsNextDecision) +{ + const ConflictPauseArm arm = GetParam(); + const ConflictPauseRun run = runConflictPause(arm, PauseOwner::Background); + EXPECT_EQ(codeOf(run.error), ErrorCodes::ABORTED); + EXPECT_EQ(run.decisions_at_stop, decisionsBeforeStop(arm)) << "one pause after each lost race"; + EXPECT_EQ(run.decisions, run.decisions_at_stop) << "no decision after the stop"; + EXPECT_EQ(run.writes, run.writes_at_stop) << "no write after the stop"; +} + +/// A killed query is not stopped by an accepted conflict: the pause after a lost race is not a safe point, so the +/// next decision runs and its write, sent on a healthy store, commits. +TEST_P(CASOwnerStopLoop, KilledQueryDecidesAgainAfterConflictPause) +{ + const ConflictPauseArm arm = GetParam(); + const ConflictPauseRun run = runConflictPause(arm, PauseOwner::Query); + EXPECT_EQ(codeOf(run.error), 0) << messageOf(run.error); + if (run.result) + EXPECT_TRUE(std::holds_alternative(*run.result)); + EXPECT_EQ(run.decisions_at_stop, decisionsBeforeStop(arm)) << "one pause after each lost race"; + EXPECT_EQ(run.decisions, run.decisions_at_stop + 1) << "one decision after the kill"; + EXPECT_EQ(run.writes, run.writes_at_stop + 1) << "one write after the kill"; +} + +INSTANTIATE_TEST_SUITE_P(CASOwnerStopLoops, CASOwnerStopLoop, + ::testing::Values( + ConflictPauseArm{DecisionLoop::BodyReadModifyWrite, false}, + ConflictPauseArm{DecisionLoop::PresenceReadModifyWrite, false}, + ConflictPauseArm{DecisionLoop::Catalog, false}, + ConflictPauseArm{DecisionLoop::BodyReadModifyWrite, true}, + ConflictPauseArm{DecisionLoop::PresenceReadModifyWrite, true}, + ConflictPauseArm{DecisionLoop::Catalog, true}), + [](const ::testing::TestParamInfo & param_info) + { + const char * loop = param_info.param.loop == DecisionLoop::BodyReadModifyWrite ? "Body" + : param_info.param.loop == DecisionLoop::PresenceReadModifyWrite ? "Presence" : "Catalog"; + return std::string(loop) + (param_info.param.slow ? "Slow" : "Fast"); + }); + +namespace +{ + +/// Counts the reads of `key` after `arm` saw a new write of it, and runs `on_read_after_write` with that count. +class ReadAfterWriteHookBackend final : public CountingBackend +{ +public: + explicit ReadAfterWriteHookBackend(String key_) : key(std::move(key_)) {} + + std::function on_read_after_write; + std::atomic reads_after_write{0}; + + void arm() { writes_at_arm = writeCount(key); } + uint64_t writesSinceArm() const { return writeCount(key) - writes_at_arm.value_or(0); } + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key && writes_at_arm && writeCount(key) > *writes_at_arm) + { + const int n = ++reads_after_write; + if (on_read_after_write) + on_read_after_write(n); + } + return CountingBackend::read(k, access); + } + +private: + const String key; + std::optional writes_at_arm; +}; + +enum class UnresolvedStop : uint8_t +{ + /// During the owed settling read of the lost step-1 write. + BeforePause, + /// During the redecide pause. + InsidePause, + /// After the pause, past the first owner check that follows it. + AfterPause, + /// While the next submission waits behind a predecessor parked in its decision. + InQueue, + /// A killed query whose next base read fails: the client-like backend raises the kill, recorded by no owner check. + UnrecordedClientVerdict, + /// The fence is lost and the owner stops during the redecide pause. + FenceLostInsidePause, + /// Another server admits the namespace during the redecide pause; the owner stops between the check + /// before `decide` and the marker that `decide` then throws. + DecisionMarkerWhileStopping, + /// The second decision's write is refused with 412, and the query is killed in the first read after that refusal: + /// the next submission's base read, as a retried refusal is not settled. + KillSettlingSecondWrite, + /// As `KillSettlingSecondWrite`, but every write after the lost one is refused and the kill comes in the base read + /// of the last submission the cap allows. + KillReadingForLastAllowedWrite, + /// As `KillReadingForLastAllowedWrite`, but the kill comes in the read that settles the last allowed write: no + /// submission follows that write, so its refusal is settled. + KillSettlingLastAllowedWrite, + /// The second decision's write is refused as `READONLY` by the store while the owner stops, so the engine returns + /// that refusal. + RefusedSecondWriteWhileStopping, + /// The second decision's write fails locally with `CORRUPTED_DATA`; the owner stays live. + LocalFaultInSecondWrite, +}; + +struct UnresolvedCreateOutcome +{ + std::optional outcome; + int code = 0; + String message; + uint64_t catalog_writes = 0; + int reads_after_write = 0; + bool returned_while_parked = false; + std::optional predecessor; + size_t lanes_after = 0; + int sleeps = 0; +}; + +/// `createNamespace` whose step-1 write loses its reply without landing; the settling read finds the +/// catalog unchanged, which proves nothing under `resend_unresolved = false`, so step 1 decides again +/// after the redecide pause. `stop_at` empty keeps the owner live. +UnresolvedCreateOutcome runUnresolvedCreate(std::optional stop_at) +{ + UnresolvedCreateOutcome out; + onThread(true, [&] + { + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto inner = std::make_shared(key); + { + auto setup_requests = openRequestsForTest(inner); + auto setup = setup_requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + } + std::optional query; + if (stop_at == UnresolvedStop::UnrecordedClientVerdict || stop_at == UnresolvedStop::KillSettlingSecondWrite + || stop_at == UnresolvedStop::KillReadingForLastAllowedWrite || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) + query.emplace(getContext().context); + BackendPtr backend = query ? BackendPtr(std::make_shared(inner)) : BackendPtr(inner); + + auto clock = std::make_shared(); + CasHotKeys hot_keys(16ULL << 20); + std::atomic stop{false}; + std::atomic fence_lost{false}; + std::atomic caller_returned{false}; + std::atomic returned_while_parked{false}; + bool slept = false; + int checks_after_sleep = 0; + int sleeps = 0; + std::latch parked{1}; + std::latch release{1}; + std::optional predecessor; + std::optional watcher; + CasRequests * requests_ptr = nullptr; + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + std::atomic competitor_admitted{false}; + std::atomic base_read_after_competitor{false}; + int checks_after_base_read = 0; + + Fence fence = Fence::open(); + fence.admit = [&fence_lost](uint64_t, uint64_t) { return fence_lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }; + CasRequests requests(backend, fence, ManualClock::nowFnOf(clock), [&](uint64_t ms) + { + clock->advance(ms + 1); + if (++sleeps != 1) + return; + slept = true; + if (stop_at == UnresolvedStop::InsidePause) + stop = true; + if (stop_at == UnresolvedStop::DecisionMarkerWhileStopping) + { + CasRefCatalog::casAdmitEntry(competitor, layout, 1, + CatalogEntry{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(7)}); + competitor_admitted = true; + } + if (stop_at == UnresolvedStop::FenceLostInsidePause) + { + fence_lost = true; + stop = true; + } + if (stop_at == UnresolvedStop::InQueue) + { + predecessor.emplace([&] + { + auto predecessor_op = requests_ptr->admit(); + out.predecessor = hot_keys.submit(key, predecessor_op, Retry::standard(), + [&](const std::optional &) -> std::optional + { + parked.count_down(); + release.wait(); + return std::nullopt; + }); + }); + parked.wait(); + watcher.emplace([&] + { + const auto deadline = std::chrono::steady_clock::now() + WATCHDOG; + while (hot_keys.queueDepthForTest(key) < 2 && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + stop = true; + while (!caller_returned && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + returned_while_parked = caller_returned.load(); + release.count_down(); + }); + } + }, &hot_keys, kDefaultRequestWindowMs); + requests_ptr = &requests; + + std::optional owner; + if (!query) + owner.emplace(OwnerScope::background([&] + { + if (stop_at == UnresolvedStop::AfterPause && slept && ++checks_after_sleep >= 2) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + /// The first check after the caller's base read is the one before `decide`, which passes. + if (base_read_after_competitor && ++checks_after_base_read >= 2) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + if (stop) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + })); + inner->on_read_after_write = [&](int n) + { + if (competitor_admitted) + base_read_after_competitor = true; + if (stop_at == UnresolvedStop::BeforePause && n == 1) + stop = true; + if (stop_at == UnresolvedStop::UnrecordedClientVerdict && n == 2) + { + query->kill(); + throw Poco::TimeoutException("ReadAfterWriteHookBackend: the read timed out"); + } + if (stop_at == UnresolvedStop::KillSettlingSecondWrite && inner->writesSinceArm() == 2) + { + query->kill(); + throw Poco::TimeoutException("ReadAfterWriteHookBackend: the settling read timed out"); + } + if (stop_at == UnresolvedStop::KillReadingForLastAllowedWrite || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) + { + const uint64_t kill_after_write + = stop_at == UnresolvedStop::KillSettlingLastAllowedWrite ? kCasMaxDecisions : kCasMaxDecisions - 1; + if (inner->writesSinceArm() == kill_after_write) + { + query->kill(); + throw Poco::TimeoutException("ReadAfterWriteHookBackend: the settling read timed out"); + } + if (inner->writesSinceArm() >= 2) + inner->refuseNextWrite(key); + } + }; + + auto op = requests.admit(); + inner->arm(); + inner->injectAmbiguousWrite(key); + if (stop_at == UnresolvedStop::KillSettlingSecondWrite || stop_at == UnresolvedStop::KillReadingForLastAllowedWrite + || stop_at == UnresolvedStop::KillSettlingLastAllowedWrite) + inner->refuseNextWrite(key); + if (stop_at == UnresolvedStop::RefusedSecondWriteWhileStopping) + inner->onBeforeWrite(key, [&] + { + if (inner->writesSinceArm() != 2) + return; + stop = true; + throw Exception(ErrorCodes::READONLY, "ReadAfterWriteHookBackend: the store is read-only"); + }); + if (stop_at == UnresolvedStop::LocalFaultInSecondWrite) + inner->onBeforeWrite(key, [&] + { + if (inner->writesSinceArm() == 2) + throw Exception(ErrorCodes::CORRUPTED_DATA, "ReadAfterWriteHookBackend: a local decode failure"); + }); + try + { + out.outcome = CasRefCatalog::createNamespace(op, layout, 1, RootNamespace{"a"}, + CreatorFence{.server_root_id = "srv1", .writer_epoch = 5, .fence_generation = 1}); + } + catch (...) + { + out.code = codeOf(std::current_exception()); + out.message = messageOf(std::current_exception()); + } + caller_returned = true; + if (watcher) + watcher->join(); + if (predecessor) + predecessor->join(); + out.returned_while_parked = returned_while_parked; + out.catalog_writes = inner->writesSinceArm(); + out.reads_after_write = inner->reads_after_write.load(); + out.lanes_after = hot_keys.laneCountForTest(); + out.sleeps = sleeps; + owner.reset(); + }); + return out; +} + +} + +/// A stop after a sent step-1 write whose outcome stays unresolved keeps the unresolved exit: one write, +/// no second decision, the 210 that names the unresolved send. A live owner decides again and creates the row. +TEST(CASOwnerStop, StoppedNamespaceCreateKeepsUnresolvedExit) +{ + for (const UnresolvedStop stop_at : {UnresolvedStop::BeforePause, UnresolvedStop::InsidePause, UnresolvedStop::AfterPause, + UnresolvedStop::InQueue, UnresolvedStop::UnrecordedClientVerdict}) + { + SCOPED_TRACE(static_cast(stop_at)); + const auto out = runUnresolvedCreate(stop_at); + EXPECT_FALSE(out.outcome.has_value()); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR); + EXPECT_NE(out.message.find("a sent write's outcome is unresolved"), String::npos) << out.message; + EXPECT_EQ(out.catalog_writes, 1u) << "one PUT"; + /// The settling read, plus the predecessor's base read or the failed base read where the arm has one: + /// no base read for a second decision of the caller's. + const int expected_reads = stop_at == UnresolvedStop::InQueue || stop_at == UnresolvedStop::UnrecordedClientVerdict ? 2 : 1; + EXPECT_EQ(out.reads_after_write, expected_reads); + EXPECT_EQ(out.lanes_after, 0u); + if (stop_at == UnresolvedStop::BeforePause) + EXPECT_EQ(out.sleeps, 0) << "the check before the redecide sleep ends the call"; + if (stop_at == UnresolvedStop::InQueue) + { + EXPECT_TRUE(out.returned_while_parked) << "the caller left while the predecessor was still parked"; + ASSERT_TRUE(out.predecessor.has_value()); + EXPECT_TRUE(std::holds_alternative(*out.predecessor)); + } + } + + { + SCOPED_TRACE("a lost fence observed in the pause stays the typed fence outcome"); + const auto out = runUnresolvedCreate(UnresolvedStop::FenceLostInsidePause); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.outcome.has_value()); + EXPECT_EQ(*out.outcome, CasRefCatalog::NamespaceCreationOutcome::FencedOut); + EXPECT_EQ(out.catalog_writes, 1u); + } + + { + SCOPED_TRACE("a marker the decision throws stays as it is"); + const auto out = runUnresolvedCreate(UnresolvedStop::DecisionMarkerWhileStopping); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.outcome.has_value()); + EXPECT_EQ(*out.outcome, CasRefCatalog::NamespaceCreationOutcome::Superseded); + EXPECT_EQ(out.catalog_writes, 2u) << "the lost step-1 write and the other server's admission"; + } + + { + SCOPED_TRACE("live owner"); + const auto out = runUnresolvedCreate(std::nullopt); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.outcome.has_value()); + EXPECT_EQ(*out.outcome, CasRefCatalog::NamespaceCreationOutcome::Live); + EXPECT_EQ(out.catalog_writes, 3u) << "the lost step-1 write, its second decision, step 3"; + } +} + +/// A refused write followed by a read that fails after a kill does not answer the first write, whose outcome is still +/// unknown: the call keeps the unresolved exit and sends nothing more, also in the last submission the cap allows, +/// whether the kill comes in that submission's read or in the read that settles its refused write. +TEST(CASOwnerStop, ObservedStopConflictKeepsAnEarlierUnresolvedExit) +{ + for (const auto & [stop_at, writes] : {std::pair{UnresolvedStop::KillSettlingSecondWrite, uint64_t{2}}, + std::pair{UnresolvedStop::KillReadingForLastAllowedWrite, uint64_t{kCasMaxDecisions - 1}}, + std::pair{UnresolvedStop::KillSettlingLastAllowedWrite, uint64_t{kCasMaxDecisions}}}) + { + SCOPED_TRACE(writes); + const auto out = runUnresolvedCreate(stop_at); + EXPECT_FALSE(out.outcome.has_value()); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR) << out.message; + EXPECT_NE(out.message.find("a sent write's outcome is unresolved"), String::npos) << out.message; + EXPECT_EQ(out.message.find("did not converge"), String::npos) << out.message; + EXPECT_EQ(out.catalog_writes, writes) << "the lost write and the refused ones, nothing after"; + } +} + +/// The store refuses the second decision's write while the owner stops. That refusal says nothing about the first +/// write, whose outcome is still unknown, so the call ends with the unresolved 210 rather than the refusal. +TEST(CASOwnerStop, RefusalUnderAStopKeepsAnEarlierUnresolvedExit) +{ + const auto out = runUnresolvedCreate(UnresolvedStop::RefusedSecondWriteWhileStopping); + EXPECT_FALSE(out.outcome.has_value()); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR) << out.message; + EXPECT_NE(out.message.find("a sent write's outcome is unresolved"), String::npos) << out.message; + EXPECT_NE(out.message.find("the store is read-only"), String::npos) << "names what ended the call: " << out.message; + EXPECT_EQ(out.catalog_writes, 2u) << "the lost write and the refused one, nothing after"; +} + +/// A local fault after an unresolved write is a bug or resource report, not a store answer: it reaches the caller +/// unchanged rather than as the retryable unresolved exit. +TEST(CASOwnerStop, LocalFaultAfterAnUnresolvedWriteIsNotReplaced) +{ + const auto out = runUnresolvedCreate(UnresolvedStop::LocalFaultInSecondWrite); + EXPECT_FALSE(out.outcome.has_value()); + EXPECT_EQ(out.code, ErrorCodes::CORRUPTED_DATA) << out.message; + EXPECT_NE(out.message.find("a local decode failure"), String::npos) << out.message; + EXPECT_EQ(out.message.find("a sent write's outcome is unresolved"), String::npos) << out.message; + EXPECT_EQ(out.catalog_writes, 2u) << "the lost write and the failed one, nothing after"; +} + +/// A catalog update that lost two races to another server stops before its next submission starts when the owner +/// stops in the conflict pause after the second; the first is retried at once. A fence lost while the first write +/// is in flight stays the typed fence outcome. +TEST(CASOwnerStop, ConflictedCatalogUpdateStopsAtTheNextSubmission) +{ + for (const bool fence_lost_in_flight : {false, true}) + { + SCOPED_TRACE(fence_lost_in_flight ? "fence lost while the write is in flight" : "stop in the conflict pause"); + onThread(false, [&] + { + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto backend = std::make_shared(); + const CatalogEntry observed{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(1)}; + auto competitor_requests = openRequestsForTest(backend); + auto competitor = competitor_requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(competitor, layout); + CasRefCatalog::casAdmitEntry(competitor, layout, 1, observed); + + std::atomic stop{false}; + std::atomic fence_lost{false}; + int pauses = 0; + uint64_t reads_at_pause = 0; + Fence fence = Fence::open(); + fence.admit = [&fence_lost](uint64_t, uint64_t) { return fence_lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }; + /// No cache: a next submission would start with a base read, so the read count shows whether it started. + CasHotKeys hot_keys(0); + CasRequests requests(backend, fence, {}, [&](uint64_t) + { + ++pauses; + reads_at_pause = backend->getCount(key); + stop = true; + }, &hot_keys, kDefaultRequestWindowMs); + auto op = requests.admit(); + + bool competing = false; + int competitor_writes = 0; + backend->onBeforeWrite(key, [&] + { + if (competing || competitor_writes > 1) + return; + competing = true; + CasRefCatalog::casAdmitEntry(competitor, layout, 1, + CatalogEntry{.ns = RootNamespace{competitor_writes == 0 ? "b" : "c"}, .state = NsState::Live, + .incarnation = UInt128(2 + competitor_writes)}); + ++competitor_writes; + competing = false; + if (fence_lost_in_flight) + { + fence_lost = true; + stop = true; + } + }); + const uint64_t writes_before = backend->writeCount(key); + + auto owner = backgroundStoppedBy(stop); + std::optional outcome; + std::exception_ptr error; + try + { + outcome = CasRefCatalog::beginRemoving(op, layout, observed, /*removal_started_round*/ 13); + } + catch (...) + { + error = std::current_exception(); + } + EXPECT_EQ(backend->writeCount(key) - writes_before, fence_lost_in_flight ? 2u : 4u) + << "each of the caller's writes and the competitor's write before it"; + if (fence_lost_in_flight) + { + EXPECT_EQ(codeOf(error), 0) << messageOf(error); + ASSERT_TRUE(outcome.has_value()); + EXPECT_EQ(*outcome, CasRefCatalog::BeginRemovingOutcome::FencedOut); + EXPECT_EQ(pauses, 0); + } + else + { + EXPECT_EQ(codeOf(error), ErrorCodes::ABORTED) << messageOf(error); + EXPECT_EQ(pauses, 1); + EXPECT_EQ(backend->getCount(key), reads_at_pause) << "no base read for a next submission"; + } + const auto snap = CasRefCatalog::read(competitor, layout); + ASSERT_EQ(snap.catalog.entries.size(), fence_lost_in_flight ? 2u : 3u); + EXPECT_EQ(snap.catalog.entries.at(0).state, NsState::Live) << "the next submission never started"; + }); + } +} + +namespace +{ + +/// The first remove of `key` meets a new incarnation another writer put there, so it answers `Mismatch`. +class ReplacedBeforeFirstRemoveBackend final : public CountingBackend +{ +public: + explicit ReplacedBeforeFirstRemoveBackend(String key_, int replacements_ = 1) : key(std::move(key_)), replacements(replacements_) {} + + std::function on_replaced; + + RawRemoval remove(const String & k, const String & expected_value, TransportAccess & access) override + { + if (k == key && replaced.fetch_add(1) < replacements) + { + const auto current = InMemoryBackend::head(k, access); + (void)InMemoryBackend::write(k, "replaced", current->value, access); + if (on_replaced) + on_replaced(); + } + return CountingBackend::remove(k, expected_value, access); + } + +private: + const String key; + const int replacements; + std::atomic replaced{0}; +}; + +} + +/// A stop around the reissue pause of `removeCurrent` sends no further HEAD. A stop at the first mismatch ends the +/// call at the checks of its zero pause, without sleeping; a stop during the pause after the second mismatch ends it +/// before the third HEAD. +TEST(CASOwnerStop, StopAroundRemoveReissuePauseSendsNoHead) +{ + for (const bool during_sleep : {false, true}) + { + SCOPED_TRACE(during_sleep ? "stop during the sleep" : "stop before the pause"); + onThread(false, [&] + { + auto backend = std::make_shared("k", /*replacements=*/2); + std::atomic stop{false}; + int sleeps = 0; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + ++sleeps; + if (during_sleep) + stop = true; + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("k", "v", Retry::once()))); + if (!during_sleep) + backend->on_replaced = [&stop] { stop = true; }; + + auto owner = backgroundStoppedBy(stop); + int code = 0; + try + { + (void)op.removeCurrent("k", Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + EXPECT_EQ(code, ErrorCodes::ABORTED); + EXPECT_EQ(backend->headCount("k"), during_sleep ? 2u : 1u); + EXPECT_EQ(backend->deleteCount("k"), during_sleep ? 2u : 1u); + EXPECT_EQ(sleeps, during_sleep ? 1 : 0); + }); + } +} + +namespace +{ + +/// The first write of `key` runs `on_first_write`, stores its bytes when `land` is set, and throws `failure`. +/// Every read of `key` runs `on_read` first. +class FirstWriteFailsBackend final : public InMemoryBackend +{ +public: + explicit FirstWriteFailsBackend(String key_) : key(std::move(key_)) {} + + std::exception_ptr failure = std::make_exception_ptr(Poco::TimeoutException("FirstWriteFailsBackend: the write timed out")); + bool land = false; + std::function on_first_write; + std::function on_write; + std::function on_read; + std::atomic writes{0}; + std::atomic reads{0}; + std::atomic refreshes{0}; + + std::expected write(const String & k, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + if (k == key) + { + if (on_write) + on_write(); + if (writes.fetch_add(1) == 0 && failure) + { + if (land) + (void)InMemoryBackend::write(k, bytes, expected_value, access); + if (on_first_write) + on_first_write(); + std::rethrow_exception(failure); + } + } + return InMemoryBackend::write(k, bytes, expected_value, access); + } + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key) + { + ++reads; + if (on_read) + on_read(); + } + return InMemoryBackend::read(k, access); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } + +private: + const String key; +}; + +/// One write call under an owner that `stop` stops: a background owner, or a query whose failed answers +/// the client-like backend replaces with its verdict. +struct StoppableWrite +{ + StoppedBy owner = StoppedBy::Background; + /// Arms the backend; `stop` stops the owner. + std::function & stop)> prepare_backend; + /// Runs during each pause, with `stop`. + std::function & stop)> during_pause; + /// Whether the `create` of the key runs inside `OwnerScope::owed`. + bool owed = false; + /// The cause a killed query throws instead of `QUERY_WAS_CANCELLED`. + std::exception_ptr kill_cause; +}; + +struct StoppableWriteOutcome +{ + std::optional result; + int code = 0; + String message; + std::exception_ptr error; + int writes = 0; + int reads = 0; + int pauses = 0; + int refreshes = 0; +}; + +constexpr auto STOPPABLE_KEY = "k"; + +StoppableWriteOutcome runStoppableWrite(const StoppableWrite & arm) +{ + StoppableWriteOutcome out; + onThread(true, [&] + { + std::optional query; + if (arm.owner == StoppedBy::Query) + query.emplace(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + BackendPtr backend = query ? BackendPtr(std::make_shared(inner)) : BackendPtr(inner); + std::atomic stopped{false}; + const std::function stop = [&] + { + stopped = true; + if (query) + query->kill(arm.kill_cause); + }; + std::atomic pauses{0}; + CasRequests requests(backend, Fence::open(), {}, [&](uint64_t) + { + ++pauses; + if (arm.during_pause) + arm.during_pause(stop); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + if (arm.prepare_backend) + arm.prepare_backend(*inner, stop); + inner->writes = 0; + inner->reads = 0; + + std::optional background; + if (arm.owner == StoppedBy::Background) + background.emplace(backgroundStoppedBy(stopped)); + try + { + std::optional owed; + if (arm.owed) + owed.emplace(OwnerScope::owed()); + out.result = op.create(STOPPABLE_KEY, "bytes", Retry::standard()); + } + catch (...) + { + out.error = std::current_exception(); + out.code = codeOf(out.error); + out.message = messageOf(out.error); + } + out.writes = inner->writes.load(); + out.reads = inner->reads.load(); + out.pauses = pauses.load(); + out.refreshes = inner->refreshes.load(); + }); + return out; +} + +void expectUnresolved(const StoppableWriteOutcome & out) +{ + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * gave_up = std::get_if(&*out.result); + ASSERT_NE(gave_up, nullptr) << "index " << out.result->index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(gave_up->attempts_sent, 1u); +} + +void expectCommittedByRead(const StoppableWriteOutcome & out) +{ + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * committed = std::get_if(&*out.result); + ASSERT_NE(committed, nullptr) << "index " << out.result->index(); + EXPECT_TRUE(committed->resolved_by_read); + EXPECT_EQ(committed->attempts_sent, 1u); +} + +} + +/// A store's definite refusal of a write whose every attempt was answered is the call's answer, also when a background +/// owner stopped during that attempt: nothing landed, so there is nothing to settle and no credential refresh to try. +/// After an earlier unanswered attempt the same refusal proves nothing about it, so the write still settles. +TEST(CASOwnerStop, BackgroundStopKeepsADefiniteRefusal) +{ + std::vector>> refusals{ + {"READONLY", [] { return std::make_exception_ptr(DB::Exception(DB::ErrorCodes::READONLY, "the store is read-only")); }}}; +#if USE_AWS_S3 + refusals.emplace_back("AccessDenied", [] + { + return std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); + }); +#endif + for (const auto & [name, refusal] : refusals) + { + { + SCOPED_TRACE(fmt::format("{}, every attempt answered", name)); + StoppableWrite arm; + arm.prepare_backend = [make = refusal](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.failure = make(); + backend.on_first_write = stop; + }; + const auto out = runStoppableWrite(arm); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + EXPECT_TRUE(std::holds_alternative(*out.result)) << "index " << out.result->index(); + EXPECT_EQ(out.writes, 1); + EXPECT_EQ(out.reads, 0) << "a refusal needs no settling read"; + EXPECT_EQ(out.refreshes, 0); + } + { + SCOPED_TRACE(fmt::format("{}, after an unanswered attempt", name)); + StoppableWrite arm; + arm.prepare_backend = [make = refusal](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.on_write = [&backend, stop, make] + { + if (backend.writes.load() == 1) + { + stop(); + std::rethrow_exception(make()); + } + }; + }; + const auto out = runStoppableWrite(arm); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * gave_up = std::get_if(&*out.result); + ASSERT_NE(gave_up, nullptr) << "index " << out.result->index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); + EXPECT_EQ(gave_up->attempts_sent, 2u); + } + } +} + +/// A stop that lands while a possibly-sent write waits to resend ends it without the resend: one `PUT`. +/// The settling read is owed only where it had not run yet, which is the connect-hint pause. +TEST(CASOwnerStop, StopInsideEachPauseSettlesWithoutResend) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + { + SCOPED_TRACE(fmt::format("{}, inside pauseAndReissue", nameOf(owner))); + StoppableWrite arm; + arm.owner = owner; + arm.during_pause = [](const auto & stop) { stop(); }; + const auto out = runStoppableWrite(arm); + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1) << "the settling read before the pause, none after it"; + EXPECT_EQ(out.pauses, 1); + } + { + SCOPED_TRACE(fmt::format("{}, after a repeatable settlement", nameOf(owner))); + StoppableWrite arm; + arm.owner = owner; + arm.prepare_backend = [](FirstWriteFailsBackend & backend, const std::function & stop) { backend.on_read = stop; }; + const auto out = runStoppableWrite(arm); + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1); + EXPECT_EQ(out.pauses, 0) << "no pause before a resend that cannot happen"; + } +#if USE_AWS_S3 + for (const bool landed : {false, true}) + { + SCOPED_TRACE(fmt::format("{}, inside pauseFlat, {}", nameOf(owner), landed ? "landed" : "not landed")); + StoppableWrite arm; + arm.owner = owner; + arm.prepare_backend = [landed](FirstWriteFailsBackend & backend, const std::function &) + { + backend.land = landed; + backend.failure = std::make_exception_ptr( + DB::S3Exception("Connection refused", Aws::S3::S3Errors::NETWORK_CONNECTION)); + }; + arm.during_pause = [](const auto & stop) { stop(); }; + const auto out = runStoppableWrite(arm); + if (landed) + expectCommittedByRead(out); + else + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1) << "the owed settling read the hinted attempt had not had"; + EXPECT_EQ(out.pauses, 1); + } +#endif + } +} + +/// A query killed with a stored cause while its write's reply is lost: the client-like backend surfaces the cause, and it +/// is the query's verdict whatever its code or type. A local-bug code is no local bug of the attempt, an exception the +/// transport cannot raise is caught before any classification, and `READONLY` is no refusal. The write is settled. +TEST(CASOwnerStop, LostReplyWithStoredCauseSettles) +{ + const std::vector>> causes{ + {"BAD_ARGUMENTS", [] { return storedCause(ErrorCodes::BAD_ARGUMENTS); }}, + {"runtime_error", [] { return std::make_exception_ptr(std::runtime_error("the query's stored cause")); }}, + {"READONLY", [] { return storedCause(ErrorCodes::READONLY); }}}; + for (const auto & [name, cause] : causes) + { + for (const bool landed : {false, true}) + { + SCOPED_TRACE(fmt::format("{}, {}", name, landed ? "landed" : "not landed")); + StoppableWrite arm; + arm.owner = StoppedBy::Query; + arm.kill_cause = cause(); + arm.prepare_backend = [landed](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.land = landed; + backend.on_first_write = stop; + }; + const auto out = runStoppableWrite(arm); + if (landed) + expectCommittedByRead(out); + else + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1) << "the owed settling read"; + EXPECT_EQ(out.pauses, 0); + } + } +} + +#if USE_AWS_S3 + +namespace +{ + +/// Finalizes by running `on_finalize`, asking the thread's query as the S3 client does, then running `on_reply` and +/// failing with the store's own `412 PreconditionFailed`. +class PreconditionFailedWriteBuffer final : public DB::WriteBufferFromFileBase +{ +public: + PreconditionFailedWriteBuffer(std::function on_finalize_, std::function on_reply_) + : DB::WriteBufferFromFileBase(DB::DBMS_DEFAULT_BUFFER_SIZE, nullptr, 0) + , on_finalize(std::move(on_finalize_)) + , on_reply(std::move(on_reply_)) + { + } + + void sync() override { next(); } + std::string getFileName() const override { return "precondition-failed-write-buffer"; } + +private: + void nextImpl() override {} + + void finalizeImpl() override + { + next(); + if (on_finalize) + on_finalize(); + CurrentThread::checkIfNotCancelled(); + if (on_reply) + on_reply(); + throw DB::S3Exception("the store answered 412", Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"); + } + + std::function on_finalize; + std::function on_reply; +}; + +class PreconditionFailedLocalObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + std::function on_finalize; + std::function on_reply; + std::atomic writes{0}; + + std::unique_ptr writeObject( + const DB::StoredObject &, DB::WriteMode, std::optional, size_t, const DB::WriteSettings &) override + { + ++writes; + return std::make_unique(on_finalize, on_reply); + } +}; + +} + +/// The native classifier reads a stopped query's `412` as no store answer: the S3 client throws the query's +/// stored cause in place of whatever the store said. A stopped background owner is invisible to the client, +/// so its genuine `412` stays a conflict. +TEST(CASOwnerStop, StoredPreconditionFailedIsNotAConflict) +{ + for (const StoppedBy owner : {StoppedBy::Query, StoppedBy::Background}) + { + SCOPED_TRACE(nameOf(owner)); + auto storage = makeLocalObjectStorageOf(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "absent"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + std::optional written; + int code = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + std::atomic stopped{false}; + storage->on_finalize = [&] + { + stopped = true; + if (owner == StoppedBy::Query) + query.kill(std::make_exception_ptr( + DB::S3Exception("the query's stored cause", Aws::S3::S3Errors::UNKNOWN, "PreconditionFailed"))); + }; + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + std::optional background; + if (owner == StoppedBy::Background) + background.emplace(backgroundStoppedBy(stopped)); + try + { + written = op.create(key, "bytes", Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + EXPECT_EQ(storage->writes.load(), 1); + if (owner == StoppedBy::Query) + { + const auto * gave_up = std::get_if(&*written); + ASSERT_NE(gave_up, nullptr) << "a stopped query's stored 412 is no conflict; index " << written->index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); + } + else + { + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "index " << written->index(); + EXPECT_FALSE(conflict->any_ambiguous); + } + } +} + +/// The store's own `412` reached the classifier, and the query was killed only after the S3 client let it through: +/// the refusal is still the store's answer, so the write ends as a conflict, not as an unresolved send. +TEST(CASOwnerStop, AKillAfterTheStoresOwn412KeepsTheConflict) +{ + auto storage = makeLocalObjectStorageOf(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "absent"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + std::optional written; + int code = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + storage->on_reply = [&] { query.kill(); }; + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + written = op.create(key, "bytes", Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + EXPECT_EQ(storage->writes.load(), 1); + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "a genuine 412 is a conflict; index " << written->index(); + EXPECT_FALSE(conflict->any_ambiguous); +} + +/// The probe's half of the test above: the store's own `NoSuchBucket` passed the S3 client, then the query was +/// killed before the probe classified it, and the answer stays the store's. +TEST(CASOwnerStop, AKillAfterTheStoresOwnProbeAnswerKeepsIt) +{ + auto storage = makeLocalObjectStorageOf(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "sentinel"); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + std::optional probed; + int code = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + storage->on_read = [&] + { + CurrentThread::checkIfNotCancelled(); + query.kill(); + throw DB::S3Exception("the store answered NoSuchBucket", Aws::S3::S3Errors::NO_SUCH_BUCKET); + }; + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + probed = op.probeSentinel(key, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(probed.has_value()); + EXPECT_EQ(probed->outcome, ProbeOutcome::ContainerAbsent); + EXPECT_EQ(storage->reads.load(), 1); +} + +#endif + +namespace +{ + +/// Counts the requests that change the store, and fails the next one with a transport-class error while `fail_next` +/// is set. +class MutationCountingBackend final : public InMemoryBackend +{ +public: + std::atomic mutations{0}; + std::atomic fail_next{false}; + + std::expected write(const String & k, const String & bytes, + const std::optional & expected_value, TransportAccess & access) override + { + countAndMaybeFail(); + return InMemoryBackend::write(k, bytes, expected_value, access); + } + + RawRemoval remove(const String & k, const String & expected_value, TransportAccess & access) override + { + countAndMaybeFail(); + return InMemoryBackend::remove(k, expected_value, access); + } + + void removeManyWriteOnce(const std::vector & keys, TransportAccess & access) override + { + countAndMaybeFail(); + InMemoryBackend::removeManyWriteOnce(keys, access); + } + + void publish(const BlobPublishRequest & request, TransportAccess & access) override + { + countAndMaybeFail(); + InMemoryBackend::publish(request, access); + } + +private: + void countAndMaybeFail() + { + ++mutations; + if (fail_next.exchange(false)) + throw Exception(ErrorCodes::S3_ERROR, "the first mutation failed"); + } +}; + +enum class MutatingVerb : uint8_t { Create, Replace, Remove, BulkRemove, Publish }; + +struct MutationRun +{ + int code = 0; + int mutations = 0; +}; + +/// Calls `verb` once on a store holding `present`, through a backend that answers a failure under a killed query with +/// the query's verdict, as the S3 client does. `stopped_before` stops its owner before the call; `fail_first` fails +/// the call's first mutation and kills the query in the pause after it. +MutationRun runMutatingVerb(MutatingVerb verb, std::optional stopped_before, bool fail_first) +{ + MutationRun run; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(); + CasRequests requests(std::make_shared(backend), Fence::open(), {}, [&](uint64_t) + { + if (fail_first) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + const auto present = op.create("present", "v", Retry::once()); + ASSERT_TRUE(std::holds_alternative(present)); + const Etag seen = std::get(present).etag; + backend->mutations = 0; + backend->fail_next = fail_first; + + std::atomic stopped{true}; + std::optional background; + if (stopped_before == StoppedBy::Background) + background.emplace(backgroundStoppedBy(stopped)); + else if (stopped_before == StoppedBy::Query) + query.kill(); + const String payload = "payload"; + try + { + switch (verb) + { + case MutatingVerb::Create: (void)op.create("new", "v", Retry::standard()); break; + case MutatingVerb::Replace: (void)op.replace("present", "w", seen, Retry::standard()); break; + case MutatingVerb::Remove: (void)op.remove("present", seen, Retry::standard()); break; + case MutatingVerb::BulkRemove: + op.removeManyWriteOnce({Layout("p").writeOnceBlobIntentProbeKey("probe")}, Retry::standard()); + break; + case MutatingVerb::Publish: + op.publish(BlobPublishRequest{ + .destination_key = "blob", + .publication = StreamingBlobPublication{ + .payload_size = payload.size(), + .fresh_envelope = "fresh", + .open_payload = [payload] { return std::make_unique(payload); }, + .expected_ref = DB::Cas::tests::idOf(payload)}}, Retry::standard()); + break; + } + } + catch (...) + { + run.code = codeOf(std::current_exception()); + } + run.mutations = backend->mutations.load(); + }); + return run; +} + +/// Calls each mutating verb once `owner` stopped. +void runEachMutatingVerbAfterStop(StoppedBy owner) +{ + using enum MutatingVerb; + for (const MutatingVerb verb : {Create, Replace, Remove, BulkRemove, Publish}) + { + SCOPED_TRACE(fmt::format("{}, verb {}", nameOf(owner), static_cast(verb))); + const MutationRun run = runMutatingVerb(verb, owner, /*fail_first=*/false); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(run.code, ErrorCodes::ABORTED); + EXPECT_EQ(run.mutations, 0) << "nothing sent"; + } + else + { + EXPECT_EQ(run.code, 0) << "a healthy first attempt of a killed query succeeds"; + EXPECT_EQ(run.mutations, 1) << "exactly the first attempt is sent"; + } + } +} + +} + +/// A background owner that stopped before a mutating call gets its verdict before anything is sent. +TEST(CASOwnerStop, BackgroundStopBeforeFirstSendSendsNothing) +{ + runEachMutatingVerbAfterStop(StoppedBy::Background); +} + +/// A killed query's first attempt of each mutating verb is sent and, on a healthy store, succeeds, as on plain S3. +TEST(CASOwnerStop, KilledQuerysFirstAttemptIsSent) +{ + runEachMutatingVerbAfterStop(StoppedBy::Query); +} + +/// A body read-modify-write whose write meets a competitor's replacement while the owner stops sends one +/// `PUT` and decides once. A background owner's verdict surfaces at the next decision. A killed query's write +/// failed with the kill, so its settled conflict is the answer and no decision follows. A stored credential cause +/// is no credential answer: no refresh, no resend. +TEST(CASOwnerStop, ConflictThenStopUnderStandardRmwDecidesOnce) +{ + struct Arm + { + const char * name; + StoppedBy owner; + std::function cause; + /// 0: the call returns a `Conflict`. + int code; + }; + std::vector arms = { + {"background owner", StoppedBy::Background, [] { return std::exception_ptr{}; }, ErrorCodes::ABORTED}, + {"killed query", StoppedBy::Query, [] { return std::exception_ptr{}; }, 0}, + }; +#if USE_AWS_S3 + arms.push_back({"killed query, stored AccessDenied", StoppedBy::Query, + [] { return std::make_exception_ptr(DB::S3Exception("the query's stored cause", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); }, + 0}); +#endif + for (const auto & arm : arms) + { + SCOPED_TRACE(arm.name); + int code = 0; + std::optional written; + int decisions = 0; + int writes = 0; + int refreshes = 0; + onThread(true, [&] + { + std::optional query; + if (arm.owner == StoppedBy::Query) + query.emplace(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + inner->failure = nullptr; + BackendPtr backend = query ? BackendPtr(std::make_shared(inner)) : BackendPtr(inner); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + ASSERT_TRUE(std::holds_alternative(competitor.create(STOPPABLE_KEY, "v0", Retry::once()))); + + std::atomic stopped{false}; + bool competing = false; + inner->writes = 0; + inner->on_write = [&] + { + if (competing || stopped) + return; + competing = true; + const auto current = competitor.read(STOPPABLE_KEY, Retry::once()); + ASSERT_TRUE(std::holds_alternative(competitor.replace(STOPPABLE_KEY, "competitor", current->etag, Retry::once()))); + competing = false; + stopped = true; + if (query) + query->kill(arm.cause()); + }; + std::optional background; + if (arm.owner == StoppedBy::Background) + background.emplace(backgroundStoppedBy(stopped)); + const int writes_before = inner->writes.load(); + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [&](const std::optional & current) + { + ++decisions; + return std::optional(current ? current->bytes + "+" : String("v")); + }, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + /// The competitor's own write passes through the same backend. + writes = inner->writes.load() - writes_before - 1; + refreshes = inner->refreshes.load(); + }); + EXPECT_EQ(code, arm.code); + if (arm.code == 0) + { + ASSERT_TRUE(written.has_value()); + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "index " << written->index(); + EXPECT_TRUE(conflict->observed_stop); + EXPECT_TRUE(std::holds_alternative(conflict->seen)) << "the settling read saw the competitor"; + } + EXPECT_EQ(decisions, 1); + EXPECT_EQ(writes, 1) << "one PUT"; + EXPECT_EQ(refreshes, 0); + } +} + +/// A clean 412 followed by a read that fails after the kill. A one-shot caller settles the 412 with that read and gets +/// the `Conflict`. A loop does not settle it: the failed read is the one after its pause, which ends the call with the +/// read's error. Neither starts a decision or a write after it. +TEST(CASOwnerStop, KilledQuerysConflictWithFailedSettlementEndsTheLoop) +{ + for (const bool once : {true, false}) + { + SCOPED_TRACE(once ? "Retry::once" : "Retry::standard"); + std::optional written; + int code = 0; + int decisions = 0; + int writes = 0; + int reads = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + inner->failure = nullptr; + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [](uint64_t) {}, nullptr, + kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create(STOPPABLE_KEY, "v0", Retry::once()))); + inner->refuseNextWrite(STOPPABLE_KEY); + inner->writes = 0; + inner->reads = 0; + inner->on_read = [&] + { + if (inner->writes.load() == 0) + return; + query.kill(); + throw Poco::TimeoutException("FirstWriteFailsBackend: the settling read timed out"); + }; + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [&](const std::optional & current) + { + ++decisions; + return std::optional(current->bytes + "+"); + }, once ? Retry::once() : Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + reads = inner->reads.load(); + }); + if (once) + { + EXPECT_EQ(code, 0) << "the conflict is the answer, not the kill"; + ASSERT_TRUE(written.has_value()); + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "index " << written->index(); + EXPECT_TRUE(std::holds_alternative(conflict->seen)); + } + else + { + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED) << "the failed read after the pause ends the call with the kill"; + EXPECT_FALSE(written.has_value()); + } + EXPECT_EQ(decisions, 1); + EXPECT_EQ(writes, 1) << "the refused PUT only"; + EXPECT_EQ(reads, 2) << "the base read and the one failed read after the refusal, not retried"; + } +} + +/// A catalog update whose 412 is followed by a settling read that fails after the kill submits nothing more: no +/// reread, no decision, no write. +TEST(CASOwnerStop, KilledQuerysCatalogUpdateStopsAfterAFailedSettlement) +{ + int code = 0; + int writes = 0; + int reads = 0; + int reads_at_failed_settlement = -1; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto inner = std::make_shared(key); + inner->failure = nullptr; + CasHotKeys hot_keys(16ULL << 20); + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [](uint64_t) {}, &hot_keys, + kDefaultRequestWindowMs); + auto op = requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(op, layout); + CasRefCatalog::casAdmitEntry(op, layout, 1, + CatalogEntry{.ns = RootNamespace{"a"}, .state = NsState::Live, .incarnation = UInt128(1)}); + inner->refuseNextWrite(key); + inner->writes = 0; + inner->reads = 0; + inner->on_read = [&] + { + if (inner->writes.load() == 0 || query.status->isKilled()) + return; + reads_at_failed_settlement = inner->reads.load(); + query.kill(); + throw Poco::TimeoutException("FirstWriteFailsBackend: the settling read timed out"); + }; + try + { + (void)CasRefCatalog::casUpdate(op, layout, [](const RefCatalog & current) { return current; }); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + reads = inner->reads.load(); + }); + EXPECT_EQ(code, ErrorCodes::ABORTED) << "the conflict ends the update"; + EXPECT_EQ(writes, 1) << "the refused PUT only"; + EXPECT_GE(reads_at_failed_settlement, 1); + EXPECT_EQ(reads, reads_at_failed_settlement) << "no read after the failed settlement"; +} + +/// A catalog erase whose 412 is followed by a settling read that fails after the kill still runs its mandatory +/// resolution read, and sends no second erase. +TEST(CASOwnerStop, KilledQuerysCatalogEraseSendsNoSecondErase) +{ + std::optional outcome; + int code = 0; + int writes = 0; + int reads = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto inner = std::make_shared(key); + inner->failure = nullptr; + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [](uint64_t) {}, nullptr, + kDefaultRequestWindowMs); + auto op = requests.admit(); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, .state = NsState::Removing, .incarnation = UInt128{7}, .removal_started_round = 13}; + ASSERT_TRUE(std::holds_alternative(op.create(key, encodeRefCatalog(RefCatalog{.entries = {removing}}), Retry::once()))); + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + CasRefCatalog::Snapshot cut = CasRefCatalog::read(op, layout); + + /// A competitor adds a row between the cut and the erase, so the erase meets a genuine 412. + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + const CatalogEntry other{.ns = RootNamespace{"b"}, .state = NsState::Live, .incarnation = UInt128{8}}; + const auto seen_by_competitor = competitor.read(key, Retry::once()); + ASSERT_TRUE(seen_by_competitor.has_value()); + ASSERT_TRUE(std::holds_alternative(competitor.replace( + key, encodeRefCatalog(RefCatalog{.entries = {removing, other}}), seen_by_competitor->etag, Retry::once()))); + inner->writes = 0; + inner->reads = 0; + bool settlement_failed = false; + inner->on_read = [&] + { + if (inner->writes.load() == 0 || std::exchange(settlement_failed, true)) + return; + query.kill(); + throw Poco::TimeoutException("FirstWriteFailsBackend: the settling read timed out"); + }; + try + { + outcome = CasRefCatalog::deleteCompletedRemovingAtSnapshot(op, layout, std::move(cut), removing, ready_parent, {}, {}, {}) + .outcome; + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + reads = inner->reads.load(); + }); + EXPECT_FALSE(outcome.has_value()) << "outcome " << static_cast(*outcome); + EXPECT_EQ(code, ErrorCodes::ABORTED) << "the conflict ends the erase"; + EXPECT_EQ(writes, 1) << "no second erase"; + EXPECT_EQ(reads, 2) << "the failed settling read and the mandatory resolution read"; +} + +/// A stopped background owner's unresolved catalog erase is followed by a resolution read that fails locally. The +/// local fault is the call's answer, not the erase's unresolved outcome. +TEST(CASOwnerStop, StoppedCatalogEraseKeepsALocalFaultOfItsResolutionRead) +{ + int code = 0; + int writes = 0; + int failed_reads = 0; + onThread(true, [&] + { + const Layout layout("p"); + const String key = layout.refCatalogKey(); + auto inner = std::make_shared(key); + CasRequests requests(inner, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, .state = NsState::Removing, .incarnation = UInt128{7}, .removal_started_round = 13}; + const auto failure = std::exchange(inner->failure, nullptr); + ASSERT_TRUE(std::holds_alternative(op.create(key, encodeRefCatalog(RefCatalog{.entries = {removing}}), Retry::once()))); + inner->failure = failure; + inner->writes = 0; + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + CasRefCatalog::Snapshot cut = CasRefCatalog::read(op, layout); + + /// The erase's own settling read stops the owner, so the erase ends unresolved without a resend. + std::atomic stopped{false}; + int reads_after_erase = 0; + inner->on_read = [&] + { + if (inner->writes.load() == 0) + return; + if (++reads_after_erase == 1) + { + stopped = true; + return; + } + ++failed_reads; + throw Exception(ErrorCodes::CORRUPTED_DATA, "the resolution read decoded a malformed catalog"); + }; + auto background = backgroundStoppedBy(stopped); + try + { + (void)CasRefCatalog::deleteCompletedRemovingAtSnapshot(op, layout, std::move(cut), removing, ready_parent, {}, {}, {}); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + }); + EXPECT_EQ(writes, 1) << "one erase, whose outcome is unresolved"; + EXPECT_EQ(failed_reads, 1) << "only the resolution read fails, after the erase's settling read"; + EXPECT_EQ(code, ErrorCodes::CORRUPTED_DATA) << "the local fault was replaced"; +} + +/// A transport fault, then a 412 settled by a successful read: the conflict is an answer, so a kill in the pause after +/// it does not stop the next decision, whose write commits on a healthy store. +TEST(CASOwnerStop, SettledConflictAfterAFaultPermitsTheNextDecisionAfterAKill) +{ + std::optional written; + int code = 0; + int decisions = 0; + int writes = 0; + int reads = 0; + int pauses = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [&](uint64_t) + { + /// The first pause precedes the resend of the timed-out attempt, the second follows the settled conflict. + if (++pauses == 2) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + /// The backend fails only the first write it sees; the seed is not it. + const auto failure = std::exchange(inner->failure, nullptr); + const auto created = competitor.create(STOPPABLE_KEY, "v0", Retry::once()); + ASSERT_TRUE(std::holds_alternative(created)); + const Etag base = std::get(created).etag; + inner->failure = failure; + inner->writes = 0; + inner->reads = 0; + bool competing = false; + inner->on_write = [&] + { + if (competing || inner->writes.load() != 1) + return; + competing = true; + ASSERT_TRUE(std::holds_alternative(competitor.replace(STOPPABLE_KEY, "competitor", base, Retry::once()))); + }; + auto op = requests.admit(); + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [&](const std::optional & current) + { + ++decisions; + return std::optional(current->bytes + "+"); + }, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + /// The competitor's write passes through the same backend. + writes = inner->writes.load() - 1; + reads = inner->reads.load(); + }); + EXPECT_EQ(code, 0) << "the kill does not stop a decision after a settled conflict"; + ASSERT_TRUE(written.has_value()); + EXPECT_TRUE(std::holds_alternative(*written)) << "index " << written->index(); + EXPECT_EQ(pauses, 2); + EXPECT_EQ(decisions, 2); + EXPECT_EQ(writes, 3) << "the timed-out PUT, its refused resend, and the PUT of the next decision"; + EXPECT_EQ(reads, 4) << "the base read, two settling reads and the read after the conflict pause"; +} + +/// A clean 412 inside a retrying read-modify-write is not settled: the read after the pause replaces it. The first one +/// is retried at once; a query killed during the pause after the second is consulted when the read after that pause +/// fails, before it is retried, and nothing is written after. +TEST(CASOwnerStop, AKillDuringTheConflictPauseIsObservedByTheFailedReadAfterIt) +{ + std::optional written; + int code = 0; + int writes = 0; + int reads_after_write = 0; + int pauses = 0; + int pauses_at_first_read_after_write = -1; + bool settled_before_pause = false; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + inner->failure = nullptr; + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [&](uint64_t) + { + if (++pauses == 1) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto competitor_requests = openRequestsForTest(inner); + auto competitor = competitor_requests.admit(); + const auto created = competitor.create(STOPPABLE_KEY, "v0", Retry::once()); + ASSERT_TRUE(std::holds_alternative(created)); + const Etag base = std::get(created).etag; + inner->writes = 0; + bool competing = false; + int moves = 0; + Etag competitor_etag = base; + /// The competitor wins the first two races: the first loss is retried at once, the second one pauses. + inner->on_write = [&] + { + if (competing || moves >= 2) + return; + competing = true; + const auto moved = competitor.replace(STOPPABLE_KEY, "competitor" + std::to_string(moves), competitor_etag, Retry::once()); + ASSERT_TRUE(std::holds_alternative(moved)); + competitor_etag = std::get(moved).etag; + ++moves; + competing = false; + }; + inner->on_read = [&] + { + if (inner->writes.load() - moves >= 2 && pauses == 0) + settled_before_pause = true; + if (pauses == 0) + return; + if (++reads_after_write == 1) + pauses_at_first_read_after_write = pauses; + throw Poco::TimeoutException("FirstWriteFailsBackend: the read timed out"); + }; + auto op = requests.admit(); + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [&](const std::optional & current) + { + return std::optional(current->bytes + "+"); + }, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + /// The competitor's writes pass through the same backend. + writes = inner->writes.load() - moves; + }); + EXPECT_FALSE(written.has_value()) << "index " << (written ? written->index() : 0); + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED) << "the failed read ends the call with the kill"; + EXPECT_EQ(writes, 2) << "no write after the kill"; + EXPECT_FALSE(settled_before_pause) << "the second 412 was not settled before the pause"; + EXPECT_EQ(pauses_at_first_read_after_write, 1); + EXPECT_EQ(reads_after_write, 1) << "the stop is consulted after the failed read, which is not retried"; + EXPECT_EQ(pauses, 1); +} + +/// A genuine refused precondition stays a conflict when the owner stops while its settling read is in +/// flight: the read is owed, and its failure is "nothing observed", not the owner's verdict. +TEST(CASOwnerStop, GenuineConflictThenStopDuringSettlementIsAConflict) +{ + std::optional written; + int code = 0; + int reads = 0; + onThread(false, [&] + { + auto backend = std::make_shared(STOPPABLE_KEY); + backend->failure = nullptr; + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create(STOPPABLE_KEY, "v0", Retry::once()))); + backend->refuseNextWrite(STOPPABLE_KEY); + backend->reads = 0; + + std::atomic stopped{false}; + backend->on_read = [&] + { + if (backend->writes.load() < 2) + return; + stopped = true; + throw Poco::TimeoutException("FirstWriteFailsBackend: the settling read timed out"); + }; + auto owner = backgroundStoppedBy(stopped); + try + { + written = op.readModifyWrite(STOPPABLE_KEY, [](const std::optional & current) + { + return std::optional(current->bytes + "+"); + }, Retry::once()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + reads = backend->reads.load(); + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + const auto * conflict = std::get_if(&*written); + ASSERT_NE(conflict, nullptr) << "index " << written->index(); + EXPECT_TRUE(std::holds_alternative(conflict->seen)); + EXPECT_EQ(conflict->attempts_sent, 1u); + EXPECT_EQ(reads, 2) << "the base read and the failed settling read"; +} + +/// A `PUT` that succeeds while the owner stops is committed and reaches the caller's bookkeeping. +TEST(CASOwnerStop, SuccessfulPutJustBeforeStopReachesBookkeeping) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + SCOPED_TRACE(nameOf(owner)); + StoppableWrite arm; + arm.owner = owner; + arm.prepare_backend = [](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.failure = nullptr; + backend.on_write = stop; + }; + const auto out = runStoppableWrite(arm); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * committed = std::get_if(&*out.result); + ASSERT_NE(committed, nullptr) << "index " << out.result->index(); + EXPECT_FALSE(committed->resolved_by_read); + EXPECT_EQ(out.writes, 1); + EXPECT_EQ(out.reads, 0); + } +} + +/// Owed work runs without the owner's stop: an owed write whose attempt failed while the owner was live +/// is resent after a stop in its pause, as an owed read is reissued. +TEST(CASOwnerStop, OwedWriteResendsAfterAStopInItsPause) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + SCOPED_TRACE(nameOf(owner)); + StoppableWrite arm; + arm.owner = owner; + arm.during_pause = [](const auto & stop) { stop(); }; + arm.owed = true; + const auto out = runStoppableWrite(arm); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * committed = std::get_if(&*out.result); + ASSERT_NE(committed, nullptr) << "index " << out.result->index(); + EXPECT_EQ(out.writes, 2) << "the resend"; + EXPECT_EQ(out.pauses, 1); + } +} + +/// An attempt that fails after the owner stopped is settled and never resent, inside `owed` too. +TEST(CASOwnerStop, OwedWriteFailedForAStoppedOwnerIsNotResent) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + SCOPED_TRACE(nameOf(owner)); + StoppableWrite arm; + arm.owner = owner; + arm.prepare_backend = [](FirstWriteFailsBackend & backend, const std::function & stop) { backend.on_first_write = stop; }; + arm.owed = true; + const auto out = runStoppableWrite(arm); + expectUnresolved(out); + EXPECT_EQ(out.writes, 1) << "no resend"; + EXPECT_EQ(out.reads, 1) << "the owed settling read"; + EXPECT_EQ(out.pauses, 0); + } +} + +#if USE_AWS_S3 + +/// A killed owner whose generation was replaced during the connect-hint pause leaves through the exit's +/// owed settling read, which the original generation refuses: the typed fence outcome and `sent_any` are +/// kept, and nothing is sent under the replacement generation. +TEST(CASOwnerStop, KilledOwnerWhoseGenerationRefusesSettlement) +{ + std::optional written; + int code = 0; + int writes = 0; + int reads = 0; + int admits_under_replacement = 0; + int pauses = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(STOPPABLE_KEY); + inner->failure = std::make_exception_ptr(DB::S3Exception("Connection refused", Aws::S3::S3Errors::NETWORK_CONNECTION)); + auto backend = std::make_shared(inner); + + std::atomic live_generation{1}; + std::atomic replacement_admits{0}; + Fence fence = Fence::open(); + fence.generation = [&] { return live_generation.load(); }; + fence.admit = [&](uint64_t admitted, uint64_t) + { + if (admitted != 1) + ++replacement_admits; + return admitted == live_generation.load() ? Fence::Admit::Ok : Fence::Admit::LostOrRearmed; + }; + std::atomic pause_count{0}; + CasRequests requests(backend, fence, {}, [&](uint64_t) + { + ++pause_count; + live_generation = 2; + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + written = op.create(STOPPABLE_KEY, "bytes", Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + writes = inner->writes.load(); + reads = inner->reads.load(); + admits_under_replacement = replacement_admits.load(); + pauses = pause_count.load(); + }); + EXPECT_EQ(code, 0); + ASSERT_TRUE(written.has_value()); + const auto * gave_up = std::get_if(&*written); + ASSERT_NE(gave_up, nullptr) << "index " << written->index(); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost) << "the refused settling read keeps its typed outcome"; + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(gave_up->attempts_sent, 1u); + EXPECT_EQ(pauses, 1); + EXPECT_EQ(writes, 1) << "no resend"; + EXPECT_EQ(reads, 0) << "the fence refused the settling read before it was sent"; + EXPECT_EQ(admits_under_replacement, 0) << "nothing is admitted under the replacement generation"; +} + +#endif + +/// A local fault of a stopped owner's write attempt is not settled as a possibly-sent write: it propagates, +/// and no settling read runs. +TEST(CASOwnerStop, LocalFaultOfAStoppedOwnersWriteIsNotSettled) +{ + struct LocalFault + { + const char * name; + std::exception_ptr error; + }; + const LocalFault faults[] = { + {"BAD_ARGUMENTS", std::make_exception_ptr(Exception(ErrorCodes::BAD_ARGUMENTS, "a local bug of the attempt"))}, + {"std::bad_alloc", std::make_exception_ptr(std::bad_alloc())}, + }; + for (const LocalFault & fault : faults) + { + SCOPED_TRACE(fault.name); + StoppableWrite arm; + arm.owner = StoppedBy::Background; + arm.prepare_backend = [&fault](FirstWriteFailsBackend & backend, const std::function & stop) + { + backend.failure = fault.error; + backend.on_first_write = stop; + }; + const auto out = runStoppableWrite(arm); + EXPECT_FALSE(out.result.has_value()) << "index " << (out.result ? out.result->index() : 0); + EXPECT_EQ(out.error, fault.error) << "not the fault itself: " << out.message; + EXPECT_EQ(out.writes, 1); + EXPECT_EQ(out.reads, 0) << "a local fault got a settling read"; + } +} + +namespace +{ + +/// Every read and `HEAD` of `key` runs `on_request`, then throws `failure`. The sentinel probe is the default adapter's, +/// over these two. +class LocalFaultReadBackend final : public InMemoryBackend +{ +public: + explicit LocalFaultReadBackend(String key_) : key(std::move(key_)) {} + + using InMemoryBackend::head; + + std::exception_ptr failure; + std::function on_request; + + std::optional read(const String & k, TransportAccess & access) override + { + if (k == key) + fail(); + return InMemoryBackend::read(k, access); + } + + std::optional head(const String & k, TransportAccess & access) override + { + if (k == key) + fail(); + return InMemoryBackend::head(k, access); + } + +private: + void fail() + { + if (on_request) + on_request(); + std::rethrow_exception(failure); + } + + const String key; +}; + +} + +/// A local fault of a read, of an observation or of a sentinel probe propagates unchanged when a background owner +/// stopped during the attempt, inside `owed` too: the owner's verdict does not replace it, and an observation does not +/// report it as nothing observed, as the write loop does not settle it. +TEST(CASOwnerStop, LocalFaultOfAStoppedOwnersReadOrProbeIsNotReplaced) +{ + enum class Surface : uint8_t { Read, Observation, Probe }; + struct LocalFault + { + const char * name; + std::function error; + }; + const LocalFault faults[] = { + {"CORRUPTED_DATA", [] { return std::make_exception_ptr(Exception(ErrorCodes::CORRUPTED_DATA, "a local decode failure")); }}, + {"std::bad_alloc", [] { return std::make_exception_ptr(std::bad_alloc()); }}, + }; + for (const LocalFault & fault : faults) + { + for (const Surface surface : {Surface::Read, Surface::Observation, Surface::Probe}) + { + for (const bool owed : {false, true}) + { + SCOPED_TRACE(fmt::format("{}, surface {}{}", fault.name, static_cast(surface), owed ? ", owed" : "")); + onThread(false, [&] + { + auto backend = std::make_shared("k"); + std::atomic stop{false}; + backend->failure = fault.error(); + backend->on_request = [&stop] { stop = true; }; + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + auto background = backgroundStoppedBy(stop); + std::optional owed_scope; + if (owed) + owed_scope.emplace(OwnerScope::owed()); + std::exception_ptr error; + try + { + if (surface == Surface::Probe) + (void)op.probeSentinel("k", Retry::standard()); + else if (surface == Surface::Observation) + (void)op.readModifyWrite("k", [](const std::optional &) { return String("v"); }, + Retry::standard()); + else + (void)op.read("k", Retry::standard()); + } + catch (...) + { + error = std::current_exception(); + } + ASSERT_TRUE(stop.load()) << "the attempt never ran"; + EXPECT_EQ(error, backend->failure) << "not the fault itself: " << messageOf(error); + }); + } + } + } +} + +/// The object-storage adapter's probe, native and emulated, lets a local fault of the storage call through as the same +/// exception; a transport failure stays `Indeterminate`. +TEST(CASOwnerStop, ObjectStorageProbeLetsALocalFaultThrough) +{ + struct Failure + { + const char * name; + std::function error; + bool local; + }; + const Failure failures[] = { + {"CORRUPTED_DATA", [] { return std::make_exception_ptr(Exception(ErrorCodes::CORRUPTED_DATA, "a local decode failure")); }, true}, + {"std::bad_alloc", [] { return std::make_exception_ptr(std::bad_alloc()); }, true}, + {"transport timeout", [] { return std::make_exception_ptr(Poco::TimeoutException("the probe timed out")); }, false}, + }; + for (const auto mode : {ObjectStorageBackend::Mode::Native, ObjectStorageBackend::Mode::EmulatedSingleProcess}) + { + for (const Failure & failure : failures) + { + const bool native = mode == ObjectStorageBackend::Mode::Native; + SCOPED_TRACE(fmt::format("{}, {}", native ? "native" : "emulated", failure.name)); + auto storage = makeLocalObjectStorageOf(); + const std::exception_ptr error = failure.error(); + (native ? storage->on_read : storage->on_exists) = [error] { std::rethrow_exception(error); }; + auto backend = std::make_shared(storage, mode); + const String key = native ? DB::Cas::tests::nativeKeyUnder(storage, "sentinel") : String("sentinel"); + std::optional probed; + std::exception_ptr thrown; + onThread(false, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + probed = op.probeSentinel(key, Retry::once()); + } + catch (...) + { + thrown = std::current_exception(); + } + }); + if (failure.local) + { + EXPECT_FALSE(probed.has_value()); + EXPECT_EQ(thrown, error) << "not the fault itself: " << messageOf(thrown); + } + else + { + EXPECT_EQ(thrown, nullptr) << messageOf(thrown); + ASSERT_TRUE(probed.has_value()); + EXPECT_EQ(probed->outcome, ProbeOutcome::Indeterminate); + } + } + } +} + +/// A stop that lands after a failed base read's own owner check, before `observe` reports the failure, is +/// reported as the owner's verdict, not as the store's failure. +TEST(CASOwnerStop, StopAfterTheReadsOwnCheckIsReportedByObserve) +{ + onThread(false, [&] + { + auto backend = std::make_shared("k"); + backend->failure = std::make_exception_ptr(Exception(ErrorCodes::NETWORK_ERROR, "the read failed")); + auto requests = openRequestsForTest(backend); + auto op = requests.admit(); + int checks_after_failure = 0; + const auto owner = OwnerScope::background([&] + { + if (backend->requests.load() > 0 && checks_after_failure++ > 0) + throw Exception(ErrorCodes::ABORTED, "background owner stopped"); + }); + int code = 0; + try + { + /// A single-attempt submission reads its base through `observe` with no hint. + (void)op.hotKeys().submit("k", op, Retry::once(), [](const std::optional &) { return std::optional("bytes"); }); + } + catch (const Exception & e) + { + code = e.code(); + } + EXPECT_EQ(checks_after_failure, 2) << "premise: the read's own check saw no stop, and observe's did"; + EXPECT_EQ(code, ErrorCodes::ABORTED); + }); +} + +/// A decision on a warm catalog hint that finds the GC authority lost while the owner is stopped reports the +/// lost authority, as the same decision on a fresh read does. +TEST(CASOwnerStop, StoppedOwnersLostAuthorityOnAWarmHintIsFencedOut) +{ + onThread(false, [&] + { + auto backend = std::make_shared(); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + const CatalogEntry stalled{ + .ns = RootNamespace{"a"}, .state = NsState::Creating, .incarnation = UInt128(1), + .creator = CreatorFence{.server_root_id = "srv", .writer_epoch = 1, .fence_generation = 1}}; + /// One plane with a cached lane for the setup and the cancel, so the cancel starts from the hint the setup left. + CasHotKeys hot_keys(/*cache_budget_bytes=*/1 << 20); + CasRequests requests(backend, Fence::open(), {}, {}, &hot_keys, kDefaultRequestWindowMs); + { + auto setup = requests.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + CasRefCatalog::casAdmitEntry(setup, layout, 1, stalled); + } + std::atomic authority_held = true; + std::atomic stopped = false; + auto op = requests.admit([&authority_held] { return authority_held.load(); }); + const auto owner = backgroundStoppedBy(stopped); + const uint64_t reads_before = backend->getCount(key); + std::optional reads_at_first_decision; + + std::optional outcome; + EXPECT_NO_THROW(outcome = CasRefCatalog::cancelStalledCreating( + op, layout, stalled, [](const CreatorFence &) { return true; }, + [&](const Retry &) + { + if (!reads_at_first_decision) + reads_at_first_decision = backend->getCount(key); + authority_held = false; + stopped = true; + })); + ASSERT_TRUE(reads_at_first_decision.has_value()); + EXPECT_EQ(*reads_at_first_decision, reads_before) << "premise: the first decision ran on the warm hint"; + ASSERT_TRUE(outcome.has_value()); + EXPECT_EQ(*outcome, CasRefCatalog::StalledCreatingCancelOutcome::FencedOut); + }); +} + +/// A killed query's first attempt is sent on a healthy store; when it fails and the query stops before the reissue, +/// nothing more is sent and the attempt's own error propagates, not the query's verdict. +TEST(CASOwnerStop, KilledQuerysFailedFirstAttemptKeepsItsError) +{ + using enum MutatingVerb; + for (const MutatingVerb verb : {Remove, BulkRemove, Publish}) + { + SCOPED_TRACE(fmt::format("verb {}", static_cast(verb))); + const MutationRun run = runMutatingVerb(verb, std::nullopt, /*fail_first=*/true); + EXPECT_EQ(run.code, ErrorCodes::S3_ERROR) << "the failed attempt's own error"; + EXPECT_EQ(run.mutations, 1) << "no reissue after the kill"; + } +} + +/// A long pause before a reissue is slept in slices, each checking the query: a kill in the third slice ends it there, +/// with the failed read's own error and no further request. +TEST(CASOwnerStop, LongFailurePauseChecksTheQueryEverySlice) +{ + std::vector slices; + int code = 0; + int sent = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared("k"); + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [&](uint64_t ms) + { + slices.push_back(ms); + if (slices.size() == 3) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("k", "v", Retry::once()))); + inner->requests = 0; + Retry policy = Retry::standard(); + /// A pause of at least 1600 ms: eight slices or more. + policy.attempt_spacing_ms = 2000; + try + { + (void)op.read("k", policy); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + sent = inner->requests.load(); + }); + EXPECT_EQ(code, ErrorCodes::TIMEOUT_EXCEEDED) << "the failed read's own error"; + EXPECT_EQ(slices.size(), 3u) << "the pause ends at the slice the kill landed in"; + /// A literal, not the constant: 200 ms is the published bound on how long a pause outlives a stop. + for (const uint64_t slice : slices) + EXPECT_LE(slice, 200u); + EXPECT_EQ(sent, 1) << "no reissue"; +} + +/// A query's stored cause with the `NOT_IMPLEMENTED` code is no batch-capability refusal: no single-key deletes. +TEST(CASOwnerStop, StoredNotImplementedStartsNoSingleKeyDeletes) +{ + class BulkFailsBackend final : public InMemoryBackend + { + public: + std::atomic bulk{0}; + std::atomic single{0}; + + void removeManyWriteOnce(const std::vector & keys, TransportAccess & access) override + { + if (keys.size() > 1) + { + ++bulk; + throw Poco::TimeoutException("BulkFailsBackend: the batch delete timed out"); + } + ++single; + InMemoryBackend::removeManyWriteOnce(keys, access); + } + }; + + int code = 0; + int bulk = 0; + int single = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(); + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [](uint64_t) {}, nullptr, + kDefaultRequestWindowMs); + auto op = requests.admit(); + const Layout layout("p"); + query.kill(storedCause(ErrorCodes::NOT_IMPLEMENTED)); + try + { + (void)removeChunkWriteOnceOrOneByOne( + op, {layout.writeOnceBlobIntentProbeKey("a"), layout.writeOnceBlobIntentProbeKey("b")}, Retry::standard()); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + bulk = inner->bulk.load(); + single = inner->single.load(); + }); + EXPECT_EQ(code, ErrorCodes::NOT_IMPLEMENTED) << "the query's stored cause propagates"; + EXPECT_EQ(bulk, 1); + EXPECT_EQ(single, 0) << "no single-key delete after the stored cause"; +} + +/// A local miss is the store's answer under a stopped background owner too, as an S3 `NoSuchKey` is: a background +/// verdict is a fresh exception, so it never arrives as a miss. +TEST(CASOwnerStop, LocalMissUnderAStoppedBackgroundOwnerIsAbsence) +{ + auto storage = makeLocalObjectStorageOf(); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + int code = 0; + bool read_absent = false; + onThread(false, [&] + { + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + const auto background = OwnerScope::background([] { throw Exception(ErrorCodes::ABORTED, "background owner stopped"); }); + try + { + read_absent = !op.read(DB::Cas::tests::nativeKeyUnder(storage, "absent"), Retry::standard()).has_value(); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + EXPECT_TRUE(read_absent); +} + +#if USE_AWS_S3 +/// A credential refusal the engine would have retried after a refresh ends as retry-later when the query stops before +/// the retry, carrying the refusal: a raw `AccessDenied` would read as damage to the part loader. +TEST(CASOwnerStop, VetoedCredentialRetryEndsAsRetryLater) +{ + FailedFirstRequest arm; + arm.failure = std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); + arm.during_pause = [](CasKillableQuery & q) { q.kill(); }; + const auto out = runFailedFirstRequest(arm); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR); + EXPECT_NE(out.message.find("the store answered AccessDenied"), String::npos) + << "the refusal is not the cause: " << out.message; + EXPECT_EQ(out.refreshes, 1) << "the live query's refusal was refreshed"; + EXPECT_EQ(out.requests, 1) << "the retry never starts"; +} + +namespace +{ + +/// Writes of "k" throw `failures` in order, then succeed; every refresh installs new credentials. +class ScriptedWriteBackend final : public InMemoryBackend +{ +public: + std::vector failures; + std::atomic writes{0}; + std::atomic refreshes{0}; + + std::expected write(const String & key, const String & bytes, const std::optional & expected_value, + TransportAccess & access) override + { + if (key == "k") + { + const size_t n = static_cast(writes++); + if (n < failures.size()) + std::rethrow_exception(failures[n]); + } + return InMemoryBackend::write(key, bytes, expected_value, access); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } +}; + +struct VetoedWriteOutcome +{ + std::optional result; + int code = 0; + String message; + int writes = 0; + int refreshes = 0; +}; + +/// `create("k")` whose writes fail with `failures`; the query is killed in pause number `kill_in_pause`. +VetoedWriteOutcome runVetoedWrite(std::vector failures, int kill_in_pause) +{ + VetoedWriteOutcome out; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto inner = std::make_shared(); + inner->failures = std::move(failures); + int pauses = 0; + CasRequests requests(std::make_shared(inner), Fence::open(), {}, [&](uint64_t) + { + if (++pauses == kill_in_pause) + query.kill(); + }, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + try + { + out.result = op.create("k", "v", Retry::standard()); + } + catch (...) + { + out.code = codeOf(std::current_exception()); + out.message = getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + out.writes = inner->writes.load(); + out.refreshes = inner->refreshes.load(); + }); + return out; +} + +std::exception_ptr accessDenied() +{ + return std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); +} + +} + +/// A conditional write whose credential retry the query vetoes ends as retry-later carrying the refusal: the store +/// refused that attempt, so its outcome is known. After an earlier unanswered attempt the write stays unresolved. +TEST(CASOwnerStop, VetoedCredentialRetryOfAWriteEndsAsRetryLater) +{ + { + SCOPED_TRACE("refused first attempt"); + const auto out = runVetoedWrite({accessDenied()}, /*kill_in_pause=*/1); + EXPECT_FALSE(out.result.has_value()); + EXPECT_EQ(out.code, ErrorCodes::NETWORK_ERROR) << out.message; + EXPECT_NE(out.message.find("the store answered AccessDenied"), String::npos) << out.message; + EXPECT_NE(out.message.find("credential retry"), String::npos) << out.message; + EXPECT_EQ(out.writes, 1) << "the retry is not sent"; + EXPECT_EQ(out.refreshes, 1); + } + { + SCOPED_TRACE("refused after an unanswered attempt"); + const auto out = runVetoedWrite( + {std::make_exception_ptr(Poco::TimeoutException("the write timed out")), accessDenied()}, /*kill_in_pause=*/2); + EXPECT_EQ(out.code, 0) << out.message; + ASSERT_TRUE(out.result.has_value()); + const auto * gave_up = std::get_if(&*out.result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_EQ(out.writes, 2); + } +} + +/// A stored `NoSuchKey` of a stopped query is not absence. A genuine `NoSuchKey` is the store's answer and stays +/// absence when the query is already killed. +TEST(CASOwnerStop, StoredNoSuchKeyIsNotAbsenceAGenuineOneIs) +{ + { + SCOPED_TRACE("stored NoSuchKey"); + auto storage = makeClientLikeLocalObjectStorage(); + const String key = DB::Cas::tests::nativeKeyUnder(storage, "present"); + { + auto out = storage->writeObject(DB::StoredObject(key), DB::WriteMode::Rewrite); + DB::writeString(String("body"), *out); + out->finalize(); + } + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + int code = 0; + bool read_absent = false; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + query.kill(std::make_exception_ptr( + DB::S3Exception("the query's stored cause", Aws::S3::S3Errors::NO_SUCH_KEY, "NoSuchKey"))); + storage->reads = 0; + storage->fail_next = true; + try + { + read_absent = !op.read(key, Retry::standard()).has_value(); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_FALSE(read_absent) << "a stored NoSuchKey is never absence"; + EXPECT_EQ(code, ErrorCodes::S3_ERROR); + EXPECT_EQ(storage->reads.load(), 1); + } + { + SCOPED_TRACE("genuine NoSuchKey after the kill"); + auto storage = makeLocalObjectStorageOf(); + auto backend = std::make_shared(storage, ObjectStorageBackend::Mode::Native); + int code = 0; + bool read_absent = false; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + CasRequests requests(backend, Fence::open(), {}, [](uint64_t) {}, nullptr, kDefaultRequestWindowMs); + auto op = requests.admit(); + query.kill(); + try + { + read_absent = !op.read(DB::Cas::tests::nativeKeyUnder(storage, "absent"), Retry::standard()).has_value(); + } + catch (...) + { + code = codeOf(std::current_exception()); + } + }); + EXPECT_EQ(code, 0); + EXPECT_TRUE(read_absent) << "the store's own miss is absence"; + EXPECT_EQ(storage->reads.load(), 1); + } +} +#endif + +namespace +{ + +/// Outlives the positive control's allocation, so the compiler cannot elide it. +[[maybe_unused]] String own_copy_allocation_sink; + +} + +/// A receiver at its memory limit still gets its own copy of a shared failure, not `MEMORY_LIMIT_EXCEEDED`: copying the +/// failure allocates, and that allocation is not where the limit is reported. +TEST(CASOwnerStop, OwnCopyOfASharedFailureIgnoresTheMemoryLimit) +{ +#if defined(SANITIZER) + GTEST_SKIP() << "a sanitizer build does not charge operator new to the memory tracker"; +#else + /// Only allocations of at least 8 MiB are checked against the 16 MiB limit; the copied text is 32 MiB. + const String text(32 << 20, 'x'); + const std::exception_ptr shared = std::make_exception_ptr(Exception(ErrorCodes::NETWORK_ERROR, "shared failure {}", text)); + const UInt64 saved_threshold = CurrentMemoryTracker::getMinAllocationSizeBytesToThrow(); + CurrentMemoryTracker::setMinAllocationSizeBytesToThrow(8 << 20); + SCOPE_EXIT({ CurrentMemoryTracker::setMinAllocationSizeBytesToThrow(saved_threshold); }); + + int control_code = 0; + int code = 0; + bool own_copy = false; + std::thread limited([&] + { + MemoryTracker limit_tracker(&total_memory_tracker, VariableContext::Process, /*log_peak_memory_usage_in_destructor_=*/false); + limit_tracker.setHardLimit(16 << 20); + ThreadStatus thread_status; + thread_status.memory_tracker.setParent(&limit_tracker); + thread_status.untracked_memory_limit = 0; + try + { + own_copy_allocation_sink = text; + } + catch (const Exception & e) + { + control_code = e.code(); + } + own_copy_allocation_sink.clear(); + own_copy_allocation_sink.shrink_to_fit(); + try + { + rethrowOwnCopy(shared); + } + catch (const Exception & e) + { + code = e.code(); + own_copy = std::current_exception() != shared; + } + }); + limited.join(); + + ASSERT_EQ(control_code, ErrorCodes::MEMORY_LIMIT_EXCEEDED) << "premise: the limit is enforced at that size"; + EXPECT_EQ(code, ErrorCodes::NETWORK_ERROR); + EXPECT_TRUE(own_copy); +#endif +} diff --git a/src/Disks/tests/gtest_cas_parallel_commit.cpp b/src/Disks/tests/gtest_cas_parallel_commit.cpp index 0b275fe67863d..f0ded315df661 100644 --- a/src/Disks/tests/gtest_cas_parallel_commit.cpp +++ b/src/Disks/tests/gtest_cas_parallel_commit.cpp @@ -2,11 +2,16 @@ #include #include #include +#include #include +#include +#include #include #include #include #include +#include +#include /// Task 2 of the CAS parallel-write-path plan (docs/superpowers/sdd): `promoteBuild`/`repointRef` /// return an exact, in-lane-derived `Cas::CommitOutcome` instead of `void`/`bool`, and @@ -306,3 +311,154 @@ TEST(CASCommitRollback, RepointByOtherWriterSurvivesRollback) EXPECT_TRUE(fx.partAccess().existsRef(key, Cas::Freshness::ForceFresh)); EXPECT_EQ(fx.currentManifest(key), fx.lastRepointManifest()); } + +/// A commit whose query is killed between two part publications still rolls back the ref it created: +/// the compensation is owed to the failed commit, and it leads the ref-log queue on the killed thread. +/// The concurrent-repoint arm proves the compensation stays conditional on the manifest it bound. +TEST(CASPartFolderAccess, KilledCommitStillRollsBackCreatedRef) +{ + { + SCOPED_TRACE("created ref, nobody repoints it"); + auto fx = makeCaWiringFixture(); + const Cas::PartRefKey key{fx.ns(), "a_created_1_1_0"}; + auto txn = fx.beginTxn(); + fx.stageInto(txn, key, 1); + fx.stageInto(txn, {fx.ns(), "z_poison_1_1_0"}, 1); + fx.armPromoteFailure({fx.ns(), "z_poison_1_1_0"}); + bool killed = false; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + fx.armAfterPromoteHook(key, [&] { query.kill(); killed = true; }); + EXPECT_ANY_THROW(txn->commit({})); + }); + ASSERT_TRUE(killed) << "the query was not killed between the publications"; + EXPECT_FALSE(fx.partAccess().existsRef(key, Cas::Freshness::ForceFresh)) << "the created ref is rolled back"; + } + { + SCOPED_TRACE("created ref, another writer repoints it before the rollback"); + auto fx = makeCaWiringFixture(); + const Cas::PartRefKey key{fx.ns(), "a_shared_1_1_0"}; + auto txn = fx.beginTxn(); + fx.stageInto(txn, key, 1); + fx.stageInto(txn, {fx.ns(), "z_poison_1_1_0"}, 1); + fx.armPromoteFailure({fx.ns(), "z_poison_1_1_0"}); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + /// The repoint stands for another, live writer, so it lands before this query is killed. + fx.armAfterPromoteHook(key, [&] + { + fx.repointToFreshManifest(key); + query.kill(); + }); + EXPECT_ANY_THROW(txn->commit({})); + }); + EXPECT_TRUE(fx.partAccess().existsRef(key, Cas::Freshness::ForceFresh)); + EXPECT_EQ(fx.currentManifest(key), fx.lastRepointManifest()) << "another writer's binding survives"; + } +} + +/// The compensation of a killed commit stays owed when it queues behind another caller's flush: it is not +/// withdrawn as a stopped follower would be, and the created ref is rolled back. +TEST(CASPartFolderAccess, KilledCommitCompensationQueuedBehindLeaderStillRollsBack) +{ + auto fx = makeCaWiringFixture(); + const auto pool = fx.storage->poolForTest(); + const Cas::PartRefKey key{fx.ns(), "a_created_1_1_0"}; + auto txn = fx.beginTxn(); + fx.stageInto(txn, key, 1); + fx.stageInto(txn, {fx.ns(), "z_poison_1_1_0"}, 1); + fx.armPromoteFailure({fx.ns(), "z_poison_1_1_0"}); + + std::atomic follower_evaluations{0}; + std::atomic leader_entered{false}; + pool->setRefFollowerWaitHookForTest([&](DB::Cas::FollowerWaitPhase) { follower_evaluations.fetch_add(1); }); + const auto spin_until = [](auto ready) + { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (!ready() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + return ready(); + }; + std::thread other_leader; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + fx.armAfterPromoteHook(key, [&] + { + /// Armed only now: the commit's own publication has flushed already. The parked leader waits for the + /// compensation to queue, then for it to have either run its wait condition (owed, so it stays) or + /// left the queue (withdrawn). + pool->setRefPreCarveHookForTest([&] + { + if (leader_entered.exchange(true)) + return; + EXPECT_TRUE(spin_until([&] { return pool->refQueuePendingForTest(fx.ns()) >= 2; })) << "the compensation never queued"; + EXPECT_TRUE(spin_until([&] { return follower_evaluations.load() >= 1 || pool->refQueuePendingForTest(fx.ns()) < 2; })); + }); + other_leader = std::thread([&] { try { pool->dropRef(fx.ns(), "z_other_ref"); } catch (...) {} }); + EXPECT_TRUE(spin_until([&] { return leader_entered.load(); })) << "the other leader never parked"; + query.kill(); + }); + EXPECT_ANY_THROW(txn->commit({})); + }); + other_leader.join(); + pool->setRefPreCarveHookForTest(nullptr); + pool->setRefFollowerWaitHookForTest(nullptr); + + EXPECT_GE(follower_evaluations.load(), 1) << "the compensation never queued behind the leader"; + EXPECT_FALSE(fx.partAccess().existsRef(key, Cas::Freshness::ForceFresh)) << "the created ref is rolled back"; +} + +/// `ATTACH PART` and `DROP DETACHED PART` rename a detached part to a reserved name before they act, and +/// undo that rename with `moveFile` on failure. A query killed after the durable rename still gets its +/// original name back, and a retry succeeds. +TEST(CASPartFolderAccess, KilledAttachStillRestoresDetachedName) +{ + for (const std::string prefix : {"attaching_", "deleting_"}) + { + SCOPED_TRACE(prefix); + auto fx = makeCaWiringFixture(); + const std::string table = CaTxnRollbackFixture::tablePrefix(); + const std::string part = "all_1_1_0"; + const std::string detached = table + "/detached/" + part; + const std::string reserved = table + "/detached/" + prefix + part; + fx.commitSimplePart({fx.ns(), part}, 1); + { + auto txn = fx.beginTxn(); + txn->moveDirectory(table + "/" + part, detached); + txn->commit(DB::NoCommitOptions{}); + } + { + auto txn = fx.beginTxn(); + txn->moveDirectory(detached, reserved); + txn->commit(DB::NoCommitOptions{}); + } + ASSERT_TRUE(fx.storage->existsDirectory(reserved)); + + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + query.kill(); + auto txn = fx.beginTxn(); + EXPECT_NO_THROW({ + txn->moveFile(reserved, detached); + txn->commit(DB::NoCommitOptions{}); + }); + }); + + EXPECT_TRUE(fx.storage->existsDirectory(detached)) << "the original detached name is back"; + EXPECT_FALSE(fx.storage->existsDirectory(reserved)); + + { + auto txn = fx.beginTxn(); + txn->moveDirectory(detached, reserved); + txn->commit(DB::NoCommitOptions{}); + } + auto txn = fx.beginTxn(); + if (prefix == "attaching_") + txn->moveDirectory(reserved, table + "/all_2_2_0"); + else + txn->removeRecursive(reserved, nullptr); + txn->commit(DB::NoCommitOptions{}); + EXPECT_FALSE(fx.storage->existsDirectory(reserved)) << "the retry completes"; + EXPECT_EQ(fx.storage->existsDirectory(table + "/all_2_2_0"), prefix == "attaching_"); + } +} diff --git a/src/Disks/tests/gtest_cas_part_folder_access.cpp b/src/Disks/tests/gtest_cas_part_folder_access.cpp index 9fe2eed96eb75..13f2240105f53 100644 --- a/src/Disks/tests/gtest_cas_part_folder_access.cpp +++ b/src/Disks/tests/gtest_cas_part_folder_access.cpp @@ -1,10 +1,15 @@ #include +#include #include #include #include +#include #include +#include #include #include +#include +#include #include #include #include @@ -13,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +37,8 @@ namespace DB::ErrorCodes extern const int MEMORY_LIMIT_EXCEEDED; extern const int NETWORK_ERROR; extern const int NO_REPLICA_HAS_PART; + extern const int QUERY_WAS_CANCELLED; + extern const int TIMEOUT_EXCEEDED; } namespace ProfileEvents @@ -39,6 +47,7 @@ extern const Event CASRefRollbackBestEffortDropFailed; extern const Event CASOwnershipConflict; extern const Event CASRefMove; extern const Event CASRelinkConfirmRefusedStateLockBusy; +extern const Event CASRelinkConfirmRefusedSlotUnreadable; } using namespace DB; @@ -1345,6 +1354,32 @@ TEST(CASPartFolderAccess, PrepareThenAbortAppendsThePrecommitRemoval) } } +/// A killed query's abort on a healthy store does its whole cleanup on its own thread: when the call returns, the +/// precommit binding is gone, the build floor has advanced and no cleanup duty is left for another caller. +TEST(CASPartFolderAccess, KilledQueryAbandonOnSameThreadRemovesPrecommit) +{ + auto backend = std::make_shared(); + auto store = openPoolForTest(backend); + const Cas::RootNamespace ns{"srv/t1"}; + Cas::CachedPartFolderAccess access(store, cacheOn()); + + std::thread killed([&] + { + ThreadStatus thread_status; + Cas::tests::CasKillableQuery query(getContext().context); + auto prepared = access.prepareEntries({ns, "part_1"}, {inlineEntry("f", "one")}, Cas::ProvenanceOp::Insert); + ASSERT_TRUE(store->livePrecommitsForTest(ns).contains({"part_1", prepared.manifestId().ref})); + const uint64_t floor_before = store->minActive(); + query.kill(); + + EXPECT_NO_THROW(prepared.abort()); + EXPECT_FALSE(store->writerCleanupDutiesPendingForTest()) << "the abort left its removal to a later caller"; + EXPECT_GT(store->minActive(), floor_before) << "the aborted build still holds the floor"; + EXPECT_TRUE(store->livePrecommitsForTest(ns).empty()) << "the precommit binding stayed live"; + }); + killed.join(); +} + /// A forgotten terminal must be impossible, not merely discouraged: `~PartWriteTxn` only retires the /// build sequence, so the handle's own destructor is the last-resort owner of the precommit removal. TEST(CASPartFolderAccess, DestroyingAnUnfinishedPreparedPartWriteAborts) @@ -1775,7 +1810,7 @@ namespace { /// A pool whose manifest decode cache is off, so every view build reaches the manifest GET. -Cas::PoolPtr openPoolWithoutDecodeCache(const std::shared_ptr & backend) +Cas::PoolPtr openPoolWithoutDecodeCache(Cas::BackendPtr backend) { return Cas::Pool::open(backend, Cas::PoolConfig{.pool_prefix = "p", .server_root_id = "test", .manifest_decode_cache_bytes = 0}); @@ -1906,11 +1941,32 @@ struct LeaderAndFollower bool follower_joined = false; }; +/// Readers that run inside a registered query. An empty function leaves that reader outside any query. +struct ReaderQueries +{ + /// Runs while the leader is parked, with the leader's query. + std::function leader_parked; + /// Runs on the follower's thread, with the follower's query, before it reads. + std::function follower_before_read; +}; + +/// Runs `read` on the current raw thread, inside a registered query when `in_query` is set. +ReaderOutcome readInQuery(bool in_query, const std::function & with_query, + const std::function & read) +{ + if (!in_query) + return read(); + ThreadStatus thread_status; + Cas::tests::CasKillableQuery query(getContext().context); + with_query(query); + return read(); +} + /// One reader leads the cold build of `key` and is held in its manifest GET; `while_parked` runs, then a /// second reader starts and the GET is released once that reader has joined the build or returned. LeaderAndFollower leaderAndFollower( ParkFirstReadBackend & backend, Cas::CachedPartFolderAccess & access, const Cas::PartRefKey & key, - const std::function & while_parked = {}) + const std::function & while_parked = {}, const ReaderQueries & queries = {}) { std::promise release; backend.release = release.get_future().share(); @@ -1946,15 +2002,24 @@ LeaderAndFollower leaderAndFollower( }; SCOPE_EXIT({ finish(); }); - leader_thread.emplace([&] { run.leader = readColdView(access, key); }); + /// Published by the leader's thread before its read parks; used only while it is parked. + Cas::tests::CasKillableQuery * leader_query = nullptr; + leader_thread.emplace([&] + { + run.leader = readInQuery(bool(queries.leader_parked), [&](Cas::tests::CasKillableQuery & query) { leader_query = &query; }, + [&] { return readColdView(access, key); }); + }); run.leader_parked = backend.parked.get_future().wait_for(kRendezvousTimeout) == std::future_status::ready; if (run.leader_parked) { if (while_parked) while_parked(); + if (queries.leader_parked) + queries.leader_parked(*leader_query); follower_thread.emplace([&] { - run.follower = readColdView(access, key); + run.follower = readInQuery(bool(queries.follower_before_read), queries.follower_before_read, + [&] { return readColdView(access, key); }); arrive(); }); run.follower_arrived = arrived.get_future().wait_for(kRendezvousTimeout) == std::future_status::ready; @@ -2044,6 +2109,154 @@ TEST(CASPartFolderAccess, AFollowersOwnMemoryLimitIsFinal) EXPECT_EQ(backend->getCount(manifest_key), 2u); } +namespace +{ + +struct ColdBuildFixture +{ + std::shared_ptr backend = std::make_shared(); + Cas::PoolPtr store = openPoolWithoutDecodeCache(std::make_shared(backend)); + const Cas::RootNamespace ns{"srv/t1"}; + Cas::CachedPartFolderAccess access{store, cacheOn()}; + const Cas::ManifestId id = publishPart(store, ns, "part_1", {inlineEntry("f", "x")}); + const Cas::PartRefKey key{ns, "part_1"}; + const String manifest_key = Cas::Layout("p").manifestKey(id); + + ColdBuildFixture() + { + backend->resetCounts(); + backend->park_key = manifest_key; + } +}; + +} + +/// A leader whose query stopped hands its followers no verdict of its own: a live follower rebuilds the +/// same manifest, and the leader reports its own stop. +TEST(CASPartFolderAccess, StoppedLeaderLetsLiveFollowerRebuild) +{ + struct Arm + { + const char * name; + std::exception_ptr cause; + int code; + }; + for (const auto & arm : {Arm{"kill", nullptr, ErrorCodes::QUERY_WAS_CANCELLED}, + Arm{"timeout", std::make_exception_ptr(Exception(ErrorCodes::TIMEOUT_EXCEEDED, "the query timed out")), + ErrorCodes::TIMEOUT_EXCEEDED}}) + { + SCOPED_TRACE(arm.name); + ColdBuildFixture fx; + fx.backend->failNextReadWith(fx.manifest_key, std::make_exception_ptr(Poco::TimeoutException("the manifest read timed out"))); + + ReaderQueries queries; + queries.leader_parked = [&](Cas::tests::CasKillableQuery & query) { query.kill(arm.cause); }; + const auto run = leaderAndFollower(*fx.backend, fx.access, fx.key, {}, queries); + ASSERT_TRUE(run.leader_parked && run.follower_arrived && run.follower_joined); + + EXPECT_EQ(run.leader.code, arm.code) << run.leader.message; + EXPECT_EQ(run.leader.view, nullptr); + EXPECT_EQ(run.follower.code, 0) << run.follower.message; + ASSERT_NE(run.follower.view, nullptr); + EXPECT_EQ(run.follower.view->manifestId(), fx.id) << "the follower rebuilt the same manifest"; + EXPECT_EQ(fx.backend->getCount(fx.manifest_key), 2u) << "the leader's failed read and the follower's rebuild"; + } +} + +/// A follower takes a successful shared build even when its own query was killed: a read-only follower +/// has no owner check. +TEST(CASPartFolderAccess, KilledReaderConsumesSuccessfulSharedBuild) +{ + ColdBuildFixture fx; + + ReaderQueries queries; + queries.follower_before_read = [](Cas::tests::CasKillableQuery & query) { query.kill(); }; + const auto run = leaderAndFollower(*fx.backend, fx.access, fx.key, {}, queries); + ASSERT_TRUE(run.leader_parked && run.follower_arrived && run.follower_joined); + + EXPECT_EQ(run.leader.code, 0) << run.leader.message; + EXPECT_EQ(run.follower.code, 0) << run.follower.message; + ASSERT_NE(run.follower.view, nullptr); + EXPECT_EQ(run.follower.view, run.leader.view) << "the follower consumed the leader's build"; + EXPECT_EQ(fx.backend->getCount(fx.manifest_key), 1u); +} + +/// A live leader's transport timeout is the leader's to reissue; its follower does not take the build over. +TEST(CASPartFolderAccess, LiveLeadersTransportTimeoutIsNotFollowerTakeover) +{ + ColdBuildFixture fx; + fx.backend->failNextReadWith(fx.manifest_key, std::make_exception_ptr( + Exception(ErrorCodes::TIMEOUT_EXCEEDED, "the manifest read timed out"))); + + const auto run = leaderAndFollower(*fx.backend, fx.access, fx.key); + ASSERT_TRUE(run.leader_parked && run.follower_arrived && run.follower_joined); + + EXPECT_EQ(run.leader.code, 0) << run.leader.message; + ASSERT_NE(run.leader.view, nullptr); + EXPECT_EQ(run.follower.view, run.leader.view) << "the follower consumed the leader's reissued build"; + EXPECT_EQ(fx.backend->getCount(fx.manifest_key), 2u) << "both reads were the leader's"; +} + +namespace +{ + +/// `dropRefIfPresent` on a raw thread whose query was killed with a stored `FILE_DOESNT_EXIST`. +int dropRefIfPresentWithStoredMiss(Cas::CachedPartFolderAccess & access, const Cas::PartRefKey & key) +{ + int code = 0; + std::thread dropper([&] + { + ThreadStatus thread_status; + Cas::tests::CasKillableQuery query(getContext().context); + query.kill(std::make_exception_ptr(Exception(ErrorCodes::FILE_DOESNT_EXIST, "the query's stored cause"))); + try + { + access.dropRefIfPresent(key); + } + catch (const Exception & e) + { + code = e.code(); + } + }); + dropper.join(); + return code; +} + +} + +/// A stopped owner's stored `FILE_DOESNT_EXIST` is not "the ref raced away": on an unsuccessful read of a cold +/// table, which the client-like backend answers with the stored cause, `dropRefIfPresent` throws it and the ref +/// stays live. +TEST(CASPartFolderAccess, StoppedOwnersStoredMissOnAColdTableKeepsTheRefLive) +{ + const Cas::RootNamespace ns{"srv/t1"}; + const Cas::PartRefKey key{ns, "part_1"}; + auto backend = std::make_shared(); + auto client_like = std::make_shared(backend); + publishPart(openPoolForTest(client_like), ns, "part_1", {inlineEntry("f", "x")}); + auto store = openPoolForTest(client_like); + Cas::CachedPartFolderAccess access(store); + ASSERT_FALSE(store->refTableRecoveredForTest(ns)); + + EXPECT_EQ(dropRefIfPresentWithStoredMiss(access, key), ErrorCodes::FILE_DOESNT_EXIST); + EXPECT_FALSE(store->refTableRecoveredForTest(ns)) << "the verdict came from the cold table's read"; + EXPECT_TRUE(access.existsRef(key, Cas::Freshness::ForceFresh)) << "the ref stays live"; +} + +/// On a warm table every request succeeds, so a killed query's drop is sent and lands. +TEST(CASPartFolderAccess, KilledQuerysDropOnAWarmTableLands) +{ + const Cas::RootNamespace ns{"srv/t1"}; + const Cas::PartRefKey key{ns, "part_1"}; + auto backend = std::make_shared(); + auto store = openPoolForTest(std::make_shared(backend)); + Cas::CachedPartFolderAccess access(store); + publishPart(store, ns, "part_1", {inlineEntry("f", "x")}); + + EXPECT_EQ(dropRefIfPresentWithStoredMiss(access, key), 0) << "a healthy drop of a killed query is sent"; + EXPECT_FALSE(access.existsRef(key, Cas::Freshness::ForceFresh)) << "the drop landed"; +} + /// A reader that resolved a newer manifest of the same ref must not receive the build of the older one. TEST(CASPartFolderAccess, ReadersOfDifferentManifestsOfOneRefDoNotShareABuild) { @@ -2136,6 +2349,93 @@ TEST(CASPartFolderAccess, ALateFollowerTakesTheViewAnotherFollowerRebuilt) EXPECT_EQ(second.view, first.view); } +/// Followers of one failed cold build each rethrow their own copy of the leader's failure, of the same type, code and +/// message: callers annotate what they catch, and two query threads must not append to one message. +TEST(CASPartFolderAccess, FollowersOfAFailedBuildRethrowTheirOwnCopy) +{ + auto backend = std::make_shared(); + auto store = openPoolWithoutDecodeCache(backend); + const Cas::Layout layout("p"); + const Cas::RootNamespace ns{"srv/t1"}; + Cas::CachedPartFolderAccess access(store, cacheOn()); + const auto id = publishPart(store, ns, "part_1", {inlineEntry("f", "x")}); + const Cas::PartRefKey key{ns, "part_1"}; + const String manifest_key = layout.manifestKey(id); + backend->park_key = manifest_key; + backend->failNextReadWith(manifest_key, std::make_exception_ptr( + Exception(ErrorCodes::CORRUPTED_DATA, "the leader's read failed"))); + std::promise release; + backend->release = release.get_future().share(); + + std::atomic joins{0}; + std::promise both_joined; + access.setHookForTest(Cas::CachedPartFolderAccess::TestHook::FollowerJoined, [&] + { + if (++joins == 2) + both_joined.set_value(); + }); + SCOPE_EXIT({ access.setHookForTest(Cas::CachedPartFolderAccess::TestHook::FollowerJoined, nullptr); }); + + const auto cold_read = [&](std::exception_ptr & failure) + { + try + { + (void)access.getView(key, Cas::Freshness::CachedForLoad); + } + catch (...) + { + failure = std::current_exception(); + } + }; + std::exception_ptr leader_failure; + std::exception_ptr first_failure; + std::exception_ptr second_failure; + std::thread leader_thread([&] { cold_read(leader_failure); }); + const bool leader_parked = backend->parked.get_future().wait_for(kRendezvousTimeout) == std::future_status::ready; + std::thread first_thread([&] { cold_read(first_failure); }); + std::thread second_thread([&] { cold_read(second_failure); }); + const bool followers_joined = both_joined.get_future().wait_for(kRendezvousTimeout) == std::future_status::ready; + release.set_value(); + leader_thread.join(); + first_thread.join(); + second_thread.join(); + ASSERT_TRUE(leader_parked && followers_joined); + + const auto object_of = [](const std::exception_ptr & failure) -> Exception * + { + if (!failure) + return nullptr; + try + { + std::rethrow_exception(failure); + } + catch (Exception & e) + { + return &e; + } + catch (...) + { + return nullptr; + } + }; + Exception * leader = object_of(leader_failure); + Exception * first = object_of(first_failure); + Exception * second = object_of(second_failure); + ASSERT_TRUE(leader && first && second); + EXPECT_NE(first, second) << "two followers hold one exception object"; + EXPECT_NE(first, leader); + EXPECT_NE(second, leader); + for (const Exception * follower : {first, second}) + { + EXPECT_EQ(follower->code(), ErrorCodes::CORRUPTED_DATA); + EXPECT_EQ(follower->message(), leader->message()); + } + const String second_before = second->message(); + first->addMessage("annotated by the first follower"); + EXPECT_EQ(second->message(), second_before); + EXPECT_EQ(leader->message().find("annotated"), String::npos); +} + TEST(CASPartFolderAccess, DropNamespaceErasesAllViews) { auto backend = std::make_shared(); @@ -2561,3 +2861,388 @@ TEST(CASPartFolderAccess, MoveRetryAfterAmbiguousAppendIsIdempotent) EXPECT_FALSE(access.existsRef({ns, "tmp_a"}, Cas::Freshness::ForceFresh)); EXPECT_EQ(access.resolve({ns, "a"}, Cas::Freshness::ForceFresh)->manifest_id, expected); } + +namespace +{ + +/// A pool whose copy-confirm poll runs on a virtual clock. `moveSlot` makes a pass answer `Unknown`: the mount +/// slot then shows a lease that is not this mount's. `on_snapshot` runs once, after the first ledger snapshot. +/// Every pause runs `on_pause`, then advances the clock. +struct CopyConfirmPollFixture +{ + std::shared_ptr backend = std::make_shared(); + std::shared_ptr> boot_ms = std::make_shared>(1'000'000); + std::shared_ptr store; + Cas::RootNamespace ns{"srv/t1"}; + std::unique_ptr access; + std::optional source; + uint64_t window_ms = 0; + std::atomic pauses{0}; + std::atomic pause_advance_ms{0}; + std::function on_pause; + std::function on_snapshot; + + CopyConfirmPollFixture() + { + Cas::PoolConfig config{.pool_prefix = "p", .server_root_id = "test"}; + config.boot_ms_fn = [clock = boot_ms] { return clock->load(); }; + config.mount_lease_ttl_ms = std::chrono::milliseconds(600'000); + store = Cas::Pool::open(std::make_shared(backend), std::move(config)); + access = std::make_unique(store); + publishPart(store, ns, "src", {inlineEntry("f", "live")}); + source = access->resolveCopySource({ns, "src"}); + window_ms = store->poolConfig().cas_request_budget.request_window_ms; + store->setCasRetrySleepForTest([this](uint64_t ms) + { + ++pauses; + if (on_pause) + on_pause(); + boot_ms->fetch_add(ms + pause_advance_ms); + }); + store->setConfirmAfterLedgerSnapshotHookForTest([this] + { + auto once = std::move(on_snapshot); + on_snapshot = nullptr; + if (once) + once(); + }); + } + + ~CopyConfirmPollFixture() + { + store->setConfirmAfterLedgerSnapshotHookForTest(nullptr); + store->setCasRetrySleepForTest(nullptr); + } + + String slotKey() const { return store->layout().mountKey("test"); } + + void moveSlot() + { + rewriteSlot([](Cas::MountLease & lease) { lease.server_uuid += 1; }); + } + + void rewriteSlot(const std::function & change) + { + Cas::CasRequests requests = DB::Cas::tests::openRequestsForTest(*backend); + Cas::CasOperation op = requests.admit(); + const auto current = op.read(slotKey(), Cas::Retry::standard()); + ASSERT_TRUE(current.has_value()); + Cas::MountLease lease = Cas::decodeMountLease(current->bytes); + change(lease); + ASSERT_TRUE(std::holds_alternative( + op.replace(slotKey(), Cas::encodeMountLease(lease), current->etag, Cas::Retry::standard()))); + } + + void moveSlotOnce() + { + on_snapshot = [this] { moveSlot(); }; + } +}; + +/// Runs `body` on a raw thread inside a registered query and returns the error code it threw (0 for none). +int inQueryThrownCode(const std::function & body) +{ + int code = 0; + std::thread worker([&] + { + ThreadStatus thread_status; + Cas::tests::CasKillableQuery query(getContext().context); + try + { + body(query); + } + catch (const Exception & e) + { + code = e.code(); + } + }); + worker.join(); + return code; +} + +struct StopArm +{ + const char * name; + /// No stop at all: the outcome a stopped query must also get. + bool live = false; + bool background = false; + std::exception_ptr cause; +}; + +std::vector backgroundStopArms() +{ + return {StopArm{.name = "background", .live = false, .background = true, .cause = nullptr}}; +} + +/// The live arm comes first: the stopped query arms compare against its outcome. +std::vector queryStopArms() +{ + return {StopArm{.name = "live", .live = true, .background = false, .cause = nullptr}, + StopArm{.name = "kill", .live = false, .background = false, .cause = nullptr}, + StopArm{.name = "timeout", .live = false, .background = false, + .cause = std::make_exception_ptr(Exception(ErrorCodes::TIMEOUT_EXCEEDED, "the query timed out"))}}; +} + +/// Runs `body` inside a registered query with a background owner; the `stop` it gets stops the arm's owner. +int inQueryStoppedBy(const StopArm & arm, const std::function & stop)> & body) +{ + return inQueryThrownCode([&](Cas::tests::CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = backgroundOwnerStoppedBy(background_stopped); + body([&arm, &query, background_stopped] + { + if (arm.live) + return; + if (arm.background) + *background_stopped = true; + else + query.kill(arm.cause); + }); + }); +} + +/// Stops each arm's owner before the first confirm pause, during it with the deadline reached, or during it with time +/// left for another pass. +void expectStopDuringConfirmPause(const std::vector & arms) +{ + enum class Where { BeforePause, InPauseAtDeadline, InPauseWithTimeLeft }; + for (const Where where : {Where::BeforePause, Where::InPauseAtDeadline, Where::InPauseWithTimeLeft}) + { + std::optional live_answer; + for (const auto & arm : arms) + { + SCOPED_TRACE(String(arm.name) + "/" + std::to_string(static_cast(where))); + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + std::function stop; + if (where == Where::BeforePause) + { + fx.on_snapshot = [&] + { + fx.moveSlot(); + stop(); + }; + fx.pause_advance_ms = fx.window_ms; + } + else + { + fx.moveSlotOnce(); + fx.on_pause = [&] + { + if (auto once = std::exchange(stop, nullptr)) + once(); + }; + fx.pause_advance_ms = where == Where::InPauseAtDeadline ? fx.window_ms : 0; + } + + std::optional answer; + const int code = inQueryStoppedBy(arm, [&](const std::function & stop_owner) + { + stop = stop_owner; + answer = fx.access->confirmCopySource(*fx.source); + }); + + if (arm.background) + { + EXPECT_EQ(code, ErrorCodes::ABORTED) << "the poll answered a stopped background owner"; + EXPECT_EQ(fx.pauses.load(), where == Where::BeforePause ? 0u : 1u); + continue; + } + EXPECT_EQ(code, 0); + ASSERT_TRUE(answer.has_value()); + if (arm.live) + { + EXPECT_NE(*answer, Cas::ConfirmAnswer::Yes) << "positive control: the slot moved"; + live_answer = answer; + continue; + } + EXPECT_EQ(answer, live_answer) << "a stopped query gets the live owner's answer"; + EXPECT_GE(fx.pauses.load(), 1u) << "the poll went on past the stop"; + } + } +} + +} + +/// A stopped background owner never receives `Unknown` from the poll, wherever the stop lands. +TEST(CASPartFolderAccess, BackgroundStopDuringConfirmPauseThrowsNotUnknown) +{ + expectStopDuringConfirmPause(backgroundStopArms()); +} + +/// The confirm poll is no safe point for a query: a killed or timed-out query gets what a live owner gets. +TEST(CASPartFolderAccess, KilledQuerysConfirmPollGetsTheLiveAnswer) +{ + expectStopDuringConfirmPause(queryStopArms()); +} + +namespace +{ + +/// A source pinned to a table a remount replaced: its `Unknown` is one-way. +void expectOneWayUnknownForStoppedOwner(const std::vector & arms) +{ + for (const auto & arm : arms) + { + SCOPED_TRACE(arm.name); + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + fx.rewriteSlot([](Cas::MountLease & lease) + { + lease.gc_fenced = true; + lease.seq += 1; + }); + ASSERT_TRUE(fx.store->tryRemountOnce()); + Cas::ConfirmAnswer answer = Cas::ConfirmAnswer::Yes; + + const int code = inQueryStoppedBy(arm, [&](const std::function & stop) + { + stop(); + answer = fx.access->confirmCopySource(*fx.source); + }); + + EXPECT_EQ(code, arm.background ? ErrorCodes::ABORTED : 0); + if (!arm.background) + EXPECT_EQ(answer, Cas::ConfirmAnswer::Unknown) << "the pinned table is retired"; + EXPECT_EQ(fx.pauses.load(), 0u); + } +} + +} + +/// A one-way `Unknown` is not handed to a stopped background owner. +TEST(CASPartFolderAccess, BackgroundStoppedOwnerIsNotHandedAOneWayUnknown) +{ + expectOneWayUnknownForStoppedOwner(backgroundStopArms()); +} + +/// A live owner and a killed or timed-out query get the one-way `Unknown`. +TEST(CASPartFolderAccess, KilledQueryIsHandedTheOneWayUnknown) +{ + expectOneWayUnknownForStoppedOwner(queryStopArms()); +} + +namespace +{ + +/// A rename whose copy confirm meets a moved slot; each arm's owner stops in the confirm pause. +void expectStoppedRenameOutcome(const std::vector & arms) +{ + std::optional live_code; + std::optional live_source_kept; + for (const auto & arm : arms) + { + SCOPED_TRACE(arm.name); + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + const Cas::RootNamespace to{"srv/t2"}; + fx.access->setHookForTest(Cas::CachedPartFolderAccess::TestHook::BeforeDestinationPublish, [&] + { + publishPart(fx.store, to, "dst", {inlineEntry("f", "live")}); + }); + SCOPE_EXIT({ fx.access->setHookForTest(Cas::CachedPartFolderAccess::TestHook::BeforeDestinationPublish, nullptr); }); + fx.moveSlotOnce(); + fx.pause_advance_ms = fx.window_ms; + std::function stop; + size_t journal_at_stop = 0; + fx.on_pause = [&] + { + journal_at_stop = fx.backend->journal().size(); + if (auto once = std::exchange(stop, nullptr)) + once(); + }; + + const int code = inQueryStoppedBy(arm, [&](const std::function & stop_owner) + { + stop = stop_owner; + fx.access->republishRef({fx.ns, "src"}, {to, "dst"}); + }); + const auto journal = fx.backend->journal(); + size_t destination_reads_after_stop = 0; + for (size_t i = journal_at_stop; i < journal.size(); ++i) + for (const String & key : journal[i].keys) + destination_reads_after_stop += journal[i].verb == JournalVerb::Read && key.contains("/manifests/" + to.string() + "/"); + const bool source_kept = fx.access->existsRef({fx.ns, "src"}, Cas::Freshness::ForceFresh); + + if (arm.background) + { + EXPECT_EQ(code, ErrorCodes::ABORTED) << "the rename was settled for a stopped background owner"; + EXPECT_EQ(destination_reads_after_stop, 0u) << "the destination was read again after the stop"; + EXPECT_TRUE(source_kept) << "the source was dropped"; + continue; + } + if (arm.live) + { + EXPECT_GT(destination_reads_after_stop, 0u) << "positive control: the live owner reads the destination again"; + EXPECT_EQ(code, 0) << "positive control: the live owner takes the equal committed destination"; + EXPECT_FALSE(source_kept) << "positive control: the live owner's rename drops the source"; + live_code = code; + live_source_kept = source_kept; + continue; + } + ASSERT_TRUE(live_code.has_value()) << "the live arm runs first"; + EXPECT_EQ(code, *live_code) << "a stopped query's rename ends as a live owner's"; + EXPECT_EQ(source_kept, *live_source_kept); + EXPECT_GT(destination_reads_after_stop, 0u); + } +} + +} + +/// A stopped background owner leaves the destination unread and the source in place: an `Unknown` answer would +/// send `republishRef` to read the destination again and take an equal committed one as the result. +TEST(CASPartFolderAccess, BackgroundStoppedRenameDoesNotReadDestinationAgainOrDropSource) +{ + expectStoppedRenameOutcome(backgroundStopArms()); +} + +/// A killed or timed-out query's rename reads the destination again and ends as a live owner's does. +TEST(CASPartFolderAccess, KilledQuerysRenameEndsAsALiveOwnersDoes) +{ + expectStoppedRenameOutcome(queryStopArms()); +} + +/// A stopped owner's first pass still sends its slot read: only a pass after the first is refused. +TEST(CASPartFolderAccess, StoppedOwnersFirstConfirmPassStillReadsTheSlot) +{ + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + const uint64_t reads_before = fx.backend->getCount(fx.slotKey()); + Cas::ConfirmAnswer answer = Cas::ConfirmAnswer::Unknown; + + const int code = inQueryThrownCode([&](Cas::tests::CasKillableQuery & query) + { + query.kill(); + answer = fx.access->confirmCopySource(*fx.source); + }); + + EXPECT_EQ(code, 0); + EXPECT_EQ(answer, Cas::ConfirmAnswer::Yes); + EXPECT_EQ(fx.backend->getCount(fx.slotKey()) - reads_before, 1u) << "the first pass did not read the slot"; +} + +/// A slot read that fails with the owner's verdict is not an unreadable slot: it is not counted as a refusal. +TEST(CASPartFolderAccess, StoppedOwnersFailedSlotReadIsNotCountedAsUnreadable) +{ + CopyConfirmPollFixture fx; + ASSERT_TRUE(fx.source.has_value()); + Cas::tests::CasKillableQuery * running = nullptr; + fx.on_snapshot = [&] + { + Cas::CasRequests requests = DB::Cas::tests::openRequestsForTest(*fx.backend); + Cas::CasOperation op = requests.admit(); + ASSERT_EQ(op.removeCurrent(fx.slotKey(), Cas::Retry::standard()), Cas::Removal::Removed); + running->kill(); + }; + const uint64_t before = ProfileEvents::global_counters[ProfileEvents::CASRelinkConfirmRefusedSlotUnreadable]; + + const int code = inQueryThrownCode([&](Cas::tests::CasKillableQuery & query) + { + running = &query; + fx.access->confirmCopySource(*fx.source); + }); + + EXPECT_EQ(code, ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRelinkConfirmRefusedSlotUnreadable] - before, 0u); +} diff --git a/src/Disks/tests/gtest_cas_part_write.cpp b/src/Disks/tests/gtest_cas_part_write.cpp index 5e09d2ea7ae77..03a010b2b0111 100644 --- a/src/Disks/tests/gtest_cas_part_write.cpp +++ b/src/Disks/tests/gtest_cas_part_write.cpp @@ -1,11 +1,15 @@ #include #include +#include #include #include #include +#include #include +#include #include #include +#include #include #include #include @@ -16,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -25,6 +30,8 @@ #include #include #include +#include +#include #include #include #include "config.h" @@ -46,6 +53,8 @@ extern const int ABORTED; extern const int CORRUPTED_DATA; extern const int LIMIT_EXCEEDED; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; +extern const int TIMEOUT_EXCEEDED; extern const int UNKNOWN_EXCEPTION; } @@ -2520,6 +2529,8 @@ class BlobPutFaultBackend final : public InMemoryBackend using InMemoryBackend::head; int fault_count = 0; /// remaining ambiguous faults on matching create attempts bool land_despite_fault = false; /// the faulted attempt's own write actually lands (response lost) + bool fault_is_not_std_exception = false; /// the injected fault does not derive from `std::exception` + std::exception_ptr fault; /// thrown instead of the ambiguous timeout when set int publish_stream_attempts = 0; /// unconditional streaming publications observed int publish_copy_attempts = 0; /// unconditional native-copy publications observed int blob_head_attempts = 0; /// transaction-level blob observations @@ -2556,12 +2567,20 @@ class BlobPutFaultBackend final : public InMemoryBackend InMemoryBackend::publish(request, access); else if (const auto * streaming = std::get_if(&request.publication)) (void)streaming->open_payload(); + if (fault_is_not_std_exception) + throw NotAStdException{}; + if (fault) + std::rethrow_exception(fault); throw Poco::TimeoutException("BlobPutFaultBackend: simulated ambiguous publication (response lost)"); } InMemoryBackend::publish(request, access); } private: + struct NotAStdException + { + }; + static bool isBlobBodyKey(const String & key) { return key.find("/blobs/") != String::npos && !key.ends_with(".meta"); @@ -2696,16 +2715,10 @@ TEST(CASPartWrite, EveryPhysicalPublicationMintsAFreshIncarnationTag) << "a repeated incarnation_tag is a repeated incarnation: GC's condemn would name the live body"; } -/// The publication loop captures ONE bound before it starts, and every verb of every iteration shares -/// it -- so eight iterations cannot spend eight request windows. Here each ambiguous -/// publication burns four ninths of the window on the injected clock, so the third one carries the loop -/// past the window it captured and the next iteration's HEAD refuses to start. The insert is refused as -/// retry-later, which is what a caller can act on; the alternative is a single blob upload sitting on -/// the request for twenty-five minutes. The eight-attempt cap stays as the secondary bound. -/// -/// The throw and the publication count are what fail if the shared bound regresses: without it this -/// same fixture publishes a fourth time and the call SUCCEEDS. -TEST(CASPartWrite, EnsureBlobPresentIsBoundedByTheOneWindowItCaptured) +/// Each request of the publication loop has a window of its own, so a publication that burns four ninths +/// of a window does not shorten the next request. The loop ends at the eight-publication cap and the +/// retry-later error it throws carries the last publication's message. +TEST(CASPartWrite, EnsureBlobPresentEndsAtTheEighthAmbiguousPublication) { auto b = std::make_shared(); auto s = openBlobFaultPool(b); @@ -2721,16 +2734,74 @@ TEST(CASPartWrite, EnsureBlobPresentIsBoundedByTheOneWindowItCaptured) build->precommitAdd(ns, "part_blob_long_loop", id); int payload_streams = 0; - b->fault_count = 3; - expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] + b->fault_count = 8; + String message; + try { (void)build->putBlob(idOf(payload), countingSource(payload, payload_streams)); - }); + ADD_FAILURE() << "the eighth ambiguous publication must end the loop"; + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::NETWORK_ERROR); + message = e.message(); + } + + EXPECT_EQ(b->publish_stream_attempts, 8); + EXPECT_NE(message.find("simulated ambiguous publication"), String::npos) << message; + /// More than three request windows: no window spans the loop's requests. + EXPECT_GT(now->load(), kDefaultRequestWindowMs * 3); +} + +/// The eighth publication is the last one the loop may make: a body that lands on it is committed. +TEST(CASPartWrite, ABodyPublishedOnTheEighthAttemptCommits) +{ + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-eighth"; + auto build = startBuildFor(s, ns, "part_blob_eighth"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload)}); + build->precommitAdd(ns, "part_blob_eighth", id); + + int payload_streams = 0; + b->fault_count = 7; + const PutBlobResult res = build->putBlob(idOf(payload), countingSource(payload, payload_streams)); + + EXPECT_EQ(res.size, payload.size()); + EXPECT_EQ(b->publish_stream_attempts, 8); + EXPECT_NO_THROW(build->promote(ns, "part_blob_eighth", build->buildId(), id)); +} + +/// A fault that is not a `std::exception` ends the loop like any other ambiguous publication, and +/// the error still says what the last publication failed with. +TEST(CASPartWrite, ANonStdExceptionOnTheEighthPublicationKeepsItsMessage) +{ + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-non-std"; + auto build = startBuildFor(s, ns, "part_blob_non_std"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload)}); + build->precommitAdd(ns, "part_blob_non_std", id); + + int payload_streams = 0; + b->fault_count = 8; + b->fault_is_not_std_exception = true; + String message; + try + { + (void)build->putBlob(idOf(payload), countingSource(payload, payload_streams)); + ADD_FAILURE() << "the eighth ambiguous publication must end the loop"; + } + catch (const DB::Exception & e) + { + EXPECT_EQ(e.code(), DB::ErrorCodes::NETWORK_ERROR); + message = e.message(); + } - EXPECT_EQ(b->publish_stream_attempts, 3) << "the fourth iteration must not start a publication"; - /// The clock is past the captured deadline when the loop stops, which is what stopped it: two - /// publications leave it inside the window and the third carries it past. - EXPECT_GE(now->load(), kDefaultRequestWindowMs); + EXPECT_EQ(b->publish_stream_attempts, 8); + EXPECT_NE(message.find("NotAStdException"), String::npos) << message; } namespace @@ -3019,6 +3090,9 @@ TEST(CASPartWriteTxn, StageManifestGiveUpTextCoversEveryOutcome) {{.why = Why::Unresolved, .deadline_source = Source::Policy, .sent_any = true, .last_seen = NotObserved{}, .attempts_sent = 5}, "5 attempt(s) sent and the resolving read did not complete (nothing observed)", true}, + {{.why = Why::Unresolved, .deadline_source = Source::Policy, .sent_any = true, .last_seen = ProvenAbsent{}, + .attempts_sent = 1}, + "1 attempt(s) sent and not sent again after the resolving read found absent", true}, {{.why = Why::Unresolved, .deadline_source = Source::Policy, .sent_any = false, .last_seen = ProvenAbsent{}}, "was not sent: a read of the current object did not complete (absent)", false}, }; @@ -3069,3 +3143,348 @@ TEST(CASPartWriteTxn, StageManifestSentThenGaveUpSaysUncertain) EXPECT_NE(text.find("UNCERTAIN"), String::npos) << text; EXPECT_NE(text.find(fmt::format("{} attempt(s) sent", b->put_attempts)), String::npos) << text; } + +namespace +{ + +/// Runs `body` on a fresh thread with a `ThreadStatus` and a killable query attached, and returns the +/// code `body` threw, or 0. +int codeOnQueryThread(const std::function & body) +{ + int code = 0; + std::thread worker([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + try + { + body(query); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + catch (...) + { + code = -1; + } + }); + worker.join(); + return code; +} + +enum class StopBeforeSwap : uint8_t { Query, Background, LeaseLoss }; + +/// Stops the owner after the upload and before its result is recorded, on the fan-out merge and on the serial path. +void expectStopBeforeDependencySwap(std::initializer_list stop_kinds) +{ + using Stop = StopBeforeSwap; + for (const bool fanout : {true, false}) + { + for (const Stop stop_kind : stop_kinds) + { + const char * stop_name = stop_kind == Stop::Query ? "query kill" + : stop_kind == Stop::Background ? "background stop" + : "lease loss"; + SCOPED_TRACE(fmt::format("{} path, {}", fanout ? "fan-out" : "serial", stop_name)); + auto b = std::make_shared(); + auto s = openPool(b); + const String payload = "stop-before-dependency-swap"; + const BlobRef ref = idOf(payload); + auto build = precommittedBuildForPayload(s, RootNamespace{"srv1/stop-before-swap"}, "part", payload); + const auto deps_before = build->depsSnapshotForTest(); + + const int code = codeOnQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + std::atomic background_stopped{false}; + const auto background = DB::Cas::OwnerScope::background([&] + { + if (background_stopped.load()) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + const auto stop = [&] + { + switch (stop_kind) + { + case Stop::Query: + query.kill(); + return; + case Stop::Background: + background_stopped = true; + return; + case Stop::LeaseLoss: + s->tripMountLost(); + DB::Cas::tests::rearmMountFenceAfterAnomalyForTest(s); + return; + } + }; + if (fanout) + { + const BlobUploadResult result + = build->uploadBlobDetached(BlobUploadRequest{ref, BlobSource::fromString(payload), payload.size()}); + build->setAdoptionHookForTest([&](size_t) { stop(); }); + build->mergeBlobUploadResults(std::span(&result, 1)); + } + else + { + build->setAdoptionHookForTest([&](size_t) { stop(); }); + (void)build->putBlob(ref, BlobSource::fromString(payload)); + } + }); + + switch (stop_kind) + { + case Stop::Query: + EXPECT_EQ(code, 0) << "a killed query's adoption proceeds"; + EXPECT_NE(build->depsSnapshotForTest(), deps_before) << "the uploaded body was not adopted"; + EXPECT_NE(build->dependencyProof(ref), std::nullopt); + break; + case Stop::Background: + case Stop::LeaseLoss: + EXPECT_EQ(code, stop_kind == Stop::Background ? DB::ErrorCodes::ABORTED : DB::ErrorCodes::NETWORK_ERROR); + EXPECT_EQ(build->depsSnapshotForTest(), deps_before) << "the dependency was adopted after the stop"; + EXPECT_EQ(build->dependencyProof(ref), std::nullopt); + break; + } + } + } +} + +} + +/// A background stop or a lease loss that lands before the dependency swap leaves the build without the dependency. +TEST(CASPartWrite, BackgroundStopOrLeaseLossBeforeDependencySwapSkipsAdoption) +{ + expectStopBeforeDependencySwap({StopBeforeSwap::Background, StopBeforeSwap::LeaseLoss}); +} + +/// Adoption sends nothing and is no safe point, so a killed query adopts the body it uploaded. +TEST(CASPartWrite, KilledQueryAdoptsTheUploadedBody) +{ + expectStopBeforeDependencySwap({StopBeforeSwap::Query}); +} + +/// The body landed and its reply was lost while the query timed out. The stop ends the upload with the +/// publication's own failure: no further publication, and no observation that would adopt the landed body. A +/// failure that is not a `std::exception` passes the request engine unclassified, so both exception types are +/// covered. +TEST(CASPartWrite, OwnerTimeoutAfterLandedBodyIsNotAdopted) +{ + for (const bool std_exception : {true, false}) + { + SCOPED_TRACE(std_exception ? "std::exception" : "not a std::exception"); + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-owner-timeout"; + auto build = startBuildFor(s, ns, "part_owner_timeout"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload)}); + build->precommitAdd(ns, "part_owner_timeout", id); + + b->fault_count = 1; + b->land_despite_fault = true; + b->fault_is_not_std_exception = !std_exception; + const int code = codeOnQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + b->on_publish = [&] + { + query.kill(std::make_exception_ptr(DB::Exception(DB::ErrorCodes::TIMEOUT_EXCEEDED, "the query's timeout"))); + }; + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + }); + b->on_publish = {}; + + EXPECT_EQ(code, -1) << "the lost reply's own exception, which is not a DB::Exception, not the query's timeout"; + EXPECT_EQ(b->publish_stream_attempts, 1) << "no further publication"; + EXPECT_EQ(b->blob_head_attempts, 1) << "the landed body was observed again"; + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt) << "the landed body was adopted"; + OperationForTest op(*b); + EXPECT_TRUE((*op).head(s->layout().blobKey(idOf(payload)), Retry::once()).has_value()) + << "the landed body stays as debris"; + } +} + +/// A publication that failed while the query was live, then a kill in the pause before the retry: the retry's +/// `HEAD` is not sent, and the upload ends with the failed publication's own error, not the query's. +TEST(CASPartWrite, KillInPublicationRetryPauseKeepsThePublicationFailure) +{ + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-kill-in-retry-pause"; + auto build = startBuildFor(s, ns, "part_kill_in_pause"); + build->precommitAdd(ns, "part_kill_in_pause", build->stageManifest({blobManifestEntry("a.bin", payload)})); + b->fault_count = 1; + + String failure; + std::thread killed([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + s->mountRequests().setSleepFnForTest([&](uint64_t) + { + if (b->publish_stream_attempts > 0) + query.kill(); + }); + try + { + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + } + catch (...) + { + failure = DB::getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + s->mountRequests().setSleepFnForTest([](uint64_t) {}); + }); + killed.join(); + + EXPECT_NE(failure.find("simulated ambiguous publication"), String::npos) << failure; + EXPECT_EQ(b->blob_head_attempts, 1) << "the retry's HEAD was sent after the kill"; + EXPECT_EQ(b->publish_stream_attempts, 1); + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt); +} + +#if USE_AWS_S3 +/// A credential refusal of a publication, then a kill in the pause before the retry: the upload ends as retry-later +/// carrying the refusal, not with the raw refusal, which would read as damage. +TEST(CASPartWrite, KillBeforeAPublicationsCredentialRetryEndsAsRetryLater) +{ + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-kill-before-credential-retry"; + auto build = startBuildFor(s, ns, "part_kill_before_credential_retry"); + build->precommitAdd(ns, "part_kill_before_credential_retry", + build->stageManifest({blobManifestEntry("a.bin", payload)})); + b->fault_count = 1; + b->fault = std::make_exception_ptr( + DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); + + int code = 0; + String failure; + std::thread killed([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + s->mountRequests().setSleepFnForTest([&](uint64_t) + { + if (b->publish_stream_attempts > 0) + query.kill(); + }); + try + { + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + } + catch (const DB::Exception & e) + { + code = e.code(); + failure = e.message(); + } + s->mountRequests().setSleepFnForTest([](uint64_t) {}); + }); + killed.join(); + + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << failure; + EXPECT_NE(failure.find("the store answered AccessDenied"), String::npos) << failure; + EXPECT_NE(failure.find("credential retry"), String::npos) << failure; + EXPECT_EQ(b->publish_stream_attempts, 1); + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt); +} + +/// A credential refusal of a publication whose query was killed during it ends as retry-later carrying the refusal, +/// as a kill in the pause does. A query's stored cause stays the same object, even a credential-class one. +TEST(CASPartWrite, KillDuringAPublicationsCredentialRefusalEndsAsRetryLater) +{ + for (const bool stored_cause : {false, true}) + { + SCOPED_TRACE(stored_cause ? "the query's stored cause" : "the store's refusal"); + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-kill-during-credential-refusal"; + auto build = startBuildFor(s, ns, "part_kill_during_credential_refusal"); + build->precommitAdd(ns, "part_kill_during_credential_refusal", + build->stageManifest({blobManifestEntry("a.bin", payload)})); + b->fault_count = 1; + b->fault = std::make_exception_ptr(DB::S3Exception( + stored_cause ? "the query's stored cause" : "the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, + "AccessDenied")); + + int code = 0; + String failure; + std::exception_ptr caught; + std::thread killed([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + b->on_publish = [&] { query.kill(stored_cause ? b->fault : nullptr); }; + try + { + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + } + catch (const DB::Exception & e) + { + code = e.code(); + failure = e.message(); + caught = std::current_exception(); + } + }); + killed.join(); + + EXPECT_EQ(b->publish_stream_attempts, 1); + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt); + if (stored_cause) + { + EXPECT_EQ(caught, b->fault) << "the stored cause was replaced: " << failure; + continue; + } + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR) << failure; + EXPECT_NE(failure.find("the store answered AccessDenied"), String::npos) << failure; + EXPECT_NE(failure.find("credential retry"), String::npos) << failure; + } +} +#endif + +/// The serial upload of a killed query sends its `HEAD`. When it finds no reusable body, the upload ends with the +/// query's error before the publication starts; a reusable body is adopted, since adoption starts no new work. +TEST(CASPartWrite, KilledQuerysUploadStartsNoPublication) +{ + for (const bool body_present : {false, true}) + { + SCOPED_TRACE(body_present ? "a reusable body is present" : "no body"); + auto b = std::make_shared(); + auto s = openBlobFaultPool(b); + const RootNamespace ns{"srv/tbl"}; + const String payload = "blob-payload-killed-before-publication"; + if (body_present) + { + auto earlier = startBuildFor(s, ns, "part_earlier"); + earlier->precommitAdd(ns, "part_earlier", earlier->stageManifest({blobManifestEntry("a.bin", payload)})); + (void)earlier->putBlob(idOf(payload), BlobSource::fromString(payload)); + } + auto build = startBuildFor(s, ns, "part_killed"); + const ManifestId id = build->stageManifest({blobManifestEntry("a.bin", payload)}); + build->precommitAdd(ns, "part_killed", id); + const int publications_before = b->publish_stream_attempts; + const int heads_before = b->blob_head_attempts; + + const int code = codeOnQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + query.kill(); + (void)build->putBlob(idOf(payload), BlobSource::fromString(payload)); + }); + + EXPECT_EQ(b->blob_head_attempts - heads_before, 1) << "the HEAD is a first attempt, sent for a killed query"; + EXPECT_EQ(b->publish_stream_attempts, publications_before) << "a publication started after the kill"; + if (body_present) + { + EXPECT_EQ(code, 0); + EXPECT_NE(build->dependencyProof(idOf(payload)), std::nullopt) << "the reusable body was not adopted"; + } + else + { + EXPECT_EQ(code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(build->dependencyProof(idOf(payload)), std::nullopt); + } + } +} diff --git a/src/Disks/tests/gtest_cas_pool.cpp b/src/Disks/tests/gtest_cas_pool.cpp index 47c1d5b260ffc..1f1ea69929cc1 100644 --- a/src/Disks/tests/gtest_cas_pool.cpp +++ b/src/Disks/tests/gtest_cas_pool.cpp @@ -202,7 +202,7 @@ ManifestId publishPartWithEntries( } /// The disk's request window reaches every request plane a pool exposes, not only the one a give-up -/// test happens to use. A plane built with the default window would freeze a 120 s deadline here. +/// test happens to use. A plane built with the default window would bind a 120 s deadline here. TEST(CASPool, EveryExposedRequestPlaneTakesTheConfiguredRequestWindow) { constexpr uint64_t window_ms = 20'000; @@ -217,9 +217,10 @@ TEST(CASPool, EveryExposedRequestPlaneTakesTheConfiguredRequestWindow) for (const auto & [name, plane] : planes) { DB::Cas::CasOperation op = plane->admit(); - const DB::Cas::Retry frozen = op.freeze(DB::Cas::Retry::standard()); - ASSERT_TRUE(frozen.policy_deadline_ms) << name; - EXPECT_EQ(*frozen.policy_deadline_ms, clock->nowMs() + window_ms) << name; + plane->setAttemptReservationForTest(window_ms - 1'000); + EXPECT_NO_THROW(op.head("k", DB::Cas::Retry::standard())) << name << ": sent when one envelope fits the window"; + plane->setAttemptReservationForTest(window_ms + 1'000); + EXPECT_THROW(op.head("k", DB::Cas::Retry::standard()), DB::Exception) << name << ": refused unsent past the window"; } } diff --git a/src/Disks/tests/gtest_cas_pool_meta.cpp b/src/Disks/tests/gtest_cas_pool_meta.cpp index bd43763bafafa..0eb79caff1320 100644 --- a/src/Disks/tests/gtest_cas_pool_meta.cpp +++ b/src/Disks/tests/gtest_cas_pool_meta.cpp @@ -34,7 +34,7 @@ CasRequests makeRequests(BackendPtr backend, FakeClock & clock, Fence fence = Fe } -TEST(CASPoolMeta, AdmitOrValidateEndsAtTheDeadlineUnderPerpetualConflict) +TEST(CASPoolMeta, AdmitOrValidateEndsAfterAHundredDecisionsUnderPerpetualConflict) { FakeClock clock; auto backend = std::make_shared(); @@ -53,10 +53,12 @@ TEST(CASPoolMeta, AdmitOrValidateEndsAtTheDeadlineUnderPerpetualConflict) const String key = layout.poolMetaKey(); EXPECT_TRUE(clock.sleeps.empty()); /// nothing paced yet -- the trailing check below is about THIS call bool inside_hook = false; + size_t decisions = 0; backend->onBeforeWrite(key, [&] { if (inside_hook) return; + ++decisions; inside_hook = true; auto hook_requests = DB::Cas::tests::openRequestsForTest(BackendPtr(backend)); auto hook_op = hook_requests.admit(); @@ -65,18 +67,17 @@ TEST(CASPoolMeta, AdmitOrValidateEndsAtTheDeadlineUnderPerpetualConflict) inside_hook = false; }); - /// `orThrow`'s `GaveUp{Deadline}` arm throws exactly `NETWORK_ERROR` (`throwCasWriteRetryLater`), - /// pinning the deadline outcome apart from the two failures a wrong migration could also throw as - /// a `DB::Exception` here: `LOGICAL_ERROR` (the absence branch) or `BAD_ARGUMENTS` (`allow_new` - /// plumbing regressed). + /// The cap text sets this apart from the two failures a wrong migration could also throw here: + /// `LOGICAL_ERROR` (the absence branch) or `BAD_ARGUMENTS` (`allow_new` plumbing regressed). auto admit_op = requests.admit(); - expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 decisions", [&] { (void)PoolMeta::createOrValidate( admit_op, layout, 256, /*gc_shards=*/1, BlobHashAlgo::XXH3_128, /*allow_new=*/true, /*allow_mint=*/false); }); - /// Bounded by the deadline, not a live-lock: it paced its retries rather than spinning. + EXPECT_EQ(decisions, kCasMaxDecisions); + /// It paced its decisions rather than spinning. EXPECT_FALSE(clock.sleeps.empty()); } diff --git a/src/Disks/tests/gtest_cas_recovery_streaming.cpp b/src/Disks/tests/gtest_cas_recovery_streaming.cpp index 5b087b7385328..96b6f76584e1c 100644 --- a/src/Disks/tests/gtest_cas_recovery_streaming.cpp +++ b/src/Disks/tests/gtest_cas_recovery_streaming.cpp @@ -6,6 +6,8 @@ #include #include #include "cas_test_helpers.h" +#include "cas_killable_query.h" +#include #include #include @@ -18,6 +20,7 @@ namespace DB::ErrorCodes { +extern const int ABORTED; extern const int CORRUPTED_DATA; extern const int S3_ERROR; } @@ -399,6 +402,106 @@ TEST(CASRecoveryStreaming, CorruptObjectFailsFast) EXPECT_EQ(backend->refs_list_count.load(), 0) << "durable corruption must not trigger recovery LIST"; } +/// A removal under a background owner, parked behind another caller's recovery, leaves at its owner's stop while that +/// recovery is still running; a killed query parked beside it keeps waiting and then reads the recovered table. +TEST(CASRecoveryStreaming, AStoppedBackgroundOwnerLeavesTheWaitForAnotherRecovery) +{ + auto backend = std::make_shared(); + seedPoolMetaForRestart(*backend); + const Layout layout("p"); + const RootNamespace ns{"00/aa@cas@"}; + publishCommittedTransition(*backend, layout, ns, "x", std::nullopt, mref(1)); + + auto store = openPoolForTest(backend); + backend->refs_prefix = layout.namespaceStreamPrefix(fixture::fixtureLife(ns)); + std::promise entered_promise; + std::atomic get_entered{false}; + std::promise release_promise; + std::shared_future release_future = release_promise.get_future().share(); + backend->target_log_key = layout.refLogKey(fixture::fixtureLife(ns), RefTxnId{1, 1}); + backend->on_first_target_get = [&] + { + if (!get_entered.exchange(true)) + entered_promise.set_value(); + release_future.wait(); + }; + backend->armed = true; + + std::exception_ptr recovering_error; + std::thread recovering([&] + { + try + { + store->listRefs(ns); + } + catch (...) + { + recovering_error = std::current_exception(); + } + }); + entered_promise.get_future().wait(); + + std::atomic stop{false}; + std::atomic removal_code{-1}; + std::thread removal([&] + { + const auto owner = OwnerScope::background([&] + { + if (stop.load()) + throw DB::Exception(DB::ErrorCodes::ABORTED, "server shutdown"); + }); + try + { + (void)store->dropNamespace(ns); + removal_code = 0; + } + catch (const DB::Exception & e) + { + removal_code = e.code(); + } + }); + const bool removal_parked = pollUntil([&] { return store->refRecoveryWaitersForTest(ns) >= 1; }); + + std::atomic query_done{false}; + std::atomic query_code{-1}; + std::thread query_reader([&] + { + onKillableQueryThread([&](CasKillableQuery & query) + { + query.kill(); + try + { + store->listRefs(ns); + query_code = 0; + } + catch (const DB::Exception & e) + { + query_code = e.code(); + } + }); + query_done = true; + }); + const bool query_parked = pollUntil([&] { return store->refRecoveryWaitersForTest(ns) >= 2; }); + + stop = true; + const bool removal_left = pollUntil([&] { return removal_code.load() != -1; }); + const bool query_still_waiting = !query_done.load(); + + release_promise.set_value(); + recovering.join(); + removal.join(); + query_reader.join(); + + ASSERT_TRUE(removal_parked) << "the removal never reached the wait"; + ASSERT_TRUE(query_parked) << "the killed query never reached the wait"; + EXPECT_TRUE(removal_left) << "the stopped removal waited for the other recovery"; + EXPECT_EQ(removal_code.load(), DB::ErrorCodes::ABORTED); + EXPECT_TRUE(query_still_waiting) << "a killed query is not a stop for this wait"; + EXPECT_EQ(query_code.load(), 0); + EXPECT_FALSE(recovering_error); + EXPECT_TRUE(store->resolveRef(ns, "x").has_value()); +} + /// Test 14 (concurrent-waiter leg): while one caller is blocked in recovery's unlocked exact-log GET, /// a second caller for the same table parks on `recovery_cv` and is woken exactly once when recovery /// completes. Neither caller may race an independent stream LIST. diff --git a/src/Disks/tests/gtest_cas_ref_catalog.cpp b/src/Disks/tests/gtest_cas_ref_catalog.cpp index 686cb22de8200..259f803e4e7d7 100644 --- a/src/Disks/tests/gtest_cas_ref_catalog.cpp +++ b/src/Disks/tests/gtest_cas_ref_catalog.cpp @@ -1,6 +1,7 @@ #include "cas_format_test_battery.h" #include "cas_test_helpers.h" #include +#include #include #include #include @@ -13,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -64,6 +66,7 @@ class GcRoundPlanSignatureAccess namespace DB::ErrorCodes { + extern const int ABORTED; extern const int CORRUPTED_DATA; extern const int LOGICAL_ERROR; extern const int LIMIT_EXCEEDED; @@ -187,6 +190,20 @@ String renderJournal(const std::vector & journal) return rendered; } +/// The next `count` writes of `key` are refused as lost races, with the store unchanged. The first lost race of a call +/// is retried at once, so a test that needs a pause refuses two. +void refuseNextWrites(InMemoryBackend & backend, const String & key, int count) +{ + auto left = std::make_shared(count); + backend.onBeforeWrite(key, [&backend, key, left] + { + if (*left == 0) + return; + --*left; + backend.refuseNextWrite(key); + }); +} + /// Lands a competing catalog body under the erase's own attempt and withdraws this actor's admission /// with it -- the concurrent winner an erase has to be resolved against, driven deterministically and /// without a second thread. @@ -1115,13 +1132,12 @@ TEST(CASRefCatalogDeathTest, CasUpdateThrowsOnVanishMidRetryInsteadOfReplacingTh } #endif -/// Persistent contention ends at the write policy's DEADLINE, with the typed retryable error -- not -/// after a fixed number of unslept iterations, and not in an infinite spin. `mutate` re-arms the -/// one-shot conflict injection on every call, so every attempt is refused; the injected clock reaches -/// the deadline without the test sleeping at all. -TEST(CASRefCatalog, CasUpdateEndsAtTheDeadlineNotAfterAHundredUnsleptIterations) +/// Persistent contention ends after 100 submissions, each refusal but the last followed by a pause, +/// with the typed retryable error. `mutate` re-arms the one-shot conflict injection on every call, so +/// every write is refused. +TEST(CASRefCatalog, CasUpdateEndsAfterAHundredPacedSubmissions) { - auto backend = std::make_shared(); + auto backend = std::make_shared(); DB::Cas::tests::FakeClock clock; CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); requests.setNowFnForTest(clock.nowFn()); @@ -1129,24 +1145,19 @@ TEST(CASRefCatalog, CasUpdateEndsAtTheDeadlineNotAfterAHundredUnsleptIterations) CasOperation op = requests.admit(); Layout layout("p"); CasRefCatalog::initializeEmptyForNewPool(op, layout); - const uint64_t started_at = clock.now; + const uint64_t writes_before = backend->writes(layout.refCatalogKey()); - int mutate_calls = 0; - DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 submissions)", [&] { CasRefCatalog::casUpdate(op, layout, [&](const RefCatalog & cur) { - ++mutate_calls; backend->refuseNextWrite(layout.refCatalogKey()); RefCatalog next = cur; return next; }); }); - EXPECT_GT(mutate_calls, 1); /// genuinely retried, not a single-shot failure - EXPECT_FALSE(clock.sleeps.empty()) << "every retry must back off; an unslept loop would burn the " - "deadline on requests instead of waiting out the contention"; - EXPECT_GE(clock.now - started_at, kDefaultRequestWindowMs - 5000) - << "the loop ended at the policy's own deadline, not at an iteration count"; + EXPECT_EQ(backend->writes(layout.refCatalogKey()) - writes_before, 100u); + EXPECT_EQ(clock.sleeps.size(), 98u) << "every refusal but the first, retried at once, and the last is paced"; } TEST(CASRefCatalog, CasAdmitEntryAcceptsAnOrdinaryCreation) @@ -1487,14 +1498,14 @@ TEST(CASRefCatalogRemoval, AConflictingEraseBacksOffBeforeItsRetry) .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); - backend->refuseNextWrite(layout.refCatalogKey()); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); EXPECT_EQ(deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh), CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); - ASSERT_EQ(clock.sleeps.size(), 1u) << "one refusal, so exactly one paced retry"; - EXPECT_LE(clock.sleeps.front(), 200u) << "the first reissue's full-jitter ceiling"; - EXPECT_EQ(backend->writes(layout.refCatalogKey()), 3u) - << "the seed, the refused erase, and the retry that landed"; + ASSERT_EQ(clock.sleeps.size(), 1u) << "the first refusal is retried at once, the second after a pause"; + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps.front(), 2)) << "the pause after the second lost race"; + EXPECT_EQ(backend->writes(layout.refCatalogKey()), 4u) + << "the seed, the two refused erases, and the retry that landed"; } /// A writer that lands during every backoff must not starve the erase: the next erase write is @@ -1533,10 +1544,10 @@ TEST(CASRefCatalogRemoval, AWriterLandingDuringEveryBackoffCannotStarveTheErase) ++external_writes; }); - backend->refuseNextWrite(layout.refCatalogKey()); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); EXPECT_EQ(deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh), CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); - EXPECT_EQ(clock.sleeps.size(), 1u) << "one refusal, one pause, and the erase after it lands"; + EXPECT_EQ(clock.sleeps.size(), 1u) << "two refusals, the first retried at once, one pause, and the erase after it lands"; EXPECT_EQ(external_writes, 1u); const RefCatalog current = CasRefCatalog::read(op, layout).catalog; @@ -1544,7 +1555,7 @@ TEST(CASRefCatalogRemoval, AWriterLandingDuringEveryBackoffCannotStarveTheErase) EXPECT_EQ(current.entries.front().ns, RootNamespace{"b0"}) << "the writer's row stays, the erased row is gone"; } - /// A pause that itself runs past the window is followed by no erase write. + /// A pause that runs past a whole window is followed by the next erase: it binds its own window. { auto backend = std::make_shared(); DB::Cas::tests::FakeClock clock; @@ -1553,24 +1564,17 @@ TEST(CASRefCatalogRemoval, AWriterLandingDuringEveryBackoffCannotStarveTheErase) auto pause = clock.sleepFn(); requests.setSleepFnForTest([&](uint64_t ms) { pause(ms + 200'000); }); CasOperation op = requests.admit(); - const Layout layout("erase-pause-past-deadline"); + const Layout layout("erase-pause-past-a-window"); seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); const uint64_t writes_after_seed = backend->writes(layout.refCatalogKey()); - backend->refuseNextWrite(layout.refCatalogKey()); - try - { - (void)deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh); - ADD_FAILURE() << "a pause that crosses the window must end the call"; - } - catch (const DB::Exception & e) - { - EXPECT_EQ(e.code(), DB::ErrorCodes::NETWORK_ERROR); - EXPECT_NE(e.message().find("deadline"), String::npos) << e.message(); - } - EXPECT_EQ(backend->writes(layout.refCatalogKey()) - writes_after_seed, 1u) - << "only the refused erase; nothing is sent after the pause crossed the deadline"; - EXPECT_EQ(CasRefCatalog::read(op, layout).catalog.entries, std::vector{removing}); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); + EXPECT_EQ(deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh), + CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); + EXPECT_EQ(clock.sleeps.size(), 1u); + EXPECT_EQ(backend->writes(layout.refCatalogKey()) - writes_after_seed, 3u) + << "the two refused erases and the erase after the pause"; + EXPECT_TRUE(CasRefCatalog::read(op, layout).catalog.entries.empty()); } } @@ -1605,7 +1609,7 @@ TEST(CASRefCatalogRemoval, AConflictedEraseSendsTheNextWriteFromAReadTakenAfterT const CasRefCatalog::Snapshot snapshot = CasRefCatalog::read(op, layout); const size_t journal_before = backend->journalFor(layout.refCatalogKey()).size(); - backend->refuseNextWrite(layout.refCatalogKey()); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); EXPECT_EQ(CasRefCatalog::deleteCompletedRemovingAtSnapshot( op, layout, snapshot, removing, ready_parent, noAuthorityRefresh, noRetirementRecord, noRetirementRecord).outcome, @@ -1626,10 +1630,76 @@ TEST(CASRefCatalogRemoval, AConflictedEraseSendsTheNextWriteFromAReadTakenAfterT << "and the next erase write comes from that read: " << renderJournal(journal_since); } +/// The authority refresh before a retried erase runs right after the pause (none after the first refusal), before the +/// catalog read the erase is conditioned on, so no request of its own sits between that read and the erase. +TEST(CASRefCatalogRemoval, TheAuthorityRefreshBeforeARetriedEraseComesBeforeItsCatalogRead) +{ + auto backend = std::make_shared(); + DB::Cas::tests::FakeClock clock; + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + requests.setNowFnForTest(clock.nowFn()); + const Layout layout("erase-refresh-before-read"); + std::vector journal_sizes_at_pause; + std::vector journal_sizes_at_refresh; + String timeline; + auto pause = clock.sleepFn(); + requests.setSleepFnForTest([&](uint64_t ms) + { + pause(ms); + timeline += 'P'; + journal_sizes_at_pause.push_back(backend->journalFor(layout.refCatalogKey()).size()); + }); + CasOperation op = requests.admit(); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, + .state = NsState::Removing, + .incarnation = UInt128{7}, + .removal_started_round = 13}; + seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + + const CasRefCatalog::Snapshot snapshot = CasRefCatalog::read(op, layout); + const size_t journal_before = backend->journalFor(layout.refCatalogKey()).size(); + refuseNextWrites(*backend, layout.refCatalogKey(), 2); + + EXPECT_EQ(CasRefCatalog::deleteCompletedRemovingAtSnapshot( + op, layout, snapshot, removing, ready_parent, + [&] + { + timeline += 'F'; + journal_sizes_at_refresh.push_back(backend->journalFor(layout.refCatalogKey()).size()); + }, + noRetirementRecord, noRetirementRecord).outcome, + CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); + + EXPECT_EQ(timeline, "FFPF") + << "a refresh before the first erase, one before the second, retried at once, and one after the pause before the third"; + ASSERT_EQ(journal_sizes_at_pause.size(), 1u); + ASSERT_EQ(journal_sizes_at_refresh.size(), 3u) << "one refresh per attempt"; + EXPECT_EQ(journal_sizes_at_refresh.front(), journal_before) << "before the first erase"; + EXPECT_EQ(journal_sizes_at_refresh.back(), journal_sizes_at_pause.front()) + << "the second refresh follows the pause with no catalog request between them"; + const std::vector journal = backend->journalFor(layout.refCatalogKey()); + const size_t refreshed_at = journal_sizes_at_refresh.back(); + ASSERT_EQ(journal.size(), refreshed_at + 3) << renderJournal(journal); + using Verb = WriteCountingBackend::Verb; + /// The retry after the first refusal is not paced, and its refresh still comes right before its catalog read. + const size_t first_retry_refreshed_at = journal_sizes_at_refresh[1]; + ASSERT_LT(first_retry_refreshed_at + 1, journal.size()) << renderJournal(journal); + EXPECT_EQ(journal[first_retry_refreshed_at], Verb::Read) << "the first retry's catalog read: " << renderJournal(journal); + EXPECT_EQ(journal[first_retry_refreshed_at + 1], Verb::Write) << "and the erase on it: " << renderJournal(journal); + EXPECT_EQ(journal[refreshed_at], Verb::Read) << "the catalog read after the refresh: " << renderJournal(journal); + EXPECT_EQ(journal[refreshed_at + 1], Verb::Write) << "the erase on it: " << renderJournal(journal); + EXPECT_EQ(journal[refreshed_at + 2], Verb::Read) << "the read that resolves the erase: " << renderJournal(journal); +} + /// A caller's liveness need not be a fact this loop can read. The GC drain's is a cached /// leader-authority flag its owner refreshes by re-reading `gc/state`, so a leader deposed while an /// erase is in flight leaves that flag stale -- and on an unrecoverable delete path one reading taken -/// before the first erase must not authorise the rest. Hence the refresh hook, run at the top of every +/// before the first erase must not authorise the rest. Hence the refresh hook, run before every /// attempt. /// /// The winner here writes the SAME row back: the incarnation moves, so the erase is refused, and the @@ -1712,12 +1782,12 @@ TEST(CASRefCatalogRemoval, NonFenceAuthorityExceptionPropagatesBeforeEraseCas) << "nothing changed under an authority failure that reached no attempt"; } -/// The counterpart to the case above: the hook fails AFTER the loop has already sent one erase and -/// resolved it (a refusal, so the row is provably unchanged), on the refresh that would gate the next +/// The counterpart to the case above: the hook fails AFTER the loop has already sent one erase and the +/// store refused it (so the row is provably unchanged), on the refresh that would gate the next /// attempt. The failure must still escape rather than be read as the fenced-out liveness answer this /// class's default `admitted()` would otherwise report, and -- exactly as when it fails up front -- no /// further erase may reach the store on an authority this call could not evaluate. -TEST(CASRefCatalogRemoval, NonFenceAuthorityExceptionPropagatesAfterEraseResolution) +TEST(CASRefCatalogRemoval, NonFenceAuthorityExceptionPropagatesAfterARefusedErase) { auto backend = std::make_shared(); DB::Cas::tests::FakeClock clock; @@ -1746,7 +1816,7 @@ TEST(CASRefCatalogRemoval, NonFenceAuthorityExceptionPropagatesAfterEraseResolut { ++refreshes; if (refreshes > 1) - throw std::runtime_error("injected authority-refresh failure after the erase resolved"); + throw std::runtime_error("injected authority-refresh failure after the erase was refused"); }), std::runtime_error); EXPECT_EQ(refreshes, 2u) << "once before the refused attempt, once before the retry it never sent"; @@ -1855,13 +1925,9 @@ TEST(CASRefCatalogRemoval, ACommitTheResolutionReadContradictsFailsRetryLaterIns << "the message must name the life still observed: " << message; } -/// The loop captures ONE bound before it starts and every call it makes shares it, so a permanently -/// contended catalog gives up "retry later" inside one request window rather than spending a fresh -/// window per verb across a hundred paced iterations -- which is hours against a document that -/// promises one window. Every erase is refused and the injected clock absorbs every paced retry, -/// so what ends the call is visible in the virtual time it took. The attempt cap stays as the -/// secondary bound; it is not what ends this call. -TEST(CASRefCatalogRemoval, PerpetualConflictGivesUpWithinOneWindowNotAtTheAttemptCap) +/// Every erase is refused. Each request binds its own window, so the attempt cap ends the call: 100 +/// erases, a pause after each refusal but the last, and the resolution read after every erase. +TEST(CASRefCatalogRemoval, PerpetualConflictGivesUpAfterAHundredErases) { class AlwaysRefusesCatalogWrites final : public WriteCountingBackend { @@ -1911,7 +1977,7 @@ TEST(CASRefCatalogRemoval, PerpetualConflictGivesUpWithinOneWindowNotAtTheAttemp .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); backend->refused_key = layout.refCatalogKey(); - const uint64_t start = clock.now; + const size_t sleeps_before = clock.sleeps.size(); String message; try { @@ -1923,14 +1989,133 @@ TEST(CASRefCatalogRemoval, PerpetualConflictGivesUpWithinOneWindowNotAtTheAttemp EXPECT_EQ(e.code(), DB::ErrorCodes::NETWORK_ERROR); message = e.message(); } - EXPECT_NE(message.find("deadline"), String::npos) - << "the shared bound, not the attempt cap, is what ended this call: " << message; - /// Two windows, so the assertion survives the jitter of the paced retries while still failing a - /// loop that binds a fresh window per iteration -- that one spends minutes here. - EXPECT_LT(clock.now - start, 2 * kDefaultRequestWindowMs) << "the loop outlived the window it captured"; - EXPECT_LT(backend->refusedAttempts(), 100u) << "the attempt cap must not be what ends this call"; - /// Greater than one is what proves the loop iterated rather than failing on its first attempt. - EXPECT_GT(backend->refusedAttempts(), 1u); + EXPECT_NE(message.find("did not converge after 100 attempts"), String::npos) << message; + EXPECT_EQ(backend->refusedAttempts(), 100u); + EXPECT_EQ(clock.sleeps.size() - sleeps_before, 98u) << "no pause after the first refusal, retried at once, nor the last"; + for (size_t i = sleeps_before; i < clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[i], static_cast(i - sleeps_before + 2))); + EXPECT_EQ(CasRefCatalog::read(op, layout).catalog.entries, std::vector{removing}); +} + +namespace +{ + +CatalogEntry removingEntryForStopTests() +{ + return CatalogEntry{.ns = RootNamespace{"a"}, .state = NsState::Removing, .incarnation = UInt128{7}, .removal_started_round = 13}; +} + +CasFoldSeal readyParentForStopTests() +{ + CasFoldSeal parent; + parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + return parent; +} + +/// Loses the reply of the next catalog write, running `on_lost` first; every catalog read after it fails. +class LostEraseUnreadableCatalogBackend final : public WriteCountingBackend +{ +public: + String catalog_key; + std::function on_lost; + + std::optional read(const String & key, DB::Cas::TransportAccess & access) override + { + if (lost && key == catalog_key) + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected catalog read failure"); + return WriteCountingBackend::read(key, access); + } + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (key != catalog_key || !on_lost || lost) + return WriteCountingBackend::write(key, bytes, expected_value, access); + lost = true; + on_lost(); + throw Poco::TimeoutException("injected lost catalog erase reply"); + } + +private: + bool lost = false; +}; + +} + +/// An erase whose reply was lost, whose owner stopped, and whose resolution read cannot complete ends with the +/// erase's "outcome unknown" exit: the erase may still land. +TEST(CASRefCatalogRemoval, UnresolvedEraseOfAStoppedOwnerKeepsItsExit) +{ + auto backend = std::make_shared(); + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + CasOperation op = requests.admit(); + const Layout layout("erase-unresolved-stop"); + const CatalogEntry removing = removingEntryForStopTests(); + seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + std::atomic stopped = false; + backend->catalog_key = layout.refCatalogKey(); + backend->on_lost = [&stopped] { stopped = true; }; + + String message; + { + const auto owner = OwnerScope::background([&stopped] + { + if (stopped) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] + { + try + { + (void)deleteCompletedRemovingForTest(op, layout, removing, readyParentForStopTests(), noAuthorityRefresh); + } + catch (const DB::Exception & e) + { + message = e.message(); + throw; + } + }); + } + EXPECT_NE(message.find("unresolved"), String::npos) << message; + EXPECT_EQ(backend->writes(layout.refCatalogKey()), 1u) << "only the seed: the lost erase bypasses the count, and nothing was resent"; +} + +/// An owner that stops while a conflicted erase is resolved starts no second decision: no authority refresh +/// and no erase follow the resolution read. +TEST(CASRefCatalogRemoval, StopDuringAConflictedErasesResolutionStartsNoNextDecision) +{ + auto backend = std::make_shared(); + FakeClock clock; + std::atomic stopped = false; + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + requests.setNowFnForTest(clock.nowFn()); + /// The conflict's pause comes before the resolution read. + requests.setSleepFnForTest([&stopped](uint64_t) { stopped = true; }); + CasOperation op = requests.admit(); + const Layout layout("erase-conflict-stop"); + const CatalogEntry removing = removingEntryForStopTests(); + seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + /// The first refusal is retried at once; the second pauses. + refuseNextWrites(*backend, layout.refCatalogKey(), 2); + + size_t refreshes = 0; + { + const auto owner = OwnerScope::background([&stopped] + { + if (stopped) + throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); + }); + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::ABORTED, [&] + { + (void)deleteCompletedRemovingForTest(op, layout, removing, readyParentForStopTests(), [&refreshes] { ++refreshes; }); + }); + } + ASSERT_TRUE(stopped) << "premise: the erase conflicted and paused"; + EXPECT_EQ(refreshes, 2u) << "one for each erase sent, none for a third decision"; + EXPECT_EQ(backend->writes(layout.refCatalogKey()), 3u) << "the seed and the two conflicted erases"; EXPECT_EQ(CasRefCatalog::read(op, layout).catalog.entries, std::vector{removing}); } @@ -2667,20 +2852,62 @@ TEST(CASRefCatalog, CreateNamespaceStep1FailsAtOnceWhenItsCatalogReadIsRefused) } #endif -/// The pause before a new decision is gated like the engine's own reissue pause: with no room left -/// for the pause and one attempt, the call ends without sleeping. -TEST(CASRefCatalog, CreateNamespaceStep1DoesNotPausePastItsDeadline) +/// The first step-1 write takes more than a window and its response is lost. The next decision's read +/// and write each bind their own window, so the row is created. +TEST(CASRefCatalog, CreateNamespaceStep1PausesThenDecidesAgainInItsOwnWindow) +{ + Step1Fixture t; + t.f.pool.setAttemptReservationForTest(1'000); + t.backend->failNextWriteWith(t.backend->catalog_key, lostResponse()); + bool slowed = false; + uint64_t first_write_ended_ms = 0; + t.backend->on_write = [&] + { + if (std::exchange(slowed, true)) + return; + t.f.clock.now.fetch_add(kDefaultRequestWindowMs + 1); + first_write_ended_ms = t.f.clock.now.load(); + }; + const size_t sleeps_before = t.f.clock.sleeps.size(); + + ASSERT_EQ(t.createA(), CasRefCatalog::NamespaceCreationOutcome::Live); + t.expectDistinctIncarnationsAndTheLastOneLive(); + EXPECT_EQ(t.step1Incarnations().size(), 2u); + EXPECT_EQ(t.f.clock.sleeps.size() - sleeps_before, 1u); + /// Only pauses move the clock after the slow write, so the call ends well inside the next window. + EXPECT_LE(t.f.clock.now.load() - first_write_ended_ms, kDefaultRequestWindowMs + 1'000 + 5'000); +} + +/// The same with an explicit lease that leaves 1.5 s: the pause fits under the lease, the next write's +/// two envelopes do not, so no second write is sent. +TEST(CASRefCatalog, CreateNamespaceStep1PausesThenSendsNoWriteWithoutRoomUnderItsLease) { Step1Fixture t; t.f.pool.setAttemptReservationForTest(1'000); t.backend->failNextWriteWith(t.backend->catalog_key, lostResponse()); - /// Leaves 1.5 s of the window: enough for the settle read, too little for a pause plus two envelopes. + const Retry policy = Retry::untilLeaseSafe(t.f.clock.now.load() + kDefaultRequestWindowMs, 0); t.backend->on_write = [&] { t.f.clock.now.fetch_add(kDefaultRequestWindowMs - 1'500); }; const size_t sleeps_before = t.f.clock.sleeps.size(); - DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { (void)t.createA(); }); + DB::Cas::tests::expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, + [&] { (void)CasRefCatalog::createNamespace(t.pool_op, t.layout, 1, RootNamespace{"a"}, t.creator, policy); }); EXPECT_EQ(t.backend->bodies.size(), 1u); - EXPECT_EQ(t.f.clock.sleeps.size() - sleeps_before, 0u); + EXPECT_EQ(t.f.clock.sleeps.size() - sleeps_before, 1u); +} + +/// The smallest window a write accepts is two envelopes and 1 ms. After a lost step-1 write the next +/// decision's write gets a whole such window of its own, so the row is created. +TEST(CASRefCatalog, CreateNamespaceStep1DecidesAgainWithTheSmallestValidWindow) +{ + Step1Fixture t; + t.f.pool.setAttemptReservationForTest(1'000); + t.backend->failNextWriteWith(t.backend->catalog_key, lostResponse()); + /// Each catalog write takes 2 ms, so no window that started before a write has room for another. + t.backend->on_write = [&] { t.f.clock.now.fetch_add(2); }; + + ASSERT_EQ(CasRefCatalog::createNamespace(t.pool_op, t.layout, 1, RootNamespace{"a"}, t.creator, Retry::within(2'001)), + CasRefCatalog::NamespaceCreationOutcome::Live); + t.expectDistinctIncarnationsAndTheLastOneLive(); } /// The step-1 write lands and its response is lost; before the next decision a sibling completes the @@ -3117,12 +3344,6 @@ TEST(CASRefCatalog, TheCatalogLoopPacesAConflictByWhetherItSettledAFault) /// are still on the catalog when the second starts, and re-admitting the same namespace would /// duplicate it rather than race it. constexpr int K = 3; - /// The settled-fault scenario draws 8, not 3: an upper-bound-only check on `backoff`'s draws - /// cannot tell the growing schedule from the flat one (both stay under 200 ms plenty often at - /// small K), so that scenario also needs a floor. With `backoff(attempt) = uniform(0, min(5000, - /// 200 << (attempt-1)))`, the flat schedule can NEVER draw over 200 ms, so a single draw over - /// 200 ms is proof by itself that the schedule grew; drawing 8 times keeps the growing schedule's - /// own chance of missing that floor purely by bad luck around 2^-28. constexpr int K2 = 8; int moved = 0; int limit = K; @@ -3149,15 +3370,14 @@ TEST(CASRefCatalog, TheCatalogLoopPacesAConflictByWhetherItSettledAFault) if (e.ns.string() == "a") { e.state = NsState::Removing; e.removal_started_round = 1; } return next; }); - ASSERT_EQ(f.clock.sleeps.size(), static_cast(K)); - for (uint64_t s : f.clock.sleeps) - EXPECT_LE(s, 200u); + /// The first loss is on the lane's cached catalog and is retried at once, without counting; the first counted loss + /// is retried at once too, so only the later ones pause. + ASSERT_EQ(f.clock.sleeps.size(), static_cast(K - 2)); + for (size_t i = 0; i < f.clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(f.clock.sleeps[i], static_cast(i + 2))); EXPECT_EQ(eventCount(ProfileEvents::CASRequestConflictPause) - pauses_before, 0u) << "the lane's caller pauses itself; the engine's counter is for its own loops"; - /// K2 conflicts that each settled a fault: the growing schedule, on the loop's own count. An - /// upper-bound check alone is satisfied by the flat schedule too (its draws are a subset of the - /// growing schedule's early-attempt range), so this also asserts a floor: at least one draw over - /// 200 ms, which the flat schedule can never produce. + /// K2 conflicts that each settled a fault: the fault schedule, on the loop's own count of them. f.clock.sleeps.clear(); moved = 0; limit = K2; @@ -3167,10 +3387,304 @@ TEST(CASRefCatalog, TheCatalogLoopPacesAConflictByWhetherItSettledAFault) CasRefCatalog::casUpdate(pool_op, layout, [](const RefCatalog & cur) { return cur; }); ASSERT_EQ(f.clock.sleeps.size(), static_cast(K2)); for (size_t i = 0; i < f.clock.sleeps.size(); ++i) - EXPECT_LE(f.clock.sleeps[i], std::min(5000, 200ull << i)); - EXPECT_TRUE(std::any_of(f.clock.sleeps.begin(), f.clock.sleeps.end(), [](uint64_t s) { return s > 200u; })) - << "the flat schedule can never draw over 200 ms; a growing schedule almost certainly does " - "somewhere in 8 draws, so this is what tells the two schedules apart"; + EXPECT_LE(f.clock.sleeps[i], std::min(5000, 200ull << i)) << "fault pause " << i + 1; + /// Every clean pause lies in its own step's range. A full-jitter draw lands in that range with probability at + /// most 1/10 at each of these steps, so all 8 do with probability below 1e-9. + size_t outside_clean = 0; + for (size_t i = 0; i < f.clock.sleeps.size(); ++i) + outside_clean += DB::Cas::tests::isConflictPause(f.clock.sleeps[i], static_cast(i + 1)) ? 0 : 1; + EXPECT_GT(outside_clean, 0u) << "a fault paced by the clean schedule"; +} + +namespace +{ + +/// Another server's catalog writer that commits on demand. Its requests are bracketed by marks, so +/// `renderOwnRequests` shows only the pool's own requests. +struct CatalogRival +{ + PoolAndExternal & f; + Layout layout; + CasOperation op; + uint64_t commits = 0; + bool inside = false; + + void commit() + { + inside = true; + f.backend->mark("rival{"); + CasRefCatalog::casAdmitEntry(op, layout, 1, liveEntry(fmt::format("r{:03}", commits), 1000 + commits)); + f.backend->mark("}rival"); + ++commits; + inside = false; + } +}; + +RefCatalog markARemoving(const RefCatalog & cur) +{ + RefCatalog next = cur; + for (auto & e : next.entries) + if (e.ns.string() == "a") + { + e.state = NsState::Removing; + e.removal_started_round = 1; + } + return next; +} + +} + +/// The rival lands right before the pool's first three writes and during every pause. The first loss is on the lane's +/// cached catalog and is retried at once on the resolve read; the second, the first on a fresh read, is retried at once +/// too; the third is paced; the write after the pause is decided on a read taken after it, so it lands. +TEST(CASRefCatalog, ACatalogUpdateIsNotStarvedByAWriterThatCommitsDuringEveryPause) +{ + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation pool_op = f.pool.admit(); + CasRefCatalog::initializeEmptyForNewPool(pool_op, layout); + CasRefCatalog::casAdmitEntry(pool_op, layout, 1, liveEntry("a", 1)); /// the lane caches the catalog + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + int collisions = 0; + f.backend->onBeforeWrite(key, [&] + { + if (rival.inside || collisions >= 3) + return; + ++collisions; + rival.commit(); + }); + auto sleep = f.clock.sleepFn(); + f.pool.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + f.backend->mark("pause"); + rival.commit(); + }); + f.backend->clearJournal(); + + int decided = 0; + CasRefCatalog::casUpdate(pool_op, layout, [&](const RefCatalog & cur) { ++decided; return markARemoving(cur); }); + + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*f.backend, key), "WRWRWPRW") + << "cached write refused, resolve read, write refused, read, write refused, pause, read, the write on it"; + EXPECT_EQ(decided, 4); + EXPECT_EQ(f.clock.sleeps.size(), 1u); + EXPECT_EQ(rival.commits, 4u); + const RefCatalog landed = CasRefCatalog::read(pool_op, layout).catalog; + ASSERT_EQ(landed.entries.size(), 5u); + EXPECT_EQ(landed.entries.front().state, NsState::Removing); +} + +/// A rival that lands right before every write still ends the loop on the submission cap, with a +/// pause between submissions and every write after a pause decided on a read taken after it. +TEST(CASRefCatalog, ACatalogUpdateAgainstAWriterBeforeEveryWriteEndsOnTheCount) +{ + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation pool_op = f.pool.admit(); + CasRefCatalog::initializeEmptyForNewPool(pool_op, layout); + CasRefCatalog::casAdmitEntry(pool_op, layout, 1, liveEntry("a", 1)); /// the lane caches the catalog + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + f.backend->onBeforeWrite(key, [&] + { + if (!rival.inside) + rival.commit(); + }); + auto sleep = f.clock.sleepFn(); + f.pool.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + f.backend->mark("pause"); + }); + f.backend->clearJournal(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 submissions", [&] + { + CasRefCatalog::casUpdate(pool_op, layout, markARemoving); + }); + + EXPECT_EQ(f.clock.sleeps.size(), kCasMaxDecisions - 2) << "no pause after the first lost race, nor the last"; + for (size_t i = 0; i < f.clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(f.clock.sleeps[i], static_cast(i + 2))); + /// The loss on the cached catalog is settled and retried at once. A loss on a fresh read is not settled when a + /// read follows it, at once after the first and after a pause from the second; the last submission's loss, which + /// nothing follows, is. + String expected = "WRW" "RW"; + for (uint32_t i = 2; i < kCasMaxDecisions - 1; ++i) + expected += "PRW"; + expected += "PRWR"; + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*f.backend, key), expected); +} + +/// A conflict that settled a transport fault ends the run of clean losses, in the catalog update and in the erase loop: +/// the clean loss after it starts a new run and is retried at once, so only the fault-settled conflict pauses. +TEST(CASRefCatalog, AFaultSettledConflictRestartsTheCleanLossCount) +{ + { + SCOPED_TRACE("catalog update"); + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation setup = f.external.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + CasRefCatalog::casAdmitEntry(setup, layout, 1, liveEntry("a", 1)); + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + int moves = 0; + f.backend->onBeforeWrite(key, [&] + { + if (rival.inside || moves >= 3) + return; + ++moves; + rival.commit(); + if (moves == 2) + f.backend->injectAmbiguousWrite(key); + }); + CasOperation pool_op = f.pool.admit(); + CasRefCatalog::casUpdate(pool_op, layout, markARemoving); + EXPECT_EQ(moves, 3) << "premise: clean, fault-settled, clean"; + EXPECT_EQ(f.clock.sleeps.size(), 1u); + } + { + SCOPED_TRACE("catalog erase"); + auto backend = std::make_shared(); + DB::Cas::tests::FakeClock clock; + CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); + requests.setNowFnForTest(clock.nowFn()); + requests.setSleepFnForTest(clock.sleepFn()); + CasOperation op = requests.admit(); + CasOperation writer = requests.admit(); + const Layout layout("erase-fault-between"); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, + .state = NsState::Removing, + .incarnation = UInt128{7}, + .removal_started_round = 13}; + seedObject(op, layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + int moves = 0; + bool inside = false; + backend->onBeforeWrite(layout.refCatalogKey(), [&] + { + if (inside || moves >= 3) + return; + inside = true; + ++moves; + CasRefCatalog::casAdmitEntry(writer, layout, 1, liveEntry(fmt::format("w{}", moves), 100 + moves)); + if (moves == 2) + backend->injectAmbiguousWrite(layout.refCatalogKey()); + inside = false; + }); + EXPECT_EQ(deleteCompletedRemovingForTest(op, layout, removing, ready_parent, noAuthorityRefresh), + CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted); + EXPECT_EQ(moves, 3) << "premise: clean, fault-settled, clean"; + EXPECT_EQ(clock.sleeps.size(), 1u); + } +} + +/// The catalog disappears between the last submission's read and its write. That write's refusal is settled, +/// as no submission follows it, so the caller that takes absence as an answer gets it rather than the count. +TEST(CASRefCatalog, AnAbsenceAtTheLastSubmissionIsReportedNotTheCount) +{ + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation setup = f.external.admit(); + CasRefCatalog::initializeEmptyForNewPool(setup, layout); + const CatalogEntry creating{ + .ns = RootNamespace{"a"}, + .state = NsState::Creating, + .incarnation = UInt128{5}, + .creator = CreatorFence{.server_root_id = "gone", .writer_epoch = 1, .fence_generation = 1}}; + CasRefCatalog::casAdmitEntry(setup, layout, 1, creating); + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + CasOperation remover = f.external.admit(); + uint32_t pool_writes = 0; + bool removing = false; + f.backend->onBeforeWrite(key, [&] + { + if (rival.inside || removing) + return; + if (++pool_writes < kCasMaxDecisions) + { + rival.commit(); + return; + } + removing = true; + ASSERT_EQ(remover.removeCurrent(key, Retry::standard()), Removal::Removed); + removing = false; + }); + + CasOperation pool_op = f.pool.admit(); + bool absent = false; + const auto outcome = CasRefCatalog::cancelStalledCreating(pool_op, layout, creating, + [](const CreatorFence &) { return true; }, [](const Retry &) {}, Retry::standard(), &absent); + + EXPECT_EQ(outcome, CasRefCatalog::StalledCreatingCancelOutcome::EntryChanged); + EXPECT_TRUE(absent); + EXPECT_EQ(pool_writes, kCasMaxDecisions); +} + +/// While the caller pauses after a lost race (its second on a fresh read: the first is retried at once), another +/// holder in the same pool commits and the lane caches that commit, then another server moves the catalog on. The submission after the pause reads instead of +/// starting from that cached body, which is older than the pause's end. +TEST(CASRefCatalog, ASubmissionAfterAPauseReadsInsteadOfStartingFromTheCache) +{ + PoolAndExternal f(std::make_shared()); + const Layout layout("p"); + CasOperation pool_op = f.pool.admit(); + CasOperation neighbour = f.pool.admit(); + CasRefCatalog::initializeEmptyForNewPool(pool_op, layout); + CasRefCatalog::casAdmitEntry(pool_op, layout, 1, liveEntry("a", 1)); + CasRefCatalog::casAdmitEntry(pool_op, layout, 1, liveEntry("n", 2)); + CatalogRival rival{f, layout, f.external.admit()}; + const String key = layout.refCatalogKey(); + bool in_pause = false; + int collisions = 0; + f.backend->onBeforeWrite(key, [&] + { + if (rival.inside || in_pause || collisions >= 3) + return; + ++collisions; + rival.commit(); + }); + auto sleep = f.clock.sleepFn(); + f.pool.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + f.backend->mark("pause"); + in_pause = true; + f.backend->mark("rival{"); + CasRefCatalog::casUpdate(neighbour, layout, [](const RefCatalog & cur) + { + RefCatalog next = cur; + for (auto & e : next.entries) + if (e.ns.string() == "n") + { + e.state = NsState::Removing; + e.removal_started_round = 2; + } + return next; + }); + f.backend->mark("}rival"); + rival.commit(); + in_pause = false; + }); + f.backend->clearJournal(); + + CasRefCatalog::casUpdate(pool_op, layout, markARemoving); + + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*f.backend, key), "WRWRWPRW") + << "after the pause: a read, then the write on it, not a write on the neighbour's cached commit"; + EXPECT_EQ(f.clock.sleeps.size(), 1u); + const RefCatalog landed = CasRefCatalog::read(pool_op, layout).catalog; + for (const auto & e : landed.entries) + if (e.ns.string() == "a" || e.ns.string() == "n") + EXPECT_EQ(e.state, NsState::Removing) << e.ns.string(); } TEST(CASRefCatalog, TheGCEraseRacesTheLaneAsItRacesEverything) diff --git a/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp b/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp index e1b618bc31ce9..1ce327a243be6 100644 --- a/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp +++ b/src/Disks/tests/gtest_cas_ref_catalog_birth_wiring.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -683,11 +684,15 @@ class ChurningCatalogBackend final : public InMemoryBackend } bool churning = false; + size_t churned_reads = 0; std::optional read(const String & key, DB::Cas::TransportAccess & access) override { if (churning && key == catalog_key) + { + ++churned_reads; bumpEveryCreatorFence(access); + } return InMemoryBackend::read(key, access); } @@ -710,16 +715,90 @@ class ChurningCatalogBackend final : public InMemoryBackend } +namespace +{ + +/// After this server's own birth of `ns` lands, rewrites the catalog under three successive reads: the confirming read +/// sees a foreign `Creating` row, the reconciliation's read sees that row moved on, and the next read sees it `Live`. +class ReplacedAfterBirthBackend final : public InMemoryBackend +{ +public: + ReplacedAfterBirthBackend(String catalog_key_, RootNamespace ns_) + : catalog_key(std::move(catalog_key_)), ns(std::move(ns_)) + { + } + + int stage = 0; + + std::optional read(const String & key, DB::Cas::TransportAccess & access) override + { + if (key == catalog_key && stage < 3) + rewrite(access); + return InMemoryBackend::read(key, access); + } + +private: + void rewrite(DB::Cas::TransportAccess & access) + { + const std::optional got = InMemoryBackend::read(catalog_key, access); + if (!got) + return; + RefCatalog catalog = decodeRefCatalog(got->bytes); + for (CatalogEntry & entry : catalog.entries) + { + if (entry.ns != ns) + continue; + if (stage == 0 && entry.state == NsState::Live) + { + entry.state = NsState::Creating; + entry.creator = CreatorFence{.server_root_id = "foreign-creator", .writer_epoch = 7, .fence_generation = 1}; + } + else if (stage == 1) + ++entry.creator->fence_generation; + else if (stage == 2) + { + entry.state = NsState::Live; + entry.creator.reset(); + } + else + return; + ++stage; + (void)InMemoryBackend::write(catalog_key, encodeRefCatalog(catalog), got->value, access); + return; + } + } + + const String catalog_key; + const RootNamespace ns; +}; + +} + +/// A birth that lands and is then replaced before its confirming read is followed by one collision, the first of this +/// call, so it is retried at once, whatever round it falls in. +TEST(CASRefCatalogBirthWiring, TheFirstCollisionAfterAConfirmedBirthIsRetriedAtOnce) +{ + const RootNamespace ns{"replaced_after_birth"}; + auto backend = std::make_shared(Layout{"p"}.refCatalogKey(), ns); + auto store = openPoolForBirthTest(backend); + std::vector pauses; + store->setCasRetrySleepForTest([&](uint64_t ms) { pauses.push_back(ms); }); + + (void)store->namespaceLife(ns); + + EXPECT_EQ(backend->stage, 3) << "premise: the row was replaced, moved on and completed"; + EXPECT_TRUE(pauses.empty()) << "a pause of " << (pauses.empty() ? 0 : pauses.front()) << " ms after the first collision"; +} + /// A catalog entry that moves under every read drives `resolveNamespaceLife`'s state machine for ever. -/// One `Retry` frozen before the loop bounds the WHOLE resolution to a single standard window, and -/// every re-read a competing actor forces is paced by a jittered sleep -- so a permanently churning -/// catalog costs one window, not one fresh window per verb per iteration hammered with no wait between -/// them. -/// -/// What the clock bound below does NOT check: it bounds this call's own wall time, not the number of -/// requests the loop sent, and it says nothing about the paths that converge. -TEST(CASRefCatalogBirthWiring, APerpetuallyChurningCatalogEntryIsPacedAndEndsWithinOneWindow) +/// Every re-read a competing actor forces is paced by the count of collisions, the first collision is retried at once, +/// the last is not paced because no re-read follows it, and the loop ends after its 32 rounds. The pause before the last +/// round carries the clock past a whole window, so the last round is sent only if each of its requests +/// binds its own window. +TEST(CASRefCatalogBirthWiring, APerpetuallyChurningCatalogEntryIsPacedAndEndsAfterItsRounds) { + constexpr size_t kRounds = 32; + auto backend = std::make_shared(Layout{"p"}.refCatalogKey()); CasRequests requests = DB::Cas::tests::openRequestsForTest(backend); CasOperation op = requests.admit(); @@ -735,18 +814,32 @@ TEST(CASRefCatalogBirthWiring, APerpetuallyChurningCatalogEntryIsPacedAndEndsWit .creator = CreatorFence{.server_root_id = "foreign-creator", .writer_epoch = 7, .fence_generation = 1}}; CasRefCatalog::casAdmitEntry(op, layout, 1, creating); - auto clock = DB::Cas::tests::VirtualRetryClock::installOn(store); + auto now_ms = std::make_shared(0); + size_t pauses = 0; + std::vector pause_ms; + std::optional last_round_started_ms; + size_t reads_before_last_round = 0; + store->setCasRequestNowFnForTest([now_ms] { return *now_ms; }); + store->setCasRetrySleepForTest([&, now_ms](uint64_t ms) + { + *now_ms += ms; + pause_ms.push_back(ms); + if (++pauses == kRounds - 2) + { + *now_ms += DB::Cas::kDefaultRequestWindowMs; + last_round_started_ms = *now_ms; + reads_before_last_round = backend->churned_reads; + } + }); backend->churning = true; - const size_t pauses_before = clock->pauseCount(); - const uint64_t now_before = clock->nowMs(); - - expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { store->namespaceLife(ns); }); - - /// Sixteen jittered draws cannot exhaust the request window even at their ceiling, so an unpaced loop - /// reaches its iteration cap having slept nothing at all. - EXPECT_GE(clock->pauseCount() - pauses_before, 16u) << "each forced re-read is paced"; - /// The frozen window, plus at most one backoff draw the pace does not consult the deadline for, - /// plus the virtual clock's one extra millisecond per pause. - EXPECT_LE(clock->nowMs() - now_before, DB::Cas::kDefaultRequestWindowMs + 5'000 + 100) - << "one standard window bounds the whole loop"; + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, fmt::format("after {} attempts", kRounds), + [&] { store->namespaceLife(ns); }); + + EXPECT_EQ(pauses, kRounds - 2) << "each re-read a lost round forced is paced, but the first and the last round are not"; + for (size_t i = 0; i < pause_ms.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(pause_ms[i], static_cast(i + 2))); + ASSERT_TRUE(last_round_started_ms.has_value()); + EXPECT_EQ(backend->churned_reads - reads_before_last_round, 2u) << "the last round's loop read and its decision read"; + EXPECT_EQ(*now_ms, *last_round_started_ms) << "no pause after the last round"; } diff --git a/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp b/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp index d65a2e3b1ec66..34295f4079788 100644 --- a/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp +++ b/src/Disks/tests/gtest_cas_ref_chunked_flush.cpp @@ -4,6 +4,7 @@ #include +#include #include #include #include @@ -13,13 +14,19 @@ #include #include #include +#include +#include #include #include +#include +#include #include #include +#include + #include #include #include @@ -39,6 +46,7 @@ extern const int LIMIT_EXCEEDED; extern const int CORRUPTED_DATA; extern const int NETWORK_ERROR; extern const int LOGICAL_ERROR; +extern const int ABORTED; } namespace ProfileEvents @@ -46,6 +54,7 @@ namespace ProfileEvents extern const Event CASRefBatchFlushes; extern const Event CASRefBatchedMutations; extern const Event CASRefSnapshotPublishDispatched; +extern const Event CASRefAppendWedged; } /// Task 8 (stage-1 §3 "Budget: counts only, chunked flush"): the counts-only admission caps -- @@ -1135,3 +1144,620 @@ TEST(CASRefWriterChunkedFlush, SnapshotPublisherLatchedAcrossChunks) EXPECT_FALSE(*newest < chunk2_id) << "settlement must re-fire the dropped chunk-2 trigger so a snapshot covers chunk 2 (no lost trigger)"; } + +/// =================================================================================== +/// A leader flushes in its caller's thread group. A killed query does not stop the shared flush, and a stopped +/// background owner can still withdraw the leader's own item until the carve. +/// =================================================================================== + +namespace +{ + +using DB::Cas::tests::CasClientLikeBackend; +using DB::Cas::tests::CasKillableQuery; +using DB::Cas::tests::StoppedBy; +using DB::Cas::tests::backgroundOwnerStoppedBy; +using DB::Cas::tests::nameOf; +using DB::Cas::tests::stopperOf; + +constexpr auto KILL_WATCHDOG = std::chrono::seconds(30); + +/// Calls `before_answer` before the first ref-log create under `log_prefix` after `armed` is set, then stores it. +class LeaderKillLogPutBackend final : public DB::Cas::tests::CountingBackend +{ +public: + String log_prefix; + std::function before_answer; + std::atomic armed{false}; + std::atomic fired{false}; + + std::expected write(const String & key, const String & bytes, + const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (!expected_value && key.starts_with(log_prefix) && armed.exchange(false)) + { + fired = true; + if (before_answer) + before_answer(); + } + return CountingBackend::write(key, bytes, expected_value, access); + } +}; + +struct KilledLeaderFixture +{ + std::shared_ptr faults = std::make_shared(); + PoolPtr store; + std::shared_ptr clock; + RootNamespace ns; + + explicit KilledLeaderFixture(const String & ns_suffix) + : ns(String("srv1/") + ns_suffix) + { + store = openPoolWith(std::make_shared(faults), PoolConfig{}); + clock = VirtualRetryClock::installOn(store); + publishEmptyPart(store, ns, "seed"); + faults->log_prefix = store->layout().namespaceStreamPrefix(DB::Cas::tests::fixture::fixtureLife(ns)) + "_log/"; + } +}; + +int exceptionCode(const std::exception_ptr & e) +{ + if (!e) + return 0; + try + { + std::rethrow_exception(e); + } + catch (const DB::Exception & ex) + { + return ex.code(); + } + catch (...) + { + return -1; + } +} + +/// The leader's side of a killed-leader case, run on a raw thread with its own `ThreadStatus` and a +/// query registered in the process list. `body` gets the query and returns the append's result. +struct LeaderRun +{ + AppendResult result; + bool group_restored = false; +}; + +template +std::future launchQueryLeader(std::thread & thread, Body leader_body) +{ + auto prom = std::make_shared>(); + std::future fut = prom->get_future(); + thread = std::thread([prom, body = std::move(leader_body)]() mutable + { + std::optional thread_status; + thread_status.emplace(); + LeaderRun run; + { + CasKillableQuery query(getContext().context); + run.result = body(query); + run.group_restored = DB::CurrentThread::getGroup() == query.group; + } + prom->set_value(run); + }); + return fut; +} + +/// The leader's item and a neighbor's share one chunk; the leader's query is killed between the carve +/// and the chunk's first answer. +struct KilledLeaderOutcome +{ + LeaderRun leader; + AppendResult neighbor; + int neighbor_builds = 0; +}; + +KilledLeaderOutcome runKilledLeaderChunk(KilledLeaderFixture & fx) +{ + auto sync = std::make_shared(); + armPreCarveBlock(fx.store, fx.ns, sync, 2); + auto neighbor_builds = std::make_shared>(0); + + std::thread leader_thread; + std::future leader = launchQueryLeader(leader_thread, [&fx](CasKillableQuery & query) + { + fx.faults->before_answer = [&query] { query.kill(); }; + fx.faults->armed = true; + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [](const RefTableState &) { return addRemovePrecommitPairs("item_leader", 1, 910000001); }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + return r; + }); + waitEntered(sync); + AppendCaller neighbor = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_neighbor"), + addRemovePrecommitPairs("item_neighbor", 1, 910000002), neighbor_builds); + waitPendingAtLeast(fx.store, fx.ns, 2); + sync->cv.notify_all(); + + KilledLeaderOutcome out; + EXPECT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the killed leader must not hang"; + EXPECT_EQ(neighbor.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the neighbor must not hang"; + out.leader = leader.get(); + out.neighbor = neighbor.fut.get(); + leader_thread.join(); + neighbor.t.join(); + fx.faults->before_answer = {}; + fx.store->setRefPreCarveHookForTest(nullptr); + out.neighbor_builds = neighbor_builds->load(); + return out; +} + +} + +/// A leader's query killed after the carve, on a store that answers every request successfully: the kill does not +/// stop the shared flush, so the chunk commits once for the leader's item and the neighbor's. +TEST(CASRefWriterChunkedFlush, KilledLeaderOnHealthyStoreCommitsWithNeighbor) +{ + KilledLeaderFixture fx("killed_leader_healthy_store"); + const uint64_t wedged_before = ProfileEvents::global_counters[ProfileEvents::CASRefAppendWedged]; + + const KilledLeaderOutcome out = runKilledLeaderChunk(fx); + + ASSERT_TRUE(fx.faults->fired) << "the kill never ran before the chunk's create"; + EXPECT_EQ(exceptionCode(out.leader.result.err), 0) << "a killed query's carved item commits"; + EXPECT_EQ(exceptionCode(out.neighbor.err), 0) << "a live neighbor must commit"; + EXPECT_EQ(out.leader.result.id, out.neighbor.id) << "both items were in one chunk"; + EXPECT_EQ(out.neighbor_builds, 1); + EXPECT_TRUE(out.leader.group_restored); + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRefAppendWedged] - wedged_before, 0u); + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + EXPECT_EQ(std::count_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == out.neighbor.id; }), 1) + << "the chunk is durable exactly once"; +} + +/// Leaving a query's thread group finalizes the thread's counters and writes a `system.query_thread_log` row, so a +/// leader must flush in its caller's group: the same group before the append, inside the flush and after it. +TEST(CASRefWriterChunkedFlush, LeaderFlushesInItsCallersThreadGroup) +{ + KilledLeaderFixture fx("leader_keeps_thread_group"); + DB::ThreadGroupPtr group_before; + DB::ThreadGroupPtr group_inside_flush; + DB::ThreadGroupPtr group_after; + bool hook_ran = false; + + std::thread leader_thread; + std::future leader = launchQueryLeader(leader_thread, [&](CasKillableQuery &) + { + group_before = DB::CurrentThread::getGroup(); + fx.store->setRefPreCarveHookForTest([&] + { + hook_ran = true; + group_inside_flush = DB::CurrentThread::getGroup(); + }); + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [](const RefTableState &) { return addRemovePrecommitPairs("item_leader", 1, 945000001); }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + group_after = DB::CurrentThread::getGroup(); + return r; + }); + ASSERT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready); + const LeaderRun run = leader.get(); + leader_thread.join(); + fx.store->setRefPreCarveHookForTest(nullptr); + + EXPECT_EQ(exceptionCode(run.result.err), 0); + ASSERT_TRUE(hook_ran) << "the hook did not run inside the flush"; + ASSERT_NE(group_before, nullptr); + EXPECT_EQ(group_inside_flush, group_before) << "the flush left the caller's thread group"; + EXPECT_EQ(group_after, group_before); + EXPECT_TRUE(run.group_restored); +} + +namespace +{ + +/// The leader's owner stops during the flush prelude while a live waiter's item is queued behind it. +void runLeaderStoppedDuringFlushPrelude(StoppedBy owner) +{ + KilledLeaderFixture fx("killed_leader_withdraws"); + auto leader_builds = std::make_shared>(0); + auto neighbor_builds = std::make_shared>(0); + auto sync = std::make_shared(); + std::function stop_leader; + + fx.store->setRefPreCarveHookForTest([&, sync] + { + std::unique_lock lk(sync->m); + if (sync->entered) + return; + sync->entered = true; + sync->cv.notify_all(); + sync->cv.wait_for(lk, KILL_WATCHDOG, [&] { return fx.store->refQueuePendingForTest(fx.ns) >= 2; }); + stop_leader(); + }); + + std::thread leader_thread; + std::future leader = launchQueryLeader(leader_thread, [&](CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = backgroundOwnerStoppedBy(background_stopped); + stop_leader = stopperOf(owner, query, background_stopped); + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [leader_builds](const RefTableState &) + { + leader_builds->fetch_add(1); + return addRemovePrecommitPairs("item_leader", 1, 920000001); + }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + return r; + }); + waitEntered(sync); + AppendCaller neighbor = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_neighbor"), + addRemovePrecommitPairs("item_neighbor", 1, 920000002), neighbor_builds); + waitPendingAtLeast(fx.store, fx.ns, 2); + sync->cv.notify_all(); + + ASSERT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the stopped leader must not hang"; + ASSERT_EQ(neighbor.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the neighbor must not hang"; + const LeaderRun run = leader.get(); + const AppendResult rn = neighbor.fut.get(); + leader_thread.join(); + neighbor.t.join(); + fx.store->setRefPreCarveHookForTest(nullptr); + + EXPECT_EQ(exceptionCode(rn.err), 0) << "the live waiter commits"; + EXPECT_EQ(neighbor_builds->load(), 1); + EXPECT_TRUE(run.group_restored); + EXPECT_EQ(fx.store->refQueuePendingForTest(fx.ns), 0u); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + const auto neighbor_txn = std::find_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == rn.id; }); + ASSERT_NE(neighbor_txn, logs.end()); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(exceptionCode(run.result.err), DB::ErrorCodes::ABORTED); + EXPECT_EQ(leader_builds->load(), 0) << "a withdrawn item is never built"; + EXPECT_EQ(neighbor_txn->ops, addRemovePrecommitPairs("item_neighbor", 1, 920000002)) << "the neighbor commits alone"; + } + else + { + EXPECT_EQ(exceptionCode(run.result.err), 0) << "a killed leader's item commits"; + EXPECT_EQ(leader_builds->load(), 1); + EXPECT_EQ(run.result.id, rn.id) << "both items were carved into one chunk"; + } +} + +} + +/// A background stop during the flush prelude withdraws the leader's own item at the carve: its `build_ops` never +/// runs, it gets the owner's verdict, and the live waiter's item commits alone. +TEST(CASRefWriterChunkedFlush, BackgroundStoppedLeaderWithdrawsOwnItemAtCarve) +{ + runLeaderStoppedDuringFlushPrelude(StoppedBy::Background); +} + +/// A leader killed during the flush prelude keeps its item: it is carved with the waiter's and the chunk commits for both. +TEST(CASRefWriterChunkedFlush, KilledLeadersItemIsCarvedAndCommitted) +{ + runLeaderStoppedDuringFlushPrelude(StoppedBy::Query); +} + +namespace +{ + +/// A leader whose owner stopped before its flush, on a lane with an outstanding wedge. +void runLeaderStoppedBeforeItsFlush(StoppedBy owner) +{ + KilledLeaderFixture fx("killed_leader_before_flush"); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + ASSERT_FALSE(logs.empty()); + RefLogTxn wedged; + wedged.ns = fx.ns.string(); + wedged.txn_id = logs.back().txn_id; + ++wedged.txn_id.ref_sequence; + wedged.ops = addRemovePrecommitPairs("item_wedged", 1, 940000002); + fx.store->forceWedgeForTest(fx.ns, wedged.txn_id.writer_epoch, wedged.txn_id.ref_sequence, + fx.store->layout().refLogKey(DB::Cas::tests::fixture::fixtureLife(fx.ns), wedged.txn_id), + sealObject(FormatId::RefLog, encodeRefLogTxn(wedged))); + auto builds = std::make_shared>(0); + size_t requests = 0; + + std::thread leader_thread; + std::future leader = launchQueryLeader(leader_thread, [&](CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = backgroundOwnerStoppedBy(background_stopped); + stopperOf(owner, query, background_stopped)(); + const size_t before = fx.faults->journal().size(); + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref("item_leader"), + [builds](const RefTableState &) + { + builds->fetch_add(1); + return addRemovePrecommitPairs("item_leader", 1, 940000001); + }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + requests = fx.faults->journal().size() - before; + return r; + }); + ASSERT_EQ(leader.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the stopped leader must not hang"; + const LeaderRun run = leader.get(); + leader_thread.join(); + + EXPECT_EQ(fx.store->refQueuePendingForTest(fx.ns), 0u); + EXPECT_TRUE(run.group_restored); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(exceptionCode(run.result.err), DB::ErrorCodes::ABORTED); + EXPECT_EQ(requests, 0u) << "a stopped leader starts no flush"; + EXPECT_EQ(builds->load(), 0); + EXPECT_TRUE(fx.store->refLaneWedgedForTest(fx.ns)) << "the wedge is left for a live leader"; + } + else + { + EXPECT_EQ(exceptionCode(run.result.err), 0) << "a killed query's leader flushes on a healthy store"; + EXPECT_GT(requests, 0u); + EXPECT_EQ(builds->load(), 1); + EXPECT_FALSE(fx.store->refLaneWedgedForTest(fx.ns)) << "the leader resolved the wedge"; + } +} + +} + +/// A leader whose background owner stopped before its flush sends nothing: not even the read that resolves the lane's +/// outstanding wedge. The carve check alone would let that read go out first. +TEST(CASRefWriterChunkedFlush, BackgroundStoppedLeaderSendsNothingBeforeItsFlush) +{ + runLeaderStoppedBeforeItsFlush(StoppedBy::Background); +} + +/// A leader whose query was killed before its flush flushes on a healthy store: it resolves the wedge and commits its +/// item. +TEST(CASRefWriterChunkedFlush, KilledLeaderResolvesTheWedgeAndCommits) +{ + runLeaderStoppedBeforeItsFlush(StoppedBy::Query); +} + +namespace +{ + +template +void waitUntil(const char * what, Body ready) +{ + const auto deadline = std::chrono::steady_clock::now() + KILL_WATCHDOG; + while (!ready() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + ASSERT_TRUE(ready()) << what; +} + +/// A follower on its own query thread. Its `build_ops` runs `on_build` and writes into a local of the follower's +/// own frame, so a follower that returned while its item was carved would leave the leader writing to a dead +/// frame (ASan reports it). `returned` is set when the follower's call has returned. +std::future launchQueryFollower( + std::thread & thread, KilledLeaderFixture & fx, const String & ref, std::atomic & builds, int64_t seed, + std::function & kill, std::function on_build, std::atomic & returned, StoppedBy owner) +{ + return launchQueryLeader( + thread, [&fx, ref, &builds, seed, &kill, build_hook = std::move(on_build), &returned, owner](CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = backgroundOwnerStoppedBy(background_stopped); + kill = stopperOf(owner, query, background_stopped); + int frame_slot = 0; + AppendResult r; + try + { + r.id = fx.store->appendRefOps(fx.ns, MutationScope::ref(ref), + [&builds, &frame_slot, build_hook, ref, seed](const RefTableState &) + { + builds.fetch_add(1); + if (build_hook) + build_hook(); + frame_slot = 1; + return addRemovePrecommitPairs(ref, 1, seed); + }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + } + catch (...) + { + r.err = std::current_exception(); + } + returned = true; + return r; + }); +} + +} + +namespace +{ + +/// A follower's owner stops while its item is queued behind a parked leader. +void runFollowerStoppedWhileQueued(StoppedBy owner) +{ + KilledLeaderFixture fx("killed_pending_follower"); + auto sync = std::make_shared(); + bool released = false; + fx.store->setRefPreCarveHookForTest([sync, &released] + { + std::unique_lock lk(sync->m); + if (sync->entered) + return; + sync->entered = true; + sync->cv.notify_all(); + sync->cv.wait_for(lk, KILL_WATCHDOG, [&] { return released; }); + }); + auto leader_builds = std::make_shared>(0); + std::atomic follower_builds{0}; + std::atomic follower_returned{false}; + std::function stop_follower; + std::atomic follower_wait_checks{0}; + fx.store->setRefFollowerWaitHookForTest([&](FollowerWaitPhase) { follower_wait_checks.fetch_add(1); }); + + AppendCaller leader = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_leader"), + addRemovePrecommitPairs("item_leader", 1, 950000001), leader_builds); + waitEntered(sync); + std::thread follower_thread; + std::future follower = launchQueryFollower( + follower_thread, fx, "item_follower", follower_builds, 950000002, stop_follower, {}, follower_returned, owner); + waitPendingAtLeast(fx.store, fx.ns, 2); + ASSERT_GE(fx.store->refQueuePendingForTest(fx.ns), 2u); + const int checks_before_stop = follower_wait_checks.load(); + stop_follower(); + /// The leader stays parked until a stopped background owner's follower has left the queue. A killed query's + /// follower is given two evaluations of its wait, so its owner was asked after the kill, and must still be queued. + if (owner == StoppedBy::Background) + { + waitUntil("the stopped follower never withdrew its item", [&] { return fx.store->refQueuePendingForTest(fx.ns) <= 1; }); + } + else + { + waitUntil("the follower's wait was not re-evaluated", [&] { return follower_wait_checks.load() >= checks_before_stop + 2; }); + EXPECT_EQ(fx.store->refQueuePendingForTest(fx.ns), 2u) << "a killed query's follower withdrew its item"; + } + { + std::lock_guard lk(sync->m); + released = true; + } + sync->cv.notify_all(); + + ASSERT_EQ(follower.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the stopped follower must not hang"; + ASSERT_EQ(leader.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the leader must not hang"; + const LeaderRun run = follower.get(); + const AppendResult rl = leader.fut.get(); + follower_thread.join(); + leader.t.join(); + fx.store->setRefPreCarveHookForTest(nullptr); + fx.store->setRefFollowerWaitHookForTest(nullptr); + + EXPECT_EQ(exceptionCode(rl.err), 0); + EXPECT_EQ(leader_builds->load(), 1); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + const auto leader_txn = std::find_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == rl.id; }); + ASSERT_NE(leader_txn, logs.end()); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(exceptionCode(run.result.err), DB::ErrorCodes::ABORTED); + EXPECT_EQ(follower_builds.load(), 0) << "a withdrawn item is never built"; + EXPECT_EQ(leader_txn->ops, addRemovePrecommitPairs("item_leader", 1, 950000001)) << "the withdrawn item is absent"; + } + else + { + EXPECT_EQ(exceptionCode(run.result.err), 0) << "a killed query's queued item commits"; + EXPECT_EQ(follower_builds.load(), 1); + const bool follower_committed + = std::any_of(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == run.result.id; }); + EXPECT_TRUE(follower_committed); + } +} + +} + +/// A follower whose background owner stopped while its item is queued withdraws it: it gets the owner's verdict, its +/// `build_ops` never runs, nothing of it reaches the log, and the leader then commits alone. +TEST(CASRefWriterChunkedFlush, BackgroundStoppedPendingFollowerWithdrawsWhileLeaderBlocked) +{ + runFollowerStoppedWhileQueued(StoppedBy::Background); +} + +/// A follower whose query was killed while its item is queued stays queued and commits with the leader. +TEST(CASRefWriterChunkedFlush, KilledPendingFollowerStaysQueuedAndCommits) +{ + runFollowerStoppedWhileQueued(StoppedBy::Query); +} + +/// A follower whose item was carved belongs to the batch: its background owner stops after the carve and before +/// its `build_ops` returns, and the follower sees the stop while the item is carved and not done. It still waits +/// for the chunk and returns the committed id. A killed query's follower never sees a stop and gets the same id. +TEST(CASRefWriterChunkedFlush, KilledCarvedFollowerWaitsForActualResult) +{ + for (const StoppedBy owner : {StoppedBy::Background, StoppedBy::Query}) + { + SCOPED_TRACE(nameOf(owner)); + KilledLeaderFixture fx("killed_carved_follower"); + auto sync = std::make_shared(); + armPreCarveBlock(fx.store, fx.ns, sync, 2); + auto leader_builds = std::make_shared>(0); + std::atomic follower_builds{0}; + std::atomic follower_returned{false}; + std::atomic carved_waits{0}; + std::function stop_follower; + fx.store->setRefFollowerWaitHookForTest([&](FollowerWaitPhase phase) + { + if (phase == FollowerWaitPhase::Carved) + carved_waits.fetch_add(1); + }); + /// Runs on the leader's thread, after the carve: stop the follower, then hold the batch until a stopped + /// background owner's follower has seen the stop and entered its carved wait, or has wrongly returned. + const auto stop_follower_while_carved = [&] + { + stop_follower(); + if (owner == StoppedBy::Query) + return; + const auto deadline = std::chrono::steady_clock::now() + KILL_WATCHDOG; + while (carved_waits.load() == 0 && !follower_returned && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + }; + + AppendCaller leader = launchAppendOps(fx.store, fx.ns, MutationScope::ref("item_leader"), + addRemovePrecommitPairs("item_leader", 1, 960000001), leader_builds); + waitEntered(sync); + std::thread follower_thread; + std::future follower = launchQueryFollower( + follower_thread, fx, "item_follower", follower_builds, 960000002, stop_follower, stop_follower_while_carved, + follower_returned, owner); + waitPendingAtLeast(fx.store, fx.ns, 2); + sync->cv.notify_all(); + + ASSERT_EQ(follower.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the carved follower must not hang"; + ASSERT_EQ(leader.fut.wait_for(KILL_WATCHDOG), std::future_status::ready) << "the leader must not hang"; + const LeaderRun run = follower.get(); + const AppendResult rl = leader.fut.get(); + follower_thread.join(); + leader.t.join(); + fx.store->setRefFollowerWaitHookForTest(nullptr); + fx.store->setRefPreCarveHookForTest(nullptr); + + if (owner == StoppedBy::Background) + EXPECT_GE(carved_waits.load(), 1) << "the follower never saw its stop while its item was carved"; + else + EXPECT_EQ(carved_waits.load(), 0) << "a killed query is not a stop for the follower's wait"; + EXPECT_EQ(exceptionCode(run.result.err), 0) << "a carved item reports its chunk's result, not its owner's verdict"; + EXPECT_EQ(exceptionCode(rl.err), 0); + EXPECT_EQ(run.result.id, rl.id) << "both items were in one chunk"; + EXPECT_EQ(follower_builds.load(), 1); + const std::vector logs = listLogTxns(*fx.faults, fx.store->layout(), fx.ns); + EXPECT_EQ(std::count_if(logs.begin(), logs.end(), [&](const RefLogTxn & txn) { return txn.txn_id == rl.id; }), 1); + } +} diff --git a/src/Disks/tests/gtest_cas_ref_lane_exception_safety.cpp b/src/Disks/tests/gtest_cas_ref_lane_exception_safety.cpp index a88838dd70493..965e45452c1d4 100644 --- a/src/Disks/tests/gtest_cas_ref_lane_exception_safety.cpp +++ b/src/Disks/tests/gtest_cas_ref_lane_exception_safety.cpp @@ -2,11 +2,14 @@ #include #include +#include #include #include #include +#include #include +#include #include #include #include @@ -215,3 +218,116 @@ TEST(CASRefWriterLaneExceptionSafety, PreTenureAllocFailureReleasesBaton) EXPECT_FALSE(store->refLeaderActiveForTest(ns)) << "a pre-tenure allocation failure left the append-lane baton held with no live leader"; } + +/// A removal waits, untimed, until the lane drains. When the last queued writer withdraws at the pre-tenure point, +/// that withdrawal is the drain, so it must wake the removal: no other writer is admitted to do it. +TEST(CASRefWriterLaneExceptionSafety, PreTenureFailureOfTheLastQueuedWriterWakesAWaitingRemoval) +{ + auto backend = std::make_shared(); + auto store = openPoolForRefLane(backend); + const RootNamespace ns{"srv1/reflane_pretenure_removal"}; + /// One ref for every writer: the leader never carves a second item of the same ref into its batch. + const auto append = [&] + { + store->appendRefOps(ns, MutationScope::ref("ref"), + [](const RefTableState &) -> std::vector { return {}; }, + RootMutationOrigin::Writer, RootMutationKind::Publish); + }; + append(); + + std::mutex m; + std::condition_variable cv; + bool leader_parked = false; + bool release_leader = false; + bool park_follower = false; + bool follower_parked = false; + bool release_follower = false; + + std::atomic park_leader{1}; + store->setRefPreCarveHookForTest([&] + { + if (park_leader.exchange(0) != 1) + return; + std::unique_lock lock(m); + leader_parked = true; + cv.notify_all(); + cv.wait(lock, [&] { return release_leader; }); + }); + std::thread leader(append); + { + std::unique_lock lock(m); + cv.wait(lock, [&] { return leader_parked; }); + } + + /// A background owner is polled outside the queue mutex while the follower waits, which is where it is held. + std::thread follower([&] + { + const auto owner = OwnerScope::background([&] + { + std::unique_lock lock(m); + if (!park_follower) + return; + follower_parked = true; + cv.notify_all(); + cv.wait(lock, [&] { return release_follower; }); + }); + EXPECT_THROW(append(), DB::Exception) << "the follower must see its own pre-tenure failure"; + }); + while (store->refQueuePendingForTest(ns) < 2) + std::this_thread::yield(); + { + std::unique_lock lock(m); + park_follower = true; + cv.wait(lock, [&] { return follower_parked; }); + release_leader = true; + } + cv.notify_all(); + leader.join(); + ASSERT_EQ(store->refQueuePendingForTest(ns), 1u) << "the follower's item must still be queued"; + ASSERT_FALSE(store->refLeaderActiveForTest(ns)); + + std::atomic tenure_fault{1}; + store->setRefPreTenureHookForTest([&] + { + if (tenure_fault.exchange(0) == 1) + throw DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "injected pre-tenure fault"); + }); + auto removal = std::make_shared>(); + std::future removal_done = removal->get_future(); + std::thread remover([store, ns, removal] + { + try + { + (void)store->dropNamespace(ns); + removal->set_value(nullptr); + } + catch (...) + { + removal->set_value(std::current_exception()); + } + }); + /// The removal closes admission and checks the drain in one critical section, so from here it is waiting. + while (!store->removalFlagsForTest(ns).admission_closed) + std::this_thread::yield(); + { + std::lock_guard lock(m); + release_follower = true; + } + cv.notify_all(); + follower.join(); + + const bool woke = removal_done.wait_for(std::chrono::seconds(10)) == std::future_status::ready; + EXPECT_TRUE(woke) << "the removal still waits for a lane that is already drained"; + if (!woke) + { + /// Nothing can wake it now; leave it parked rather than hang the binary. + remover.detach(); + return; + } + remover.join(); + store->setRefPreTenureHookForTest(nullptr); + store->setRefPreCarveHookForTest(nullptr); + const std::exception_ptr error = removal_done.get(); + EXPECT_FALSE(error) << "the removal must complete"; + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} diff --git a/src/Disks/tests/gtest_cas_ref_recovery_cas_walk.cpp b/src/Disks/tests/gtest_cas_ref_recovery_cas_walk.cpp index 44e3ac2222979..662d399932e88 100644 --- a/src/Disks/tests/gtest_cas_ref_recovery_cas_walk.cpp +++ b/src/Disks/tests/gtest_cas_ref_recovery_cas_walk.cpp @@ -5,6 +5,7 @@ #include "config.h" #include +#include #include #include #include @@ -14,8 +15,11 @@ #include #include #include +#include #include #include +#include +#include #include #include @@ -57,9 +61,12 @@ namespace DB::ErrorCodes { +extern const int ABORTED; extern const int CORRUPTED_DATA; extern const int INVALID_STATE; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; +extern const int READONLY; } namespace ProfileEvents @@ -72,10 +79,12 @@ extern const Event CASRefRecoveryCancelled; extern const Event CASRefCheckpointPublished; extern const Event CASRefCheckpointStamped; extern const Event CASRefAppendTombstoneWritten; +extern const Event CASRefRecoveryRetries; } using namespace DB::Cas; using DB::Cas::tests::VirtualRetryClock; +using DB::Cas::tests::onKillableQueryThread; using DB::Cas::tests::committedRow; using DB::Cas::tests::CountingBackend; using DB::Cas::tests::expectThrowsCode; @@ -1138,7 +1147,6 @@ TEST(CASRefRecoveryCasWalk, UnresolvedRecoveryStampWritesNoTombstoneAndInstallsN auto fake_now = std::make_shared>(1'000'000); PoolConfig config = walkTestConfig(); config.boot_ms_fn = [fake_now] { return fake_now->load(); }; - config.cas_request_budget.recovery_retry_budget_ms = 1; config.cas_request_budget.recovery_retry_initial_backoff_ms = 1; config.cas_request_budget.recovery_retry_max_backoff_ms = 1; auto store = openWalkPool(backend, config); @@ -1162,6 +1170,119 @@ TEST(CASRefRecoveryCasWalk, UnresolvedRecoveryStampWritesNoTombstoneAndInstallsN EXPECT_FALSE(store->refTableRecoveredForTest(ns)) << "nothing is installed"; } +namespace +{ + +/// Runs `on_settle` once, in the first read of `watched_key` after a write of it was refused. +class SettleHookBackend : public HidingListBackend +{ +public: + String watched_key; + uint64_t writes_at_arm = 0; + std::function on_settle; + + std::optional read(const String & key, DB::Cas::TransportAccess & access) override + { + if (key == watched_key && on_settle && writeCount(key) > writes_at_arm) + std::exchange(on_settle, nullptr)(); + return HidingListBackend::read(key, access); + } +}; + +struct StoppedConflictRun +{ + int code = 0; + String message; + uint64_t stamp_writes = 0; + uint64_t tombstone_writes = 0; +}; + +/// A recovery that seals dead epoch 1, run by a query; the write of `refused` (the stamp or the tombstone) is refused +/// with 412, and with `kill` the query is killed in the read that settles that refusal, which then fails. +StoppedConflictRun runRecoveryWithARefusedWrite(bool refuse_stamp, bool kill) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + const RootNamespace ns{refuse_stamp ? "srv1/stamp_conflict" : "srv1/tombstone_conflict"}; + burnEpochsUpTo(backend, layout, 2); + seedTxn(*backend, layout, ns, RefTxnId{1, 1}, "a", /*birth=*/true); + seedCkpt(*backend, layout, ns, lifeEpochCkpt(1, RefTxnId{1, 1})); + const NamespaceLifeId life = catalogLife(backend, layout, ns); + const String ckpt_key = layout.refCkptKey(life); + const String tombstone_key = layout.refLogKey(life, RefTxnId{1, 2}); + auto store = openWalkPool(backend); + store->setCasRetrySleepForTest([](uint64_t) {}); + + backend->watched_key = refuse_stamp ? ckpt_key : tombstone_key; + backend->writes_at_arm = backend->writeCount(backend->watched_key); + backend->refuseNextWrite(backend->watched_key); + const uint64_t stamp_writes_before = backend->writeCount(ckpt_key); + const uint64_t tombstone_writes_before = backend->writeCount(tombstone_key); + + StoppedConflictRun run; + std::thread caller([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + if (kill) + backend->on_settle = [&query] + { + query.kill(); + throw Poco::TimeoutException("SettleHookBackend: the settling read timed out"); + }; + try + { + (void)store->listRefs(ns); + } + catch (const DB::Exception & e) + { + run.code = e.code(); + run.message = e.message(); + } + backend->on_settle = nullptr; + }); + caller.join(); + run.stamp_writes = backend->writeCount(ckpt_key) - stamp_writes_before; + run.tombstone_writes = backend->writeCount(tombstone_key) - tombstone_writes_before; + return run; +} + +} + +/// A refused stamp whose settling read the query's stop cut short ends that walk: the 412 proves the stamp did not +/// land, so the error is a retry-later naming the stop, and no second walk sends a second stamp. A clean refusal +/// restarts the walk, whose second stamp lands. +TEST(CASRefRecoveryCasWalk, RefusedStampSettledUnderAStoppedQueryEndsTheWalk) +{ + { + SCOPED_TRACE("killed in the settling read"); + const auto run = runRecoveryWithARefusedWrite(/*refuse_stamp=*/true, /*kill=*/true); + EXPECT_EQ(run.code, DB::ErrorCodes::NETWORK_ERROR) << run.message; + EXPECT_NE(run.message.find("stopped after its refused generation 3 stamp"), String::npos) << run.message; + EXPECT_EQ(run.stamp_writes, 1u) << "one walk, one stamp"; + EXPECT_EQ(run.tombstone_writes, 0u); + } + { + SCOPED_TRACE("live"); + const auto run = runRecoveryWithARefusedWrite(/*refuse_stamp=*/true, /*kill=*/false); + EXPECT_EQ(run.code, 0) << run.message; + EXPECT_EQ(run.stamp_writes, 2u) << "the refused stamp, then the restarted walk's stamp"; + EXPECT_EQ(run.tombstone_writes, 1u); + } +} + +/// The same for the tombstone: its settling read observed nothing, so the walk ends with a retry-later and chases no +/// successor. +TEST(CASRefRecoveryCasWalk, RefusedTombstoneSettledUnderAStoppedQueryEndsTheWalk) +{ + const auto run = runRecoveryWithARefusedWrite(/*refuse_stamp=*/false, /*kill=*/true); + EXPECT_EQ(run.code, DB::ErrorCodes::NETWORK_ERROR) << run.message; + EXPECT_NE(run.message.find("could not observe"), String::npos) << run.message; + EXPECT_EQ(run.stamp_writes, 1u); + EXPECT_EQ(run.tombstone_writes, 1u) << "one walk, one tombstone"; +} + /// GENESIS. A namespace born at epoch 5 has no epochs 1-4 of its own: they are not "empty epochs it /// failed to close", they are epochs before it existed. The walk starts at the namespace's `life_epoch` /// and writes no phantom seals below it, and with no transition ever having happened it installs NO @@ -1992,6 +2113,43 @@ TEST(CASRefRecoveryCasWalk, RecoveryRequestSequenceStampsThenWritesOneTombstone) EXPECT_EQ(store->refRecoveryRestartsForTest(ns), 0u); } +/// A cold read by a stopped query still recovers the table: the one recovery walk, its stamp and its +/// tombstone included, is owed, so a healthy store answers with every committed ref. +TEST(CASRefRecoveryCasWalk, KilledColdReaderStillRecoversWithStampOrTombstone) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + const RootNamespace ns{"srv1/killed_cold_reader"}; + + burnEpochsUpTo(backend, layout, /*target_live_epoch=*/4); + seedCkpt(*backend, layout, ns, lifeEpochCkpt(1, RefTxnId{1, 2})); + seedTxn(*backend, layout, ns, RefTxnId{1, 1}, "a", /*birth=*/true); + seedTxn(*backend, layout, ns, RefTxnId{1, 2}, "b", /*birth=*/false); + seedTxn(*backend, layout, ns, RefTxnId{1, 3}, "c", /*birth=*/false); + + auto store = openWalkPool(backend); + ASSERT_TRUE(store); + const uint64_t stamped_before = ProfileEvents::global_counters[ProfileEvents::CASRefCheckpointStamped]; + const uint64_t sealed_before = ProfileEvents::global_counters[ProfileEvents::CASRefRecoveryEpochSealed]; + + size_t refs = 0; + std::thread reader([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + EXPECT_NO_THROW(refs = store->listRefs(ns).size()); + }); + reader.join(); + + EXPECT_EQ(refs, 3u) << "every committed ref stays visible"; + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRefCheckpointStamped] - stamped_before, 1u) + << "the walk stamped the checkpoint"; + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRefRecoveryEpochSealed] - sealed_before, 1u) + << "the walk sealed the dead epoch with a tombstone"; +} + /// --------------------------------------------------------------------------------------------- /// Generation 3: one-request append, forward-linked tombstones, uniform genesis /// --------------------------------------------------------------------------------------------- @@ -3408,3 +3566,259 @@ TEST(CASRefWriterTombstone, TombstoneInstallRefusedAfterItsCreateNeedsRecoveryAn << "no second tombstone"; EXPECT_TRUE(store->listRefs(ns).contains("c")); } + +/// --------------------------------------------------------------------------------------------- +/// A stopped owner and the stamp and tombstone writes of recovery +/// --------------------------------------------------------------------------------------------- + +namespace +{ + +/// Loses the reply of the next `lost_replies` writes of `watched_key` before they apply, after `on_lost` +/// runs, so the settling read finds the old state, which proves neither way. `refused_writes` refuses +/// the next writes of the key instead. Counts every write of the key. +class LostWriteReplyBackend : public JournalingBackend +{ +public: + String watched_key; + std::atomic lost_replies{0}; + std::atomic refused_writes{0}; + std::atomic writes_of_watched_key{0}; + std::function on_lost; + + std::expected write( + const String & key, const String & bytes, const std::optional & expected_value, + DB::Cas::TransportAccess & access) override + { + if (key == watched_key) + { + ++writes_of_watched_key; + if (refused_writes.fetch_sub(1) > 0) + throw DB::Exception(DB::ErrorCodes::READONLY, "test: the store refuses the write"); + if (lost_replies.fetch_sub(1) > 0) + { + if (on_lost) + on_lost(); + throw Poco::TimeoutException("test: the write's reply is lost"); + } + } + return JournalingBackend::write(key, bytes, expected_value, access); + } +}; + +struct ResidentStampRecovery +{ + std::shared_ptr backend; + PoolPtr store; + RootNamespace ns; + NamespaceLifeId life; + String ckpt_key; + String tombstone_key; +}; + +/// A namespace whose recovery stamps its generation 1 `_ckpt`, then closes the dead epoch 1 with a +/// tombstone at {1,4}. Its runtime is resident and unrecovered: a first recovery failed before its first +/// request, so the next `namespaceLife` recovers it in place. +ResidentStampRecovery openResidentStampRecovery(const String & name, uint64_t backoff_ms = 1) +{ + auto backend = std::make_shared(); + const RootNamespace ns{"srv1/" + name}; + const Layout layout("p"); + burnEpochsUpTo(backend, layout, /*target_live_epoch=*/4); + seedCkpt(*backend, layout, ns, lifeEpochCkpt(1, RefTxnId{1, 2})); + seedTxn(*backend, layout, ns, RefTxnId{1, 1}, "a", /*birth=*/true); + seedTxn(*backend, layout, ns, RefTxnId{1, 2}, "b", /*birth=*/false); + seedTxn(*backend, layout, ns, RefTxnId{1, 3}, "c", /*birth=*/false); + + auto fail_first = std::make_shared>(true); + PoolConfig config = walkTestConfig(); + config.cas_request_budget.recovery_retry_initial_backoff_ms = backoff_ms; + config.cas_request_budget.recovery_retry_max_backoff_ms = backoff_ms; + config.recovery_pre_first_request_hook_for_test = [fail_first] + { + if (fail_first->exchange(false)) + throw DB::Exception(DB::ErrorCodes::ABORTED, "test: the first recovery fails before its first request"); + }; + PoolPtr store = openWalkPool(backend, config); + const NamespaceLifeId life = catalogLife(backend, layout, ns); + expectThrowsCode(DB::ErrorCodes::ABORTED, [&] { (void)store->namespaceLife(ns); }); + EXPECT_NE(store->refTableRuntimeIdentityForTest(ns), 0u) << "the runtime stays resident"; + EXPECT_FALSE(store->refTableRecoveredForTest(ns)); + return ResidentStampRecovery{ + .backend = backend, + .store = store, + .ns = ns, + .life = life, + .ckpt_key = layout.refCkptKey(life), + .tombstone_key = layout.refLogKey(life, RefTxnId{1, 4})}; +} + +/// The owner stops while the reply of the recovery's write at `key` is lost: the caller of `namespaceLife` +/// sees the unresolved 210 after one send, nothing is installed and the catalog row is unchanged. Control: +/// a live owner retries and recovers. +void expectStoppedOwnerKeepsUnresolvedRecoveryWrite(bool tombstone) +{ + const String unresolved_message = tombstone + ? "the tombstone at 1-4 is UNRESOLVED" + : "the generation 3 stamp of its `_ckpt` is unresolved"; + for (const bool stop : {true, false}) + { + SCOPED_TRACE(stop ? "stopped owner" : "control: live owner"); + auto fx = openResidentStampRecovery(fmt::format("unresolved_{}_{}", tombstone ? "tombstone" : "stamp", stop ? "stopped" : "live")); + const uint64_t installs_before = fx.store->recoveryInstallCountForTest(); + fx.backend->watched_key = tombstone ? fx.tombstone_key : fx.ckpt_key; + fx.backend->lost_replies = 1; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + if (stop) + { + fx.backend->on_lost = [&query] { query.kill(); }; + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, unresolved_message, + [&] { (void)fx.store->namespaceLife(fx.ns); }); + } + else + { + EXPECT_NO_THROW((void)fx.store->namespaceLife(fx.ns)); + } + fx.backend->on_lost = {}; + }); + if (stop) + { + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 1) << "the lost write is not sent again"; + EXPECT_EQ(fx.store->recoveryInstallCountForTest(), installs_before); + EXPECT_FALSE(fx.store->refTableRecoveredForTest(fx.ns)); + EXPECT_EQ(catalogLife(fx.backend, Layout("p"), fx.ns), fx.life) << "the catalog row is unchanged"; + } + else + { + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 2); + EXPECT_EQ(fx.store->recoveryInstallCountForTest(), installs_before + 1); + } + } +} + +} + +TEST(CASRefWriterRecoveryRetry, UnresolvedStampThenStopKeepsUnresolvedExitThroughNamespaceLife) +{ + expectStoppedOwnerKeepsUnresolvedRecoveryWrite(/*tombstone=*/false); +} + +TEST(CASRefWriterRecoveryRetry, UnresolvedTombstoneThenStopKeepsUnresolvedExitThroughNamespaceLife) +{ + expectStoppedOwnerKeepsUnresolvedRecoveryWrite(/*tombstone=*/true); +} + +/// The catalog row is removed and replaced while the stamp's reply is lost: the stopped caller sees the +/// unresolved 210 and starts no work on the successor life. +TEST(CASRefWriterRecoveryRetry, UnresolvedStampThenStopThroughNamespaceLifeWithRowGone) +{ + auto fx = openResidentStampRecovery("unresolved_stamp_row_gone"); + const Layout layout("p"); + const CatalogEntry predecessor{.ns = fx.life.ns, .state = NsState::Live, .incarnation = fx.life.incarnation, .creator = std::nullopt}; + std::optional successor; + size_t journal_at_loss = 0; + fx.backend->watched_key = fx.ckpt_key; + fx.backend->lost_replies = 1; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + fx.backend->on_lost = [&] + { + successor = replaceCatalogLifeForTest(fx.backend, layout, predecessor, DB::UInt128(0x5eed)); + query.kill(); + journal_at_loss = fx.backend->journal().size(); + }; + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + "the generation 3 stamp of its `_ckpt` is unresolved", [&] { (void)fx.store->namespaceLife(fx.ns); }); + fx.backend->on_lost = {}; + }); + ASSERT_TRUE(successor); + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 1); + const NamespaceLifeId successor_life = NamespaceLifeId::fromCatalogEntry(successor->ns, successor->incarnation); + const auto journal = fx.backend->journal(); + for (size_t i = journal_at_loss; i < journal.size(); ++i) + { + const auto & [method, key] = journal[i]; + EXPECT_TRUE(method == "GET" || method == "HEAD") << method << " " << key << ": no write after the stop"; + EXPECT_FALSE(key.starts_with(layout.namespaceStreamPrefix(successor_life)) + || key.starts_with(layout.namespaceStatePrefix(successor_life))) + << method << " " << key << ": no request for the successor life"; + } + EXPECT_EQ(fx.store->refTableLifeForTest(fx.ns), std::nullopt) << "the removed life is detached"; +} + +/// The owner stops during the pool's own backoff after a walk whose stamp stayed unresolved: the +/// unresolved 210, not the owner's verdict. +TEST(CASRefWriterRecoveryRetry, StopInBackoffAfterUnresolvedStampKeeps210) +{ + auto fx = openResidentStampRecovery("unresolved_stamp_stop_in_backoff", /*backoff_ms=*/10'000); + fx.backend->watched_key = fx.ckpt_key; + fx.backend->lost_replies = 1; + const uint64_t retries_before = counterOf(ProfileEvents::CASRefRecoveryRetries); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + /// The counter moves right before the backoff starts. + std::thread killer([&] + { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (counterOf(ProfileEvents::CASRefRecoveryRetries) == retries_before && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + query.kill(); + }); + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + "the generation 3 stamp of its `_ckpt` is unresolved", [&] { (void)fx.store->namespaceLife(fx.ns); }); + killer.join(); + }); + EXPECT_GT(counterOf(ProfileEvents::CASRefRecoveryRetries), retries_before) << "the backoff started"; + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 1); + EXPECT_FALSE(fx.store->refTableRecoveredForTest(fx.ns)); +} + +namespace +{ + +/// Runs `namespaceLife` under a background owner that the recovery's backoff stops, so the gate before the next walk +/// is the first check to observe the stop, and expects `code` with `message` after one write of the watched key. +void expectBackgroundStopInBackoff(ResidentStampRecovery & fx, int code, const String & message) +{ + std::atomic stopped{false}; + fx.store->setRefRecoveryRetrySleepForTest([&stopped](uint64_t, const auto &) { stopped = true; }); + { + const auto owner = DB::Cas::OwnerScope::background([&stopped] + { + if (stopped.load()) + throw DB::Exception(DB::ErrorCodes::ABORTED, "test: the background owner stopped"); + }); + DB::Cas::tests::expectThrowsCodeWithMessage(code, message, [&] { (void)fx.store->namespaceLife(fx.ns); }); + } + fx.store->setRefRecoveryRetrySleepForTest([](uint64_t, const auto &) {}); + EXPECT_TRUE(stopped.load()) << "the recovery paused after its failed walk"; + EXPECT_EQ(fx.backend->writes_of_watched_key.load(), 1) << "no walk after the stop"; + EXPECT_FALSE(fx.store->refTableRecoveredForTest(fx.ns)); +} + +} + +/// A background owner stopped after a walk whose stamp or tombstone stayed unresolved gets the unresolved 210, +/// not its own verdict: the write may still land. +TEST(CASRefWriterRecoveryRetry, BackgroundStopAfterUnresolvedWriteKeeps210) +{ + for (const bool tombstone : {false, true}) + { + SCOPED_TRACE(tombstone ? "tombstone" : "stamp"); + auto fx = openResidentStampRecovery(tombstone ? "background_unresolved_tombstone" : "background_unresolved_stamp"); + fx.backend->watched_key = tombstone ? fx.tombstone_key : fx.ckpt_key; + fx.backend->lost_replies = 1; + expectBackgroundStopInBackoff(fx, DB::ErrorCodes::NETWORK_ERROR, + tombstone ? "the tombstone at 1-4 is UNRESOLVED" : "the generation 3 stamp of its `_ckpt` is unresolved"); + } +} + +/// A refused stamp sent nothing that may land, so a background owner stopped after it gets its own verdict. +TEST(CASRefWriterRecoveryRetry, StampRefusalIsNotUnresolved) +{ + auto fx = openResidentStampRecovery("stamp_refusal"); + fx.backend->watched_key = fx.ckpt_key; + fx.backend->refused_writes = 1; + expectBackgroundStopInBackoff(fx, DB::ErrorCodes::ABORTED, "the background owner stopped"); +} diff --git a/src/Disks/tests/gtest_cas_ref_writer.cpp b/src/Disks/tests/gtest_cas_ref_writer.cpp index a38d877aa0926..71ccc60d8e246 100644 --- a/src/Disks/tests/gtest_cas_ref_writer.cpp +++ b/src/Disks/tests/gtest_cas_ref_writer.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -13,9 +14,13 @@ #include #include #include +#include +#include #include #include #include +#include +#include #include #include @@ -28,6 +33,7 @@ #include #include #include +#include #include #include @@ -46,7 +52,10 @@ extern const int CORRUPTED_DATA; extern const int INVALID_STATE; extern const int LOGICAL_ERROR; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; +extern const int READONLY; extern const int S3_ERROR; +extern const int TIMEOUT_EXCEEDED; } namespace ProfileEvents @@ -67,6 +76,9 @@ extern const Event CASGCStuckRemovals; using namespace DB::Cas; using DB::Cas::tests::CountingBackend; +using DB::Cas::tests::exceptionCodeOf; +using DB::Cas::tests::onKillableQueryThread; +using DB::Cas::tests::StoppedBy; using DB::Cas::tests::committedRow; using DB::Cas::tests::expectThrowsCode; using DB::Cas::tests::expectThrowsCodeWithMessage; @@ -5327,6 +5339,200 @@ TEST(CASRefWriterNamespaceRemoval, AmbiguousBeginRemovingKeepsTheWriteLaneClosed EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); } +/// A failure after the lane closed but before the removal's error handler is armed sent nothing, +/// so it must not leave a `Live` lane closed. +TEST(CASRefWriterNamespaceRemoval, ThrowDuringRemovalSetupCannotStrandLiveLane) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/throw_during_removal_setup"}; + publishEmptyPart(store, ns, "owned"); + + store->setRemovalAttemptHookForTest([] { throw std::runtime_error("setup failed"); }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + EXPECT_THROW(store->dropNamespace(ns), std::runtime_error); + store->setRemovalAttemptHookForTest({}); + + EXPECT_NO_THROW(updatePublishedAt(store, ns)) << "the lane of a Live namespace must be open again"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + EXPECT_NO_THROW(store->dropNamespace(ns)); +} + +namespace +{ + +struct StoppedRemovalRun +{ + int failed_catalog_reads = 0; + int catalog_reads_after_failure = 0; +}; + +/// A removal that fails before it sends anything, whose reopen proof's first catalog read fails. The owner +/// stops in the backoff after that failure, where `in_backoff` runs as well. +StoppedRemovalRun runStoppedRemovalBeforeSend(const std::shared_ptr & backend, const PoolPtr & store, + const RootNamespace & ns, const std::function & in_backoff = {}) +{ + const String catalog_key = store->layout().refCatalogKey(); + std::atomic fail_next_catalog_read{false}; + std::atomic failed_catalog_reads{0}; + std::atomic catalog_reads_after_failure{0}; + backend->read_observer = [&](const String & key) + { + if (key != catalog_key) + return; + if (fail_next_catalog_read.exchange(false)) + { + ++failed_catalog_reads; + throw Poco::TimeoutException("the reopen proof's first catalog read is lost"); + } + if (failed_catalog_reads.load() > 0) + ++catalog_reads_after_failure; + }; + SCOPE_EXIT({ backend->read_observer = {}; }); + + std::thread owner_thread([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + store->setCasRetrySleepForTest([&](uint64_t) + { + if (failed_catalog_reads.load() > 0 && !query.status->isKilled()) + { + query.kill(); + if (in_backoff) + in_backoff(); + } + }); + store->setRemovalAttemptHookForTest([&] + { + fail_next_catalog_read = true; + throw std::runtime_error("removal setup failed before any send"); + }); + EXPECT_THROW(store->dropNamespace(ns), std::runtime_error); + EXPECT_TRUE(query.status->isKilled()) << "the owner stopped during the reopen proof"; + store->setRemovalAttemptHookForTest({}); + store->setCasRetrySleepForTest({}); + }); + owner_thread.join(); + return {failed_catalog_reads.load(), catalog_reads_after_failure.load()}; +} + +} + +/// The guard's reopen proof is owed to the closed lane: a removal that fails before it sends anything +/// reopens a proven `Live` lane even when its owner stops during the backoff after a failed first read. +/// Owed work does not widen the reopen: a possible late write or a lost lease still keeps the lane closed. +TEST(CASRefWriterNamespaceRemoval, StoppedRemovalBeforeSendReopensProvenLiveLane) +{ + { + SCOPED_TRACE("exact Live"); + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + const RootNamespace ns{"srv1/stopped_removal_before_send"}; + publishEmptyPart(store, ns, "owned"); + + const StoppedRemovalRun run = runStoppedRemovalBeforeSend(backend, store, ns); + + EXPECT_EQ(run.failed_catalog_reads, 1); + EXPECT_EQ(run.catalog_reads_after_failure, 1) << "the failed proof read was reissued once"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + EXPECT_NO_THROW(updatePublishedAt(store, ns)) << "the proven Live lane must be open again"; + } + { + SCOPED_TRACE("possible late write"); + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/stopped_removal_after_ambiguous_write"}; + publishEmptyPart(store, ns, "owned"); + dropWithAmbiguousCatalogWrite(backend, store, ns); + + const StoppedRemovalRun run = runStoppedRemovalBeforeSend(backend, store, ns); + + EXPECT_EQ(run.failed_catalog_reads, 1); + EXPECT_EQ(run.catalog_reads_after_failure, 1) << "the owed proof read was reissued"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + expectPositiveLaneClosed(store, ns); + } + { + SCOPED_TRACE("lease loss"); + auto backend = std::make_shared(); + /// Moves the mount's clock past its lease deadline and back, so the lane stays observable afterwards. + auto lease_clock_offset = std::make_shared>(0); + PoolConfig config; + config.cas_request_budget = wedgeTestBudget(); + config.boot_ms_fn = [lease_clock_offset] { return Pool::bootMs() + lease_clock_offset->load(); }; + auto store = openPoolWithConfig(backend, config); + const RootNamespace ns{"srv1/stopped_removal_lease_loss"}; + publishEmptyPart(store, ns, "owned"); + const uint64_t past_the_lease = 10 * static_cast(store->poolConfig().mount_lease_ttl_ms.count()); + + const StoppedRemovalRun run = runStoppedRemovalBeforeSend(backend, store, ns, [&] + { + lease_clock_offset->store(past_the_lease); + }); + lease_clock_offset->store(0); + + EXPECT_EQ(run.failed_catalog_reads, 1); + EXPECT_EQ(run.catalog_reads_after_failure, 0) << "the expired lease refused the reissue"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + /// The refusal of a closed lane with no possible late write and no observed `Removing` row. + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "is Removing: creation waits", + [&] { updatePublishedAt(store, ns); }); + } +} + +/// Warm `namespaceLife` checks admission first: with an expired generation it reports the fence verdict +/// and leaves the lane unchanged, also when its owner stopped. +TEST(CASRefWriter, WarmNamespaceLifeExpiredGenerationReturnsFenceVerdict) +{ + auto backend = std::make_shared(); + auto store = openPool(backend); + const RootNamespace ns{"srv1/warm_life_expired_generation"}; + publishEmptyPart(store, ns, "owned"); + const uint64_t runtime = store->refTableRuntimeIdentityForTest(ns); + const RefLaneState lane = store->laneStateForTest(ns); + DB::Cas::tests::rearmMountFenceAfterAnomalyForTest(store); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "no longer admitted", [&] { (void)store->namespaceLife(ns); }); + + std::thread stopped_owner([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "no longer admitted", [&] { (void)store->namespaceLife(ns); }); + }); + stopped_owner.join(); + + EXPECT_EQ(store->refTableRuntimeIdentityForTest(ns), runtime); + EXPECT_EQ(store->laneStateForTest(ns), lane); +} + +/// The guard must not reopen after an earlier ambiguous `Live -> Removing` send: that write may still land. +TEST(CASRefWriterNamespaceRemoval, ThrowDuringRemovalSetupAfterAmbiguousWriteKeepsTheLaneClosed) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/throw_in_setup_after_ambiguous_write"}; + publishEmptyPart(store, ns, "owned"); + + dropWithAmbiguousCatalogWrite(backend, store, ns); + + store->setRemovalAttemptHookForTest([] { throw std::runtime_error("setup failed"); }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + EXPECT_THROW(store->dropNamespace(ns), std::runtime_error); + store->setRemovalAttemptHookForTest({}); + expectPositiveLaneClosed(store, ns); + + EXPECT_NO_THROW(store->dropNamespace(ns)) << "a retried removal completes"; + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} + /// The uncertainty outlives the call that created it: a retried removal that fails before it sends /// anything, then sees an unchanged `Live` row, must not reopen the lane. TEST(CASRefWriterNamespaceRemoval, FailedRetryAfterAmbiguousBeginRemovingDoesNotReopenTheLane) @@ -5375,9 +5581,9 @@ TEST(CASRefWriterNamespaceRemoval, AmbiguousBeginRemovingSurvivesRefTableEvictio EXPECT_NO_THROW(store->dropNamespace(ns)); } -/// Upper bound on the virtual time one drop may spend: the window frozen at its entry, one backoff draw -/// the pace does not consult the deadline for (the cap of `Retry::backoff`), and slack for -/// the virtual clock's extra millisecond per pause. +/// Upper bound on the virtual time a request may spend after it starts: its own window, one backoff draw +/// the pace does not consult the deadline for (the cap of `Retry::backoff`), and slack for the virtual +/// clock's extra millisecond per pause. const uint64_t kMaxBackoffDrawMs = 5000; const uint64_t kVirtualClockPauseSlackMs = 100; const uint64_t kOneWindowPlusBackoffMs @@ -5426,8 +5632,9 @@ TEST(CASRefWriterNamespaceRemoval, ResolveReadProvingRemovingLeavesNoUnresolvedW ASSERT_TRUE(applied_by_resolve_read) << "the kept write was never applied before the resolve read"; ASSERT_TRUE(released_at_ms.has_value()); - /// The loop gives up once the next pause plus the room `CasOperation::pauseBeforeRedecide` reserves for the - /// next decision's read and write no longer fits in the window. An earlier release came from a read inside the loop. + /// The loop keeps deciding until its window is nearly spent: the last decision's read and write each need an + /// envelope, so the release lands no earlier than that much before the window's end. An earlier release came + /// from a read inside the loop. const uint64_t next_decision_reservation_ms = 2 * store->mountRequests().attemptReservationMs(); EXPECT_GE(*released_at_ms - drop_started_ms, kDefaultRequestWindowMs - kMaxBackoffDrawMs - next_decision_reservation_ms) @@ -5558,6 +5765,316 @@ TEST(CASRefWriterNamespaceRemoval, ConcurrentRemovalAttemptsDoNotOverlapAndKeepT EXPECT_NO_THROW(store->dropNamespace(ns)); } +namespace +{ + +constexpr auto STOP_WATCHDOG = std::chrono::seconds(30); + +/// Keeps a blocker parked until the stopped caller has returned, or until the watchdog fires. +struct StoppedCallerSync +{ + void parkBlocker() + { + std::unique_lock lock(mutex); + blocker_parked = true; + cv.notify_all(); + cv.wait_for(lock, STOP_WATCHDOG, [&] { return stopped_returned; }); + blocker_left = true; + } + + bool waitBlockerParked() + { + std::unique_lock lock(mutex); + return cv.wait_for(lock, STOP_WATCHDOG, [&] { return blocker_parked; }); + } + + /// True when the blocker was still parked. + bool stoppedCallerReturned() + { + std::lock_guard lock(mutex); + stopped_returned = true; + cv.notify_all(); + return !blocker_left; + } + + std::mutex mutex; + std::condition_variable cv; + bool blocker_parked = false; + bool stopped_returned = false; + bool blocker_left = false; +}; + +template +bool spinUntil(Ready ready) +{ + const auto deadline = std::chrono::steady_clock::now() + STOP_WATCHDOG; + while (!ready() && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + return ready(); +} + +} + +namespace +{ + +/// A removal's owner stops while it waits for another removal's attempt. +void runRemovalFollowerStoppedWhileWaiting(StoppedBy owner) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/stopped_removal_follower"}; + publishEmptyPart(store, ns, "owned"); + + StoppedCallerSync sync; + std::atomic holder_entered{false}; + store->setRemovalAttemptHookForTest([&] + { + if (!holder_entered.exchange(true)) + sync.parkBlocker(); + }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + + std::future holder = std::async(std::launch::async, [&] { return exceptionCodeOf([&] { store->dropNamespace(ns); }); }); + ASSERT_TRUE(sync.waitBlockerParked()); + + int follower_code = 0; + bool returned_while_holder_parked = false; + CasRefLedger::RemovalFlagsForTest flags_on_return; + std::thread follower([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + auto background_stopped = std::make_shared>(false); + const auto background = DB::Cas::tests::backgroundOwnerStoppedBy(background_stopped); + const auto stop = DB::Cas::tests::stopperOf(owner, query, background_stopped); + /// The holder passed this hook before it parked, so only the follower stops here. A killed query + /// keeps waiting, so the holder is released from here; the follower has not claimed the attempt yet. + store->setRemovalRuntimeAcquiredHookForTest([&] + { + stop(); + if (owner == StoppedBy::Query) + sync.stoppedCallerReturned(); + }); + follower_code = exceptionCodeOf([&] { store->dropNamespace(ns); }); + store->setRemovalRuntimeAcquiredHookForTest(nullptr); + flags_on_return = store->removalFlagsForTest(ns); + returned_while_holder_parked = sync.stoppedCallerReturned(); + }); + follower.join(); + ASSERT_EQ(holder.wait_for(STOP_WATCHDOG), std::future_status::ready); + + if (owner == StoppedBy::Background) + { + EXPECT_EQ(follower_code, DB::ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_holder_parked) << "the stopped follower waited for the holder's attempt"; + EXPECT_TRUE(flags_on_return.attempt_active) << "the holder's attempt must stay claimed"; + EXPECT_TRUE(flags_on_return.admission_closed) << "the holder's closed lane must stay closed"; + } + else + { + EXPECT_EQ(follower_code, 0) << "a killed query's removal completes after the holder's"; + EXPECT_FALSE(returned_while_holder_parked); + EXPECT_FALSE(flags_on_return.attempt_active); + } + EXPECT_EQ(holder.get(), 0); + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} + +} + +/// A removal whose background owner stops leaves; the attempt stays claimed by the removal that holds it, which then +/// completes. +TEST(CASRefWriterNamespaceRemoval, BackgroundStoppedRemovalFollowerLeavesOwnerClaimed) +{ + runRemovalFollowerStoppedWhileWaiting(StoppedBy::Background); +} + +/// A removal whose query is killed keeps waiting and completes after the holder. +TEST(CASRefWriterNamespaceRemoval, KilledRemovalFollowerCompletesAfterTheHolder) +{ + runRemovalFollowerStoppedWhileWaiting(StoppedBy::Query); +} + +/// A namespace removal run by a killed query on a healthy store completes: every request it needs is sent. +TEST(CASRefWriterNamespaceRemoval, KilledQuerysRemovalCompletesOnAHealthyStore) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + const RootNamespace ns{"srv1/killed_removal"}; + publishEmptyPart(store, ns, "owned"); + + int code = -1; + std::thread killed([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + code = exceptionCodeOf([&] { store->dropNamespace(ns); }); + }); + killed.join(); + + EXPECT_EQ(code, 0); + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} + +namespace +{ + +/// A removal's owner stops while it waits for appends admitted before its closure, with the catalog row left +/// `Live` or turned `Removing` meanwhile. +void runRemovalStoppedDuringPositiveDrain(StoppedBy owner) +{ + for (const bool row_turns_removing : {false, true}) + { + SCOPED_TRACE(row_turns_removing ? "row turned Removing" : "exact Live"); + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{row_turns_removing ? "srv1/stopped_drain_removing" : "srv1/stopped_drain_live"}; + publishEmptyPart(store, ns, "owned"); + const NamespaceLifeId life = *lifeIfCatalogedForTest(backend, store->layout(), ns); + + StoppedCallerSync sync; + std::atomic leader_entered{false}; + store->setRefPreCarveHookForTest([&] + { + if (!leader_entered.exchange(true)) + sync.parkBlocker(); + }); + SCOPE_EXIT({ store->setRefPreCarveHookForTest(nullptr); }); + + std::future leader = std::async(std::launch::async, [&] { return exceptionCodeOf([&] { updatePublishedAt(store, ns); }); }); + ASSERT_TRUE(sync.waitBlockerParked()); + + int removal_code = 0; + bool returned_while_leader_parked = false; + CasRefLedger::RemovalFlagsForTest flags_on_return; + std::function stop_removal; + std::atomic removal_query_ready{false}; + std::thread removal([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + auto background_stopped = std::make_shared>(false); + const auto background = DB::Cas::tests::backgroundOwnerStoppedBy(background_stopped); + stop_removal = DB::Cas::tests::stopperOf(owner, query, background_stopped); + removal_query_ready = true; + removal_code = exceptionCodeOf([&] { store->dropNamespace(ns); }); + flags_on_return = store->removalFlagsForTest(ns); + returned_while_leader_parked = sync.stoppedCallerReturned(); + }); + /// Only the drain wait follows the closure, so a closed lane means the removal is in, or entering, that wait. + const bool closed = spinUntil([&] { return store->removalFlagsForTest(ns).admission_closed; }); + EXPECT_TRUE(closed); + if (row_turns_removing) + rewriteCatalogRow(backend, store->layout(), ns, CatalogEntry{ + .ns = ns, .state = NsState::Removing, .incarnation = life.incarnation, .removal_started_round = 0}); + ASSERT_TRUE(removal_query_ready.load()); + stop_removal(); + /// A killed query keeps waiting, so the parked leader is released independently. + if (owner == StoppedBy::Query) + sync.stoppedCallerReturned(); + removal.join(); + ASSERT_EQ(leader.wait_for(STOP_WATCHDOG), std::future_status::ready); + + EXPECT_EQ(leader.get(), 0) << "the append admitted before the closure commits"; + if (owner == StoppedBy::Query) + { + EXPECT_EQ(removal_code, 0) << "a killed query's removal completes once the admitted append committed"; + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); + continue; + } + EXPECT_EQ(removal_code, DB::ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_leader_parked) << "the stopped removal waited for the admitted append"; + EXPECT_FALSE(flags_on_return.attempt_active); + EXPECT_EQ(flags_on_return.admission_closed, row_turns_removing); + if (row_turns_removing) + { + expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { updatePublishedAt(store, ns); }); + } + else + { + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + EXPECT_NO_THROW(updatePublishedAt(store, ns)) << "the proven Live lane must be open again"; + } + } +} + +} + +/// A removal whose background owner stops while it waits for appends admitted before its closure sent nothing. +/// It reopens the lane only when a fresh read proves the exact `Live` row; a row turned `Removing` meanwhile keeps +/// it closed. The admitted append commits either way. +TEST(CASRefWriterNamespaceRemoval, BackgroundStoppedPositiveDrainReopensOnlyItsProvenLiveLane) +{ + runRemovalStoppedDuringPositiveDrain(StoppedBy::Background); +} + +/// A removal whose query is killed while it waits for an admitted append keeps waiting and removes the namespace +/// once the append has committed. +TEST(CASRefWriterNamespaceRemoval, KilledQuerysRemovalWaitsForTheAdmittedAppendAndCompletes) +{ + runRemovalStoppedDuringPositiveDrain(StoppedBy::Query); +} + +/// The `Live -> Removing` reply is lost and the owner stops while the write's settling read is in flight. The +/// read is owed and cannot prove the outcome, so the write is not resent, the caller gets the unresolved +/// retry-later exit, and the lane stays closed against the write that may still land. +TEST(CASRefWriterNamespaceRemoval, StopDuringRemovingSettlementKeepsUnresolvedExit) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const RootNamespace ns{"srv1/stop_during_removing_settlement"}; + publishEmptyPart(store, ns, "owned"); + const String catalog_key = store->layout().refCatalogKey(); + const size_t catalog_writes_before = catalogWritesInJournal(backend, store->layout()); + + StoppedCallerSync sync; + std::atomic parked_once{false}; + backend->read_observer = [&](const String & key) + { + if (key == catalog_key && backend->catalog_cas_fault_fired && !parked_once.exchange(true)) + sync.parkBlocker(); + }; + SCOPE_EXIT({ backend->read_observer = {}; }); + backend->catalog_fault_key = catalog_key; + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::ThrowUncommitted; + + int removal_code = 0; + std::function kill_removal; + std::thread removal([&] + { + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + kill_removal = [&query] { query.kill(); }; + removal_code = exceptionCodeOf([&] { store->dropNamespace(ns); }); + sync.stoppedCallerReturned(); + }); + const bool parked = sync.waitBlockerParked(); + EXPECT_TRUE(parked) << "the lost write was never settled by a read"; + if (parked) + kill_removal(); + { + std::lock_guard lock(sync.mutex); + sync.stopped_returned = true; + } + sync.cv.notify_all(); + removal.join(); + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::None; + + EXPECT_EQ(removal_code, DB::ErrorCodes::NETWORK_ERROR); + EXPECT_EQ(catalogWritesInJournal(backend, store->layout()) - catalog_writes_before, 1u) << "a stopped owner resends nothing"; + EXPECT_EQ(catalogEntryOrThrow(backend, store->layout(), ns).state, NsState::Live); + expectPositiveLaneClosed(store, ns); +} + /// A refusal at the admission check inside `beginRemoving` comes before any write is sent, so nothing can /// land and a fresh `Live` row reopens the lane. The boot clock reads past the lease deadline exactly once, /// at that check. @@ -5880,9 +6397,9 @@ TEST(CASRefWriterNamespaceRemoval, EntryChangedAfterASentAttemptKeepsTheLaneClos expectPositiveLaneClosed(store, ns); } -/// A creator-fence read made while the drop decides must draw on the drop's one frozen window: a slow -/// first read plus a failing fence read must not exceed that window. -TEST(CASRefWriterNamespaceRemoval, DropWithASlowCreatorFenceReadEndsAtTheEntryDeadline) +/// A slow first catalog read carries the clock past a whole window; the creator-fence read after it is +/// sent and ends at its own window. +TEST(CASRefWriterNamespaceRemoval, DropSendsItsCreatorFenceReadAfterASlowFirstRead) { auto backend = std::make_shared(); auto store = openPool(backend, wedgeTestBudget()); @@ -5898,14 +6415,14 @@ TEST(CASRefWriterNamespaceRemoval, DropWithASlowCreatorFenceReadEndsAtTheEntryDe creating.creator = CreatorFence{.server_root_id = foreign_creator, .writer_epoch = 7, .fence_generation = 1}; casAdmitEntryForTest(backend, layout, 1, creating); - bool first_catalog_read_done = false; + std::optional first_read_ended_ms; size_t fence_reads = 0; backend->read_observer = [&](const String & key) { - if (key == layout.refCatalogKey() && !first_catalog_read_done) + if (key == layout.refCatalogKey() && !first_read_ended_ms) { - first_catalog_read_done = true; - clock->advance(60'000); + clock->advance(kDefaultRequestWindowMs + 10'000); + first_read_ended_ms = clock->nowMs(); } if (key == layout.mountKey(foreign_creator)) { @@ -5915,33 +6432,32 @@ TEST(CASRefWriterNamespaceRemoval, DropWithASlowCreatorFenceReadEndsAtTheEntryDe }; SCOPE_EXIT({ backend->read_observer = nullptr; }); - const uint64_t now_before = clock->nowMs(); EXPECT_THROW(store->dropNamespace(ns), DB::Exception); - ASSERT_TRUE(first_catalog_read_done); + ASSERT_TRUE(first_read_ended_ms.has_value()); EXPECT_GT(fence_reads, 0U) << "the creator fence was never read"; - EXPECT_LE(clock->nowMs() - now_before, kOneWindowPlusBackoffMs) - << "the drop spent more than the one window frozen at its entry"; + EXPECT_LE(clock->nowMs() - *first_read_ended_ms, kOneWindowPlusBackoffMs) + << "the creator-fence read outlived its own window"; } -/// The `gc/state` read is part of the removal decision, so it draws on the same window as the catalog read -/// that came before it. -TEST(CASRefWriterNamespaceRemoval, DropSpendsOneWindowAcrossItsReads) +/// A slow first catalog read carries the clock past a whole window; the `gc/state` read of the removal +/// decision is sent and ends at its own window. +TEST(CASRefWriterNamespaceRemoval, DropSendsItsGcStateReadAfterASlowFirstRead) { auto backend = std::make_shared(); auto store = openPool(backend, wedgeTestBudget()); auto clock = VirtualRetryClock::installOn(store); const Layout & layout = store->layout(); - const RootNamespace ns{"srv1/one_window_across_reads"}; + const RootNamespace ns{"srv1/gc_state_read_after_slow_read"}; publishEmptyPart(store, ns, "owned"); - bool first_catalog_read_done = false; + std::optional first_read_ended_ms; size_t gc_state_reads = 0; backend->read_observer = [&](const String & key) { - if (key == layout.refCatalogKey() && !first_catalog_read_done) + if (key == layout.refCatalogKey() && !first_read_ended_ms) { - first_catalog_read_done = true; - clock->advance(60'000); + clock->advance(kDefaultRequestWindowMs + 10'000); + first_read_ended_ms = clock->nowMs(); } if (key == layout.gcStateKey()) { @@ -5951,64 +6467,212 @@ TEST(CASRefWriterNamespaceRemoval, DropSpendsOneWindowAcrossItsReads) }; SCOPE_EXIT({ backend->read_observer = nullptr; }); - const uint64_t now_before = clock->nowMs(); EXPECT_THROW(store->dropNamespace(ns), DB::Exception); - ASSERT_TRUE(first_catalog_read_done); - EXPECT_GT(gc_state_reads, 0U) << "the gc/state read was never reached"; - EXPECT_LE(clock->nowMs() - now_before, kOneWindowPlusBackoffMs) - << "the drop spent more than the one window frozen at its entry"; + ASSERT_TRUE(first_read_ended_ms.has_value()); + EXPECT_GT(gc_state_reads, 0U) << "the gc/state read was never sent"; + EXPECT_LE(clock->nowMs() - *first_read_ended_ms, kOneWindowPlusBackoffMs) + << "the gc/state read outlived its own window"; } -/// The `Live -> Removing` catalog update draws on the drop's one frozen window too: a slow first read -/// plus catalog writes that never land must not exceed that window. -TEST(CASRefWriterNamespaceRemoval, DropSpendsOneWindowAcrossItsCatalogUpdate) +/// A slow first catalog read carries the clock past a whole window; the `Live -> Removing` catalog +/// update is sent and ends at its own window. +TEST(CASRefWriterNamespaceRemoval, DropSendsItsCatalogUpdateAfterASlowFirstRead) { auto backend = std::make_shared(); auto store = openPool(backend, wedgeTestBudget()); auto clock = VirtualRetryClock::installOn(store); const Layout & layout = store->layout(); - const RootNamespace ns{"srv1/one_window_across_catalog_update"}; + const RootNamespace ns{"srv1/catalog_update_after_slow_read"}; publishEmptyPart(store, ns, "owned"); backend->catalog_fault_key = layout.refCatalogKey(); backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::ThrowUncommitted; - bool first_catalog_read_done = false; + std::optional first_read_ended_ms; backend->read_observer = [&](const String & key) { - if (key == layout.refCatalogKey() && !first_catalog_read_done) + if (key == layout.refCatalogKey() && !first_read_ended_ms) { - first_catalog_read_done = true; - clock->advance(60'000); + clock->advance(kDefaultRequestWindowMs + 10'000); + first_read_ended_ms = clock->nowMs(); } }; SCOPE_EXIT({ backend->read_observer = nullptr; }); - const uint64_t now_before = clock->nowMs(); - EXPECT_THROW(store->dropNamespace(ns), DB::Exception); + EXPECT_THROW(store->dropNamespace(ns), DB::Exception); + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::None; + ASSERT_TRUE(first_read_ended_ms.has_value()); + EXPECT_TRUE(backend->catalog_cas_fault_fired) << "no catalog write was sent"; + EXPECT_LE(clock->nowMs() - *first_read_ended_ms, kOneWindowPlusBackoffMs) + << "the catalog update outlived its own window"; +} + +/// A gap longer than the window between two requests of the removal does not end it: the reads after +/// the gap are sent. +/// The `gc/state` read then fails before any write is sent, the catch-side read finds the row `Live`, and +/// the lane reopens. +TEST(CASRefWriterNamespaceRemoval, AReadFailingAfterAGapLongerThanTheWindowLeavesTheLaneOpen) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + auto clock = VirtualRetryClock::installOn(store); + const Layout & layout = store->layout(); + const RootNamespace ns{"srv1/gap_longer_than_window"}; + publishEmptyPart(store, ns, "owned"); + + std::optional gap_ended_ms; + store->setRemovalAttemptHookForTest([&] + { + clock->advance(kDefaultRequestWindowMs + 10'000); + gap_ended_ms = clock->nowMs(); + }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + size_t gc_state_reads = 0; + backend->read_observer = [&](const String & key) + { + if (key == layout.gcStateKey() && gap_ended_ms) + { + ++gc_state_reads; + throw DB::Exception(DB::ErrorCodes::S3_ERROR, "simulated transient GET failure"); + } + }; + SCOPE_EXIT({ backend->read_observer = nullptr; }); + const size_t catalog_writes_before = catalogWritesInJournal(backend, layout); + + expectThrowsCodeWithMessage( + DB::ErrorCodes::NETWORK_ERROR, "gave up at the policy deadline", [&] { store->dropNamespace(ns); }); + ASSERT_TRUE(gap_ended_ms.has_value()); + EXPECT_GT(gc_state_reads, 0U) << "the removal's reads after the gap were never sent"; + EXPECT_LE(clock->nowMs() - *gap_ended_ms, kOneWindowPlusBackoffMs) + << "the gc/state read outlived its own window"; + EXPECT_EQ(catalogWritesInJournal(backend, layout), catalog_writes_before) << "a catalog write was sent"; + EXPECT_EQ(catalogEntryOrThrow(backend, layout, ns).state, NsState::Live); + EXPECT_NO_THROW(updatePublishedAt(store, ns)); +} + +/// Another server lands an unrelated catalog row inside every `Live -> Removing` write, so each write is +/// refused and the update ends at its submission cap. A write was sent, so the lane stays closed even +/// though the row still reads `Live`. An insert is refused before it sends anything, so it leaves no cleanup +/// duty and does not pin the build floor, and a retried removal completes. +TEST(CASRefWriterNamespaceRemoval, ACapExitAfterSendsLeavesTheLaneClosedAndARetriedDropCompletes) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + /// Pauses take no time, so the submission cap and not a window ends the update. + store->setCasRetrySleepForTest([](uint64_t) {}); + const Layout & layout = store->layout(); + const RootNamespace ns{"srv1/cap_exit_after_sends"}; + publishEmptyPart(store, ns, "owned"); + + backend->catalog_fault_key = layout.refCatalogKey(); + bool racing = false; + bool in_observer = false; + size_t rival_rows = 0; + store->setRemovalAttemptHookForTest([&] { racing = true; }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + backend->read_observer = [&](const String & key) + { + if (!racing || in_observer || key != layout.refCatalogKey()) + return; + in_observer = true; + SCOPE_EXIT({ in_observer = false; }); + /// Zero-padded, so each appended row sorts after the ones before it. + RefCatalog rival = readCatalogForTest(backend, layout).catalog; + rival.entries.push_back(CatalogEntry{ + .ns = RootNamespace{fmt::format("srv2/rival_{:03}", rival_rows)}, .state = NsState::Live, + .incarnation = UInt128(0xa000 + rival_rows)}); + ++rival_rows; + backend->catalog_replacement_bytes = encodeRefCatalog(rival); + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::OtherWriterReplacement; + }; + SCOPE_EXIT({ backend->read_observer = nullptr; }); + const size_t catalog_writes_before = catalogWritesInJournal(backend, layout); + + expectThrowsCodeWithMessage( + DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 submissions", [&] { store->dropNamespace(ns); }); + store->setRemovalAttemptHookForTest({}); + racing = false; + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::None; + EXPECT_EQ(catalogWritesInJournal(backend, layout) - catalog_writes_before, 100U); + EXPECT_EQ(catalogEntryOrThrow(backend, layout, ns).state, NsState::Live); + expectPositiveLaneClosed(store, ns); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "retry the `DROP TABLE`", + [&] { (void)publishEmptyPart(store, ns, "inserted_after_the_failed_drop"); }); + EXPECT_FALSE(store->writerCleanupDutiesPendingForTest()) << "the refused insert left a cleanup duty"; + EXPECT_EQ(store->minActive(), store->peekNextBuildSeq()) << "the refused insert pins the build floor"; + + EXPECT_NO_THROW(store->dropNamespace(ns)) << "a retried removal completes"; + EXPECT_FALSE(store->namespaceStillLogicallyPresent(ns)); +} + +/// A transaction whose precommit landed calls `precommitAdd` again after the lane closed. The refusal of +/// that second call must keep the first call's duty, so `abandon` neither forgets the binding nor deletes +/// the manifest body it names. +TEST(CASRefWriterNamespaceRemoval, ARefusedSecondPrecommitKeepsTheDurableDuty) +{ + auto backend = std::make_shared(); + auto store = openPool(backend, wedgeTestBudget()); + store->setCasRetrySleepForTest([](uint64_t) {}); + const Layout & layout = store->layout(); + const RootNamespace ns{"srv1/refused_second_precommit"}; + publishEmptyPart(store, ns, "owned"); + + auto build = startBuildFor(store, ns, "held"); + const ManifestId id = build->stageManifest({}); + build->precommitAdd(ns, "held", id); + ASSERT_EQ(build->precommitState(), PartWriteTxn::PrecommitState::Durable); + + backend->catalog_fault_key = layout.refCatalogKey(); + bool racing = false; + bool in_observer = false; + size_t rival_rows = 0; + store->setRemovalAttemptHookForTest([&] { racing = true; }); + SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + backend->read_observer = [&](const String & key) + { + if (!racing || in_observer || key != layout.refCatalogKey()) + return; + in_observer = true; + SCOPE_EXIT({ in_observer = false; }); + RefCatalog rival = readCatalogForTest(backend, layout).catalog; + rival.entries.push_back(CatalogEntry{ + .ns = RootNamespace{fmt::format("srv2/rival_{:03}", rival_rows)}, .state = NsState::Live, + .incarnation = UInt128(0xb000 + rival_rows)}); + ++rival_rows; + backend->catalog_replacement_bytes = encodeRefCatalog(rival); + backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::OtherWriterReplacement; + }; + SCOPE_EXIT({ backend->read_observer = nullptr; }); + + expectThrowsCodeWithMessage( + DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 submissions", [&] { store->dropNamespace(ns); }); + store->setRemovalAttemptHookForTest({}); + racing = false; backend->catalog_cas_fault = RefWriterTestBackend::CatalogCasFault::None; - ASSERT_TRUE(first_catalog_read_done); - EXPECT_TRUE(backend->catalog_cas_fault_fired) << "no catalog write was attempted"; - EXPECT_LE(clock->nowMs() - now_before, kOneWindowPlusBackoffMs) - << "the drop spent more than the one window frozen at its entry"; -} - -/// A local wait that outlasts the window is not cut short. The next read gives up at once with nothing -/// sent, the catch-side read has its own window and finds the row `Live`, and the lane reopens. -TEST(CASRefWriterNamespaceRemoval, AWaitLongerThanTheWindowEndsTheDropAndLeavesTheLaneOpen) -{ - auto backend = std::make_shared(); - auto store = openPool(backend, wedgeTestBudget()); - auto clock = VirtualRetryClock::installOn(store); - const Layout & layout = store->layout(); - const RootNamespace ns{"srv1/wait_longer_than_window"}; - publishEmptyPart(store, ns, "owned"); + expectPositiveLaneClosed(store, ns); - store->setRemovalAttemptHookForTest([&] { clock->advance(kDefaultRequestWindowMs + 10'000); }); - SCOPE_EXIT({ store->setRemovalAttemptHookForTest({}); }); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "retry the `DROP TABLE`", + [&] { build->precommitAdd(ns, "held", id); }); + EXPECT_EQ(build->precommitState(), PartWriteTxn::PrecommitState::Durable) + << "the refused second call erased the first call's duty"; - expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { store->dropNamespace(ns); }); - EXPECT_EQ(catalogEntryOrThrow(backend, layout, ns).state, NsState::Live); - EXPECT_NO_THROW(updatePublishedAt(store, ns)); + bool abandoned = false; + try + { + build->abandon(); + abandoned = true; + } + catch (const DB::Exception &) // NOLINT(bugprone-empty-catch) + { + } + build.reset(); + const bool bound = independentFullReplayForTest(*backend, layout, ns).getPrecommits().contains({"held", id.ref}); + if (abandoned) + EXPECT_FALSE(bound) << "abandon returned without removing the binding"; + else + EXPECT_TRUE(store->writerCleanupDutiesPendingForTest()) << "a failed abandon left the binding without a cleanup duty"; + if (bound) + EXPECT_TRUE(readOf(backend, layout.manifestKey(id))) << "the body a precommit binding names was deleted"; } /// A remount replaces the runtime, and the new one starts with the lane open. @@ -7753,7 +8417,7 @@ CasRequestBudget sealTestTinyBudget() /// =================================================================================== /// Layer 1 of the stuck-table-load fix: `ensureRefTableRecovered` retries a whole recovery attempt -/// after a TRANSIENT object-store NETWORK_ERROR (bounded by `recovery_retry_budget_ms`), instead of +/// after a TRANSIENT object-store NETWORK_ERROR (bounded by `kCasMaxRecoveryWalks`), instead of /// failing the table's async load permanently. Non-transient errors and the terminal vanish-race /// brake still fail fast. /// =================================================================================== @@ -7773,7 +8437,6 @@ TEST(CASRefWriterRecoveryRetry, TransientSealFailureIsRetriedThenSucceeds) config.server_id = UInt128(1); config.mount_lease_ttl_ms = std::chrono::milliseconds(500); config.cas_request_budget = sealTestTinyBudget(); - config.cas_request_budget.recovery_retry_budget_ms = 120000; config.cas_request_budget.recovery_retry_initial_backoff_ms = 1000; config.cas_request_budget.recovery_retry_max_backoff_ms = 30000; /// Captured by value: `fake_now` stays frozen for the whole test (see below), and the Pool can @@ -7829,7 +8492,6 @@ TEST(CASRefWriterRecoveryRetry, RecoveryDoesNotEnumerateItsStream) config.server_id = UInt128(1); config.mount_lease_ttl_ms = std::chrono::milliseconds(500); config.cas_request_budget = sealTestTinyBudget(); - config.cas_request_budget.recovery_retry_budget_ms = 120000; /// Captured by value: `fake_now` is never mutated in this test, and the Pool can outlive this /// stack frame (a background publish holds `shared_from_this()`), so a by-reference capture would /// dangle. @@ -7857,11 +8519,13 @@ TEST(CASRefWriterRecoveryRetry, RecoveryDoesNotEnumerateItsStream) << "the chain is closed by one tombstone without enumerating the stream"; } -TEST(CASRefWriterRecoveryRetry, TransientFailureLongerThanBudgetPropagates) +/// A transient failure that never clears ends recovery after `kCasMaxRecoveryWalks` walks, however much +/// time the pauses take: seven 60 s pauses pass and no elapsed-time check ends the loop. +TEST(CASRefWriterRecoveryRetry, TransientFailureThatNeverClearsPropagatesAfterTheWalkCap) { auto backend = std::make_shared(); const Layout layout("p"); - const RootNamespace ns{"srv1/retry_budget"}; + const RootNamespace ns{"srv1/retry_cap"}; seedSealFixtureDeadEpochs(backend, layout, ns); seedUncleanPredecessorMount(backend, layout, /*epoch=*/2); @@ -7873,13 +8537,11 @@ TEST(CASRefWriterRecoveryRetry, TransientFailureLongerThanBudgetPropagates) PoolConfig config; config.server_id = UInt128(1); - /// Lease TTL >> the recovery budget so the CLOCK-advancing backoff below trips the budget check, - /// not the mount fence -- this test specifically exercises the budget-exhaustion path. - config.mount_lease_ttl_ms = std::chrono::milliseconds(600000); + /// Lease TTL far above the total pause time, so the fence never ends the loop before the cap does. + config.mount_lease_ttl_ms = std::chrono::milliseconds(3'600'000); config.cas_request_budget = sealTestTinyBudget(); - config.cas_request_budget.recovery_retry_budget_ms = 5000; /// small, deterministic - config.cas_request_budget.recovery_retry_initial_backoff_ms = 1000; - config.cas_request_budget.recovery_retry_max_backoff_ms = 30000; + config.cas_request_budget.recovery_retry_initial_backoff_ms = 60'000; + config.cas_request_budget.recovery_retry_max_backoff_ms = 60'000; config.boot_ms_fn = [fake_now] { return fake_now->load(); }; config.wait_sleep_fn = [](uint64_t) {}; auto store = openPoolWithConfig(backend, config); @@ -7889,9 +8551,16 @@ TEST(CASRefWriterRecoveryRetry, TransientFailureLongerThanBudgetPropagates) /// The tombstone at `{2,2}`, the slot after the chain's last record, is the first log the walk writes. const RefTxnId seal_id{2, 2}; backend->fault_key_substr = layout.refLogKey(DB::Cas::tests::fixture::fixtureLife(ns), seal_id); - backend->fault_count = 1000; /// never stops failing within the budget + backend->fault_latched = true; + using ProfileEvents::global_counters; + const auto retries_before = global_counters[ProfileEvents::CASRefRecoveryRetries]; + const uint64_t clock_before = fake_now->load(); expectThrowsCode(DB::ErrorCodes::NETWORK_ERROR, [&] { store->listRefs(ns); }); + + EXPECT_EQ(global_counters[ProfileEvents::CASRefRecoveryRetries], retries_before + (kCasMaxRecoveryWalks - 1)) + << "eight walks mean seven pauses"; + EXPECT_GE(fake_now->load() - clock_before, uint64_t{7} * 60'000) << "420 s of pauses passed, so no elapsed-time check ended the loop"; } TEST(CASRefWriterRecoveryRetry, NonNetworkErrorIsNotRetried) @@ -7992,7 +8661,6 @@ TEST(CASRefWriterRecoveryRetry, ThrowingBackoffSleepDoesNotWedgeRecovery) config.server_id = UInt128(1); config.mount_lease_ttl_ms = std::chrono::milliseconds(500); config.cas_request_budget = sealTestTinyBudget(); - config.cas_request_budget.recovery_retry_budget_ms = 120000; config.wait_sleep_fn = [](uint64_t) {}; auto store = openPoolWithConfig(backend, config); ASSERT_TRUE(store); @@ -8020,6 +8688,602 @@ TEST(CASRefWriterRecoveryRetry, ThrowingBackoffSleepDoesNotWedgeRecovery) EXPECT_EQ(store->listRefs(ns).size(), 2u) << "a second touch must recover; the retry lane is not wedged"; } +/// =================================================================================== +/// The recovery loop ends after `kCasMaxRecoveryWalks` walks in total, whichever mix of transient +/// failures and structural restarts spent them. Pauses are no-ops, so only the cap can end the loop. +/// =================================================================================== + +namespace +{ + +enum class WalkFate : uint8_t +{ + Succeed, + FailTransiently, + /// The walk ends by finding `_ckpt` replaced, which asks for a restart. + Restart, + Corrupt, +}; + +/// Decides each walk's fate from its position; a walk past the end of the script succeeds. +struct RecoveryWalkScript +{ + std::vector fates; + int transient_code = DB::ErrorCodes::S3_ERROR; + /// Set before the recovery starts; run on the recovering thread. + std::function before_walk; + std::function on_pause; + std::function on_read; + std::atomic armed{false}; + std::atomic walks{0}; + std::atomic pauses{0}; + std::atomic ckpt_reads_in_walk{0}; + std::atomic replacing_ckpt{false}; + + WalkFate current() const + { + const uint32_t n = walks.load(); + return n >= 1 && n <= fates.size() ? fates[n - 1] : WalkFate::Succeed; + } +}; + +struct ScriptedRecovery +{ + std::shared_ptr backend; + std::shared_ptr script; + PoolPtr store; + RootNamespace ns; +}; + +/// With `production_backoff_ms`, the pool keeps its own backoff and pauses that long after a failed walk. +ScriptedRecovery openScriptedRecovery(std::vector fates, std::optional production_backoff_ms = std::nullopt) +{ + ScriptedRecovery scripted; + scripted.backend = std::make_shared(); + scripted.script = std::make_shared(); + scripted.script->fates = std::move(fates); + scripted.ns = RootNamespace{"srv1/walk_cap"}; + const Layout layout("p"); + + seedSealFixtureDeadEpochs(scripted.backend, layout, scripted.ns); + seedUncleanPredecessorMount(scripted.backend, layout, /*epoch=*/2); + + PoolConfig config; + config.server_id = UInt128(1); + config.mount_lease_ttl_ms = std::chrono::milliseconds(500); + config.cas_request_budget = sealTestTinyBudget(); + config.boot_ms_fn = [] { return uint64_t{1'000'000}; }; + config.wait_sleep_fn = [](uint64_t) {}; + if (production_backoff_ms) + { + config.cas_request_budget.recovery_retry_initial_backoff_ms = *production_backoff_ms; + config.cas_request_budget.recovery_retry_max_backoff_ms = *production_backoff_ms; + } + config.recovery_pre_first_request_hook_for_test = [script = scripted.script] + { + if (!script->armed) + return; + const uint32_t walk = ++script->walks; + script->ckpt_reads_in_walk = 0; + if (script->before_walk) + script->before_walk(walk); + if (script->current() == WalkFate::FailTransiently) + throw DB::Exception(script->transient_code, "scripted walk failure"); + if (script->current() == WalkFate::Corrupt) + throw DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "scripted walk corruption"); + }; + scripted.store = openPoolWithConfig(scripted.backend, config); + if (!production_backoff_ms) + { + scripted.store->setCasRetrySleepForTest([](uint64_t) {}); + scripted.store->setRefRecoveryRetrySleepForTest([script = scripted.script](uint64_t, const auto &) + { + ++script->pauses; + if (script->on_pause) + script->on_pause(); + }); + } + + /// A walk reads `_ckpt` first and last; replacing it between the two makes the last read disagree. + const NamespaceLifeId life = lifeIfCatalogedForTest(scripted.backend, layout, scripted.ns).value(); + const String ckpt_key = layout.refCkptKey(life); + scripted.backend->read_observer = [script = scripted.script, ckpt_key, layout, life, + weak_backend = std::weak_ptr(scripted.backend)](const String & key) + { + if (script->armed && script->on_read) + script->on_read(key); + if (!script->armed || key != ckpt_key || script->replacing_ckpt) + return; + if (++script->ckpt_reads_in_walk != 2 || script->current() != WalkFate::Restart) + return; + script->replacing_ckpt = true; + SCOPE_EXIT({ script->replacing_ckpt = false; }); + const BackendPtr backend_ptr = weak_backend.lock(); + ASSERT_TRUE(backend_ptr); + const auto sampled = readCkptForTest(backend_ptr, layout, life); + ASSERT_TRUE(sampled); + ASSERT_TRUE(replaceForTest(backend_ptr, ckpt_key, encodeRefCkptAtGeneration(sampled->ckpt, 3), sampled->etag)); + }; + scripted.script->armed = true; + return scripted; +} + +} + +TEST(CASRefWriterRecoveryRetry, SuccessOnTheEighthWalkInstalls) +{ + auto scripted = openScriptedRecovery(std::vector(7, WalkFate::FailTransiently)); + + EXPECT_EQ(scripted.store->listRefs(scripted.ns).size(), 2u); + EXPECT_EQ(scripted.script->walks.load(), 8u); +} + +TEST(CASRefWriterRecoveryRetry, ATransientFailureOnTheEighthWalkRethrows) +{ + auto scripted = openScriptedRecovery(std::vector(8, WalkFate::FailTransiently)); + + /// The failure of the last walk propagates unchanged, not recoded as a retry-later error. + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 8u) << "no ninth walk after the cap"; + EXPECT_EQ(scripted.script->pauses.load(), 7u) << "a pause follows every failed walk except the last"; +} + +TEST(CASRefWriterRecoveryRetry, AStructuralRestartOnTheEighthWalkReportsExhaustion) +{ + std::vector fates(5, WalkFate::FailTransiently); + fates.insert(fates.end(), 3, WalkFate::Restart); + auto scripted = openScriptedRecovery(std::move(fates)); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "the last walk restarted because the checkpoint or its base moved", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 8u) << "no ninth walk after the cap"; + EXPECT_EQ(scripted.script->pauses.load(), 5u); +} + +TEST(CASRefWriterRecoveryRetry, MixedFailuresEndAtEightWalks) +{ + using enum WalkFate; + auto scripted = openScriptedRecovery({Restart, FailTransiently, Restart, Restart, FailTransiently, Restart, + FailTransiently, FailTransiently}); + + /// Transient failures end at walks 2, 5, 7 and 8; the last one is not followed by a pause. + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 8u) << "no ninth walk after the cap"; + EXPECT_EQ(scripted.script->pauses.load(), 3u); +} + +/// The eighth walk is also the fourth restart in a row, so the structural brake reports it. +TEST(CASRefWriterRecoveryRetry, TheEighthWalkAsTheFourthConsecutiveRestartHitsTheBrake) +{ + std::vector fates(4, WalkFate::FailTransiently); + fates.insert(fates.end(), 4, WalkFate::Restart); + auto scripted = openScriptedRecovery(std::move(fates)); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "restarted 3 times", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 8u); +} + +/// Guard: restarts alone stop at the structural brake (the initial walk plus three restarts), well +/// before the cap. +TEST(CASRefWriterRecoveryRetry, TheStructuralBrakeEndsBeforeEightWalks) +{ + auto scripted = openScriptedRecovery(std::vector(20, WalkFate::Restart)); + + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "restarted 3 times", + [&] { scripted.store->listRefs(scripted.ns); }); + EXPECT_EQ(scripted.script->walks.load(), 4u); +} + +/// =================================================================================== +/// A stopped owner: no new walk after a failed walk; a restart after a successful walk, a structural exit +/// and a follower keep their plain answers. +/// =================================================================================== + +namespace +{ + +std::exception_ptr queryTimeout() +{ + return std::make_exception_ptr(DB::Exception(DB::ErrorCodes::TIMEOUT_EXCEEDED, "test: the query timed out")); +} + +} + +TEST(CASRefWriterRecoveryRetry, OwnerTimeoutEndsAfterFailedWalkTransportTimeoutCanRecover) +{ + { + SCOPED_TRACE("the owner timed out during a failed walk"); + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + scripted.script->before_walk = [&query](uint32_t) { query.kill(queryTimeout()); }; + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + scripted.script->before_walk = {}; + }); + EXPECT_EQ(scripted.script->walks.load(), 1u) << "no walk after the owner's timeout"; + EXPECT_EQ(scripted.script->pauses.load(), 0u); + } + { + SCOPED_TRACE("control: a transport timeout under a live owner"); + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}); + scripted.script->transient_code = DB::ErrorCodes::TIMEOUT_EXCEEDED; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery &) + { + size_t refs = 0; + EXPECT_NO_THROW(refs = scripted.store->listRefs(scripted.ns).size()); + EXPECT_EQ(refs, 2u); + }); + EXPECT_EQ(scripted.script->walks.load(), 2u); + } +} + +TEST(CASRefWriterRecoveryRetry, StopAfterTransientFailureStartsNoNewWalk) +{ + for (const bool stop_in_backoff : {false, true}) + { + SCOPED_TRACE(stop_in_backoff ? "stop in the backoff" : "stop during the failed walk"); + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + if (stop_in_backoff) + scripted.script->on_pause = [&query] { query.kill(); }; + else + scripted.script->before_walk = [&query](uint32_t) { query.kill(); }; + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + scripted.script->on_pause = {}; + scripted.script->before_walk = {}; + }); + EXPECT_EQ(scripted.script->walks.load(), 1u); + EXPECT_EQ(scripted.script->pauses.load(), stop_in_backoff ? 1u : 0u); + } +} + +/// The pool's own backoff, ten seconds long, sleeps in owner-stop slices: a kill during a slice ends recovery when that +/// slice ends, with no further slice and no new walk. +TEST(CASRefWriterRecoveryRetry, StopDuringBackoffEndsWithinASlice) +{ + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}, /*production_backoff_ms=*/10'000); + std::mutex mutex; + std::condition_variable cv; + bool sleeping = false; + bool killed = false; + std::vector slices; + scripted.store->setRefRecoveryRetrySliceSleepForTest([&](uint64_t ms) + { + std::unique_lock lock(mutex); + slices.push_back(ms); + sleeping = true; + cv.notify_all(); + cv.wait_for(lock, STOP_WATCHDOG, [&] { return killed; }); + }); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + std::thread killer([&] + { + std::unique_lock lock(mutex); + cv.wait_for(lock, STOP_WATCHDOG, [&] { return sleeping; }); + query.kill(); + killed = true; + cv.notify_all(); + }); + expectThrowsCodeWithMessage(DB::ErrorCodes::S3_ERROR, "scripted walk failure", + [&] { scripted.store->listRefs(scripted.ns); }); + killer.join(); + }); + ASSERT_EQ(slices.size(), 1u) << "a slice started after the kill"; + EXPECT_EQ(*std::max_element(slices.begin(), slices.end()), static_cast(DB::Cas::kOwnerStopSlice.count())) + << "the backoff is not sliced at the owner-stop slice"; + EXPECT_EQ(scripted.script->walks.load(), 1u); +} + +TEST(CASRefWriterRecoveryRetry, StopDuringCorruptionConfirmationIsNotCorruption) +{ + auto scripted = openScriptedRecovery({WalkFate::Corrupt}); + const String catalog_key = scripted.store->layout().refCatalogKey(); + /// The walk fails before its first request, so the next catalog read is the confirmation's. + std::atomic walk_failed{false}; + std::atomic confirmation_read_lost{false}; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + scripted.script->before_walk = [&](uint32_t) { walk_failed = true; }; + scripted.script->on_read = [&](const String & key) + { + if (key != catalog_key || !walk_failed.exchange(false)) + return; + confirmation_read_lost = true; + query.kill(); + throw Poco::TimeoutException("test: the confirmation's catalog read is lost"); + }; + String error; + try + { + scripted.store->listRefs(scripted.ns); + } + catch (const Poco::TimeoutException & e) + { + error = e.message(); + } + catch (...) + { + error = "unexpected: " + DB::getCurrentExceptionMessage(false); + } + EXPECT_EQ(error, "test: the confirmation's catalog read is lost") << "the confirmation's own failure"; + scripted.script->before_walk = {}; + scripted.script->on_read = {}; + }); + EXPECT_TRUE(confirmation_read_lost.load()) << "the owner stopped during the corruption confirmation"; + EXPECT_EQ(scripted.script->walks.load(), 1u); + + /// The failure released the recovery and `state_mutex`, so the next recovery of the table proceeds. A wedged one + /// keeps its own references to the pool, so its thread is left behind. + auto next_recovery = std::make_shared>(); + auto recovered = next_recovery->get_future(); + std::thread next([store = scripted.store, ns = scripted.ns, next_recovery] + { + try + { + next_recovery->set_value(store->listRefs(ns).size()); + } + catch (...) + { + next_recovery->set_exception(std::current_exception()); + } + }); + if (recovered.wait_for(STOP_WATCHDOG) != std::future_status::ready) + { + next.detach(); + FAIL() << "the next recovery of the table did not return"; + } + next.join(); + EXPECT_EQ(recovered.get(), 2u); + EXPECT_EQ(scripted.script->walks.load(), 2u); +} + +/// A confirmation that fails under a live owner did not establish that the catalog still names the life, so its own +/// failure is the answer, never the walk's corruption. +TEST(CASRefWriterRecoveryRetry, FailedCorruptionConfirmationUnderALiveOwnerIsNotCorruption) +{ + auto scripted = openScriptedRecovery({WalkFate::Corrupt}); + const String catalog_key = scripted.store->layout().refCatalogKey(); + /// The walk fails before its first request, so the next catalog read is the confirmation's. + std::atomic walk_failed{false}; + std::atomic confirmation_read_refused{false}; + int code = 0; + String message; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery &) + { + scripted.script->before_walk = [&](uint32_t) { walk_failed = true; }; + scripted.script->on_read = [&](const String & key) + { + if (key != catalog_key || !walk_failed.exchange(false)) + return; + confirmation_read_refused = true; + throw DB::Exception(DB::ErrorCodes::READONLY, "test: the confirmation's catalog read is refused"); + }; + try + { + scripted.store->listRefs(scripted.ns); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + scripted.script->before_walk = {}; + scripted.script->on_read = {}; + }); + EXPECT_TRUE(confirmation_read_refused.load()); + EXPECT_EQ(code, DB::ErrorCodes::READONLY) << message; + EXPECT_NE(message.find("the confirmation's catalog read is refused"), String::npos) << message; + EXPECT_EQ(scripted.script->walks.load(), 1u); +} + +/// A kill in the backoff after a network failure vetoes the next walk and keeps the network error, which the part +/// loader's classifier reads as retryable rather than as damage. +TEST(CASRefWriterRecoveryRetry, KillInBackoffAfterNetworkFailureKeepsTheNetworkError) +{ + auto scripted = openScriptedRecovery({WalkFate::FailTransiently}); + scripted.script->transient_code = DB::ErrorCodes::NETWORK_ERROR; + std::exception_ptr error; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + scripted.script->on_pause = [&query] { query.kill(); }; + try + { + scripted.store->listRefs(scripted.ns); + } + catch (...) + { + error = std::current_exception(); + } + scripted.script->on_pause = {}; + }); + ASSERT_TRUE(error); + EXPECT_EQ(DB::getExceptionMessage(error, false).find("scripted walk failure") != String::npos, true) + << DB::getExceptionMessage(error, false); + EXPECT_TRUE(DB::isRetryableException(error)) << "a vetoed retry must not read as part damage"; + EXPECT_EQ(scripted.script->walks.load(), 1u); + EXPECT_EQ(scripted.script->pauses.load(), 1u); +} + +/// A walk that fails with real corruption of a life the catalog no longer names ends the same for a killed query as +/// for a live one: the confirmation is no retry, so it runs and finds the life removed. +TEST(CASRefWriterRecoveryRetry, KilledQuerysCorruptionOfARemovedLifeIsConfirmed) +{ + const auto run = [](bool kill) + { + auto scripted = openScriptedRecovery({WalkFate::Corrupt}); + const Layout layout("p"); + const NamespaceLifeId life = lifeIfCatalogedForTest(scripted.backend, layout, scripted.ns).value(); + std::pair outcome{0, ""}; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + scripted.script->before_walk = [&](uint32_t) + { + eraseLifeForTest(scripted.backend, layout, life); + if (kill) + query.kill(); + }; + try + { + outcome.second = std::to_string(scripted.store->listRefs(scripted.ns).size()); + } + catch (const DB::Exception & e) + { + outcome = {e.code(), e.message()}; + } + scripted.script->before_walk = {}; + }); + EXPECT_EQ(scripted.script->walks.load(), 1u); + return outcome; + }; + const auto live = run(false); + const auto killed = run(true); + EXPECT_NE(live.first, DB::ErrorCodes::CORRUPTED_DATA) << live.second; + EXPECT_EQ(killed.first, live.first) << killed.second; + EXPECT_EQ(killed.second, live.second); +} + +/// A query's stored cause with the `CORRUPTED_DATA` code says nothing about the checkpoint: the failed base read +/// starts no checkpoint reread and no restart, and the stored cause propagates. +TEST(CASRefWriterRecoveryRetry, StoredCorruptedDataStartsNoCheckpointReread) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + const RootNamespace ns{"srv1/stored_corruption"}; + const ManifestRef ma = manifestRef(1, 1, 1); + DB::Cas::tests::fixture::admitLive(*backend, layout, ns); + const NamespaceLifeId life = *lifeIfCatalogedForTest(backend, layout, ns); + const RefTxnId snap{1, 10}; + DB::Cas::tests::fixture::writeRefLogRaw(*backend, layout, RefLogTxn{ + .ns = ns.string(), + .txn_id = snap, + .ops = publishCommittedOps("a", ma), + .prev_epoch_seal = std::nullopt}); + writeRefSnapshotRaw(*backend, layout, minimalLiveSnapshot(ns.string(), snap, {committedRow("a", ma)})); + ASSERT_TRUE(createRaw(backend, layout.refCkptKey(life), encodeRefCkptAtGeneration(RefCkpt{ + .life_epoch = 1, + .committed_through = snap, + .checkpoint_snapshot_id = snap, + .last_epoch_seal = std::nullopt}, 1))); + auto store = openPool(backend); + const String snapshot_key = layout.refSnapshotKey(life, snap); + const String ckpt_key = layout.refCkptKey(life); + uint64_t ckpt_reads_before = 0; + std::exception_ptr error; + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + /// The store fails the base read the way the S3 client does for a killed query: with the query's cause. + backend->read_observer = [&](const String & key) + { + if (key != snapshot_key) + return; + query.kill(std::make_exception_ptr(DB::Exception(DB::ErrorCodes::CORRUPTED_DATA, "the query's stored cause"))); + DB::CurrentThread::checkIfNotCancelled(); + }; + ckpt_reads_before = backend->getCount(ckpt_key); + try + { + (void)store->resolveRef(ns, "a"); + } + catch (...) + { + error = std::current_exception(); + } + backend->read_observer = {}; + }); + ASSERT_TRUE(error); + EXPECT_NE(DB::getExceptionMessage(error, false).find("the query's stored cause"), String::npos) + << DB::getExceptionMessage(error, false); + EXPECT_EQ(backend->getCount(ckpt_key) - ckpt_reads_before, 1u) << "the walk's own checkpoint read, no reread"; + EXPECT_EQ(store->refRecoveryRestartsForTest(ns), 0u); +} + +/// Guard: a follower waits read-only, so a killed follower takes the leader's successful recovery. +TEST(CASRefWriterRecoveryRetry, KilledFollowerConsumesSuccessfulRecovery) +{ + auto backend = std::make_shared(); + const Layout layout("p"); + const NamespaceLifeId life = seedRecoverablePart(backend, layout, RootNamespace{"srv1/killed_follower"}); + const auto park = std::make_shared(); + auto store = openPoolWithConfig(backend, ParkedRecovery::config(park)); + const uint64_t installs_before = store->recoveryInstallCountForTest(); + + std::atomic calls{0}; + auto [leader, follower] = runWithAWaiter(park, store, life.ns, + [&]() -> std::optional + { + if (calls.fetch_add(1) == 0) + return store->resolveRef(life.ns, "part_1"); + std::optional thread_status; + thread_status.emplace(); + DB::Cas::tests::CasKillableQuery query(getContext().context); + query.kill(); + return store->resolveRef(life.ns, "part_1"); + }, + [] {}); + EXPECT_TRUE(leader.get().has_value()); + std::optional follower_answer; + EXPECT_NO_THROW(follower_answer = follower.get()); + EXPECT_TRUE(follower_answer.has_value()); + EXPECT_EQ(store->recoveryInstallCountForTest(), installs_before + 1) << "the follower ran no walk of its own"; +} + +/// Guard: a walk that succeeds but finds the checkpoint moved restarts for a stopped reader too. +TEST(CASRefWriterRecoveryRetry, CheckpointMovedRestartRunsForStoppedReader) +{ + auto scripted = openScriptedRecovery({WalkFate::Restart}); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + query.kill(); + size_t refs = 0; + EXPECT_NO_THROW(refs = scripted.store->listRefs(scripted.ns).size()); + EXPECT_EQ(refs, 2u); + }); + EXPECT_EQ(scripted.script->walks.load(), 2u) << "the restart walk ran"; + EXPECT_TRUE(scripted.store->refTableRecoveredForTest(scripted.ns)); +} + +/// Guard: the structural brake and the walk cap answer a stopped reader with their retryable error. +TEST(CASRefWriterRecoveryRetry, StoppedReaderAtStructuralBrakeAndWalkCapGets210) +{ + { + SCOPED_TRACE("the structural brake"); + auto scripted = openScriptedRecovery(std::vector(20, WalkFate::Restart)); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + query.kill(); + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "restarted 3 times", + [&] { scripted.store->listRefs(scripted.ns); }); + }); + EXPECT_EQ(scripted.script->walks.load(), 4u); + } + { + SCOPED_TRACE("the walk cap"); + std::vector fates(5, WalkFate::FailTransiently); + fates.insert(fates.end(), 3, WalkFate::Restart); + auto scripted = openScriptedRecovery(std::move(fates)); + onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + /// The owner stops once the failed walks are behind it: walks 6 to 8 follow successful walks. + scripted.script->before_walk = [&query](uint32_t walk) + { + if (walk == 6) + query.kill(); + }; + expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "the last walk restarted because the checkpoint or its base moved", + [&] { scripted.store->listRefs(scripted.ns); }); + scripted.script->before_walk = {}; + }); + EXPECT_EQ(scripted.script->walks.load(), 8u); + } +} + /// =================================================================================== /// Task 16: `hasAnyRefWithPrefix` -- pure existence probe, same recovery preamble as `listRefs` but /// without materializing the full ref map (an early-exit scan). diff --git a/src/Disks/tests/gtest_cas_requests.cpp b/src/Disks/tests/gtest_cas_requests.cpp index 3c5004c539423..f8f25a6529eb5 100644 --- a/src/Disks/tests/gtest_cas_requests.cpp +++ b/src/Disks/tests/gtest_cas_requests.cpp @@ -7,11 +7,13 @@ #include #include #include +#include #include #include #include #include "cas_test_helpers.h" #include +#include #include #include @@ -114,8 +116,36 @@ TEST(CASIncarnation, GrammarRefusesTheNineWays) EXPECT_FALSE(isIncarnationValue(Dialect::Emulated, "")); } +TEST(CASRetry, TheConflictPauseGrowsToItsCeilingWithUpToAQuarterOfJitter) +{ + thread_local_rng.seed(2026); /// a fixed sequence, so the spread checks below cannot fail on an unlucky draw + EXPECT_EQ(Retry::conflictBackoff(1), 0u) << "the first loss is retried at once"; + const std::vector bases{0, 40, 80, 120, 160, 400, 720, 750, 750, 750}; + const std::vector losses{1, 2, 3, 4, 5, 11, 19, 20, 21, 100}; + for (size_t step = 1; step < losses.size(); ++step) + { + const uint32_t loss = losses[step]; + const uint64_t base = bases[step]; + uint64_t low = std::numeric_limits::max(); + uint64_t high = 0; + for (int i = 0; i < 1000; ++i) + { + const uint64_t pause = Retry::conflictBackoff(loss); + ASSERT_GE(pause, base) << "loss " << loss; + ASSERT_LE(pause, base + base / 4) << "loss " << loss; + low = std::min(low, pause); + high = std::max(high, pause); + } + /// The bounds alone cannot tell jitter from a constant, so the spread is asserted too. + EXPECT_LT(low, base + base / 16) << "loss " << loss; + EXPECT_GT(high, base + base * 3 / 16) << "loss " << loss; + } + EXPECT_LE(Retry::conflictBackoff(std::numeric_limits::max()), 750u + 750u / 4) << "the ceiling holds for any count"; +} + TEST(CASRetry, BackoffIsFullJitterUnderTheCap) { + thread_local_rng.seed(2026); /// a fixed sequence, so the spread checks below cannot fail on an unlucky draw for (uint32_t attempt = 1; attempt <= 12; ++attempt) { const uint64_t ceiling = std::min(5000, 200ull << (attempt - 1)); @@ -147,41 +177,81 @@ TEST(CASRetry, PoliciesAreShapedAsSpecified) { const uint64_t now = 1'000'000; EXPECT_EQ(Retry::standard().bind(now, kEngineTestWindowMs).deadline_ms, now + 90'000); - EXPECT_FALSE(Retry::standard().bind(now, kEngineTestWindowMs).lease_bound); + EXPECT_NE(Retry::standard().bind(now, kEngineTestWindowMs).source, Retry::Bound::Source::Lease); EXPECT_FALSE(Retry::standard().single_attempt); EXPECT_TRUE(Retry::once().single_attempt); const Retry::Bound lease = Retry::untilLeaseSafe(now + 10'000, 2'000).bind(now, kEngineTestWindowMs); EXPECT_EQ(lease.deadline_ms, now + 8'000); - EXPECT_TRUE(lease.lease_bound); + EXPECT_EQ(lease.source, Retry::Bound::Source::Lease); EXPECT_EQ(Retry::within(1'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 1'000); } -/// A frozen policy is ONE absolute deadline: time passing does not buy a later one, freezing again -/// cannot extend it, and the lease bound still wins when it is the smaller of the two -- which is what -/// keeps `GaveUp::Source` able to say which bound refused. -TEST(CASRetry, AFrozenPolicyIsOneDeadlineAndTheLeaseStillWins) +/// A cap later than the request's own window leaves the window. +TEST(CASRetry, AnOutsideCapLaterThanTheWindowLeavesTheWindow) { - FakeClock clock; - auto backend = std::make_shared(); - auto requests = makeRequests(backend, clock); - auto op = requests.admit(); + const uint64_t now = 1'000'000; + EXPECT_EQ(Retry::standard().cappedAt(now + 3'600'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 90'000); + EXPECT_EQ(Retry::within(5'000).cappedAt(now + 60'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 5'000); +} - const uint64_t start = clock.now; - const Retry frozen = op.freeze(Retry::standard()); - ASSERT_TRUE(frozen.policy_deadline_ms.has_value()); - EXPECT_EQ(frozen.bind(start, kEngineTestWindowMs).deadline_ms, start + 90'000); - EXPECT_EQ(frozen.bind(start + 50'000, kEngineTestWindowMs).deadline_ms, start + 90'000); - EXPECT_FALSE(frozen.bind(start + 50'000, kEngineTestWindowMs).lease_bound); - /// The single-attempt view of a frozen policy keeps the deadline rather than starting a window. - EXPECT_EQ(frozen.asSingleAttempt().policy_deadline_ms, frozen.policy_deadline_ms); - EXPECT_TRUE(frozen.asSingleAttempt().single_attempt); +/// An earlier cap or an earlier lease bound wins, and the lease bound still says so when it is the one that won. +TEST(CASRetry, AnEarlierOutsideCapAndAnEarlierLeaseBothWin) +{ + const uint64_t now = 1'000'000; + const Retry::Bound capped = Retry::standard().cappedAt(now + 10'000).bind(now, kEngineTestWindowMs); + EXPECT_EQ(capped.deadline_ms, now + 10'000); + EXPECT_NE(capped.source, Retry::Bound::Source::Lease); + + Retry both = Retry::untilLeaseSafe(now + 10'000, 2'000).cappedAt(now + 20'000); + EXPECT_EQ(both.bind(now, kEngineTestWindowMs).deadline_ms, now + 8'000); + EXPECT_EQ(both.bind(now, kEngineTestWindowMs).source, Retry::Bound::Source::Lease); - clock.now += 50'000; - EXPECT_EQ(op.freeze(frozen).policy_deadline_ms, frozen.policy_deadline_ms); + both = Retry::untilLeaseSafe(now + 10'000, 2'000).cappedAt(now + 3'000); + EXPECT_EQ(both.bind(now, kEngineTestWindowMs).deadline_ms, now + 3'000); + EXPECT_NE(both.bind(now, kEngineTestWindowMs).source, Retry::Bound::Source::Lease); - const Retry::Bound leashed = op.freeze(Retry::untilLeaseSafe(start + 10'000, 2'000)).bind(clock.now, kEngineTestWindowMs); - EXPECT_EQ(leashed.deadline_ms, start + 8'000); - EXPECT_TRUE(leashed.lease_bound); + EXPECT_EQ(Retry::standard().cappedAt(now + 20'000).cappedAt(now + 5'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 5'000); + EXPECT_EQ(Retry::standard().cappedAt(now + 60'000).bind(now + 50'000, kEngineTestWindowMs).deadline_ms, now + 60'000); + EXPECT_EQ(Retry::standard().cappedAt(now + 5'000).cappedAt(now + 20'000).bind(now, kEngineTestWindowMs).deadline_ms, now + 5'000); +} + +/// A bound names the bound that set its deadline; a tie goes to the request window, then to the outside cap. +TEST(CASRetry, BindNamesTheExactSourceOfItsDeadline) +{ + using Source = Retry::Bound::Source; + const uint64_t now = 1'000'000; + EXPECT_EQ(Retry::standard().bind(now, kEngineTestWindowMs).source, Source::RequestWindow); + EXPECT_EQ(Retry::standard().cappedAt(now + 10'000).bind(now, kEngineTestWindowMs).source, Source::OutsideCap); + EXPECT_EQ(Retry::untilLeaseSafe(now + 10'000, 2'000).bind(now, kEngineTestWindowMs).source, Source::Lease); + + const Retry::Bound all_equal + = Retry::untilLeaseSafe(now + 92'000, 2'000).cappedAt(now + 90'000).bind(now, kEngineTestWindowMs); + EXPECT_EQ(all_equal.deadline_ms, now + 90'000); + EXPECT_EQ(all_equal.source, Source::RequestWindow); + + const Retry::Bound cap_equals_lease + = Retry::untilLeaseSafe(now + 12'000, 2'000).cappedAt(now + 10'000).bind(now, kEngineTestWindowMs); + EXPECT_EQ(cap_equals_lease.deadline_ms, now + 10'000); + EXPECT_EQ(cap_equals_lease.source, Source::OutsideCap); +} + +TEST(CASRetry, BindSaturatesWhenTheWindowOverflows) +{ + const uint64_t now = std::numeric_limits::max() - 10; + EXPECT_EQ(Retry::within(1'000).bind(now, kEngineTestWindowMs).deadline_ms, std::numeric_limits::max()); +} + +/// The tool's preflight checks the bound the engine will apply, so a plane window too short for one attempt +/// is the tool's timeout even when the tool's own deadline is far away. +TEST(CASRequests, ToolDeadlinePreflightChecksTheWindowNotOnlyTheCap) +{ + FakeClock clock; + auto backend = std::make_shared(); + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, 1'000); + requests.setAttemptReservationForTest(5'000); + const ToolDeadline deadline(requests, std::chrono::hours(1), "tool", "raise --timeout"); + auto op = requests.admit(); + EXPECT_THROW(deadline.bound(op, "phase"), DB::Exception); } /// A policy that names no window takes the window of the plane it runs on; one that names its own keeps it. @@ -274,6 +344,234 @@ TEST(CASWriteResult, OrThrowMapsEveryAlternative) [&] { orThrow(WriteResult{unresolved}, "t"); }); } +TEST(CASRequests, GaveUpAttemptsThrowsRetryLaterWithTheDecisionCount) +{ + const GaveUp capped{ + .why = GaveUp::Why::Attempts, .deadline_source = GaveUp::Source::Policy, + .sent_any = true, .last_seen = NotObserved{}}; + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "did not converge after 100 decisions", + [&] { orThrow(WriteResult{capped}, "t"); }); +} + +TEST(CASRequests, ThrowDidNotConvergeNamesItsUnit) +{ + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "casUpdate: did not converge after 7 submissions", + [&] { throwDidNotConverge("casUpdate", 7, "submissions"); }); +} + +TEST(CASRequests, PauseBeforeRedecideSleepsWithTheSmallestValidWindow) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + const GaveUp unresolved{ + .why = GaveUp::Why::Unresolved, .deadline_source = GaveUp::Source::Policy, + .sent_any = true, .last_seen = NotObserved{}}; + /// Two envelopes plus 1 ms is the smallest window a write accepts; a 2 ms pause must not need more. + const Retry policy = Retry::within(2 * requests.attemptReservationMs() + 1); + + EXPECT_FALSE(op.pauseAfterUnresolvedWrite(2, unresolved, policy).has_value()); + ASSERT_EQ(clock.sleeps.size(), 1u); + EXPECT_EQ(clock.sleeps.front(), 2u); +} + +namespace +{ + +GaveUp unresolvedAfterOneSend() +{ + return GaveUp{.why = GaveUp::Why::Unresolved, .deadline_source = GaveUp::Source::Policy, + .sent_any = true, .last_seen = NotObserved{}, .attempts_sent = 1}; +} + +/// The give-up `pauseAfterUnresolvedWrite` returned for a 2 ms pause, which must not have slept. +GaveUp refusedPause(CasOperation & op, FakeClock & clock, const Retry & policy) +{ + const std::optional given_up = op.pauseAfterUnresolvedWrite(2, unresolvedAfterOneSend(), policy); + EXPECT_TRUE(clock.sleeps.empty()); + if (!given_up || !std::holds_alternative(*given_up)) + { + ADD_FAILURE() << "the pause was not refused"; + return unresolvedAfterOneSend(); + } + return std::get(*given_up); +} + +} + +TEST(CASRequests, PauseBeforeRedecideRefusesAPauseThatEndsAfterTheOutsideCap) +{ + FakeClock clock; + auto requests = makeRequests(std::make_shared(), clock); + auto op = requests.admit(); + + const GaveUp gave_up = refusedPause(op, clock, Retry::standard().cappedAt(clock.now + 1)); + EXPECT_EQ(gave_up.why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up.deadline_source, GaveUp::Source::Policy); + EXPECT_EQ(gave_up.attempts_sent, 1u); +} + +TEST(CASRequests, PauseBeforeRedecideRefusesAPauseThatEndsAfterTheExplicitLease) +{ + FakeClock clock; + auto requests = makeRequests(std::make_shared(), clock); + auto op = requests.admit(); + + const GaveUp gave_up = refusedPause(op, clock, Retry::untilLeaseSafe(clock.now + 1, /*margin=*/0)); + EXPECT_EQ(gave_up.why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up.deadline_source, GaveUp::Source::Lease); +} + +/// A lost fence names the bound a request would be given now, as every request does: the lease only +/// when it ends before the window. +TEST(CASRequests, PauseBeforeRedecideRefusesAfterAFenceLossAndNamesTheBoundARequestWouldGet) +{ + FakeClock clock; + Fence lost{ + [] { return uint64_t(1); }, + [](uint64_t, uint64_t) { return Fence::Admit::LostOrRearmed; }, + [](uint64_t) {}}; + auto requests = makeRequests(std::make_shared(), clock, lost); + auto op = requests.admit(); + + const GaveUp under_window = refusedPause(op, clock, Retry::standard()); + EXPECT_EQ(under_window.why, GaveUp::Why::FenceLost); + EXPECT_EQ(under_window.deadline_source, GaveUp::Source::Policy); + + const GaveUp under_near_lease = refusedPause(op, clock, Retry::untilLeaseSafe(clock.now + 1'000, /*margin=*/0)); + EXPECT_EQ(under_near_lease.why, GaveUp::Why::FenceLost); + EXPECT_EQ(under_near_lease.deadline_source, GaveUp::Source::Lease); + + const GaveUp under_far_lease = refusedPause(op, clock, Retry::untilLeaseSafe(clock.now + 10 * kEngineTestWindowMs, /*margin=*/0)); + EXPECT_EQ(under_far_lease.why, GaveUp::Why::FenceLost); + EXPECT_EQ(under_far_lease.deadline_source, GaveUp::Source::Policy); +} + +/// The mount lease has less time left than the pause: the call ends unslept and names the lease. A +/// shorter pause still sleeps. +TEST(CASRequests, PauseBeforeRedecideRefusesAPauseLongerThanTheMountLeaseLeft) +{ + FakeClock clock; + const uint64_t lease_left_ms = 1'000; + Fence short_lease{ + [] { return uint64_t{0}; }, + [&](uint64_t, uint64_t needed_ms) { return needed_ms >= lease_left_ms ? Fence::Admit::NoBudget : Fence::Admit::Ok; }, + [](uint64_t) {}}; + auto requests = makeRequests(std::make_shared(), clock, short_lease); + auto op = requests.admit(); + + const std::optional given_up = op.pauseAfterUnresolvedWrite(lease_left_ms, unresolvedAfterOneSend(), Retry::standard()); + EXPECT_TRUE(clock.sleeps.empty()); + ASSERT_TRUE(given_up.has_value()); + const auto * gave_up = std::get_if(&*given_up); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Lease); + EXPECT_EQ(gave_up->attempts_sent, 1u); + + EXPECT_FALSE(op.pauseAfterUnresolvedWrite(lease_left_ms - 1, unresolvedAfterOneSend(), Retry::standard()).has_value()); + EXPECT_EQ(clock.sleeps, std::vector{lease_left_ms - 1}); +} + +/// A pause that fits exactly ends on the limit, and the call ends there instead of deciding again. +TEST(CASRequests, PauseBeforeRedecideEndingOnTheOutsideCapEndsTheCall) +{ + FakeClock clock; + auto requests = makeRequests(std::make_shared(), clock); + auto op = requests.admit(); + + const std::optional given_up + = op.pauseAfterUnresolvedWrite(50, unresolvedAfterOneSend(), Retry::standard().cappedAt(clock.now + 50)); + EXPECT_EQ(clock.sleeps.size(), 1u); + ASSERT_TRUE(given_up.has_value()); + const auto * gave_up = std::get_if(&*given_up); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); +} + +TEST(CASRequests, PauseBeforeRedecideEndingOnTheExplicitLeaseEndsTheCall) +{ + FakeClock clock; + auto requests = makeRequests(std::make_shared(), clock); + auto op = requests.admit(); + + const std::optional given_up + = op.pauseAfterUnresolvedWrite(50, unresolvedAfterOneSend(), Retry::untilLeaseSafe(clock.now + 50, /*margin=*/0)); + EXPECT_EQ(clock.sleeps.size(), 1u); + ASSERT_TRUE(given_up.has_value()); + const auto * gave_up = std::get_if(&*given_up); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Lease); +} + +namespace +{ + +/// Two lost races, the first retried at once, then a pause that sleeps 10 s past what it asked for. `policy_ending_at` builds the +/// policy from the instant the room for one write and one conflict pause ends. Returns the result and +/// how many times `decide` ran. +std::pair raceThenOversleep(const std::function & policy_ending_at) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto rival_requests = makeRequests(backend, clock); + auto rival = rival_requests.admit(); + requests.setSleepFnForTest([&](uint64_t ms) { clock.sleepFn()(ms + 10'000); }); + /// The rival wins the first two races: the first is retried at once, the second pauses. + int staged = 0; + bool staging = false; + backend->onBeforeWrite("k", [&] + { + if (staging || staged >= 2) + return; + staging = true; + if (const auto current = rival.read("k", Retry::once())) + orThrow(rival.replace("k", "theirs again", current->etag, Retry::once()), "rival"); + else + orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + ++staged; + staging = false; + }); + + int decisions = 0; + auto op = requests.admit(); + const Retry policy = policy_ending_at(clock.now + 2 * requests.attemptReservationMs() + 1'000); + WriteResult result = op.readModifyWrite("k", + [&](const std::optional &) -> std::optional + { + ++decisions; + return String("mine"); + }, + policy); + return {std::move(result), decisions}; +} + +} + +TEST(CASRequests, ReadModifyWriteWakingPastTheOutsideCapRunsNoSecondDecide) +{ + const auto [result, decisions] = raceThenOversleep([](uint64_t end) { return Retry::standard().cappedAt(end); }); + EXPECT_EQ(decisions, 2); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); +} + +TEST(CASRequests, ReadModifyWriteWakingPastTheExplicitLeaseRunsNoSecondDecide) +{ + const auto [result, decisions] = raceThenOversleep([](uint64_t end) { return Retry::untilLeaseSafe(end, /*margin=*/0); }); + EXPECT_EQ(decisions, 2); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Lease); +} + TEST(CASFence, OpenFenceAdmitsEverythingAndNeverMoves) { Fence f = Fence::open(); @@ -645,18 +943,18 @@ TEST(CASRetry, BindSaturatesAndLeavesAnEqualLeaseOffTheLeaseSource) /// A window one short of the whole range, so any `now` above 1 overflows a naive addition. EXPECT_EQ(Retry::within(largest - 1).bind(2, kEngineTestWindowMs).deadline_ms, largest); EXPECT_EQ(Retry::within(largest - 1).bind(1, kEngineTestWindowMs).deadline_ms, largest); - EXPECT_FALSE(Retry::within(largest - 1).bind(2, kEngineTestWindowMs).lease_bound); + EXPECT_NE(Retry::within(largest - 1).bind(2, kEngineTestWindowMs).source, Retry::Bound::Source::Lease); const uint64_t now = 1'000'000; /// The lease bound lands exactly on the policy deadline. The lease is taken only when it is /// STRICTLY smaller, so the tie belongs to the policy and `GaveUp` will not name the lease. const Retry::Bound tie = Retry::untilLeaseSafe(now + 92'000, 2'000).bind(now, kEngineTestWindowMs); EXPECT_EQ(tie.deadline_ms, now + 90'000); - EXPECT_FALSE(tie.lease_bound); + EXPECT_NE(tie.source, Retry::Bound::Source::Lease); const Retry::Bound lease = Retry::untilLeaseSafe(now + 91'999, 2'000).bind(now, kEngineTestWindowMs); EXPECT_EQ(lease.deadline_ms, now + 89'999); - EXPECT_TRUE(lease.lease_bound); + EXPECT_EQ(lease.source, Retry::Bound::Source::Lease); } TEST(CASRetrySpacing, UntilDefinitiveHasNoDeadlineAndSpacesItsAttempts) @@ -670,7 +968,7 @@ TEST(CASRetrySpacing, UntilDefinitiveHasNoDeadlineAndSpacesItsAttempts) { const Retry::Bound bound = policy.bind(now, kEngineTestWindowMs); EXPECT_EQ(bound.deadline_ms, largest) << "now " << now; - EXPECT_FALSE(bound.lease_bound) << "now " << now; + EXPECT_NE(bound.source, Retry::Bound::Source::Lease) << "now " << now; } EXPECT_FALSE(Retry::standard().attempt_spacing_ms.has_value()); EXPECT_FALSE(Retry::untilLeaseSafe(2'000'000, 2'000).attempt_spacing_ms.has_value()); @@ -1079,7 +1377,7 @@ TEST(CASRequests, OnPresenceSettlesARefusedPreconditionWithAHead) ASSERT_TRUE(std::holds_alternative(result)); /// A refused precondition needs only to know WHAT is at the key, so this loop never fetches a body. EXPECT_EQ(backend->getTotal(), 0u); - EXPECT_EQ(backend->headTotal(), 2u); + EXPECT_EQ(backend->headTotal(), 2u) << "the base and the read after the pause; the refusal itself is not settled"; EXPECT_EQ(backend->writeTotal(), 2u); } @@ -1126,11 +1424,11 @@ TEST(CASRequests, RemoveCurrentReObservesAMismatchAndRefusesUnderOnce) orThrow(op.create("k", "v", Retry::standard()), "create"); EXPECT_EQ(op.removeCurrent("k", Retry::standard()), Removal::Removed); - /// Another incarnation became current between the observation and the delete: observe again, - /// paced like every other reissue, and delete what the second look saw. + /// Another incarnation became current between the observation and the delete: a lost race, the first of + /// the call, so it observes again at once and deletes what the second look saw. EXPECT_EQ(backend->heads, 2u); EXPECT_EQ(backend->removes, 2u); - EXPECT_EQ(clock.sleeps.size(), 1u); + EXPECT_TRUE(clock.sleeps.empty()); } { FakeClock clock; @@ -1510,6 +1808,108 @@ TEST(CASRequests, OnPresenceReportsMetaEvenWhenItHadToFetchTheBody) EXPECT_EQ(backend->getTotal(), 1u); } +TEST(CASRequests, AFenceLostDuringThePauseRunsNoSecondDecide) +{ + FakeClock clock; + auto backend = std::make_shared(); + bool lost = false; + Fence fence{ + [] { return uint64_t(1); }, + [&](uint64_t, uint64_t) { return lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }, + [&](uint64_t) {}}; + auto requests = makeRequests(backend, clock, fence); + auto rival_requests = makeRequests(backend, clock); + auto rival = rival_requests.admit(); + requests.setSleepFnForTest([&](uint64_t ms) + { + clock.sleepFn()(ms); + lost = true; + }); + + /// The rival wins the first two races: the first is retried at once, the second pauses. + int staged = 0; + bool staging = false; + backend->onBeforeWrite("k", [&] + { + if (staging || staged >= 2) + return; + staging = true; + if (const auto current = rival.read("k", Retry::once())) + orThrow(rival.replace("k", "theirs again", current->etag, Retry::once()), "rival"); + else + orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + ++staged; + staging = false; + }); + + int decisions = 0; + auto op = requests.admit(); + WriteResult result = op.readModifyWrite("k", + [&](const std::optional &) -> std::optional + { + ++decisions; + return String("mine"); + }, + Retry::standard()); + + /// The conflicts were informative, so the loop would decide again; the fence moved in the pause after the second. + EXPECT_EQ(decisions, 2); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); +} + +TEST(CASRequests, AFenceLostDuringThePauseRunsNoSecondDecideOnPresence) +{ + FakeClock clock; + auto backend = std::make_shared(); + bool lost = false; + Fence fence{ + [] { return uint64_t(1); }, + [&](uint64_t, uint64_t) { return lost ? Fence::Admit::LostOrRearmed : Fence::Admit::Ok; }, + [&](uint64_t) {}}; + auto requests = makeRequests(backend, clock, fence); + auto rival_requests = makeRequests(backend, clock); + auto rival = rival_requests.admit(); + requests.setSleepFnForTest([&](uint64_t ms) + { + clock.sleepFn()(ms); + lost = true; + }); + + /// The rival wins the first two races: the first is retried at once, the second pauses. + int staged = 0; + bool staging = false; + backend->onBeforeWrite("k", [&] + { + if (staging || staged >= 2) + return; + staging = true; + if (const auto current = rival.read("k", Retry::once())) + orThrow(rival.replace("k", "theirs again", current->etag, Retry::once()), "rival"); + else + orThrow(rival.create("k", "theirs", Retry::once()), "rival"); + ++staged; + staging = false; + }); + + int decisions = 0; + auto op = requests.admit(); + WriteResult result = op.readModifyWriteOnPresence("k", + [&](const std::optional &) -> std::optional + { + ++decisions; + return String("mine"); + }, + Retry::standard()); + + /// The conflicts were informative, so the loop would decide again; the fence moved in the pause after the second. + EXPECT_EQ(decisions, 2); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::FenceLost); +} + TEST(CASRequests, AmbiguousReplaceWhoseResolveShowsThePreconditionUnchangedIsReissued) { FakeClock clock; @@ -1832,7 +2232,7 @@ TEST(CASRequests, ReadModifyWriteLosesNoIncrementUnderContentionAndBoundsAHotKey ASSERT_TRUE(counted.has_value()); EXPECT_EQ(counted->bytes, "100"); /// every conflict re-decided against what the resolve read saw - /// A key rewritten under EVERY attempt is bounded by the deadline instead of looping forever. + /// A key rewritten under EVERY attempt is bounded by the decision cap instead of looping forever. FakeClock clock; auto hot = makeRequests(backend, clock); auto competitor = makeRequests(backend, clock); @@ -1852,7 +2252,7 @@ TEST(CASRequests, ReadModifyWriteLosesNoIncrementUnderContentionAndBoundsAHotKey WriteResult result = op.readModifyWrite("ctr", increment, Retry::standard()); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); - EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->why, GaveUp::Why::Attempts); EXPECT_TRUE(gave_up->sent_any); EXPECT_FALSE(clock.sleeps.empty()); /// it paced its retries rather than spinning } @@ -1905,7 +2305,7 @@ DecideOnObject appendX() } -TEST(CASRequests, CleanConflictsArePacedFlatAndDoNotAdvanceTheReissueCounter) +TEST(CASRequests, CleanConflictsArePacedByTheirLossCountAndDoNotAdvanceTheReissueCounter) { FakeClock clock; auto backend = std::make_shared(); @@ -1920,12 +2320,21 @@ TEST(CASRequests, CleanConflictsArePacedFlatAndDoNotAdvanceTheReissueCounter) WriteResult result = op.readModifyWrite("k", appendX(), Retry::standard()); ASSERT_TRUE(std::holds_alternative(result)); - EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRequestConflictPause] - pauses_before, K); + /// The first loss is retried at once: no pause is slept or counted for it. + EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRequestConflictPause] - pauses_before, K - 1); EXPECT_EQ(ProfileEvents::global_counters[ProfileEvents::CASRequestReissue] - reissues_before, 0u); - ASSERT_EQ(clock.sleeps.size(), static_cast(K)); - for (uint64_t s : clock.sleeps) - EXPECT_LE(s, 200u); /// flat: every pause is one `backoff(1)` draw, whatever the loss count + ASSERT_EQ(clock.sleeps.size(), static_cast(K - 1)); + for (size_t i = 0; i < clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[i], static_cast(i + 2))); EXPECT_EQ(backend->writeCount("k"), 1u + K + 1u + K); /// seed, K refused, K rival moves, the one that landed + + /// A new call starts its own count. + clock.sleeps.clear(); + RaceMaker again(backend, clock, "k", 3, /*ambiguous=*/false); + ASSERT_TRUE(std::holds_alternative(op.readModifyWrite("k", appendX(), Retry::standard()))); + ASSERT_EQ(clock.sleeps.size(), 2u); + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[0], 2)); + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[1], 3)); } TEST(CASRequests, AConflictThatSettledAFaultKeepsTheGrowingSchedule) @@ -1950,6 +2359,183 @@ TEST(CASRequests, AConflictThatSettledAFaultKeepsTheGrowingSchedule) EXPECT_LE(clock.sleeps[i], std::min(5000, 200ull << i)) << "reissue " << i; } +namespace +{ + +/// Another writer of `key` that commits on demand. Its requests are bracketed by marks, so +/// `renderOwnRequests` shows only the caller's own requests. +struct MarkedRival +{ + MarkedRival(std::shared_ptr backend_, FakeClock & clock, String key_) + : backend(std::move(backend_)), key(std::move(key_)) + , rival_requests(makeRequests(backend, clock)), rival(rival_requests.admit()) + { + } + + void commit() + { + inside = true; + backend->mark("rival{"); + const auto current = rival.read(key, Retry::once()); + (void)orThrow(rival.replace(key, current->bytes + "r", current->etag, Retry::once()), "rival"); + backend->mark("}rival"); + ++commits; + inside = false; + } + + std::shared_ptr backend; + String key; + int commits = 0; + bool inside = false; + CasRequests rival_requests; + CasOperation rival; +}; + +String repeated(std::string_view unit, size_t times) +{ + String out; + for (size_t i = 0; i < times; ++i) + out += unit; + return out; +} + +} + +/// A conflict that settled a transport fault ends the run of clean losses: the clean loss after it starts a new run and +/// is retried at once, so only the fault-settled conflict pauses. +TEST(CASRequests, AFaultSettledConflictRestartsTheCleanLossCount) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + (void)orThrow(op.create("k", "v", Retry::standard()), "seed"); + MarkedRival rival(backend, clock, "k"); + int moves = 0; + backend->onBeforeWrite("k", [&] + { + if (rival.inside || moves >= 3) + return; + ++moves; + rival.commit(); + if (moves == 2) + backend->injectAmbiguousWrite("k"); + }); + + ASSERT_TRUE(std::holds_alternative(op.readModifyWrite("k", appendX(), Retry::standard()))); + EXPECT_EQ(moves, 3) << "premise: clean, fault-settled, clean"; + EXPECT_EQ(clock.sleeps.size(), 1u) << "the clean losses around the fault are each the first of their run"; +} + +/// The rival lands right before the first two writes and during every pause. The first loss is retried at once; the +/// write after the pause that follows the second is decided on a read taken after it, so it lands. +TEST(CASRequests, AReadModifyWriteIsNotStarvedByAWriterThatCommitsDuringEveryPause) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + (void)orThrow(op.create("k", "v", Retry::standard()), "seed"); + MarkedRival rival(backend, clock, "k"); + int collisions = 0; + backend->onBeforeWrite("k", [&] + { + if (rival.inside || collisions >= 2) + return; + ++collisions; + rival.commit(); + }); + auto sleep = clock.sleepFn(); + requests.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + backend->mark("pause"); + rival.commit(); + }); + backend->clearJournal(); + + WriteResult result = op.readModifyWrite("k", appendX(), Retry::standard()); + + ASSERT_TRUE(std::holds_alternative(result)); + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*backend, "k"), "RWRWPRW") + << "read, refused write, read, refused write, pause, read, the write on it"; + EXPECT_EQ(clock.sleeps.size(), 1u); + EXPECT_EQ(rival.commits, 3); + expectBytes(*backend, "k", "vrrrx"); +} + +TEST(CASRequests, AnOnPresenceWriteIsNotStarvedByAWriterThatCommitsDuringEveryPause) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + (void)orThrow(op.create("k", "v", Retry::standard()), "seed"); + MarkedRival rival(backend, clock, "k"); + int collisions = 0; + backend->onBeforeWrite("k", [&] + { + if (rival.inside || collisions >= 2) + return; + ++collisions; + rival.commit(); + }); + auto sleep = clock.sleepFn(); + requests.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + backend->mark("pause"); + rival.commit(); + }); + backend->clearJournal(); + + WriteResult result = op.readModifyWriteOnPresence("k", + [](const std::optional &) -> std::optional { return String("w"); }, Retry::standard()); + + ASSERT_TRUE(std::holds_alternative(result)); + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*backend, "k"), "HWHWPHW"); + EXPECT_EQ(clock.sleeps.size(), 1u); + expectBytes(*backend, "k", "w"); +} + +/// A rival that lands between every read and the write on it still ends the loop on the decision +/// cap, and every write after the first is decided on a read taken after its pause. +TEST(CASRequests, AReadModifyWriteAgainstAWriterBeforeEveryWriteEndsOnTheCount) +{ + FakeClock clock; + auto backend = std::make_shared(); + auto requests = makeRequests(backend, clock); + auto op = requests.admit(); + (void)orThrow(op.create("k", "v", Retry::standard()), "seed"); + MarkedRival rival(backend, clock, "k"); + backend->onBeforeWrite("k", [&] + { + if (!rival.inside) + rival.commit(); + }); + auto sleep = clock.sleepFn(); + requests.setSleepFnForTest([&](uint64_t ms) + { + sleep(ms); + backend->mark("pause"); + }); + backend->clearJournal(); + + WriteResult result = op.readModifyWrite("k", appendX(), Retry::standard()); + + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr); + EXPECT_EQ(gave_up->why, GaveUp::Why::Attempts); + EXPECT_EQ(clock.sleeps.size(), kCasMaxDecisions - 2) << "no pause after the first refusal, retried at once, nor the last"; + for (size_t i = 0; i < clock.sleeps.size(); ++i) + EXPECT_TRUE(DB::Cas::tests::isConflictPause(clock.sleeps[i], static_cast(i + 2))); + /// Only the last refusal is settled: no decision follows it, and its read is what the give-up reports. + EXPECT_EQ(DB::Cas::tests::renderOwnRequests(*backend, "k"), "RWRW" + repeated("PRW", kCasMaxDecisions - 3) + "PRWR"); + const auto * seen = std::get_if(&gave_up->last_seen); + ASSERT_NE(seen, nullptr); + expectBytes(*backend, "k", seen->bytes); +} + TEST(CASRequests, ReplaceReportsWhetherAConflictSettledAFault) { FakeClock clock; @@ -2029,8 +2615,9 @@ TEST(CASRequests, CleanConflictsBeforeAFaultDoNotInflateTheFaultsFirstBackoff) WriteResult result = op.readModifyWrite("k", appendX(), Retry::standard()); ASSERT_TRUE(std::holds_alternative(result)); - ASSERT_EQ(clock.sleeps.size(), static_cast(K + 1)); - EXPECT_LE(clock.sleeps[K], 200u) << "the first transport reissue sleeps within backoff(1)"; + /// The first clean loss is retried at once, so K - 1 conflict pauses precede the reissue's. + ASSERT_EQ(clock.sleeps.size(), static_cast(K)); + EXPECT_LE(clock.sleeps[K - 1], 200u) << "the first transport reissue sleeps within backoff(1)"; } TEST(CASRequests, ADeterministicLocalFailureSurfacesUnchangedWithoutAReissue) @@ -2437,7 +3024,7 @@ TEST(CASRequests, ANameOnlyAccessDenialOnAReadPropagatesWhenNoRefreshIsAvailable EXPECT_TRUE(clock.sleeps.empty()); } -TEST(CASRequests, ReadModifyWriteWhoseResolveAndFreshObservationBothFailGivesUpUnresolved) +TEST(CASRequests, ReadModifyWriteWhoseReadAfterTheConflictPauseFailsGivesUpUnresolved) { FakeClock clock; auto backend = std::make_shared(); @@ -2446,9 +3033,10 @@ TEST(CASRequests, ReadModifyWriteWhoseResolveAndFreshObservationBothFailGivesUpU orThrow(op.create("k", "v0", Retry::standard()), "create"); backend->resetCounts(); - /// The store refuses the precondition, and both reads that would settle what happened answer with - /// a store refusal the read loop surfaces at once rather than reissuing. They are armed from inside - /// the write so the loop's OWN first read still succeeds and `decide` sees the object. + /// The store refuses the precondition, and the read after the conflict pause answers with a store + /// refusal the read loop surfaces at once rather than reissuing; the refusal itself is not settled, as + /// that read replaces what settling it would see. Armed from inside the write so the loop's OWN first + /// read still succeeds and `decide` sees the object. backend->refuseNextWrite("k"); bool armed = false; backend->onBeforeWrite("k", [&] @@ -2457,14 +3045,13 @@ TEST(CASRequests, ReadModifyWriteWhoseResolveAndFreshObservationBothFailGivesUpU return; armed = true; backend->failNextReadWith("k", s3Error(Aws::S3::S3Errors::UNKNOWN, "MalformedXML")); - backend->failNextReadWith("k", s3Error(Aws::S3::S3Errors::UNKNOWN, "MalformedXML")); }); WriteResult result = op.readModifyWrite("k", [](const std::optional &) -> std::optional { return String("v1"); }, Retry::standard()); const auto * gave_up = std::get_if(&result); ASSERT_NE(gave_up, nullptr); - /// No BOUND refused either read -- the reads themselves failed -- so naming a deadline the clock + /// No BOUND refused the read -- the read itself failed -- so naming a deadline the clock /// never reached would send its reader to widen the wrong thing, and nothing was observed to /// report as a conflict. EXPECT_EQ(gave_up->why, GaveUp::Why::Unresolved); @@ -2472,8 +3059,8 @@ TEST(CASRequests, ReadModifyWriteWhoseResolveAndFreshObservationBothFailGivesUpU EXPECT_TRUE(std::holds_alternative(gave_up->last_seen)); /// The write count is unchanged after the first attempt: nothing ever said another one was safe. EXPECT_EQ(backend->writeTotal(), 1u); - EXPECT_EQ(backend->getTotal(), 3u); - EXPECT_EQ(clock.sleeps.size(), 1u); + EXPECT_EQ(backend->getTotal(), 2u); + EXPECT_TRUE(clock.sleeps.empty()) << "the first conflict is retried at once"; } /// A missing bucket is an ANSWER the store gave, but not an answer about the object: an S3-compatible diff --git a/src/Disks/tests/gtest_cas_sentinel_probe.cpp b/src/Disks/tests/gtest_cas_sentinel_probe.cpp index 399b2871e3eac..4ec8d2dddf4f8 100644 --- a/src/Disks/tests/gtest_cas_sentinel_probe.cpp +++ b/src/Disks/tests/gtest_cas_sentinel_probe.cpp @@ -7,26 +7,39 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include +#include +#include +#include +#include #include #include #include +#include +#include #include +#include + #if USE_AWS_S3 #include #endif namespace DB::ErrorCodes { +extern const int ABORTED; extern const int NETWORK_ERROR; +extern const int QUERY_WAS_CANCELLED; +extern const int S3_ERROR; } using namespace DB::Cas; @@ -56,9 +69,9 @@ CasRequests makeRequests(Backend & backend, DB::Cas::tests::FakeClock * clock = return CasRequests(std::move(ptr), Fence::open(), {}, {}, nullptr, DB::Cas::kDefaultRequestWindowMs); } -/// A Backend decorator whose read/head/list all throw an untyped runtime error when armed — modelling -/// a backend with no sharper evidence than "something went wrong" (a network timeout, a 5xx, an -/// unclassifiable failure). The fault is injected on the PRIMITIVES, which is what +/// A Backend decorator whose read/head/list all throw a transport timeout when armed — modelling a +/// backend with no sharper evidence than "something went wrong". An exception that is not a +/// `Poco::Exception` is a local fault, which the probe lets through. The fault is injected on the PRIMITIVES, which is what /// `Backend::probeSentinelRaw`'s default derives its answer from; every other operation delegates to /// InMemoryBackend unchanged. class TransportFaultBackend final : public InMemoryBackend @@ -67,21 +80,21 @@ class TransportFaultBackend final : public InMemoryBackend std::optional head(const String & key, TransportAccess & access) override { if (fail.load()) - throw std::runtime_error("injected fault: transport error"); + throw Poco::TimeoutException("injected fault: transport error"); return InMemoryBackend::head(key, access); } std::optional read(const String & key, TransportAccess & access) override { if (fail.load()) - throw std::runtime_error("injected fault: transport error"); + throw Poco::TimeoutException("injected fault: transport error"); return InMemoryBackend::read(key, access); } RawListPage list(const String & prefix, const String & cursor, size_t limit, TransportAccess & access) override { if (fail.load()) - throw std::runtime_error("injected fault: transport error"); + throw Poco::TimeoutException("injected fault: transport error"); return InMemoryBackend::list(prefix, cursor, limit, access); } @@ -396,3 +409,351 @@ TEST(CASSentinelProbe, InstrumentedBackendForwardsToInnerClassification) } #endif + +namespace +{ + +using DB::Cas::tests::CasKillableQuery; +using DB::Cas::tests::onThread; + +struct ProbeObserved +{ + bool returned = false; + ProbeOutcome outcome = ProbeOutcome::Indeterminate; + int code = 0; + String what; +}; + +ProbeObserved probeOnce(CasRequests & requests, const String & key, const Retry & policy) +{ + ProbeObserved seen; + auto op = requests.admit(); + try + { + seen.outcome = probeSentinel(op, key, policy).outcome; + seen.returned = true; + } + catch (const DB::Exception & e) + { + seen.code = e.code(); + seen.what = e.message(); + } + catch (const std::exception & e) + { + seen.code = -1; + seen.what = e.what(); + } + return seen; +} + +/// Counts probes and credential refreshes. A failure first asks the thread's query, as the S3 client does. +class FailingProbeBackend final : public InMemoryBackend +{ +public: + enum class Mode { Throw, ReturnIndeterminate, ReturnPresent }; + + Mode mode = Mode::Throw; + std::exception_ptr failure = std::make_exception_ptr(Poco::TimeoutException("the probe timed out")); + std::atomic probes{0}; + std::atomic refreshes{0}; + + SentinelProbeResult probeSentinelRaw(const String &, TransportAccess &) override + { + ++probes; + DB::CurrentThread::checkIfNotCancelled(); + if (mode == Mode::ReturnIndeterminate) + return {ProbeOutcome::Indeterminate, std::nullopt}; + if (mode == Mode::ReturnPresent) + return {ProbeOutcome::Present, String("v")}; + std::rethrow_exception(failure); + } + + bool refreshCredentials() override + { + ++refreshes; + return true; + } +}; + +/// What the store answers to a request it refuses for credentials. +std::exception_ptr credentialFailure() +{ +#if USE_AWS_S3 + return std::make_exception_ptr(DB::S3Exception("the store answered AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, "AccessDenied")); +#else + return std::make_exception_ptr(Poco::IOException("the store answered AccessDenied")); +#endif +} + +void stopBackground(std::optional & scope) +{ + scope.emplace(OwnerScope::background([] { throw DB::Exception(DB::ErrorCodes::ABORTED, "background owner stopped"); })); +} + +} + +/// A stopped owner's probe surfaces the owner's verdict: no reissue, no credential refresh, and no +/// `Indeterminate` returned in its place. +TEST(CASSentinelProbe, StoppedProbePreservesCallerVerdict) +{ + for (const bool once : {true, false}) + { + const Retry policy = once ? Retry::once() : Retry::standard(); + SCOPED_TRACE(once ? "once" : "standard"); + + for (const auto mode : {FailingProbeBackend::Mode::Throw, FailingProbeBackend::Mode::ReturnIndeterminate}) + { + SCOPED_TRACE(mode == FailingProbeBackend::Mode::Throw ? "backend throws" : "backend returns Indeterminate"); + ProbeObserved seen; + int probes = 0; + int refreshes = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(); + backend->mode = mode; + backend->failure = credentialFailure(); + DB::Cas::tests::FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + query.kill(); + seen = probeOnce(requests, "k", policy); + probes = backend->probes.load(); + refreshes = backend->refreshes.load(); + }); + EXPECT_FALSE(seen.returned) << "the verdict, not an outcome"; + EXPECT_EQ(seen.code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(probes, 1); + EXPECT_EQ(refreshes, 0); + } + + { + SCOPED_TRACE("background owner, backend returns Indeterminate"); + ProbeObserved seen; + int probes = 0; + onThread(false, [&] + { + auto backend = std::make_shared(); + backend->mode = FailingProbeBackend::Mode::ReturnIndeterminate; + DB::Cas::tests::FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + std::optional scope; + stopBackground(scope); + seen = probeOnce(requests, "k", policy); + probes = backend->probes.load(); + }); + EXPECT_FALSE(seen.returned) << "the returned Indeterminate is replaced by the verdict"; + EXPECT_EQ(seen.code, DB::ErrorCodes::ABORTED); + EXPECT_EQ(probes, 1); + } + + { + SCOPED_TRACE("background owner, backend throws a credential answer"); + ProbeObserved seen; + int probes = 0; + int refreshes = 0; + onThread(false, [&] + { + auto backend = std::make_shared(); + backend->failure = credentialFailure(); + DB::Cas::tests::FakeClock clock; + CasRequests requests(backend, Fence::open(), clock.nowFn(), clock.sleepFn(), nullptr, DB::Cas::kDefaultRequestWindowMs); + std::optional scope; + stopBackground(scope); + seen = probeOnce(requests, "k", policy); + probes = backend->probes.load(); + refreshes = backend->refreshes.load(); + }); + EXPECT_FALSE(seen.returned); + EXPECT_EQ(seen.code, DB::ErrorCodes::ABORTED); + EXPECT_EQ(probes, 1); + EXPECT_EQ(refreshes, 0); + } + } +} + +/// A stop that lands during the pause before a reissue starts no further probe, even one that would succeed. The +/// probe ends with what the failed one had: the exception behind it, or the inconclusive outcome itself. +TEST(CASSentinelProbe, StopDuringProbeBackoffStartsNoReissue) +{ + for (const bool with_cause : {false, true}) + { + SCOPED_TRACE(with_cause ? "the failed probe threw" : "the failed probe returned Indeterminate"); + ProbeObserved seen; + int probes = 0; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + auto backend = std::make_shared(); + backend->mode = with_cause ? FailingProbeBackend::Mode::Throw : FailingProbeBackend::Mode::ReturnIndeterminate; + DB::Cas::tests::FakeClock clock; + auto sleep = clock.sleepFn(); + CasRequests requests(backend, Fence::open(), clock.nowFn(), [&](uint64_t ms) + { + sleep(ms); + backend->mode = FailingProbeBackend::Mode::ReturnPresent; /// the reissue would succeed: it must not start + query.kill(); + }, nullptr, DB::Cas::kDefaultRequestWindowMs); + seen = probeOnce(requests, "k", Retry::standard()); + probes = backend->probes.load(); + }); + if (with_cause) + { + EXPECT_FALSE(seen.returned); + EXPECT_EQ(seen.code, -1) << "the probe's own Poco timeout, not the query's verdict"; + EXPECT_EQ(seen.what, "Timeout"); + } + else + { + ASSERT_TRUE(seen.returned) << seen.what; + EXPECT_EQ(seen.outcome, ProbeOutcome::Indeterminate); + } + EXPECT_EQ(probes, 1); + } +} + +/// A healthy first probe is never refused, whoever stopped. +TEST(CASSentinelProbe, HealthyFirstProbeIsNotRefused) +{ + for (const bool background : {false, true}) + { + SCOPED_TRACE(background ? "background owner" : "killed query"); + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + InMemoryBackend backend; + auto requests = makeRequests(backend); + auto op = requests.admit(); + ASSERT_TRUE(std::holds_alternative(op.create("k", "v", Retry::once()))); + std::optional scope; + if (background) + stopBackground(scope); + else + query.kill(); + ASSERT_NE(ownerStopRequested(), nullptr); + EXPECT_EQ(probeSentinel(op, "k", Retry::standard()).outcome, ProbeOutcome::Present); + EXPECT_EQ(probeSentinel(op, "missing", Retry::standard()).outcome, ProbeOutcome::KeyAbsent); + }); + } +} + +#if USE_AWS_S3 + +namespace +{ + +/// Fails every access with `code` after asking the thread's query, as the S3 client does. +class ClientLikeS3ObjectStorage final : public DB::LocalObjectStorage +{ +public: + using DB::LocalObjectStorage::LocalObjectStorage; + + mutable std::atomic accesses{0}; + Aws::S3::S3Errors code = Aws::S3::S3Errors::SERVICE_UNAVAILABLE; + + std::unique_ptr readObject( + const DB::StoredObject & object, const DB::ReadSettings &, std::optional, bool, bool) const override + { + fail(object.remote_path); + } + + DB::SmallObjectDataWithMetadata readSmallObjectAndGetObjectMetadata( /// NOLINT + const DB::StoredObject & object, const DB::ReadSettings &, size_t, std::optional) const override + { + fail(object.remote_path); + } + + DB::ObjectMetadata getObjectMetadata(const std::string & path, bool) const override { fail(path); } + +private: + [[noreturn]] void fail(const String & path) const + { + ++accesses; + DB::CurrentThread::checkIfNotCancelled(); + throw DB::S3Exception("the store answered for " + path, code); + } +}; + +std::shared_ptr makeClientLikeS3Storage(Aws::S3::S3Errors code) +{ + static std::atomic counter{0}; + const auto root = (std::filesystem::temp_directory_path() + / ("cas_sentinel_probe_stop_" + std::to_string(::getpid()) + "_" + std::to_string(counter.fetch_add(1)))).string(); + std::filesystem::remove_all(root); + std::filesystem::create_directories(root); + DB::LocalObjectStorageSettings settings("test", root, /*read_only_=*/false); + auto storage = DB::Cas::tests::ownedByDirectory(std::make_shared(std::move(settings)), root); + storage->code = code; + return storage; +} + +} + +/// A stopped query's native probe is inconclusive, a stored cause that is itself an `S3Exception` `NoSuchBucket` or +/// `AccessDenied` included: none of them becomes an authoritative outcome, and the probe is not reissued. +TEST(CASSentinelProbe, StoppedQueryNativeProbeIsNotAnAuthoritativeOutcome) +{ + struct Arm + { + const char * name; + Aws::S3::S3Errors store_code; + std::function cause; + }; + const std::vector arms = { + {"plain kill", Aws::S3::S3Errors::SERVICE_UNAVAILABLE, [] { return std::exception_ptr{}; }}, + {"stored NoSuchBucket", Aws::S3::S3Errors::NO_SUCH_BUCKET, + [] { return std::make_exception_ptr(DB::S3Exception("stored cause", Aws::S3::S3Errors::NO_SUCH_BUCKET)); }}, + {"stored AccessDenied", Aws::S3::S3Errors::ACCESS_DENIED, + [] { return std::make_exception_ptr(DB::S3Exception("stored cause", Aws::S3::S3Errors::ACCESS_DENIED)); }}, + }; + for (const bool once : {true, false}) + { + for (const auto & arm : arms) + { + SCOPED_TRACE(String(once ? "once, " : "standard, ") + arm.name); + auto storage = makeClientLikeS3Storage(arm.store_code); + ObjectStorageBackend backend(storage, ObjectStorageBackend::Mode::Native); + ProbeObserved seen; + onThread(true, [&] + { + CasKillableQuery query(getContext().context); + DB::Cas::tests::FakeClock clock; + auto requests = makeRequests(backend, &clock); + query.kill(arm.cause()); + seen = probeOnce(requests, nativeKeyUnder(storage, "some/key"), once ? Retry::once() : Retry::standard()); + }); + ASSERT_TRUE(seen.returned) << seen.what; + EXPECT_EQ(seen.outcome, ProbeOutcome::Indeterminate); + EXPECT_EQ(storage->accesses.load(), 1) << "no reissue"; + } + } +} + +/// The S3 client cannot see a background owner, so the store's own answer stays authoritative. +TEST(CASSentinelProbe, BackgroundOwnerKeepsTheStoresAnswer) +{ + const std::vector> answers = { + {Aws::S3::S3Errors::NO_SUCH_BUCKET, ProbeOutcome::ContainerAbsent}, + {Aws::S3::S3Errors::ACCESS_DENIED, ProbeOutcome::AccessDenied}, + {Aws::S3::S3Errors::NO_SUCH_KEY, ProbeOutcome::KeyAbsent}, + }; + for (const auto & [code, expected] : answers) + { + SCOPED_TRACE(static_cast(code)); + auto storage = makeClientLikeS3Storage(code); + ObjectStorageBackend backend(storage, ObjectStorageBackend::Mode::Native); + ProbeObserved seen; + onThread(false, [&] + { + auto requests = makeRequests(backend); + std::optional scope; + stopBackground(scope); + ASSERT_NE(ownerStopRequested(), nullptr); + seen = probeOnce(requests, nativeKeyUnder(storage, "some/key"), Retry::standard()); + }); + ASSERT_TRUE(seen.returned) << seen.what; + EXPECT_EQ(seen.outcome, expected); + EXPECT_EQ(storage->accesses.load(), 1); + } +} + +#endif diff --git a/src/Disks/tests/gtest_cas_settings.cpp b/src/Disks/tests/gtest_cas_settings.cpp index b22ab0823a6ad..864ce810d82d4 100644 --- a/src/Disks/tests/gtest_cas_settings.cpp +++ b/src/Disks/tests/gtest_cas_settings.cpp @@ -856,11 +856,9 @@ TEST(CASContentAddressedSettings, RequestWindowDefaultAndValidation) [&] { DB::Cas::validateCasRequestWindow(budget); }); budget.request_window_ms = budget.attemptEnvelopeMs() + 1; EXPECT_NO_THROW(DB::Cas::validateCasRequestWindow(budget)); - - EXPECT_EQ(DB::Cas::CasRequestBudget{}.recovery_retry_budget_ms, 240'000u); } -TEST(CASContentAddressedSettings, RequestWindowSettingSetsTheWindowAndTwiceTheRecoveryBudget) +TEST(CASContentAddressedSettings, RequestWindowSettingSetsTheWindow) { auto cfg = makeConfig("srv190000"); ContentAddressedSettings s; @@ -869,12 +867,4 @@ TEST(CASContentAddressedSettings, RequestWindowSettingSetsTheWindowAndTwiceTheRe DB::Cas::PoolConfig pool_config; DB::Cas::setCasRequestWindow(pool_config.cas_request_budget, s[ContentAddressedSetting::request_window_ms].value); EXPECT_EQ(pool_config.cas_request_budget.request_window_ms, 90'000u); - EXPECT_EQ(pool_config.cas_request_budget.recovery_retry_budget_ms, 180'000u); - - constexpr uint64_t max = std::numeric_limits::max(); - DB::Cas::setCasRequestWindow(pool_config.cas_request_budget, max / 2); - EXPECT_EQ(pool_config.cas_request_budget.recovery_retry_budget_ms, max - 1); - DB::Cas::setCasRequestWindow(pool_config.cas_request_budget, max / 2 + 1); - EXPECT_EQ(pool_config.cas_request_budget.recovery_retry_budget_ms, max); - EXPECT_EQ(pool_config.cas_request_budget.request_window_ms, max / 2 + 1); } diff --git a/src/Disks/tests/gtest_cas_shared_deadline.cpp b/src/Disks/tests/gtest_cas_shared_deadline.cpp new file mode 100644 index 0000000000000..6293458e4692f --- /dev/null +++ b/src/Disks/tests/gtest_cas_shared_deadline.cpp @@ -0,0 +1,1312 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +/// Each request of the engine binds its own window when it is sent. In the first two sections a first step +/// takes all but one millisecond of a window and succeeds, and the test checks that the next request +/// is still sent and the operation completes; its failure text carries what the first step used and +/// what a window shared with the next request would have left. The other sections check a lost +/// write's settlement and the caps on decisions and submissions. + +namespace ProfileEvents +{ +extern const Event CASRefRecoveryRetries; +} + +namespace DB::ErrorCodes +{ +extern const int NETWORK_ERROR; +} + +using namespace DB::Cas; +using DB::Cas::tests::ManualClock; +using DB::Cas::tests::TimeTakingBackend; +using DB::Cas::tests::idOf; + +namespace +{ + +using Verb = TimeTakingBackend::Verb; +using Ending = TimeTakingBackend::Ending; + +constexpr uint64_t kWindowMs = kDefaultRequestWindowMs; +/// What one attempt reserves on a disk with default settings: `cas_attempt_timeout_ms` 5000 and two +/// connect caps of 1000. A read reserves one, a write two. +constexpr uint64_t kEnvelopeMs = 7'000; +constexpr uint64_t kFirstStepMs = kWindowMs - 1; +/// The longest pause `Retry::backoff` draws. +constexpr uint64_t kMaxBackoffMs = 5'000; + +std::function exactly(const String & wanted) +{ + return [wanted](const String & key) { return key == wanted; }; +} + +/// Runs `step` and returns the text of whatever it threw, or nothing. +std::optional failureOf(const std::function & step) +{ + try + { + step(); + } + catch (...) + { + return DB::getCurrentExceptionMessage(/*with_stacktrace=*/false); + } + return std::nullopt; +} + +String orNone(const std::optional & failure) +{ + return failure ? *failure : String("none"); +} + +/// The two numbers of a case, as text for a failure message. `sent` counts the requests of the next +/// step the store received after the first step ended. +String sharedWindow(uint64_t window_ms, uint64_t started_ms, uint64_t first_step_ended_ms, const String & next, size_t sent) +{ + const uint64_t used_ms = first_step_ended_ms - started_ms; + const uint64_t left_ms = window_ms > used_ms ? window_ms - used_ms : 0; + return fmt::format( + "\n first step: {} ms of the shared {} ms\n next ({}): {} ms of {} left, {}\n ", + used_ms, window_ms, next, left_ms, window_ms, + sent == 0 ? String("refused unsent, 0 attempt(s)") : fmt::format("sent {} time(s)", sent)); +} + +/// Requests of `verb` to `key` that reached the store at or after `from_ms`. +size_t sentSince(const TimeTakingBackend & backend, uint64_t from_ms, Verb verb, const String & key) +{ + size_t count = 0; + for (const TimeTakingBackend::Seen & request : backend.seen()) + if (request.verb == verb && request.key == key && request.at_ms >= from_ms) + ++count; + return count; +} + +String whyOf(GaveUp::Why why) +{ + switch (why) + { + case GaveUp::Why::Deadline: return "deadline"; + case GaveUp::Why::FenceLost: return "fence lost"; + case GaveUp::Why::Unresolved: return "unresolved"; + case GaveUp::Why::Attempts: return "attempts"; + } + return "unknown"; +} + +String outcomeOf(const WriteResult & result) +{ + if (std::holds_alternative(result)) + return "committed"; + if (std::holds_alternative(result)) + return "conflict"; + if (std::holds_alternative(result)) + return "declined"; + if (const auto * refused = std::get_if(&result)) + return "refused by the store: " + refused->message; + const GaveUp & gave_up = std::get(result); + return fmt::format("gave up ({}, {} bound) after {} attempt(s)", whyOf(gave_up.why), + gave_up.deadline_source == GaveUp::Source::Lease ? "lease" : "policy", gave_up.attempts_sent); +} + +/// A request plane over an open fence, with the reservation of a real disk and a clock the test moves. +struct Plane +{ + std::shared_ptr backend = std::make_shared(); + std::shared_ptr clock = std::make_shared(); + CasRequests requests; + CasOperation op; + + explicit Plane(CasHotKeys * lane = nullptr, Fence fence = Fence::open()) + : requests(backend, std::move(fence), ManualClock::nowFnOf(clock), ManualClock::sleepFnOf(clock), lane, kWindowMs) + , op(requests.admit()) + { + requests.setAttemptReservationForTest(kEnvelopeMs); + backend->stampWith(ManualClock::nowFnOf(clock)); + } + + void seed(const String & key, const String & bytes) + { + ASSERT_TRUE(std::holds_alternative(op.create(key, bytes, Retry::standard()))); + } + + String bytesOf(const String & key) + { + const std::optional object = op.read(key, Retry::standard()); + return object ? object->bytes : String(""); + } + + /// The next `verb` of `key` takes all but one millisecond of a window. + void slowDown(Verb verb, const String & key, Ending ending = Ending::Answered) + { + backend->armWith(verb, exactly(key), [clock_ = clock] { clock_->advance(kFirstStepMs); }, /*times=*/1, ending); + } + + /// The next `times` requests of `verb` to `key` each take `ms` and end as `ending`. + void takeTime(Verb verb, const String & key, uint64_t ms, size_t times, Ending ending = Ending::Answered) + { + backend->armWith(verb, exactly(key), [clock_ = clock, ms] { clock_->advance(ms); }, times, ending); + } + + /// Counts the pauses of the plane's own operation; the clock still moves as before. + void countPauses(size_t & pauses) + { + requests.setSleepFnForTest([clock_ = clock, &pauses](uint64_t ms) + { + ++pauses; + clock_->advance(ms + 1); + }); + } +}; + +/// A second writer on the plane's store. Inside each of the plane's next `times` requests of `verb` to +/// `key` it replaces the object, so that request meets a moved precondition. +struct Rival +{ + Rival(Plane & plane, Verb verb, const String & key_, size_t times) + : key(key_) + , requests(plane.backend, Fence::open(), ManualClock::nowFnOf(plane.clock), ManualClock::sleepFnOf(plane.clock), + nullptr, kWindowMs) + , op(requests.admit()) + { + requests.setAttemptReservationForTest(kEnvelopeMs); + plane.backend->armWith(verb, [this](const String & k) { return k == key && !inside; }, [this] { move(); }, times); + } + + void move() + { + inside = true; + if (const auto current = op.read(key, Retry::once())) + (void)op.replace(key, current->bytes + "r", current->etag, Retry::once()); + else + (void)op.create(key, "r", Retry::once()); + inside = false; + ++moves; + if (after_move) + after_move(); + } + + String key; + bool inside = false; + size_t moves = 0; + /// Runs inside the plane's request, after the move. + std::function after_move; + CasRequests requests; + CasOperation op; +}; + +/// A mount fence the test trips: by re-arming its generation, or by letting the lease run out. +struct TrippableFence +{ + enum class Trip : uint8_t { Rearm, LeaseExpiry }; + + uint64_t generation = 0; + bool lease_expired = false; + + Fence fence() + { + return Fence{ + [this] { return generation; }, + [this](uint64_t admitted_generation, uint64_t) + { + if (admitted_generation != generation) + return Fence::Admit::LostOrRearmed; + return lease_expired ? Fence::Admit::NoBudget : Fence::Admit::Ok; + }, + [](uint64_t) {}}; + } + + void trip(Trip how) + { + if (how == Trip::Rearm) + ++generation; + else + lease_expired = true; + } +}; + +String tripName(TrippableFence::Trip how) +{ + return how == TrippableFence::Trip::Rearm ? "re-armed generation" : "expired lease"; +} + +CatalogEntry liveEntry(const String & ns, uint64_t incarnation) +{ + return CatalogEntry{.ns = RootNamespace{ns}, .state = NsState::Live, .incarnation = UInt128(incarnation)}; +} + +/// Another server writing the ref catalog. Inside each of the plane's next `times` writes of the catalog +/// it admits a new row, so that write meets a moved precondition. +struct CatalogRival +{ + CatalogRival(Plane & plane, const Layout & layout_, size_t times) + : layout(layout_) + , requests(plane.backend, Fence::open(), ManualClock::nowFnOf(plane.clock), ManualClock::sleepFnOf(plane.clock), + nullptr, kWindowMs) + , op(requests.admit()) + { + requests.setAttemptReservationForTest(kEnvelopeMs); + plane.backend->armWith(Verb::Write, [this](const String & k) { return k == layout.refCatalogKey() && !inside; }, + [this] { move(); }, times); + } + + void move() + { + inside = true; + CasRefCatalog::casAdmitEntry(op, layout, 1, liveEntry(fmt::format("rival{}", moves), 1000 + moves)); + inside = false; + ++moves; + } + + Layout layout; + bool inside = false; + size_t moves = 0; + CasRequests requests; + CasOperation op; +}; + +/// A mounted pool whose request planes read a clock the test moves and reserve what a real disk does. +struct PoolOnManualClock +{ + std::shared_ptr backend = std::make_shared(); + std::shared_ptr clock = std::make_shared(); + PoolPtr store; + + PoolOnManualClock() + { + store = Pool::open(backend, PoolConfig{.pool_prefix = "p", .server_root_id = "test"}); + store->setCasRequestNowFnForTest(ManualClock::nowFnOf(clock)); + store->setCasRetrySleepForTest(ManualClock::sleepFnOf(clock)); + store->mountRequests().setAttemptReservationForTest(kEnvelopeMs); + backend->stampWith(ManualClock::nowFnOf(clock)); + } + + void slowDown(Verb verb, const String & key) + { + backend->armWith(verb, exactly(key), [clock_ = clock] { clock_->advance(kFirstStepMs); }); + } +}; + +/// A pool whose LEASE clock is the test's too, for the bounds that are kept on it. The lease is an +/// hour long, so the request window and not the lease is what ends a wait. +PoolPtr openOnBootClock(const std::shared_ptr & backend, const std::shared_ptr & clock) +{ + PoolConfig config; + config.pool_prefix = "p"; + config.server_root_id = "test"; + config.mount_lease_ttl_ms = std::chrono::hours(1); + config.unsafe_remount_no_delay = true; + config.boot_ms_fn = ManualClock::nowFnOf(clock); + PoolPtr store = Pool::open(backend, config); + store->setCasRetrySleepForTest(ManualClock::sleepFnOf(clock)); + store->mountRequests().setAttemptReservationForTest(kEnvelopeMs); + backend->stampWith(ManualClock::nowFnOf(clock)); + return store; +} + +ManifestEntry blobManifestEntry(const String & path, const String & payload) +{ + ManifestEntry entry; + entry.path = path; + entry.placement = EntryPlacement::Blob; + entry.ref = idOf(payload); + entry.blob_size = payload.size(); + return entry; +} + +ManifestId publishOnePart(const PoolPtr & store, const RootNamespace & ns, const String & ref, const String & payload) +{ + PartWriteInfo info; + info.intended_ref = ns.string() + "/" + ref; + auto build = store->beginPartWrite(info); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, ref, id); + build->putBlob(idOf(payload), BlobSource::fromString(payload)); + build->promote(ns, ref, build->buildId(), id); + return id; +} + +} + +/// --------------------------------------------------------------------------------------------- +/// The request engine: every request binds its own window when it is sent. +/// --------------------------------------------------------------------------------------------- + +TEST(CASSharedDeadline, ReadModifyWriteSendsItsWriteAfterASlowRead) +{ + Plane plane; + plane.seed("k", "v1"); + plane.slowDown(Verb::Read, "k"); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.readModifyWrite( + "k", [](const std::optional &) -> std::optional { return "v2"; }, Retry::standard()); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_TRUE(std::holds_alternative(result)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the conditional write", sentSince(*plane.backend, first_ended_ms, Verb::Write, "k")) + << "result: " << outcomeOf(result); + EXPECT_EQ(plane.bytesOf("k"), "v2"); +} + +/// The same verb when the caller's `decide` takes the time: a decision may read other keys under +/// windows of their own. +TEST(CASSharedDeadline, ReadModifyWriteSendsItsWriteAfterASlowDecide) +{ + Plane plane; + plane.seed("k", "v1"); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional &) -> std::optional + { + plane.clock->advance(kFirstStepMs); + return "v2"; + }, Retry::standard()); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_TRUE(std::holds_alternative(result)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the conditional write", sentSince(*plane.backend, first_ended_ms, Verb::Write, "k")) + << "result: " << outcomeOf(result); + EXPECT_EQ(plane.bytesOf("k"), "v2"); +} + +TEST(CASSharedDeadline, ReadModifyWriteOnPresenceSendsItsWriteAfterASlowHead) +{ + Plane plane; + plane.slowDown(Verb::Head, "k"); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.readModifyWriteOnPresence( + "k", [](const std::optional &) -> std::optional { return "created"; }, Retry::standard()); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_TRUE(std::holds_alternative(result)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the create", sentSince(*plane.backend, first_ended_ms, Verb::Write, "k")) + << "result: " << outcomeOf(result); + EXPECT_EQ(plane.bytesOf("k"), "created"); +} + +TEST(CASSharedDeadline, RemoveCurrentSendsItsRemoveAfterASlowHead) +{ + Plane plane; + plane.seed("k", "v1"); + plane.slowDown(Verb::Head, "k"); + + const uint64_t started_ms = plane.clock->now(); + std::optional removed; + const auto failure = failureOf([&] { removed = plane.op.removeCurrent("k", Retry::standard()); }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_EQ(removed, std::optional(Removal::Removed)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the conditional delete", sentSince(*plane.backend, first_ended_ms, Verb::Remove, "k")) + << "error: " << orNone(failure); +} + +/// Verbs called one after another with `Retry::standard` are bound at their own call, so nothing is shared. +TEST(CASSharedDeadline, EachVerbCalledWithTheStandardPolicyStartsItsOwnWindow) +{ + Plane plane; + plane.seed("k", "v1"); + plane.slowDown(Verb::Head, "k"); + plane.slowDown(Verb::Read, "k"); + + const uint64_t started_ms = plane.clock->now(); + const std::optional meta = plane.op.head("k", Retry::standard()); + const std::optional object = plane.op.read("k", Retry::standard()); + ASSERT_TRUE(meta.has_value()); + ASSERT_TRUE(object.has_value()); + const WriteResult replaced = plane.op.replace("k", "v2", object->etag, Retry::standard()); + + EXPECT_GT(plane.clock->now() - started_ms, kWindowMs); + EXPECT_TRUE(std::holds_alternative(replaced)) << outcomeOf(replaced); +} + +/// A slow page costs the next one nothing. +TEST(CASSharedDeadline, ForEachListedKeyGivesEachPageItsOwnWindow) +{ + Plane plane; + for (int i = 0; i < 5; ++i) + plane.seed("list/" + std::to_string(i), "x"); + plane.backend->armWith(Verb::List, exactly("list/"), [clock = plane.clock] { clock->advance(kFirstStepMs); }, /*times=*/3); + + const uint64_t started_ms = plane.clock->now(); + std::vector keys; + plane.op.forEachListedKey("list/", [&](const ListedKey & listed) + { + keys.push_back(listed.key); + return true; + }, Retry::standard(), /*page_limit=*/2); + + EXPECT_EQ(keys.size(), 5u); + EXPECT_GT(plane.clock->now() - started_ms, 2 * kWindowMs) << "the pages were not slow"; +} + +/// A stream's window bounds only its open; the body is read under no deadline. +TEST(CASSharedDeadline, StreamBodyIsNotMeasuredAgainstTheWindowOfItsOpen) +{ + Plane plane; + const String body(4096, 'b'); + plane.seed("big", body); + plane.backend->setStreamChunkForTest(1024); + plane.slowDown(Verb::Stream, "big"); + + std::unique_ptr stream = plane.op.stream("big", Retry::standard()); + ASSERT_TRUE(stream); + plane.clock->advance(10 * kWindowMs); + String read; + DB::readStringUntilEOF(read, *stream); + EXPECT_EQ(read, body); +} + +/// --------------------------------------------------------------------------------------------- +/// The hot-key lane and the ref catalog loops over it. +/// --------------------------------------------------------------------------------------------- + +/// Nobody else is in the lane: the base read alone uses a window. +TEST(CASSharedDeadline, HotKeyLaneSendsItsWriteAfterASlowBaseRead) +{ + CasHotKeys lane(0); + Plane plane(&lane); + plane.seed("k", "1"); + plane.slowDown(Verb::Read, "k"); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = lane.submit("k", plane.op, Retry::standard(), + [](const std::optional & current) -> std::optional { return current->bytes + ",2"; }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_TRUE(std::holds_alternative(result)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the conditional write", sentSince(*plane.backend, first_ended_ms, Verb::Write, "k")) + << "result: " << outcomeOf(result); + EXPECT_EQ(plane.bytesOf("k"), "1,2"); +} + +/// Another writer holds the key while all but one millisecond of the waiter's window passes. No +/// request of the waiter was slow: the wait is the lane's own. +TEST(CASSharedDeadline, HotKeyLaneServesAWriterThatWaitedBehindAnother) +{ + CasHotKeys lane(0); + Plane plane(&lane); + std::latch parked{1}; + std::latch release{1}; + plane.backend->armWith(Verb::Write, exactly("k"), [&] + { + parked.count_down(); + release.wait(); + }); + + std::optional held; + std::optional waited; + std::thread holder([&] + { + auto op = plane.requests.admit(); + held = lane.submit("k", op, Retry::standard(), [](const std::optional &) -> std::optional { return "1"; }); + }); + parked.wait(); + const uint64_t started_ms = plane.clock->now(); + std::thread waiter([&] + { + auto op = plane.requests.admit(); + waited = lane.submit("k", op, Retry::standard(), [](const std::optional & current) -> std::optional + { + return (current ? current->bytes : String()) + ",2"; + }); + }); + while (lane.queueDepthForTest("k") < 2) + std::this_thread::yield(); + plane.clock->advance(kFirstStepMs); + release.count_down(); + holder.join(); + waiter.join(); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_TRUE(held.has_value()); + ASSERT_TRUE(waited.has_value()); + ASSERT_TRUE(std::holds_alternative(*held)) << "the holder itself failed: " << outcomeOf(*held); + EXPECT_TRUE(std::holds_alternative(*waited)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the waiter's base read", sentSince(*plane.backend, first_ended_ms, Verb::Read, "k")) + << "result: " << outcomeOf(*waited); + EXPECT_EQ(plane.bytesOf("k"), "1,2"); +} + +/// Another server wins the first race late. The update decides again on what the lost write's +/// settling read saw, and its own change lands next to the other server's. +TEST(CASSharedDeadline, CasUpdateDecidesAgainAfterALostRaceThatTookTheWindow) +{ + CasHotKeys lane(0); + Plane plane(&lane); + CasRequests other_server = DB::Cas::tests::openRequestsForTest(plane.backend); + CasOperation other_op = other_server.admit(); + const Layout layout("p"); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + + const String key = layout.refCatalogKey(); + size_t after_the_other_server = 0; + plane.backend->armWith(Verb::Write, exactly(key), [&] + { + plane.clock->advance(kFirstStepMs); + CasRefCatalog::casAdmitEntry(other_op, layout, 1, liveEntry("b", 2)); + after_the_other_server = plane.backend->seenCount(); + }); + + const uint64_t started_ms = plane.clock->now(); + size_t decisions = 0; + const auto failure = failureOf([&] + { + CasRefCatalog::casUpdate(plane.op, layout, [&](const RefCatalog & current) + { + ++decisions; + RefCatalog next = current; + for (CatalogEntry & entry : next.entries) + { + if (entry.ns == RootNamespace{"a"}) + { + entry.state = NsState::Removing; + entry.removal_started_round = 1; + } + } + return next; + }); + }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_FALSE(failure.has_value()) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the read that settles the lost race", + plane.backend->seenSince(after_the_other_server, Verb::Read, key)) + << "decisions made: " << decisions << "; error: " << orNone(failure); + EXPECT_EQ(decisions, 2u); + const RefCatalog durable = CasRefCatalog::read(other_op, layout).catalog; + ASSERT_EQ(durable.entries.size(), 2u); + EXPECT_EQ(durable.entries[0].ns, RootNamespace{"a"}); + EXPECT_EQ(durable.entries[0].state, NsState::Removing) << "the update's own change did not land"; + EXPECT_EQ(durable.entries[1].ns, RootNamespace{"b"}); + EXPECT_EQ(durable.entries[1].state, NsState::Live); +} + +/// The erase landed slowly; the read that resolves it is a request of its own. +TEST(CASSharedDeadline, DeleteCompletedRemovingSendsItsResolutionReadAfterASlowErase) +{ + Plane plane; + const Layout layout("p"); + const CatalogEntry removing{ + .ns = RootNamespace{"a"}, .state = NsState::Removing, .incarnation = UInt128{7}, .removal_started_round = 13}; + plane.seed(layout.refCatalogKey(), encodeRefCatalog(RefCatalog{.entries = {removing}})); + CasFoldSeal ready_parent; + ready_parent.ref_lives.emplace(UInt128{7}, RefLifeFoldState{ + .coverage = RefCoverage{.classification = CoverageClass::Folded, .last_folded_ref_id = RefTxnId{1, 2}}, + .cleanup_evidence = RefCleanupEvidence{.remove_txn_id = RefTxnId{1, 2}}}); + + const String key = layout.refCatalogKey(); + plane.slowDown(Verb::Write, key); + uint64_t started_ms = 0; + std::optional outcome; + const auto failure = failureOf([&] + { + /// The helper reads the catalog first; the erase loop starts at the first authority refresh. + outcome = DB::Cas::tests::deleteCompletedRemovingForTest(plane.op, layout, removing, ready_parent, + [&] { started_ms = started_ms ? started_ms : plane.clock->now(); }).outcome; + }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_EQ(outcome, std::optional(CasRefCatalog::CompletedRemovingDeleteOutcome::Deleted)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the resolution read", sentSince(*plane.backend, first_ended_ms, Verb::Read, key)) + << "error: " << orNone(failure); + /// The erase's own acknowledgment is not the answer; the resolution read is. + EXPECT_EQ(sentSince(*plane.backend, first_ended_ms, Verb::Read, key), 1u); +} + +/// The leader's authority check in the lane passes late; the cancel it authorised is a request of its own. +TEST(CASSharedDeadline, CancelStalledCreatingSendsItsWriteAfterASlowAuthorityCheck) +{ + CasHotKeys lane(0); + Plane plane(&lane); + const Layout layout("p"); + const CatalogEntry creating{ + .ns = RootNamespace{"c"}, .state = NsState::Creating, .incarnation = UInt128{9}, + .creator = CreatorFence{.server_root_id = "gone", .writer_epoch = 1, .fence_generation = 1}}; + const String key = layout.refCatalogKey(); + plane.seed(key, encodeRefCatalog(RefCatalog{.entries = {creating}})); + + const uint64_t started_ms = plane.clock->now(); + bool checked = false; + std::optional outcome; + const auto failure = failureOf([&] + { + outcome = CasRefCatalog::cancelStalledCreating( + plane.op, layout, creating, [](const CreatorFence &) { return true; }, + [&](const Retry &) + { + if (!std::exchange(checked, true)) + plane.clock->advance(kFirstStepMs); + }); + }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + EXPECT_EQ(outcome, std::optional(CasRefCatalog::StalledCreatingCancelOutcome::Cancelled)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the cancelling write", sentSince(*plane.backend, first_ended_ms, Verb::Write, key)) + << "error: " << orNone(failure); + EXPECT_TRUE(CasRefCatalog::read(plane.op, layout).catalog.entries.empty()); +} + +/// --------------------------------------------------------------------------------------------- +/// A mounted pool: the loops of the ref ledger. +/// --------------------------------------------------------------------------------------------- + +/// The first catalog read of `resolveNamespaceLife` is slow; the next request of the loop is a request +/// of its own, so the first insert into a new table succeeds. +TEST(CASSharedDeadline, ResolveNamespaceLifeSendsItsNextRequestAfterASlowCatalogRead) +{ + PoolOnManualClock pool; + const RootNamespace ns{"srv/new_table"}; + const String key = pool.store->layout().refCatalogKey(); + /// The admission reads the catalog once before the loop; the read after it is the loop's first. + pool.backend->armWith(Verb::Read, [key, reads = std::make_shared(0)](const String & read_key) + { + return read_key == key && ++*reads == 2; + }, [clock = pool.clock] { clock->advance(kFirstStepMs); }); + + const uint64_t started_ms = pool.clock->now(); + const auto failure = failureOf([&] { publishOnePart(pool.store, ns, "part", "payload"); }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_EQ(pool.backend->slowedKeys(), std::vector{key}) << "no catalog read ran slowly"; + EXPECT_FALSE(failure.has_value()) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the next catalog read", sentSince(*pool.backend, first_ended_ms, Verb::Read, key)) + << "error: " << orNone(failure); + EXPECT_TRUE(pool.store->resolveRef(ns, "part").has_value()); +} + +/// The first cancel of `cancelIdleOwnCreatingRows` is slow and lands; the second row's cancel is a +/// request of its own. +TEST(CASSharedDeadline, CancelIdleOwnCreatingRowsCancelsTheSecondRowAfterASlowFirstCancel) +{ + PoolOnManualClock pool; + const Layout & layout = pool.store->layout(); + CasRequests other_requests = DB::Cas::tests::openRequestsForTest(pool.backend); + CasOperation other_op = other_requests.admit(); + const CreatorFence ours{ + .server_root_id = "test", .writer_epoch = pool.store->liveWriterEpoch(), .fence_generation = pool.store->fenceGeneration()}; + for (uint64_t i = 1; i <= 2; ++i) + CasRefCatalog::casAdmitEntry(other_op, layout, 1, CatalogEntry{ + .ns = RootNamespace{fmt::format("srv/own_row_{}", i)}, .state = NsState::Creating, .incarnation = UInt128{i}, + .creator = ours}); + ASSERT_EQ(CasRefCatalog::read(other_op, layout).catalog.entries.size(), 2u); + + const String key = layout.refCatalogKey(); + pool.slowDown(Verb::Write, key); + const uint64_t started_ms = pool.clock->now(); + const auto failure = failureOf([&] { pool.store->cancelIdleOwnCreatingRows(); }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_EQ(pool.backend->slowedKeys(), std::vector{key}) << "no cancel ran slowly"; + const size_t rows_left = CasRefCatalog::read(other_op, layout).catalog.entries.size(); + EXPECT_EQ(rows_left, 0u) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the second row's cancel", sentSince(*pool.backend, first_ended_ms, Verb::Write, key)) + << "rows left: " << rows_left << "; error: " << orNone(failure); +} + +/// The first catalog read of `dropNamespaceImpl` is slow; the table is in memory and nothing else takes +/// time. The removal's next requests are requests of their own. +TEST(CASSharedDeadline, DropNamespaceSendsItsNextRequestAfterASlowFirstRead) +{ + PoolOnManualClock pool; + const RootNamespace ns{"srv/tbl"}; + publishOnePart(pool.store, ns, "part", "payload"); + const String key = pool.store->layout().refCatalogKey(); + pool.slowDown(Verb::Read, key); + + const uint64_t started_ms = pool.clock->now(); + const auto failure = failureOf([&] { pool.store->dropNamespace(ns); }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_EQ(pool.backend->slowedKeys(), std::vector{key}) << "no catalog read ran slowly"; + EXPECT_FALSE(failure.has_value()) + << "catalog reads after the slow read: " << sentSince(*pool.backend, first_ended_ms, Verb::Read, key) + << "; error: " << orNone(failure); + EXPECT_FALSE(pool.store->resolveRef(ns, "part").has_value()); +} + +/// The body `HEAD` is slow and finds nothing; the publication that follows is a request of its own and +/// must still be sent. +TEST(CASSharedDeadline, BlobLoopStartsItsPublicationAfterASlowHead) +{ + PoolOnManualClock pool; + const RootNamespace ns{"srv/tbl"}; + const String payload = "body-behind-a-slow-head"; + const String key = pool.store->layout().blobKey(idOf(payload)); + + PartWriteInfo info; + info.intended_ref = ns.string() + "/part"; + auto build = pool.store->beginPartWrite(info); + const ManifestId id = build->stageManifest({blobManifestEntry("data.bin", payload)}); + build->precommitAdd(ns, "part", id); + + pool.slowDown(Verb::Head, key); + const uint64_t started_ms = pool.clock->now(); + const auto failure = failureOf([&] + { + build->putBlob(idOf(payload), BlobSource::fromString(payload)); + build->promote(ns, "part", build->buildId(), id); + }); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_EQ(pool.backend->slowedKeys(), std::vector{key}) << "the body `HEAD` never ran slowly"; + EXPECT_FALSE(failure.has_value()) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the body publication", sentSince(*pool.backend, first_ended_ms, Verb::Publish, key)) + << "error: " << orNone(failure); + EXPECT_EQ(pool.backend->publicationsOf(key), 1u); +} + +/// --------------------------------------------------------------------------------------------- +/// A write whose response is lost: the settling read is a request with its own window. +/// --------------------------------------------------------------------------------------------- + +TEST(CASSharedDeadline, ALostWriteThatLandedIsProvenAfterItsWindow) +{ + Plane plane; + plane.takeTime(Verb::Write, "k", kWindowMs + 1, /*times=*/1, Ending::LostAfterLanding); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.create("k", "landed", Retry::standard()); + const uint64_t write_ended_ms = started_ms + kWindowMs + 1; + + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Write, "k"), 1u); + EXPECT_EQ(sentSince(*plane.backend, write_ended_ms, Verb::Read, "k"), 1u) << "result: " << outcomeOf(result); + const auto * committed = std::get_if(&result); + ASSERT_NE(committed, nullptr) << outcomeOf(result); + EXPECT_TRUE(committed->resolved_by_read); + EXPECT_EQ(plane.bytesOf("k"), "landed"); +} + +/// The settling read proves the write absent; resending the same bytes is still governed by the +/// write's own window, which is spent. +TEST(CASSharedDeadline, ALostWriteThatDidNotLandIsNotSentAgain) +{ + Plane plane; + plane.takeTime(Verb::Write, "k", kWindowMs + 1, /*times=*/1, Ending::LostBeforeLanding); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.create("k", "lost", Retry::standard()); + const uint64_t write_ended_ms = started_ms + kWindowMs + 1; + + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Write, "k"), 1u); + EXPECT_EQ(sentSince(*plane.backend, write_ended_ms, Verb::Read, "k"), 1u) << "result: " << outcomeOf(result); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, GaveUp::Source::Policy); + EXPECT_TRUE(gave_up->sent_any); + EXPECT_TRUE(std::holds_alternative(gave_up->last_seen)); + EXPECT_EQ(plane.bytesOf("k"), ""); +} + +/// The settling read fails until its own window ends, and the give-up names the bound of that read: +/// the policy's window, or an explicit lease that ends before it. +TEST(CASSharedDeadline, AFailingSettlementReportsItsOwnStop) +{ + const auto settle = [](std::optional lease_after_ms, GaveUp::Source expected) + { + SCOPED_TRACE(lease_after_ms ? "with an explicit lease" : "under the window"); + Plane plane; + const uint64_t started_ms = plane.clock->now(); + const Retry policy = lease_after_ms ? Retry::untilLeaseSafe(started_ms + *lease_after_ms, 0) : Retry::standard(); + plane.takeTime(Verb::Write, "k", kFirstStepMs, /*times=*/1, Ending::LostAfterLanding); + plane.takeTime(Verb::Read, "k", 1'000, /*times=*/1'000, Ending::LostBeforeLanding); + + const WriteResult result = plane.op.create("k", "landed", policy); + const uint64_t write_ended_ms = started_ms + kFirstStepMs; + const uint64_t read_end_ms = lease_after_ms ? started_ms + *lease_after_ms : write_ended_ms + kWindowMs; + + EXPECT_GT(sentSince(*plane.backend, write_ended_ms, Verb::Read, "k"), 1u) << outcomeOf(result); + EXPECT_GT(plane.clock->now(), read_end_ms - kEnvelopeMs - kMaxBackoffMs); + EXPECT_LE(plane.clock->now(), read_end_ms); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_EQ(gave_up->deadline_source, expected); + EXPECT_EQ(gave_up->attempts_sent, 1u); + }; + settle(std::nullopt, GaveUp::Source::Policy); + /// The write is bound by the window, the settling read by the lease. + settle(kWindowMs + kWindowMs / 2, GaveUp::Source::Lease); +} + +/// A write that meets nothing but transport failures ends at its own window, measured from when it +/// was sent rather than from when its operation started. +TEST(CASSharedDeadline, ATransportStormEndsInsideTheRequestsOwnWindow) +{ + Plane plane; + plane.takeTime(Verb::Write, "k", 1'000, /*times=*/1'000, Ending::LostBeforeLanding); + + const uint64_t started_ms = plane.clock->now(); + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional &) -> std::optional + { + plane.clock->advance(kWindowMs + 1); + return "v"; + }, Retry::standard()); + const uint64_t write_started_ms = started_ms + kWindowMs + 1; + + EXPECT_GT(sentSince(*plane.backend, write_started_ms, Verb::Write, "k"), 1u) << outcomeOf(result); + /// Every attempt, the resends included, starts only with room in the write's own window for itself and its + /// settling read. + for (const TimeTakingBackend::Seen & request : plane.backend->seen()) + if (request.verb == Verb::Write && request.key == "k" && request.at_ms >= write_started_ms) + EXPECT_LE(request.at_ms + 2 * kEnvelopeMs, write_started_ms + kWindowMs) + << "an attempt started " << request.at_ms - write_started_ms << " ms into the write's window"; + /// The write stops only when the next attempt, its settling read and the pause before it no longer fit. + EXPECT_GT(plane.clock->now() - write_started_ms, kWindowMs - 2 * kEnvelopeMs - kMaxBackoffMs); + EXPECT_LE(plane.clock->now() - write_started_ms, kWindowMs + kEnvelopeMs + kMaxBackoffMs); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, GaveUp::Why::Deadline); + EXPECT_TRUE(gave_up->sent_any); +} + +/// --------------------------------------------------------------------------------------------- +/// Loops that decide again end on a count of decisions. +/// --------------------------------------------------------------------------------------------- + +TEST(CASSharedDeadline, ReadModifyWriteSucceedsOnTheHundredthDecision) +{ + Plane plane; + plane.seed("k", "v"); + Rival rival(plane, Verb::Write, "k", kCasMaxDecisions - 1); + size_t pauses = 0; + plane.countPauses(pauses); + + size_t decisions = 0; + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional & current) -> std::optional + { + ++decisions; + return current->bytes + "x"; + }, Retry::standard()); + + ASSERT_TRUE(std::holds_alternative(result)) << outcomeOf(result); + EXPECT_EQ(decisions, kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; + EXPECT_EQ(rival.moves, kCasMaxDecisions - 1); + EXPECT_EQ(std::get(result).attempts_sent, kCasMaxDecisions); +} + +TEST(CASSharedDeadline, ReadModifyWriteEndsAfterAHundredDecisions) +{ + Plane plane; + plane.seed("k", "v"); + Rival rival(plane, Verb::Write, "k", 10 * kCasMaxDecisions); + size_t pauses = 0; + plane.countPauses(pauses); + const uint64_t started_ms = plane.clock->now(); + + size_t decisions = 0; + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional & current) -> std::optional + { + ++decisions; + return current->bytes + "x"; + }, Retry::standard()); + + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, GaveUp::Why::Attempts); + EXPECT_EQ(gave_up->attempts_sent, kCasMaxDecisions); + EXPECT_EQ(decisions, kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; + /// Every loss but the last is followed by a read, after a pause from the second, and only the last refusal, which + /// no decision follows, is settled: the plane's own reads are the first one, one per later decision and the last + /// settlement. + EXPECT_EQ(rival.moves, kCasMaxDecisions); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Read, "k") - rival.moves, 1 + (kCasMaxDecisions - 1) + 1); + const auto * seen = std::get_if(&gave_up->last_seen); + ASSERT_NE(seen, nullptr); + EXPECT_EQ(seen->bytes, plane.bytesOf("k")); +} + +TEST(CASSharedDeadline, RemoveCurrentSucceedsOnTheHundredthDecision) +{ + Plane plane; + plane.seed("k", "v"); + Rival rival(plane, Verb::Remove, "k", kCasMaxDecisions - 1); + size_t pauses = 0; + plane.countPauses(pauses); + const uint64_t started_ms = plane.clock->now(); + + std::optional removed; + const auto failure = failureOf([&] { removed = plane.op.removeCurrent("k", Retry::standard()); }); + + EXPECT_EQ(removed, std::optional(Removal::Removed)) << "error: " << orNone(failure); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Head, "k"), kCasMaxDecisions); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Remove, "k"), kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; +} + +TEST(CASSharedDeadline, RemoveCurrentEndsAfterAHundredDecisions) +{ + Plane plane; + plane.seed("k", "v"); + Rival rival(plane, Verb::Remove, "k", 10 * kCasMaxDecisions); + size_t pauses = 0; + plane.countPauses(pauses); + const uint64_t started_ms = plane.clock->now(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "CAS remove of 'k': did not converge after 100 decisions", + [&] { (void)plane.op.removeCurrent("k", Retry::standard()); }); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Head, "k"), kCasMaxDecisions); + EXPECT_EQ(sentSince(*plane.backend, started_ms, Verb::Remove, "k"), kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; + EXPECT_NE(plane.bytesOf("k"), ""); +} + +/// The fence trips while the read that settles the hundredth lost race is in flight. That read still +/// answers, and the call reports the trip, as the pause before a next decision would have, not the count. +TEST(CASSharedDeadline, ReadModifyWriteReportsAFenceTripDuringItsLastSettlementNotTheCount) +{ + const auto run = [](TrippableFence::Trip how, GaveUp::Why why, GaveUp::Source source) + { + SCOPED_TRACE(tripName(how)); + TrippableFence mount; + Plane plane(nullptr, mount.fence()); + plane.seed("k", "v"); + Rival rival(plane, Verb::Write, "k", 10 * kCasMaxDecisions); + bool tripped = false; + plane.backend->armWith(Verb::Read, + [&](const String & key) { return key == "k" && !rival.inside && rival.moves == kCasMaxDecisions; }, + [&] + { + mount.trip(how); + tripped = true; + }); + const size_t journal_from = plane.backend->seenCount(); + + size_t decisions = 0; + const WriteResult result = plane.op.readModifyWrite("k", [&](const std::optional & current) -> std::optional + { + ++decisions; + return current->bytes + "x"; + }, Retry::standard()); + + ASSERT_TRUE(tripped) << "the hundredth settling read was never sent; " << outcomeOf(result); + const auto * gave_up = std::get_if(&result); + ASSERT_NE(gave_up, nullptr) << outcomeOf(result); + EXPECT_EQ(gave_up->why, why) << outcomeOf(result); + EXPECT_EQ(gave_up->deadline_source, source) << outcomeOf(result); + EXPECT_EQ(gave_up->attempts_sent, kCasMaxDecisions); + EXPECT_EQ(decisions, kCasMaxDecisions); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, "k") - rival.moves, kCasMaxDecisions); + }; + run(TrippableFence::Trip::Rearm, GaveUp::Why::FenceLost, GaveUp::Source::Policy); + run(TrippableFence::Trip::LeaseExpiry, GaveUp::Why::Deadline, GaveUp::Source::Lease); +} + +/// The fence trips while the hundredth conditional delete is in flight and meets a replaced object. +TEST(CASSharedDeadline, RemoveCurrentReportsAFenceTripDuringItsLastDeleteNotTheCount) +{ + const auto run = [](TrippableFence::Trip how, const String & expected) + { + SCOPED_TRACE(tripName(how)); + TrippableFence mount; + Plane plane(nullptr, mount.fence()); + plane.seed("k", "v"); + Rival rival(plane, Verb::Remove, "k", 10 * kCasMaxDecisions); + rival.after_move = [&] + { + if (rival.moves == kCasMaxDecisions) + mount.trip(how); + }; + const size_t journal_from = plane.backend->seenCount(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, expected, + [&] { (void)plane.op.removeCurrent("k", Retry::standard()); }); + EXPECT_EQ(rival.moves, kCasMaxDecisions); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Head, "k"), kCasMaxDecisions); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Remove, "k"), kCasMaxDecisions); + }; + run(TrippableFence::Trip::Rearm, "mount fence tripped"); + run(TrippableFence::Trip::LeaseExpiry, "no lease budget"); +} + +/// The fence trips while the hundredth submission's write is in flight, and that write is refused: the call reports +/// the lost fence, not the count. The first submission writes twice, on the lane's cached catalog and then on its +/// resolve read, so the hundredth submission sends write `kCasMaxDecisions + 1`. +TEST(CASSharedDeadline, CasUpdateReportsAFenceTripDuringItsLastWriteNotTheCount) +{ + TrippableFence mount; + CasHotKeys lane(16ULL << 20); + Plane plane(&lane, mount.fence()); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + CatalogRival rival(plane, layout, 10 * kCasMaxDecisions); + bool tripped = false; + /// The rival's own read, inside the move that refuses write `kCasMaxDecisions + 1`. + plane.backend->armWith(Verb::Read, + [&](const String & k) { return k == key && rival.inside && rival.moves == kCasMaxDecisions; }, + [&] + { + mount.trip(TrippableFence::Trip::Rearm); + tripped = true; + }); + const size_t journal_from = plane.backend->seenCount(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "mount fence tripped", [&] + { + CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) { return current; }); + }); + EXPECT_TRUE(tripped) << "the hundredth submission's write was never sent"; + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions + 1); +} + +/// The fence trips while the read that settles the hundredth submission's refused write is in flight: no +/// submission follows it, so that write is settled, and the call reports the lost fence, not the count. +TEST(CASSharedDeadline, CasUpdateReportsAFenceTripDuringItsLastSettlementNotTheCount) +{ + TrippableFence mount; + CasHotKeys lane(16ULL << 20); + Plane plane(&lane, mount.fence()); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + CatalogRival rival(plane, layout, 10 * kCasMaxDecisions); + bool tripped = false; + /// The plane's own read after write `kCasMaxDecisions + 1`, the hundredth submission's. + plane.backend->armWith(Verb::Read, + [&](const String & k) { return k == key && !rival.inside && rival.moves == kCasMaxDecisions + 1; }, + [&] + { + mount.trip(TrippableFence::Trip::Rearm); + tripped = true; + }); + const size_t journal_from = plane.backend->seenCount(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, "mount fence tripped", [&] + { + CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) { return current; }); + }); + EXPECT_TRUE(tripped) << "the hundredth submission's settling read was never sent"; + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions + 1); +} + +/// `casUpdate` counts submissions to the hot-key lane: one submission can run its `decide` twice on a +/// cached catalog, so the tests count the plane's writes of the catalog, not the calls of `mutate`. The +/// first submission starts from the cached catalog, loses, and writes again at once on the resolve read, +/// so `kCasMaxDecisions` submissions send one write more than that. +TEST(CASSharedDeadline, CasUpdateSucceedsOnTheHundredthSubmission) +{ + CasHotKeys lane(16ULL << 20); + Plane plane(&lane); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + CatalogRival rival(plane, layout, kCasMaxDecisions); + size_t pauses = 0; + plane.countPauses(pauses); + const size_t journal_from = plane.backend->seenCount(); + + const auto failure = failureOf([&] + { + CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) + { + RefCatalog next = current; + next.entries.front().state = NsState::Removing; + next.entries.front().removal_started_round = 1; + return next; + }); + }); + + EXPECT_FALSE(failure.has_value()) << orNone(failure); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions + 1); + EXPECT_EQ(rival.moves, kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; + const RefCatalog durable = CasRefCatalog::read(plane.op, layout).catalog; + EXPECT_EQ(durable.entries.size(), 1 + rival.moves); + EXPECT_EQ(durable.entries.front().state, NsState::Removing); +} + +/// Every write meets a moved precondition. The hundredth refused submission ends the call without a +/// pause after it, and the error names a clean conflict. The first submission writes twice. +TEST(CASSharedDeadline, CasUpdateEndsAfterAHundredSubmissionsOnACleanConflict) +{ + CasHotKeys lane(16ULL << 20); + Plane plane(&lane); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + CasRefCatalog::casAdmitEntry(plane.op, layout, 1, liveEntry("a", 1)); + CatalogRival rival(plane, layout, 10 * kCasMaxDecisions); + size_t pauses = 0; + plane.countPauses(pauses); + const size_t journal_from = plane.backend->seenCount(); + + /// The closing parenthesis is the end of the reason: nothing names an unresolved write. + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + fmt::format("CAS ref catalog '{}' update: did not converge after 100 submissions)", key), [&] + { + CasRefCatalog::casUpdate(plane.op, layout, [](const RefCatalog & current) { return current; }); + }); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key) - rival.moves, kCasMaxDecisions + 1); + EXPECT_EQ(rival.moves, kCasMaxDecisions + 1); + EXPECT_EQ(pauses, kCasMaxDecisions - 2) << "the first lost race is retried at once"; +} + +/// Namespace-create step 1 decides again after a write whose fate is unknown. When the hundredth +/// write is that one, the error says the write may have landed. +TEST(CASSharedDeadline, CasUpdateEndsAfterAHundredSubmissionsAfterAnUnresolvedLastWrite) +{ + CasHotKeys lane(16ULL << 20); + Plane plane(&lane); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + plane.takeTime(Verb::Write, key, 0, 10 * kCasMaxDecisions, Ending::LostBeforeLanding); + size_t pauses = 0; + plane.countPauses(pauses); + const size_t journal_from = plane.backend->seenCount(); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + fmt::format("CAS ref catalog '{0}' update: a sent write's outcome is unresolved; the call ended with: Code: 210. DB::Exception: " + "CAS write could not be committed (CAS ref catalog '{0}' update: did not converge after 100 submissions)", key), + [&] + { + (void)CasRefCatalog::createNamespace(plane.op, layout, 1, RootNamespace{"a"}, + CreatorFence{.server_root_id = "srv", .writer_epoch = 1, .fence_generation = 1}); + }); + EXPECT_EQ(plane.backend->seenSince(journal_from, Verb::Write, key), kCasMaxDecisions); + EXPECT_EQ(pauses, kCasMaxDecisions - 1); + EXPECT_TRUE(CasRefCatalog::read(plane.op, layout).catalog.entries.empty()); +} + +/// The lease expires while the read that settles the hundredth unresolved write is in flight. The error +/// names the lease and still says the last write may have landed. +TEST(CASSharedDeadline, CasUpdateReportsTheLeaseAndAnUnresolvedLastWriteAtTheHundredthSubmission) +{ + TrippableFence mount; + CasHotKeys lane(16ULL << 20); + Plane plane(&lane, mount.fence()); + const Layout layout("p"); + const String key = layout.refCatalogKey(); + CasRefCatalog::initializeEmptyForNewPool(plane.op, layout); + size_t writes = 0; + plane.backend->armWith(Verb::Write, exactly(key), [&] { ++writes; }, 10 * kCasMaxDecisions, Ending::LostBeforeLanding); + bool tripped = false; + plane.backend->armWith(Verb::Read, [&](const String & k) { return k == key && writes == kCasMaxDecisions; }, [&] + { + mount.trip(TrippableFence::Trip::LeaseExpiry); + tripped = true; + }); + + DB::Cas::tests::expectThrowsCodeWithMessage(DB::ErrorCodes::NETWORK_ERROR, + fmt::format("CAS ref catalog '{0}' update: a sent write's outcome is unresolved; the call ended with: Code: 210. DB::Exception: " + "CAS write could not be committed (CAS ref catalog '{0}' update: gave up at the lease deadline after 100 submissions)", key), + [&] + { + (void)CasRefCatalog::createNamespace(plane.op, layout, 1, RootNamespace{"a"}, + CreatorFence{.server_root_id = "srv", .writer_epoch = 1, .fence_generation = 1}); + }); + EXPECT_TRUE(tripped) << "the hundredth settling read was never sent"; + EXPECT_EQ(writes, kCasMaxDecisions); +} + +/// The slot read of `Pool::confirmPinnedRef` binds its own request window: a ledger check that took all but +/// one millisecond of the poll's window does not shorten it. +TEST(CASSharedDeadline, ConfirmPinnedRefSendsItsSlotReadAfterASlowLedgerCheck) +{ + auto backend = std::make_shared(); + auto clock = std::make_shared(); + const PoolPtr store = openOnBootClock(backend, clock); + const RootNamespace ns{"srv/source"}; + const ManifestId id = publishOnePart(store, ns, "x", "payload"); + const auto pinned = store->resolveRefPinned(ns, "x"); + ASSERT_TRUE(pinned.has_value()); + const String slot_key = store->layout().mountKey("test"); + + const uint64_t started_ms = clock->now(); + bool waited = false; + store->setConfirmAfterLedgerSnapshotHookForTest([&] + { + if (!std::exchange(waited, true)) + clock->advance(kFirstStepMs); + }); + std::optional answer; + const auto failure = failureOf([&] { answer = store->confirmPinnedRef(pinned->table, ns, "x", id.ref); }); + store->setConfirmAfterLedgerSnapshotHookForTest(nullptr); + const uint64_t first_ended_ms = started_ms + kFirstStepMs; + + ASSERT_TRUE(waited) << "the confirm never reached its ledger check"; + EXPECT_EQ(answer, std::optional(ConfirmAnswer::Yes)) + << sharedWindow(kWindowMs, started_ms, first_ended_ms, "the mount slot read", sentSince(*backend, first_ended_ms, Verb::Read, slot_key)) + << "error: " << orNone(failure); +} + +/// A recovery walk whose reads were slow and whose last read then failed for one request window is +/// retried: no elapsed-time limit ends recovery, only the cap on the number of walks. +TEST(CASSharedDeadline, RecoveryRetriesAWalkThatFailedLateInItsBudget) +{ + auto backend = std::make_shared(); + auto clock = std::make_shared(); + const RootNamespace ns{"srv/tbl"}; + { + const PoolPtr first = openOnBootClock(backend, clock); + publishOnePart(first, ns, "part_a", "payload-a"); + publishOnePart(first, ns, "part_b", "payload-b"); + } + const PoolPtr store = openOnBootClock(backend, clock); + ASSERT_FALSE(store->refTableRecoveredForTest(ns)); + const String catalog_key = store->layout().refCatalogKey(); + + const uint64_t started_ms = clock->now(); + constexpr uint64_t slow_read_ms = kWindowMs + 20'000; + /// Later reads fail for one request window, then the store answers again. + const uint64_t fault_ends_ms = started_ms + slow_read_ms + kWindowMs; + backend->armWith(Verb::Read, [catalog_key](const String & key) { return key != catalog_key; }, + [clock] { clock->advance(slow_read_ms); }); + backend->armWith(Verb::Read, + [catalog_key, clock, fault_ends_ms](const String & key) { return key != catalog_key && clock->now() < fault_ends_ms; }, + [] {}, /*times=*/std::numeric_limits::max(), Ending::LostBeforeLanding); + + const uint64_t retries_before = ProfileEvents::global_counters[ProfileEvents::CASRefRecoveryRetries]; + size_t refs = 0; + uint64_t walk_ended_ms = 0; + const auto failure = failureOf([&] + { + try + { + refs = store->listRefs(ns).size(); + } + catch (...) + { + walk_ended_ms = clock->now(); + throw; + } + }); + const uint64_t retries = ProfileEvents::global_counters[ProfileEvents::CASRefRecoveryRetries] - retries_before; + + ASSERT_GE(backend->slowedKeys().size(), 2u) << "the walk made fewer than two reads, so none failed after the slow one"; + const uint64_t used_ms = (walk_ended_ms ? walk_ended_ms : clock->now()) - started_ms; + EXPECT_FALSE(failure.has_value()) + << fmt::format("\n first walk took {} ms; {} retry(ies)\n ", used_ms, retries) + << "error: " << orNone(failure); + EXPECT_EQ(refs, 2u); + EXPECT_GE(retries, 1u) << "a second walk was started"; +} diff --git a/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp b/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp index 8117cb7e1db96..09bcba8b31d14 100644 --- a/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp +++ b/src/Disks/tests/gtest_cas_sweep_deletion_premise.cpp @@ -4,12 +4,26 @@ #include #include #include +#include "cas_killable_query.h" #include "cas_sweep_test_support.h" #include "cas_test_helpers.h" +#include +#include +#include #include +#include +#include +#include #include +namespace DB::ErrorCodes +{ + extern const int NETWORK_ERROR; + extern const int QUERY_WAS_CANCELLED; + extern const int READONLY; +} + using namespace DB::Cas; using namespace DB::Cas::tests; @@ -144,6 +158,63 @@ TEST(CASSweepDeletionPremise, AConsumedEpochSealWithACleanTailDeletes) EXPECT_TRUE(warnings.empty()) << "nothing was retained, so nothing is warned about"; } +/// The round commits its orphan cursor before the namespace janitor runs, so the bodies that commit nominated are +/// deleted even when the janitor then ends a killed round with its failure; a live round treats the same janitor +/// failure as a leak and succeeds. +TEST(CASSweepDeletionPremise, AKilledJanitorAfterTheCommitLeavesNoNominatedBody) +{ + for (const bool killed : {false, true}) + { + SCOPED_TRACE(killed ? "killed query" : "live query"); + OrphanFixture f(/*gc_fold_max_defer_rounds*/0); + const Layout & layout = f.store->layout(); + seedCursorAt(*f.backend, layout, f.ns, RefTxnId{kBuildEpoch + 1, 1}); + const String dead_log = layout.refLogKey( + NamespaceLifeId::fromCatalogEntry(RootNamespace{"dead/janitor-kill"}, UInt128{0xDB}), RefTxnId{1, 1}); + { + OperationForTest op(*f.backend); + ASSERT_TRUE(std::holds_alternative((*op).create(dead_log, "dead residue", Retry::once()))); + } + + int code = 0; + String message; + uint64_t nominations_deleted = 0; + std::atomic fired{false}; + onKillableQueryThread([&](CasKillableQuery & query) + { + f.backend->onBeforeBulkRemove([&] + { + if (fired.exchange(true)) + return; + if (killed) + query.kill(); + throw DB::Exception(DB::ErrorCodes::READONLY, "injected janitor batch delete refusal"); + }); + Gc gc(f.store, hexToU128("00000000000000000000000000000001")); + gc.setPhaseSink([&](const GcPhaseRecord & phase) + { + if (phase.phase == "orphan_sweep") + nominations_deleted = phase.metrics.at("deleted"); + }); + try + { + ASSERT_TRUE(runRegularRoundReclaiming(gc).acquired_lease); + } + catch (const DB::Exception & e) + { + code = e.code(); + message = e.message(); + } + f.backend->onBeforeBulkRemove({}); + }); + + ASSERT_TRUE(fired.load()) << "the round sent no janitor batch delete"; + EXPECT_EQ(code, killed ? DB::ErrorCodes::READONLY : 0) << message; + EXPECT_EQ(nominations_deleted, 1u); + EXPECT_FALSE(f.orphanExists()) << "the nominated body outlived the commit that nominated it"; + } +} + /// Uncertainty rule, hold arm. The cursor HAS consumed epoch 1's seal, so rule (1) alone would let the /// body go -- but the namespace is held, which means the fold could not account for everything at or /// above the held position. A held namespace retains everything under it. @@ -761,3 +832,168 @@ TEST(CASSweepDeletionPremise, NamespaceWorkBudgetCapsDistinctViewsPerPage) ++surviving; EXPECT_EQ(surviving, 1u) << "exactly one candidate remains -- the one whose namespace had no budget left"; } + +namespace +{ + +/// Runs `on_read` once, before the first read of a key containing `read_substring`, and `on_remove` once, before +/// the remove of `remove_key`. A hook that throws replaces that request's answer. +class SweepFaultBackend final : public InMemoryBackend +{ +public: + String read_substring; + std::function on_read; + String remove_key; + std::function on_remove; + + std::optional read(const String & key, TransportAccess & access) override + { + if (on_read && key.find(read_substring) != String::npos) + std::exchange(on_read, {})(); + return InMemoryBackend::read(key, access); + } + + RawRemoval remove(const String & key, const String & expected_value, TransportAccess & access) override + { + if (on_remove && key == remove_key) + std::exchange(on_remove, {})(); + return InMemoryBackend::remove(key, expected_value, access); + } +}; + +/// `OrphanFixture` with three eligible, unowned manifests in build 5 and a cursor past their epoch's seal, so a live +/// sweep deletes all three. +struct KilledSweepFixture +{ + std::shared_ptr backend = std::make_shared(); + PoolPtr store; + RootNamespace ns{"00/aa@cas@"}; + std::vector orphan_keys; + + KilledSweepFixture() + { + store = openPoolForTest(backend); + casAdmitRecoverableEntry(*backend, store->layout(), ns); + for (const uint64_t ordinal : {0xABu, 0xACu, 0xADu}) + { + const ManifestRef orphan = ref(5, ordinal); + writeManifestRaw(*backend, store->layout(), ns, orphan, {blobEntryFor("a", DB::UInt128(ordinal))}); + orphan_keys.push_back(store->layout().manifestKey(ManifestId{ns, orphan})); + } + std::sort(orphan_keys.begin(), orphan_keys.end()); + setWatermarkMinActive(*backend, store->layout(), kServerRoot, kBuildEpoch, /*min_active_build_sequence*/6); + seedCursorAt(*backend, store->layout(), ns, RefTxnId{kBuildEpoch + 1, 1}); + } + + bool exists(const String & key) const + { + OperationForTest op(*backend); + return (*op).head(key, Retry::once()).has_value(); + } +}; + +struct SweepRun +{ + int code = 0; + uint64_t deleted = 0; + std::vector warnings; +}; + +/// The decommission drain's call, on a thread of a query; `arm` runs on that thread first. +SweepRun sweepOnQueryThread(KilledSweepFixture & f, const std::function & arm) +{ + SweepRun out; + std::thread caller([&] + { + std::optional thread_status; + thread_status.emplace(); + CasKillableQuery query(getContext().context); + arm(query); + try + { + out.deleted = sweepNamespace(*f.store, f.ns, buildPrefix(5), &out.warnings); + } + catch (const DB::Exception & e) + { + out.code = e.code(); + } + }); + caller.join(); + return out; +} + +} + +/// A killed query's sweep stops at the next key with the query's own error, also inside one build prefix: no key of +/// the prefix is deleted after the kill. +TEST(CASSweepDeletionPremise, KilledQueryEndsTheSweepAtTheNextKey) +{ + KilledSweepFixture f; + const SweepRun run = sweepOnQueryThread(f, [](CasKillableQuery & query) { query.kill(); }); + + EXPECT_EQ(run.code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + for (const String & key : f.orphan_keys) + EXPECT_TRUE(f.exists(key)) << key; + + const SweepRun live = sweepOnQueryThread(f, [](CasKillableQuery &) {}); + EXPECT_EQ(live.code, 0); + EXPECT_EQ(live.deleted, f.orphan_keys.size()) << "positive control: a live sweep deletes every key"; +} + +/// A query killed while the first key's delete is in flight: that delete lands, and the sweep ends at the next key +/// with the query's error, so the other keys of the prefix stay. +TEST(CASSweepDeletionPremise, KilledQueryEndsTheSweepAtTheKeyAfterTheKill) +{ + KilledSweepFixture f; + const SweepRun run = sweepOnQueryThread(f, [&](CasKillableQuery & query) + { + f.backend->remove_key = f.orphan_keys.front(); + f.backend->on_remove = [&query] { query.kill(); }; + }); + + EXPECT_EQ(run.code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_FALSE(f.exists(f.orphan_keys.front())) << "the delete in flight at the kill"; + for (size_t i = 1; i < f.orphan_keys.size(); ++i) + EXPECT_TRUE(f.exists(f.orphan_keys[i])) << "a key after the kill was deleted: " << f.orphan_keys[i]; +} + +/// A delete of the last key that fails after the kill ends the sweep with that failure, not with a warning. +TEST(CASSweepDeletionPremise, KilledQuerysFailedDeleteOfTheLastKeyPropagates) +{ + KilledSweepFixture f; + const SweepRun run = sweepOnQueryThread(f, [&](CasKillableQuery & query) + { + f.backend->remove_key = f.orphan_keys.back(); + f.backend->on_remove = [&query] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected delete failure"); + }; + }); + + EXPECT_EQ(run.code, DB::ErrorCodes::NETWORK_ERROR); + EXPECT_TRUE(f.exists(f.orphan_keys.back())); + for (size_t i = 0; i + 1 < f.orphan_keys.size(); ++i) + EXPECT_FALSE(f.exists(f.orphan_keys[i])) << "the keys before the kill were deleted: " << f.orphan_keys[i]; + EXPECT_TRUE(run.warnings.empty()) << fmt::format("{}", fmt::join(run.warnings, "; ")); +} + +/// A protection-view read that fails after the kill ends the sweep with that failure, not with a skipped namespace. +TEST(CASSweepDeletionPremise, KilledQuerysFailedProtectionReadPropagates) +{ + KilledSweepFixture f; + const SweepRun run = sweepOnQueryThread(f, [&](CasKillableQuery & query) + { + f.backend->read_substring = "_ckpt"; + f.backend->on_read = [&query] + { + query.kill(); + throw DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "injected checkpoint read failure"); + }; + }); + + EXPECT_EQ(run.code, DB::ErrorCodes::NETWORK_ERROR); + for (const String & key : f.orphan_keys) + EXPECT_TRUE(f.exists(key)) << key; + EXPECT_TRUE(run.warnings.empty()) << fmt::format("{}", fmt::join(run.warnings, "; ")); +} diff --git a/src/Disks/tests/gtest_cas_upload_detached.cpp b/src/Disks/tests/gtest_cas_upload_detached.cpp index 83d67b17f282f..976b67b7b9c02 100644 --- a/src/Disks/tests/gtest_cas_upload_detached.cpp +++ b/src/Disks/tests/gtest_cas_upload_detached.cpp @@ -444,7 +444,7 @@ TEST(CASUploadDetached, MergeFailureLeavesBuildUntouched) const auto pre_merge_snapshot = build->depsSnapshotForTest(); ASSERT_EQ(pre_merge_snapshot.size(), 1u); /// only the pre-existing dep; the detached uploads folded nothing - build->setMergeHookForTest([](size_t applied_so_far) + build->setAdoptionHookForTest([](size_t applied_so_far) { if (applied_so_far == 1) throw std::bad_alloc(); diff --git a/src/Disks/tests/gtest_cas_upload_fanout.cpp b/src/Disks/tests/gtest_cas_upload_fanout.cpp index cdc8e1393d872..958364b4639b8 100644 --- a/src/Disks/tests/gtest_cas_upload_fanout.cpp +++ b/src/Disks/tests/gtest_cas_upload_fanout.cpp @@ -12,10 +12,14 @@ #include #include #include +#include #include #include #include +#include #include +#include +#include #include #include @@ -46,9 +50,17 @@ using DB::Cas::tests::OperationForTest; namespace DB::ErrorCodes { +extern const int CANNOT_SCHEDULE_TASK; extern const int LOGICAL_ERROR; extern const int INCORRECT_DATA; +extern const int NETWORK_ERROR; extern const int NOT_IMPLEMENTED; +extern const int QUERY_WAS_CANCELLED; +} + +namespace DB::FailPoints +{ +extern const char thread_group_switcher_post_attach_failure[]; } namespace CurrentMetrics @@ -1010,6 +1022,164 @@ TEST(CASUploadFanout, TrackingSeamThrowStillDrains) EXPECT_EQ(build->depsSnapshotForTest().size(), 0u) << "merge-nothing on a tracking-seam throw"; } +namespace +{ + +/// Counts blob publications and the blob `HEAD`s per key. +class PublicationCountingBackend final : public InMemoryBackend +{ +public: + std::optional head(const String & key, TransportAccess & access) override + { + { + std::lock_guard lock(mutex); + ++heads[key]; + } + return InMemoryBackend::head(key, access); + } + + void publish(const BlobPublishRequest & request, TransportAccess & access) override + { + ++publications; + InMemoryBackend::publish(request, access); + } + + int headsOf(const String & key) + { + std::lock_guard lock(mutex); + return heads[key]; + } + + std::atomic publications{0}; + +private: + std::mutex mutex; + std::map heads; +}; + +} + +/// A query killed while one upload task is parked still dispatches the sibling and lets it send its `HEAD`: a +/// dispatch and a first attempt are not safe points. No worker starts a publication after the kill, the caller +/// returns only after the parked task finished, and the build records no dependency. +TEST(CASUploadFanout, StoppedWorkerStartsNoPublicationAndParentJoinsSibling) +{ + auto b = std::make_shared(); + auto s = openPool(b); + auto build = precommitBuildFor(s, RootNamespace{"srv1/nsStoppedFanout"}, "part"); + const auto deps_before = stableDeps(*build); + + const String one = "stopped-fanout-one"; + const String two = "stopped-fanout-two"; + /// Dispatch runs in ascending-ref order. + const String parked = (idOf(one) < idOf(two)) ? one : two; + const String later = (parked == one) ? two : one; + + constexpr auto watchdog = std::chrono::seconds(30); + BoundedEvent parked_running; + BoundedEvent killed; + BoundedEvent release_parked; + BoundedEvent parent_returned; + std::mutex dispatched_mutex; + std::vector dispatched; + std::atomic query_ptr{nullptr}; + + BlobUploadFanoutHooksForTest hooks; + hooks.in_task = [&](const BlobRef & ref) + { + { + std::lock_guard lock(dispatched_mutex); + dispatched.push_back(ref); + } + if (ref == idOf(parked)) + { + parked_running.fire(); + EXPECT_TRUE(release_parked.wait(watchdog)); + } + }; + hooks.after_enqueue = [&](const BlobRef & ref) + { + if (ref != idOf(parked)) + return; + /// Running, so the unwind cannot cancel it before it starts. + EXPECT_TRUE(parked_running.wait(watchdog)); + query_ptr.load()->kill(); + killed.fire(); + }; + + int code = 0; + int parked_heads_at_return = -1; + std::thread parent([&] + { + DB::ThreadStatus thread_status; + DB::Cas::tests::CasKillableQuery query(getContext().context); + query_ptr = &query; + std::vector reqs{localRequest(one), localRequest(two)}; + auto pool = makePool(2); + try + { + fanOutBlobUploads(*build, reqs, *pool, &hooks); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + parked_heads_at_return = b->headsOf(s->layout().blobKey(idOf(parked))); + parent_returned.fire(); + }); + + EXPECT_TRUE(killed.wait(watchdog)); + EXPECT_FALSE(parent_returned.wait(std::chrono::milliseconds(300))) + << "the caller returned while a dispatched upload task was still parked"; + release_parked.fire(); + EXPECT_TRUE(parent_returned.wait(watchdog)); + parent.join(); + + EXPECT_EQ(code, DB::ErrorCodes::QUERY_WAS_CANCELLED); + EXPECT_EQ(parked_heads_at_return, 1) << "the parked task's upload ran before the caller returned"; + EXPECT_EQ(dispatched.size(), 2u) << "the sibling was not dispatched after the kill"; + EXPECT_EQ(b->headsOf(s->layout().blobKey(idOf(later))), 1) << "the sibling did not send its HEAD"; + EXPECT_EQ(b->publications.load(), 0) << "a worker started a publication after the kill"; + EXPECT_EQ(stableDeps(*build), deps_before) << "the build recorded a dependency of the stopped fan-out"; +} + +/// An upload worker that fails to join the inserting query's thread group sends nothing: outside the query a missing +/// `HEAD` would not see the query's stop and the worker would publish. The fan-out fails and records no dependency. +TEST(CASUploadFanout, WorkerOutsideTheQuerySendsNothing) +{ + CAS_SKIP_WITHOUT_FAILPOINTS(); + auto b = std::make_shared(); + auto s = openPool(b); + auto build = precommitBuildFor(s, RootNamespace{"srv1/nsDetachedWorker"}, "part"); + const auto deps_before = stableDeps(*build); + const String one = "detached-worker-one"; + + int code = 0; + String failure; + DB::Cas::tests::onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery &) + { + /// Armed after the query's own attach, so the worker's switch is the one that fails; it fails one switch only. + DB::FailPointInjection::enableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); + SCOPE_EXIT({ DB::FailPointInjection::disableFailPoint(DB::FailPoints::thread_group_switcher_post_attach_failure); }); + std::vector reqs{localRequest(one)}; + auto pool = makePool(2); + try + { + fanOutBlobUploads(*build, reqs, *pool); + } + catch (const DB::Exception & e) + { + code = e.code(); + failure = e.message(); + } + }); + + EXPECT_EQ(code, DB::ErrorCodes::CANNOT_SCHEDULE_TASK) << failure; + EXPECT_EQ(b->publications.load(), 0) << "a worker outside the query published a blob"; + EXPECT_EQ(b->headsOf(s->layout().blobKey(idOf(one))), 0) << "a worker outside the query sent a HEAD"; + EXPECT_EQ(stableDeps(*build), deps_before); +} + /// A part's uploads run concurrently and each holds its payload reader until it finishes, so a small /// staged payload must not pin a full default-sized read buffer. TEST(CASUploadFanout, LocalStagedPayloadReaderIsSizedToThePayload) @@ -1043,3 +1213,93 @@ TEST(CASUploadFanout, LocalStagedPayloadReaderIsSizedToThePayload) DB::readStringUntilEOF(large_read, *large_reader); EXPECT_EQ(large_read, large); } + +namespace +{ + +/// Holds every intent `GET` until `expected` of them are in flight, runs `on_all_arrived` once, then answers as the S3 +/// client does: a miss checks the query, which throws the query's stored exception once it is killed. +class IntentReadRendezvousBackend final : public InMemoryBackend +{ +public: + std::optional read(const String & key, TransportAccess & access) override + { + if (intents_prefix.empty() || !key.starts_with(intents_prefix)) + return InMemoryBackend::read(key, access); + { + std::unique_lock lock(mutex); + if (++arrived == expected) + { + on_all_arrived(); + cv.notify_all(); + } + else if (!cv.wait_for(lock, std::chrono::seconds(30), [&] { return arrived >= expected; })) + timed_out = true; + } + auto answer = InMemoryBackend::read(key, access); + if (!answer) + DB::CurrentThread::checkIfNotCancelled(); + return answer; + } + + /// Empty until the pool is open: the pool's own reads are not intent reads. + String intents_prefix; + int expected = 2; + std::function on_all_arrived; + bool timed_out = false; + +private: + std::mutex mutex; + std::condition_variable cv; + int arrived = 0; +}; + +} + +/// Two upload tasks whose intent reads fail with the query's stored exception receive the same object, so neither +/// may annotate it. The stored message must stay as the query set it; with an annotating catch it changes on every +/// run, and TSan or ASan also sees the two unsynchronized writes to one string. +TEST(CASUploadFanout, ConcurrentIntentReadsLeaveTheStoredQueryExceptionUnchanged) +{ + const String stored_text = "the query's stored network failure"; + for (int iteration = 0; iteration < 50; ++iteration) + { + SCOPED_TRACE(iteration); + auto b = std::make_shared(); + auto s = openPool(b); + b->intents_prefix = s->layout().blobIntentsPrefix(); + auto build = precommitBuildFor(s, RootNamespace{"srv1/nsStoredVerdict"}, "part"); + const String one = "stored-verdict-one"; + const String two = "stored-verdict-two"; + seedPresentBody(*b, s->layout(), s->poolMeta(), one); + seedPresentBody(*b, s->layout(), s->poolMeta(), two); + + const auto cause = std::make_exception_ptr(DB::Exception(DB::ErrorCodes::NETWORK_ERROR, "{}", stored_text)); + int code = 0; + DB::Cas::tests::onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + b->on_all_arrived = [&] { query.kill(cause); }; + std::vector reqs{localRequest(one), localRequest(two)}; + auto pool = makePool(2); + try + { + fanOutBlobUploads(*build, reqs, *pool); + } + catch (const DB::Exception & e) + { + code = e.code(); + } + }); + + ASSERT_FALSE(b->timed_out) << "the two intent reads never overlapped"; + EXPECT_EQ(code, DB::ErrorCodes::NETWORK_ERROR); + try + { + std::rethrow_exception(cause); + } + catch (const DB::Exception & e) + { + ASSERT_EQ(e.message(), stored_text) << "an intent read annotated the query's stored exception"; + } + } +} diff --git a/src/Disks/tests/gtest_cas_writer_duties.cpp b/src/Disks/tests/gtest_cas_writer_duties.cpp index 19c42a59922b1..b15f7d41f9026 100644 --- a/src/Disks/tests/gtest_cas_writer_duties.cpp +++ b/src/Disks/tests/gtest_cas_writer_duties.cpp @@ -1,27 +1,41 @@ #include +#include #include #include #include #include #include +#include #include +#include +#include +#include #include #include #include +#include +#include +#include #include #include +#include +#include +#include #include namespace DB::ErrorCodes { +extern const int ABORTED; extern const int NETWORK_ERROR; } using namespace DB::Cas; using DB::Cas::tests::SharedWaitLog; +using DB::Cas::tests::StoppedBy; +using DB::Cas::tests::exceptionCodeOf; namespace { @@ -276,6 +290,18 @@ TEST(CASWriterDuties, WedgeResolvedAsRejectDrainsTheDutyAsNoOp) /// Removing `mutateRefsAfterWriterCleanup` from the `dropRef` delegate leaves the rejected build at /// `minActive` even though the ref removal succeeds. The observable floor proves the direct API /// serviced the inherited cleanup duty before performing its own mutation. +/// A precommit append refused after admission may already be on its way, so it keeps its cleanup duty and the build +/// floor. Only a closed removal lane refuses before the append is queued, and that refusal owes nothing. +TEST(CASWriterDuties, PrecommitRefusedAfterAdmissionKeepsItsDuty) +{ + auto backend = std::make_shared(); + auto store = openFrozenSingleAttemptPool(backend); + const RootNamespace ns{"srv1/writer_duty_refused_after_admission"}; + publishEmptyRef(store, ns, "target"); + leaveRejectedCleanupDuty(store, ns); + EXPECT_TRUE(store->writerCleanupDutiesPendingForTest()); +} + TEST(CASWriterDuties, DropRefServicesPendingDutyBeforeRemovingTheRef) { auto backend = std::make_shared(); @@ -644,3 +670,206 @@ TEST(CASWriterDuties, DutySurvivesSettlementFailureForRetry) EXPECT_EQ(store->minActive(), store->peekNextBuildSeq()) << "the retried drain settles the retained duty and lets the mutation proceed"; } + +namespace +{ + +constexpr auto STOP_WATCHDOG = std::chrono::seconds(30); + +/// Leaves one duty per ref, each owing a real `OwnerTransition` removal: durable precommits destroyed +/// unsettled. Every precommit lands before the first destruction, since a precommit drains pending duties. +std::vector leaveDurableCleanupDuties(const PoolPtr & store, const RootNamespace & ns, const std::vector & ref_names) +{ + std::vector builds; + std::vector seqs; + for (const auto & ref_name : ref_names) + { + ManifestId id; + builds.push_back(stageEmptyManifest(store, ns, ref_name, id)); + seqs.push_back(builds.back()->buildSeq()); + builds.back()->precommitAdd(ns, ref_name, id); + } + for (auto & build : builds) + build.reset(); + return seqs; +} + +/// Runs `call` on a thread with a killable query and a background owner; `arm` gets the stop of `owner` before +/// `call` runs. +int runAsStoppable(StoppedBy owner, const std::function &)> & arm, const std::function & call) +{ + int code = 0; + DB::Cas::tests::onKillableQueryThread([&](DB::Cas::tests::CasKillableQuery & query) + { + auto background_stopped = std::make_shared>(false); + const auto background = DB::Cas::tests::backgroundOwnerStoppedBy(background_stopped); + arm(DB::Cas::tests::stopperOf(owner, query, background_stopped)); + code = exceptionCodeOf(call); + }); + return code; +} + +void updateLater(const PoolPtr & store, const RootNamespace & ns) +{ + store->updateRefPublishedAt(ns, "later", [](RefPublishedAtUpdate & update) { update.published_at_ms = 17; }); +} + +} + +namespace +{ + +/// A caller's owner stops in the cleanup-duty drain: once while it waits behind another drainer, once while it drains +/// itself between two duties. +void runCleanupDrainWithStoppedCaller(StoppedBy owner) +{ + { + SCOPED_TRACE("waiting behind another drainer"); + auto backend = std::make_shared(); + auto store = openFrozenSingleAttemptPool(backend); + const RootNamespace ns{"srv1/writer_duty_stopped_waiter"}; + publishEmptyRef(store, ns, "target"); + publishEmptyRef(store, ns, "later"); + const uint64_t duty_seq = leaveDurableCleanupDuties(store, ns, {"durable"}).front(); + ASSERT_TRUE(store->writerCleanupDutiesPendingForTest()); + + std::mutex mutex; + std::condition_variable cv; + bool drainer_parked = false; + bool release_drainer = false; + bool drainer_left = false; + std::atomic entered{false}; + store->setRefPreCarveHookForTest([&] + { + if (entered.exchange(true)) + return; + std::unique_lock lock(mutex); + drainer_parked = true; + cv.notify_all(); + cv.wait_for(lock, STOP_WATCHDOG, [&] { return release_drainer; }); + drainer_left = true; + }); + SCOPE_EXIT({ store->setRefPreCarveHookForTest(nullptr); }); + /// A killed query keeps waiting, so the parked drainer is released once that caller is seen waiting. + store->setWriterCleanupWaitHookForTest([&] + { + if (owner != StoppedBy::Query) + return; + std::lock_guard lock(mutex); + release_drainer = true; + cv.notify_all(); + }); + SCOPE_EXIT({ store->setWriterCleanupWaitHookForTest(nullptr); }); + std::future drainer + = std::async(std::launch::async, [&] { return exceptionCodeOf([&] { store->dropRef(ns, "target"); }); }); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, STOP_WATCHDOG, [&] { return drainer_parked; })); + } + + bool returned_while_drainer_parked = false; + bool draining_on_return = false; + bool pending_on_return = false; + uint64_t floor_on_return = 0; + const int code = runAsStoppable(owner, [](const std::function & stop) { stop(); }, [&] + { + SCOPE_EXIT({ + draining_on_return = store->writerCleanupDrainingForTest(ns); + pending_on_return = store->writerCleanupDutiesPendingForTest(); + floor_on_return = store->minActive(); + std::lock_guard lock(mutex); + returned_while_drainer_parked = !drainer_left; + release_drainer = true; + cv.notify_all(); + }); + updateLater(store, ns); + }); + ASSERT_EQ(drainer.wait_for(STOP_WATCHDOG), std::future_status::ready); + + if (owner == StoppedBy::Background) + { + EXPECT_EQ(code, DB::ErrorCodes::ABORTED); + EXPECT_TRUE(returned_while_drainer_parked) << "the stopped caller waited for the other drainer"; + EXPECT_TRUE(draining_on_return) << "the other drainer's claim must stay"; + EXPECT_TRUE(pending_on_return); + EXPECT_EQ(floor_on_return, duty_seq); + } + else + { + EXPECT_EQ(code, 0) << "a killed query waits for the other drainer and proceeds"; + EXPECT_FALSE(returned_while_drainer_parked) << "the killed query returned before the drainer was released"; + EXPECT_FALSE(draining_on_return); + EXPECT_FALSE(pending_on_return); + } + EXPECT_EQ(drainer.get(), 0); + EXPECT_FALSE(store->writerCleanupDutiesPendingForTest()); + EXPECT_EQ(store->minActive(), store->peekNextBuildSeq()); + EXPECT_NO_THROW(updateLater(store, ns)) << "a later caller is admitted"; + } + + { + SCOPED_TRACE("draining, stopped between duties"); + auto backend = std::make_shared(); + auto store = openFrozenSingleAttemptPool(backend); + const RootNamespace ns{"srv1/writer_duty_stopped_drainer"}; + publishEmptyRef(store, ns, "later"); + const uint64_t next_seq = leaveDurableCleanupDuties(store, ns, {"settled", "next"}).back(); + + std::atomic stopped{false}; + std::atomic tenures_after_stop{0}; + const int code = runAsStoppable(owner, [&](const std::function & stop) + { + /// The first duty's append is installed when the owner stops; it completes as shared work. + store->setCarveHookForTest([&, stop](CasRefLedger::CarvePhaseForTest phase) + { + if (phase == CasRefLedger::CarvePhaseForTest::PostInstallPreAck && !stopped.exchange(true)) + stop(); + }); + store->setRefPreTenureHookForTest([&] + { + if (stopped.load()) + ++tenures_after_stop; + }); + }, [&] { updateLater(store, ns); }); + store->setCarveHookForTest(nullptr); + store->setRefPreTenureHookForTest(nullptr); + + EXPECT_TRUE(stopped.load()); + EXPECT_FALSE(store->writerCleanupDrainingForTest(ns)); + if (owner == StoppedBy::Background) + { + EXPECT_EQ(code, DB::ErrorCodes::ABORTED); + EXPECT_EQ(tenures_after_stop.load(), 0) << "a stopped drainer starts no append for the next duty"; + EXPECT_TRUE(store->writerCleanupDutiesPendingForTest()); + EXPECT_EQ(store->minActive(), next_seq) << "the settled duty is retired, the next one is not"; + const auto live = store->livePrecommitsForTest(ns); + ASSERT_EQ(live.size(), 1u); + EXPECT_EQ(live.begin()->first, "next"); + EXPECT_NO_THROW(updateLater(store, ns)) << "a later caller drains the next duty"; + } + else + { + EXPECT_EQ(code, 0) << "a killed query drains every duty and runs its own mutation"; + EXPECT_GT(tenures_after_stop.load(), 0) << "the next duty's append ran after the kill"; + EXPECT_TRUE(store->livePrecommitsForTest(ns).empty()); + } + EXPECT_FALSE(store->writerCleanupDutiesPendingForTest()); + EXPECT_EQ(store->minActive(), store->peekNextBuildSeq()); + } +} + +} + +/// A caller whose background owner stops leaves the cleanup-duty drain without changing it: waiting behind another +/// drainer, it leaves that drainer's claim, the queued duty and the build floor; draining itself, it stops between +/// duties only after the settled one is retired and popped, and starts no append for the next one. +TEST(CASWriterDuties, BackgroundStoppedCleanupDrainerLeavesDutyAndFloor) +{ + runCleanupDrainWithStoppedCaller(StoppedBy::Background); +} + +/// A killed query is not a background owner: it waits for the other drainer, and drains every duty itself. +TEST(CASWriterDuties, KilledQueryWaitsForTheDrainerAndDrainsEveryDuty) +{ + runCleanupDrainWithStoppedCaller(StoppedBy::Query); +} diff --git a/src/Interpreters/ContentAddressedGarbageCollectionLog.cpp b/src/Interpreters/ContentAddressedGarbageCollectionLog.cpp index 5052577f85a55..de407e028c547 100644 --- a/src/Interpreters/ContentAddressedGarbageCollectionLog.cpp +++ b/src/Interpreters/ContentAddressedGarbageCollectionLog.cpp @@ -39,7 +39,7 @@ ColumnsDescription ContentAddressedGarbageCollectionLogElement::getColumnsDescri {"gc_id", std::make_shared(), "GC scheduler instance id (which mounter)."}, {"trigger", trigger_enum, "Scheduled (background tick) or Manual (SYSTEM command)."}, {"round", std::make_shared(), "GC round number (0 on Start)."}, - {"outcome", outcome_enum, "Unknown (Start) / Success (led, folded, and completed) / NotALeader (another replica holds the GC lease) / Deferred (led but took the skip-unchanged fast path -- no fold ran) / Aborted (the round threw a transient error -- backend unavailability, a lost lease, a concurrent leader -- and the next scheduled round retries) / Stopped (a transient error observed after the disk\'s teardown began: the round was cut short by a server shutdown or the storage\'s destructor, so neither waited for it; a correlation, not a cause -- a transient incident that started before the teardown is recorded the same way, and decommission does not arm the flag at all) / Error (the round threw a non-transient error -- during a teardown too)."}, + {"outcome", outcome_enum, "Unknown (Start) / Success (led, folded, and completed) / NotALeader (another replica holds the GC lease) / Deferred (led but took the skip-unchanged fast path -- no fold ran) / Aborted (the round threw a transient error -- backend unavailability, a lost lease, a concurrent leader -- and the next scheduled round retries) / Stopped (the round was cut short on request: a transient error after the disk\'s teardown began, a stop by `SYSTEM CAS GC STOP`, or a manual round whose query was killed or timed out; for a teardown this is a correlation, not a cause -- a transient incident that started before the teardown is recorded the same way, and decommission does not arm the flag at all) / Error (the round threw a non-transient error -- during a teardown too)."}, {"candidates_marked", std::make_shared(), "Objects retired (marked) this round."}, {"objects_deleted", std::make_shared(), "Objects physically deleted this round."}, {"objects_absent", std::make_shared(), "Retire candidates found already absent."}, @@ -53,14 +53,14 @@ ColumnsDescription ContentAddressedGarbageCollectionLogElement::getColumnsDescri {"fence_outs", std::make_shared(), "Expired mounts fenced out by this round's heartbeat floor."}, {"anomalies", std::make_shared(), "Fold clamps surfaced (and survived) this round; steady >0 warrants a look at the round log details."}, {"duration_ms", std::make_shared(), "Round wall-clock duration (Finish)."}, - {"error", std::make_shared(), "Exception text when outcome = Aborted, Stopped or Error. On a Stopped row it names the engine\'s refusal, not the teardown."}, - {"error_code", std::make_shared(), "Exception code when outcome = Aborted, Stopped or Error; 0 otherwise. The structured twin of `error`: key monitoring on this column, not on message text."}, + {"error", std::make_shared(), "Exception text when outcome = Aborted, Stopped or Error. On a Stopped row it is the message of the exception that ended the round: for example `CAS GC round stopped by its scheduler` or the killed query\'s own message; after a teardown it names the engine\'s refusal, not the teardown."}, + {"error_code", std::make_shared(), "Exception code when outcome = Aborted, Stopped or Error; 0 otherwise. The structured twin of `error`: key monitoring on this column, not on message text. On a Stopped row it is the code the round ended with: usually ABORTED for SYSTEM CAS GC STOP and QUERY_WAS_CANCELLED or TIMEOUT_EXCEEDED for a manual round, but any transient code can appear, such as NETWORK_ERROR after a write whose outcome is unknown."}, {"ProfileEvents", std::make_shared(lc_string, std::make_shared()), "On a Start/Finish row: the per-round ProfileEvents delta (the Cas* counters and S3 events for this round). On a Phase row: THAT PHASE's delta, so `GROUP BY phase` over `ProfileEvents['S3ListObjects']` attributes the round's LIST budget to the phase that spent it. Requests issued by GC I/O pool workers (the `pending_deletes` fan-out and the fold read-ahead) are missing from their phase rows; they still count in `system.events`."}, {"round_id", std::make_shared(), "Correlator for every row of one round attempt (its Start, each Phase, and its Finish). Minted per attempt; unlike `round` it exists even for a round that never committed and for a round that never led. Group by this column to reconstruct one round."}, {"phase", lc_string, - "The GC phase this row describes (empty on Start/Finish), in execution order: lease, pre_fold_ref_drain, heartbeat_floor, defer_decision, parent_seal_read, fold_ref_group, fold_seal_read, fold_ref_intake, intent_sweep_list, fold_reduce, fold_seal_write, pending_deletes, round_commit, handoff_reclaim, manifest_deletes, namespace_cleanup, ref_object_cleanup, orphan_sweep. A round that defers, or that never acquires the lease, emits only the phases it reached."}, + "The GC phase this row describes (empty on Start/Finish), in execution order: lease, pre_fold_ref_drain, heartbeat_floor, defer_decision, parent_seal_read, fold_ref_group, fold_seal_read, fold_ref_intake, intent_sweep_list, fold_reduce, fold_seal_write, pending_deletes, round_commit, handoff_reclaim, manifest_deletes, orphan_sweep, namespace_cleanup, ref_object_cleanup. A round that defers, or that never acquires the lease, emits only the phases it reached."}, {"phase_duration_microseconds", std::make_shared(), "Wall-clock duration of this phase in microseconds (Phase rows only). Microseconds because several phases are routinely sub-millisecond and the point is to see when they are not. Phase durations do not sum to the round's `duration_ms`: the round also does untimed bookkeeping between phases."}, {"phase_metrics", std::make_shared(lc_string, std::make_shared()), diff --git a/tests/integration/test_cas_mount_renewal_retry/s3_fault_proxy.py b/tests/integration/helpers/s3_mocks/s3_fault_proxy.py similarity index 62% rename from tests/integration/test_cas_mount_renewal_retry/s3_fault_proxy.py rename to tests/integration/helpers/s3_mocks/s3_fault_proxy.py index cf3102611a192..641599683a30b 100644 --- a/tests/integration/test_cas_mount_renewal_retry/s3_fault_proxy.py +++ b/tests/integration/helpers/s3_mocks/s3_fault_proxy.py @@ -22,6 +22,23 @@ `remaining_faults` budget. The `drop_after_forward` mode records the upstream result and request body digest, then closes the downstream connection so retry recovery can prove response-loss cases. +`slow_then_drop` waits `slow_ms`, forwards, then closes without the response. `trickle` forwards, then +sends the response in pieces spread over `slow_ms`. `trace: true` records every request at ingress +(optionally scoped by `trace_path_substring`) and `/stats` returns it as `trace`, with the proxy's +monotonic clock as `now_mono_ms`. A record names the fault it got; after a trickle, `outcome` is +`delivered` once the last piece is flushed or `disconnected` when a write fails, and +`t_last_piece_mono_ms` is when the last piece started to be written. With `trace_bodies: true` a record +also carries the request body as Latin-1 text when it is at most `TRACE_BODY_MAX_BYTES`, else None. + +`rules` is an ordered script of `{method, path_substring, action, count}` with an optional +`body_substring`. Only the first rule with `count > 0` is consulted: a request it matches consumes one +count and gets its action, any other request gets the random decision above. `path_substring`, +`trace_path_substring` and `body_substring` are each a string or a list of strings that must all occur. +Actions: `forward`; `412`, an S3 `PreconditionFailed` without forwarding; `503`, a `SlowDown` without +forwarding; `hold`, which parks the request until `POST /release {id, respond: forward|503}`. A traced +parked request gets `t_release_mono_ms` when it is released. `GET /parked` lists the parked requests; +`/stats` returns the rules with their remaining counts. + Control plane (separate port): POST /config {json}, GET /stats, GET /healthz. Deterministic: fault decisions are driven by a seeded PRNG keyed per-request-index, so a given (seed, rate) is reproducible. """ @@ -29,6 +46,7 @@ import hashlib import http.client import http.server +import io import json import os import random @@ -41,20 +59,29 @@ UPSTREAM = os.environ.get("RUSTFS_UPSTREAM", "rustfs1:11121") # host:port of the real store S3_PORT = int(os.environ.get("S3_PROXY_PORT", "11121")) CTL_PORT = int(os.environ.get("S3_PROXY_CTL_PORT", "8474")) +TRICKLE_INTERVAL_MS = 250 +TRACE_BODY_MAX_BYTES = 64 * 1024 # Runtime-mutable fault config (guarded by _cfg_lock). rate=0 => pure pass-through. _cfg_lock = threading.Lock() _DEFAULT_CFG = { "rate": 0.0, # fraction of matched requests that get a fault - "modes": ["503"], # subset of {503,429,slow,reset,drop_after_forward} + # subset of {503,429,slow,reset,drop_after_forward,slow_then_drop,trickle}: + # slow_then_drop waits slow_ms, forwards, then closes without the response; + # trickle forwards, then sends the response in pieces spread over slow_ms. + "modes": ["503"], "methods": ["GET", "PUT", "HEAD", "POST"], # HTTP methods eligible for S22 faults "slow_ms": 1500, # latency for the "slow" mode "seed": 1, "path_substring": None, # optional request-path scope + "trace": False, # record every request at ingress; returned by /stats + "trace_path_substring": None, # optional scope of the trace + "trace_bodies": False, # record small request bodies in the trace "remaining_faults": None, # optional exact finite fault budget; None = legacy unlimited # S27 list-anomaly config (independent of the S22 fault rate): "list_anomaly": None, # None | "duplicate" | "drop_token" "list_prefix": "roots/", # only LIST calls whose prefix contains this are perturbed + "rules": [], # ordered script; see the module docstring } _DEFAULT_STATS = { "forwarded": 0, @@ -62,13 +89,18 @@ "list_perturbed": 0, "by_mode": {}, "drop_after_forward": [], + "trace": [], } _cfg = dict(_DEFAULT_CFG) _stats = dict(_DEFAULT_STATS) _stats["by_mode"] = {} _stats["drop_after_forward"] = [] +_stats["trace"] = [] _req_index = [0] _idx_lock = threading.Lock() +# id -> {"id", "method", "path", "t_mono_ms", "event", "respond", "trace"}; guarded by _cfg_lock. +_parked = {} +_parked_ids = [0] def _get_cfg(): @@ -104,14 +136,26 @@ def _record_drop_after_forward(method, path, body, upstream_status, upstream_eta del records[:-64] +def _release(record, respond): + record["respond"] = respond + if record["trace"] is not None: + record["trace"]["t_release_mono_ms"] = time.monotonic() * 1000.0 + record["event"].set() + + def _reset(): with _cfg_lock: + # A parked handler thread must not outlive the test that parked it. + for record in _parked.values(): + _release(record, "503") + _parked.clear() _cfg.clear() _cfg.update(_DEFAULT_CFG) _stats.clear() _stats.update(_DEFAULT_STATS) _stats["by_mode"] = {} _stats["drop_after_forward"] = [] + _stats["trace"] = [] with _idx_lock: _req_index[0] = 0 @@ -119,6 +163,21 @@ def _reset(): _SLOWDOWN_BODY = (b'' b'SlowDownPlease reduce your request rate.' b'/fault-proxy') +_PRECONDITION_FAILED_BODY = (b'' + b'PreconditionFailed' + b'At least one of the pre-conditions you specified did not hold' + b'/fault-proxy') + + +def _path_matches(path, substring): + if substring is None: + return True + substrings = [substring] if isinstance(substring, str) else substring + return all(s in (path or "") for s in substrings) + + +def _body_matches(body, substring): + return _path_matches(body.decode("latin-1"), substring) class Handler(http.server.BaseHTTPRequestHandler): @@ -128,6 +187,34 @@ def log_message(self, *a): pass # quiet # --- fault decision ----------------------------------------------------- + def _admit(self, ingress_mono_ms): + """Consumes the head rule, publishes the trace record and parks a held request in one critical section, so + a concurrent `/config` reset or `/release` sees all three or none of them. Returns the rule's action and the + parked record.""" + with _cfg_lock: + action = None + head = next((r for r in _cfg["rules"] if r["count"] > 0), None) + if (head is not None and head["method"] == self.command and _path_matches(self.path, head["path_substring"]) + and _body_matches(self._cached_body, head.get("body_substring"))): + head["count"] -= 1 + action = head["action"] + if _cfg["trace"] and _path_matches(self.path, _cfg.get("trace_path_substring")): + body = None + if _cfg.get("trace_bodies") and len(self._cached_body) <= TRACE_BODY_MAX_BYTES: + body = self._cached_body.decode("latin-1") + # Every key exists before the record is published; later fields start as None. + self._trace_record = {"t_mono_ms": ingress_mono_ms, "method": self.command, "path": self.path, + "fault": None, "rule": action, "status": None, "outcome": None, + "t_last_piece_mono_ms": None, "t_release_mono_ms": None, "body": body} + _stats["trace"].append(self._trace_record) + parked = None + if action == "hold": + _parked_ids[0] += 1 + parked = {"id": _parked_ids[0], "method": self.command, "path": self.path, "t_mono_ms": ingress_mono_ms, + "event": threading.Event(), "respond": None, "trace": self._trace_record} + _parked[parked["id"]] = parked + return action, parked + def _should_fault(self, cfg): # Keep the original unscoped decision path byte-for-byte: existing scenario configs omit # both new fields and therefore retain their request-index/seed behavior. @@ -146,8 +233,7 @@ def _should_fault(self, cfg): current = _cfg if current["rate"] <= 0 or self.command not in current["methods"]: return None - path_substring = current.get("path_substring") - if path_substring is not None and path_substring not in (self.path or ""): + if not _path_matches(self.path, current.get("path_substring")): return None remaining = current.get("remaining_faults") if remaining is not None and remaining <= 0: @@ -161,17 +247,40 @@ def _should_fault(self, cfg): current["remaining_faults"] = remaining - 1 return mode + def _send_error(self, code, body): + self._trace_status(code) + self.send_response(code) + self.send_header("Content-Type", "application/xml") + self.send_header("Content-Length", str(len(body))) + self.send_header("Connection", "keep-alive") + self.end_headers() + self.wfile.write(body) + + def _hold(self, parked): + parked["event"].wait() + if parked["respond"] == "forward": + self._forward() + else: + self._send_error(503, _SLOWDOWN_BODY) + + def _apply_rule(self, action, parked): + _bump("by_mode", "rule_" + action) + if action == "forward": + self._forward() + elif action == "412": + self._send_error(412, _PRECONDITION_FAILED_BODY) + elif action == "503": + self._send_error(503, _SLOWDOWN_BODY) + elif action == "hold": + self._hold(parked) + else: + raise ValueError(f"unknown rule action {action}") + def _emit_fault(self, mode): _bump("faults") _bump("by_mode", mode) if mode in ("503", "429"): - code = 503 if mode == "503" else 429 - self.send_response(code) - self.send_header("Content-Type", "application/xml") - self.send_header("Content-Length", str(len(_SLOWDOWN_BODY))) - self.send_header("Connection", "keep-alive") - self.end_headers() - self.wfile.write(_SLOWDOWN_BODY) + self._send_error(503 if mode == "503" else 429, _SLOWDOWN_BODY) elif mode == "slow": time.sleep(_get_cfg()["slow_ms"] / 1000.0) self._forward() # after the delay, serve the real response @@ -184,6 +293,11 @@ def _emit_fault(self, mode): pass elif mode == "drop_after_forward": self._forward(drop_after_forward=True) + elif mode == "slow_then_drop": + time.sleep(_get_cfg()["slow_ms"] / 1000.0) + self._forward(drop_after_forward=True) + elif mode == "trickle": + self._forward(trickle=True) # --- request body ------------------------------------------------------- def _read_body(self): @@ -207,7 +321,7 @@ def _read_body(self): return b"" # --- forward to upstream ------------------------------------------------ - def _forward(self, drop_after_forward=False): + def _forward(self, drop_after_forward=False, trickle=False): body = getattr(self, "_cached_body", None) if body is None: body = self._read_body() @@ -265,6 +379,10 @@ def _forward(self, drop_after_forward=False): pass self.connection.close() return + self._trace_status(resp.status) + real_wfile = self.wfile + if trickle: + self.wfile = io.BytesIO() self.send_response(resp.status) is_head = (self.command == "HEAD") for k, v in resp.getheaders(): @@ -281,10 +399,34 @@ def _forward(self, drop_after_forward=False): self.end_headers() if not is_head: self.wfile.write(data) + if trickle: + # Keeps the socket active, so only a total-time bound ends the attempt. + raw = self.wfile.getvalue() + self.wfile = real_wfile + pieces = max(1, int(cfg["slow_ms"] // TRICKLE_INTERVAL_MS)) + step = max(1, -(-len(raw) // pieces)) + outcome = "disconnected" + try: + for i in range(0, len(raw), step): + time.sleep(TRICKLE_INTERVAL_MS / 1000.0) + if i + step >= len(raw) and self._trace_record is not None: + self._trace_record["t_last_piece_mono_ms"] = time.monotonic() * 1000.0 + self.wfile.write(raw[i:i + step]) + self.wfile.flush() + outcome = "delivered" + finally: + if self._trace_record is not None: + self._trace_record["outcome"] = outcome conn.close() + def _trace_status(self, status): + if self._trace_record is not None: + self._trace_record["status"] = status + def _handle(self): cfg = _get_cfg() + self._trace_record = None + ingress_mono_ms = time.monotonic() * 1000.0 # Cache body once (fault paths + forward both may need it). try: self._cached_body = self._read_body() @@ -294,8 +436,13 @@ def _handle(self): print(f"[dbg] {self.command} {self.path[:60]} CL={self.headers.get('Content-Length')} " f"TE={self.headers.get('Transfer-Encoding')} CE={self.headers.get('Content-Encoding')} " f"Expect={self.headers.get('Expect')} read={len(self._cached_body)}", flush=True) - mode = self._should_fault(cfg) - if mode is None: + action, parked = self._admit(ingress_mono_ms) + mode = self._should_fault(cfg) if action is None else None + if self._trace_record is not None: + self._trace_record["fault"] = mode + if action is not None: + self._apply_rule(action, parked) + elif mode is None: self._forward() else: self._emit_fault(mode) @@ -365,21 +512,41 @@ def do_GET(self): snapshot = dict(_stats) snapshot["by_mode"] = dict(_stats["by_mode"]) snapshot["drop_after_forward"] = list(_stats["drop_after_forward"]) + snapshot["trace"] = [dict(r) for r in _stats["trace"]] + snapshot["rules"] = [dict(r) for r in _cfg["rules"]] + snapshot["now_mono_ms"] = time.monotonic() * 1000.0 return self._json(200, snapshot) + if self.path.startswith("/parked"): + with _cfg_lock: + parked = [{k: r[k] for k in ("id", "method", "path", "t_mono_ms")} + for r in _parked.values() if r["respond"] is None] + return self._json(200, {"parked": parked}) self._json(404, {"error": "not found"}) def do_POST(self): - if not self.path.startswith("/config"): - return self._json(404, {"error": "not found"}) length = int(self.headers.get("Content-Length", "0")) try: patch = json.loads(self.rfile.read(length) or b"{}") except Exception as e: return self._json(400, {"error": f"bad json: {e}"}) + if self.path.startswith("/release"): + respond = patch.get("respond", "forward") + if respond not in ("forward", "503"): + return self._json(400, {"error": f"bad respond {respond}"}) + with _cfg_lock: + record = _parked.pop(patch.get("id"), None) + if record is None: + return self._json(404, {"error": "not parked"}) + _release(record, respond) + return self._json(200, {"ok": True}) + if not self.path.startswith("/config"): + return self._json(404, {"error": "not found"}) reset = bool(patch.pop("reset", False)) if reset: _reset() with _cfg_lock: + if "rules" in patch: + patch["rules"] = [dict(r) for r in patch["rules"]] _cfg.update(patch) snap = dict(_cfg) self._json(200, {"ok": True, "config": snap}) diff --git a/tests/integration/test_cas_mount_renewal_retry/docker_compose_proxy.yml b/tests/integration/test_cas_mount_renewal_retry/docker_compose_proxy.yml index 67f39af36922b..d83488f9ea4c7 100644 --- a/tests/integration/test_cas_mount_renewal_retry/docker_compose_proxy.yml +++ b/tests/integration/test_cas_mount_renewal_retry/docker_compose_proxy.yml @@ -11,9 +11,9 @@ services: condition: service_started volumes: # Compose resolves relative binds against the generated first compose file in - # `/_instances-*/node`, not against this appended file, so `../..` is the - # directory holding this file. - - ../../s3_fault_proxy.py:/proxy/s3_fault_proxy.py:ro + # `/_instances-*/node`, not against this appended file, so `../../..` is + # `tests/integration`. + - ../../../helpers/s3_mocks/s3_fault_proxy.py:/proxy/s3_fault_proxy.py:ro expose: - "11121" ports: diff --git a/tests/integration/test_cas_request_window/__init__.py b/tests/integration/test_cas_request_window/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/integration/test_cas_request_window/configs/blob_upload_serial.xml b/tests/integration/test_cas_request_window/configs/blob_upload_serial.xml new file mode 100644 index 0000000000000..62a192ac8f339 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/blob_upload_serial.xml @@ -0,0 +1,4 @@ + + + 1 + diff --git a/tests/integration/test_cas_request_window/configs/drop_cooldown.xml b/tests/integration/test_cas_request_window/configs/drop_cooldown.xml new file mode 100644 index 0000000000000..42988c699315a --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/drop_cooldown.xml @@ -0,0 +1,5 @@ + + + 600 + diff --git a/tests/integration/test_cas_request_window/configs/drop_delay.xml b/tests/integration/test_cas_request_window/configs/drop_delay.xml new file mode 100644 index 0000000000000..3b6211126770a --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/drop_delay.xml @@ -0,0 +1,4 @@ + + + 0 + diff --git a/tests/integration/test_cas_request_window/configs/storage_conf.xml b/tests/integration/test_cas_request_window/configs/storage_conf.xml new file mode 100644 index 0000000000000..ec44b710170a0 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/storage_conf.xml @@ -0,0 +1,35 @@ + + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-window + http://s3proxy:11121/test/cas_request_window/ + clickhouse + clickhouse + false + + 500 + 1000 + 5000 + 10000 + 2000 + 500 + + + + + +
+ disk_cas_window +
+
+
+
+
+
diff --git a/tests/integration/test_cas_request_window/configs/storage_conf_gc.xml b/tests/integration/test_cas_request_window/configs/storage_conf_gc.xml new file mode 100644 index 0000000000000..8ab3bc3ef4027 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/storage_conf_gc.xml @@ -0,0 +1,37 @@ + + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-gc + http://s3proxy:11121/test/cas_request_gc/ + clickhouse + clickhouse + + true + 3600 + + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + + +
+ disk_cas_gc +
+
+
+
+
+
diff --git a/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml b/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml new file mode 100644 index 0000000000000..1e57ebc461a5f --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/storage_conf_stop.xml @@ -0,0 +1,38 @@ + + + + + object_storage + s3 + cas + 30 + 10000 + itest-cas-stop + http://s3proxy:11121/test/cas_request_stop/ + clickhouse + clickhouse + false + + false + 500 + 8000 + 19000 + 21000 + 2000 + 500 + + + + + +
+ disk_cas_stop +
+
+
+
+
+
diff --git a/tests/integration/test_cas_request_window/configs/transactions.xml b/tests/integration/test_cas_request_window/configs/transactions.xml new file mode 100644 index 0000000000000..f2a01989fdf20 --- /dev/null +++ b/tests/integration/test_cas_request_window/configs/transactions.xml @@ -0,0 +1,3 @@ + + 42 + diff --git a/tests/integration/test_cas_request_window/docker_compose_proxy.yml b/tests/integration/test_cas_request_window/docker_compose_proxy.yml new file mode 100644 index 0000000000000..210d732547b7c --- /dev/null +++ b/tests/integration/test_cas_request_window/docker_compose_proxy.yml @@ -0,0 +1,40 @@ +services: + s3proxy: + image: python:3.12-slim + command: ["python3", "/proxy/s3_fault_proxy.py"] + environment: + RUSTFS_UPSTREAM: "rustfs1:11121" + S3_PROXY_PORT: "11121" + S3_PROXY_CTL_PORT: "8474" + depends_on: + rustfs1: + condition: service_started + volumes: + # Compose resolves relative binds against the generated first compose file in + # `/_instances-*/node`, not against this appended file, so `../../..` is + # `tests/integration`. + - ../../../helpers/s3_mocks/s3_fault_proxy.py:/proxy/s3_fault_proxy.py:ro + expose: + - "11121" + ports: + - "127.0.0.1::8474" + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8474/healthz', timeout=2)"] + interval: 1s + timeout: 3s + retries: 30 + + node: + depends_on: + s3proxy: + condition: service_healthy + + node_stop: + depends_on: + s3proxy: + condition: service_healthy + + node_gc: + depends_on: + s3proxy: + condition: service_healthy diff --git a/tests/integration/test_cas_request_window/test.py b/tests/integration/test_cas_request_window/test.py new file mode 100644 index 0000000000000..124ce4d0d64db --- /dev/null +++ b/tests/integration/test_cas_request_window/test.py @@ -0,0 +1,988 @@ +"""One CAS metadata request gets its own window, not a deadline shared with the previous one. + +Pinned values (configs/storage_conf.xml, configs/drop_cooldown.xml): + attempt envelope 2000 ms, cas_request_window_ms 5000 (more than two envelopes), + slow_ms 7000 (more than the window), trickle interval 250 ms (shorter than the 500 ms + connect_timeout_ms, so the socket never idles that long), + database_catalog_drop_error_cooldown_sec 600 (a failed removal is not requeued while a test + checks it). + +The kill tests run on `node_stop` (configs/storage_conf_stop.xml): attempt timeout 8000 ms, so a +request parked for the kill handshake is not abandoned by its attempt timeout first. A plain `DROP TABLE` +there is removed at once (configs/drop_delay.xml). It runs with Keeper and transactions enabled +(configs/transactions.xml), and uploads a part's blobs one at a time (configs/blob_upload_serial.xml). + +The GC test runs on `node_gc` (configs/storage_conf_gc.xml): the same timing and a one-hour GC interval. +A manual round never takes the GC lease from another process, and a restart leaves the lease with the +previous one, so this server is never restarted. + +Each test drops the tables it leaves and scopes its fault rules and trace to its own pool, so the module +passes in any order and when repeated. +""" + +import json +import os +import re +import subprocess +import threading +import time +import urllib.request + +import pytest + +from helpers.cluster import ClickHouseCluster + +cluster = ClickHouseCluster(__file__) + +POLICY = "cas_window" +SLOW_MS = 7000 +WINDOW_S = 5 +WINDOW_PREFIX = "/test/cas_request_window/" +CATALOG = WINDOW_PREFIX + "cas/ref_catalog" +STOP_POLICY = "cas_stop" +STOP_PREFIX = "/test/cas_request_stop/" +STOP_CATALOG = STOP_PREFIX + "cas/ref_catalog" +# `cas_attempt_timeout_ms` of `configs/storage_conf_stop.xml`: a parked request's socket gives up after it. +STOP_ATTEMPT_TIMEOUT_S = 8 +# The store behind the proxy, which the servers can read directly. +STORE_URL = "http://rustfs1:11121" +GC_DISK = "disk_cas_gc" +# Without slashes, so it also matches a listing's URL-encoded `prefix` parameter. +GC_POOL = "cas_request_gc" + + +def _control(url, path, patch=None): + data = None if patch is None else json.dumps(patch).encode() + request = urllib.request.Request( + url + path, data=data, headers={"Content-Type": "application/json"}, method="GET" if data is None else "POST" + ) + with urllib.request.urlopen(request, timeout=10) as response: + return json.loads(response.read().decode()) + + +def _wait_until(probe, timeout): + end = time.monotonic() + timeout + while time.monotonic() < end: + result = probe() + if result: + return result + time.sleep(0.2) + raise AssertionError("condition did not become true within {}s".format(timeout)) + + +@pytest.fixture(scope="module") +def node(): + cluster.add_instance( + "node", + main_configs=["configs/storage_conf.xml", "configs/drop_cooldown.xml"], + with_rustfs=True, + ) + # `stay_alive` lets a test restart the server, which drops its cached ref tables. + cluster.add_instance("node_stop", main_configs=["configs/storage_conf_stop.xml", "configs/drop_delay.xml", + "configs/transactions.xml", "configs/blob_upload_serial.xml"], + with_rustfs=True, with_zookeeper=True, stay_alive=True) + cluster.add_instance("node_gc", main_configs=["configs/storage_conf_gc.xml"], with_rustfs=True) + cluster.base_cmd.extend(["--file", os.path.join(os.path.dirname(__file__), "docker_compose_proxy.yml")]) + try: + cluster.start() + binding = subprocess.check_output(cluster.base_cmd + ["port", "s3proxy", "8474"], text=True).strip() + cluster.proxy_url = "http://{}".format(binding) + _wait_until(lambda: _control(cluster.proxy_url, "/healthz"), timeout=30) + yield cluster.instances["node"] + finally: + cluster.shutdown() + + +@pytest.fixture(scope="module") +def node_stop(node): + return cluster.instances["node_stop"] + + +@pytest.fixture(scope="module") +def node_gc(node): + return cluster.instances["node_gc"] + + +def _drop_all_tables(instance): + for name in instance.query("SELECT table FROM system.detached_tables WHERE database = 'default'").split(): + instance.query("ATTACH TABLE default.`{}`".format(name)) + for name in instance.query("SELECT name FROM system.tables WHERE database = 'default'").split(): + instance.query("DROP TABLE default.`{}` SYNC".format(name)) + + +@pytest.fixture(autouse=True) +def clean_state(node, node_stop, node_gc): + _control(cluster.proxy_url, "/config", {"reset": True}) + yield + _control(cluster.proxy_url, "/config", {"reset": True}) + for instance in (node, node_stop, node_gc): + _drop_all_tables(instance) + + +def _arm(**config): + _control(cluster.proxy_url, "/config", dict(rate=1.0, trace=True, **config)) + + +def _stats(): + return _control(cluster.proxy_url, "/stats") + + +def _create(node, name): + node.query( + "CREATE TABLE {} (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(name, POLICY) + ) + + +def test_long_body_with_a_lost_response_commits(node): + _create(node, "long_body") + _arm( + modes=["slow_then_drop"], methods=["PUT"], path_substring=[WINDOW_PREFIX, "/blobs/"], remaining_faults=1, + slow_ms=SLOW_MS, trace_path_substring=[WINDOW_PREFIX, "/blobs/"], + ) + # A random body, so no earlier run stored it and the `PUT` is not skipped. + node.query("INSERT INTO long_body SELECT number, randomPrintableASCII(16) FROM numbers(1000)", timeout=60) + + stats = _stats() + dropped = stats["drop_after_forward"] + assert len(dropped) == 1, dropped + key = dropped[0]["path"] + assert dropped[0]["upstream_status"] == 200, dropped + trace = stats["trace"] + puts = [i for i, r in enumerate(trace) if r["method"] == "PUT" and r["path"] == key] + # The HEAD proves the landed body, so it is never sent again. + assert len(puts) == 1, trace + assert any(r["method"] == "HEAD" and r["path"] == key and r["status"] == 200 for r in trace[puts[0] + 1:]), trace + assert node.query("SELECT count() FROM long_body").strip() == "1000" + + +def _remount_attempts(node): + return int(node.query("SELECT sum(value) FROM system.events WHERE event = 'CASRemountAttempts'").strip()) + + +def test_slow_catalog_read_then_drop(node): + # GC is off for this disk. A remount also reads the catalog, so the test checks that none started. + _create(node, "slow_catalog") + node.query("INSERT INTO slow_catalog VALUES (1, 'x')") + remounts_before = _remount_attempts(node) + retries_before = node.count_in_log("Will retry later").strip() + _arm( + modes=["trickle"], methods=["GET"], path_substring=CATALOG, remaining_faults=1, + slow_ms=SLOW_MS, trace_path_substring=CATALOG, + ) + drop_started_ms = time.monotonic() * 1000.0 + drop = node.get_query_request("DROP TABLE slow_catalog SYNC", timeout=90) + + def settled(): + trace = _stats()["trace"] + return all(r["status"] is not None for r in trace) and all( + r["outcome"] is not None for r in trace if r["fault"] == "trickle") + + # A failed removal is requeued only after the 600 s cooldown and logs "Will retry later". + _wait_until(lambda: (drop.process.poll() is not None + or node.count_in_log("Will retry later").strip() != retries_before) and settled(), timeout=60) + trace = sorted(_stats()["trace"], key=lambda r: r["t_mono_ms"]) + assert _remount_attempts(node) == remounts_before + + slowed = trace[0] + assert slowed["fault"] == "trickle" and slowed["method"] == "GET" and slowed["status"] == 200, trace + first_put = next((i for i, r in enumerate(trace) if r["method"] == "PUT" and r["status"] == 200), None) + assert first_put is not None, trace + assert slowed["outcome"] == "delivered", trace + assert slowed["t_last_piece_mono_ms"] - slowed["t_mono_ms"] > WINDOW_S * 1000, trace + assert slowed["t_mono_ms"] >= drop_started_ms, (drop_started_ms, trace) + # The removal reads the catalog twice before its write; another attempt of the slowed read would + # add a GET here. + prefix = trace[:first_put + 1] + assert len(prefix) == 3, trace + assert prefix[1]["method"] == "GET" and prefix[1]["status"] == 200, trace + assert prefix[1]["t_mono_ms"] > slowed["t_last_piece_mono_ms"], trace + assert node.count_in_log("Will retry later").strip() == retries_before + drop.get_answer() + + +def test_failing_catalog_read_gives_up_at_its_window(node): + """Every catalog request answers 503. The `CREATE TABLE` fails in its first catalog read, which gives up at its + request window: every attempt of that read is a `GET` sent within the window from the first one, and nothing is + sent after it. One operation only, so this does not show that a later operation gets a window of its own.""" + _arm(modes=["503"], methods=["GET", "PUT", "HEAD"], path_substring=CATALOG, trace_path_substring=CATALOG) + error = node.query_and_get_error("CREATE TABLE failing (id UInt64) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}'".format(POLICY)) + assert re.search(r"read of '[^']*ref_catalog': gave up at the policy deadline after (\d+|zero|one or more) " + r"attempt\(s\)", error), error + + # The slack covers scheduling only. Waiting it out on the proxy's clock lets a late attempt show up. + first_ms = _stats()["trace"][0]["t_mono_ms"] + window_end_ms = first_ms + WINDOW_S * 1000 + 500 + _wait_until(lambda: _stats()["now_mono_ms"] > window_end_ms, timeout=2 * WINDOW_S) + trace = _stats()["trace"] + assert len(trace) > 1 and all(r["method"] == "GET" and r["status"] == 503 for r in trace), trace + assert not [r for r in trace if r["t_mono_ms"] > window_end_ms], trace + + +def _rule(method, path_substring, action, count=1, body_substring=None): + return {"method": method, "path_substring": path_substring, "action": action, "count": count, + "body_substring": body_substring} + + +def _arm_rules(rules): + _control(cluster.proxy_url, "/config", + {"rules": rules, "trace": True, "trace_path_substring": STOP_PREFIX, "trace_bodies": True}) + + +def _create_sql(name): + return "CREATE TABLE {} (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " \ + "SETTINGS storage_policy = '{}'".format(name, STOP_POLICY) + + +def _stop_and_release(node, query_id, path_substring, respond="forward", kill=True): + """Parked request, stop, `is_cancelled`, release: nothing the stopped query does after the release + can predate the stop. Returns the release time on the proxy's clock.""" + parked = _wait_until( + lambda: [p for p in _control(cluster.proxy_url, "/parked")["parked"] if path_substring in p["path"]], timeout=60) + assert len(parked) == 1, parked + # The release must reach the parked request before its socket times out, or the stopped query sees a timeout + # instead of the released answer. Killed and polled over HTTP: a client start per query is slow in a sanitizer + # build. + if kill: + node.http_query("KILL QUERY WHERE query_id = '{}' ASYNC".format(query_id)) + # `ASYNC` returns before the query is marked cancelled. + _wait_until(lambda: node.http_query( + "SELECT is_cancelled FROM system.processes WHERE query_id = '{}'".format(query_id)).strip() == "1", + timeout=STOP_ATTEMPT_TIMEOUT_S - 1) + _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": respond}) + released = [r for r in _stats()["trace"] if r["t_release_mono_ms"] is not None] + assert len(released) == 1, released + return released[0]["t_release_mono_ms"] + + +def _catalog_puts(trace): + return [r for r in trace if r["method"] == "PUT" and r["path"].startswith(STOP_CATALOG)] + + +def _remaining_counts(): + return [r["count"] for r in _stats()["rules"]] + + +def _events(node, event): + return int(node.query("SELECT sum(value) FROM system.events WHERE event = '{}'".format(event)).strip()) + + +def _stop_settings(stop): + return {"max_execution_time": 3, "timeout_overflow_mode": "throw"} if stop == "timeout" else None + + +def _catalog_entries(record): + """The namespace entries of a traced catalog `PUT`, parsed from its body.""" + entries = (json.loads(line) for line in (record["body"] or "").splitlines()) + return [e for e in entries if e.get("kind") == "entry"] + + +def _namespace_of(trace, life): + namespaces = {e["ns"] for r in _catalog_puts(trace) for e in _catalog_entries(r) if e["life"] == life} + assert len(namespaces) == 1, (life, namespaces) + return namespaces.pop() + + +def _life_of(trace, uuid): + """The namespace life that the catalog writes in `trace` give the table with `uuid`. A temporary table's + namespace carries the UUID URL-encoded.""" + forms = (uuid, uuid.replace("-", "%2D")) + lives = {e["life"] for r in _catalog_puts(trace) for e in _catalog_entries(r) if any(f in e["ns"] for f in forms)} + assert len(lives) == 1, (uuid, lives) + return lives.pop() + + +def _table_uuid(node, name): + return node.query("SELECT uuid FROM system.tables WHERE database = 'default' AND name = '{}'".format(name)).strip() + + +def _create_with_life(node, name): + """Creates `name` on `STOP_POLICY` and returns its namespace life.""" + _arm_rules([]) + seen = len(_stats()["trace"]) + node.query(_create_sql(name)) + return _life_of(_stats()["trace"][seen:], _table_uuid(node, name)) + + +def _stored_lines(node, path): + """The text lines of the compressed object at `path`, read from the store past the proxy.""" + return node.http_query( + "SELECT line FROM s3('{}{}', 'clickhouse', 'clickhouse', 'LineAsString', 'line String', 'zstd') " + "FORMAT TSVRaw".format(STORE_URL, path.split("?")[0])).splitlines() + + +def _landed_log_records(trace, life): + return [r for r in trace if r["method"] == "PUT" and r["status"] == 200 + and "cas/ns/stream/{}/_log/".format(life) in r["path"]] + + +def _log_ops(node, record): + """The operations of a landed ref-log record.""" + return [json.loads(line) for line in _stored_lines(node, record["path"]) if line.startswith('{"op"')] + + +def _removal_records(node, trace, life): + """The landed ref-log records of `life` in `trace` that carry the terminal `remove_namespace` operation and + follow a landed catalog write that moved `life` to `Removing`.""" + marked = [r["t_mono_ms"] for r in _catalog_puts(trace) + if r["status"] == 200 and _removing_body(life) in (r["body"] or "")] + if not marked: + return [] + return [r for r in _landed_log_records(trace, life) if r["t_mono_ms"] > marked[0] + and any(op["op"] == "remove_namespace" for op in _log_ops(node, r))] + + +def _brief(trace): + """`trace` without request bodies, for an assertion message.""" + return [(r["method"], r["path"], r["status"], r["rule"]) for r in trace] + + +def _removing_body(life): + """A substring of exactly the catalog writes that name `life` as `Removing`.""" + return '"state":"removing","life":"{}"'.format(life) + + +@pytest.mark.parametrize("stop", ["kill", "timeout"]) +def test_stop_after_accepted_conflicts_permits_next_put(node_stop, stop): + """Three `PUT`s of a catalog write meet 412; the read before the fourth is parked while the query stops and then + succeeds. An accepted conflict is an answer, not a failure, so the fourth `PUT` is sent and lands.""" + rules = [] + for action in ("forward", "forward", "hold"): + rules += [_rule("PUT", STOP_CATALOG, "412"), _rule("GET", STOP_CATALOG, action)] + _arm_rules(rules) + query_id = "accepted_conflicts_" + stop + request = node_stop.get_query_request( + _create_sql(query_id), query_id=query_id, settings=_stop_settings(stop), timeout=120) + released_ms = _stop_and_release(node_stop, query_id, STOP_CATALOG, kill=(stop == "kill")) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + puts = _catalog_puts(trace) + assert [r["status"] for r in puts[:4]] == [412, 412, 412, 200], trace + assert puts[3]["t_mono_ms"] > released_ms, trace + assert _remaining_counts() == [0] * 6 + # Whether the stopped `CREATE` still reports its stop after the catalog write is outside CAS. + _, error = request.get_answer_and_error() + if request.process.returncode != 0: + assert re.search(r"Code: {}\b".format(394 if stop == "kill" else 159), error), error + + +@pytest.mark.parametrize("stop", ["kill", "timeout"]) +def test_failed_read_after_a_lost_race_and_stop_starts_no_further_put(node_stop, stop): + """A catalog write meets 412, and the next catalog read is parked while the query stops, then answered with 503. + No further `PUT` is sent. A write decided on the lane's cached catalog has its 412 settled by that read, and the + call ends with the conflict the read could not resolve. A write decided on a fresh read is retried at once without + settling, so the parked read is the one before the next attempt, and the call ends with that read's error: the + query's own stop.""" + + def lose_race_then_fail_the_read(suffix): + _control(cluster.proxy_url, "/config", {"reset": True}) + _arm_rules([_rule("PUT", STOP_CATALOG, "412"), _rule("GET", STOP_CATALOG, "hold"), + _rule("PUT", STOP_CATALOG, "412", count=1000)]) + query_id = "failed_read_{}_{}".format(suffix, stop) + request = node_stop.get_query_request( + _create_sql(query_id), query_id=query_id, settings=_stop_settings(stop), timeout=120) + released_ms = _stop_and_release(node_stop, query_id, STOP_CATALOG, respond="503", kill=(stop == "kill")) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + assert [r["status"] for r in _catalog_puts(trace)] == [412], trace + assert not [r for r in _catalog_puts(trace) if r["t_mono_ms"] > released_ms], trace + assert _remaining_counts() == [0, 0, 1000] + return request.get_error() + + # A table created without faults leaves the lane holding the catalog it wrote. + _control(cluster.proxy_url, "/config", {"reset": True}) + node_stop.query(_create_sql("failed_read_warm_" + stop), timeout=120) + error = lose_race_then_fail_the_read("cached") + # `ABORTED`: the conflict the settling read could not resolve. + assert re.search(r"Code: 236\b", error) and "conflict" in error, error + + # That conflict observed nothing, so the lane keeps no catalog and the next write starts from a read. + error = lose_race_then_fail_the_read("fresh") + assert re.search(r"Code: {}\b".format(394 if stop == "kill" else 159), error), error + + +def test_kill_after_ambiguous_create_keeps_unresolved_exit(node_stop): + _arm_rules([_rule("PUT", STOP_CATALOG, "503"), _rule("GET", STOP_CATALOG, "hold")]) + query_id = "ambiguous_create" + request = node_stop.get_query_request(_create_sql("ambiguous_create"), query_id=query_id, timeout=120) + _stop_and_release(node_stop, query_id, STOP_CATALOG) + _wait_until(lambda: request.process.poll() is not None or len(_catalog_puts(_stats()["trace"])) > 1, timeout=60) + trace = _stats()["trace"] + assert [r["status"] for r in _catalog_puts(trace)] == [503], trace + error = request.get_error() + # The pause before the next decision vetoes it and returns the unresolved send. + assert re.search(r"Code: 210\b", error) and "the write is unresolved (sent" in error, error + assert _remaining_counts() == [0, 0] + + # Control: a live owner decides again after each ambiguous attempt until one lands. + _control(cluster.proxy_url, "/config", {"reset": True}) + _arm_rules([_rule("PUT", STOP_CATALOG, "503", count=8)]) + node_stop.query(_create_sql("ambiguous_create_live"), timeout=120) + statuses = [r["status"] for r in _catalog_puts(_stats()["trace"])] + assert statuses[:9] == [503] * 8 + [200], statuses + assert _remaining_counts() == [0] + assert node_stop.query("EXISTS TABLE ambiguous_create_live").strip() == "1" + + +def test_killed_leader_with_chunk_in_flight_leaves_a_usable_lane(node_stop): + """A killed ref-log leader whose chunk `PUT` fails settles it by a read that meets a 404. The S3 client + reports that 404 as the leader's stop, so the lane may need one recovery; a concurrent insert into the + table still commits and later inserts work. Whether the concurrent insert shares the leader's chunk is + not observable here.""" + life = _create_with_life(node_stop, "ref_batch") + wedged_before = _events(node_stop, "CASRefAppendWedged") + _arm_rules([_rule("PUT", [STOP_PREFIX, "cas/ns/stream/{}/_log/".format(life)], "hold")]) + # A synchronous insert appends from the query's own thread, so the kill reaches the chunk's leader. + sync = {"async_insert": 0} + leader = node_stop.get_query_request("INSERT INTO ref_batch VALUES (1, 'leader')", query_id="ref_batch_leader", + settings=sync, timeout=120) + _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + neighbor = node_stop.get_query_request("INSERT INTO ref_batch VALUES (2, 'neighbor')", settings=sync, timeout=120) + # The release answers 503 without forwarding, so the chunk's settling read meets a 404. + released_ms = _stop_and_release(node_stop, "ref_batch_leader", "/_log/", respond="503") + neighbor.get_answer() + _wait_until(lambda: leader.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + held = next(r for r in trace if r["rule"] == "hold") + assert held["status"] == 503, trace + assert [r for r in trace if r["method"] == "GET" and r["path"] == held["path"] and r["status"] == 404 + and r["t_mono_ms"] > released_ms], trace + assert _events(node_stop, "CASRefAppendWedged") <= wedged_before + 1, trace + assert _remaining_counts() == [0] + assert node_stop.query("SELECT count() FROM ref_batch WHERE id = 2").strip() == "1" + node_stop.query("INSERT INTO ref_batch VALUES (3, 'after')", settings=sync) + assert node_stop.query("SELECT count() FROM ref_batch WHERE id = 3").strip() == "1" + + +def test_atomic_sync_drop_kill_releases_only_waiter(node_stop): + """Killing `DROP TABLE ... SYNC` in an `Atomic` database stops only the waiting query. The background + removal keeps its parked catalog request and completes in the same attempt.""" + life = _create_with_life(node_stop, "atomic_sync_drop") + node_stop.query("INSERT INTO atomic_sync_drop VALUES (1, 'x')") + uuid = _table_uuid(node_stop, "atomic_sync_drop") + retries_before = node_stop.count_in_log("Will retry later").strip() + _arm_rules([_rule("PUT", STOP_CATALOG, "hold", body_substring=_removing_body(life))]) + seen = len(_stats()["trace"]) + query_id = "atomic_sync_drop" + request = node_stop.get_query_request("DROP TABLE atomic_sync_drop SYNC", query_id=query_id, timeout=120) + parked = _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + assert len(parked) == 1, parked + # Over HTTP: the parked write must still be parked when the kill returns. + node_stop.http_query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) + _wait_until(lambda: request.process.poll() is not None, timeout=30) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + assert _control(cluster.proxy_url, "/parked")["parked"] == parked + + _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) + _wait_until(lambda: node_stop.query( + "SELECT count() FROM system.dropped_tables WHERE uuid = '{}'".format(uuid)).strip() == "0", timeout=60) + _wait_until(lambda: _removal_records(node_stop, _stats()["trace"][seen:], life), timeout=60) + trace = _stats()["trace"][seen:] + assert [r["status"] for r in _catalog_puts(trace)] == [200], _brief(trace) + assert _remaining_counts() == [0] + assert node_stop.count_in_log("Will retry later").strip() == retries_before + + +def _active_parts(node, name): + return node.query("SELECT name FROM system.parts WHERE table = '{}' AND active ORDER BY name".format(name)) + + +def _detach_cold(node, name): + """Creates a one-part table of two rows, detaches it permanently and restarts the server so its ref table is not + cached. Returns the table's namespace life and its active parts before the detach.""" + life = _create_with_life(node, name) + node.query("INSERT INTO {} VALUES (1, 'a'), (2, 'b')".format(name)) + parts = _active_parts(node, name) + node.query("DETACH TABLE {} PERMANENTLY".format(name)) + node.restart_clickhouse() + _control(cluster.proxy_url, "/config", {"reset": True}) + return life, parts + + +def _assert_reattached(node, name, parts): + """Every part of `_detach_cold`'s table is active again, and none was detached as broken.""" + assert _active_parts(node, name) == parts + assert node.query("SELECT count() FROM {}".format(name)).strip() == "2" + assert _broken_on_start(node, name) == "0" + + +def _cold_attach_with_parked_walk(node, name, respond, settings=None): + """Runs `ATTACH TABLE` on `_detach_cold`'s table with the first `_log/` GET of its namespace life parked, stops + the query and releases the GET with `respond`. Returns the request, the life's id, the release time and the + active parts before the detach.""" + life, parts = _detach_cold(node, name) + _arm_rules([_rule("GET", [STOP_PREFIX, "cas/ns/stream/{}/_log/".format(life)], "hold")]) + request = node.get_query_request("ATTACH TABLE {}".format(name), query_id=name, settings=settings, timeout=120) + released_ms = _stop_and_release(node, name, "/_log/", respond=respond, kill=settings is None) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + return request, life, released_ms, parts + + +def _broken_on_start(node, name): + return node.query( + "SELECT count() FROM system.detached_parts WHERE table = '{}' AND reason = 'broken-on-start'".format(name)).strip() + + +def test_killed_cold_attach_keeps_parts_active(node_stop): + """A stopped `ATTACH TABLE` whose cold ref walk reads a healthy store, then a second `ATTACH` if the + stop ended the first one: every part is active. When the first `ATTACH` fails, it fails in the ref walk + before any part loads, so the `broken-on-start` check then covers only the second `ATTACH`.""" + request, _, _, parts = _cold_attach_with_parked_walk(node_stop, "cold_attach", respond="forward") + _, error = request.get_answer_and_error() + if request.process.returncode != 0: + assert re.search(r"Code: 394\b", error), error + node_stop.query("ATTACH TABLE cold_attach") + _assert_reattached(node_stop, "cold_attach", parts) + assert _remaining_counts() == [0] + + +def test_kill_during_cold_ref_walk(node_stop): + """An `ATTACH TABLE` whose query timed out while its cold ref walk failed ends without another walk; a + second query recovers the data. The timeout's 159 is a transient code, so only the owner check keeps + recovery from walking again.""" + request, life, released_ms, parts = _cold_attach_with_parked_walk( + node_stop, "cold_walk", respond="503", settings={"max_execution_time": 3, "timeout_overflow_mode": "throw"}) + error = request.get_error() + assert re.search(r"Code: 159\b", error), error + trace = _stats()["trace"] + assert not [r for r in trace if life in r["path"] and r["t_mono_ms"] > released_ms], trace + node_stop.query("ATTACH TABLE cold_walk") + _assert_reattached(node_stop, "cold_walk", parts) + + +def test_kill_in_recovery_backoff_keeps_the_store_error(node_stop): + """A cold `ATTACH TABLE` whose ref walk failed on store errors while the query was live, killed in the backoff + before the next walk: no other walk starts, and the query ends with the walk's own retryable `NETWORK_ERROR`, not + with its stop. A second `ATTACH` loads every part, and none is detached as broken.""" + name = "backoff_kill" + life, parts = _detach_cold(node_stop, name) + # Every read of the life's log fails, so the walk fails once its request window passes. + _arm_rules([_rule("GET", [STOP_PREFIX, "cas/ns/stream/{}/_log/".format(life)], "503", count=1000)]) + + def recovery_retries(): + return int(node_stop.http_query( + "SELECT sum(value) FROM system.events WHERE event = 'CASRefRecoveryRetries'").strip() or 0) + + retries_before = recovery_retries() + request = node_stop.get_query_request("ATTACH TABLE {}".format(name), query_id=name, timeout=120) + # Counted right before the backoff, which lasts a second before the next walk. Polled and killed over HTTP: + # starting a client per poll or for the kill can take most of that second in a sanitizer build. + end = time.monotonic() + 60 + while recovery_retries() == retries_before: + assert time.monotonic() < end and request.process.poll() is None, "the walk did not fail" + time.sleep(0.02) + life_gets_at_kill = len([r for r in _stats()["trace"] if life in r["path"]]) + node_stop.http_query("KILL QUERY WHERE query_id = '{}' ASYNC".format(name)) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + error = request.get_error() + # The walk's own give-up on the life's log, not a retry-later of another request. + assert re.search(r"Code: 210\b", error) and re.search(r"_log/.*gave up at the \w+ deadline", error, re.DOTALL), error + assert len([r for r in _stats()["trace"] if life in r["path"]]) == life_gets_at_kill, "another walk started" + + _control(cluster.proxy_url, "/config", {"reset": True}) + node_stop.query("ATTACH TABLE {}".format(name)) + _assert_reattached(node_stop, name, parts) + + +def _blob_puts_after(trace, released_ms): + return [r for r in trace if r["method"] == "PUT" and "/blobs/" in r["path"] and r["t_mono_ms"] > released_ms] + + +def test_kill_while_blob_head_is_parked_publishes_nothing(node_stop): + """A query killed while the `HEAD` of its part's only blob, a new body, is parked: the `HEAD` is released and + answers 404, which the S3 client reports as the query's stop, so the upload ends with 394 before any publication + of that blob. No blob publication starts after the release, no part is committed, and the next insert succeeds. + An outcome test: the check before a publication is not reached here; the unit tests cover it.""" + node_stop.query("CREATE TABLE blob_head_kill {}".format(ONE_BLOB_TABLE)) + _arm_rules([_rule("HEAD", [STOP_PREFIX, "/blobs/"], "hold")]) + request, query_id = _blob_fixture_insert(node_stop, "blob_head_kill", ONE_BLOB_INSERT) + released_ms = _stop_and_release(node_stop, query_id, "/blobs/") + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + held = next(r for r in trace if r["rule"] == "hold") + assert held["status"] == 404, trace + assert not [r for r in trace if r["method"] == "PUT" and r["path"] == held["path"]], trace + assert not _blob_puts_after(trace, released_ms), trace + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + assert _remaining_counts() == [0] + assert node_stop.query("SELECT count() FROM blob_head_kill").strip() == "0" + + node_stop.query("INSERT INTO blob_head_kill VALUES (1, 'next')") + assert node_stop.query("SELECT count() FROM blob_head_kill").strip() == "1" + + +def _blob_requests(trace, method): + return [r for r in trace if r["method"] == method and "/blobs/" in r["path"]] + + +# One blob per part: a packed part keeps every file in `data.packed`. +ONE_BLOB_TABLE = "(id UInt64, payload String) ENGINE = MergeTree ORDER BY id " \ + "SETTINGS storage_policy = '{}', min_bytes_for_full_part_storage = '1G'".format(STOP_POLICY) +ONE_BLOB_INSERT = "INSERT INTO {} SELECT number, randomPrintableASCII(100) FROM numbers(10000)" +# Two new blobs per part: the `Wide` column bodies are random. Uncompressed fixed-length values make the marks and +# the index the same in every part, so after the first part they are reused and only answer a `HEAD`. The second +# argument of `randomPrintableASCII` keeps the two calls distinct: one call would give both columns one body. +TWO_BLOB_TABLE = "(a String CODEC(NONE), b String CODEC(NONE)) ENGINE = MergeTree ORDER BY tuple() " \ + "SETTINGS storage_policy = '{}', min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0, " \ + "min_bytes_for_full_part_storage = 0".format(STOP_POLICY) +TWO_BLOB_INSERT = "INSERT INTO {} SELECT randomPrintableASCII(100, 1), randomPrintableASCII(100, 2) FROM numbers(10000)" + + +def _checked_blob_fixture(node, name, table, insert, new_blobs): + """Creates `name`, after checking on two other tables of the same shape that an insert of `insert` publishes + exactly `new_blobs` blobs and reuses every other one. The first of them stores the reusable bodies.""" + for suffix in ("_warm", "_control"): + node.query("CREATE TABLE {}{} {}".format(name, suffix, table)) + _arm_rules([]) + node.query(insert.format(name + "_warm"), settings={"async_insert": 0}) + seen = len(_stats()["trace"]) + node.query(insert.format(name + "_control"), settings={"async_insert": 0}) + trace = _stats()["trace"][seen:] + puts = sorted({r["path"] for r in _blob_requests(trace, "PUT")}) + missing = sorted({r["path"] for r in _blob_requests(trace, "HEAD") if r["status"] == 404}) + assert len(puts) == new_blobs and puts == missing, \ + "the fixture of {} publishes {} blob(s), not {}: PUT {}, HEAD 404 {}".format(name, len(puts), new_blobs, puts, missing) + node.query("CREATE TABLE {} {}".format(name, table)) + _control(cluster.proxy_url, "/config", {"reset": True}) + + +def _blob_fixture_insert(node, name, insert): + query_id = name + "_insert" + request = node.get_query_request(insert.format(name), query_id=query_id, settings={"async_insert": 0}, timeout=120) + return request, query_id + + +def test_kill_during_last_blob_upload_commits_the_part(node_stop): + """The insert's part has one blob. A query killed while its `PUT` is parked: the `PUT` is released and lands, and + adoption, promotion and the part rename are no safe points and meet no failure, so the part is committed. No blob + publication starts after the release.""" + name = "blob_last_put_kill" + _checked_blob_fixture(node_stop, name, ONE_BLOB_TABLE, ONE_BLOB_INSERT, new_blobs=1) + _arm_rules([_rule("PUT", [STOP_PREFIX, "/blobs/"], "hold")]) + request, query_id = _blob_fixture_insert(node_stop, name, ONE_BLOB_INSERT) + released_ms = _stop_and_release(node_stop, query_id, "/blobs/") + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + puts = _blob_requests(trace, "PUT") + assert [(r["rule"], r["status"]) for r in puts] == [("hold", 200)], trace + assert not _blob_puts_after(trace, released_ms), trace + _, error = request.get_answer_and_error() + # The query may still report its kill once the part is committed. + if request.process.returncode != 0: + assert re.search(r"Code: 394\b", error), error + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "10000" + assert _remaining_counts() == [0] + + node_stop.query("INSERT INTO {} VALUES (100000, 'next')".format(name)) + assert node_stop.query("SELECT count() FROM {} WHERE id = 100000".format(name)).strip() == "1" + + +def test_kill_during_first_blob_upload_publishes_no_later_blob(node_stop): + """The insert's part has two new blobs, published one after another. A query killed while the first `PUT` is + parked: the `PUT` is released and lands, then the second blob's `HEAD` answers 404, which the S3 client reports as + the query's stop. The second blob is not published, the insert ends with 394 and commits nothing.""" + name = "blob_first_put_kill" + _checked_blob_fixture(node_stop, name, TWO_BLOB_TABLE, TWO_BLOB_INSERT, new_blobs=2) + _arm_rules([_rule("PUT", [STOP_PREFIX, "/blobs/"], "hold")]) + request, query_id = _blob_fixture_insert(node_stop, name, TWO_BLOB_INSERT) + released_ms = _stop_and_release(node_stop, query_id, "/blobs/") + _wait_until(lambda: request.process.poll() is not None, timeout=60) + trace = _stats()["trace"] + held = next(r for r in trace if r["rule"] == "hold") + assert held["status"] == 200, trace + later_misses = [r for r in _blob_requests(trace, "HEAD") + if r["t_mono_ms"] > released_ms and r["path"] != held["path"] and r["status"] == 404] + assert len(later_misses) == 1, trace + assert not [r for r in _blob_requests(trace, "PUT") if r["path"] == later_misses[0]["path"]], trace + assert not _blob_puts_after(trace, released_ms), trace + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "0" + assert _remaining_counts() == [0] + + node_stop.query("INSERT INTO {} VALUES ('next', 'next')".format(name)) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "1" + + +LIFE_LOG = re.compile(r"cas/ns/stream/([0-9a-f]+)/_log/") + + +def _landed_log_puts(trace): + """The lives of the ref-log `PUT`s in `trace` that landed.""" + return [m.group(1) for r in trace if r["method"] == "PUT" and r["status"] == 200 + for m in [LIFE_LOG.search(r["path"])] if m] + + +def _killed_after_first_ref_append(node, query_id, sql, settings): + """Runs `sql`, which creates a table and writes one part per second into it, and kills it once a ref-log append + has landed, so the query owns committed CAS work when it stops. Merges are stopped meanwhile. Returns the request + after the query ended, the life of the first append, which the caller attributes, and the length of the proxy + trace when the kill was sent.""" + node.query("SYSTEM STOP MERGES") + try: + _arm_rules([]) + seen = len(_stats()["trace"]) + request = node.get_query_request(sql, query_id=query_id, settings=settings, timeout=120) + appended = _wait_until(lambda: _landed_log_puts(_stats()["trace"][seen:]), timeout=60) + killed_at = len(_stats()["trace"]) + node.query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + finally: + node.query("SYSTEM START MERGES") + return request, appended[0], killed_at + + +ONE_PART_PER_SECOND = {"max_block_size": 1, "max_insert_block_size": 1, "min_insert_block_size_rows": 0, + "min_insert_block_size_bytes": 0, "async_insert": 0} + + +ROLLED_BACK_CSN = 2**64 - 1 + + +def _rolled_back_installs(node, trace, life, part): + """The landed ref-log records of `life` in `trace` that install `part` with a manifest, also written in + `trace`, whose `txn_version.txt` carries the rolled-back creation CSN.""" + namespace = _namespace_of(_stats()["trace"], life) + rolled_back = set() + for r in trace: + if r["method"] == "PUT" and r["status"] == 200 and "/cas/manifests/" in r["path"]: + lines = _stored_lines(node, r["path"]) + header = json.loads(lines[1]) + if header["namespace"] == namespace and "creation_csn: {}".format(ROLLED_BACK_CSN) in lines: + rolled_back.add((header["epoch"], header["build"])) + return [r for r in _landed_log_records(trace, life) for op in _log_ops(node, r) + if op.get("new_ref") == part and (op["new_epoch"], op["new_build"]) in rolled_back] + + +def test_killed_implicit_transaction_insert_rolls_back(node_stop): + """An `INSERT` in an implicit transaction killed after the transaction registered a part it created: the + transaction rolls back and persists that part's rolled-back version. A ref-log record that lands after the kill + and before the query ends installs the registered part with a manifest whose `txn_version.txt` carries the + rolled-back creation CSN. Only the row inserted before remains, the server keeps running, and the next + transactional insert succeeds.""" + name = "txn_kill" + life = _create_with_life(node_stop, name) + try: + node_stop.query("SYSTEM STOP MERGES") + node_stop.query("INSERT INTO {} VALUES (1000, 'first')".format(name)) + fatal_before = int(node_stop.count_in_log("").strip()) + query_id = "txn_kill_insert" + request = node_stop.get_query_request( + "INSERT INTO {} SELECT number, 'x' FROM numbers(30) WHERE sleepEachRow(1) = 0".format(name), + query_id=query_id, settings=dict(ONE_PART_PER_SECOND, implicit_transaction=1), timeout=120) + # A part of an uncommitted transaction is active with an unknown CSN once the transaction registered it. + registered = _wait_until(lambda: node_stop.query( + "SELECT name FROM system.parts WHERE table = '{}' AND active AND creation_csn = 0 LIMIT 1".format(name)).strip(), + timeout=60) + killed_at = len(_stats()["trace"]) + node_stop.query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + ended_at = len(_stats()["trace"]) + # A merge of transactional parts is not supported on a CAS disk. + node_stop.query("SYSTEM STOP MERGES {}".format(name)) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + window = _stats()["trace"][killed_at:ended_at] + assert _rolled_back_installs(node_stop, window, life, registered), (registered, window) + # The cleanup may already have removed the rolled-back part. + csn = node_stop.query( + "SELECT creation_csn FROM system.parts WHERE table = '{}' AND name = '{}'".format(name, registered)).strip() + assert csn in ("", str(ROLLED_BACK_CSN)), (registered, csn) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "1" + assert int(node_stop.count_in_log("").strip()) == fatal_before + + node_stop.query("INSERT INTO {} VALUES (100, 'next')".format(name), + settings={"implicit_transaction": 1, "async_insert": 0}) + assert node_stop.query("SELECT count() FROM {}".format(name)).strip() == "2" + finally: + # Its transactional parts must not meet a merge in a later test, and a server-wide `START MERGES` lifts + # the table's own stop. + try: + node_stop.query("DROP TABLE IF EXISTS {} SYNC".format(name)) + finally: + node_stop.query("SYSTEM START MERGES") + + +def _holder_errors(node): + return int(node.count_in_log(" TemporaryTableHolder").strip()) + + +def _temporary_table_dropped(node, uuid): + """The storage of the temporary table with `uuid` finished dropping its data.""" + return node.count_in_log("({}): dropAllData: done.".format(uuid)).strip() == "1" + + +def test_killed_temporary_table_query_is_dropped_at_disconnect(node_stop): + """A `CREATE TEMPORARY TABLE ... AS SELECT` on a CAS disk killed after it committed a part fails with 394 and + leaves the table in its session. The table is dropped when the client disconnects: its namespace moves to + `Removing` in the catalog, its ref log ends with the terminal record, its storage finishes dropping, and the + server keeps running.""" + fatal_before = int(node_stop.count_in_log("").strip()) + holder_errors_before = _holder_errors(node_stop) + request, life, killed_at = _killed_after_first_ref_append( + node_stop, "temporary_kill", + "CREATE TEMPORARY TABLE temporary_kill (id UInt64, payload String) ENGINE = MergeTree ORDER BY id " + "SETTINGS storage_policy = '{}' AS SELECT number, 'x' FROM numbers(30) WHERE sleepEachRow(1) = 0".format(STOP_POLICY), + ONE_PART_PER_SECOND) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + namespace = _namespace_of(_stats()["trace"], life) + temporary = re.search(r"/_temporary_and_external_tables/_tmp_([0-9a-f%D]+)@cas@$", namespace) + assert temporary, namespace + uuid = temporary.group(1).replace("%2D", "-") + _wait_until(lambda: _removal_records(node_stop, _stats()["trace"][killed_at:], life), timeout=60) + _wait_until(lambda: _temporary_table_dropped(node_stop, uuid), timeout=60) + # A failed drop is logged by the holder and leaves the table attached. + assert _holder_errors(node_stop) == holder_errors_before + assert int(node_stop.count_in_log("").strip()) == fatal_before + assert node_stop.query("SELECT 1").strip() == "1" + + +def test_killed_replace_of_a_temporary_table_drops_the_replaced_table(node_stop): + """`REPLACE TEMPORARY TABLE` on a CAS disk killed while it fills the new table, after it committed a part. The + query ends with 394 and the session keeps the new table. The replaced table is dropped: its namespace moves to + `Removing` in the catalog, its ref log ends with the terminal record, its storage finishes dropping, and the + server keeps running. GC erases the catalog row later; it is off on this disk.""" + session = {"session_id": "replace_temporary_kill"} + table = "(id UInt64, payload String) ENGINE = MergeTree ORDER BY id SETTINGS storage_policy = '{}'".format(STOP_POLICY) + + def session_query(sql, **params): + return node_stop.http_query(sql, params=dict(session, **params), method="POST") + + def table_uuid(): + return session_query("SELECT uuid FROM system.tables WHERE is_temporary AND name = 'replace_kill'").strip() + + try: + _arm_rules([]) + session_query("CREATE TEMPORARY TABLE replace_kill {}".format(table)) + node_stop.query("SYSTEM STOP MERGES") + session_query("INSERT INTO replace_kill VALUES (1, 'x')") + replaced_uuid = table_uuid() + replaced_life = _life_of(_stats()["trace"], replaced_uuid) + fatal_before = int(node_stop.count_in_log("").strip()) + holder_errors_before = _holder_errors(node_stop) + + query_id = "replace_temporary_kill" + seen = len(_stats()["trace"]) + outcome = {} + + def replace(): + outcome["answer"], outcome["error"] = node_stop.http_query_and_get_answer_with_error( + "REPLACE TEMPORARY TABLE replace_kill {} AS SELECT number, 'y' FROM numbers(30) WHERE sleepEachRow(1) = 0" + .format(table), params=dict(session, query_id=query_id, wait_end_of_query=1, **ONE_PART_PER_SECOND), + method="POST", timeout=120) + + thread = threading.Thread(target=replace) + thread.start() + try: + # The fill starts after the session swapped in the new table, so a part of another life is the fill's. + _wait_until(lambda: [life for life in _landed_log_puts(_stats()["trace"][seen:]) if life != replaced_life], + timeout=60) + killed_at = len(_stats()["trace"]) + node_stop.query("KILL QUERY WHERE query_id = '{}' SYNC".format(query_id)) + finally: + thread.join(timeout=120) + assert not thread.is_alive(), "the killed REPLACE did not return" + assert re.search(r"Code: 394\b", outcome["error"] or ""), outcome + + _wait_until(lambda: _removal_records(node_stop, _stats()["trace"][killed_at:], replaced_life), timeout=60) + _wait_until(lambda: _temporary_table_dropped(node_stop, replaced_uuid), timeout=60) + assert _holder_errors(node_stop) == holder_errors_before + new_uuid = table_uuid() + assert new_uuid and new_uuid != replaced_uuid, (replaced_uuid, new_uuid) + assert int(node_stop.count_in_log("").strip()) == fatal_before + assert node_stop.query("SELECT 1").strip() == "1" + finally: + node_stop.query("SYSTEM START MERGES") + # Dropped now rather than when the session expires or the server stops, during a later test. + session_query("DROP TEMPORARY TABLE IF EXISTS replace_kill") + + +def test_manual_gc_kill_preserves_owner_code(node_gc): + """A killed `SYSTEM CAS GC RUN` whose drain's first catalog `GET` is parked returns 394 and sends no + request of that round after the release. Mount renewals and `gc/hb` pulses continue and are not counted.""" + node_gc.query("CREATE TABLE gc_kill (id UInt64) ENGINE = MergeTree ORDER BY id SETTINGS storage_policy = 'cas_gc'") + node_gc.query("INSERT INTO gc_kill VALUES (1)") + # The first round adopts a generation; only then does a round's drain read the catalog. + first = json.loads(node_gc.http_query("SYSTEM CAS GC RUN {}".format(GC_DISK), + params={"default_format": "JSONEachRow"}, method="POST")) + assert first["acquired_lease"] in (1, True), first + catalog = GC_POOL + "/cas/ref_catalog" + _control(cluster.proxy_url, "/config", + {"rules": [_rule("GET", catalog, "hold")], "trace": True, "trace_path_substring": GC_POOL}) + query_id = "manual_gc_kill" + request = node_gc.get_query_request("SYSTEM CAS GC RUN {}".format(GC_DISK), query_id=query_id, timeout=120) + released_ms = _stop_and_release(node_gc, query_id, catalog) + _wait_until(lambda: request.process.poll() is not None, timeout=60) + error = request.get_error() + assert re.search(r"Code: 394\b", error), error + late = [r for r in _stats()["trace"] if r["t_mono_ms"] > released_ms + and not r["path"].endswith("/mount") and "/gc/hb" not in r["path"]] + assert not late, late + assert _remaining_counts() == [0] + + +def test_shutdown_hands_atomic_drop_to_restart(node_stop): + """Server shutdown stops the background removal of a dropped table after its `Live -> Removing` write and + before the terminal ref-log record, so the dropped metadata survives the exit and the removal finishes + after restart. One SIGTERM to the exact server PID: a second one, or SIGKILL, would end the process + without the orderly shutdown under test.""" + name = "shutdown_drop" + life = _create_with_life(node_stop, name) + node_stop.query("INSERT INTO {} VALUES (1, 'x')".format(name)) + life_log = "cas/ns/stream/{}/_log/".format(life) + uuid = _table_uuid(node_stop, name) + # The database disk may be remote, so the dropped metadata is followed through the log, not the local filesystem. + metadata_removed = "Removing metadata .*{}.sql of dropped table".format(uuid) + removed_before = int(node_stop.count_in_log(metadata_removed).strip()) + stopped_before = int(node_stop.count_in_log("removal stopped by server shutdown").strip()) + shutting_down_before = int(node_stop.count_in_log("Waiting for current connections to close").strip()) + fatal_before = int(node_stop.count_in_log("").strip()) + # Taken before the hold, so only the kill and the log poll run before the parked `PUT`'s attempt timeout. + pid = node_stop.get_process_pid("clickhouse") + assert pid is not None + + _control(cluster.proxy_url, "/config", {"reset": True}) + # Only this table's `Live -> Removing` write names its life as `Removing`. + _arm_rules([_rule("PUT", STOP_CATALOG, "hold", body_substring=_removing_body(life))]) + node_stop.query("DROP TABLE {}".format(name)) + parked = _wait_until(lambda: _control(cluster.proxy_url, "/parked")["parked"], timeout=60) + assert len(parked) == 1, parked + node_stop.exec_in_container(["bash", "-c", "kill -15 {}".format(pid)], user="root") + # Logged right after `IsServerShuttingDown` is set, so the removal resumes under shutdown. + _wait_until(lambda: int(node_stop.count_in_log("Waiting for current connections to close").strip()) + > shutting_down_before, timeout=30) + _control(cluster.proxy_url, "/release", {"id": parked[0]["id"], "respond": "forward"}) + released_ms = [r for r in _stats()["trace"] if r["t_release_mono_ms"] is not None][0]["t_release_mono_ms"] + _wait_until(lambda: node_stop.get_process_pid("clickhouse") is None, timeout=60) + + trace = _stats()["trace"] + held = next(r for r in trace if r["rule"] == "hold") + assert held["path"].startswith(STOP_CATALOG) and held["status"] == 200, trace + assert _removing_body(life) in held["body"], held + assert [r for r in trace if r["method"] == "PUT" and life_log in r["path"] and r["status"] == 200 + and r["t_mono_ms"] < held["t_mono_ms"]], trace + assert not [r for r in trace if r["method"] == "PUT" and life_log in r["path"] and r["t_mono_ms"] > released_ms], trace + assert int(node_stop.count_in_log(metadata_removed).strip()) == removed_before + assert int(node_stop.count_in_log("removal stopped by server shutdown").strip()) > stopped_before + # A crash during shutdown also ends the process; an orderly exit logs nothing fatal. + assert int(node_stop.count_in_log("").strip()) == fatal_before + + restarted_ms = _stats()["trace"][-1]["t_mono_ms"] + node_stop.start_clickhouse() + # Only metadata that survived the exit can be found and removed by the restarted server. + _wait_until(lambda: int(node_stop.count_in_log(metadata_removed).strip()) > removed_before, timeout=60) + assert node_stop.query("SELECT count() FROM system.dropped_tables WHERE uuid = '{}'".format(uuid)).strip() == "0" + + def appended_through_terminal(): + appended = [r for r in _stats()["trace"] + if r["t_mono_ms"] > restarted_ms and r["method"] == "PUT" and life_log in r["path"]] + terminal = [r for r in appended if r["status"] == 200 and _log_ops(node_stop, r)[-1]["op"] == "remove_namespace"] + return appended if terminal else None + + # The retried removal may seal the previous writer epoch first. + appended = _wait_until(appended_through_terminal, timeout=60) + assert all(r["status"] == 200 for r in appended), _brief(appended)