mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
fix(mito2): keep a region open when a flush-on-close cannot flush it (#10689)
* fix(mito2): keep a region open when a flush-on-close cannot flush it A close with `flush_on_close` whose region holds rows in its memtable but cannot flush in its current state, for example a follower, used to skip the flush and close the region anyway. It now fails with the retryable `FlushableRegionState` error and leaves the region open, so the caller retries and the retry flushes once the region can. The close reads whether the region can flush once. Closes without `flush_on_close` are unchanged. A metric physical region is reported by its data region, which closes first, so once a close has closed the data region its metadata region keeps no lease. A retry that finds the data region closed and the metadata region a follower waives the requested flush of the metadata region. That close keeps the region's unflushed rows that are in a WAL; a region without a WAL loses them, as before this change. Signed-off-by: jeremyhi <fengjiachun@gmail.com> * docs: state what a refused flush-on-close leaves to the caller Signed-off-by: jeremyhi <fengjiachun@gmail.com> --------- Signed-off-by: jeremyhi <fengjiachun@gmail.com>
This commit is contained in:
@@ -1009,6 +1009,83 @@ mod test {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::follower_at_retry(false)]
|
||||
#[case::leader_at_retry(true)]
|
||||
#[tokio::test]
|
||||
async fn test_close_with_flush_closes_follower_metadata_region_once_data_region_is_closed(
|
||||
#[case] leads_at_retry: bool,
|
||||
) {
|
||||
let env = TestEnv::new().await;
|
||||
// The periodic metadata flush must not persist the logical region before the test does.
|
||||
env.metric().inner.flush_task.stop().await.unwrap();
|
||||
env.init_metric_region().await;
|
||||
let engine = env.metric();
|
||||
let mito = env.mito();
|
||||
let physical_region_id = env.default_physical_region_id();
|
||||
let metadata_region_id = utils::to_metadata_region_id(physical_region_id);
|
||||
let data_region_id = utils::to_data_region_id(physical_region_id);
|
||||
// The metadata region holds the logical region in its memtable and cannot flush it.
|
||||
mito.set_region_role(metadata_region_id, RegionRole::Follower)
|
||||
.unwrap();
|
||||
let close = || {
|
||||
RegionRequest::Close(RegionCloseRequest {
|
||||
flush_on_close: true,
|
||||
})
|
||||
};
|
||||
|
||||
let error = engine
|
||||
.handle_request(physical_region_id, close())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(common_error::ext::RetryHint::Retryable, error.retry_hint());
|
||||
assert!(!mito.is_region_exists(data_region_id));
|
||||
assert!(mito.is_region_exists(metadata_region_id));
|
||||
assert!(engine.inner.is_physical_region(physical_region_id));
|
||||
|
||||
// The retry finds the data region closed. It flushes a metadata region that leads and
|
||||
// closes a follower without the flush.
|
||||
if leads_at_retry {
|
||||
mito.set_region_role(metadata_region_id, RegionRole::Leader)
|
||||
.unwrap();
|
||||
}
|
||||
engine
|
||||
.handle_request(physical_region_id, close())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!mito.is_region_exists(metadata_region_id));
|
||||
assert!(!engine.inner.is_physical_region(physical_region_id));
|
||||
|
||||
// Without WAL replay, only a flushed metadata region still holds the logical region.
|
||||
engine
|
||||
.handle_request(
|
||||
physical_region_id,
|
||||
RegionRequest::Open(RegionOpenRequest {
|
||||
engine: METRIC_ENGINE_NAME.to_string(),
|
||||
table_dir: TestEnv::default_table_dir(),
|
||||
path_type: PathType::Bare,
|
||||
options: [(PHYSICAL_TABLE_METADATA_KEY.to_string(), String::new())]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
skip_wal_replay: true,
|
||||
checkpoint: None,
|
||||
requirements: Default::default(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
leads_at_retry,
|
||||
engine
|
||||
.inner
|
||||
.state
|
||||
.read()
|
||||
.unwrap()
|
||||
.logical_regions()
|
||||
.contains_key(&env.default_logical_region_id())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_offline_cleanup_physical_region() {
|
||||
let env = TestEnv::new().await;
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
|
||||
//! Close a metric region
|
||||
|
||||
use common_telemetry::debug;
|
||||
use common_telemetry::{debug, info};
|
||||
use snafu::ResultExt;
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_engine::{RegionEngine, RegionRole};
|
||||
use store_api::region_request::{AffectedRows, RegionCloseRequest, RegionRequest};
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
@@ -68,20 +68,39 @@ impl MetricEngineInner {
|
||||
let data_region_id = utils::to_data_region_id(region_id);
|
||||
let metadata_region_id = utils::to_metadata_region_id(region_id);
|
||||
|
||||
// The engine reports a physical region by its data region, so once that is closed the
|
||||
// metadata region keeps no lease. A retry that finds the data region closed and the
|
||||
// metadata region a follower waives the requested flush of the metadata region. The role
|
||||
// is read before that close, so the waiver also holds for a metadata region promoted in
|
||||
// between. The close then releases the region's WAL only up to its flushed entry id, so
|
||||
// unflushed rows that are in a WAL are kept; a region without a WAL loses them, as on any
|
||||
// close of a region that cannot flush.
|
||||
let data_region_closed = !self.mito.is_region_exists(data_region_id);
|
||||
self.mito
|
||||
.handle_request(
|
||||
data_region_id,
|
||||
RegionRequest::Close(RegionCloseRequest { flush_on_close }),
|
||||
)
|
||||
.await
|
||||
.with_context(|_| CloseMitoRegionSnafu { region_id })?;
|
||||
.context(CloseMitoRegionSnafu { region_id })?;
|
||||
let skip_metadata_flush = flush_on_close
|
||||
&& data_region_closed
|
||||
&& self.mito.role(metadata_region_id) == Some(RegionRole::Follower);
|
||||
if skip_metadata_flush {
|
||||
info!(
|
||||
"Waiving the requested flush of follower metadata region {}, its data region is closed",
|
||||
metadata_region_id
|
||||
);
|
||||
}
|
||||
self.mito
|
||||
.handle_request(
|
||||
metadata_region_id,
|
||||
RegionRequest::Close(RegionCloseRequest { flush_on_close }),
|
||||
RegionRequest::Close(RegionCloseRequest {
|
||||
flush_on_close: flush_on_close && !skip_metadata_flush,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.with_context(|_| CloseMitoRegionSnafu { region_id })?;
|
||||
.context(CloseMitoRegionSnafu { region_id })?;
|
||||
|
||||
PHYSICAL_REGION_COUNT.dec();
|
||||
|
||||
|
||||
@@ -12,14 +12,16 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::assert_matches;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use api::v1::Rows;
|
||||
use common_base::Plugins;
|
||||
use common_error::ext::{ErrorExt, RetryHint};
|
||||
use common_recordbatch::RecordBatches;
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_engine::{RegionEngine, RegionRole};
|
||||
use store_api::region_request::{PathType, RegionCloseRequest, RegionOpenRequest, RegionRequest};
|
||||
use store_api::storage::{RegionId, ScanRequest};
|
||||
|
||||
@@ -27,6 +29,7 @@ use crate::config::MitoConfig;
|
||||
use crate::engine::flush_test::MockRegionHook;
|
||||
use crate::engine::listener::AlterFlushListener;
|
||||
use crate::engine::region_hook::RegionHookRef;
|
||||
use crate::error::Error;
|
||||
use crate::test_util::{
|
||||
CheckpointTaskBlocker, CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows,
|
||||
rows_schema,
|
||||
@@ -153,15 +156,28 @@ async fn test_engine_close_region_flush_on_close() {
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
// A follower cannot flush, so the close fails and leaves the region open.
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Close(RegionCloseRequest {
|
||||
flush_on_close: true,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.set_region_role(region_id, RegionRole::Follower)
|
||||
.unwrap();
|
||||
let close = || {
|
||||
RegionRequest::Close(RegionCloseRequest {
|
||||
flush_on_close: true,
|
||||
})
|
||||
};
|
||||
let err = engine.handle_request(region_id, close()).await.unwrap_err();
|
||||
assert_eq!(RetryHint::Retryable, err.retry_hint());
|
||||
assert_matches!(
|
||||
err.into_inner().as_any().downcast_ref::<Error>().unwrap(),
|
||||
Error::FlushableRegionState { .. }
|
||||
);
|
||||
assert!(engine.is_region_exists(region_id));
|
||||
|
||||
// The retry flushes once the region leads again.
|
||||
engine
|
||||
.set_region_role(region_id, RegionRole::Leader)
|
||||
.unwrap();
|
||||
engine.handle_request(region_id, close()).await.unwrap();
|
||||
assert!(!engine.is_region_exists(region_id));
|
||||
|
||||
engine
|
||||
@@ -186,6 +202,19 @@ async fn test_engine_close_region_flush_on_close() {
|
||||
.unwrap();
|
||||
let batches = RecordBatches::try_collect(stream).await.unwrap();
|
||||
assert_eq!(3, batches.iter().map(|b| b.num_rows()).sum::<usize>());
|
||||
|
||||
// A follower with nothing to flush still closes.
|
||||
assert_eq!(Some(RegionRole::Follower), engine.role(region_id));
|
||||
assert!(
|
||||
engine
|
||||
.get_region(region_id)
|
||||
.unwrap()
|
||||
.version()
|
||||
.memtables
|
||||
.is_empty()
|
||||
);
|
||||
engine.handle_request(region_id, close()).await.unwrap();
|
||||
assert!(!engine.is_region_exists(region_id));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -250,22 +250,12 @@ async fn test_staging_state_validation_patterns() {
|
||||
assert!(writable_is_writable, "Writable regions should be writable");
|
||||
|
||||
// Test flushable state check
|
||||
let staging_is_flushable = matches!(
|
||||
staging_state,
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable)
|
||||
| RegionRoleState::Leader(RegionLeaderState::Staging)
|
||||
| RegionRoleState::Leader(RegionLeaderState::Downgrading)
|
||||
);
|
||||
assert!(staging_is_flushable, "Staging regions should be flushable");
|
||||
|
||||
let writable_is_flushable = matches!(
|
||||
writable_state,
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable)
|
||||
| RegionRoleState::Leader(RegionLeaderState::Staging)
|
||||
| RegionRoleState::Leader(RegionLeaderState::Downgrading)
|
||||
assert!(
|
||||
staging_state.is_flushable(),
|
||||
"Staging regions should be flushable"
|
||||
);
|
||||
assert!(
|
||||
writable_is_flushable,
|
||||
writable_state.is_flushable(),
|
||||
"Writable regions should be flushable"
|
||||
);
|
||||
}
|
||||
|
||||
+11
-6
@@ -149,6 +149,16 @@ impl RegionRoleState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether a region in this state is admitted to flush.
|
||||
pub(crate) fn is_flushable(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Leader(RegionLeaderState::Writable)
|
||||
| Self::Leader(RegionLeaderState::Staging)
|
||||
| Self::Leader(RegionLeaderState::Downgrading)
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns whether the region is staging or ending staging. A staged edit belongs to the
|
||||
/// session too, which only [MitoRegion::in_staging_session] can tell.
|
||||
pub(crate) fn in_staging_session(self) -> bool {
|
||||
@@ -405,12 +415,7 @@ impl MitoRegion {
|
||||
|
||||
/// Returns whether the region is flushable.
|
||||
pub(crate) fn is_flushable(&self) -> bool {
|
||||
matches!(
|
||||
self.manifest_ctx.state.load(),
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable)
|
||||
| RegionRoleState::Leader(RegionLeaderState::Staging)
|
||||
| RegionRoleState::Leader(RegionLeaderState::Downgrading)
|
||||
)
|
||||
self.manifest_ctx.state.load().is_flushable()
|
||||
}
|
||||
|
||||
/// Returns whether the region should abort index building.
|
||||
|
||||
@@ -19,6 +19,7 @@ use store_api::logstore::LogStore;
|
||||
use store_api::region_request::{RegionCloseRequest, RegionFlushReason, RegionFlushRequest};
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::error::FlushableRegionStateSnafu;
|
||||
use crate::manifest::action::cap_wal_release;
|
||||
use crate::metrics::WAL_RELEASE_ADMISSION_FAILURE_TOTAL;
|
||||
use crate::region::MitoRegionRef;
|
||||
@@ -56,10 +57,19 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
self.reject_region_edits_as_not_found(region_id);
|
||||
}
|
||||
|
||||
// Memtables containing skip-WAL writes must be flushed before closing.
|
||||
// Followers cannot flush; explicit flush-on-close and region WAL options
|
||||
// retain their existing behavior.
|
||||
if close_needs_flush(®ion, &request) && region.is_flushable() {
|
||||
// The refusal and the flush decision use one snapshot of the state, so a concurrent role
|
||||
// change cannot skip both.
|
||||
let needs_flush = close_needs_flush(®ion, &request);
|
||||
let state = region.state();
|
||||
if request.flush_on_close && needs_flush && !state.is_flushable() {
|
||||
info!(
|
||||
"Region {} in state {:?} cannot flush before closing, keeping it open",
|
||||
region_id, state
|
||||
);
|
||||
sender.send(FlushableRegionStateSnafu { region_id, state }.fail());
|
||||
return;
|
||||
}
|
||||
if needs_flush && state.is_flushable() {
|
||||
// A region that awaits its Leader lease holds rows that exist nowhere else only if
|
||||
// it was written to, which happens only after it was routed to; a close, such as the
|
||||
// one of a shutdown, must not drop them. It gives up the role as a downgrade does, so
|
||||
@@ -92,7 +102,6 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
return;
|
||||
}
|
||||
|
||||
// No close-time flush is required, or the region cannot flush.
|
||||
let pending_closes = self.take_pending_closes(region_id);
|
||||
self.close_region(region_id).await;
|
||||
for ddl in pending_closes {
|
||||
|
||||
@@ -780,6 +780,12 @@ impl RegionCleanUpRequest {
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct RegionCloseRequest {
|
||||
/// Whether to flush the region before closing it.
|
||||
///
|
||||
/// When set and the engine cannot flush the region's unflushed data in its
|
||||
/// current state, the request fails with a retryable error and the region
|
||||
/// is not removed, so a retry of the close reaches it. An engine may
|
||||
/// instead close the region without the flush when no retry could perform
|
||||
/// it, and logs that it waived the flush.
|
||||
pub flush_on_close: bool,
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user