diff --git a/Cargo.lock b/Cargo.lock index cade81dc4f9..89207e473bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6185,7 +6185,7 @@ dependencies = [ [[package]] name = "greptime-proto" version = "0.1.0" -source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f#c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f" +source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=8aa45418597636516410c0c892dbd0269754a02c#8aa45418597636516410c0c892dbd0269754a02c" dependencies = [ "prost 0.14.1", "prost-types 0.14.1", diff --git a/Cargo.toml b/Cargo.toml index a6083acf70e..f6b7a6812e1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -164,7 +164,7 @@ fs2 = "0.4" fst = "0.4.7" futures = "0.3" futures-util = "0.3" -greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f" } +greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "8aa45418597636516410c0c892dbd0269754a02c" } hdfs-native = "0.14.6" hex = "0.4" hostname = "0.4.0" diff --git a/src/common/function/src/admin.rs b/src/common/function/src/admin.rs index 733abf17502..1852614bd08 100644 --- a/src/common/function/src/admin.rs +++ b/src/common/function/src/admin.rs @@ -14,6 +14,7 @@ mod build_index_table; mod cancel_region_compaction; +mod discard_pending_tails; mod discard_unflushed_data; mod flush_compact_region; mod flush_compact_table; @@ -37,6 +38,7 @@ use reconcile_table::ReconcileTableFunction; use crate::admin::build_index_table::{BuildIndexFunction, BuildSeriesIndexFunction}; use crate::admin::cancel_region_compaction::CancelRegionCompactionFunction; +use crate::admin::discard_pending_tails::DiscardPendingTailsFunction; use crate::admin::discard_unflushed_data::DiscardUnflushedDataFunction; use crate::flush_flow::FlushFlowFunction; use crate::function_registry::FunctionRegistry; @@ -66,6 +68,7 @@ impl AdminFunction { /// Register functions that must only be resolved by an ADMIN statement. pub fn register_admin_only(registry: &FunctionRegistry) { registry.register(DiscardUnflushedDataFunction::factory()); + registry.register(DiscardPendingTailsFunction::factory()); #[cfg(feature = "enterprise")] registry.register(PurgeTableFunction::factory()); } diff --git a/src/common/function/src/admin/discard_pending_tails.rs b/src/common/function/src/admin/discard_pending_tails.rs new file mode 100644 index 00000000000..0249d694bb2 --- /dev/null +++ b/src/common/function/src/admin/discard_pending_tails.rs @@ -0,0 +1,203 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use arrow::datatypes::DataType as ArrowDataType; +use common_error::ext::BoxedError; +use common_macro::admin_fn; +use common_query::error::{ + InvalidFuncArgsSnafu, MissingTableMutationHandlerSnafu, Result, TableMutationSnafu, + UnsupportedInputDataTypeSnafu, +}; +use datafusion_expr::Signature; +use datatypes::data_type::DataType; +use datatypes::prelude::*; +use session::context::QueryContextRef; +use session::table_name::table_name_to_full_name; +use snafu::{ResultExt, ensure}; +use store_api::storage::RegionId; +use table::table_name::TableName; + +use crate::handlers::TableMutationHandlerRef; +use crate::helper::{cast_u64, one_of_sigs2}; + +/// Discards the pending WAL tails that a datanode wrote from a region or from all regions +/// of a table, without replaying them. Returns the number of discarded tails. +/// +/// A region's flushed entry id is raised to the largest bound of the tails it discards. Where +/// the WAL checks its history when a region opens, as the object-store WAL does after the +/// datanode restarts, the region then opens only if the WAL of the datanode that leads the +/// region holds history through that bound, unless the WAL is configured to accept missing +/// history, which opens the region and loses its writes that were not flushed. The function +/// does not check this: whoever records the tails ensures it. +/// +/// - `region_id` or `table_name`: the region or the table. +/// - `node_id`: the datanode that wrote the tails. +#[admin_fn( + name = DiscardPendingTailsFunction, + display_name = discard_pending_tails, + sig_fn = signature, + ret = uint64, + single_row +)] +pub(crate) async fn discard_pending_tails( + table_mutation_handler: &TableMutationHandlerRef, + query_ctx: &QueryContextRef, + params: &[ValueRef<'_>], +) -> Result { + ensure!( + params.len() == 2, + InvalidFuncArgsSnafu { + err_msg: format!( + "The length of the args is not correct, expect 2, have: {}", + params.len() + ), + } + ); + let Some(node_id) = cast_u64(¶ms[1])? else { + return UnsupportedInputDataTypeSnafu { + function: "discard_pending_tails", + datatypes: params + .iter() + .map(|value| value.data_type()) + .collect::>(), + } + .fail(); + }; + + let discarded = match params[0] { + ValueRef::String(table_name) => { + let (catalog_name, schema_name, table_name) = + table_name_to_full_name(table_name, query_ctx) + .map_err(BoxedError::new) + .context(TableMutationSnafu)?; + table_mutation_handler + .discard_pending_tails_by_table( + TableName::new(catalog_name, schema_name, table_name), + node_id, + query_ctx.clone(), + ) + .await? + } + _ => { + let Some(region_id) = cast_u64(¶ms[0])? else { + return UnsupportedInputDataTypeSnafu { + function: "discard_pending_tails", + datatypes: params + .iter() + .map(|value| value.data_type()) + .collect::>(), + } + .fail(); + }; + table_mutation_handler + .discard_pending_tails(RegionId::from_u64(region_id), node_id, query_ctx.clone()) + .await? + } + }; + + Ok(Value::from(discarded as u64)) +} + +fn signature() -> Signature { + let numerics = ConcreteDataType::numerics() + .into_iter() + .map(|data_type| data_type.as_arrow_type()) + .collect::>(); + let mut targets = numerics.clone(); + targets.push(ArrowDataType::Utf8); + one_of_sigs2(targets, numerics) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow::array::{StringArray, UInt64Array}; + use arrow::datatypes::{DataType, Field}; + use datafusion_expr::ColumnarValue; + + use super::*; + use crate::function::FunctionContext; + use crate::function_factory::ScalarFunctionFactory; + use crate::function_registry::{FUNCTION_REGISTRY, get_admin_function}; + + #[test] + fn test_discard_pending_tails_is_admin_only() { + assert!(get_admin_function("discard_pending_tails").is_some()); + assert!( + FUNCTION_REGISTRY + .get_function("discard_pending_tails") + .is_none() + ); + } + + /// Calls the function with `args`; the mock handler returns the node id for a region and + /// 42 plus the node id for a table. + async fn call(args: Vec<(ColumnarValue, DataType)>) -> datafusion_common::Result { + let factory: ScalarFunctionFactory = DiscardPendingTailsFunction::factory().into(); + let function = factory.provide(FunctionContext::mock()); + let (args, arg_fields): (Vec<_>, Vec<_>) = args + .into_iter() + .enumerate() + .map(|(i, (arg, data_type))| { + ( + arg, + Arc::new(Field::new(format!("arg_{i}"), data_type, false)), + ) + }) + .unzip(); + let args = datafusion::logical_expr::ScalarFunctionArgs { + args, + arg_fields, + return_field: Arc::new(Field::new("result", DataType::UInt64, false)), + number_rows: 1, + config_options: Arc::new(datafusion_common::config::ConfigOptions::default()), + }; + let ColumnarValue::Array(array) = function + .as_async() + .unwrap() + .invoke_async_with_args(args) + .await? + else { + panic!("expected array output"); + }; + Ok(array + .as_any() + .downcast_ref::() + .unwrap() + .value(0)) + } + + fn uint64(value: u64) -> (ColumnarValue, DataType) { + let array = Arc::new(UInt64Array::from(vec![value])); + (ColumnarValue::Array(array), DataType::UInt64) + } + + fn string(value: &str) -> (ColumnarValue, DataType) { + let array = Arc::new(StringArray::from(vec![value])); + (ColumnarValue::Array(array), DataType::Utf8) + } + + #[tokio::test] + async fn test_discard_pending_tails_of_region_or_table() { + assert_eq!(7, call(vec![uint64(99), uint64(7)]).await.unwrap()); + assert_eq!(49, call(vec![string("my_table"), uint64(7)]).await.unwrap()); + } + + #[tokio::test] + async fn test_discard_pending_tails_requires_two_arguments() { + let error = call(vec![uint64(99)]).await.unwrap_err(); + assert!(error.to_string().contains("expect 2, have: 1"), "{error}"); + } +} diff --git a/src/common/function/src/handlers.rs b/src/common/function/src/handlers.rs index 0c2491fce06..57c586d6688 100644 --- a/src/common/function/src/handlers.rs +++ b/src/common/function/src/handlers.rs @@ -91,6 +91,23 @@ pub trait TableMutationHandler: Send + Sync { table_name: TableName, ctx: QueryContextRef, ) -> Result; + + /// Discards the pending WAL tails that datanode `node_id` wrote from a table region. + async fn discard_pending_tails( + &self, + region_id: RegionId, + node_id: u64, + ctx: QueryContextRef, + ) -> Result; + + /// Discards the pending WAL tails that datanode `node_id` wrote from all regions of a + /// table. + async fn discard_pending_tails_by_table( + &self, + table_name: TableName, + node_id: u64, + ctx: QueryContextRef, + ) -> Result; } /// A trait for handling procedure service requests in `QueryEngine`. diff --git a/src/common/function/src/state.rs b/src/common/function/src/state.rs index c07d91b7fae..a9275774edf 100644 --- a/src/common/function/src/state.rs +++ b/src/common/function/src/state.rs @@ -223,6 +223,25 @@ impl FunctionState { ) -> Result { Ok(ROWS) } + + /// Returns the node id; the table form adds ROWS, so tests can tell the forms apart. + async fn discard_pending_tails( + &self, + _region_id: RegionId, + node_id: u64, + _ctx: QueryContextRef, + ) -> Result { + Ok(node_id as AffectedRows) + } + + async fn discard_pending_tails_by_table( + &self, + _table_name: TableName, + node_id: u64, + _ctx: QueryContextRef, + ) -> Result { + Ok(ROWS + node_id as AffectedRows) + } } #[async_trait] diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index fbfa7ad57de..dbebb91473d 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -1988,6 +1988,7 @@ impl RegionServerInner { | RegionRequest::Flush(_) | RegionRequest::Compact(_) | RegionRequest::CancelCompaction(_) + | RegionRequest::DiscardPendingTails(_) | RegionRequest::Truncate(_) | RegionRequest::BuildIndex(_) | RegionRequest::EnterStaging(_) diff --git a/src/metric-engine/src/engine.rs b/src/metric-engine/src/engine.rs index ea307a21053..d08bff76c07 100644 --- a/src/metric-engine/src/engine.rs +++ b/src/metric-engine/src/engine.rs @@ -294,6 +294,19 @@ impl RegionEngine for MetricEngine { request: RegionRequest::Truncate(request), } .fail(), + // Only the data region's pending tails are discarded; the metadata region's are not. + RegionRequest::DiscardPendingTails(_) => { + if self.inner.is_physical_region(region_id) { + self.inner + .mito + .handle_request(utils::to_data_region_id(region_id), request) + .await + .context(error::MitoDiscardPendingTailsOperationSnafu) + .map(|response| response.affected_rows) + } else { + UnsupportedRegionRequestSnafu { request }.fail() + } + } RegionRequest::Delete(delete) => self.inner.delete_region(region_id, delete).await, RegionRequest::Catchup(_) => { let mut response = self @@ -727,8 +740,8 @@ mod test { use store_api::mito_engine_options::WAL_OPTIONS_KEY; use store_api::region_request::{ PathType, RegionCancelCompactionRequest, RegionCleanUpRequest, RegionCloseRequest, - RegionDropRequest, RegionFlushRequest, RegionOpenRequest, RegionPutRequest, RegionRequest, - RegionTruncateRequest, + RegionDiscardPendingTailsRequest, RegionDropRequest, RegionFlushRequest, RegionOpenRequest, + RegionPutRequest, RegionRequest, RegionTruncateRequest, }; use super::*; @@ -796,6 +809,45 @@ mod test { ); } + #[tokio::test] + async fn test_discard_pending_tails_physical_and_logical_regions() { + let env = TestEnv::new().await; + env.init_metric_region().await; + let request = + || RegionRequest::DiscardPendingTails(RegionDiscardPendingTailsRequest { node_id: 1 }); + let data_region_id = utils::to_data_region_id(env.default_physical_region_id()); + // A physical region accepts the request; neither of its Mito regions has pending tails. + let response = env + .metric() + .handle_request(env.default_physical_region_id(), request()) + .await + .unwrap(); + assert_eq!(response.affected_rows, 0); + // The request reaches the data region, which refuses it as a follower. + env.mito() + .set_region_role(data_region_id, RegionRole::Follower) + .unwrap(); + let error = env + .metric() + .handle_request(env.default_physical_region_id(), request()) + .await + .unwrap_err(); + assert_eq!( + common_error::status_code::StatusCode::RegionNotReady, + error.status_code() + ); + + let error = env + .metric() + .handle_request(env.default_logical_region_id(), request()) + .await + .unwrap_err(); + assert_eq!( + common_error::status_code::StatusCode::Unsupported, + error.status_code() + ); + } + #[tokio::test] async fn test_discard_unflushed_data_only() { let env = TestEnv::new().await; diff --git a/src/metric-engine/src/error.rs b/src/metric-engine/src/error.rs index f326429e2e0..92339d26ed6 100644 --- a/src/metric-engine/src/error.rs +++ b/src/metric-engine/src/error.rs @@ -185,6 +185,13 @@ pub enum Error { location: Location, }, + #[snafu(display("Mito discard pending tails operation fails"))] + MitoDiscardPendingTailsOperation { + source: BoxedError, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Mito sync operation fails"))] MitoSyncOperation { source: BoxedError, @@ -475,6 +482,7 @@ impl ErrorExt for Error { | MitoWriteOperation { source, .. } | MitoFlushOperation { source, .. } | MitoTruncateOperation { source, .. } + | MitoDiscardPendingTailsOperation { source, .. } | MitoSyncOperation { source, .. } | MitoEnterStagingOperation { source, .. } | BatchOpenMitoRegion { source, .. } @@ -515,6 +523,7 @@ impl ErrorExt for Error { | MitoWriteOperation { source, .. } | MitoFlushOperation { source, .. } | MitoTruncateOperation { source, .. } + | MitoDiscardPendingTailsOperation { source, .. } | MitoSyncOperation { source, .. } | MitoEnterStagingOperation { source, .. } | MitoCopyRegionFromOperation { source, .. } diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index add0aab907c..90b1d86918a 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -161,7 +161,10 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes flushed entry id skips them. A node bounds its replays' concurrency and SST writes apart from flushes, and their chunk memory within the global write buffer (`TailReplayLimits`). Replayed SSTs build indexes as flushed ones (`IndexBuildType::Flush`), under - `create_on_flush`. + `create_on_flush`. `RegionRequest::DiscardPendingTails` discards one node's tails + without replaying them; it commits through `update_manifest_for_tails` too + (`worker/handle_tail_replay.rs`) and raises the flushed entry id to the largest + discarded `upto`, so the same entry id rule applies. - Lock ordering: take the manifest lock before updating `version_control`; the reverse deadlocks against concurrent flush/compaction. - All region I/O runs on tokio workers; never `block_on` inside a worker. diff --git a/src/mito2/src/engine/listener.rs b/src/mito2/src/engine/listener.rs index e34fdcd6975..c89bdeb5c5f 100644 --- a/src/mito2/src/engine/listener.rs +++ b/src/mito2/src/engine/listener.rs @@ -41,6 +41,12 @@ pub trait EventListener: Send + Sync { /// Notifies the listener before a tail replay commits its result. async fn on_tail_commit_begin(&self, _region_id: RegionId) {} + /// Notifies the listener after a tail replay committed its result, before the worker is told. + async fn on_tail_commit_end(&self, _region_id: RegionId) {} + + /// Notifies the listener after a discard of pending tails released the region's WAL. + fn on_discarded_tails_wal_released(&self, _region_id: RegionId) {} + /// Notifies the listener each time a tail replay checks for a Leader lease while it waits. fn on_tail_lease_check(&self, _region_id: RegionId) {} diff --git a/src/mito2/src/engine/tail_replay_test.rs b/src/mito2/src/engine/tail_replay_test.rs index 9d2f18c3a8e..69f373731eb 100644 --- a/src/mito2/src/engine/tail_replay_test.rs +++ b/src/mito2/src/engine/tail_replay_test.rs @@ -18,11 +18,12 @@ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +use api::region::RegionResponse; use api::v1::{Mutation, OpType, Rows, WalEntry}; use async_trait::async_trait; use common_base::Plugins; use common_base::readable_size::ReadableSize; -use common_error::ext::ErrorExt; +use common_error::ext::{BoxedError, ErrorExt}; use common_error::status_code::StatusCode; use common_recordbatch::RecordBatches; use common_wal::config::object_store::FIXED_DIRECTORY_GENERATION; @@ -43,8 +44,9 @@ use store_api::region_engine::{ RegionEngine, RegionManifestInfo, RegionRole, SettableRegionRoleState, }; use store_api::region_request::{ - PathType, RegionAlterRequest, RegionCatchupRequest, RegionCloseRequest, RegionDropRequest, - RegionFlushRequest, RegionRequest, RegionTruncateRequest, + PathType, RegionAlterRequest, RegionCatchupRequest, RegionCloseRequest, + RegionDiscardPendingTailsRequest, RegionDropRequest, RegionFlushRequest, RegionOpenRequest, + RegionRequest, RegionTruncateRequest, }; use store_api::storage::{RegionId, ScanRequest}; @@ -90,6 +92,10 @@ struct TailReplayListener { commits: AtomicUsize, /// Commit attempts numbered from it on wait until it changes; 0 holds none. held_from: AtomicUsize, + /// Whether a committed replay waits before telling the worker. + hold_commit_end: AtomicBool, + commit_ends: AtomicUsize, + discard_releases: AtomicUsize, failures: Mutex>, ended: AtomicUsize, lease_checks: AtomicUsize, @@ -107,6 +113,17 @@ impl EventListener for TailReplayListener { } } + async fn on_tail_commit_end(&self, _region_id: RegionId) { + self.commit_ends.fetch_add(1, Ordering::Relaxed); + while self.hold_commit_end.load(Ordering::Relaxed) { + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + + fn on_discarded_tails_wal_released(&self, _region_id: RegionId) { + self.discard_releases.fetch_add(1, Ordering::Relaxed); + } + fn on_tail_lease_check(&self, _region_id: RegionId) { self.lease_checks.fetch_add(1, Ordering::Relaxed); } @@ -134,6 +151,18 @@ impl TailReplayListener { self.held_from.store(attempt, Ordering::Relaxed); } + fn hold_commit_end(&self, hold: bool) { + self.hold_commit_end.store(hold, Ordering::Relaxed); + } + + fn discard_releases(&self) -> usize { + self.discard_releases.load(Ordering::Relaxed) + } + + fn commit_ends(&self) -> usize { + self.commit_ends.load(Ordering::Relaxed) + } + fn commits(&self) -> usize { self.commits.load(Ordering::Relaxed) } @@ -274,6 +303,11 @@ impl TestRegion { /// Commits `edit`, which records tails, and reopens the region as a Follower. async fn reopen_with_edit(&self, edit: RegionEdit) { commit_edit(&self.engine, self.region_id, edit).await; + self.reopen().await; + } + + /// Reopens the region as a Follower. + async fn reopen(&self) { reopen_region( &self.engine, self.region_id, @@ -284,6 +318,18 @@ impl TestRegion { .await; } + /// Writes rows `[6, 9)` to the WAL of [REMOTE_NODE_ID] and reopens the region with a tail of + /// this node over rows `[0, 6)` and a tail of [REMOTE_NODE_ID] over the new rows. Returns the + /// two tails. + async fn reopen_with_own_and_remote_tails(&self) -> (PendingTail, PendingTail) { + let remote_upto = self.write_remote_rows(self.region_id, 6, 9).await; + let own = own_tail(0, self.entries[1], UptoKind::Reported); + let remote = remote_tail(0, remote_upto, UptoKind::Reported); + self.reopen_with_tails(vec![own.clone(), remote.clone()]) + .await; + (own, remote) + } + fn promote(&self) { self.engine .set_region_role(self.region_id, RegionRole::Leader) @@ -432,6 +478,77 @@ impl TestRegion { batches.pretty_print().unwrap().contains("99.0") } + async fn discard_pending_tails(&self, node_id: u64) -> Result { + let request = + RegionRequest::DiscardPendingTails(RegionDiscardPendingTailsRequest { node_id }); + let response = self.engine.handle_request(self.region_id, request).await?; + Ok(response.affected_rows) + } + + /// Flushes this node's rows, records a listed tail of [REMOTE_NODE_ID] whose bound lies + /// above every entry of both nodes, loses that node's WAL and makes the region writable, so + /// the replay keeps failing. Returns the bound. + async fn start_lost_listed_tail(&self) -> EntryId { + // Rows of the region stay readable after a reopen from a flushed entry id at the bound. + flush_region(&self.engine, self.region_id, None).await; + self.write_remote_rows(self.region_id, 6, 9).await; + // A listed bound may name no entry. It lies many objects above every entry, so later + // writes of this node reach it only once its sequence floor is raised past it. + let upto = self.remote_listed_bound().await.max(self.entries[1]) + (1 << 30); + self.reopen_with_tails(vec![remote_tail(0, upto, UptoKind::Listed)]) + .await; + self.delete_remote_objects().await; + self.catchup().await; + wait_until(|| self.listener.failed()).await; + upto + } + + /// Stops the engine and its log store as a crash of the process would, then opens the + /// region on a new engine over a new log store on the same storage. + async fn crash_and_open(self) -> Result { + let TestRegion { + mut env, + wal_store, + log_store, + engine, + region_id, + table_dir, + .. + } = self; + log_store.crash().await; + engine.stop().await.unwrap(); + drop(engine); + let released = Arc::downgrade(&log_store); + drop(log_store); + wait_until(|| released.strong_count() == 0).await; + let log_store = ObjectStoreLogStore::try_new( + wal_store, + &wal_config(), + NODE_ID, + FIXED_DIRECTORY_GENERATION, + ) + .await + .unwrap(); + let engine = env + .create_engine_with_log_store_and_time( + MitoConfig::default(), + log_store, + Arc::new(StdTimeProvider), + None, + ) + .await; + let request = RegionRequest::Open(RegionOpenRequest { + engine: String::new(), + table_dir, + options: wal_options(), + skip_wal_replay: false, + path_type: PathType::Bare, + checkpoint: None, + requirements: Default::default(), + }); + engine.handle_request(region_id, request).await + } + fn version(&self) -> VersionRef { self.engine.get_region(self.region_id).unwrap().version() } @@ -1076,14 +1193,7 @@ async fn test_closed_replay_keeps_chunks_of_uncertain_commit() { wait_until(|| region.listener.ended() == 1).await; assert_eq!(1, region.stored_ssts().await); - reopen_region( - ®ion.engine, - region.region_id, - region.table_dir.clone(), - false, - wal_options(), - ) - .await; + region.reopen().await; assert!(!region.has_pending_tails()); assert_eq!(6, count_rows(®ion.engine, region.region_id).await); } @@ -1948,3 +2058,511 @@ async fn test_failed_replay_reloads_region_after_failed_commit() { assert!(!region.has_pending_tails()); } + +#[tokio::test] +async fn test_discard_keeps_other_tails_and_their_wal() { + let region = TestRegion::new("tail-discard-remote", false, None).await; + let (own, remote) = region.reopen_with_own_and_remote_tails().await; + region.listener.hold_from(1); + region.catchup().await; + // The replay read both tails and waits to commit them. + wait_until(|| region.listener.commits() == 1).await; + assert_eq!( + region.entries.to_vec(), + stored_entry_ids(®ion.log_store, region.region_id).await + ); + + assert_eq!( + 1, + region.discard_pending_tails(REMOTE_NODE_ID).await.unwrap() + ); + + let version = region.version(); + assert_eq!(vec![own], version.pending_tails); + assert_eq!(remote.upto, version.flushed_entry_id); + wait_until(|| region.listener.discard_releases() == 1).await; + // The release kept the entries of the own tail, which the raised flushed entry id covers. + assert_eq!( + region.entries.to_vec(), + stored_entry_ids(®ion.log_store, region.region_id).await + ); + assert_eq!( + 0, + region.discard_pending_tails(REMOTE_NODE_ID).await.unwrap() + ); + region.listener.hold_from(0); + region.wait_until_replayed().await; + assert_eq!(6, count_rows(®ion.engine, region.region_id).await); +} + +#[tokio::test] +async fn test_discard_after_unapplied_replay_commit_is_busy() { + let region = TestRegion::new("tail-discard-unapplied", false, None).await; + let remote_upto = region.write_remote_rows(region.region_id, 6, 9).await; + region + .reopen_with_tails(vec![remote_tail(0, remote_upto, UptoKind::Reported)]) + .await; + region.listener.hold_commit_end(true); + region.catchup().await; + // The replay committed and has not told the worker yet. + wait_until(|| region.listener.commit_ends() == 1).await; + + let error = region + .discard_pending_tails(REMOTE_NODE_ID) + .await + .unwrap_err(); + assert_eq!(StatusCode::RegionBusy, error.status_code()); + + region.listener.hold_commit_end(false); + region.wait_until_replayed().await; + assert_eq!(1, region.stored_ssts().await); + assert_eq!(9, count_rows(®ion.engine, region.region_id).await); +} + +#[rstest] +#[case::follower(None)] +#[case::altering(Some(RegionLeaderState::Altering))] +#[case::editing(Some(RegionLeaderState::Editing))] +#[tokio::test] +async fn test_discard_on_unwritable_region_changes_nothing( + #[case] busy: Option, +) { + let region = TestRegion::new("tail-discard-unwritable", false, None).await; + let tails = vec![own_tail(0, region.entries[1], UptoKind::Reported)]; + region.reopen_with_tails(tails.clone()).await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + if let Some(busy) = busy { + region.listener.hold_from(1); + region.promote(); + wait_until(|| region.listener.commits() == 1).await; + set_busy(&mito_region, busy); + } + let version = next_manifest_version(&mito_region).await; + + let error = region.discard_pending_tails(NODE_ID).await.unwrap_err(); + + assert_eq!(StatusCode::RegionNotReady, error.status_code()); + assert_eq!(tails, region.version().pending_tails); + assert_eq!(version, next_manifest_version(&mito_region).await); +} + +#[tokio::test] +async fn test_discard_own_tails_releases_their_wal() { + let region = TestRegion::new("tail-discard-own", false, None).await; + let remote_upto = region.write_remote_rows(region.region_id, 6, 9).await; + let remote = remote_tail(0, remote_upto, UptoKind::Reported); + region + .reopen_with_tails(vec![ + own_tail(0, region.entries[0], UptoKind::Reported), + own_tail(region.entries[0], region.entries[1], UptoKind::Reported), + remote.clone(), + ]) + .await; + region.listener.hold_from(1); + region.promote(); + wait_until(|| region.listener.commits() == 1).await; + + assert_eq!(2, region.discard_pending_tails(NODE_ID).await.unwrap()); + + let version = region.version(); + assert_eq!(vec![remote], version.pending_tails); + assert_eq!(region.entries[1], version.flushed_entry_id); + wait_until(|| region.listener.discard_releases() == 1).await; + assert!( + stored_entry_ids(®ion.log_store, region.region_id) + .await + .is_empty() + ); + region.listener.hold_from(0); + region.wait_until_replayed().await; + assert_eq!(3, count_rows(®ion.engine, region.region_id).await); +} + +#[tokio::test] +async fn test_discard_listed_tail_raises_flushed_entry_id_to_its_bound() { + let region = TestRegion::new("tail-discard-listed", false, None).await; + let upto = region.start_lost_listed_tail().await; + + assert_eq!( + 1, + region.discard_pending_tails(REMOTE_NODE_ID).await.unwrap() + ); + + let current = region + .engine + .get_region(region.region_id) + .unwrap() + .version_control + .current(); + assert_eq!(upto, current.version.flushed_entry_id); + assert_eq!(upto, current.last_entry_id); + region.reopen().await; + assert!(!region.has_pending_tails()); + assert_eq!(6, count_rows(®ion.engine, region.region_id).await); +} + +/// The caller retries a discard whose commit landed but reported an error. Under conditional +/// publication a retry with other content conflicts with the landed edit and fences the +/// region, which reloads from it. +#[tokio::test] +async fn test_discard_retry_after_unknown_result_reloads_region() { + let version = Arc::new(AtomicU64::new(u64::MAX)); + let region = TestRegion::new( + "tail-discard-uncertain", + true, + Some(lose_delta_response(version.clone())), + ) + .await; + let (own, _) = region.reopen_with_own_and_remote_tails().await; + region.listener.hold_from(1); + region.promote_with_lease(); + wait_until(|| region.listener.commits() == 1).await; + let old = region.engine.get_region(region.region_id).unwrap(); + version.store(next_manifest_version(&old).await, Ordering::Relaxed); + + // The discard lands but its commit reports an error. + region + .discard_pending_tails(REMOTE_NODE_ID) + .await + .unwrap_err(); + assert!(region.has_pending_tails()); + // A discard of the other node's tails commits other content at the same version. + let error = region.discard_pending_tails(NODE_ID).await.unwrap_err(); + + assert_eq!(StatusCode::StorageUnavailable, error.status_code()); + wait_until(|| is_replaced(®ion.engine, &old)).await; + assert_eq!(vec![own], region.version().pending_tails); + region.promote_with_lease(); + assert_eq!( + 0, + region.discard_pending_tails(REMOTE_NODE_ID).await.unwrap() + ); +} + +/// Without conditional publication, a replay's commit that landed but reported an error is +/// uncertain until the replay commits again; a discard meanwhile would commit on top of it and +/// record the replayed tails again. +#[tokio::test] +async fn test_discard_over_uncertain_replay_commit_is_busy() { + let version = Arc::new(AtomicU64::new(u64::MAX)); + let region = TestRegion::new( + "tail-discard-uncertain-replay", + false, + Some(lose_delta_response(version.clone())), + ) + .await; + region.reopen_with_own_and_remote_tails().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + version.store(next_manifest_version(&mito_region).await, Ordering::Relaxed); + region.listener.hold_from(2); + region.catchup().await; + // The replay's commit lands but reports an error, and its retry waits. + wait_until(|| region.listener.commits() == 2).await; + + let error = region + .discard_pending_tails(REMOTE_NODE_ID) + .await + .unwrap_err(); + + assert_eq!(StatusCode::RegionBusy, error.status_code()); + // A flush that commits meanwhile leaves the replay's update uncertain. + let schema = rows_schema(&CreateRequestBuilder::new().build()); + put_range(®ion.engine, region.region_id, &schema, 9, 12).await; + flush_region(®ion.engine, region.region_id, None).await; + let error = region + .discard_pending_tails(REMOTE_NODE_ID) + .await + .unwrap_err(); + assert_eq!(StatusCode::RegionBusy, error.status_code()); + region.listener.hold_from(0); + region.wait_until_replayed().await; + region.reopen().await; + assert!(!region.has_pending_tails()); + assert_eq!(12, count_rows(®ion.engine, region.region_id).await); +} + +/// A replay that commits after a discard whose result is uncertain replays every tail, so no +/// row is lost and no tail is left. +#[tokio::test] +async fn test_replay_commit_over_uncertain_discard_replays_every_tail() { + let version = Arc::new(AtomicU64::new(u64::MAX)); + let region = TestRegion::new( + "tail-replay-uncertain-discard", + false, + Some(lose_delta_response(version.clone())), + ) + .await; + region.reopen_with_own_and_remote_tails().await; + region.listener.hold_from(1); + region.catchup().await; + wait_until(|| region.listener.commits() == 1).await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + version.store(next_manifest_version(&mito_region).await, Ordering::Relaxed); + + // The discard lands but reports an error. + region + .discard_pending_tails(REMOTE_NODE_ID) + .await + .unwrap_err(); + region.listener.hold_from(0); + region.wait_until_replayed().await; + region.reopen().await; + + assert!(!region.has_pending_tails()); + assert_eq!(9, count_rows(®ion.engine, region.region_id).await); +} + +/// A discard waiting for the manifest lock while the region is demoted answers the region +/// state error, not busy. +#[tokio::test] +async fn test_discard_demoted_before_its_commit_reports_region_state() { + let region = TestRegion::new("tail-discard-demoted", false, None).await; + let tails = vec![own_tail(0, region.entries[1], UptoKind::Reported)]; + region.reopen_with_tails(tails.clone()).await; + region.listener.hold_from(1); + region.promote(); + wait_until(|| region.listener.commits() == 1).await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let version = next_manifest_version(&mito_region).await; + let manager = &mito_region.manifest_ctx.manifest_manager; + let reading = manager.read().await; + + let (discarded, ()) = tokio::join!(region.discard_pending_tails(NODE_ID), async { + // The discard's commit waits for the lock while the region is demoted. + wait_until(|| manager.try_read().is_err()).await; + region + .engine + .set_region_role(region.region_id, RegionRole::Follower) + .unwrap(); + drop(reading); + }); + + let error = discarded.unwrap_err(); + assert_eq!(StatusCode::RegionNotReady, error.status_code()); + assert_eq!(tails, region.version().pending_tails); + assert_eq!(version, next_manifest_version(&mito_region).await); +} + +/// Lets the first write of the manifest delta `version` land as if its response was lost, and +/// fails the write of the next delta before it stores anything. +fn lose_delta_response_then_reject(version: Arc) -> MockLayer { + let armed = Arc::new(AtomicBool::new(true)); + MockLayerBuilder::default() + .writer_factory(Arc::new(move |path, _args, inner| { + let target = version.load(Ordering::Relaxed); + if target == u64::MAX { + return inner; + } + let (lost, rejected) = (delta_file(target), delta_file(target + 1)); + if path.contains(&lost) && armed.swap(false, Ordering::Relaxed) { + Box::new(LostResponseWriter { inner }) + } else if path.contains(&rejected) { + Box::new(RejectingWriter) + } else { + inner + } + })) + .build() + .unwrap() +} + +struct RejectingWriter; + +impl Write for RejectingWriter { + async fn write(&mut self, _bs: Buffer) -> MockResult<()> { + Err(MockError::new(ErrorKind::ConfigInvalid, "rejected")) + } + + async fn close(&mut self) -> MockResult { + Err(MockError::new(ErrorKind::ConfigInvalid, "rejected")) + } + + async fn abort(&mut self) -> MockResult<()> { + Ok(()) + } +} + +/// A replay retry that fails without storing anything keeps the earlier attempt's uncertain +/// result, so a discard stays busy. +#[tokio::test] +async fn test_discard_stays_busy_after_a_rejected_replay_retry() { + let version = Arc::new(AtomicU64::new(u64::MAX)); + let region = TestRegion::new( + "tail-discard-rejected-retry", + false, + Some(lose_delta_response_then_reject(version.clone())), + ) + .await; + region.reopen_with_own_and_remote_tails().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + version.store(next_manifest_version(&mito_region).await, Ordering::Relaxed); + region.listener.hold_from(3); + region.catchup().await; + // The first commit lands but reports an error, the second is rejected, the third waits. + wait_until(|| region.listener.commits() == 3).await; + + let error = region + .discard_pending_tails(REMOTE_NODE_ID) + .await + .unwrap_err(); + + assert_eq!(StatusCode::RegionBusy, error.status_code()); + region.listener.hold_from(0); + region.wait_until_replayed().await; + region.reopen().await; + assert!(!region.has_pending_tails()); + assert_eq!(9, count_rows(®ion.engine, region.region_id).await); +} + +/// The uncertain result of a cancelled replay keeps discards busy until a later replay of the +/// same instance publishes. +#[tokio::test] +async fn test_discard_stays_busy_after_an_uncertain_replay_ends() { + let version = Arc::new(AtomicU64::new(u64::MAX)); + let region = TestRegion::new( + "tail-discard-ended-uncertain", + false, + Some(lose_delta_response(version.clone())), + ) + .await; + region.reopen_with_own_and_remote_tails().await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + version.store(next_manifest_version(&mito_region).await, Ordering::Relaxed); + region.listener.hold_from(2); + region.catchup().await; + wait_until(|| region.listener.commits() == 2).await; + // A demotion ends the replay while its update is uncertain. + region + .engine + .set_region_role(region.region_id, RegionRole::Follower) + .unwrap(); + region.listener.hold_from(3); + wait_until(|| region.listener.ended() == 1).await; + region.promote(); + wait_until(|| region.listener.commits() == 3).await; + + let error = region + .discard_pending_tails(REMOTE_NODE_ID) + .await + .unwrap_err(); + + assert_eq!(StatusCode::RegionBusy, error.status_code()); + region.listener.hold_from(0); + region.wait_until_replayed().await; + assert_eq!( + 0, + region.discard_pending_tails(REMOTE_NODE_ID).await.unwrap() + ); +} + +/// A replay's commit that succeeds after one with an uncertain result clears the uncertainty, +/// so a discard of the tail the replay keeps succeeds. +#[tokio::test] +async fn test_discard_succeeds_after_an_uncertain_replay_commit_is_retried() { + let version = Arc::new(AtomicU64::new(u64::MAX)); + let region = TestRegion::new( + "tail-discard-recommitted", + false, + Some(lose_delta_response(version.clone())), + ) + .await; + let remote_upto = region.write_remote_rows(region.region_id, 6, 9).await; + // Another node's listed tail stays from its last entry read until the region is leased. + let remote = remote_tail(0, remote_upto + 1, UptoKind::Listed); + region + .reopen_with_tails(vec![ + own_tail(0, region.entries[1], UptoKind::Reported), + remote.clone(), + ]) + .await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + version.store(next_manifest_version(&mito_region).await, Ordering::Relaxed); + region.catchup().await; + // The first commit lands but reports an error, and its retry commits. + let kept = PendingTail { + after: remote_upto, + ..remote + }; + wait_until(|| region.version().pending_tails == vec![kept.clone()]).await; + assert_eq!(2, region.listener.commits()); + + assert_eq!( + 1, + region.discard_pending_tails(REMOTE_NODE_ID).await.unwrap() + ); + assert!(!region.has_pending_tails()); +} + +/// With conditional publication, a discard over a replay's update that was saved but reported +/// an error conflicts with it, and the region reloads from storage without the tails. +#[tokio::test] +async fn test_conditional_discard_over_uncertain_replay_reloads_region() { + let version = Arc::new(AtomicU64::new(u64::MAX)); + let region = TestRegion::new( + "tail-discard-conditional-uncertain", + true, + Some(lose_delta_response(version.clone())), + ) + .await; + region.reopen_with_own_and_remote_tails().await; + let old = region.engine.get_region(region.region_id).unwrap(); + version.store(next_manifest_version(&old).await, Ordering::Relaxed); + region.listener.hold_from(2); + region.promote_with_lease(); + wait_until(|| region.listener.commits() == 2).await; + + let error = region + .discard_pending_tails(REMOTE_NODE_ID) + .await + .unwrap_err(); + + assert_eq!(StatusCode::StorageUnavailable, error.status_code()); + wait_until(|| is_replaced(®ion.engine, &old)).await; + assert!(!region.has_pending_tails()); + region.listener.hold_from(0); + assert_eq!(9, count_rows(®ion.engine, region.region_id).await); +} + +/// A discard raises the flushed entry id to a listed tail's bound. After a crash, the +/// object-store WAL, which by default does not accept missing history, checks history, so the +/// region opens only if this node's WAL durably holds history through the bound, as whoever +/// records the tail ensures. +#[rstest] +#[case::history_past_bound(true)] +#[case::history_below_bound(false)] +#[tokio::test] +async fn test_discard_reopens_after_crash_with_history_past_bound( + #[case] history_past_bound: bool, +) { + let region = TestRegion::new("tail-discard-crash", false, None).await; + let upto = region.start_lost_listed_tail().await; + if history_past_bound { + // Moves this node's next entry id past the bound and makes an entry there durable. + let provider = region + .engine + .get_region(region.region_id) + .unwrap() + .provider + .clone(); + region + .log_store + .obsolete(&provider, region.region_id, upto) + .await + .unwrap(); + let schema = rows_schema(&CreateRequestBuilder::new().build()); + put_range(®ion.engine, region.region_id, &schema, 9, 10).await; + } + assert_eq!( + 1, + region.discard_pending_tails(REMOTE_NODE_ID).await.unwrap() + ); + + let opened = region.crash_and_open().await; + + if history_past_bound { + opened.unwrap(); + } else { + let error = format!("{:?}", opened.unwrap_err()); + assert!(error.contains("does not hold the history"), "{error}"); + } +} diff --git a/src/mito2/src/manifest/action.rs b/src/mito2/src/manifest/action.rs index 5abeb31ace6..dbe419588d1 100644 --- a/src/mito2/src/manifest/action.rs +++ b/src/mito2/src/manifest/action.rs @@ -268,8 +268,8 @@ pub struct RegionManifest { /// `after < upto`: a new segment of a node takes as `after` the largest of the /// flushed entry id, the `upto`s of the node's existing segments and its handoff /// floor, and is added only if that is below its `upto`. So the entries of a node - /// between two of its segments are flushed or at or below a handoff floor of the - /// node, and need no replay. + /// between two of its segments are flushed, discarded or at or below a handoff floor + /// of the node, and need no replay. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub pending_tails: Vec, /// The [HandoffFloor] of each node, removed once the flushed entry id reaches it. @@ -283,12 +283,20 @@ impl RegionManifest { } /// Returns the entry id after which node `node_id` replays its WAL when it opens - /// the region. Entries up to it are flushed, left to the pending tails, or below - /// the handoff floor of the node. + /// the region. Entries up to it are flushed, discarded, left to the pending tails, + /// or below the handoff floor of the node. /// /// Entries of the node in `(after, upto]` of one of its tails belong to that tail. /// Whoever adds a tail ensures that every entry id the node allocates afterwards is /// above the tail's `upto`, so no later write of the node falls in a skipped range. + /// It also ensures that the node's WAL durably holds history through `upto`: a tail + /// commit or a discard can raise the flushed entry id to it, and an open of the region + /// checks that the WAL holds history through the flushed entry id where the log store + /// checks history (see [LogStore::check_region_history]). A discard raises the flushed + /// entry id on whichever node leads the region, so whoever adds a tail ensures both for + /// every node that may lead the region afterwards, not only for the tail's own node. + /// + /// [LogStore::check_region_history]: store_api::logstore::LogStore::check_region_history pub(crate) fn wal_replay_start(&self, node_id: Option) -> EntryId { let floor = node_id.and_then(|node_id| self.handoff_floors.get(&node_id).copied()); self.pending_tails diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index a263a6d7668..c99f48d5a18 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -23,7 +23,7 @@ pub(crate) mod version; use std::cell::OnceCell; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; -use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use std::time::Instant; @@ -1336,17 +1336,29 @@ pub(crate) enum IndexPublication { Stale(IndexPublicationStale), } -/// Result of publishing the result of a pending tail replay to the manifest. +/// Result of publishing an edit of the pending tails, a replay's result or a discard, to the +/// manifest. #[derive(Debug, PartialEq, Eq)] pub(crate) enum TailPublication { - /// The result was committed. + /// The edit was committed. Committed(ManifestVersion), - /// The region is altering or applying an edit, so the result waits. + /// The region is altering or applying an edit, or, without conditional publication, a + /// replay's earlier update may be saved without being applied. Busy, - /// The region is no longer a writable leader with the replayed tails. + /// The region is no longer a writable leader, or its manifest no longer records the + /// expected tails. Stale, } +/// Who publishes an edit of the pending tails. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum TailsEditor { + /// A tail replay, which commits its own uncertain update again. + Replay, + /// A discard of one node's tails. + Discard, +} + /// Why an index publication became stale. #[derive(Debug, PartialEq, Eq)] pub(crate) enum IndexPublicationStale { @@ -1393,6 +1405,12 @@ pub(crate) struct ManifestContext { /// lease of a heartbeat sent after it applies; 0 otherwise. While it is set, the region keeps /// the unread part of another node's listed tails. catchup_promoted_at: AtomicU64, + /// Whether a tail replay's manifest update has an uncertain result: it may be saved in + /// storage without being applied to this instance's manifest. Tracked only without + /// conditional publication, where a later update takes a new version instead of + /// conflicting with a saved one. A value left by an ended replay task keeps discards busy + /// until a replay of this instance publishes or the region is reopened. + replay_publication_uncertain: AtomicBool, /// Deadline of the region's latest Leader or StagingLeader lease from the metasrv, which is how /// long the Leader role stays valid. The engine extends it from those leases, and writes check /// it. @@ -1423,6 +1441,7 @@ impl ManifestContext { reload_pending: false, }), catchup_promoted_at: AtomicU64::new(0), + replay_publication_uncertain: AtomicBool::new(false), leader_deadline: Deadline::default(), node_lease, staging_partition_info: Mutex::new(None), @@ -1767,12 +1786,20 @@ impl ManifestContext { }) } - /// Publishes the result of a replay of the pending tails `replayed`, if the region is - /// still a writable leader whose manifest records exactly those tails. + /// Publishes an edit of the pending tails `expected` by `editor`, if the region is still a + /// writable leader whose manifest records exactly those tails. + /// + /// Without conditional publication, a discard is busy while a replay's earlier update has an + /// uncertain result, since it may be in storage and the discard would record the replayed + /// tails again. A replay's update is uncertain from before its write until it commits; an + /// attempt that fails without saving anything keeps the uncertainty of the attempts before + /// it. With conditional publication the next update reuses the version of an uncertain + /// one, so a discard over a saved update conflicts and the region reloads instead. pub(crate) async fn update_manifest_for_tails( &self, - replayed: &[PendingTail], + expected: &[PendingTail], action_list: RegionMetaActionList, + editor: TailsEditor, ) -> Result { let manager = self.manifest_manager.write().await; match self.state.load() { @@ -1782,11 +1809,38 @@ impl ManifestContext { } _ => return Ok(TailPublication::Stale), } - if manager.manifest().pending_tails != replayed { + if manager.manifest().pending_tails != expected { return Ok(TailPublication::Stale); } - let manifest_version = self.update_and_fire(manager, action_list, false).await?; - Ok(TailPublication::Committed(manifest_version)) + let tracks_uncertainty = !manager.is_conditional_publication(); + let was_uncertain = match editor { + // Set under the lock before the write, so no discard commits between a saved write + // and its error. + TailsEditor::Replay if tracks_uncertainty => self + .replay_publication_uncertain + .swap(true, Ordering::Relaxed), + TailsEditor::Discard + if tracks_uncertainty + && self.replay_publication_uncertain.load(Ordering::Relaxed) => + { + return Ok(TailPublication::Busy); + } + _ => false, + }; + let result = self.update_and_fire(manager, action_list, false).await; + if editor == TailsEditor::Replay && tracks_uncertainty { + match &result { + Ok(_) => self + .replay_publication_uncertain + .store(false, Ordering::Relaxed), + // This attempt saved nothing, but an earlier one may have. + Err(e) if !e.may_have_persisted_manifest_update() => self + .replay_publication_uncertain + .store(was_uncertain, Ordering::Relaxed), + Err(_) => {} + } + } + Ok(TailPublication::Committed(result?)) } /// Performs a manifest write under a caller-held write lock and returns a diff --git a/src/mito2/src/request.rs b/src/mito2/src/request.rs index be3e76f53c9..c17881a5a46 100644 --- a/src/mito2/src/request.rs +++ b/src/mito2/src/request.rs @@ -800,6 +800,13 @@ pub(crate) enum WorkerRequest { sender: OptionOutputTx, }, + /// Discards the region's pending WAL tails that node `node_id` wrote. + DiscardPendingTails { + region_id: RegionId, + node_id: u64, + sender: OptionOutputTx, + }, + /// Notify a worker to stop. Stop, @@ -936,6 +943,11 @@ impl WorkerRequest { task_id: v.task_id, sender: sender.into(), }, + RegionRequest::DiscardPendingTails(v) => WorkerRequest::DiscardPendingTails { + region_id, + node_id: v.node_id, + sender: sender.into(), + }, RegionRequest::BuildIndex(v) => WorkerRequest::Ddl(SenderDdlRequest { region_id, sender: sender.into(), @@ -1177,6 +1189,19 @@ pub(crate) enum BackgroundNotify { }, /// A tail replay ended. TailReplayEnded, + /// An edit that discards pending tails was published in the manifest. + PendingTailsDiscarded { + /// The instance the tails were discarded from. + region: MitoRegionRef, + /// The published edit. + edit: RegionEdit, + /// The tails the manifest recorded when the edit was published. + tails: Vec, + /// The number of tails the edit removed. + discarded: usize, + /// Receives `discarded`. + sender: OptionOutputTx, + }, } impl BackgroundNotify { @@ -1213,7 +1238,8 @@ impl BackgroundNotify { | Self::RegionBecameWritable | Self::RegionCannotReplay { .. } | Self::TailReplayCommitted { .. } - | Self::TailReplayEnded => false, + | Self::TailReplayEnded + | Self::PendingTailsDiscarded { .. } => false, } } } @@ -1603,6 +1629,31 @@ mod tests { assert_eq!(receiver.await.unwrap().unwrap(), 1); } + #[tokio::test] + async fn test_discard_pending_tails_is_worker_control_request() { + let region_id = RegionId::new(7, 3); + let (request, receiver) = WorkerRequest::try_from_region_request( + region_id, + RegionRequest::DiscardPendingTails( + store_api::region_request::RegionDiscardPendingTailsRequest { node_id: 5 }, + ), + None, + ) + .unwrap(); + let WorkerRequest::DiscardPendingTails { + region_id: actual_region_id, + node_id, + sender, + } = request + else { + panic!("a pending tails discard must bypass the DDL queue"); + }; + assert_eq!(actual_region_id, region_id); + assert_eq!(node_id, 5); + sender.send(Ok(2)); + assert_eq!(receiver.await.unwrap().unwrap(), 2); + } + fn new_column_schema( name: &str, data_type: ColumnDataType, diff --git a/src/mito2/src/tail_replay.rs b/src/mito2/src/tail_replay.rs index 04582ed8ec7..f34ca87453f 100644 --- a/src/mito2/src/tail_replay.rs +++ b/src/mito2/src/tail_replay.rs @@ -39,7 +39,7 @@ use crate::memtable::time_partition::TimePartitions; use crate::metrics::TAIL_REPLAY_FAILURE_TOTAL; use crate::region::opener::replay_entry; use crate::region::version::{VersionBuilder, VersionControl, VersionControlRef}; -use crate::region::{MitoRegion, MitoRegionRef, TailPublication}; +use crate::region::{MitoRegion, MitoRegionRef, TailPublication, TailsEditor}; use crate::request::{BackgroundNotify, WorkerRequest, WorkerRequestWithTime}; use crate::schedule::CancellableTaskState; use crate::sst::file::{FileMeta, UncommittedSsts}; @@ -66,6 +66,28 @@ pub(crate) fn should_replay_tails(region: &MitoRegion) -> bool { region.can_replay_tails() && region.version().has_pending_tails() } +/// Releases the WAL of `region` on node `node_id` up to where the region now replays it on +/// open, keeping the node's remaining tails, after an edit of its pending tails. A failure is +/// only logged. +pub(crate) async fn release_wal_after_tails_edit( + region: &MitoRegion, + wal: &Wal, + node_id: Option, +) { + let manifest = region.manifest_ctx.manifest().await; + let entry_id = cap_wal_release( + &manifest.pending_tails, + node_id, + manifest.wal_replay_start(node_id), + ); + if let Err(e) = wal + .obsolete(region.region_id, entry_id, ®ion.provider) + .await + { + error!(e; "Failed to release the WAL of region {} after its pending tails changed", region.region_id); + } +} + /// Replays the pending tails of a region into SSTs and publishes them in one manifest edit. /// /// Each round reads the tails in order and writes each into its own SSTs: an SST can give all its @@ -408,7 +430,7 @@ impl TailReplayTask { match self .region .manifest_ctx - .update_manifest_for_tails(tails, action_list.clone()) + .update_manifest_for_tails(tails, action_list.clone(), TailsEditor::Replay) .await { Ok(TailPublication::Committed(manifest_version)) => { @@ -416,7 +438,8 @@ impl TailReplayTask { info!( "Published the replayed WAL tails of region {region_id} in manifest version {manifest_version}" ); - self.release_wal().await; + release_wal_after_tails_edit(&self.region, &self.wal, self.node_id).await; + self.listener.on_tail_commit_end(region_id).await; let region = self.region.clone(); let tails = tails.to_vec(); let notify = BackgroundNotify::TailReplayCommitted { @@ -468,25 +491,6 @@ impl TailReplayTask { } } - /// Releases the WAL up to where the region now replays it on open, keeping this node's - /// remaining tails. A failure is only logged. - async fn release_wal(&self) { - let region = &self.region; - let manifest = region.manifest_ctx.manifest().await; - let entry_id = cap_wal_release( - &manifest.pending_tails, - self.node_id, - manifest.wal_replay_start(self.node_id), - ); - if let Err(e) = self - .wal - .obsolete(region.region_id, entry_id, ®ion.provider) - .await - { - error!(e; "Failed to release the WAL of region {} after publishing its tails", region.region_id); - } - } - /// Awaits `future` unless the task is cancelled first. async fn unless_cancelled(&self, future: impl Future>) -> Result { let cancellation = self.state.cancel_token(); diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index 6b4f1a61590..da605572c4f 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -1642,6 +1642,13 @@ impl RegionWorkerLoop { }; sender.send(result); } + WorkerRequest::DiscardPendingTails { + region_id, + node_id, + sender, + } => { + self.handle_discard_pending_tails(region_id, node_id, sender); + } WorkerRequest::Stop => { debug_assert!(!self.running.load(Ordering::Relaxed)); } @@ -1857,10 +1864,22 @@ impl RegionWorkerLoop { edit, tails, } => { - self.handle_tail_replay_committed(region_id, region, edit, tails) + self.apply_tails_edit(region_id, ®ion, edit, &tails) .await } BackgroundNotify::TailReplayEnded => self.handle_tail_replay_ended(region_id), + BackgroundNotify::PendingTailsDiscarded { + region, + edit, + tails, + discarded, + sender, + } => { + self.handle_pending_tails_discarded( + region_id, region, edit, tails, discarded, sender, + ) + .await + } } // Completion handlers may return early after releasing their scheduler. Dispatch // here covers those paths as well as their normal completion. @@ -2023,6 +2042,22 @@ impl WorkerListener { } } + /// A tail replay committed its result and has not told the worker yet. + pub(crate) async fn on_tail_commit_end(&self, _region_id: RegionId) { + #[cfg(any(test, feature = "test"))] + if let Some(listener) = &self.listener { + listener.on_tail_commit_end(_region_id).await; + } + } + + /// A discard of pending tails released the region's WAL. + pub(crate) fn on_discarded_tails_wal_released(&self, _region_id: RegionId) { + #[cfg(any(test, feature = "test"))] + if let Some(listener) = &self.listener { + listener.on_discarded_tails_wal_released(_region_id); + } + } + /// A tail replay checks for a Leader lease while it waits. pub(crate) fn on_tail_lease_check(&self, _region_id: RegionId) { #[cfg(any(test, feature = "test"))] diff --git a/src/mito2/src/worker/handle_tail_replay.rs b/src/mito2/src/worker/handle_tail_replay.rs index 46d6b2f6911..e6838b0ec99 100644 --- a/src/mito2/src/worker/handle_tail_replay.rs +++ b/src/mito2/src/worker/handle_tail_replay.rs @@ -12,23 +12,32 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Starting, applying and ending background replays of pending WAL tails. +//! Starting, applying and ending background replays of pending WAL tails, and discarding +//! pending tails without replaying them. use std::sync::Arc; -use common_telemetry::info; +use common_telemetry::{error, info, warn}; use store_api::logstore::LogStore; use store_api::storage::RegionId; use tokio::sync::mpsc::Sender; use crate::config::IndexBuildMode; -use crate::manifest::action::{PendingTail, RegionEdit}; -use crate::region::MitoRegionRef; +use crate::error::{RegionBusySnafu, RegionStateSnafu}; +use crate::manifest::action::{ + PendingTail, RegionEdit, RegionMetaAction, RegionMetaActionList, WalRecoveryEdit, +}; +use crate::region::{ + MitoRegionRef, RegionLeaderState, RegionRoleState, TailPublication, TailsEditor, +}; use crate::request::{BackgroundNotify, BuildIndexRequest, OptionOutputTx, WorkerRequestWithTime}; use crate::schedule::CancellableTaskState; use crate::sst::index::IndexBuildType; -use crate::tail_replay::{TailReplayTask, notify_worker, should_replay_tails}; +use crate::tail_replay::{ + TailReplayTask, notify_worker, release_wal_after_tails_edit, should_replay_tails, +}; use crate::worker::RegionWorkerLoop; +use crate::worker::handle_reload::notify_if_fenced; impl RegionWorkerLoop { /// Starts replaying the pending tails of the region, unless a replay of it still runs. @@ -66,23 +75,160 @@ impl RegionWorkerLoop { } } - /// Applies a published tail replay unless its instance was replaced, or its version no - /// longer records `tails`, the tails it replayed, because a sync rebuilt it from a later - /// manifest. - pub(crate) async fn handle_tail_replay_committed( + /// Discards the pending tails of the region that node `node_id` wrote, without replaying + /// them, and sends the number of discarded tails to `sender`. A region without such tails + /// sends 0 and changes nothing. + /// + /// The edit removes the tails, keeps the others in order and raises the flushed entry id + /// to the largest `upto` of the removed tails, for a listed tail too, whose `upto` can lie + /// above every entry this node wrote. Replaying the WAL at open then skips this node's + /// entries up to the new flushed entry id, except those covered by the node's remaining + /// tails, which a background replay still reads. + /// + /// Where the log store checks history and does not accept missing history, opening the + /// region also requires this node's WAL to hold history through the new flushed entry + /// id. The discard checks neither condition: whoever adds a tail ensures both (see + /// [RegionManifest::wal_replay_start](crate::manifest::action::RegionManifest::wal_replay_start)). + /// + /// The edit is committed outside the worker against the tails the version records now, so + /// a replay or a sync that changed them first makes it fail as busy, and a running replay + /// of the region is left to find the tails changed. Without conditional publication it also + /// fails as busy while a replay's update has an uncertain result, see + /// [ManifestContext::update_manifest_for_tails](crate::region::ManifestContext::update_manifest_for_tails). + pub(crate) fn handle_discard_pending_tails( + &mut self, + region_id: RegionId, + node_id: u64, + sender: OptionOutputTx, + ) { + let region = match self.regions.writable_non_staging_region(region_id) { + Ok(region) => region, + Err(e) => { + sender.send(Err(e)); + return; + } + }; + let (tails, flushed_entry_id) = { + let version = region.version(); + (version.pending_tails.clone(), version.flushed_entry_id) + }; + let (discarded, remaining): (Vec<_>, Vec<_>) = tails + .iter() + .cloned() + .partition(|tail| tail.node_id == node_id); + let Some(upto) = discarded.iter().map(|tail| tail.upto).max() else { + info!("Region {region_id} has no pending tails from node {node_id}"); + sender.send(Ok(0)); + return; + }; + warn!( + "Discarding the pending WAL tails of region {region_id} from node {node_id}: {discarded:?}, flushed entry id: {flushed_entry_id}" + ); + let edit = RegionEdit { + timestamp_ms: Some(chrono::Utc::now().timestamp_millis()), + flushed_entry_id: (upto > flushed_entry_id).then_some(upto), + wal_recovery: WalRecoveryEdit { + pending_tails: Some(remaining), + handoff_floor: None, + }, + ..Default::default() + }; + let wal = self.wal.clone(); + let local_node_id = self.file_ref_manager.node_id(); + let request_sender = self.sender.clone(); + let listener = self.listener.clone(); + common_runtime::spawn_global(async move { + let action_list = + RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone())); + match region + .manifest_ctx + .update_manifest_for_tails(&tails, action_list, TailsEditor::Discard) + .await + { + Ok(TailPublication::Committed(manifest_version)) => { + info!( + "Discarded the pending WAL tails of region {region_id} from node {node_id} in manifest version {manifest_version}" + ); + // Notifies first: the release is storage I/O, and a replay that ends + // meanwhile restarts from the old tails until the worker applies the edit. + let notify = BackgroundNotify::PendingTailsDiscarded { + region: region.clone(), + edit, + tails, + discarded: discarded.len(), + sender, + }; + notify_worker(&request_sender, region_id, notify).await; + release_wal_after_tails_edit(®ion, &wal, local_node_id).await; + listener.on_discarded_tails_wal_released(region_id); + } + Ok(TailPublication::Busy) => { + info!( + "Region {region_id} is altering or editing, or a tail replay's update has an uncertain result, not discarding the tails from node {node_id}" + ); + sender.send(RegionBusySnafu { region_id }.fail()); + } + Ok(TailPublication::Stale) => { + let state = region.state(); + if state == RegionRoleState::Leader(RegionLeaderState::Writable) { + info!( + "Region {region_id} changed its pending tails, not discarding the tails from node {node_id}" + ); + sender.send(RegionBusySnafu { region_id }.fail()); + } else { + sender.send( + RegionStateSnafu { + region_id, + state, + expect: RegionRoleState::Leader(RegionLeaderState::Writable), + } + .fail(), + ); + } + } + Err(e) => { + error!(e; "Failed to discard the pending WAL tails of region {region_id} from node {node_id}"); + notify_if_fenced(&request_sender, ®ion).await; + sender.send(Err(e)); + } + } + }); + } + + /// Applies a published edit that discards pending tails, see [Self::apply_tails_edit], and + /// sends the number of `discarded` tails, even if the region changed since. + pub(crate) async fn handle_pending_tails_discarded( &mut self, region_id: RegionId, region: MitoRegionRef, edit: RegionEdit, tails: Vec, + discarded: usize, + sender: OptionOutputTx, + ) { + self.apply_tails_edit(region_id, ®ion, edit, &tails) + .await; + sender.send(Ok(discarded)); + self.maybe_replay_tails(region_id); + } + + /// Applies `edit`, which a tail replay or a discard published for the pending tails + /// `tails`, unless the instance `region` was replaced, or its version no longer records + /// `tails` because a sync rebuilt it from a later manifest. + pub(crate) async fn apply_tails_edit( + &mut self, + region_id: RegionId, + region: &MitoRegionRef, + edit: RegionEdit, + tails: &[PendingTail], ) { let registered = self.regions.get_region(region_id); - if !registered.is_some_and(|registered| Arc::ptr_eq(®istered, ®ion)) { + if !registered.is_some_and(|registered| Arc::ptr_eq(®istered, region)) { info!("Region {region_id} changed after its tails were published"); return; } if region.version().pending_tails != tails { - info!("Region {region_id} no longer records the replayed tails, skipping their edit"); + info!("Region {region_id} no longer records the published tails, skipping their edit"); return; } // A truncate uses the last entry id, which must not be below the flushed entry id. @@ -107,7 +253,7 @@ impl RegionWorkerLoop { ) .await; } - self.schedule_compaction(®ion).await; + self.schedule_compaction(region).await; } /// Cancels the tail replay of the region unless `region`, the instance a role change made diff --git a/src/operator/src/request.rs b/src/operator/src/request.rs index 88eac1a940a..f7cdf3316f5 100644 --- a/src/operator/src/request.rs +++ b/src/operator/src/request.rs @@ -17,8 +17,9 @@ use std::sync::Arc; use api::helper::to_pb_time_unit; use api::v1::region::region_request::Body as RegionRequestBody; use api::v1::region::{ - BuildIndexRequest, CancelCompactionRequest, CompactRequest, CompactionTimeRange, FlushRequest, - RegionRequestHeader, TruncateRequest, Unflushed, build_index_request, truncate_request, + BuildIndexRequest, CancelCompactionRequest, CompactRequest, CompactionTimeRange, + DiscardPendingTailsRequest, FlushRequest, RegionRequestHeader, TruncateRequest, Unflushed, + build_index_request, truncate_request, }; use catalog::CatalogManagerRef; use common_catalog::build_db_string; @@ -26,7 +27,7 @@ use common_catalog::consts::METRIC_ENGINE; use common_meta::node_manager::{AffectedRows, NodeManagerRef}; use common_meta::peer::Peer; use common_telemetry::tracing_context::TracingContext; -use common_telemetry::{debug, error, info}; +use common_telemetry::{debug, error, info, warn}; use common_time::range::TimestampRange; use common_time::timestamp::TimeUnit as TimestampUnit; use futures_util::future; @@ -36,6 +37,7 @@ use session::context::QueryContextRef; use snafu::prelude::*; use store_api::metric_engine_consts; use store_api::storage::RegionId; +use table::metadata::{TableId, TableInfoRef}; use table::requests::{BuildIndexTableRequest, CompactTableRequest, FlushTableRequest}; use table::table_name::TableName; @@ -279,38 +281,19 @@ impl Requester { table_name: TableName, ctx: QueryContextRef, ) -> Result { - let table = self - .catalog_manager - .table( - &table_name.catalog_name, - &table_name.schema_name, - &table_name.table_name, - None, - ) - .await - .context(CatalogSnafu)?; - let table = table.with_context(|| TableNotFoundSnafu { - table_name: table_name.to_string(), - })?; - let table_info = table.table_info(); - ensure_discard_unflushed_supported( + let table_info = self.table_info(&table_name).await?; + ensure_discard_supported( &table_info.meta.engine, table_info.is_physical_table(), + "discarding unflushed data from a Metric Engine logical table", )?; - - let partitions = &self - .partition_manager - .find_physical_partition_info(table_info.ident.table_id) - .await - .with_context(|_| FindTablePartitionRuleSnafu { - table_name: table_name.to_string(), - })? - .partitions; - let requests = partitions - .iter() - .map(|partition| { + let requests = self + .physical_region_ids(&table_name, table_info.ident.table_id) + .await? + .into_iter() + .map(|region_id| { RegionRequestBody::Truncate(TruncateRequest { - region_id: partition.id.into(), + region_id: region_id.into(), kind: Some(truncate_request::Kind::Unflushed(Unflushed {})), }) }) @@ -327,6 +310,131 @@ impl Requester { ) .await } + + /// Discards the region's pending WAL tails that datanode `node_id` wrote. + pub(crate) async fn handle_discard_pending_tails( + &self, + region_id: RegionId, + node_id: u64, + ctx: QueryContextRef, + ) -> Result { + let request = RegionRequestBody::DiscardPendingTails(DiscardPendingTailsRequest { + region_id: region_id.into(), + datanode_id: node_id, + }); + + info!( + user = ctx.current_user().username(), + "Handle region discard pending tails request: {region_id}, node: {node_id}" + ); + let discarded = self.do_request(vec![request], None, &ctx).await?; + if discarded == 0 { + info!("No pending tails from node {node_id} in region {region_id}"); + } + Ok(discarded) + } + + /// Discards the pending WAL tails that datanode `node_id` wrote in every region of the + /// table. Each failed region is logged with its error, and the first error is returned + /// after a warning with the number of tails the regions that succeeded discarded. + pub(crate) async fn handle_discard_pending_tails_by_table( + &self, + table_name: TableName, + node_id: u64, + ctx: QueryContextRef, + ) -> Result { + let table_info = self.table_info(&table_name).await?; + ensure_discard_supported( + &table_info.meta.engine, + table_info.is_physical_table(), + "discarding pending WAL tails from a Metric Engine logical table", + )?; + let region_ids = self + .physical_region_ids(&table_name, table_info.ident.table_id) + .await?; + let requests = region_ids + .iter() + .map(|region_id| { + RegionRequestBody::DiscardPendingTails(DiscardPendingTailsRequest { + region_id: (*region_id).into(), + datanode_id: node_id, + }) + }) + .collect(); + + info!( + user = ctx.current_user().username(), + "Handle table discard pending tails request: {table_name}, node: {node_id}" + ); + let results = self + .do_requests( + requests, + Some(build_db_string( + &table_name.catalog_name, + &table_name.schema_name, + )), + &ctx, + ) + .await?; + let discarded = results.iter().flatten().sum::(); + let mut first_error = None; + for (region_id, result) in region_ids.into_iter().zip(results) { + if let Err(e) = result { + error!(e; "Failed to discard the pending tails from node {node_id} in region {region_id} of table {table_name}"); + first_error.get_or_insert(e); + } + } + if let Some(e) = first_error { + warn!( + "Discarded {discarded} pending tails from node {node_id} in the regions of table {table_name} that succeeded" + ); + return Err(e); + } + if discarded == 0 { + info!("No pending tails from node {node_id} in table {table_name}"); + } + Ok(discarded) + } + + /// Returns the info of the table, or a [TableNotFound](crate::error::Error::TableNotFound) + /// error if the catalog has no such table. + async fn table_info(&self, table_name: &TableName) -> Result { + let table = self + .catalog_manager + .table( + &table_name.catalog_name, + &table_name.schema_name, + &table_name.table_name, + None, + ) + .await + .context(CatalogSnafu)?; + let table = table.with_context(|| TableNotFoundSnafu { + table_name: table_name.to_string(), + })?; + Ok(table.table_info()) + } + + /// Returns the region ids of the physical table behind `table_id`, from its physical + /// partition info. For a Metric Engine logical table these are the regions of its physical + /// table, so a caller that must not act on them rejects a logical table first. + async fn physical_region_ids( + &self, + table_name: &TableName, + table_id: TableId, + ) -> Result> { + Ok(self + .partition_manager + .find_physical_partition_info(table_id) + .await + .with_context(|_| FindTablePartitionRuleSnafu { + table_name: table_name.to_string(), + })? + .partitions + .iter() + .map(|partition| partition.id) + .collect()) + } } fn to_pb_compaction_time_range(range: TimestampRange) -> Result { @@ -373,6 +481,19 @@ impl Requester { db_string: Option, ctx: &QueryContextRef, ) -> Result { + self.do_requests(requests, db_string, ctx) + .await? + .into_iter() + .sum() + } + + /// Sends `requests` to their region leaders and returns the result of each. + async fn do_requests( + &self, + requests: Vec, + db_string: Option, + ctx: &QueryContextRef, + ) -> Result>> { let request_factory = RegionRequestFactory::new(RegionRequestHeader { tracing_context: TracingContext::from_current_span().to_w3c(), dbname: db_string.unwrap_or_else(|| ctx.get_db_string()), @@ -396,12 +517,10 @@ impl Requester { }); let results = future::try_join_all(tasks).await.context(JoinTaskSnafu)?; - let affected_rows = results + Ok(results .into_iter() .map(|resp| resp.map(|r| r.affected_rows)) - .sum::>()?; - - Ok(affected_rows) + .collect()) } async fn find_region_leader_by_request( @@ -412,6 +531,7 @@ impl Requester { RegionRequestBody::Flush(req) => req.region_id, RegionRequestBody::Compact(req) => req.region_id, RegionRequestBody::CancelCompaction(req) => req.region_id, + RegionRequestBody::DiscardPendingTails(req) => req.region_id, RegionRequestBody::BuildIndex(req) => req.region_id, RegionRequestBody::Truncate(req) => req.region_id, _ => { @@ -462,12 +582,14 @@ fn ensure_build_series_index_supported(engine: &str, is_physical_table: bool) -> Ok(()) } -fn ensure_discard_unflushed_supported(engine: &str, is_physical_table: bool) -> Result<()> { +fn ensure_discard_supported( + engine: &str, + is_physical_table: bool, + feat: &'static str, +) -> Result<()> { ensure!( engine != METRIC_ENGINE || is_physical_table, - NotSupportedSnafu { - feat: "discarding unflushed data from a Metric Engine logical table" - } + NotSupportedSnafu { feat } ); Ok(()) } @@ -552,6 +674,100 @@ mod tests { assert!(requests.try_recv().is_err()); } + #[tokio::test] + async fn test_discard_pending_tails_routes_by_node_and_sums_regions() { + use catalog::RegisterTableRequest; + use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME}; + use table::dist_table::DummyDataSource; + + let backend = test_util::prepare_mocked_backend().await; + let partition_manager = test_util::create_partition_rule_manager(backend).await; + let (sender, mut requests) = tokio::sync::mpsc::channel(8); + // Region `n` discards `n` tails, except that region 3 fails for node 7. + let watcher = DatanodeWatcher::new(sender).with_handler(|peer, request| { + let Some(RegionRequestBody::DiscardPendingTails(DiscardPendingTailsRequest { + datanode_id: node_id, + .. + })) = request.body + else { + panic!("expected a pending tails discard"); + }; + if peer.id == 3 && node_id == 7 { + return common_meta::error::UnexpectedSnafu { + err_msg: "mock error", + } + .fail(); + } + Ok(RegionResponse::new(peer.id as usize)) + }); + let catalog = catalog::memory::MemoryCatalogManager::with_default_setup(); + let table = Arc::new(table::Table::new( + Arc::new(test_util::new_test_table_info(1, "table_1", [].into_iter())), + table::metadata::FilterPushDownType::Unsupported, + Arc::new(DummyDataSource), + )); + catalog + .register_table_sync(RegisterTableRequest { + catalog: DEFAULT_CATALOG_NAME.to_string(), + schema: DEFAULT_SCHEMA_NAME.to_string(), + table_name: "table_1".to_string(), + table_id: 1, + table, + }) + .unwrap(); + let requester = Requester::new( + catalog, + partition_manager, + Arc::new(MockDatanodeManager::new(watcher)), + ); + let ctx = Arc::new(QueryContext::with( + DEFAULT_CATALOG_NAME, + DEFAULT_SCHEMA_NAME, + )); + let expected = |region_number, node_id| { + Some(RegionRequestBody::DiscardPendingTails( + DiscardPendingTailsRequest { + region_id: RegionId::new(1, region_number).as_u64(), + datanode_id: node_id, + }, + )) + }; + + let discarded = requester + .handle_discard_pending_tails(RegionId::new(1, 1), 7, ctx.clone()) + .await + .unwrap(); + assert_eq!(1, discarded); + let (peer, request) = requests.try_recv().unwrap(); + assert_eq!(1, peer.id); + assert_eq!(expected(1, 7), request.body); + assert!(requests.try_recv().is_err()); + + let table_name = TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "table_1"); + let mut sent_to_regions = |node_id| { + let mut sent = Vec::new(); + while let Ok((peer, request)) = requests.try_recv() { + assert_eq!(expected(peer.id as u32, node_id), request.body); + sent.push(peer.id); + } + sent.sort(); + sent + }; + let error = requester + .handle_discard_pending_tails_by_table(table_name.clone(), 7, ctx.clone()) + .await + .unwrap_err(); + assert!(matches!(error, crate::error::Error::RequestRegion { .. })); + assert_eq!(vec![1, 2, 3], sent_to_regions(7)); + + let discarded = requester + .handle_discard_pending_tails_by_table(table_name, 8, ctx) + .await + .unwrap(); + assert_eq!(1 + 2 + 3, discarded); + assert_eq!(vec![1, 2, 3], sent_to_regions(8)); + } + #[test] fn test_build_series_index_requires_physical_metric_table() { ensure_build_series_index_supported(METRIC_ENGINE, true).unwrap(); @@ -575,12 +791,13 @@ mod tests { } #[test] - fn test_discard_unflushed_rejects_metric_logical_table() { - let error = ensure_discard_unflushed_supported(METRIC_ENGINE, false).unwrap_err(); + fn test_ensure_discard_supported() { + let feat = "discarding pending WAL tails from a Metric Engine logical table"; + let error = ensure_discard_supported(METRIC_ENGINE, false, feat).unwrap_err(); assert!(matches!(error, crate::error::Error::NotSupported { .. })); - ensure_discard_unflushed_supported(METRIC_ENGINE, true).unwrap(); - ensure_discard_unflushed_supported("mito", false).unwrap(); + ensure_discard_supported(METRIC_ENGINE, true, feat).unwrap(); + ensure_discard_supported("mito", false, feat).unwrap(); } #[test] diff --git a/src/operator/src/table.rs b/src/operator/src/table.rs index 69eb85062b5..30c8d0dfcca 100644 --- a/src/operator/src/table.rs +++ b/src/operator/src/table.rs @@ -170,4 +170,30 @@ impl TableMutationHandler for TableMutationOperator { .map_err(BoxedError::new) .context(query_error::TableMutationSnafu) } + + async fn discard_pending_tails( + &self, + region_id: RegionId, + node_id: u64, + ctx: QueryContextRef, + ) -> QueryResult { + self.requester + .handle_discard_pending_tails(region_id, node_id, ctx) + .await + .map_err(BoxedError::new) + .context(query_error::TableMutationSnafu) + } + + async fn discard_pending_tails_by_table( + &self, + table_name: TableName, + node_id: u64, + ctx: QueryContextRef, + ) -> QueryResult { + self.requester + .handle_discard_pending_tails_by_table(table_name, node_id, ctx) + .await + .map_err(BoxedError::new) + .context(query_error::TableMutationSnafu) + } } diff --git a/src/query/src/datafusion.rs b/src/query/src/datafusion.rs index 30e4af7bdc5..25d4fc585ef 100644 --- a/src/query/src/datafusion.rs +++ b/src/query/src/datafusion.rs @@ -1566,6 +1566,24 @@ mod tests { ) -> common_query::error::Result { unimplemented!("unexpected discard_unflushed_data_by_table") } + + async fn discard_pending_tails( + &self, + _region_id: store_api::storage::RegionId, + _node_id: u64, + _ctx: session::context::QueryContextRef, + ) -> common_query::error::Result { + unimplemented!("unexpected discard_pending_tails") + } + + async fn discard_pending_tails_by_table( + &self, + _table_name: table::table_name::TableName, + _node_id: u64, + _ctx: session::context::QueryContextRef, + ) -> common_query::error::Result { + unimplemented!("unexpected discard_pending_tails_by_table") + } } fn native_schema() -> Arc { diff --git a/src/store-api/src/region_request.rs b/src/store-api/src/region_request.rs index f86184fd9f4..60d21091d80 100644 --- a/src/store-api/src/region_request.rs +++ b/src/store-api/src/region_request.rs @@ -25,9 +25,9 @@ use api::v1::region::bulk_insert_request::Body; use api::v1::region::{ AlterRequest, AlterRequests, BuildIndexRequest, BulkInsertRequest, CancelCompactionRequest, CleanUpRequest as PbCleanUpRequest, CloseRequest, CompactRequest, CreateRequest, - CreateRequests, DeleteRequests, DropRequest, DropRequests, FlushRequest, InsertRequests, - OpenRequest, TruncateRequest, alter_request, build_index_request, compact_request, - region_request, truncate_request, + CreateRequests, DeleteRequests, DiscardPendingTailsRequest, DropRequest, DropRequests, + FlushRequest, InsertRequests, OpenRequest, TruncateRequest, alter_request, build_index_request, + compact_request, region_request, truncate_request, }; use api::v1::{ self, Analyzer, ArrowIpc, FulltextBackend as PbFulltextBackend, Option as PbOption, Rows, @@ -162,6 +162,7 @@ pub enum RegionRequest { Flush(RegionFlushRequest), Compact(RegionCompactRequest), CancelCompaction(RegionCancelCompactionRequest), + DiscardPendingTails(RegionDiscardPendingTailsRequest), BuildIndex(RegionBuildIndexRequest), Truncate(RegionTruncateRequest), Catchup(RegionCatchupRequest), @@ -186,6 +187,9 @@ impl RegionRequest { region_request::Body::Flush(flush) => make_region_flush(flush), region_request::Body::Compact(compact) => make_region_compact(compact), region_request::Body::CancelCompaction(cancel) => make_region_cancel_compaction(cancel), + region_request::Body::DiscardPendingTails(discard) => { + make_region_discard_pending_tails(discard) + } region_request::Body::BuildIndex(index) => make_region_build_index(index), region_request::Body::Truncate(truncate) => make_region_truncate(truncate), region_request::Body::Creates(creates) => make_region_creates(creates), @@ -469,6 +473,17 @@ fn make_region_cancel_compaction( )]) } +fn make_region_discard_pending_tails( + discard: DiscardPendingTailsRequest, +) -> Result> { + Ok(vec![( + discard.region_id.into(), + RegionRequest::DiscardPendingTails(RegionDiscardPendingTailsRequest { + node_id: discard.datanode_id, + }), + )]) +} + fn make_region_build_index(index: BuildIndexRequest) -> Result> { let region_id = index.region_id.into(); Ok(vec![( @@ -1949,6 +1964,15 @@ pub struct RegionCancelCompactionRequest { pub task_id: String, } +/// Discards the region's pending WAL tails, the WAL ranges it still has to recover, that +/// datanode `node_id` wrote, without replaying them. Returns the number of discarded tails; a +/// region without such tails returns 0 and changes nothing. +#[derive(Debug)] +pub struct RegionDiscardPendingTailsRequest { + /// The datanode that wrote the tails. + pub node_id: u64, +} + #[derive(Debug)] pub struct RegionCompactRequest { pub options: compact_request::Options, @@ -2116,6 +2140,7 @@ impl fmt::Display for RegionRequest { RegionRequest::Flush(_) => write!(f, "Flush"), RegionRequest::Compact(_) => write!(f, "Compact"), RegionRequest::CancelCompaction(_) => write!(f, "CancelCompaction"), + RegionRequest::DiscardPendingTails(_) => write!(f, "DiscardPendingTails"), RegionRequest::BuildIndex(_) => write!(f, "BuildIndex"), RegionRequest::Truncate(_) => write!(f, "Truncate"), RegionRequest::Catchup(_) => write!(f, "Catchup"), @@ -2170,6 +2195,25 @@ mod tests { } } + #[test] + fn test_discard_pending_tails_request_wire() { + use api::v1::region::RegionRequest as PbRegionRequest; + use prost::Message; + + let bytes = include_bytes!( + "../../../tests/compatibility/wire/discard_pending_tails/discard_pending_tails.pb" + ); + let request = PbRegionRequest::decode(bytes.as_slice()).unwrap(); + assert_eq!(request.encode_to_vec(), bytes); + let mut requests = RegionRequest::try_from_request_body(request.body.unwrap()).unwrap(); + let (region_id, request) = requests.remove(0); + assert_eq!(RegionId::new(1024, 1), region_id); + let RegionRequest::DiscardPendingTails(request) = request else { + panic!("expected a pending tails discard, got {request:?}") + }; + assert_eq!(7, request.node_id); + } + #[test] fn test_build_index_options_round_trip() { use prost::Message; diff --git a/tests/cases/standalone/common/function/admin/discard_pending_tails.result b/tests/cases/standalone/common/function/admin/discard_pending_tails.result new file mode 100644 index 00000000000..f8e33d47625 --- /dev/null +++ b/tests/cases/standalone/common/function/admin/discard_pending_tails.result @@ -0,0 +1,84 @@ +CREATE TABLE discard_pending_tails_test ( + host STRING PRIMARY KEY, + val DOUBLE, + ts TIMESTAMP TIME INDEX +) PARTITION ON COLUMNS (host) ( + host < 'm', + host >= 'm' +) ENGINE = mito; + +Affected Rows: 0 + +INSERT INTO discard_pending_tails_test VALUES ('kept', 1, 1), ('remains', 2, 2); + +Affected Rows: 2 + +-- No region of the table has pending tails from the node, so nothing is discarded. +ADMIN discard_pending_tails('discard_pending_tails_test', 1); + ++--------------------------------------------------------------+ +| ADMIN discard_pending_tails('discard_pending_tails_test', 1) | ++--------------------------------------------------------------+ +| 0 | ++--------------------------------------------------------------+ + +SELECT host, val FROM discard_pending_tails_test ORDER BY host; + ++---------+-----+ +| host | val | ++---------+-----+ +| kept | 1.0 | +| remains | 2.0 | ++---------+-----+ + +-- The function must only be available through ADMIN. +-- SQLNESS REPLACE \nDid\syou\smean.* +SELECT discard_pending_tails('discard_pending_tails_test', 1); + +Error: 3000(PlanQuery), Failed to plan SQL: Error during planning: Invalid function 'discard_pending_tails'. + +DROP TABLE discard_pending_tails_test; + +Affected Rows: 0 + +CREATE TABLE discard_pending_tails_physical ( + ts TIMESTAMP TIME INDEX, + val DOUBLE +) ENGINE = metric WITH ("physical_metric_table" = ""); + +Affected Rows: 0 + +CREATE TABLE discard_pending_tails_logical ( + host STRING PRIMARY KEY, + val DOUBLE, + ts TIMESTAMP TIME INDEX +) ENGINE = metric WITH ("on_physical_table" = "discard_pending_tails_physical"); + +Affected Rows: 0 + +ADMIN discard_pending_tails('discard_pending_tails_physical', 1); + ++------------------------------------------------------------------+ +| ADMIN discard_pending_tails('discard_pending_tails_physical', 1) | ++------------------------------------------------------------------+ +| 0 | ++------------------------------------------------------------------+ + +-- Logical Metric Engine tables share their physical regions with other logical tables. +ADMIN discard_pending_tails('discard_pending_tails_logical', 1); + +Error: 1002(Unexpected), Failed to execute admin function discard_pending_tails: Execution error: Not supported: discarding pending WAL tails from a Metric Engine logical table + +DROP TABLE discard_pending_tails_logical; + +Affected Rows: 0 + +DROP TABLE discard_pending_tails_physical; + +Affected Rows: 0 + +-- A region id reaches the region path; this one belongs to no table. +ADMIN discard_pending_tails(4398046511104, 1); + +Error: 1002(Unexpected), Failed to execute admin function discard_pending_tails: Execution error: Failed to find table route: 1024 + diff --git a/tests/cases/standalone/common/function/admin/discard_pending_tails.sql b/tests/cases/standalone/common/function/admin/discard_pending_tails.sql new file mode 100644 index 00000000000..04642064bb2 --- /dev/null +++ b/tests/cases/standalone/common/function/admin/discard_pending_tails.sql @@ -0,0 +1,44 @@ +CREATE TABLE discard_pending_tails_test ( + host STRING PRIMARY KEY, + val DOUBLE, + ts TIMESTAMP TIME INDEX +) PARTITION ON COLUMNS (host) ( + host < 'm', + host >= 'm' +) ENGINE = mito; + +INSERT INTO discard_pending_tails_test VALUES ('kept', 1, 1), ('remains', 2, 2); + +-- No region of the table has pending tails from the node, so nothing is discarded. +ADMIN discard_pending_tails('discard_pending_tails_test', 1); + +SELECT host, val FROM discard_pending_tails_test ORDER BY host; + +-- The function must only be available through ADMIN. +-- SQLNESS REPLACE \nDid\syou\smean.* +SELECT discard_pending_tails('discard_pending_tails_test', 1); + +DROP TABLE discard_pending_tails_test; + +CREATE TABLE discard_pending_tails_physical ( + ts TIMESTAMP TIME INDEX, + val DOUBLE +) ENGINE = metric WITH ("physical_metric_table" = ""); + +CREATE TABLE discard_pending_tails_logical ( + host STRING PRIMARY KEY, + val DOUBLE, + ts TIMESTAMP TIME INDEX +) ENGINE = metric WITH ("on_physical_table" = "discard_pending_tails_physical"); + +ADMIN discard_pending_tails('discard_pending_tails_physical', 1); + +-- Logical Metric Engine tables share their physical regions with other logical tables. +ADMIN discard_pending_tails('discard_pending_tails_logical', 1); + +DROP TABLE discard_pending_tails_logical; + +DROP TABLE discard_pending_tails_physical; + +-- A region id reaches the region path; this one belongs to no table. +ADMIN discard_pending_tails(4398046511104, 1); diff --git a/tests/compatibility/README.md b/tests/compatibility/README.md index 47f80bafc76..45b80a75daf 100644 --- a/tests/compatibility/README.md +++ b/tests/compatibility/README.md @@ -43,6 +43,13 @@ as before the field existed: cargo nextest run -p store-api -E 'test(test_legacy_granted_region_wire)' ``` +The [pending tails discard fixture](wire/discard_pending_tails/README.md) checks that +a region request discarding pending WAL tails stays at body field 24: + +```shell +cargo nextest run -p store-api -E 'test(test_discard_pending_tails_request_wire)' +``` + ## Object store WAL fixtures Frozen objects of the object store WAL are checked byte for byte by the format tests of diff --git a/tests/compatibility/wire/discard_pending_tails/README.md b/tests/compatibility/wire/discard_pending_tails/README.md new file mode 100644 index 00000000000..fa2fb6f4163 --- /dev/null +++ b/tests/compatibility/wire/discard_pending_tails/README.md @@ -0,0 +1,31 @@ +# Pending tails discard wire compatibility + +A generated protobuf fixture of `greptime.v1.region.RegionRequest`, not a capture +from a released binary. + +`discard_pending_tails.pb` uses the schema at greptime-proto revision +`8aa45418597636516410c0c892dbd0269754a02c`, which adds +`DiscardPendingTailsRequest` as body field 24. Logical contents: region +`4398046511105` (table `1024`, region number `1`) and datanode `7`. + +SHA-256: `374e0c28eaee73e4df3f2e79a6345bf70caa589800c9eb5a19314d08a9ef5fa0`. + +Run the regression: + +```shell +cargo nextest run -p store-api -E 'test(test_discard_pending_tails_request_wire)' +``` + +The test checks that the fixture decodes to a pending tails discard of that +region and datanode, and that the decoded message encodes back to exactly the +fixture bytes, so the request stays at body field 24. + +## Reproduce the fixture + +With `PROTO_ROOT` pointing to the `proto` directory of that revision: + +```shell +printf '%s\n' 'discard_pending_tails { region_id: 4398046511105 datanode_id: 7 }' | + protoc --proto_path="$PROTO_ROOT" --encode=greptime.v1.region.RegionRequest \ + greptime/v1/region/server.proto > discard_pending_tails.pb +``` diff --git a/tests/compatibility/wire/discard_pending_tails/discard_pending_tails.pb b/tests/compatibility/wire/discard_pending_tails/discard_pending_tails.pb new file mode 100644 index 00000000000..70487dc7410 --- /dev/null +++ b/tests/compatibility/wire/discard_pending_tails/discard_pending_tails.pb @@ -0,0 +1,2 @@ + +�€€€€€ \ No newline at end of file