feat: report a downgraded region's last entry once durable and roll back for skip-WAL rows (#10765)

* feat: report a downgraded region's last entry once durable and roll back for skip-WAL rows

A downgrade of a region whose manifest is published conditionally (writes
require a lease and the WAL is the object store WAL) no longer flushes
unless the memtable holds rows that are not in the WAL; the next leader
recovers the rest from the source's WAL. A change to Follower reports the
last entry id only once the WAL is durable through it.

A downgrade reply now carries `has_skip_wal_writes` when the region may
still hold rows outside the WAL after the downgrade; the metasrv then
rolls the migration back instead of retrying or taking the region over,
and aborts with that reason. An empty memtable left marked by a failed
write no longer reports such rows.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: flush a downgrading region that skips the WAL and tighten tests

A handover of a region whose options skip the WAL records no tail of its
source, so a downgrade now flushes such a region even when its memtable
holds only rows logged before the option changed.

Tests cover that case, the metadata region's rows on the Noop WAL, a
Follower change that waits without holding the worker and again on a
region that is already a Follower, a flagged reply after an unflagged
one in the same batch, the failure of a write that installs no row, and
the abort reason of a failed candidate upgrade. Docs scope the meaning
of a false `has_skip_wal_writes` and of the metadata region's flush.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: report logged rows of a region that skips the WAL and bound an abandoned downgrade

A region whose options skip the WAL is handed over without a tail of its
source, so its unflushed rows count as rows the next leader cannot
recover from the WAL: `MitoRegion::has_skip_wal_writes` reports them and
decides the downgrade's flush, so a follower that cannot flush them rolls
the migration back.

The datanode bounds each region's downgrade, the flush and the change to
Follower together, by its flush timeout and replies with a retryable
error past it. The task that waits for the WAL to be durable stops
waiting once nobody waits for its reply, and a role change builds the
durability barrier only for a Follower.

Tests cover a follower whose options were made to skip the WAL, with and
without rows, a downgrade timeout that releases the region, and a
rollback of two requested regions; the abort reason of a failed
candidate upgrade is compared exactly.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: refuse a handover to a candidate with stale skip-WAL options

A candidate whose options skip the WAL commits an empty handover, which
records no tail of its source. An ALTER during the migration reaches only
the routed source, so a candidate can still skip the WAL while the source
logs rows it does not flush. Such a handover now fails, committing
nothing, when the source has unflushed WAL entries; the error is not
retryable, since only closing the candidate after the rollback fixes its
options.

The datanode waits for a shared downgrade flush without its own timer,
under the downgrade's single bound. Docs describe the rollback reason as
rows the candidate may not recover from the WAL, and when a false flag
can be trusted. Tests cover the refused handover and its recovery once
the options match, a flagged reply carrying an error, and a downgrade
timeout that waits until the durability wait is admitted.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: split the abandoned downgrade test and cover a deadline used up by the last attempt

The datanode test of a timed-out downgrade no longer waits for the
durability wait to be admitted, which raced the deadline; a Mito test
drops the reply of a Follower change once its wait is admitted and
checks that the region is released. A metasrv test covers a last
downgrade attempt whose mailbox expiry uses up the procedure's time:
the candidate upgrade then rolls the migration back without sending
anything. The rollback test keeps a flagged success and a flagged error.

Docs describe the skip-WAL predicate as rows the next leader may not
recover, scope the durability comment to a Follower change, note that
the metasrv must also understand the flag, and say why a refused
handover is not retried.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: scope the mock leader to the downgrade deadline test

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* refactor: report only skip-WAL rows now that a handover records the source's tail

A handover or takeover now records the source's tail even when the
candidate's options skip the WAL, so the rows a region logged before its
options turned skip_wal on are recovered from that tail. The downgrade
flush and the flag therefore count only rows written without the WAL:
every other row in the memtable is in the WAL up to the reported last
entry, which the Follower change still waits to be durable whatever the
region's options.

Tests run the source through the graceful downgrade: rows logged before
the option, with and without an earlier flush, reach a candidate by a
handover or by a takeover after the report was lost; a candidate that a
rolled-back migration left awaiting its Leader lease recovers the rows
the source logged since; a downgrade under enqueued acknowledgement
waits for those rows to be durable; and rows written while the WAL was
skipped stay reported after the option is turned off again.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: release the region before the durability wait and tighten downgrade tests

The task that changes a region to Follower finishes the work that needs
the region, including the fencing notification, before it waits for
the last entry to become durable, so a pending wait holds only the last
entry id, the barrier and the reply.

Tests check that a downgrade of an object store WAL region without
write leases still flushes, that each setup role change succeeds, and
that an abandoned wait is dropped, observed through the log store it
holds. Docs state the durability barrier per provider.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: cover a mixed downgrade flush, the flag on a timed-out downgrade and its abort reason

A downgrade's flush of logged and skip-WAL rows persists both, as a
reopen without WAL replay shows. A downgrade that times out still
reports the skip-WAL rows its region holds. The last downgrade attempt
that uses up the deadline aborts as a failed candidate upgrade. The
timeout reply is built in a match that rustfmt formats.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* docs: scope the downgrade flush skip and the reply fixture wording

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: let the only downgrade attempt use up the deadline

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: reply to a role change before the fencing notice unless a Follower waits for its WAL

Only a successful change to Follower notifies, releases the region and waits for its WAL before it replies; every other outcome replies first, as before. Log the entry the wait is for and an abandoned wait, and describe the deadline test's lease as ending with the procedure's time.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: drop the retry interval the single-attempt deadline test never waits

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: reply to a Leader change before its sweep, and check the partial-flush handover's bound

A successful change to Leader replies before it schedules the HDFS temp-file sweep, as before. The partial-flush handover case asserts that the source's flushed entry id is the first batch's last entry, strictly between zero and the final entry. The region server's skip-WAL accessor is crate-visible.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* docs: say which logged rows a handover and a takeover recover after a downgrade skips its flush

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: skip a retried downgrade's flush of a metric metadata region that is already a Follower

A downgrade whose change to Follower timed out after the metadata region became a Follower is retried with a Downgrading flush, which failed on the metadata region because a Follower is not flushable, so every retry failed. The flush now skips that region; its handover still fails while it holds entries its manifest does not cover. Drop tests that decide no condition this change adds, and tighten doc wording.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: flush a metric metadata Follower that still holds rows on a retried downgrade

Skip the retried downgrade's flush of the metadata region only when it is a Follower whose memtables are empty; one that still holds rows gets the flush, which fails as before. Restore the check that a flagged downgrade reply decodes into the pre-field layout.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: check the reason first and fence the pair in the dirty metadata Follower test

Read the metadata region's role and memtables only for a Downgrading flush. The dirty metadata Follower test sets the pair to DowngradingLeader through the metric engine, as the downgrade handler does, and checks that the flush fails on the Follower.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: check that only a downgrade's flush skips a flushed metadata Follower

The clean retry first sends a flush without a reason, which still fails on the metadata Follower, then the downgrade's flush, which skips it. A shared helper changes a role and asserts that it succeeded.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* style: address review nits on the downgrade reply and flush test

Name the role states through SettableRegionRoleState instead of importing its variants, order the derives of DowngradeRegionReply as elsewhere in the file, and drop the comment that restates the role helper.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

---------

Signed-off-by: jeremyhi <jiachun_feng@proton.me>
This commit is contained in:
jeremyhi authored and GitHub committed 2026-12-03 10:36:04 +00:00
1 parent a7216f7422
commit 10893e0412
31 files changed
+1330 -172

No files matched your search

+46 -3
View File
@@ -161,7 +161,7 @@ impl Display for RegionIdent {
}
/// The result of downgrade leader region.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct DowngradeRegionReply {
/// The [RegionId].
/// For compatibility, it is defaulted to [RegionId::new(0, 0)].
@@ -175,6 +175,13 @@ pub struct DowngradeRegionReply {
pub exists: bool,
/// Return error if any during the operation.
pub error: Option<InstructionError>,
/// Whether rows written without the WAL, which a takeover cannot recover, may remain on the
/// region, so the migration rolls back instead; false from a datanode that sets the field means
/// none remained when the reply was built. A datanode that predates the field never sets it,
/// and a metasrv that predates it ignores it, so the rollback protects such rows only once
/// both are upgraded. Omitted from the serialized form when false.
#[serde(default, skip_serializing_if = "store_api::is_false")]
pub has_skip_wal_writes: bool,
}
impl Display for DowngradeRegionReply {
@@ -349,9 +356,9 @@ impl OpenRegion {
pub struct DowngradeRegion {
/// The [RegionId].
pub region_id: RegionId,
/// The timeout of waiting for flush the region.
/// The timeout of the whole downgrade: the flush and the change to follower.
///
/// `None` stands for don't flush before downgrading the region.
/// `None` stands for don't flush before downgrading the region, with no timeout.
#[serde(default)]
pub flush_timeout: Option<Duration>,
}
@@ -1731,6 +1738,7 @@ mod tests {
metadata_last_entry_id: None,
exists: true,
error: None,
has_skip_wal_writes: false,
}),
);
@@ -1754,6 +1762,40 @@ mod tests {
);
}
#[test]
fn test_has_skip_wal_writes_wire() {
// A generated encoding in the layout before the field (see the fixture's README), not a
// capture from a release.
let legacy: &[u8] = include_bytes!(
"../../../../tests/compatibility/wire/downgrade_region_skip_wal_writes/legacy_downgrade_regions_reply.json"
);
let reply: InstructionReply = serde_json::from_slice(legacy).unwrap();
assert_eq!(serde_json::to_vec(&reply).unwrap(), legacy);
let replies = reply.expect_downgrade_regions_reply();
assert!(!replies[0].has_skip_wal_writes);
let flagged = DowngradeRegionReply {
has_skip_wal_writes: true,
..replies[0].clone()
};
let encoded = serde_json::to_value(&flagged).unwrap();
assert_eq!(
encoded["has_skip_wal_writes"],
serde_json::Value::Bool(true)
);
#[allow(dead_code)]
#[derive(Deserialize)]
struct LegacyDowngradeRegionReply {
#[serde(default)]
region_id: RegionId,
last_entry_id: Option<u64>,
metadata_last_entry_id: Option<u64>,
exists: bool,
error: Option<InstructionError>,
}
serde_json::from_value::<LegacyDowngradeRegionReply>(encoded).unwrap();
}
#[test]
fn test_deserialize_instruction() {
// legacy open region instruction
@@ -1865,6 +1907,7 @@ mod tests {
metadata_last_entry_id: None,
exists: true,
error: None,
has_skip_wal_writes: false,
}),
);
assert_eq!(downgrade_region_instruction_reply, downgrade_region_reply);
@@ -20,11 +20,10 @@ use common_telemetry::tracing::info;
use common_telemetry::{error, warn};
use futures::future::join_all;
use store_api::region_engine::{SetRegionRoleStateResponse, SettableRegionRoleState};
use store_api::region_request::{RegionFlushRequest, RegionRequest};
use store_api::region_request::{RegionFlushReason, RegionFlushRequest, RegionRequest};
use store_api::storage::RegionId;
use crate::heartbeat::handler::{HandlerContext, InstructionHandler};
use crate::heartbeat::task_tracker::WaitResult;
#[derive(Debug, Clone, Copy, Default)]
pub struct DowngradeRegionsHandler;
@@ -41,10 +40,8 @@ impl DowngradeRegionsHandler {
warn!("Region: {region_id} is not found");
return DowngradeRegionReply {
region_id,
last_entry_id: None,
metadata_last_entry_id: None,
exists: false,
error: None,
..Default::default()
};
};
@@ -60,9 +57,9 @@ impl DowngradeRegionsHandler {
}
// If flush_timeout is not set, directly convert region to follower.
let Some(flush_timeout) = flush_timeout else {
if flush_timeout.is_none() {
return ctx.downgrade_to_follower_gracefully(region_id).await;
};
}
// Sets region to downgrading,
// the downgrading region will reject all write requests.
@@ -77,30 +74,26 @@ impl DowngradeRegionsHandler {
warn!("Region: {region_id} is not found");
return DowngradeRegionReply {
region_id,
last_entry_id: None,
metadata_last_entry_id: None,
exists: false,
error: None,
..Default::default()
};
}
Ok(SetRegionRoleStateResponse::InvalidTransition(err)) => {
error!(err; "Failed to convert region to downgrading leader - invalid transition");
return DowngradeRegionReply {
region_id,
last_entry_id: None,
metadata_last_entry_id: None,
exists: true,
error: Some(InstructionError::from_error(&err)),
..Default::default()
};
}
Err(err) => {
error!(err; "Failed to convert region to downgrading leader");
return DowngradeRegionReply {
region_id,
last_entry_id: None,
metadata_last_entry_id: None,
exists: true,
error: Some(InstructionError::from_error(&err)),
..Default::default()
};
}
}
@@ -114,7 +107,10 @@ impl DowngradeRegionsHandler {
region_server_moved
.handle_request(
region_id,
RegionRequest::Flush(RegionFlushRequest::default()),
RegionRequest::Flush(RegionFlushRequest {
reason: Some(RegionFlushReason::Downgrading),
..Default::default()
}),
)
.await?;
@@ -127,27 +123,15 @@ impl DowngradeRegionsHandler {
warn!("Another flush task is running for the region: {region_id}");
}
// The caller bounds the wait; the flush keeps running for a retry to join.
let mut watcher = register_result.into_watcher();
let result = ctx.downgrade_tasks.wait(&mut watcher, flush_timeout).await;
match result {
WaitResult::Timeout => DowngradeRegionReply {
match ctx.downgrade_tasks.wait_until_finish(&mut watcher).await {
Ok(_) => ctx.downgrade_to_follower_gracefully(region_id).await,
Err(err) => DowngradeRegionReply {
region_id,
last_entry_id: None,
metadata_last_entry_id: None,
exists: true,
error: Some(InstructionError::legacy_internal_retryable(format!(
"Flush region timeout, region: {region_id}, timeout: {:?}",
flush_timeout
))),
},
WaitResult::Finish(Ok(_)) => ctx.downgrade_to_follower_gracefully(region_id).await,
WaitResult::Finish(Err(err)) => DowngradeRegionReply {
region_id,
last_entry_id: None,
metadata_last_entry_id: None,
exists: true,
error: Some(InstructionError::from_error(&err)),
..Default::default()
},
}
}
@@ -164,7 +148,39 @@ impl InstructionHandler for DowngradeRegionsHandler {
) -> Option<InstructionReply> {
let futures = downgrade_regions
.into_iter()
.map(|downgrade_region| Self::handle_downgrade_region(ctx, downgrade_region));
.map(|downgrade_region| async move {
let region_id = downgrade_region.region_id;
let flush_timeout = downgrade_region.flush_timeout;
let downgrade = Self::handle_downgrade_region(ctx, downgrade_region);
// One bound, no shorter than the metasrv's, covers the flush and the change to
// Follower, so an abandoned downgrade stops waiting for either.
let reply = match flush_timeout {
Some(timeout) => match tokio::time::timeout(timeout, downgrade).await {
Ok(reply) => reply,
Err(_) => {
warn!("Downgrade region {region_id} timed out after {timeout:?}");
let reason = format!(
"Downgrade region timeout, region: {region_id}, timeout: {timeout:?}"
);
DowngradeRegionReply {
region_id,
exists: true,
error: Some(InstructionError::legacy_internal_retryable(reason)),
..Default::default()
}
}
},
None => downgrade.await,
};
// Read after the downgrade, whose flush persists such rows, and whatever its
// outcome: rows still outside the WAL are lost if another node takes the region
// over.
let has_skip_wal_writes = ctx.region_server.has_skip_wal_writes(reply.region_id);
DowngradeRegionReply {
has_skip_wal_writes,
..reply
}
});
// Join all futures; parallelism is governed by the underlying flush scheduler.
let results = join_all(futures).await;
@@ -186,36 +202,32 @@ impl HandlerContext {
last_entry_id: success.last_entry_id(),
metadata_last_entry_id: success.metadata_last_entry_id(),
exists: true,
error: None,
..Default::default()
},
Ok(SetRegionRoleStateResponse::NotFound) => {
warn!("Region: {region_id} is not found");
DowngradeRegionReply {
region_id,
last_entry_id: None,
metadata_last_entry_id: None,
exists: false,
error: None,
..Default::default()
}
}
Ok(SetRegionRoleStateResponse::InvalidTransition(err)) => {
error!(err; "Failed to convert region to follower - invalid transition");
DowngradeRegionReply {
region_id,
last_entry_id: None,
metadata_last_entry_id: None,
exists: true,
error: Some(InstructionError::from_error(&err)),
..Default::default()
}
}
Err(err) => {
error!(err; "Failed to convert region to {}", SettableRegionRoleState::Follower);
DowngradeRegionReply {
region_id,
last_entry_id: None,
metadata_last_entry_id: None,
exists: true,
error: Some(InstructionError::from_error(&err)),
..Default::default()
}
}
}
@@ -228,17 +240,29 @@ mod tests {
use std::sync::Arc;
use std::time::Duration;
use api::v1::Rows;
use common_error::ext::RetryHint;
use common_meta::heartbeat::handler::{HandleControl, HeartbeatResponseHandler};
use common_meta::heartbeat::mailbox::MessageMeta;
use common_meta::instruction::{DowngradeRegion, Instruction};
use common_meta::kv_backend::memory::MemoryKvBackend;
use common_wal::config::object_store::{
AckMode, FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig,
};
use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions};
use log_store::ObjectStoreLogStore;
use mito2::config::MitoConfig;
use mito2::engine::MITO_ENGINE_NAME;
use mito2::test_util::{CreateRequestBuilder, TestEnv};
use mito2::test_util::{CreateRequestBuilder, TestEnv, build_rows, rows_schema};
use object_store::ObjectStore;
use object_store::services::Memory;
use store_api::region_engine::{
RegionEngine, RegionRole, SetRegionRoleStateResponse, SetRegionRoleStateSuccess,
};
use store_api::region_request::RegionRequest;
use store_api::region_request::{
AlterKind, RegionAlterRequest, RegionFlushReason, RegionFlushRequest, RegionPutRequest,
RegionRequest, SetRegionOption,
};
use store_api::storage::RegionId;
use tokio::time::Instant;
@@ -605,4 +629,218 @@ mod tests {
assert_eq!(engine.role(region_id).unwrap(), RegionRole::Follower);
assert_eq!(engine.role(region_id1).unwrap(), RegionRole::Follower);
}
#[tokio::test]
async fn test_failed_downgrade_flush_reports_skip_wal_writes() {
let mock_region_server = mock_region_server();
let region_id = RegionId::new(1024, 1);
let (mock_engine, _) =
MockRegionEngine::with_custom_apply_fn(MITO_ENGINE_NAME, |region_engine| {
region_engine.mock_role = Some(Some(RegionRole::Leader));
region_engine.mock_skip_wal_writes = true;
region_engine.handle_request_mock_fn = Some(Box::new(|_, request| {
let violated = match request {
RegionRequest::Flush(RegionFlushRequest {
reason: Some(RegionFlushReason::Downgrading),
..
}) => "mock flush failed",
_ => "not a downgrade's flush",
};
error::UnexpectedSnafu { violated }.fail()
}));
region_engine.handle_set_readonly_gracefully_mock_fn = Some(Box::new(|_| {
Ok(SetRegionRoleStateResponse::success(
SetRegionRoleStateSuccess::mito(1024),
))
}))
});
mock_region_server.register_test_region(region_id, mock_engine);
let kv_backend = Arc::new(MemoryKvBackend::new());
let handler_context = HandlerContext::new_for_test(mock_region_server, kv_backend);
let reply = DowngradeRegionsHandler
.handle(
&handler_context,
vec![DowngradeRegion {
region_id,
flush_timeout: Some(Duration::from_secs(1)),
}],
)
.await;
let reply = &reply.unwrap().expect_downgrade_regions_reply()[0];
let error = reply.error.as_ref().unwrap();
assert!(error.message.contains("mock flush failed"), "{error:?}");
assert!(reply.has_skip_wal_writes);
}
/// A downgrade reports the skip-WAL rows the region still holds after it: a follower cannot
/// flush them, while a writable leader flushes them and reports none. Rows logged before the
/// region's options skip the WAL are not reported.
#[tokio::test]
async fn test_downgrade_reports_skip_wal_writes_left_after_it() {
let mut region_server = mock_region_server();
let mut engine_env = TestEnv::with_prefix("downgrade-skip-wal-writes").await;
let engine = engine_env.create_engine(MitoConfig::default()).await;
region_server.register_engine(Arc::new(engine.clone()));
// Each region: whether its rows skip the WAL, whether it stays a writable leader, whether
// its options then skip the WAL, and the flag its downgrade reports.
let regions = [
(false, false, false, false),
(true, false, false, true),
(true, true, false, false),
(false, false, true, false),
];
for (number, (skip_wal, leader, skip_wal_option, _)) in (1..).zip(regions) {
let region_id = RegionId::new(1024, number);
let request = CreateRequestBuilder::new().build();
let schema = rows_schema(&request);
region_server
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
let put = RegionPutRequest {
skip_wal,
rows: Rows {
schema,
rows: build_rows(0, 3),
},
hint: None,
partition_expr_version: None,
};
region_server
.handle_request(region_id, RegionRequest::Put(put))
.await
.unwrap();
if !leader {
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
}
if skip_wal_option {
let alter = RegionAlterRequest {
kind: AlterKind::SetRegionOptions {
options: vec![SetRegionOption::SkipWal(true)],
},
};
region_server
.handle_request(region_id, RegionRequest::Alter(alter))
.await
.unwrap();
}
}
let kv_backend = Arc::new(MemoryKvBackend::new());
let handler_context = HandlerContext::new_for_test(region_server, kv_backend);
let downgrades = (1..)
.take(regions.len())
.map(|number| DowngradeRegion {
region_id: RegionId::new(1024, number),
flush_timeout: Some(Duration::from_secs(10)),
})
.collect();
let reply = DowngradeRegionsHandler
.handle(&handler_context, downgrades)
.await;
let replies = reply.unwrap().expect_downgrade_regions_reply();
assert!(replies.iter().all(|reply| reply.error.is_none()));
assert_eq!(
regions.map(|(_, _, _, flag)| flag).to_vec(),
replies
.iter()
.map(|reply| reply.has_skip_wal_writes)
.collect::<Vec<_>>()
);
assert_eq!(
Some(RegionRole::Follower),
engine.role(RegionId::new(1024, 3))
);
}
/// A downgrade whose change to Follower cannot finish before its timeout, since the upload of
/// its last entry never completes, replies with a retryable error that still reports the
/// skip-WAL rows, and drops the wait.
#[tokio::test]
async fn test_downgrade_timeout_releases_the_durability_wait() {
let config = ObjectStoreWalConfig {
ack_mode: AckMode::Enqueued,
..Default::default()
};
let log_store = ObjectStoreLogStore::try_new(
ObjectStore::new(Memory::default()).unwrap(),
&config,
0,
FIXED_DIRECTORY_GENERATION,
)
.await
.unwrap();
let mut engine_env = TestEnv::with_prefix("downgrade-timeout").await;
let engine = engine_env
.create_engine_with_log_store(MitoConfig::default(), log_store.clone())
.await;
let mut region_server = mock_region_server();
region_server.register_engine(Arc::new(engine.clone()));
let region_id = RegionId::new(1024, 1);
let wal_options = WalOptions::ObjectStore(ObjectStoreWalOptions::new(
config.node_prefix(0, FIXED_DIRECTORY_GENERATION),
));
let request = CreateRequestBuilder::new()
.insert_option(
WAL_OPTIONS_KEY,
&serde_json::to_string(&wal_options).unwrap(),
)
.build();
let schema = rows_schema(&request);
region_server
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// The logged put is acknowledged once enqueued; its upload never completes.
log_store.hold_creates();
for (skip_wal, start) in [(false, 0), (true, 3)] {
let put = RegionPutRequest {
skip_wal,
rows: Rows {
schema: schema.clone(),
rows: build_rows(start, start + 3),
},
hint: None,
partition_expr_version: None,
};
region_server
.handle_request(region_id, RegionRequest::Put(put))
.await
.unwrap();
}
engine
.set_region_role(region_id, RegionRole::Follower)
.unwrap();
let references = Arc::strong_count(&log_store);
let kv_backend = Arc::new(MemoryKvBackend::new());
let handler_context = HandlerContext::new_for_test(region_server, kv_backend);
let reply = tokio::time::timeout(
Duration::from_secs(10),
DowngradeRegionsHandler.handle(
&handler_context,
vec![DowngradeRegion {
region_id,
flush_timeout: Some(Duration::from_millis(200)),
}],
),
)
.await
.unwrap();
let reply = &reply.unwrap().expect_downgrade_regions_reply()[0];
let error = reply.error.as_ref().unwrap();
assert_eq!(RetryHint::Retryable, error.retry_hint, "{error:?}");
assert!(error.message.contains("timeout"), "{error:?}");
assert!(reply.has_skip_wal_writes);
tokio::time::timeout(Duration::from_secs(10), async {
while Arc::strong_count(&log_store) > references {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
}
+1 -69
View File
@@ -14,7 +14,6 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use futures_util::future::BoxFuture;
use snafu::ResultExt;
@@ -102,28 +101,6 @@ impl<T: Send + Sync + Clone> RegisterResult<T> {
}
}
/// The result of waiting.
pub(crate) enum WaitResult<T> {
Timeout,
Finish(Result<T>),
}
#[cfg(test)]
impl<T> WaitResult<T> {
/// Returns true if it's [WaitResult::Timeout].
pub(crate) fn is_timeout(&self) -> bool {
matches!(self, WaitResult::Timeout)
}
/// Into the [WaitResult::Timeout] if it's.
pub(crate) fn into_finish(self) -> Option<Result<T>> {
match self {
WaitResult::Timeout => None,
WaitResult::Finish(result) => Some(result),
}
}
}
impl<T: Send + Sync + Clone + 'static> TaskTracker<T> {
/// Returns an empty [AsyncTaskTracker].
pub(crate) fn new() -> Self {
@@ -132,19 +109,7 @@ impl<T: Send + Sync + Clone + 'static> TaskTracker<T> {
}
}
/// Waits for a [RegisterResult] and returns a [WaitResult].
pub(crate) async fn wait(
&self,
watcher: &mut TaskWatcher<T>,
timeout: Duration,
) -> WaitResult<T> {
match tokio::time::timeout(timeout, wait(watcher)).await {
Ok(result) => WaitResult::Finish(result),
Err(_) => WaitResult::Timeout,
}
}
/// Waits for a [RegisterResult] and returns a [WaitResult].
/// Waits until the task of a [RegisterResult] finishes.
pub(crate) async fn wait_until_finish(&self, watcher: &mut TaskWatcher<T>) -> Result<T> {
wait(watcher).await
}
@@ -196,7 +161,6 @@ impl<T: Send + Sync + Clone + 'static> TaskTracker<T> {
#[cfg(test)]
mod tests {
use std::time::Duration;
use store_api::storage::RegionId;
use tokio::sync::oneshot;
@@ -249,36 +213,4 @@ mod tests {
.await;
assert!(result.is_running());
}
#[tokio::test]
async fn test_async_task_tracker_wait_timeout() {
let tracker = TaskTracker::<TestResult>::new();
let region_id = RegionId::new(1024, 1);
let (tx, rx) = oneshot::channel::<()>();
let result = tracker
.try_register(
region_id,
Box::pin(async move {
let _ = rx.await;
Ok(TestResult { value: 1024 })
}),
)
.await;
let mut watcher = result.into_watcher();
let result = tracker.wait(&mut watcher, Duration::from_millis(100)).await;
assert!(result.is_timeout());
// Triggers first future return.
tx.send(()).unwrap();
let result = tracker
.wait(&mut watcher, Duration::from_millis(100))
.await
.into_finish()
.unwrap()
.unwrap();
assert_eq!(TestResult { value: 1024 }, result);
assert!(tracker.watcher(region_id).await.is_none());
}
}
+8
View File
@@ -549,6 +549,14 @@ impl RegionServer {
.and_then(|engine| engine.is_confirmed_leader(region_id))
}
/// See [`RegionEngine::has_skip_wal_writes`](store_api::region_engine::RegionEngine::has_skip_wal_writes).
pub(crate) fn has_skip_wal_writes(&self, region_id: RegionId) -> bool {
self.inner
.region_map
.get(&region_id)
.is_some_and(|engine| engine.has_skip_wal_writes(region_id))
}
pub fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<()> {
let engine = self
.inner
+9
View File
@@ -136,6 +136,7 @@ pub struct MockRegionEngine {
pub(crate) handle_stop_mock_fn: Option<MockStopHandler>,
pub(crate) mock_role: Option<Option<RegionRole>>,
pub(crate) mock_confirmed_leader: Option<bool>,
pub(crate) mock_skip_wal_writes: bool,
/// The candidate lease ids of the leases the engine received.
pub(crate) candidate_lease_ids: Mutex<Vec<Option<u64>>>,
engine: String,
@@ -156,6 +157,7 @@ impl MockRegionEngine {
handle_stop_mock_fn: None,
mock_role: None,
mock_confirmed_leader: None,
mock_skip_wal_writes: false,
candidate_lease_ids: Mutex::default(),
engine: engine.to_string(),
}),
@@ -180,6 +182,7 @@ impl MockRegionEngine {
handle_stop_mock_fn: None,
mock_role: None,
mock_confirmed_leader: None,
mock_skip_wal_writes: false,
candidate_lease_ids: Mutex::default(),
engine: engine.to_string(),
}),
@@ -204,6 +207,7 @@ impl MockRegionEngine {
handle_stop_mock_fn: None,
mock_role: None,
mock_confirmed_leader: None,
mock_skip_wal_writes: false,
candidate_lease_ids: Mutex::default(),
engine: engine.to_string(),
}),
@@ -229,6 +233,7 @@ impl MockRegionEngine {
handle_stop_mock_fn: None,
mock_role: None,
mock_confirmed_leader: None,
mock_skip_wal_writes: false,
candidate_lease_ids: Mutex::default(),
engine: engine.to_string(),
};
@@ -342,6 +347,10 @@ impl RegionEngine for MockRegionEngine {
})
}
fn has_skip_wal_writes(&self, _region_id: RegionId) -> bool {
self.mock_skip_wal_writes
}
async fn sync_region(
&self,
region_id: RegionId,
+15 -1
View File
@@ -377,6 +377,18 @@ pub enum Error {
location: Location,
},
#[snafu(display(
"Leader {} of region {} may hold rows its candidate cannot recover from the WAL",
peer_id,
region_id
))]
LeaderHoldsSkipWalWrites {
region_id: RegionId,
peer_id: u64,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Failed to downgrade region leader, region: {}", region_id))]
DowngradeLeader {
region_id: RegionId,
@@ -1079,7 +1091,9 @@ impl ErrorExt for Error {
| Error::PeerUnavailable { .. }
| Error::PusherNotFound { .. } => StatusCode::Unexpected,
Error::MailboxTimeout { .. } | Error::ExceededDeadline { .. } => StatusCode::Cancelled,
Error::RepartitionPendingTails { .. } => StatusCode::RegionNotReady,
Error::RepartitionPendingTails { .. } | Error::LeaderHoldsSkipWalWrites { .. } => {
StatusCode::RegionNotReady
}
Error::PruneTaskAlreadyRunning { .. }
| Error::DrainDatanodeRunning { .. }
| Error::RetryLater { .. }
@@ -248,6 +248,7 @@ fn mock_instruction_reply(message: &MailboxMessage) -> Option<MailboxMessage> {
metadata_last_entry_id: Some(1),
exists: true,
error: None,
has_skip_wal_writes: false,
})
.collect(),
))
@@ -348,6 +348,8 @@ pub struct VolatileContext {
/// The regions whose upgrade reply from the candidate has been accepted. A retry of the
/// upgrade does not send them again.
upgraded_regions: HashSet<RegionId>,
/// Why a step rolls the migration back, if it is not a failed upgrade of the candidate.
rollback_reason: Option<String>,
/// Metrics of region migration.
metrics: Metrics,
}
@@ -76,12 +76,19 @@ impl State for DowngradeLeaderRegion {
ctx.persistent_ctx.region_ids
);
}
Err(error::Error::ExceededDeadline { .. }) => {
Err(err @ error::Error::ExceededDeadline { .. }) => {
info!(
"Downgrade region leader exceeded deadline, region: {:?}",
ctx.persistent_ctx.region_ids
);
// Rollbacks the metadata if procedure is timeout
ctx.volatile_ctx.rollback_reason = Some(err.to_string());
return Ok((Box::new(UpdateMetadata::Rollback), Status::executing(false)));
}
Err(err @ error::Error::LeaderHoldsSkipWalWrites { .. }) => {
warn!(err; "Rolling back the migration of regions {:?}", ctx.persistent_ctx.region_ids);
// The leader keeps the rows, since the candidate may not recover them.
ctx.volatile_ctx.rollback_reason = Some(err.to_string());
return Ok((Box::new(UpdateMetadata::Rollback), Status::executing(false)));
}
Err(err) => {
@@ -145,6 +152,7 @@ impl DowngradeLeaderRegion {
metadata_last_entry_id,
exists,
error,
..
} = reply;
if let Some(error) = error {
@@ -205,7 +213,7 @@ impl DowngradeLeaderRegion {
///
/// Retry:
/// - [MailboxTimeout](error::Error::MailboxTimeout), Timeout.
/// - The Datanode replies with a retryable error.
/// - The Datanode replies, without the `has_skip_wal_writes` flag, with a retryable error.
/// - The Datanode replies, without an error, that the region doesn't exist. A closing
/// region leaves the region map while its manifest write may still be in flight.
///
@@ -216,6 +224,8 @@ impl DowngradeLeaderRegion {
/// - [MailboxReceiver](error::Error::MailboxReceiver), The sender is dropped without sending (impossible).
/// - [UnexpectedInstructionReply](error::Error::UnexpectedInstructionReply).
/// - [ExceededDeadline](error::Error::ExceededDeadline)
/// - [LeaderHoldsSkipWalWrites](error::Error::LeaderHoldsSkipWalWrites), a reply carries the
/// `has_skip_wal_writes` flag.
/// - Invalid JSON.
async fn downgrade_region(&self, ctx: &mut Context) -> Result<()> {
let region_ids = &ctx.persistent_ctx.region_ids;
@@ -262,6 +272,13 @@ impl DowngradeLeaderRegion {
.fail();
};
if let Some(reply) = replies.iter().find(|reply| reply.has_skip_wal_writes) {
return error::LeaderHoldsSkipWalWritesSnafu {
region_id: reply.region_id,
peer_id: leader.id,
}
.fail();
}
let mut result = Ok(());
for reply in replies {
let handled = self.handle_downgrade_region_reply(ctx, &reply, &now);
@@ -351,6 +368,7 @@ impl DowngradeLeaderRegion {
///
/// Abort:
/// - ExceededDeadline
/// - LeaderHoldsSkipWalWrites
async fn downgrade_region_with_retry(&self, ctx: &mut Context) -> Result<()> {
let mut retry = 0;
@@ -363,6 +381,8 @@ impl DowngradeLeaderRegion {
if matches!(err, error::Error::ExceededDeadline { .. }) {
error!(err; "Failed to downgrade region leader, regions: {:?}, exceeded deadline", ctx.persistent_ctx.region_ids);
return Err(err);
} else if matches!(err, error::Error::LeaderHoldsSkipWalWrites { .. }) {
return Err(err);
} else if matches!(err, error::Error::PusherNotFound { .. }) {
// Throws the error immediately if the datanode is unreachable.
error!(err; "Failed to downgrade region leader, regions: {:?}, datanode({}) is unreachable(PusherNotFound)", ctx.persistent_ctx.region_ids, ctx.persistent_ctx.from_peer.id);
@@ -402,9 +422,10 @@ mod tests {
use common_meta::key::table_route::TableRouteValue;
use common_meta::key::test_utils::new_test_table_info;
use common_meta::peer::Peer;
use common_meta::rpc::router::{Region, RegionRoute};
use common_meta::rpc::router::{LeaderState, Region, RegionRoute};
use common_meta::wal_provider::RegionWalOptions;
use store_api::storage::RegionId;
use tokio::sync::mpsc::error::TryRecvError;
use tokio::time::Instant;
use super::*;
@@ -430,14 +451,17 @@ mod tests {
}
async fn prepare_table_metadata(ctx: &Context, wal_options: RegionWalOptions) {
let region_id = ctx.persistent_ctx.region_ids[0];
let table_info = new_test_table_info(region_id.table_id());
let region_routes = vec![RegionRoute {
region: Region::new_test(region_id),
leader_peer: Some(ctx.persistent_ctx.from_peer.clone()),
follower_peers: vec![ctx.persistent_ctx.to_peer.clone()],
..Default::default()
}];
let region_ids = &ctx.persistent_ctx.region_ids;
let table_info = new_test_table_info(region_ids[0].table_id());
let region_routes = region_ids
.iter()
.map(|region_id| RegionRoute {
region: Region::new_test(*region_id),
leader_peer: Some(ctx.persistent_ctx.from_peer.clone()),
follower_peers: vec![ctx.persistent_ctx.to_peer.clone()],
..Default::default()
})
.collect();
ctx.table_metadata_manager
.create_table_metadata(
table_info,
@@ -488,7 +512,7 @@ mod tests {
#[tokio::test]
async fn test_procedure_exceeded_deadline() {
let state = DowngradeLeaderRegion::default();
let mut state = DowngradeLeaderRegion::default();
let persistent_context = new_persistent_context();
let env = TestingEnv::new();
let mut ctx = env.context_factory().new_context(persistent_context);
@@ -507,6 +531,12 @@ mod tests {
.unwrap_err();
assert_matches!(err, Error::ExceededDeadline { .. });
assert!(!err.is_retryable());
let procedure_ctx = new_procedure_context();
let (mut rollback, _) = state.next(&mut ctx, &procedure_ctx).await.unwrap();
let (mut abort, _) = rollback.next(&mut ctx, &procedure_ctx).await.unwrap();
let error = abort.next(&mut ctx, &procedure_ctx).await.unwrap_err();
assert!(error.to_string().contains("Exceeded deadline"), "{error}");
}
#[tokio::test]
@@ -606,6 +636,7 @@ mod tests {
metadata_last_entry_id: None,
exists: false,
error: None,
has_skip_wal_writes: false,
};
let failed = DowngradeRegionReply {
region_id: RegionId::new(1024, 2),
@@ -617,6 +648,7 @@ mod tests {
"non retryable mocked",
RetryHint::NonRetryable,
)),
has_skip_wal_writes: false,
};
let downgraded = DowngradeRegionReply {
region_id: RegionId::new(1024, 3),
@@ -624,6 +656,7 @@ mod tests {
metadata_last_entry_id: None,
exists: true,
error: None,
has_skip_wal_writes: false,
};
for (replies, retryable) in [
@@ -843,6 +876,7 @@ mod tests {
metadata_last_entry_id: None,
exists: false,
error: None,
has_skip_wal_writes: false,
},
DowngradeRegionReply {
region_id: downgraded_region_id,
@@ -850,6 +884,7 @@ mod tests {
metadata_last_entry_id: Some(2),
exists: true,
error: None,
has_skip_wal_writes: false,
},
];
Ok(new_downgrade_regions_reply(id, replies))
@@ -908,4 +943,158 @@ mod tests {
let update_metadata = next.as_any().downcast_ref::<UpdateMetadata>().unwrap();
assert_matches!(update_metadata, UpdateMetadata::Rollback);
}
/// A leader that holds rows that are not in its WAL keeps the region: the procedure rolls the
/// whole batch back at once instead of retrying or taking the region over, whatever an
/// earlier reply of the batch says.
#[tokio::test]
async fn test_next_rolls_back_if_leader_holds_skip_wal_writes() {
for error in [
None,
Some(InstructionError::legacy_internal_retryable("flush failed")),
] {
let mut state = Box::<DowngradeLeaderRegion>::default();
let region_ids = vec![RegionId::new(1024, 1), RegionId::new(1024, 2)];
let persistent_context = PersistentContext::new(
vec![("greptime".into(), "public".into())],
Peer::empty(1),
Peer::empty(2),
region_ids.clone(),
Duration::from_millis(1000),
RegionMigrationTriggerReason::Unknown,
);
let from_peer_id = persistent_context.from_peer.id;
let mut env = TestingEnv::new();
let mut ctx = env.context_factory().new_context(persistent_context);
prepare_table_metadata(&ctx, HashMap::default()).await;
let procedure_ctx = new_procedure_context();
UpdateMetadata::Downgrade
.downgrade_leader_region(&mut ctx, &procedure_ctx.provider)
.await
.unwrap();
let table_metadata_manager = env.table_metadata_manager().clone();
let leader_states = || async {
let table_route = table_metadata_manager
.table_route_manager()
.table_route_storage()
.get(1024)
.await
.unwrap()
.unwrap();
table_route
.region_routes()
.unwrap()
.iter()
.map(|route| (route.region.id, route.leader_state))
.collect::<Vec<_>>()
};
assert_eq!(
region_ids
.iter()
.map(|region_id| (*region_id, Some(LeaderState::Downgrading)))
.collect::<Vec<_>>(),
leader_states().await
);
let mailbox_ctx = env.mailbox_context();
let mailbox = mailbox_ctx.mailbox().clone();
let (tx, rx) = tokio::sync::mpsc::channel(1);
mailbox_ctx
.insert_heartbeat_response_receiver(Channel::Datanode(from_peer_id), tx)
.await;
let attempts = Arc::new(AtomicUsize::new(0));
let attempts_moved = attempts.clone();
send_mock_reply(mailbox, rx, move |id| {
attempts_moved.fetch_add(1, Ordering::Relaxed);
let unflagged = DowngradeRegionReply {
region_id: RegionId::new(1024, 1),
last_entry_id: error.is_none().then_some(1),
exists: true,
error: error.clone(),
..Default::default()
};
// A follower reports the flag with its last entry id, a failed flush with its error.
let flagged = DowngradeRegionReply {
region_id: RegionId::new(1024, 2),
last_entry_id: error.is_none().then_some(1),
exists: true,
error: error.clone(),
has_skip_wal_writes: true,
..Default::default()
};
Ok(new_downgrade_regions_reply(id, vec![unflagged, flagged]))
});
let (mut next, _) = state.next(&mut ctx, &procedure_ctx).await.unwrap();
let update_metadata = next.as_any().downcast_ref::<UpdateMetadata>().unwrap();
assert_matches!(update_metadata, UpdateMetadata::Rollback);
assert_eq!(attempts.load(Ordering::Relaxed), 1);
assert!(ctx.volatile_ctx.leader_region_last_entry_ids.is_empty());
let (mut abort, _) = next.next(&mut ctx, &procedure_ctx).await.unwrap();
assert_eq!(
region_ids
.iter()
.map(|region_id| (*region_id, None))
.collect::<Vec<_>>(),
leader_states().await
);
let error = abort.next(&mut ctx, &procedure_ctx).await.unwrap_err();
assert!(
error.to_string().contains("cannot recover from the WAL"),
"{error}"
);
}
}
/// A last downgrade attempt that gets no reply until its mailbox expiry uses up the procedure's
/// time sends the migration through the slow path to the candidate upgrade, which then rolls
/// the migration back without sending the candidate anything and aborts as a failed upgrade.
#[tokio::test]
async fn test_downgrade_that_uses_up_the_deadline_rolls_back_without_upgrade() {
let mut state = Box::new(DowngradeLeaderRegion {
optimistic_retry: 1,
..Default::default()
});
let persistent_context = new_persistent_context();
let from_peer_id = persistent_context.from_peer.id;
let to_peer_id = persistent_context.to_peer.id;
let mut env = TestingEnv::new();
let mut ctx = env.context_factory().new_context(persistent_context);
prepare_table_metadata(&ctx, HashMap::default()).await;
let mailbox_ctx = env.mailbox_context();
let (tx, mut rx) = tokio::sync::mpsc::channel(4);
mailbox_ctx
.insert_heartbeat_response_receiver(Channel::Datanode(from_peer_id), tx)
.await;
let (candidate_tx, mut candidate_rx) = tokio::sync::mpsc::channel(4);
mailbox_ctx
.insert_heartbeat_response_receiver(Channel::Datanode(to_peer_id), candidate_tx)
.await;
// The lease ends with the procedure's time, so once the mailbox expiry ends the only
// attempt the test does not wait for the lease.
ctx.volatile_ctx
.set_leader_region_lease_deadline(ctx.persistent_ctx.timeout);
let procedure_ctx = new_procedure_context();
let (mut next, status) = state.next(&mut ctx, &procedure_ctx).await.unwrap();
// The only request stayed in the leader's queue until its mailbox deadline expired.
assert_matches!(rx.try_recv(), Ok(Ok(_)));
assert_matches!(rx.try_recv(), Err(TryRecvError::Empty));
assert_matches!(status, Status::Executing { persist: false, .. });
assert!(ctx.next_operation_timeout().is_none());
assert!(next.as_any().is::<UpgradeCandidateRegion>());
let (mut next, _) = next.next(&mut ctx, &procedure_ctx).await.unwrap();
let update_metadata = next.as_any().downcast_ref::<UpdateMetadata>().unwrap();
assert_matches!(update_metadata, UpdateMetadata::Rollback);
assert_matches!(candidate_rx.try_recv(), Err(TryRecvError::Empty));
let (mut abort, _) = next.next(&mut ctx, &procedure_ctx).await.unwrap();
let error = abort.next(&mut ctx, &procedure_ctx).await.unwrap_err();
assert_matches!(
error,
Error::MigrationAbort { reason, .. } if reason == "Failed to upgrade the candidate region."
);
}
}
@@ -82,9 +82,10 @@ impl State for UpdateMetadata {
"Failed to broadcast the invalidate table cache message during the rollback, error: {err:?}"
);
};
let reason = ctx.volatile_ctx.rollback_reason.as_deref();
Ok((
Box::new(RegionMigrationAbort::new(
"Failed to upgrade the candidate region.",
reason.unwrap_or("Failed to upgrade the candidate region."),
)),
Status::executing(false),
))
@@ -156,12 +156,17 @@ mod tests {
let table_metadata_manager = env.table_metadata_manager();
let procedure_ctx = new_procedure_context();
let (next, _) = state.next(&mut ctx, &procedure_ctx).await.unwrap();
let (mut next, _) = state.next(&mut ctx, &procedure_ctx).await.unwrap();
let _ = next
.as_any()
.downcast_ref::<RegionMigrationAbort>()
.unwrap();
let error = next.next(&mut ctx, &procedure_ctx).await.unwrap_err();
assert_matches!(
error,
Error::MigrationAbort { reason, .. } if reason == "Failed to upgrade the candidate region."
);
let table_route = table_metadata_manager
.table_route_manager()
+1
View File
@@ -217,6 +217,7 @@ pub fn new_downgrade_region_reply(
metadata_last_entry_id: None,
exists: exist,
error: legacy_instruction_error(error),
has_skip_wal_writes: false,
}],
)
}
+3
View File
@@ -64,6 +64,9 @@ Mito2 data region. Queries against a physical region pass straight through.
- **Physical column rules** (`engine/alter/`): ordinary metric fields stay on
logical tables; shared physical field adds are only for the native histogram
Struct field.
- **Metadata region catchup** (`engine/catchup.rs`, `mito_catchup_requests`): it names no source
and so takes no WAL tail, which is why `flush_region` (`engine/flush.rs`) flushes the metadata
region in full on a downgrade. Change the two together.
## Testing
+7
View File
@@ -562,6 +562,13 @@ impl RegionEngine for MetricEngine {
Some(metadata && data)
}
fn has_skip_wal_writes(&self, region_id: RegionId) -> bool {
let mito = &self.inner.mito;
self.inner.is_physical_region(region_id)
&& (mito.has_skip_wal_writes(utils::to_metadata_region_id(region_id))
|| mito.has_skip_wal_writes(utils::to_data_region_id(region_id)))
}
fn as_any(&self) -> &dyn Any {
self
}
+2
View File
@@ -112,6 +112,8 @@ fn mito_catchup_requests(
// source's unflushed metadata yet: it replays only this node's WAL and commits
// with no candidate-lease check. The candidate lease id tells a repeat of the
// migration's catchup from one of another migration.
// Since this catchup takes no tail, `flush_region` keeps the metadata region fully
// flushed on a downgrade; the two change together.
source_node_id: None,
candidate_lease_id: req.candidate_lease_id,
},
+223 -8
View File
@@ -13,8 +13,10 @@
// limitations under the License.
use snafu::ResultExt;
use store_api::region_engine::RegionEngine;
use store_api::region_request::{AffectedRows, RegionFlushRequest, RegionRequest};
use store_api::region_engine::{RegionEngine, RegionRole};
use store_api::region_request::{
AffectedRows, RegionFlushReason, RegionFlushRequest, RegionRequest,
};
use store_api::storage::RegionId;
use crate::engine::MetricEngineInner;
@@ -35,12 +37,27 @@ impl MetricEngineInner {
}
let metadata_region_id = utils::to_metadata_region_id(region_id);
// Flushes the metadata region as well
self.mito
.handle_request(metadata_region_id, RegionRequest::Flush(req.clone()))
.await
.context(MitoFlushOperationSnafu)
.map(|response| response.affected_rows)?;
// Flushes the metadata region as well. Its catchup names no source, so a handover takes
// no tail of this node's WAL for it (see `mito_catchup_requests`), and a downgrade flushes
// it in full, as a downgrading region flushes a request without a reason.
// A downgrade retried after an earlier attempt flushed the metadata region and made only
// it a Follower skips it, as a Follower is not flushable; a Follower that still holds rows
// gets the flush, which fails.
let downgrading = req.reason == Some(RegionFlushReason::Downgrading);
let skip_metadata = downgrading
&& self.mito.role(metadata_region_id) == Some(RegionRole::Follower)
&& self.mito.is_memtable_empty(metadata_region_id) == Some(true);
if !skip_metadata {
let metadata_req = RegionFlushRequest {
reason: req.reason.filter(|_| !downgrading),
..req.clone()
};
self.mito
.handle_request(metadata_region_id, RegionRequest::Flush(metadata_req))
.await
.context(MitoFlushOperationSnafu)
.map(|response| response.affected_rows)?;
}
let data_region_id = utils::to_data_region_id(region_id);
self.mito
@@ -53,9 +70,21 @@ impl MetricEngineInner {
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
use api::v1::Rows;
use common_wal::config::object_store::{FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig};
use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions};
use futures_util::TryStreamExt;
use itertools::Itertools as _;
use log_store::ObjectStoreLogStore;
use mito2::config::MitoConfig;
use mito2::test_util::TestEnv as MitoTestEnv;
use object_store::ObjectStore;
use object_store::services::Memory;
use store_api::region_engine::{
RegionRole, SetRegionRoleStateResponse, SettableRegionRoleState,
};
use store_api::region_request::RegionPutRequest;
use super::*;
@@ -174,4 +203,190 @@ StorageSstEntry { file_path: "test_metric_region/22_0000000042/data/index/<file_
StorageSstEntry { file_path: "test_metric_region/22_0000000042/metadata/<file_id>.parquet", file_size: None, last_modified_ms: None, node_id: None }"#
);
}
/// A downgrade's flush of a physical region whose regions publish their manifests
/// conditionally flushes the metadata region, whose next leader replays none of this node's
/// WAL, and the data region only if it holds rows that are not in the WAL.
#[rstest::rstest]
#[case::logged(false)]
#[case::skip_wal(true)]
#[tokio::test]
async fn test_downgrade_flushes_metadata_region(#[case] skip_wal: bool) {
let config = ObjectStoreWalConfig::default();
let wal = ObjectStoreLogStore::try_new(
ObjectStore::new(Memory::default()).unwrap(),
&config,
0,
FIXED_DIRECTORY_GENERATION,
)
.await
.unwrap();
let mut mito_env = MitoTestEnv::with_prefix("metric-downgrade-flush").await;
let mito = mito_env
.create_engine_with_log_store(MitoConfig::default(), wal)
.await;
mito.require_write_lease();
let now = Instant::now();
mito.freeze_lease_clock(now);
let env = TestEnv::with_mito_engine(mito_env, mito.clone());
let region_id = RegionId::new(1, 1);
let wal_options = WalOptions::ObjectStore(ObjectStoreWalOptions::new(
config.node_prefix(0, FIXED_DIRECTORY_GENERATION),
));
env.create_physical_region(
region_id,
"test_metric_table",
vec![(
WAL_OPTIONS_KEY.to_string(),
serde_json::to_string(&wal_options).unwrap(),
)],
)
.await;
let engine = env.metric();
engine
.set_region_role_with_lease(
region_id,
RegionRole::Leader,
now,
now + Duration::from_secs(10),
None,
)
.unwrap();
// The logical region's creation writes to the metadata region, its rows to the data region.
let logical_region_id = RegionId::new(1024, 1);
env.create_logical_region(region_id, logical_region_id)
.await;
let request = RegionRequest::Put(RegionPutRequest {
skip_wal,
rows: Rows {
schema: row_schema_with_tags(&["job"]),
rows: build_rows(1, 10),
},
hint: None,
partition_expr_version: None,
});
engine
.handle_request(logical_region_id, request)
.await
.unwrap();
assert_eq!(skip_wal, engine.has_skip_wal_writes(region_id));
let memtable_size = |region_id| mito.region_statistic(region_id).unwrap().memtable_size;
let metadata_region_id = utils::to_metadata_region_id(region_id);
assert_ne!(0, memtable_size(metadata_region_id));
set_role(
&engine,
region_id,
SettableRegionRoleState::DowngradingLeader,
)
.await;
let flush = RegionFlushRequest {
reason: Some(RegionFlushReason::Downgrading),
..Default::default()
};
engine
.handle_request(region_id, RegionRequest::Flush(flush.clone()))
.await
.unwrap();
assert_eq!(0, memtable_size(metadata_region_id));
assert_eq!(
skip_wal,
memtable_size(utils::to_data_region_id(region_id)) == 0
);
assert!(!engine.has_skip_wal_writes(region_id));
// An attempt that timed out after making only the metadata region a Follower is retried;
// only a downgrade's flush skips that Follower.
set_role(&mito, metadata_region_id, SettableRegionRoleState::Follower).await;
let err = engine
.handle_request(region_id, RegionRequest::Flush(Default::default()))
.await
.unwrap_err();
assert!(
format!("{err:?}").contains("is in Follower state"),
"{err:?}"
);
engine
.handle_request(region_id, RegionRequest::Flush(flush))
.await
.unwrap();
set_role(&engine, region_id, SettableRegionRoleState::Follower).await;
}
async fn set_role(
engine: &dyn RegionEngine,
region_id: RegionId,
state: SettableRegionRoleState,
) {
let response = engine
.set_region_role_state_gracefully(region_id, state)
.await;
assert!(
matches!(response, Ok(SetRegionRoleStateResponse::Success(_))),
"{response:?}"
);
}
/// A downgrade's flush does not skip a metadata region that became a Follower while it still
/// holds rows: the flush fails, as a Follower is not flushable.
#[tokio::test]
async fn test_downgrade_flush_fails_on_metadata_follower_with_rows() {
let env = TestEnv::new().await;
let region_id = RegionId::new(1, 1);
env.create_physical_region(region_id, "test_metric_table", vec![])
.await;
env.create_logical_region(region_id, RegionId::new(1024, 1))
.await;
let metadata_region_id = utils::to_metadata_region_id(region_id);
let mito = env.mito();
assert_eq!(Some(false), mito.is_memtable_empty(metadata_region_id));
let engine = env.metric();
// A downgrade that made only the metadata region a Follower is retried.
set_role(&mito, metadata_region_id, SettableRegionRoleState::Follower).await;
set_role(
&engine,
region_id,
SettableRegionRoleState::DowngradingLeader,
)
.await;
let flush = RegionFlushRequest {
reason: Some(RegionFlushReason::Downgrading),
..Default::default()
};
let err = engine
.handle_request(region_id, RegionRequest::Flush(flush))
.await
.unwrap_err();
assert!(
format!("{err:?}").contains("is in Follower state"),
"{err:?}"
);
}
/// On the Noop WAL the metadata region's rows are outside the WAL, so the physical region
/// reports skip-WAL writes before any data row, and a flush clears them.
#[tokio::test]
async fn test_metadata_rows_on_noop_wal_are_skip_wal_writes() {
let env = TestEnv::new().await;
let region_id = RegionId::new(1, 1);
env.create_physical_region(
region_id,
"test_metric_table",
vec![(
WAL_OPTIONS_KEY.to_string(),
serde_json::to_string(&WalOptions::Noop).unwrap(),
)],
)
.await;
env.create_logical_region(region_id, RegionId::new(1024, 1))
.await;
let engine = env.metric();
assert!(engine.has_skip_wal_writes(region_id));
engine
.handle_request(region_id, RegionRequest::Flush(Default::default()))
.await
.unwrap();
assert!(!engine.has_skip_wal_writes(region_id));
}
}
+8
View File
@@ -203,6 +203,14 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
version, one heartbeat request, one WAL listing per source, even after ALTER enables skip_wal)
and waits for its candidate lease (`GrantedLeases::wait_for_candidate_lease`) before it
commits after that version.
- A downgrade's flush (`RegionFlushReason::Downgrading`) of a region whose manifest is published
conditionally writes nothing unless the memtable may hold rows written without the WAL
(`MitoRegion::downgrade_needs_flush`); the next leader recovers the logged rows from a tail of
this node: a handover up to the reported last entry, which is durable; a takeover up to the bound
its listing of this node's WAL returns, which misses entries an `enqueued` WAL has not yet
uploaded. A change to Follower reports the last entry id only once the provider's durability
barrier passes it (`set_role_state_gracefully` in `worker.rs`); for the object store WAL, once
the entries through it are uploaded.
- A leader that is writable, altering or editing replays its pending tails in one
background task (`tail_replay.rs`), started by the worker when a lease, catchup or
role change makes the region writable, or when it registers a region created or opened
+11
View File
@@ -714,6 +714,12 @@ impl MitoEngine {
Ok(())
}
/// Returns whether the memtables of the region hold no rows, or `None` if it is not found.
pub fn is_memtable_empty(&self, region_id: RegionId) -> Option<bool> {
self.find_region(region_id)
.map(|region| region.version().memtables.is_empty())
}
/// Find the current version's memtables and SSTs stats by region_id.
/// The stats must be collected in one place one time to ensure data consistency.
pub fn find_memtable_and_sst_stats(
@@ -2049,6 +2055,11 @@ impl RegionEngine for MitoEngine {
.map(|region| region.is_confirmed_leader())
}
fn has_skip_wal_writes(&self, region_id: RegionId) -> bool {
self.find_region(region_id)
.is_some_and(|region| region.version().memtables.has_skip_wal_writes())
}
fn as_any(&self) -> &dyn Any {
self
}
+265 -2
View File
@@ -48,8 +48,9 @@ use store_api::region_engine::{
};
use store_api::region_request::{
EnterStagingRequest, PathType, RegionCatchupRequest, RegionCleanUpRequest, RegionCloseRequest,
RegionCompactRequest, RegionDropRequest, RegionFlushRequest, RegionOpenRequest, RegionRequest,
RegionTruncateRequest, StagingPartitionDirective,
RegionCompactRequest, RegionDropRequest, RegionFlushReason, RegionFlushRequest,
RegionOpenRequest, RegionPutRequest, RegionRequest, RegionTruncateRequest,
StagingPartitionDirective,
};
use store_api::storage::{FileId, RegionId, ScanRequest};
use tokio::sync::{Notify, oneshot};
@@ -2426,3 +2427,265 @@ async fn test_end_of_staging_conflict_reloads_region() {
assert!(response.is_invalid_transition(), "{response:?}");
wait_until(|| is_replaced(&engine, &old)).await;
}
/// A downgrade's flush of a region whose manifest is published conditionally writes the memtable
/// only if it holds rows that are not in the WAL, also once its options skip the WAL, and the
/// region reports its last entry once the WAL holds it.
#[rstest]
#[case::logged(false, false)]
#[case::skip_wal(true, false)]
#[case::logged_then_skip_wal_option(false, true)]
#[tokio::test]
async fn test_downgrade_flushes_only_with_skip_wal_rows(
#[case] skip_wal: bool,
#[case] skip_wal_option: bool,
) {
let mut env = TestEnv::with_prefix("downgrade-flushes-skip-wal-rows").await;
let (engine, log_store) = env
.create_engine_with_object_store_wal(MitoConfig::default(), &held_wal_config())
.await;
let region_id = RegionId::new(1, 1);
let (table_dir, schema, _) = create_leased_region_on(&engine, region_id).await;
let put = RegionPutRequest {
skip_wal,
rows: Rows {
schema,
rows: build_rows(0, 3),
},
hint: None,
partition_expr_version: None,
};
engine
.handle_request(region_id, RegionRequest::Put(put))
.await
.unwrap();
if skip_wal_option {
engine
.handle_request(region_id, set_skip_wal_request(true))
.await
.unwrap();
}
assert_eq!(skip_wal, engine.has_skip_wal_writes(region_id));
let response = engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::DowngradingLeader)
.await
.unwrap();
assert!(
matches!(response, SetRegionRoleStateResponse::Success(_)),
"{response:?}"
);
let flush = RegionFlushRequest {
reason: Some(RegionFlushReason::Downgrading),
..Default::default()
};
// A flush of the logged rows would wait for the held upload.
tokio::time::timeout(
Duration::from_secs(10),
engine.handle_request(region_id, RegionRequest::Flush(flush)),
)
.await
.unwrap()
.unwrap();
let store = env.get_object_store().unwrap();
let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare);
assert_eq!(usize::from(skip_wal), count_ssts(&store, &region_dir).await);
assert!(!engine.has_skip_wal_writes(region_id));
let region = engine.get_region(region_id).unwrap();
let last_entry_id = region.version_control.current().last_entry_id;
let to_follower = || {
let engine = engine.clone();
tokio::spawn(async move {
engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
.await
})
};
let wait_for_durability_waits = |count| {
tokio::time::timeout(
Duration::from_secs(10),
log_store.wait_for_durability_waits(count),
)
};
let mut followers = vec![to_follower()];
if !skip_wal {
wait_for_durability_waits(1).await.unwrap().unwrap();
// The wait holds no worker, which still answers the region's requests.
tokio::time::timeout(
Duration::from_secs(10),
engine.handle_request(region_id, RegionRequest::Flush(Default::default())),
)
.await
.unwrap()
.unwrap_err();
// A region that is already a Follower waits as well.
followers.push(to_follower());
wait_for_durability_waits(2).await.unwrap().unwrap();
assert!(followers.iter().all(|follower| !follower.is_finished()));
log_store.seal_open_batch().await.unwrap();
assert_eq!(
vec![last_entry_id],
stored_entry_ids(&log_store, region_id).await
);
}
for follower in followers {
let response = follower.await.unwrap().unwrap();
let SetRegionRoleStateResponse::Success(success) = response else {
panic!("{response:?}");
};
assert_eq!(Some(last_entry_id), success.last_entry_id());
}
}
/// A change to Follower whose last entry cannot become durable fails, and the region stays a
/// Follower.
#[tokio::test]
async fn test_follower_change_fails_if_its_last_entry_cannot_become_durable() {
let mut env = TestEnv::with_prefix("follower-change-wal-crash").await;
let (engine, log_store) = env
.create_engine_with_object_store_wal(MitoConfig::default(), &held_wal_config())
.await;
let region_id = RegionId::new(1, 1);
let (_, schema, _) = create_leased_region_on(&engine, region_id).await;
put_range(&engine, region_id, &schema, 0, 3).await;
let follower = tokio::spawn({
let engine = engine.clone();
async move {
engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
.await
}
});
tokio::time::timeout(
Duration::from_secs(10),
log_store.wait_for_durability_waits(1),
)
.await
.unwrap()
.unwrap();
log_store.crash().await;
let response = follower.await.unwrap().unwrap();
assert!(response.is_invalid_transition(), "{response:?}");
assert_eq!(Some(RegionRole::Follower), engine.role(region_id));
}
/// A downgrade's flush of a memtable that holds logged and skip-WAL rows persists both.
#[tokio::test]
async fn test_downgrade_flush_persists_logged_and_skip_wal_rows() {
let mut env = TestEnv::with_prefix("downgrade-flush-mixed-rows").await;
let (engine, _log_store) = new_engine(&mut env).await;
let region_id = RegionId::new(1, 1);
let (_, schema, _) = create_leased_region_on(&engine, region_id).await;
for (skip_wal, start) in [(false, 0), (true, 3)] {
let put = RegionPutRequest {
skip_wal,
rows: Rows {
schema: schema.clone(),
rows: build_rows(start, start + 3),
},
hint: None,
partition_expr_version: None,
};
engine
.handle_request(region_id, RegionRequest::Put(put))
.await
.unwrap();
}
let response = engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::DowngradingLeader)
.await
.unwrap();
assert!(
matches!(response, SetRegionRoleStateResponse::Success(_)),
"{response:?}"
);
let flush = RegionFlushRequest {
reason: Some(RegionFlushReason::Downgrading),
..Default::default()
};
engine
.handle_request(region_id, RegionRequest::Flush(flush))
.await
.unwrap();
let version = engine.get_region(region_id).unwrap().version();
assert!(version.memtables.is_empty());
let rows: u64 = version.ssts.levels()[0]
.files()
.map(|file| file.meta_ref().num_rows)
.sum();
assert_eq!(6, rows);
}
/// A region on the object store WAL whose writes need no lease publishes its manifest
/// unconditionally, so its downgrade still flushes the rows it logged.
#[tokio::test]
async fn test_downgrade_without_write_leases_flushes_logged_rows() {
let mut env = TestEnv::with_prefix("downgrade-unleased-flush").await;
let (engine, _log_store) = new_engine(&mut env).await;
let region_id = RegionId::new(1, 1);
let (table_dir, schema) = create_region(&engine, region_id).await;
put_range(&engine, region_id, &schema, 0, 3).await;
let response = engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::DowngradingLeader)
.await
.unwrap();
assert!(
matches!(response, SetRegionRoleStateResponse::Success(_)),
"{response:?}"
);
let flush = RegionFlushRequest {
reason: Some(RegionFlushReason::Downgrading),
..Default::default()
};
engine
.handle_request(region_id, RegionRequest::Flush(flush))
.await
.unwrap();
let store = env.get_object_store().unwrap();
let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare);
assert_eq!(1, count_ssts(&store, &region_dir).await);
}
/// A change to Follower waits for its last entry to become durable without holding the region,
/// stops waiting once nobody waits for its reply, and still completes the change.
#[tokio::test]
async fn test_abandoned_follower_change_stops_waiting() {
let mut env = TestEnv::with_prefix("abandoned-follower-change").await;
let (engine, log_store) = env
.create_engine_with_object_store_wal(MitoConfig::default(), &held_wal_config())
.await;
let region_id = RegionId::new(1, 1);
let (_, schema, _) = create_leased_region_on(&engine, region_id).await;
put_range(&engine, region_id, &schema, 0, 3).await;
let region = engine.get_region(region_id).unwrap();
let region_references = Arc::strong_count(&region);
// The durability barrier and its wait each hold the log store.
let references = Arc::strong_count(&log_store);
let follower = tokio::spawn({
let engine = engine.clone();
async move {
engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
.await
}
});
tokio::time::timeout(
Duration::from_secs(10),
log_store.wait_for_durability_waits(1),
)
.await
.unwrap()
.unwrap();
assert!(Arc::strong_count(&log_store) > references);
wait_until(|| Arc::strong_count(&region) <= region_references).await;
follower.abort();
wait_until(|| Arc::strong_count(&log_store) <= references).await;
assert_eq!(Some(RegionRole::Follower), engine.role(region_id));
}
+40
View File
@@ -17,6 +17,7 @@ use std::sync::Arc;
use std::time::Duration;
use api::v1::Rows;
use api::v1::value::ValueData;
use common_error::ext::ErrorExt;
use common_wal::options::{WAL_OPTIONS_KEY, WalOptions};
use rstest::rstest;
@@ -1101,3 +1102,42 @@ async fn test_close_request_skip_wal_during_flush(#[case] new_skip_wal: bool) {
.unwrap();
assert_eq!(actual, expected);
}
/// A skip-WAL write that installs no row leaves the region without skip-WAL rows, so its
/// downgrade does not report rows that do not exist.
#[tokio::test]
async fn test_skip_wal_write_that_installs_nothing_leaves_no_skip_wal_rows() {
let mut env = TestEnv::with_prefix("skip-wal-write-installs-nothing").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let schema = rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
// No time partition can start at this timestamp, so the write fails before it installs a row.
let mut rows = build_rows(0, 1);
rows[0].values[2].value_data = Some(ValueData::TimestampMillisecondValue(i64::MIN));
let put = RegionPutRequest {
skip_wal: true,
rows: Rows { schema, rows },
hint: None,
partition_expr_version: None,
};
let error = engine
.handle_request(region_id, RegionRequest::Put(put))
.await
.unwrap_err();
assert!(format!("{error:?}").contains("out of range"), "{error:?}");
assert!(
engine
.get_region(region_id)
.unwrap()
.version()
.memtables
.is_empty()
);
assert!(!engine.has_skip_wal_writes(region_id));
}
+64 -12
View File
@@ -44,13 +44,15 @@ use rstest::rstest;
use store_api::logstore::LogStore;
use store_api::logstore::provider::Provider;
use store_api::region_engine::{
RegionEngine, RegionManifestInfo, RegionRole, SettableRegionRoleState,
RegionEngine, RegionManifestInfo, RegionRole, SetRegionRoleStateResponse,
SettableRegionRoleState,
};
use store_api::region_request::{
EnterStagingRequest, PathType, RegionAlterRequest, RegionBuildIndexRequest,
RegionCatchupRequest, RegionCloseRequest, RegionCompactRequest,
RegionDiscardPendingTailsRequest, RegionDropRequest, RegionFlushRequest, RegionOpenRequest,
RegionPutRequest, RegionRequest, RegionTruncateRequest, StagingPartitionDirective,
RegionDiscardPendingTailsRequest, RegionDropRequest, RegionFlushReason, RegionFlushRequest,
RegionOpenRequest, RegionPutRequest, RegionRequest, RegionTruncateRequest,
StagingPartitionDirective,
};
use store_api::storage::{RegionId, ScanRequest};
use tokio::sync::Semaphore;
@@ -3341,15 +3343,47 @@ async fn test_catchup_of_region_with_rows_in_memtable(
assert_eq!(expected, count_rows(&region.engine, region.region_id).await);
}
/// Rows still in the source's WAL when ALTER enables skip_wal survive a migration.
/// Downgrades the region as a migration does and returns the last entry id it reports.
async fn downgrade(engine: &MitoEngine, region_id: RegionId) -> EntryId {
let response = engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::DowngradingLeader)
.await
.unwrap();
assert!(
matches!(response, SetRegionRoleStateResponse::Success(_)),
"{response:?}"
);
let flush = RegionFlushRequest {
reason: Some(RegionFlushReason::Downgrading),
..Default::default()
};
engine
.handle_request(region_id, RegionRequest::Flush(flush))
.await
.unwrap();
let response = engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
.await
.unwrap();
let SetRegionRoleStateResponse::Success(success) = response else {
panic!("{response:?}");
};
success.last_entry_id().unwrap()
}
/// Rows still in the source's WAL when ALTER enables skip_wal survive a migration: the source's
/// downgrade does not flush them, and the candidate recovers them from the source's tail, by a
/// handover from the reported last entry or by a takeover once that report was lost.
#[rstest]
#[case::handover(UptoKind::Reported, 6)]
#[case::takeover(UptoKind::Listed, 6)]
#[case::start_only_takeover(UptoKind::Listed, 0)]
#[case::handover(UptoKind::Reported, 6, 0)]
#[case::handover_after_flush(UptoKind::Reported, 6, 3)]
#[case::takeover(UptoKind::Listed, 6, 0)]
#[case::start_only_takeover(UptoKind::Listed, 0, 0)]
#[tokio::test]
async fn test_migration_replays_pre_alter_skip_wal_rows(
#[case] kind: UptoKind,
#[case] rows: usize,
#[case] flushed_rows: usize,
) {
let wal_store = ObjectStore::new(Memory::default()).unwrap();
let config = wal_config();
@@ -3369,8 +3403,19 @@ async fn test_migration_replays_pre_alter_skip_wal_rows(
.await;
let id = RegionId::new(1, 1);
let (table_dir, schema, _) = create_leased_region_on(&source, id).await;
if rows > 0 {
put_range(&source, id, &schema, 0, rows).await;
let mut flushed_last = 0;
if flushed_rows > 0 {
put_range(&source, id, &schema, 0, flushed_rows).await;
flushed_last = source
.get_region(id)
.unwrap()
.version_control
.current()
.last_entry_id;
flush_region(&source, id, None).await;
}
if rows > flushed_rows {
put_range(&source, id, &schema, flushed_rows, rows).await;
}
source
.handle_request(id, set_skip_wal_request(true))
@@ -3378,8 +3423,15 @@ async fn test_migration_replays_pre_alter_skip_wal_rows(
.unwrap();
let source_region = source.get_region(id).unwrap();
let last = source_region.version_control.current().last_entry_id;
assert_eq!(0, source_region.version().flushed_entry_id);
source.set_region_role(id, RegionRole::Follower).unwrap();
let flushed_entry_id = source_region.version().flushed_entry_id;
assert_eq!(flushed_last, flushed_entry_id);
assert!(flushed_rows == 0 || (0 < flushed_entry_id && flushed_entry_id < last));
let store = env.get_object_store().unwrap();
let region_dir = region_dir_from_table_dir(&table_dir, id, PathType::Bare);
let ssts = count_ssts(&store, &region_dir).await;
assert_eq!(last, downgrade(&source, id).await);
assert!(!source.has_skip_wal_writes(id));
assert_eq!(ssts, count_ssts(&store, &region_dir).await);
let mut env = env.with_node_id(REMOTE_NODE_ID);
let listener = Arc::new(TailReplayListener::default());
@@ -3437,7 +3489,7 @@ async fn test_migration_replays_pre_alter_skip_wal_rows(
panic!("expected a pending tail")
};
assert_eq!(
(NODE_ID, 0, kind),
(NODE_ID, flushed_entry_id, kind),
(tail.node_id, tail.after, tail.upto_kind)
);
if reported {
+5 -1
View File
@@ -58,7 +58,10 @@ impl MemtableVersion {
/// Returns whether current memtables may contain skip-WAL writes.
pub(crate) fn has_skip_wal_writes(&self) -> bool {
self.mutable.has_skip_wal_writes() || self.immutable_has_skip_wal_writes
// A write marks the mutable memtables before it installs rows, so one that installed none
// into an empty memtable leaves it marked but empty.
(self.mutable.has_skip_wal_writes() && !self.mutable.is_empty())
|| self.immutable_has_skip_wal_writes
}
/// Immutable memtables and their original partition time ranges.
@@ -351,6 +354,7 @@ mod tests {
1,
);
version.mutable.mark_skip_wal_writes();
assert!(!version.has_skip_wal_writes());
version.mutable.write(&kvs).unwrap();
assert!(snapshot.has_skip_wal_writes());
+10
View File
@@ -488,6 +488,16 @@ impl MitoRegion {
self.is_staging() || self.manifest_ctx.awaits_leader_lease()
}
/// Returns whether a downgrade's flush has to write the region's memtable. It may skip the
/// rows logged in this node's WAL only where the next leader's handover or takeover records a
/// tail of this node, as the catchup of a conditionally published region that names its
/// source does; a caller whose catchup names no source, such as the metric engine's metadata
/// region, asks for a full flush instead.
pub(crate) fn downgrade_needs_flush(&self) -> bool {
!self.manifest_ctx.is_conditional_publication()
|| self.version().memtables.has_skip_wal_writes()
}
/// Returns whether the region is in a staging session: staging, ending staging, or in a
/// staged edit.
pub(crate) fn in_staging_session(&self) -> bool {
+6 -1
View File
@@ -620,6 +620,7 @@ mod tests {
use super::*;
use crate::error::UnexpectedSnafu;
use crate::memtable::bulk::part::BulkPart;
use crate::memtable::time_series::TimeSeriesMemtableBuilder;
use crate::test_util::version_util::VersionControlBuilder;
#[test]
@@ -889,7 +890,11 @@ mod tests {
for skip_wal in [false, true] {
for bulk in [false, true] {
for fail_before_install in [false, true] {
let builder = VersionControlBuilder::new();
let mut builder = VersionControlBuilder::new();
// Only a memtable that holds rows reports skip-WAL writes, so use one that
// keeps them.
builder
.set_memtable_builder(Arc::new(TimeSeriesMemtableBuilder::default()));
let region_id = builder.region_id();
let version_control = Arc::new(builder.build());
let mut ctx = RegionWriteCtx::new(
+54 -17
View File
@@ -1904,7 +1904,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
&mut self,
region_id: RegionId,
region_role_state: SettableRegionRoleState,
sender: oneshot::Sender<SetRegionRoleStateResponse>,
mut sender: oneshot::Sender<SetRegionRoleStateResponse>,
) {
if let Some(region) = self.regions.get_region(region_id) {
if matches!(
@@ -1923,22 +1923,40 @@ impl<S: LogStore> RegionWorkerLoop<S> {
#[cfg(feature = "hdfs-object-store")]
let sweep_limiter = self.sweep_limiter.clone();
let request_sender = self.sender.clone();
// The next leader may read the entries up to the last entry a Follower reports from
// this node's WAL.
let durability_barrier = (region_role_state == SettableRegionRoleState::Follower)
.then(|| self.wal.durability_barrier(region_id, &region.provider));
// We need to do this in background as we need the manifest lock.
common_runtime::spawn_global(async move {
let drain = drain_ended_staging(&request_sender, region_id);
match region
let result = region
.set_role_state_gracefully(region_role_state, drain)
.await
{
Ok(()) => {
let last_entry_id = region.version_control.current().last_entry_id;
let _ = sender.send(SetRegionRoleStateResponse::success(
SetRegionRoleStateSuccess::mito(last_entry_id),
));
.map(|()| region.version_control.current().last_entry_id);
if let Err(e) = &result {
error!(e; "Failed to set region {} role state to {:?}", region_id, region_role_state);
}
// A Follower reports its last entry id, read after writes are fenced, only once it
// is durable; any other outcome is replied to at once.
let (last_entry_id, barrier) = match (result, durability_barrier) {
(Ok(last_entry_id), Some(barrier)) => (last_entry_id, barrier),
(result, _) => {
#[cfg(feature = "hdfs-object-store")]
let is_leader =
result.is_ok() && region_role_state == SettableRegionRoleState::Leader;
let _ = sender.send(match result {
Ok(last_entry_id) => SetRegionRoleStateResponse::success(
SetRegionRoleStateSuccess::mito(last_entry_id),
),
Err(e) => {
SetRegionRoleStateResponse::invalid_transition(BoxedError::new(e))
}
});
// Only a writable leader reclaims what a writer that died
// before it renamed its temporary file left behind.
#[cfg(feature = "hdfs-object-store")]
if region_role_state == SettableRegionRoleState::Leader {
if is_leader {
temp_file_sweeper::spawn_region_sweep(
region.access_layer(),
region_id,
@@ -1946,16 +1964,35 @@ impl<S: LogStore> RegionWorkerLoop<S> {
sweep_limiter,
);
}
// The call commits outside the worker when it ends staging or backfills
// metadata.
handle_reload::notify_if_fenced(&request_sender, &region).await;
return;
}
Err(e) => {
error!(e; "Failed to set region {} role state to {:?}", region_id, region_role_state);
let _ = sender.send(SetRegionRoleStateResponse::invalid_transition(
BoxedError::new(e),
));
}
}
// The call commits outside the worker when it ends staging or backfills metadata.
};
handle_reload::notify_if_fenced(&request_sender, &region).await;
// The wait below needs only the last entry id.
drop(region);
debug!(
"Region {} waits for its WAL through entry {}",
region_id, last_entry_id
);
let response = tokio::select! {
result = barrier.wait(last_entry_id) => match result {
Ok(()) => SetRegionRoleStateResponse::success(
SetRegionRoleStateSuccess::mito(last_entry_id),
),
Err(e) => {
error!(e; "Failed to wait for the WAL of region {} through entry {}", region_id, last_entry_id);
SetRegionRoleStateResponse::invalid_transition(BoxedError::new(e))
}
},
_ = sender.closed() => {
debug!("Region {} stops waiting for its WAL: nobody waits for the reply", region_id);
return;
}
};
let _ = sender.send(response);
});
} else {
let _ = sender.send(SetRegionRoleStateResponse::NotFound);
+6
View File
@@ -406,6 +406,12 @@ impl<S: LogStore> RegionWorkerLoop<S> {
return;
}
if request.reason == Some(RegionFlushReason::Downgrading) && !region.downgrade_needs_flush()
{
sender.send(Ok(0));
return;
}
let reason = resolve_flush_reason(request.reason, region.is_downgrading());
let mut task =
self.new_flush_task(&region, reason, request.row_group_size, self.config.clone());
+9
View File
@@ -1787,6 +1787,15 @@ pub trait RegionEngine: Send + Sync {
.map(|role| role != RegionRole::Follower)
}
/// Returns whether the region may hold rows that only a flush persists: rows written with
/// `skip_wal`, or any row of a region without a WAL. True may be conservative; false means
/// exactly that the region holds no such unflushed rows. Whether another node can recover the
/// region's logged rows from its WAL, and up to which entry, is a separate condition. The
/// default returns false, which suits an engine that keeps no such rows.
fn has_skip_wal_writes(&self, _region_id: RegionId) -> bool {
false
}
fn as_any(&self) -> &dyn Any;
}
+6 -1
View File
@@ -1954,7 +1954,12 @@ pub enum RegionFlushReason {
RemoteWalPrune,
/// Flush region before closing region.
Closing,
/// Flush region before downgrading region.
/// Flush region before downgrading region. The engine may skip the whole flush when the
/// region's next leader recovers the memtable's rows from this node's WAL (a handover from the
/// durable last entry the downgrade reports; a takeover only the entries already stored);
/// otherwise it flushes the whole memtable. Sent to a region already set to
/// DowngradingLeader; an engine may answer RegionBusy for a region in another state, such as
/// a staging region with unflushed rows.
Downgrading,
}
+8
View File
@@ -57,6 +57,14 @@ region statistic without pending tails decodes and encodes as before the flag ex
cargo nextest run -p common-meta -E 'test(test_has_pending_tails_wire)'
```
The [downgrade region reply fixture](wire/downgrade_region_skip_wal_writes/README.md) checks
that a downgrade reply that reports `has_skip_wal_writes` as false decodes and encodes as before
the flag existed, and that a reply with the flag decodes in the layout before it:
```shell
cargo nextest run -p common-meta -E 'test(test_has_skip_wal_writes_wire)'
```
## Object store WAL fixtures
Frozen objects of the object store WAL are checked byte for byte by the format tests of
@@ -0,0 +1,29 @@
# Downgrade region reply compatibility
`legacy_downgrade_regions_reply.json` is a generated legacy-shaped JSON fixture, not a capture
from a released binary: a datanode's `InstructionReply::DowngradeRegions` in the layout that
`common_meta::instruction` writes at GreptimeDB commit
`9aebf3a8213c9c7fc13f5e6d2926d1ad1f73b22c`, before the `has_skip_wal_writes` field. That
commit's `test_serialize_instruction_reply` pins the same layout.
Logical contents: one reply for region `4398046511105` (table `1024`, region number `1`), which
exists and was downgraded at last entry id `7`, with no metadata entry id and no error.
SHA-256: `dfd141978f9841e1ba27780d0beb491da7bb3a2682786c3846914a8e6ab5cb3c`.
Run the regression:
```shell
cargo nextest run -p common-meta -E 'test(test_has_skip_wal_writes_wire)'
```
The test checks that the fixture decodes to a reply without the flag and encodes back to exactly
the same bytes, so a reply without the flag keeps the pre-field layout of the commit above, and
that a reply with the flag writes it under its own key and decodes in that pre-field layout.
## Reproduce the fixture
```shell
printf '%s' '{"type":"downgrade_regions","replies":[{"region_id":4398046511105,"last_entry_id":7,"metadata_last_entry_id":null,"exists":true,"error":null}]}' \
> legacy_downgrade_regions_reply.json
```
@@ -0,0 +1 @@
{"type":"downgrade_regions","replies":[{"region_id":4398046511105,"last_entry_id":7,"metadata_last_entry_id":null,"exists":true,"error":null}]}