From 5f0e22171ed54c4bb1245492648e2b5d04704b68 Mon Sep 17 00:00:00 2001 From: Dragon Roar <2181719471@qq.com> Date: Wed, 28 Oct 2026 06:55:55 +0000 Subject: [PATCH 01/19] fix(log-store): skip records with unparsable keys instead of aborting the read (#9749) * fix(log-store): skip records with unparsable keys instead of aborting the read Signed-off-by: lczllx <2181719471@qq.com> * fix(log-store): keep undecodable RecordMeta keys fatal Signed-off-by: lczllx <2181719471@qq.com> --------- Signed-off-by: lczllx <2181719471@qq.com> --- src/log-store/src/kafka/log_store.rs | 511 ++++++++++++++++++++++--- src/log-store/src/kafka/util/record.rs | 52 ++- 2 files changed, 503 insertions(+), 60 deletions(-) diff --git a/src/log-store/src/kafka/log_store.rs b/src/log-store/src/kafka/log_store.rs index daa6dfbcf21..33cdd242564 100644 --- a/src/log-store/src/kafka/log_store.rs +++ b/src/log-store/src/kafka/log_store.rs @@ -40,7 +40,8 @@ use crate::kafka::consumer::{ConsumerBuilder, RecordsBuffer, RegionWalRange}; use crate::kafka::periodic_offset_fetcher::PeriodicOffsetFetcher; use crate::kafka::producer::OrderedBatchProducerRef; use crate::kafka::util::record::{ - ESTIMATED_META_SIZE, Record, convert_to_kafka_records, maybe_emit_entry, remaining_entries, + ESTIMATED_META_SIZE, Record, convert_to_kafka_records, is_record_meta_key, maybe_emit_entry, + remaining_entries, }; use crate::metrics; @@ -408,26 +409,41 @@ impl LogStore for KafkaLogStore { ); // Ignores no-op records. - if kafka_record.value.is_none() { - if check_termination(offset, end_offset) { - if let Some(entries) = remaining_entries(&provider, &mut entry_records) { - yield Ok(entries); + if kafka_record.value.is_some() { + let key = kafka_record.key; + match Record::try_from_parts(key.as_deref(), kafka_record.value) { + Ok(record) => { + // Tries to construct an entry from records consumed so far. + if let Some(mut entry) = + maybe_emit_entry(&provider, record, &mut entry_records)? + { + // We don't rely on the EntryId generated by mito2. + // Instead, we use the offset return from Kafka as EntryId. + // Therefore, we MUST overwrite the EntryId with RecordOffset. + entry.set_entry_id(offset as u64); + yield Ok(vec![entry]); + } + } + Err(err) => { + // A key that cannot be decoded is skipped only when the log store + // never wrote it. A key that is a JSON object with a `version` + // field may be a `RecordMeta` written by an incompatible version, + // for example one with a newer `RecordType` variant read after a + // rollback or during a rolling upgrade; skipping it would lose the + // entry once the WAL is pruned past its offset, so it stays fatal. + if key.as_deref().is_some_and(is_record_meta_key) { + yield Err(err); + return; + } + warn!( + "Skipping unparsable record at offset {} of topic {}, reason: {}", + offset, provider.topic, err + ); } - break; } - continue; - } - - let record = Record::try_from(kafka_record)?; - // Tries to construct an entry from records consumed so far. - if let Some(mut entry) = maybe_emit_entry(&provider, record, &mut entry_records)? { - // We don't rely on the EntryId generated by mito2. - // Instead, we use the offset return from Kafka as EntryId. - // Therefore, we MUST overwrite the EntryId with RecordOffset. - entry.set_entry_id(offset as u64); - yield Ok(vec![entry]); } + // The termination check runs for every consumed record, including skipped ones. if check_termination(offset, end_offset) { if let Some(entries) = remaining_entries(&provider, &mut entry_records) { yield Ok(entries); @@ -529,21 +545,25 @@ mod tests { use common_base::readable_size::ReadableSize; use common_meta::datanode::TopicStatsReporter; use common_telemetry::info; - use common_telemetry::tracing::warn; use common_wal::config::kafka::DatanodeKafkaConfig; use common_wal::config::kafka::common::KafkaConnectionConfig; + use common_wal::maybe_skip_kafka_integration_test; + use common_wal::test_util::get_kafka_endpoints; use dashmap::DashMap; use futures::TryStreamExt; use rand::Rng; use rand::prelude::SliceRandom; - use rskafka::client::partition::OffsetAt; + use rskafka::client::partition::{Compression, OffsetAt}; + use rskafka::record::Record as KafkaRecord; use store_api::logstore::LogStore; use store_api::logstore::entry::{Entry, MultiplePartEntry, MultiplePartHeader, NaiveEntry}; use store_api::logstore::provider::Provider; use store_api::storage::RegionId; use super::build_entry; + use crate::error; use crate::kafka::log_store::{KafkaLogStore, PeriodicTopicStatsReporter, TopicStat}; + use crate::kafka::util::record::{ESTIMATED_META_SIZE, convert_to_kafka_records}; #[test] fn test_build_naive_entry() { @@ -630,26 +650,76 @@ mod tests { .unwrap(); } + async fn new_test_logstore(max_batch_bytes: ReadableSize) -> KafkaLogStore { + let config = DatanodeKafkaConfig { + connection: KafkaConnectionConfig { + broker_endpoints: get_kafka_endpoints(), + ..Default::default() + }, + max_batch_bytes, + ..Default::default() + }; + KafkaLogStore::try_new(&config).await.unwrap() + } + + async fn produce_records( + logstore: &KafkaLogStore, + provider: &Provider, + records: Vec, + ) { + // A freshly created topic can be missing from the broker's metadata for a short + // while; `try_create_client` already retries that case. + let client = logstore + .client_manager + .get_or_insert(provider.as_kafka_provider().unwrap()) + .await + .unwrap() + .client() + .clone(); + client + .produce(records, Compression::NoCompression) + .await + .unwrap(); + } + + /// Builds a record that was not written by this log store. + fn foreign_record(key: Option<&[u8]>) -> KafkaRecord { + KafkaRecord { + key: key.map(|key| key.to_vec()), + value: Some(b"foreign payload".to_vec()), + timestamp: chrono::Utc::now(), + headers: Default::default(), + } + } + + /// Returns the log end offset of the topic, i.e. the exclusive end of the range that + /// `read` consumes. + async fn log_end_offset(logstore: &KafkaLogStore, provider: &Provider) -> i64 { + let client = logstore + .client_manager + .get_or_insert(provider.as_kafka_provider().unwrap()) + .await + .unwrap(); + client.client().get_offset(OffsetAt::Latest).await.unwrap() + } + + /// Returns one record per kind of key that the log store never writes: a missing key, a + /// key that is not JSON, a JSON value that is not an object, and a JSON object without a + /// `version` field. + fn foreign_records() -> Vec { + vec![ + foreign_record(None), + foreign_record(Some(b"not-a-json-key")), + foreign_record(Some(b"[1, 2, 3]")), + foreign_record(Some(br#"{"hello": "world"}"#)), + ] + } + #[tokio::test] async fn test_append_batch_basic() { common_telemetry::init_default_ut_logging(); - let Ok(broker_endpoints) = std::env::var("GT_KAFKA_ENDPOINTS") else { - warn!("The endpoints is empty, skipping the test 'test_append_batch_basic'"); - return; - }; - let broker_endpoints = broker_endpoints - .split(',') - .map(|s| s.trim().to_string()) - .collect::>(); - let config = DatanodeKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints, - ..Default::default() - }, - max_batch_bytes: ReadableSize::kb(32), - ..Default::default() - }; - let logstore = KafkaLogStore::try_new(&config).await.unwrap(); + maybe_skip_kafka_integration_test!(); + let logstore = new_test_logstore(ReadableSize::kb(32)).await; let topic_name = uuid::Uuid::new_v4().to_string(); prepare_topic(&logstore, &topic_name).await; let provider = Provider::kafka_provider(topic_name); @@ -715,25 +785,10 @@ mod tests { #[tokio::test] async fn test_append_batch_basic_large() { common_telemetry::init_default_ut_logging(); - let Ok(broker_endpoints) = std::env::var("GT_KAFKA_ENDPOINTS") else { - warn!("The endpoints is empty, skipping the test 'test_append_batch_basic_large'"); - return; - }; + maybe_skip_kafka_integration_test!(); let data_size_kb = rand::rng().random_range(9..31usize); info!("Entry size: {}Ki", data_size_kb); - let broker_endpoints = broker_endpoints - .split(',') - .map(|s| s.trim().to_string()) - .collect::>(); - let config = DatanodeKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints, - ..Default::default() - }, - max_batch_bytes: ReadableSize::kb(8), - ..Default::default() - }; - let logstore = KafkaLogStore::try_new(&config).await.unwrap(); + let logstore = new_test_logstore(ReadableSize::kb(8)).await; let topic_name = uuid::Uuid::new_v4().to_string(); prepare_topic(&logstore, &topic_name).await; let provider = Provider::kafka_provider(topic_name); @@ -788,6 +843,356 @@ mod tests { assert_eq!(high_wathermark, (data_size_kb as u64 / 8 + 1) * 20 * 5 - 1); } + #[tokio::test] + async fn test_read_skips_unparsable_record_inside_multipart_entry() { + maybe_skip_kafka_integration_test!(); + let logstore = new_test_logstore(ReadableSize::kb(8)).await; + let topic_name = uuid::Uuid::new_v4().to_string(); + prepare_topic(&logstore, &topic_name).await; + let provider = Provider::kafka_provider(topic_name); + + let region_id = RegionId::new(1, 1); + // Splits the entry into First, Middle(1) and Last. + let max_data_size = 8 * 1024 - ESTIMATED_META_SIZE; + let data = vec![7u8; max_data_size * 2 + 10]; + let entry = logstore + .entry(data.clone(), 0, region_id, &provider) + .unwrap(); + assert_matches!(entry, Entry::MultiplePart(_)); + let mut records = convert_to_kafka_records(entry).unwrap(); + assert_eq!(records.len(), 3); + + let last = records.pop().unwrap(); + // Places an unparsable record before the entry and between every pair of parts. + produce_records( + &logstore, + &provider, + vec![foreign_record(Some(b"not-a-json-key"))], + ) + .await; + produce_records(&logstore, &provider, vec![records[0].clone()]).await; + produce_records( + &logstore, + &provider, + vec![foreign_record(Some(br#"{"hello": "world"}"#))], + ) + .await; + produce_records(&logstore, &provider, vec![records[1].clone()]).await; + produce_records( + &logstore, + &provider, + vec![foreign_record(Some(b"not-a-json-key"))], + ) + .await; + produce_records(&logstore, &provider, vec![last]).await; + + let entries = logstore + .read(&provider, 0) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + .into_iter() + .flatten() + .collect::>(); + assert_eq!(entries.len(), 1); + let entry = entries + .into_iter() + .next() + .unwrap() + .into_multiple_part_entry() + .unwrap(); + assert_eq!( + entry.headers, + vec![ + MultiplePartHeader::First, + MultiplePartHeader::Middle(1), + MultiplePartHeader::Last + ] + ); + assert_eq!(entry.parts.concat(), data); + } + + #[tokio::test] + async fn test_read_skips_unparsable_record_across_regions() { + maybe_skip_kafka_integration_test!(); + let logstore = new_test_logstore(ReadableSize::kb(8)).await; + let topic_name = uuid::Uuid::new_v4().to_string(); + prepare_topic(&logstore, &topic_name).await; + let provider = Provider::kafka_provider(topic_name); + + let region_a = RegionId::new(1, 1); + let region_b = RegionId::new(1, 2); + let max_data_size = 8 * 1024 - ESTIMATED_META_SIZE; + let data_a = vec![1u8; max_data_size * 2 + 10]; + let data_b = vec![2u8; max_data_size * 2 + 10]; + let records_a = convert_to_kafka_records( + logstore + .entry(data_a.clone(), 0, region_a, &provider) + .unwrap(), + ) + .unwrap(); + let records_b = convert_to_kafka_records( + logstore + .entry(data_b.clone(), 0, region_b, &provider) + .unwrap(), + ) + .unwrap(); + assert_eq!(records_a.len(), 3); + assert_eq!(records_b.len(), 3); + + // Interleaves the parts of both entries with unparsable records. + for i in 0..3 { + produce_records(&logstore, &provider, vec![records_a[i].clone()]).await; + produce_records(&logstore, &provider, vec![records_b[i].clone()]).await; + produce_records( + &logstore, + &provider, + vec![foreign_record(Some(b"not-a-json-key"))], + ) + .await; + } + + let entries = logstore + .read(&provider, 0) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + .into_iter() + .flatten() + .collect::>(); + assert_eq!(entries.len(), 2); + + let mut entries = entries + .into_iter() + .map(|entry| (entry.region_id(), entry.into_multiple_part_entry().unwrap())) + .collect::>(); + assert_eq!(entries.remove(®ion_a).unwrap().parts.concat(), data_a); + assert_eq!(entries.remove(®ion_b).unwrap().parts.concat(), data_b); + assert!(entries.is_empty()); + } + + #[tokio::test] + async fn test_read_finishes_when_last_record_is_unparsable() { + maybe_skip_kafka_integration_test!(); + let logstore = new_test_logstore(ReadableSize::kb(32)).await; + let topic_name = uuid::Uuid::new_v4().to_string(); + prepare_topic(&logstore, &topic_name).await; + let provider = Provider::kafka_provider(topic_name); + + let region_id = RegionId::new(1, 1); + let mut expected = generate_entries(&logstore, &provider, 3, region_id, 128); + logstore.append_batch(expected.clone()).await.unwrap(); + // Appends an unparsable record as the last record of the read range. + produce_records( + &logstore, + &provider, + vec![foreign_record(Some(b"not-a-json-key"))], + ) + .await; + + let entries = tokio::time::timeout( + Duration::from_secs(30), + logstore + .read(&provider, 0) + .await + .unwrap() + .try_collect::>(), + ) + .await + .expect("read should finish after skipping the unparsable record") + .unwrap() + .into_iter() + .flatten() + .collect::>(); + + expected.iter_mut().for_each(|entry| entry.set_entry_id(0)); + let mut entries = entries; + entries.iter_mut().for_each(|entry| entry.set_entry_id(0)); + assert_eq!(entries, expected); + } + + #[tokio::test] + async fn test_read_skips_foreign_records_of_every_kind() { + maybe_skip_kafka_integration_test!(); + let logstore = new_test_logstore(ReadableSize::kb(32)).await; + let topic_name = uuid::Uuid::new_v4().to_string(); + prepare_topic(&logstore, &topic_name).await; + let provider = Provider::kafka_provider(topic_name); + + // Places every kind of unparsable record before the first entry. + for record in foreign_records() { + produce_records(&logstore, &provider, vec![record]).await; + } + + let region_id = RegionId::new(1, 1); + let mut expected = generate_entries(&logstore, &provider, 1, region_id, 128); + logstore.append_batch(expected.clone()).await.unwrap(); + + let entries = logstore + .read(&provider, 0) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + .into_iter() + .flatten() + .collect::>(); + + expected.iter_mut().for_each(|entry| entry.set_entry_id(0)); + let mut entries = entries; + entries.iter_mut().for_each(|entry| entry.set_entry_id(0)); + assert_eq!(entries, expected); + } + + #[tokio::test] + async fn test_read_finishes_when_topic_only_has_foreign_records() { + maybe_skip_kafka_integration_test!(); + let logstore = new_test_logstore(ReadableSize::kb(32)).await; + let topic_name = uuid::Uuid::new_v4().to_string(); + prepare_topic(&logstore, &topic_name).await; + let provider = Provider::kafka_provider(topic_name); + + for record in foreign_records() { + produce_records(&logstore, &provider, vec![record]).await; + } + + // Asserts the read range covers the produced records; an empty range would let `read` + // return without exercising the skip path. + assert_eq!(log_end_offset(&logstore, &provider).await, 4); + + let entries = tokio::time::timeout( + Duration::from_secs(30), + logstore + .read(&provider, 0) + .await + .unwrap() + .try_collect::>(), + ) + .await + .expect("read should finish after skipping all unparsable records") + .unwrap(); + + assert!(entries.into_iter().flatten().next().is_none()); + } + + #[tokio::test] + async fn test_read_fails_on_incompatible_record_meta() { + maybe_skip_kafka_integration_test!(); + let logstore = new_test_logstore(ReadableSize::kb(32)).await; + + // Keys that look like a `RecordMeta` but cannot be decoded by this version. They may + // come from an incompatible version of the log store, so the read must not skip them. + let keys: [&[u8]; 2] = [ + // A `RecordType` variant this version does not know. + br#"{"version": 0, "tp": "Compressed", "entry_id": 0, "ns": {"region_id": 1, "topic": ""}}"#, + // A field with the wrong type. + br#"{"version": "0", "tp": "Full", "entry_id": 0, "ns": {"region_id": 1, "topic": ""}}"#, + ]; + for key in keys { + let topic_name = uuid::Uuid::new_v4().to_string(); + prepare_topic(&logstore, &topic_name).await; + let provider = Provider::kafka_provider(topic_name); + produce_records(&logstore, &provider, vec![foreign_record(Some(key))]).await; + + let err = logstore + .read(&provider, 0) + .await + .unwrap() + .try_collect::>>() + .await + .unwrap_err(); + assert_matches!(err, error::Error::DecodeJson { .. }); + } + } + + #[tokio::test] + async fn test_read_fails_on_missing_middle_part() { + maybe_skip_kafka_integration_test!(); + let logstore = new_test_logstore(ReadableSize::kb(8)).await; + let topic_name = uuid::Uuid::new_v4().to_string(); + prepare_topic(&logstore, &topic_name).await; + let provider = Provider::kafka_provider(topic_name); + + let region_id = RegionId::new(1, 1); + // Splits the entry into First, Middle(1), Middle(2) and Last. + let max_data_size = 8 * 1024 - ESTIMATED_META_SIZE; + let data = vec![7u8; max_data_size * 3 + 10]; + let entry = logstore.entry(data, 0, region_id, &provider).unwrap(); + let records = convert_to_kafka_records(entry).unwrap(); + assert_eq!(records.len(), 4); + + // Only a missing part of an entry we wrote is fatal; a foreign record is skipped + // because it cannot be one of our parts. + produce_records( + &logstore, + &provider, + vec![foreign_record(Some(b"not-a-json-key"))], + ) + .await; + produce_records(&logstore, &provider, vec![records[0].clone()]).await; + produce_records(&logstore, &provider, vec![records[2].clone()]).await; + + let err = logstore + .read(&provider, 0) + .await + .unwrap() + .try_collect::>>() + .await + .unwrap_err(); + assert_matches!(err, error::Error::IllegalSequence { .. }); + } + + #[tokio::test] + async fn test_read_succeeds_on_two_part_entry() { + maybe_skip_kafka_integration_test!(); + let logstore = new_test_logstore(ReadableSize::kb(8)).await; + let topic_name = uuid::Uuid::new_v4().to_string(); + prepare_topic(&logstore, &topic_name).await; + let provider = Provider::kafka_provider(topic_name); + + let region_id = RegionId::new(1, 1); + // Splits the entry into First and Last, without any middle part. + let max_data_size = 8 * 1024 - ESTIMATED_META_SIZE; + let data = vec![7u8; max_data_size + 10]; + let entry = logstore + .entry(data.clone(), 0, region_id, &provider) + .unwrap(); + let records = convert_to_kafka_records(entry).unwrap(); + assert_eq!(records.len(), 2); + + for record in records { + produce_records(&logstore, &provider, vec![record]).await; + } + + let entries = logstore + .read(&provider, 0) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + .into_iter() + .flatten() + .collect::>(); + assert_eq!(entries.len(), 1); + let entry = entries + .into_iter() + .next() + .unwrap() + .into_multiple_part_entry() + .unwrap(); + assert_eq!( + entry.headers, + vec![MultiplePartHeader::First, MultiplePartHeader::Last] + ); + assert_eq!(entry.parts.concat(), data); + } + #[tokio::test] async fn test_topic_stats_reporter() { common_telemetry::init_default_ut_logging(); diff --git a/src/log-store/src/kafka/util/record.rs b/src/log-store/src/kafka/util/record.rs index aefb098e0db..97311bff006 100644 --- a/src/log-store/src/kafka/util/record.rs +++ b/src/log-store/src/kafka/util/record.rs @@ -108,17 +108,32 @@ impl TryFrom for KafkaRecord { } // TODO(niebayes): improve the performance of decoding kafka record. -impl TryFrom for Record { - type Error = crate::error::Error; - - fn try_from(kafka_record: KafkaRecord) -> Result { - let key = kafka_record.key.context(MissingKeySnafu)?; - let meta = serde_json::from_slice(&key).context(DecodeJsonSnafu)?; - let data = kafka_record.value.context(MissingValueSnafu)?; +impl Record { + /// Decodes a record from the key and value of a [`KafkaRecord`]. + /// + /// The key is borrowed so that callers can inspect it if decoding fails, e.g. to + /// tell a foreign key apart from a [`RecordMeta`] written by an incompatible version + /// of the log store. + pub(crate) fn try_from_parts(key: Option<&[u8]>, value: Option>) -> Result { + let key = key.context(MissingKeySnafu)?; + let meta = serde_json::from_slice(key).context(DecodeJsonSnafu)?; + let data = value.context(MissingValueSnafu)?; Ok(Self { meta, data }) } } +/// Returns whether a key is a JSON object with a `version` field, i.e. whether it may have +/// been written as a [`RecordMeta`] key. +/// +/// A `RecordMeta` key that cannot be decoded may come from an incompatible version of the +/// log store, so the reader must not treat such a key as a foreign record. +pub(crate) fn is_record_meta_key(key: &[u8]) -> bool { + matches!( + serde_json::from_slice::(key), + Ok(serde_json::Value::Object(fields)) if fields.contains_key("version") + ) +} + pub(crate) fn convert_to_kafka_records(entry: Entry) -> Result> { match entry { Entry::Naive(entry) => Ok(vec![KafkaRecord::try_from(Record { @@ -559,6 +574,29 @@ mod tests { assert_eq!(full_entry.entry_id(), 3); } + #[test] + fn test_is_record_meta_key() { + let meta = RecordMeta { + version: VERSION, + tp: RecordType::Full, + entry_id: 1, + ns: NamespaceImpl { + region_id: RegionId::new(1, 1).as_u64(), + topic: "greptimedb_wal_topic".to_string(), + }, + }; + assert!(is_record_meta_key(&serde_json::to_vec(&meta).unwrap())); + // A `RecordMeta` key this version cannot decode, e.g. one with a new `RecordType` + // variant. + assert!(is_record_meta_key( + br#"{"version": 0, "tp": "Compressed", "entry_id": 0, "ns": {"region_id": 1, "topic": ""}}"# + )); + // Keys the log store never writes. + assert!(!is_record_meta_key(b"not-a-json-key")); + assert!(!is_record_meta_key(b"[1, 2, 3]")); + assert!(!is_record_meta_key(br#"{"hello": "world"}"#)); + } + #[test] fn test_meta_size() { let meta = RecordMeta { From 724072bb33a442ce8e716f4263c4da4b33704231 Mon Sep 17 00:00:00 2001 From: Chenglong Zheng Date: Wed, 28 Oct 2026 06:56:11 +0000 Subject: [PATCH 02/19] =?UTF-8?q?feat:=20Add=20last=5Fsequence=20for=20max?= =?UTF-8?q?=20allocated=20sequence=20and=20add=20tests=20for=20=E2=80=A6?= =?UTF-8?q?=20(#9951)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Add last_sequence for max allocated sequence and add tests for the reproduced issue cases Signed-off-by: hahaha * test: Add a regression test for Kafka remote catchup Signed-off-by: hahaha --------- Signed-off-by: hahaha --- src/mito2/src/engine.rs | 2 + src/mito2/src/engine/catchup_test.rs | 291 ++++++++++++- src/mito2/src/engine/edit_region_test.rs | 68 ++- .../engine/object_store_wal_recovery_test.rs | 19 +- src/mito2/src/engine/sequence_test.rs | 410 ++++++++++++++++++ src/mito2/src/engine/staging_test.rs | 46 +- src/mito2/src/engine/sync_test.rs | 83 +++- src/mito2/src/region/version.rs | 76 +++- src/mito2/src/region_write_ctx.rs | 200 ++++++++- src/mito2/src/worker/handle_catchup.rs | 4 + src/mito2/src/worker/handle_manifest.rs | 7 +- src/mito2/src/worker/handle_write.rs | 23 +- 12 files changed, 1181 insertions(+), 48 deletions(-) create mode 100644 src/mito2/src/engine/sequence_test.rs diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 0147fb71e2a..3791489d73f 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -74,6 +74,8 @@ mod scan_corrupt; #[cfg(test)] mod scan_test; #[cfg(test)] +mod sequence_test; +#[cfg(test)] mod set_role_state_test; #[cfg(test)] mod skip_wal_test; diff --git a/src/mito2/src/engine/catchup_test.rs b/src/mito2/src/engine/catchup_test.rs index 5c8e357c056..b470db5e12a 100644 --- a/src/mito2/src/engine/catchup_test.rs +++ b/src/mito2/src/engine/catchup_test.rs @@ -14,6 +14,7 @@ use std::assert_matches; use std::collections::HashMap; +use std::sync::Arc; use api::v1::Rows; use common_error::ext::ErrorExt; @@ -32,6 +33,7 @@ use store_api::storage::{RegionId, ScanRequest}; use crate::config::MitoConfig; use crate::engine::MitoEngine; use crate::error::Error; +use crate::manifest::action::RegionEdit; use crate::test_util::{ CreateRequestBuilder, LogStoreFactory, TestEnv, build_rows, flush_region, kafka_log_store_factory, prepare_test_for_kafka_log_store, put_rows, @@ -168,6 +170,220 @@ async fn test_catchup_with_last_entry_id(factory: Option) { assert!(resp.is_ok()); } +#[apply(single_kafka_log_store_factory)] +async fn test_catchup_preserves_region_edit_sequence( + factory: Option, + #[values(false, true)] open_before_edit: bool, +) { + use store_api::region_engine::SettableRegionRoleState; + + common_telemetry::init_default_ut_logging(); + let Some(factory) = factory else { + return; + }; + + let mut env = TestEnv::with_prefix("catchup_edit_sequence") + .await + .with_log_store_factory(factory.clone()); + let topic = prepare_test_for_kafka_log_store(&factory).await.unwrap(); + let config = MitoConfig { + schedule_compaction_after_edit: false, + ..Default::default() + }; + let leader_engine = env.create_engine(config.clone()).await; + let follower_engine = env.create_follower_engine(config).await; + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new() + .kafka_topic(Some(topic.clone())) + .build(); + let column_schemas = rows_schema(&request); + let open_request = RegionOpenRequest { + engine: String::new(), + table_dir: request.table_dir.clone(), + path_type: PathType::Bare, + options: HashMap::from([( + WAL_OPTIONS_KEY.to_string(), + serde_json::to_string(&WalOptions::Kafka(KafkaWalOptions::new(topic))).unwrap(), + )]), + skip_wal_replay: true, + checkpoint: None, + requirements: Default::default(), + }; + leader_engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_rows( + &leader_engine, + region_id, + Rows { + schema: column_schemas.clone(), + rows: build_rows(0, 3), + }, + ) + .await; + flush_region(&leader_engine, region_id, None).await; + let leader = leader_engine.get_region(region_id).unwrap(); + let flushed_entry_id = leader.version().flushed_entry_id; + let flushed_sequence = leader.version().flushed_sequence; + let flushed_rows = scan_region(&leader_engine, region_id) + .await + .pretty_print() + .unwrap(); + + put_rows( + &leader_engine, + region_id, + Rows { + schema: column_schemas.clone(), + rows: build_rows(3, 5), + }, + ) + .await; + let unflushed = leader.version_control.current(); + let unflushed_entry_id = unflushed.last_entry_id; + assert!(unflushed_entry_id > flushed_entry_id); + assert_eq!(unflushed.version.flushed_entry_id, flushed_entry_id); + + if open_before_edit { + follower_engine + .handle_request(region_id, RegionRequest::Open(open_request.clone())) + .await + .unwrap(); + } + // Reuses the flushed SST without flushing the second batch. + let file = leader.version().ssts.levels()[0] + .files + .values() + .next() + .unwrap() + .meta_ref() + .clone(); + leader_engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![file], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + }, + ) + .await + .unwrap(); + let edit_sequence = leader.version_control.committed_sequence(); + assert!(edit_sequence > unflushed.committed_sequence); + let expected_rows = scan_region(&leader_engine, region_id) + .await + .pretty_print() + .unwrap(); + assert_ne!(flushed_rows, expected_rows); + + if !open_before_edit { + follower_engine + .handle_request(region_id, RegionRequest::Open(open_request)) + .await + .unwrap(); + } + let candidate_before_catchup = follower_engine.get_region(region_id).unwrap(); + let before_catchup = candidate_before_catchup.version_control.current(); + assert!(candidate_before_catchup.provider.is_remote_wal()); + assert!(before_catchup.version.memtables.is_empty()); + assert_eq!(before_catchup.last_entry_id, flushed_entry_id); + assert_eq!( + before_catchup.committed_sequence, + if open_before_edit { + flushed_sequence + } else { + edit_sequence + } + ); + assert_eq!( + scan_region(&follower_engine, region_id) + .await + .pretty_print() + .unwrap(), + flushed_rows + ); + + let resp = leader_engine + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower) + .await + .unwrap(); + let last_entry_id = get_last_entry_id(resp); + assert_eq!(last_entry_id, Some(unflushed_entry_id)); + assert_eq!(leader.version().flushed_entry_id, flushed_entry_id); + assert!(!leader.version().memtables.is_empty()); + follower_engine + .handle_request( + region_id, + RegionRequest::Catchup(RegionCatchupRequest { + set_writable: true, + entry_id: last_entry_id, + ..Default::default() + }), + ) + .await + .unwrap(); + let candidate = follower_engine.get_region(region_id).unwrap(); + assert!(candidate.is_writable()); + assert_eq!( + Arc::ptr_eq( + &candidate_before_catchup.version_control, + &candidate.version_control + ), + !open_before_edit + ); + let recovered = candidate.version_control.current(); + assert!(recovered.last_entry_id >= unflushed_entry_id); + assert_eq!(recovered.version.flushed_entry_id, flushed_entry_id); + assert!(recovered.committed_sequence >= edit_sequence); + assert!(recovered.last_sequence >= recovered.committed_sequence); + assert!(!recovered.version.memtables.is_empty()); + assert_eq!( + scan_region(&follower_engine, region_id) + .await + .pretty_print() + .unwrap(), + expected_rows + ); + + put_rows( + &follower_engine, + region_id, + Rows { + schema: column_schemas, + rows: build_rows(5, 6), + }, + ) + .await; + let current = candidate.version_control.current(); + assert_eq!(current.committed_sequence, recovered.last_sequence + 1); + assert!(current.committed_sequence > edit_sequence); + assert!(current.last_sequence >= current.committed_sequence); + let expected = "\ ++-------+---------+---------------------+ +| tag_0 | field_0 | ts | ++-------+---------+---------------------+ +| 0 | 0.0 | 1970-01-01T00:00:00 | +| 1 | 1.0 | 1970-01-01T00:00:01 | +| 2 | 2.0 | 1970-01-01T00:00:02 | +| 3 | 3.0 | 1970-01-01T00:00:03 | +| 4 | 4.0 | 1970-01-01T00:00:04 | +| 5 | 5.0 | 1970-01-01T00:00:05 | ++-------+---------+---------------------+"; + assert_eq!( + scan_region(&follower_engine, region_id) + .await + .pretty_print() + .unwrap(), + expected + ); +} + #[apply(single_kafka_log_store_factory)] async fn test_catchup_with_incorrect_last_entry_id(factory: Option) { use store_api::region_engine::SettableRegionRoleState; @@ -536,7 +752,10 @@ async fn scan_region(engine: &MitoEngine, region_id: RegionId) -> RecordBatches } #[apply(single_raft_engine_log_store_factory)] -async fn test_local_catchup(factory: Option) { +async fn test_local_catchup( + factory: Option, + #[values(false, true)] reopen_before_catchup: bool, +) { use store_api::region_engine::SettableRegionRoleState; use crate::test_util::LogStoreImpl; @@ -599,6 +818,10 @@ async fn test_local_catchup(factory: Option) { rows: build_rows(8, 9), }; put_rows(&leader_engine, region_id, rows).await; + let old_region = leader_engine.get_region(region_id).unwrap(); + if !reopen_before_catchup { + old_region.version_control.update_last_sequence(10); + } let resp = leader_engine .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower) .await @@ -606,27 +829,27 @@ async fn test_local_catchup(factory: Option) { let last_entry_id = get_last_entry_id(resp); assert_eq!(last_entry_id.unwrap(), 3); - close_region(&leader_engine, region_id).await; - // Reopen the region, and skip the wal replay. - leader_engine - .handle_request( - region_id, - RegionRequest::Open(RegionOpenRequest { - engine: String::new(), - table_dir: table_dir.clone(), - options: HashMap::new(), - skip_wal_replay: true, - path_type: PathType::Bare, - checkpoint: None, - requirements: Default::default(), - }), - ) - .await - .unwrap(); + assert_eq!(old_region.version_control.committed_sequence(), 7); - // The last entry id should be 1. - let region = leader_engine.get_region(region_id).unwrap(); - assert_eq!(region.version_control.current().last_entry_id, 1); + if reopen_before_catchup { + close_region(&leader_engine, region_id).await; + open_region(&leader_engine, region_id, table_dir, true).await; + } + let region_before_catchup = leader_engine.get_region(region_id).unwrap(); + let current = region_before_catchup.version_control.current(); + if reopen_before_catchup { + assert!(current.version.memtables.is_empty()); + assert_eq!( + ( + current.last_sequence, + current.committed_sequence, + current.last_entry_id + ), + (3, 3, 1) + ); + } else { + assert!(!current.version.memtables.is_empty()); + } // There are 2 entries in the log store. let (start, end) = log_store.span(&RaftEngineProvider::new(region_id.into())); @@ -644,9 +867,24 @@ async fn test_local_catchup(factory: Option) { ) .await; assert!(resp.is_ok()); - // After catchup, the last entry id should be 3. let region = leader_engine.get_region(region_id).unwrap(); - assert_eq!(region.version_control.current().last_entry_id, 3); + assert_eq!( + Arc::ptr_eq( + ®ion_before_catchup.version_control, + ®ion.version_control + ), + reopen_before_catchup + ); + let expected_last_sequence = if reopen_before_catchup { 3 } else { 10 }; + let current = region.version_control.current(); + assert_eq!( + ( + current.last_sequence, + current.committed_sequence, + current.last_entry_id + ), + (expected_last_sequence, 3, 3) + ); // The log store has been obsoleted these 2 entries. let (start, end) = log_store.span(&RaftEngineProvider::new(region_id.into())); @@ -654,7 +892,7 @@ async fn test_local_catchup(factory: Option) { assert_eq!(end, None); // For local WAL, entries are not replayed during catchup. - // Therefore, any rows that were not flushed before closing the region will not be visible. + // Therefore, any rows that were not flushed before reopening the region will not be visible. let batches = scan_region(&leader_engine, region_id).await; let expected = "\ +-------+---------+---------------------+ @@ -672,6 +910,11 @@ async fn test_local_catchup(factory: Option) { rows: build_rows(4, 7), }; put_rows(&leader_engine, region_id, rows).await; + let current = region.version_control.current(); + assert_eq!( + (current.last_sequence, current.committed_sequence), + (expected_last_sequence + 3, expected_last_sequence + 3) + ); let batches = scan_region(&leader_engine, region_id).await; let expected = "\ diff --git a/src/mito2/src/engine/edit_region_test.rs b/src/mito2/src/engine/edit_region_test.rs index ace17905eb4..4ae44196e15 100644 --- a/src/mito2/src/engine/edit_region_test.rs +++ b/src/mito2/src/engine/edit_region_test.rs @@ -26,7 +26,7 @@ use common_time::util::current_time_millis; use datatypes::arrow::array::{ArrayRef, Float64Array, StringArray, TimestampMillisecondArray}; use datatypes::arrow::datatypes::{DataType, Field, Schema, TimeUnit}; use object_store::ObjectStore; -use store_api::region_engine::RegionEngine; +use store_api::region_engine::{RegionEngine, RegionManifestInfo, RegionRole}; use store_api::region_request::{ RegionBulkInsertsRequest, RegionCloseRequest, RegionPutRequest, RegionRequest, }; @@ -38,6 +38,7 @@ use crate::engine::MitoEngine; use crate::engine::listener::EventListener; use crate::manifest::action::RegionEdit; use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState}; +use crate::request::{RegionEditRequest, WorkerRequest}; use crate::sst::file::FileMeta; use crate::test_util::{CreateRequestBuilder, TestEnv, build_rows, rows_schema}; use crate::time_provider::mock::MockTimeProvider; @@ -565,6 +566,71 @@ async fn test_region_edit_with_file_sequence_is_not_merged() { assert_eq!(Some(3), region_file_sequence(®ion, third_file_id)); } +#[tokio::test] +async fn test_failed_region_edit_preserves_sequence() { + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + schedule_compaction_after_edit: false, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + engine + .handle_request( + region_id, + RegionRequest::Create(CreateRequestBuilder::new().build()), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + region.version_control.update_last_sequence(2); + let manifest_guard = region.manifest_ctx.manifest_manager.write().await; + let (tx, rx) = oneshot::channel(); + engine + .inner + .workers + .submit_to_worker( + region_id, + WorkerRequest::EditRegion(RegionEditRequest::new( + region_id, + test_region_edit(region_id, FileId::random()), + false, + tx, + )), + ) + .await + .unwrap(); + // Sync fails before taking the manifest lock, after the edit starts. + assert!( + engine + .sync_region(region_id, RegionManifestInfo::mito(0, 0, 0).into()) + .await + .is_err() + ); + assert_eq!( + region.state(), + RegionRoleState::Leader(RegionLeaderState::Editing) + ); + assert_eq!(region.version_control.current().last_sequence, 3); + assert_eq!(region.version_control.committed_sequence(), 0); + region.set_role(RegionRole::Follower); + drop(manifest_guard); + assert!(rx.await.unwrap().is_err()); + assert_eq!(region.version_control.current().last_sequence, 3); + assert_eq!(region.version_control.committed_sequence(), 0); + + region.set_role(RegionRole::Leader); + let file_id = FileId::random(); + engine + .edit_region(region_id, test_region_edit(region_id, file_id)) + .await + .unwrap(); + assert_eq!(region_file_sequence(®ion, file_id), Some(4)); + let current = region.version_control.current(); + assert_eq!((current.last_sequence, current.committed_sequence), (4, 4)); +} + #[tokio::test] async fn test_region_edit_clears_preserve_row_sequence() { let mut env = TestEnv::new().await; diff --git a/src/mito2/src/engine/object_store_wal_recovery_test.rs b/src/mito2/src/engine/object_store_wal_recovery_test.rs index d5da18bf521..a9713d02fcc 100644 --- a/src/mito2/src/engine/object_store_wal_recovery_test.rs +++ b/src/mito2/src/engine/object_store_wal_recovery_test.rs @@ -1251,8 +1251,21 @@ async fn test_reopen_after_a_failed_create_shows_only_the_acknowledged_write() { assert_eq!(vec![0, 1], wal_object_seqs(&object_store).await); assert_eq!(0, latest(&store, REGION_A)); - // The same key and timestamp is written again under the same row - // sequence, and acknowledged from object 2. + assert_eq!( + 1, + region(&engine, REGION_A) + .version_control + .current() + .last_sequence + ); + assert_eq!( + 0, + region(&engine, REGION_A) + .version_control + .committed_sequence() + ); + + // Write the same key and timestamp with a higher sequence in object 2. let mut writer = SealedWriter { store: store.clone(), admitted: 1, @@ -1266,7 +1279,7 @@ async fn test_reopen_after_a_failed_create_shows_only_the_acknowledged_write() { assert_eq!(vec![1, 2], wal_object_seqs(&object_store).await); assert_eq!(entry_id(2, 1), latest(&store, REGION_A)); let region_a = region(&engine, REGION_A); - assert_eq!(1, region_a.version_control.committed_sequence()); + assert_eq!(2, region_a.version_control.committed_sequence()); let expected = "\ +-------+---------+---------------------+ | tag_0 | field_0 | ts | diff --git a/src/mito2/src/engine/sequence_test.rs b/src/mito2/src/engine/sequence_test.rs new file mode 100644 index 00000000000..f6c99ebb61b --- /dev/null +++ b/src/mito2/src/engine/sequence_test.rs @@ -0,0 +1,410 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Mito sequence recovery tests using a memory WAL with store-assigned entry ids. +//! Uses ObjectStore providers; Kafka producers are not tested. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use api::v1::Rows; +use common_recordbatch::RecordBatches; +use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions}; +use futures::stream; +use log_store::error::{Error, IllegalStateSnafu, Result}; +use store_api::logstore::entry::{Entry, NaiveEntry}; +use store_api::logstore::provider::Provider; +use store_api::logstore::{AppendBatchResponse, EntryId, LogStore, SendableEntryStream}; +use store_api::region_engine::{RegionEngine, RegionRole}; +use store_api::region_request::{PathType, RegionOpenRequest, RegionPutRequest, RegionRequest}; +use store_api::storage::{RegionId, ScanRequest}; +use tokio::sync::oneshot; + +use crate::config::MitoConfig; +use crate::engine::MitoEngine; +use crate::test_util::{ + CreateRequestBuilder, TestEnv, build_rows_for_key, flush_region, rows_schema, +}; + +#[derive(Debug)] +enum AppendFault { + Persist, + Partial(RegionId), + Deferred { + release: oneshot::Receiver<()>, + saved: oneshot::Sender<()>, + }, +} + +#[derive(Debug, Default)] +struct LogState { + entries: HashMap>, + fault: Option, + append_calls: usize, +} + +impl LogState { + fn save(&mut self, entries: Vec) -> AppendBatchResponse { + let mut last_entry_ids = HashMap::new(); + for mut entry in entries { + let log = self.entries.entry(entry.provider().clone()).or_default(); + // Entry ids start from 1 (zero means no data). + let offset = log.len() as u64 + 1; + entry.set_entry_id(offset); + last_entry_ids.insert(entry.region_id(), offset); + log.push(entry); + } + AppendBatchResponse { last_entry_ids } + } +} + +#[derive(Debug, Default)] +struct MemoryLogStore { + state: Arc>, +} + +impl MemoryLogStore { + fn fail_next_append(&self, fault: AppendFault) { + let mut state = self.state.lock().unwrap(); + assert!(state.fault.replace(fault).is_none()); + } +} + +#[async_trait::async_trait] +impl LogStore for MemoryLogStore { + type Error = Error; + + async fn stop(&self) -> Result<()> { + Ok(()) + } + + async fn append_batch(&self, entries: Vec) -> Result { + let mut state = self.state.lock().unwrap(); + state.append_calls += 1; + match state.fault.take() { + None => return Ok(state.save(entries)), + Some(AppendFault::Persist) => { + state.save(entries); + } + Some(AppendFault::Partial(region_id)) => { + state.save( + entries + .into_iter() + .filter(|e| e.region_id() == region_id) + .collect(), + ); + } + Some(AppendFault::Deferred { release, saved }) => { + let state = self.state.clone(); + common_runtime::spawn_global(async move { + if release.await.is_ok() { + state.lock().unwrap().save(entries); + let _ = saved.send(()); + } + }); + } + } + IllegalStateSnafu {}.fail() + } + + async fn read( + &self, + provider: &Provider, + id: EntryId, + ) -> Result> { + // Snapshot the log for recovery. + let entries = self + .state + .lock() + .unwrap() + .entries + .get(provider) + .cloned() + .unwrap_or_default(); + Ok(Box::pin(stream::iter([Ok(entries + .into_iter() + .filter(|e| e.entry_id() >= id) + .collect())]))) + } + + async fn create_namespace(&self, _provider: &Provider) -> Result<()> { + Ok(()) + } + async fn delete_namespace(&self, _provider: &Provider) -> Result<()> { + Ok(()) + } + async fn list_namespaces(&self) -> Result> { + Ok(vec![]) + } + async fn obsolete( + &self, + _provider: &Provider, + _region_id: RegionId, + _id: EntryId, + ) -> Result<()> { + Ok(()) + } + async fn obsolete_all(&self, _provider: &Provider, _region_id: RegionId) -> Result<()> { + Ok(()) + } + + fn entry( + &self, + data: Vec, + entry_id: EntryId, + region_id: RegionId, + provider: &Provider, + ) -> Result { + Ok(Entry::Naive(NaiveEntry { + data, + entry_id, + region_id, + provider: provider.clone(), + })) + } + + fn latest_entry_id(&self, provider: &Provider) -> Result { + Ok(self + .state + .lock() + .unwrap() + .entries + .get(provider) + .and_then(|log| log.last()) + .map_or(0, Entry::entry_id)) + } +} + +fn wal_options() -> HashMap { + HashMap::from([( + WAL_OPTIONS_KEY.to_string(), + serde_json::to_string(&WalOptions::ObjectStore(ObjectStoreWalOptions::new( + "sequence-test/".to_string(), + ))) + .unwrap(), + )]) +} + +async fn create_region( + engine: &MitoEngine, + region_id: RegionId, +) -> (String, Vec) { + let request = CreateRequestBuilder::new() + .insert_option(WAL_OPTIONS_KEY, &wal_options()[WAL_OPTIONS_KEY]) + .build(); + let table_dir = request.table_dir.clone(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + (table_dir, schema) +} + +async fn open_region(engine: &MitoEngine, region_id: RegionId, table_dir: String) { + engine + .handle_request( + region_id, + RegionRequest::Open(RegionOpenRequest { + engine: String::new(), + table_dir, + path_type: PathType::Bare, + options: wal_options(), + skip_wal_replay: false, + checkpoint: None, + requirements: Default::default(), + }), + ) + .await + .unwrap(); + engine + .set_region_role(region_id, RegionRole::Leader) + .unwrap(); +} + +fn put_request(schema: &[api::v1::ColumnSchema], keys: &[(&str, usize)]) -> RegionPutRequest { + RegionPutRequest { + rows: Rows { + schema: schema.to_vec(), + rows: keys + .iter() + .flat_map(|(key, value)| build_rows_for_key(key, 0, 1, *value)) + .collect(), + }, + skip_wal: false, + hint: None, + partition_expr_version: None, + } +} + +async fn scan_rows(engine: &MitoEngine, region_id: RegionId) -> String { + let stream = engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(); + RecordBatches::try_collect(stream) + .await + .unwrap() + .pretty_print() + .unwrap() +} + +#[tokio::test] +async fn test_persisted_wal_error_does_not_overwrite_success() { + for flat_format in [false, true] { + for (deferred, flush) in [(false, false), (true, false), (true, true)] { + let mut env = TestEnv::new().await; + let store = Arc::new(MemoryLogStore::default()); + let config = MitoConfig { + default_flat_format: flat_format, + num_workers: 1, + ..Default::default() + }; + let engine = env + .create_engine_with_log_store(config.clone(), store.clone()) + .await; + let region_id = RegionId::new(1, 1); + let (table_dir, schema) = create_region(&engine, region_id).await; + let (release, released) = oneshot::channel(); + let (saved, saved_rx) = oneshot::channel(); + store.fail_next_append(if deferred { + AppendFault::Deferred { + release: released, + saved, + } + } else { + AppendFault::Persist + }); + assert!( + engine + .handle_request( + region_id, + RegionRequest::Put(put_request(&schema, &[("a", 1), ("b", 1)])) + ) + .await + .is_err() + ); + let failed = engine + .get_region(region_id) + .unwrap() + .version_control + .current(); + assert_eq!(failed.committed_sequence, 0); + assert_eq!(failed.last_sequence, 2); + assert_eq!(failed.last_entry_id, 0); + assert_eq!(failed.version.flushed_sequence, 0); + engine + .handle_request( + region_id, + RegionRequest::Put(put_request(&schema, &[("b", 2)])), + ) + .await + .unwrap(); + if flush { + flush_region(&engine, region_id, None).await; + } + if deferred { + release.send(()).unwrap(); + saved_rx.await.unwrap(); + } + assert!( + scan_rows(&engine, region_id) + .await + .contains("| b | 2.0") + ); + engine.stop().await.unwrap(); + drop(engine); + let engine = env.create_engine_with_log_store(config, store).await; + open_region(&engine, region_id, table_dir).await; + let recovered = scan_rows(&engine, region_id).await; + assert!( + recovered.contains("| b | 2.0"), + "deferred={deferred}, flush={flush}, flat={flat_format}: {recovered}" + ); + let current = engine + .get_region(region_id) + .unwrap() + .version_control + .current(); + assert_eq!(current.committed_sequence, 3); + assert_eq!(current.last_sequence, 3); + engine.stop().await.unwrap(); + } + } +} + +#[tokio::test] +async fn test_partial_region_append_preserves_all_allocations() { + let mut env = TestEnv::new().await; + let store = Arc::new(MemoryLogStore::default()); + let engine = env + .create_engine_with_log_store( + MitoConfig { + num_workers: 1, + ..Default::default() + }, + store.clone(), + ) + .await; + let regions = [RegionId::new(1, 1), RegionId::new(1, 2)]; + let mut schemas = Vec::new(); + let mut table_dirs = Vec::new(); + for id in regions { + let (dir, schema) = create_region(&engine, id).await; + table_dirs.push(dir); + schemas.push(schema); + } + store.fail_next_append(AppendFault::Partial(regions[0])); + let requests = regions + .into_iter() + .zip(&schemas) + .map(|(id, schema)| (id, put_request(schema, &[("a", 1), ("b", 1)]))) + .collect(); + for (_, response) in Arc::new(engine.clone()).handle_batch_put_requests(requests) { + assert!(response.await.is_err()); + } + assert_eq!(store.state.lock().unwrap().append_calls, 1); + for (id, schema) in regions.into_iter().zip(&schemas) { + let region = engine.get_region(id).unwrap(); + let current = region.version_control.current(); + assert_eq!( + ( + current.last_sequence, + current.committed_sequence, + current.last_entry_id + ), + (2, 0, 0) + ); + assert!(current.version.memtables.is_empty()); + assert_eq!( + store.latest_entry_id(®ion.provider).unwrap(), + u64::from(id == regions[0]) + ); + engine + .handle_request(id, RegionRequest::Put(put_request(schema, &[("b", 2)]))) + .await + .unwrap(); + assert_eq!(region.version_control.current().committed_sequence, 3); + } + engine.stop().await.unwrap(); + drop(engine); + let engine = env + .create_engine_with_log_store(MitoConfig::default(), store) + .await; + for (id, dir) in regions.into_iter().zip(table_dirs) { + open_region(&engine, id, dir).await; + assert!(scan_rows(&engine, id).await.contains("| b | 2.0")); + } + engine.stop().await.unwrap(); +} diff --git a/src/mito2/src/engine/staging_test.rs b/src/mito2/src/engine/staging_test.rs index 98973de4f30..c29c4bbe3a3 100644 --- a/src/mito2/src/engine/staging_test.rs +++ b/src/mito2/src/engine/staging_test.rs @@ -759,6 +759,39 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) .await .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let file = { + let manager = region.manifest_ctx.manifest_manager.read().await; + manager + .staging_manifest() + .unwrap() + .files + .values() + .next() + .unwrap() + .clone() + }; + for expected in [11, 12] { + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![file.clone()], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + }, + ) + .await + .unwrap(); + let current = region.version_control.current(); + assert_eq!(current.last_sequence, expected); + assert_eq!(current.committed_sequence, 10); + } + // Verify we're in staging mode and staging manifests exist let data_home = env.data_home(); let region_dir = format!("{}/data/test/1024_0000000000", data_home.display()); @@ -770,13 +803,11 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) .unwrap(); assert_eq!( staging_files_before.len(), - // Two files for flush operation - // One file for entering staging mode - 3, - "Staging manifest directory should contain 3 files before exit, got: {:?}", + // Two flushes, two edits and entering staging mode. + 5, + "Staging manifest directory should contain 5 files before exit, got: {:?}", staging_files_before ); - let region = engine.get_region(region_id).unwrap(); { let manager = region.manifest_ctx.manifest_manager.read().await; let staging_manifest = manager.staging_manifest().unwrap(); @@ -950,6 +981,11 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) // Verify we're back in normal mode let workers = &engine.inner.workers; let region = workers.get_region(region_id).unwrap(); + let current = region.version_control.current(); + assert_eq!( + (current.last_sequence, current.committed_sequence), + (12, 12) + ); assert!( !region.is_staging(), "Region should no longer be in staging mode" diff --git a/src/mito2/src/engine/sync_test.rs b/src/mito2/src/engine/sync_test.rs index d75a9ef0313..ee0cd7ebe64 100644 --- a/src/mito2/src/engine/sync_test.rs +++ b/src/mito2/src/engine/sync_test.rs @@ -20,10 +20,10 @@ use common_recordbatch::RecordBatches; use datatypes::prelude::ConcreteDataType; use datatypes::schema::ColumnSchema; use store_api::metadata::ColumnMetadata; -use store_api::region_engine::{RegionEngine, RegionManifestInfo}; +use store_api::region_engine::{RegionEngine, RegionManifestInfo, RegionRole}; use store_api::region_request::{ AddColumn, AddColumnLocation, AlterKind, PathType, RegionAlterRequest, RegionOpenRequest, - RegionRequest, + RegionPutRequest, RegionRequest, }; use store_api::storage::{RegionId, ScanRequest}; @@ -170,6 +170,11 @@ async fn test_sync_after_flush_region_with_format(flat_format: bool) { .await .unwrap(); common_telemetry::info!("Scan the region on the follower engine after sync"); + let follower = follower_engine.get_region(region_id).unwrap(); + assert_eq!(follower.version_control.current().last_sequence, 3); + // Sync does not update committed sequence or entry id. + assert_eq!(follower.version_control.committed_sequence(), 0); + assert_eq!(follower.version_control.current().last_entry_id, 0); // Scan the region on the follower engine let expected = "\ +-------+---------+---------------------+ @@ -180,6 +185,80 @@ async fn test_sync_after_flush_region_with_format(flat_format: bool) { | 2 | 2.0 | 1970-01-01T00:00:02 | +-------+---------+---------------------+"; scan_check(&follower_engine, region_id, expected, 0, 1).await; + + // An edit may have a committed sequence above the flushed sequence. + let file = engine + .get_region(region_id) + .unwrap() + .version() + .ssts + .levels()[0] + .files + .values() + .next() + .unwrap() + .meta_ref() + .clone(); + engine + .edit_region( + region_id, + crate::manifest::action::RegionEdit { + files_to_add: vec![file], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + }, + ) + .await + .unwrap(); + let manifest_version = engine + .get_region(region_id) + .unwrap() + .manifest_ctx + .manifest_version() + .await; + follower_engine + .sync_region( + region_id, + RegionManifestInfo::mito(manifest_version, 0, 0).into(), + ) + .await + .unwrap(); + assert_eq!(follower.version_control.current().last_sequence, 4); + assert_eq!(follower.version_control.committed_sequence(), 0); + + // Writes after promotion must use a higher sequence. + follower_engine + .set_region_role(region_id, RegionRole::Leader) + .unwrap(); + let request = CreateRequestBuilder::new().build(); + // Skip WAL to isolate row sequence allocation. + follower_engine + .handle_request( + region_id, + RegionRequest::Put(RegionPutRequest { + rows: Rows { + schema: rows_schema(&request), + rows: build_rows(0, 1), + }, + skip_wal: true, + hint: None, + partition_expr_version: None, + }), + ) + .await + .unwrap(); + assert_eq!( + 5, + follower_engine + .get_region(region_id) + .unwrap() + .version_control + .committed_sequence() + ); } #[tokio::test] diff --git a/src/mito2/src/region/version.rs b/src/mito2/src/region/version.rs index 1c595fb0b9f..c1940b31ab0 100644 --- a/src/mito2/src/region/version.rs +++ b/src/mito2/src/region/version.rs @@ -59,6 +59,7 @@ impl VersionControl { VersionControl { data: RwLock::new(VersionControlData { version: Arc::new(version), + last_sequence: flushed_sequence, committed_sequence: flushed_sequence, last_entry_id: flushed_entry_id, is_dropped: false, @@ -76,16 +77,24 @@ impl VersionControl { self.data.read().unwrap().clone() } + /// Updates last sequence number to the maximum. + pub(crate) fn update_last_sequence(&self, seq: SequenceNumber) { + let mut data = self.data.write().unwrap(); + data.last_sequence = data.last_sequence.max(seq); + } + /// Updates the `committed_sequence` of version. pub(crate) fn set_committed_sequence(&self, seq: SequenceNumber) { let mut data = self.data.write().unwrap(); - data.committed_sequence = seq; + data.committed_sequence = data.committed_sequence.max(seq); + data.last_sequence = data.last_sequence.max(data.committed_sequence); } /// Updates committed sequence and entry id. pub(crate) fn set_sequence_and_entry_id(&self, seq: SequenceNumber, entry_id: EntryId) { let mut data = self.data.write().unwrap(); - data.committed_sequence = seq; + data.committed_sequence = data.committed_sequence.max(seq); + data.last_sequence = data.last_sequence.max(data.committed_sequence); data.last_entry_id = entry_id; } @@ -162,6 +171,9 @@ impl VersionControl { } else { version_data.committed_sequence }; + version_data.last_sequence = version_data + .last_sequence + .max(version_data.committed_sequence); version_data.version = new_version; } @@ -312,6 +324,7 @@ impl VersionControl { /// Overwrites the current version with a new version. pub(crate) fn overwrite_current(&self, version: VersionRef) { let mut version_data = self.data.write().unwrap(); + version_data.last_sequence = version_data.last_sequence.max(version.flushed_sequence); version_data.version = version; } @@ -336,6 +349,8 @@ pub(crate) type VersionControlRef = Arc; pub(crate) struct VersionControlData { /// Latest version. pub(crate) version: VersionRef, + /// Last allocated sequence number. + pub(crate) last_sequence: SequenceNumber, /// Sequence number of last committed data. /// /// Starts from 1 (zero means no data). @@ -561,3 +576,60 @@ impl VersionBuilder { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_util::version_util::VersionControlBuilder; + + #[test] + fn test_sequence_watermarks_are_monotonic() { + let builder = VersionControlBuilder::new(); + let mut version = builder.build_version(); + version.flushed_sequence = 8; + version.flushed_entry_id = 4; + let vc = VersionControl::new(version); + assert_eq!( + (vc.current().last_sequence, vc.committed_sequence()), + (8, 8) + ); + + vc.update_last_sequence(20); + vc.update_last_sequence(9); + vc.set_committed_sequence(10); + vc.set_committed_sequence(9); + assert_eq!( + (vc.current().last_sequence, vc.committed_sequence()), + (20, 10) + ); + assert_eq!(vc.current().last_entry_id, 4); + vc.set_sequence_and_entry_id(12, 5); + vc.set_sequence_and_entry_id(4, 6); + assert_eq!( + (vc.current().last_sequence, vc.committed_sequence()), + (20, 12) + ); + assert_eq!(vc.current().version.flushed_sequence, 8); + + for sequence in [25, 11] { + vc.apply_edit( + Some(RegionEdit { + files_to_add: vec![], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: Some(sequence), + }), + &[], + builder.file_purger(), + ); + assert_eq!( + (vc.current().last_sequence, vc.committed_sequence()), + (25, 25) + ); + assert_eq!(vc.current().last_entry_id, 6); + } + } +} diff --git a/src/mito2/src/region_write_ctx.rs b/src/mito2/src/region_write_ctx.rs index e4e1e505326..d37c42545a0 100644 --- a/src/mito2/src/region_write_ctx.rs +++ b/src/mito2/src/region_write_ctx.rs @@ -100,9 +100,9 @@ pub(crate) struct RegionWriteCtx { /// VersionControl of the region. version_control: VersionControlRef, /// Next sequence number to write. - /// - /// The context assigns a unique sequence number for each row. next_sequence: SequenceNumber, + /// Maximum sequence number allocated by this context. + max_sequence: Option, /// Next entry id of WAL to write. next_entry_id: EntryId, /// Valid WAL entry to write. @@ -148,7 +148,7 @@ impl RegionWriteCtx { ) -> RegionWriteCtx { let VersionControlData { version, - committed_sequence, + last_sequence, last_entry_id, .. } = version_control.current(); @@ -159,7 +159,8 @@ impl RegionWriteCtx { region_id, version, version_control: version_control.clone(), - next_sequence: committed_sequence + 1, + next_sequence: last_sequence + 1, + max_sequence: None, next_entry_id: last_entry_id + 1, wal_entry: WalEntry::default(), memtable_mutations: Vec::new(), @@ -208,8 +209,7 @@ impl RegionWriteCtx { self.wal_notifiers.push(notify); } - // Increase sequence number. - self.next_sequence += num_rows as u64; + self.advance_sequence(num_rows); // Update metrics. match OpType::try_from(op_type) { @@ -224,6 +224,8 @@ impl RegionWriteCtx { &mut self, wal_writer: &mut WalWriter, ) -> Result<()> { + // Reserve sequences before WAL writes to avoid reuse on failure. + self.reserve_sequences(); wal_writer.add_entry( self.region_id, self.next_entry_id, @@ -294,6 +296,10 @@ impl RegionWriteCtx { if self.failed { return; } + // Reserve sequences for WAL replay and skip-WAL writes. + if self.source == WriteSource::WalReplay || self.skip_wal() { + self.reserve_sequences(); + } // A failed installation may leave some rows in memory. if self.has_skip_wal_writes { self.version.memtables.mutable.mark_skip_wal_writes(); @@ -395,7 +401,7 @@ impl RegionWriteCtx { self.bulk_notifiers .push(WriteNotify::new(sender, bulk.num_rows())); - self.next_sequence += bulk.num_rows() as u64; + self.advance_sequence(bulk.num_rows()); self.bulk_parts.push(bulk); true } @@ -453,6 +459,21 @@ impl RegionWriteCtx { } } + /// Advances the sequence number and records the maximum. + fn advance_sequence(&mut self, num_rows: usize) { + self.next_sequence += num_rows as u64; + if num_rows > 0 { + let sequence = self.next_sequence - 1; + self.max_sequence = Some(self.max_sequence.map_or(sequence, |max| max.max(sequence))); + } + } + + fn reserve_sequences(&self) { + if let Some(sequence) = self.max_sequence { + self.version_control.update_last_sequence(sequence); + } + } + /// Publishes the assigned sequences and entry id to the region's committed /// watermark. Only call after both [`write_mutations`](Self::write_mutations) /// and [`write_bulk`](Self::write_bulk) have completed; a failed context @@ -461,8 +482,13 @@ impl RegionWriteCtx { if self.failed { return; } - self.version_control - .set_sequence_and_entry_id(self.next_sequence - 1, self.next_entry_id - 1); + if let Some(sequence) = self.max_sequence { + self.version_control + .set_sequence_and_entry_id(sequence, self.next_entry_id - 1); + } else { + // Empty entries only update the entry id. + self.version_control.set_entry_id(self.next_entry_id - 1); + } } } @@ -1014,4 +1040,160 @@ mod tests { raw_data: None, } } + + fn sequence_rows(num_rows: usize) -> Rows { + use api::v1::helper::{tag_column_schema, time_index_column_schema}; + Rows { + schema: vec![ + time_index_column_schema("ts", api::v1::ColumnDataType::TimestampMillisecond), + tag_column_schema("tag_0", api::v1::ColumnDataType::String), + ], + rows: (0..num_rows) + .map(|i| api::v1::Row { + values: vec![ + crate::test_util::ts_ms_value(i as i64), + api::v1::Value { + value_data: Some(api::v1::value::ValueData::StringValue( + "a".to_string(), + )), + }, + ], + }) + .collect(), + } + } + + #[tokio::test] + async fn test_replay_sequence_maximum_below_allocation_floor() { + let builder = VersionControlBuilder::new(); + let region_id = builder.region_id(); + let vc = Arc::new(builder.build()); + vc.update_last_sequence(100); + let provider = Provider::raft_engine_provider(region_id.as_u64()); + let mut ctx = RegionWriteCtx::new( + region_id, + &vc, + provider.clone(), + None, + WriteSource::WalReplay, + ); + for (sequence, num_rows) in [(40, 2), (3, 1)] { + ctx.push_mutation( + OpType::Put as i32, + Some(sequence_rows(num_rows)), + None, + OptionOutputTx::none(), + Some(sequence), + false, + ); + } + for sequence in [10, 2] { + let mut part = new_bulk_part(); + part.fill_missing_columns(&ctx.version.metadata).unwrap(); + assert!(ctx.push_bulk(OptionOutputTx::none(), part, Some(sequence), false)); + } + assert_eq!(ctx.wal_entry.mutations[0].sequence, 40); + assert_eq!(ctx.bulk_parts[0].sequence, 10); + assert_eq!(ctx.bulk_parts[1].sequence, 2); + assert_eq!(vc.committed_sequence(), 0); + ctx.set_next_entry_id(8); + ctx.write_memtables().await; + assert_eq!(vc.committed_sequence(), 41); + assert_eq!(vc.current().last_sequence, 100); + assert_eq!(vc.current().last_entry_id, 7); + + let mut ctx = RegionWriteCtx::new(region_id, &vc, provider, None, WriteSource::Request); + ctx.push_mutation( + OpType::Put as i32, + Some(sequence_rows(2)), + None, + OptionOutputTx::none(), + None, + true, + ); + assert_eq!(ctx.memtable_mutations[0].0.sequence, 101); + ctx.write_memtables().await; + assert_eq!(vc.committed_sequence(), 102); + assert_eq!(vc.current().last_sequence, 102); + assert_eq!(vc.current().last_entry_id, 7); + } + + #[tokio::test] + async fn test_empty_context_does_not_publish_allocation_floor() { + let builder = VersionControlBuilder::new(); + let region_id = builder.region_id(); + let vc = Arc::new(builder.build()); + vc.update_last_sequence(100); + for empty_objects in [false, true] { + let mut ctx = + RegionWriteCtx::new(region_id, &vc, Provider::Noop, None, WriteSource::WalReplay); + if empty_objects { + ctx.push_mutation( + OpType::Put as i32, + Some(sequence_rows(0)), + None, + OptionOutputTx::none(), + Some(500), + false, + ); + ctx.push_mutation( + OpType::Put as i32, + None, + None, + OptionOutputTx::none(), + Some(600), + false, + ); + let mut part = new_bulk_part(); + part.fill_missing_columns(&ctx.version.metadata).unwrap(); + part.batch = part.batch.slice(0, 0); + assert!(ctx.push_bulk(OptionOutputTx::none(), part, Some(700), true)); + } + ctx.set_next_entry_id(4); + ctx.write_memtables().await; + let current = vc.current(); + assert_eq!(current.last_sequence, 100); + assert_eq!(current.committed_sequence, 0); + assert_eq!(current.last_entry_id, 3); + } + } + + #[tokio::test] + async fn test_rejected_bulk_does_not_publish_sequence() { + use datatypes::arrow::array::StringDictionaryBuilder; + use datatypes::arrow::datatypes::Int32Type; + + let builder = VersionControlBuilder::new(); + let vc = Arc::new(builder.build()); + vc.update_last_sequence(100); + let mut ctx = RegionWriteCtx::new( + builder.region_id(), + &vc, + Provider::Noop, + None, + WriteSource::Request, + ); + let mut part = new_bulk_part(); + let mut dictionary = StringDictionaryBuilder::::new(); + dictionary.append("a").unwrap(); + dictionary.append("b").unwrap(); + let dictionary = Arc::new(dictionary.finish()) as ArrayRef; + let mut fields = part.batch.schema().fields().to_vec(); + fields.push(Arc::new(Field::new( + "tag_0", + dictionary.data_type().clone(), + true, + ))); + part.batch = DfRecordBatch::try_new( + Arc::new(Schema::new(fields)), + vec![part.batch.column(0).clone(), dictionary], + ) + .unwrap(); + let (tx, rx) = oneshot::channel(); + assert!(!ctx.push_bulk(OptionOutputTx::from(tx), part, Some(500), false)); + assert!(rx.await.unwrap().is_err()); + ctx.write_memtables().await; + assert_eq!(vc.committed_sequence(), 0); + assert_eq!(vc.current().last_sequence, 100); + } } diff --git a/src/mito2/src/worker/handle_catchup.rs b/src/mito2/src/worker/handle_catchup.rs index 92874672789..65f20c5837a 100644 --- a/src/mito2/src/worker/handle_catchup.rs +++ b/src/mito2/src/worker/handle_catchup.rs @@ -153,6 +153,10 @@ impl RegionWorkerLoop { .open(&self.config, &self.wal) .await?; debug_assert!(!reopened_region.is_writable()); + // Preserve allocated sequences without publishing the old memtables. + reopened_region + .version_control + .update_last_sequence(region.version_control.current().last_sequence); self.register_region(reopened_region.clone()); if let Some(state) = &self.series_index_task_state { state.wake(); diff --git a/src/mito2/src/worker/handle_manifest.rs b/src/mito2/src/worker/handle_manifest.rs index 373080aee90..9510b484d84 100644 --- a/src/mito2/src/worker/handle_manifest.rs +++ b/src/mito2/src/worker/handle_manifest.rs @@ -274,6 +274,10 @@ impl RegionWorkerLoop { ); let version = version_builder.build(); region.version_control.overwrite_current(Arc::new(version)); + // Restore last sequence from the manifest. + if let Some(sequence) = manifest.committed_sequence { + region.version_control.update_last_sequence(sequence); + } let updated = manifest.manifest_version > original_manifest_version; let _ = sender.send(Ok((manifest.manifest_version, updated))); @@ -311,7 +315,7 @@ impl RegionWorkerLoop { waiters, preload_sst_cache, } = request; - let file_sequence = region.version_control.committed_sequence() + 1; + let file_sequence = region.version_control.current().last_sequence + 1; edit.committed_sequence = Some(file_sequence); // Generic region edits (direct/import/staging) assign a new destination @@ -337,6 +341,7 @@ impl RegionWorkerLoop { waiters.reply_with(|| Err(e.clone()).context(EditRegionSnafu { region_id })); return; } + region.version_control.update_last_sequence(file_sequence); let request_sender = self.sender.clone(); let cache_manager = self.cache_manager.clone(); diff --git a/src/mito2/src/worker/handle_write.rs b/src/mito2/src/worker/handle_write.rs index 7e290a768fb..6b8e5be4276 100644 --- a/src/mito2/src/worker/handle_write.rs +++ b/src/mito2/src/worker/handle_write.rs @@ -1045,6 +1045,13 @@ mod tests { assert!(region_ctxs[&failing_region].is_failed()); assert!(!region_ctxs[&ok_region].is_failed()); assert_eq!(entry_id + 1, region_ctxs[&ok_region].next_entry_id()); + assert_eq!( + region_ctxs[&failing_region] + .version_control() + .current() + .last_sequence, + 1 + ); for region_ctx in region_ctxs.values_mut() { region_ctx.write_memtables().await; @@ -1077,6 +1084,7 @@ mod tests { async fn check_bulk_write_sequence_not_committed_before_install_worker_level(skip_wal: bool) { let region_id = RegionId::new(1, 1); let version_control = Arc::new(VersionControlBuilder::new().build()); + version_control.update_last_sequence(2); let mut region_ctxs = HashMap::new(); let mut ctx = RegionWriteCtx::new( @@ -1111,6 +1119,9 @@ mod tests { .await .expect("bulk write never reached the install barrier"); + assert_eq!(version_control.current().last_sequence, 5); + assert_eq!(version_control.current().last_entry_id, 0); + assert_eq!( 0, version_control.committed_sequence(), @@ -1120,11 +1131,14 @@ mod tests { barrier.release(); write_handle.await.expect("bulk write should complete"); assert_eq!( - 3, + 5, version_control.committed_sequence(), "committed sequence must cover the installed bulk rows" ); + let current = version_control.current(); + assert_eq!(current.last_sequence, 5); + assert_eq!(current.last_entry_id, u64::from(!skip_wal)); assert_eq!(3, rx.await.unwrap().unwrap()); } @@ -1159,6 +1173,7 @@ mod tests { let mut region_ctxs = HashMap::new(); let (ctx, rx) = new_region_ctx(region_id, false); + let version_control = ctx.version_control().clone(); region_ctxs.insert(region_id, ctx); assert!(!write_wal(&wal, &mut region_ctxs).await); @@ -1166,5 +1181,11 @@ mod tests { // All contexts are consumed and waiters are notified with the error. assert!(region_ctxs.is_empty()); assert!(rx.await.unwrap().is_err()); + let current = version_control.current(); + assert_eq!(current.last_sequence, 1); + assert_eq!(current.committed_sequence, 0); + assert_eq!(current.last_entry_id, 0); + assert_eq!(current.version.flushed_sequence, 0); + assert_eq!(current.version.flushed_entry_id, 0); } } From cdc0d3a055ecf71ba32278a2951881f88de1a1dc Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Wed, 28 Oct 2026 07:26:22 +0000 Subject: [PATCH 03/19] feat(procedure): support detached subprocedure recovery (#10009) Select Discard or Detach when submitting children via Status::Suspended. Persist the policy from the child's first normal or rollback checkpoint. Recover detached children as independent roots with their original id and context, using existing execution and cleanup without rebuilding the graph. Keep fresh root admission serialized while allowing accepted procedures to recover above the submission limit. Cover first persistence, repeated recovery, rollback, cleanup, defaults, and concurrent admission. Signed-off-by: WenyXu --- src/common/procedure/src/lib.rs | 1 + src/common/procedure/src/local.rs | 179 ++++--- src/common/procedure/src/local/recovery.rs | 582 +++++++++++++++++++++ src/common/procedure/src/local/runner.rs | 49 +- src/common/procedure/src/procedure.rs | 33 ++ src/common/procedure/src/store.rs | 35 +- 6 files changed, 793 insertions(+), 86 deletions(-) create mode 100644 src/common/procedure/src/local/recovery.rs diff --git a/src/common/procedure/src/lib.rs b/src/common/procedure/src/lib.rs index a21e5d1c47a..419fb41ca30 100644 --- a/src/common/procedure/src/lib.rs +++ b/src/common/procedure/src/lib.rs @@ -33,5 +33,6 @@ pub use crate::procedure::{ ContextProviderRef, EventContext, EventTrigger, LockKey, Output, ParseIdError, PoisonKey, PoisonKeys, Procedure, ProcedureContext, ProcedureId, ProcedureInfo, ProcedureManager, ProcedureManagerRef, ProcedureState, ProcedureWithId, RetryPhase, Status, StringKey, + SubprocedureRecovery, }; pub use crate::watcher::Watcher; diff --git a/src/common/procedure/src/local.rs b/src/common/procedure/src/local.rs index 2ae7f5e3e08..8801028b198 100644 --- a/src/common/procedure/src/local.rs +++ b/src/common/procedure/src/local.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +mod recovery; mod runner; use std::collections::hash_map::Entry; @@ -32,9 +33,9 @@ use tokio::sync::watch::{self, Receiver, Sender}; use tokio::sync::{Mutex as TokioMutex, Notify}; use crate::error::{ - self, CheckStatusSnafu, DuplicateProcedureSnafu, Error, LoaderConflictSnafu, - ManagerNotStartSnafu, ManagerPasuedSnafu, PoisonKeyNotDefinedSnafu, ProcedureNotFoundSnafu, - Result, StartRemoveOutdatedMetaTaskSnafu, StopRemoveOutdatedMetaTaskSnafu, + CheckStatusSnafu, DuplicateProcedureSnafu, Error, LoaderConflictSnafu, ManagerNotStartSnafu, + ManagerPasuedSnafu, PoisonKeyNotDefinedSnafu, ProcedureNotFoundSnafu, Result, + StartRemoveOutdatedMetaTaskSnafu, StopRemoveOutdatedMetaTaskSnafu, TooManyRunningProceduresSnafu, }; use crate::local::runner::Runner; @@ -44,7 +45,8 @@ use crate::store::poison_store::PoisonStoreRef; use crate::store::{ProcedureMessage, ProcedureMessages, ProcedureStore, StateStoreRef}; use crate::{ BoxedProcedure, ContextProvider, EventTrigger, LockKey, PoisonKey, ProcedureContext, - ProcedureId, ProcedureManager, ProcedureState, ProcedureWithId, StringKey, Watcher, + ProcedureId, ProcedureManager, ProcedureState, ProcedureWithId, StringKey, + SubprocedureRecovery, Watcher, }; /// The expired time of a procedure's metadata. @@ -81,6 +83,8 @@ pub(crate) struct ProcedureMeta { type_name: String, /// Parent procedure id. parent_id: Option, + /// Recovery policy captured when the procedure is submitted as a child. + subprocedure_recovery: SubprocedureRecovery, /// Context associated with the root submission. context: ProcedureContext, /// Notify to wait for subprocedures. @@ -116,6 +120,7 @@ impl ProcedureMeta { ProcedureMeta { id, parent_id, + subprocedure_recovery: SubprocedureRecovery::Discard, context, child_notify: Notify::new(), lock_key, @@ -129,6 +134,12 @@ impl ProcedureMeta { } } + /// Sets the recovery policy for this subprocedure. + fn with_subprocedure_recovery(mut self, recovery: SubprocedureRecovery) -> Self { + self.subprocedure_recovery = recovery; + self + } + /// Returns current [ProcedureState]. fn state(&self) -> ProcedureState { self.state_receiver.borrow().clone() @@ -724,7 +735,6 @@ impl LocalManager { origin: RootSubmissionOrigin, ) -> Result { ensure!(self.manager_ctx.running(), ManagerNotStartSnafu); - let meta = Arc::new(ProcedureMeta::new( procedure_id, procedure_state, @@ -735,6 +745,16 @@ impl LocalManager { procedure.type_name(), )); let event_recorder = self.event_recorder.0.lock().unwrap(); + // Serialize admission and registration so concurrent fresh submissions cannot + // exceed the limit. Recovery resumes already accepted work and bypasses it. + if matches!(origin, RootSubmissionOrigin::Fresh) { + ensure!( + self.manager_ctx.num_running_procedures() < self.config.max_running_procedures, + TooManyRunningProceduresSnafu { + max_running_procedures: self.config.max_running_procedures, + } + ); + } let runner = Runner { meta: meta.clone(), procedure, @@ -750,21 +770,13 @@ impl LocalManager { rollback_retry_attempt: 0, }; - let watcher = meta.state_receiver.clone(); - - ensure!( - self.manager_ctx.num_running_procedures() < self.config.max_running_procedures, - TooManyRunningProceduresSnafu { - max_running_procedures: self.config.max_running_procedures, - } - ); - // Inserts meta into the manager before actually spawnd the runner. ensure!( self.manager_ctx.try_insert_procedure(meta), DuplicateProcedureSnafu { procedure_id }, ); + let watcher = runner.meta.state_receiver.clone(); let initial_event = runner.build_event(origin.event_trigger()); let tracing_context = TracingContext::from_current_span(); @@ -773,7 +785,7 @@ impl LocalManager { self.manager_ctx.spawn_runner_task(procedure_id, || { common_runtime::spawn_global(async move { let span = tracing_context.attach(tracing::info_span!( - "LocalManager::submit_root_procedure", + "LocalManager::submit_root_procedure", procedure_name = %runner.meta.type_name, procedure_id = %runner.meta.id, )); @@ -798,60 +810,6 @@ impl LocalManager { Ok(watcher) } - fn submit_recovered_messages( - &self, - messages: HashMap, - init_state: InitProcedureState, - ) { - for (procedure_id, message) in &messages { - if message.parent_id.is_none() { - // This is the root procedure. We only submit the root procedure as it will - // submit sub-procedures to the manager. - let Some(mut loaded_procedure) = self - .manager_ctx - .load_one_procedure_from_message(*procedure_id, message) - else { - // Try to load other procedures. - continue; - }; - - info!( - "Recover root procedure {}-{}, step: {}", - loaded_procedure.procedure.type_name(), - procedure_id, - loaded_procedure.step - ); - - let procedure_state = match init_state { - InitProcedureState::RollingBack => ProcedureState::RollingBack { - error: Arc::new( - error::RollbackProcedureRecoveredSnafu { - error: message.error.clone().unwrap_or("Unknown error".to_string()), - } - .build(), - ), - }, - InitProcedureState::Running => ProcedureState::Running, - }; - - if let Err(e) = loaded_procedure.procedure.recover() { - error!(e; "Failed to recover procedure {}", procedure_id); - } - - if let Err(e) = self.submit_root( - *procedure_id, - procedure_state, - loaded_procedure.step, - loaded_procedure.procedure, - message.context.clone(), - RootSubmissionOrigin::Recovery, - ) { - error!(e; "Failed to recover procedure {}", procedure_id); - } - } - } - } - /// Recovers unfinished procedures and reruns them. async fn recover(&self) -> Result<()> { info!("LocalManager start to recover"); @@ -862,9 +820,13 @@ impl LocalManager { rollback_messages, finished_ids, } = self.procedure_store.load_messages().await?; - // Submits recovered messages first. - self.submit_recovered_messages(rollback_messages, InitProcedureState::RollingBack); - self.submit_recovered_messages(messages, InitProcedureState::Running); + let rollback_messages = rollback_messages + .into_iter() + .map(|(id, message)| (id, message, InitProcedureState::RollingBack)); + let messages = messages + .into_iter() + .map(|(id, message)| (id, message, InitProcedureState::Running)); + self.submit_recovered_messages(rollback_messages.chain(messages)); if !finished_ids.is_empty() { info!( @@ -2352,6 +2314,79 @@ mod tests { ); } + #[tokio::test] + async fn test_concurrent_root_submission_respects_limit() { + struct ConcurrentProcedure(Arc); + + #[async_trait::async_trait] + impl Procedure for ConcurrentProcedure { + fn type_name(&self) -> &str { + "ConcurrentProcedure" + } + + async fn execute(&mut self, _ctx: &Context) -> Result { + std::future::pending().await + } + + fn dump(&self) -> Result { + Ok(String::new()) + } + + fn lock_key(&self) -> LockKey { + // Both submissions reach metadata construction before either registers. + self.0.wait(); + LockKey::default() + } + } + + let dir = create_temp_dir("concurrent_root_submission"); + let state_store = Arc::new(ObjectStateStore::new(test_util::new_object_store(&dir))); + let manager = LocalManager::new( + ManagerConfig { + max_running_procedures: 1, + ..Default::default() + }, + state_store, + Arc::new(InMemoryPoisonStore::new()), + None, + None, + ); + manager.manager_ctx.start(); + let barrier = Arc::new(std::sync::Barrier::new(2)); + let results = std::thread::scope(|scope| { + let handles: Vec<_> = (0..2) + .map(|_| { + let barrier = barrier.clone(); + let manager = &manager; + scope.spawn(move || { + manager.submit_root( + ProcedureId::random(), + ProcedureState::Running, + 0, + Box::new(ConcurrentProcedure(barrier)), + ProcedureContext::default(), + RootSubmissionOrigin::Fresh, + ) + }) + }) + .collect(); + handles + .into_iter() + .map(|h| h.join().unwrap()) + .collect::>() + }); + manager.stop().await.unwrap(); + + assert_eq!(1, results.iter().filter(|result| result.is_ok()).count()); + assert_eq!( + 1, + results + .iter() + .filter(|result| matches!(result, Err(Error::TooManyRunningProcedures { .. }))) + .count() + ); + } + #[tokio::test] async fn test_too_many_running_procedures() { let dir = create_temp_dir("too_many_running_procedures"); diff --git a/src/common/procedure/src/local/recovery.rs b/src/common/procedure/src/local/recovery.rs new file mode 100644 index 00000000000..10de0890d12 --- /dev/null +++ b/src/common/procedure/src/local/recovery.rs @@ -0,0 +1,582 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; + +use common_telemetry::{error, info}; + +use crate::error; +use crate::local::{LocalManager, RootSubmissionOrigin}; +use crate::procedure::InitProcedureState; +use crate::store::ProcedureMessage; +use crate::{ProcedureId, ProcedureState, ProcedureWithId}; + +/// A loaded procedure ready to resume from its checkpoint. +struct RecoveredProcedure { + procedure: ProcedureWithId, + state: ProcedureState, + step: u32, +} + +impl LocalManager { + /// Loads all eligible procedures before starting any recovered runner. + pub(crate) fn submit_recovered_messages( + &self, + messages: impl IntoIterator, + ) { + // Load both rollback and execution checkpoints before spawning. Loaders + // rebuild trackers that parents consult before submitting new work. + let procedures: Vec<_> = messages + .into_iter() + .filter_map(|(id, message, state)| self.load_recovered_procedure(id, message, state)) + .collect(); + + for RecoveredProcedure { + procedure, + state, + step, + } in procedures + { + let procedure_id = procedure.id; + // Detached children use the existing root lifecycle and cleanup. + if let Err(e) = self.submit_root( + procedure_id, + state, + step, + procedure.procedure, + procedure.context, + RootSubmissionOrigin::Recovery, + ) { + error!(e; "Failed to recover procedure {}", procedure_id); + } + } + } + + fn load_recovered_procedure( + &self, + procedure_id: ProcedureId, + message: ProcedureMessage, + init_state: InitProcedureState, + ) -> Option { + if message.parent_id.is_some() && message.subprocedure_recovery.is_discard() { + return None; + } + // The loader logs failures; skip them without adding a duplicate error. + let mut loaded = self + .manager_ctx + .load_one_procedure_from_message(procedure_id, &message)?; + match message.parent_id { + Some(parent_id) => info!( + "Recover detached subprocedure {}-{}, former parent: {}, step: {}", + loaded.procedure.type_name(), + procedure_id, + parent_id, + loaded.step + ), + None => info!( + "Recover root procedure {}-{}, step: {}", + loaded.procedure.type_name(), + procedure_id, + loaded.step + ), + } + let state = match init_state { + InitProcedureState::Running => ProcedureState::Running, + InitProcedureState::RollingBack => ProcedureState::RollingBack { + error: Arc::new( + error::RollbackProcedureRecoveredSnafu { + error: message.error.unwrap_or_else(|| "Unknown error".to_string()), + } + .build(), + ), + }, + }; + if let Err(e) = loaded.procedure.recover() { + error!(e; "Failed to recover procedure {}", procedure_id); + } + Some(RecoveredProcedure { + procedure: ProcedureWithId { + id: procedure_id, + procedure: loaded.procedure, + context: message.context, + }, + state, + step: loaded.step, + }) + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + + use async_trait::async_trait; + use common_test_util::temp_dir::create_temp_dir; + use tokio::sync::Notify; + use tokio::time::timeout; + + use super::*; + use crate::error::Result; + use crate::local::{ManagerConfig, test_util}; + use crate::store::state_store::ObjectStateStore; + use crate::test_util::InMemoryPoisonStore; + use crate::{ + Context, LockKey, Procedure, ProcedureContext, ProcedureManager, Status, + SubprocedureRecovery, + }; + + struct MockParentProcedure { + child: Option, + recovery: SubprocedureRecovery, + } + + #[async_trait] + impl Procedure for MockParentProcedure { + fn type_name(&self) -> &str { + "MockParentProcedure" + } + + async fn execute(&mut self, _: &Context) -> Result { + let Some(child) = self.child.take() else { + return Ok(Status::done()); + }; + Ok(match self.recovery { + SubprocedureRecovery::Discard => Status::suspended(vec![child], false), + SubprocedureRecovery::Detach => Status::Suspended { + subprocedures: vec![child], + persist: false, + recovery: SubprocedureRecovery::Detach, + }, + }) + } + + fn dump(&self) -> Result { + unreachable!("The fixture deliberately does not checkpoint the parent") + } + + fn lock_key(&self) -> LockKey { + LockKey::default() + } + } + + #[derive(Clone)] + struct MockChildProcedure { + checkpointed: bool, + init_state: InitProcedureState, + entered: Arc, + release: Arc, + recoveries: Arc, + rollbacks: Arc, + } + + #[async_trait] + impl Procedure for MockChildProcedure { + fn type_name(&self) -> &str { + "MockChildProcedure" + } + + async fn execute(&mut self, _: &Context) -> Result { + if matches!(self.init_state, InitProcedureState::RollingBack) { + return error::UnexpectedSnafu { + err_msg: "Child needs rollback", + } + .fail(); + } + if !self.checkpointed { + self.checkpointed = true; + return Ok(Status::executing(true)); + } + self.entered.notify_one(); + self.release.notified().await; + Ok(Status::done()) + } + + fn recover(&mut self) -> Result<()> { + self.recoveries.fetch_add(1, Ordering::Relaxed); + // The next execution checkpoint must persist the detached root identity. + self.checkpointed = false; + Ok(()) + } + + fn dump(&self) -> Result { + Ok(self.checkpointed.to_string()) + } + + fn lock_key(&self) -> LockKey { + LockKey::default() + } + + fn rollback_supported(&self) -> bool { + true + } + + async fn rollback(&mut self, _: &Context) -> Result<()> { + self.rollbacks.fetch_add(1, Ordering::Relaxed); + self.entered.notify_one(); + self.release.notified().await; + Ok(()) + } + } + + #[tokio::test] + async fn test_detach_child_after_restart() { + check_child_recovery(SubprocedureRecovery::Detach, InitProcedureState::Running).await; + } + + #[tokio::test] + async fn test_detach_rollback_child_after_restart() { + check_child_recovery( + SubprocedureRecovery::Detach, + InitProcedureState::RollingBack, + ) + .await; + } + + #[tokio::test] + async fn test_discard_child_after_restart() { + check_child_recovery(SubprocedureRecovery::Discard, InitProcedureState::Running).await; + } + + #[tokio::test] + async fn test_discard_rollback_child_after_restart() { + check_child_recovery( + SubprocedureRecovery::Discard, + InitProcedureState::RollingBack, + ) + .await; + } + + #[tokio::test] + async fn test_load_all_procedures_before_spawning() { + // Cover both checkpoint kinds and both cross-kind parent/child orderings. + for (parent_rollback, child_rollback) in + [(false, false), (false, true), (true, false), (true, true)] + { + let dir = create_temp_dir("load-before-spawn"); + let manager = LocalManager::new( + ManagerConfig::default(), + Arc::new(ObjectStateStore::new(test_util::new_object_store(&dir))), + Arc::new(InMemoryPoisonStore::new()), + None, + None, + ); + let manager_ctx = manager.manager_ctx.clone(); + let loads = Arc::new(AtomicUsize::new(0)); + let recoveries = Arc::new(AtomicUsize::new(0)); + let loaded_count = loads.clone(); + let recovered_count = recoveries.clone(); + manager + .register_loader( + "MockChildProcedure", + Box::new(move |data| { + // A loader must never observe an already spawned parent. + // This check is deterministic even if its runner has not run yet. + assert!(manager_ctx.runner_tasks.lock().unwrap().is_empty()); + loaded_count.fetch_add(1, Ordering::Relaxed); + Ok(Box::new(MockChildProcedure { + checkpointed: data.parse().unwrap(), + init_state: InitProcedureState::Running, + entered: Arc::new(Notify::new()), + release: Arc::new(Notify::new()), + recoveries: recovered_count.clone(), + rollbacks: Arc::new(AtomicUsize::new(0)), + })) + }), + ) + .unwrap(); + let parent_id = ProcedureId::random(); + let child_id = ProcedureId::random(); + for (id, parent, rollback) in [ + (parent_id, None, parent_rollback), + (child_id, Some(parent_id), child_rollback), + ] { + let message = ProcedureMessage { + type_name: "MockChildProcedure".to_string(), + data: "true".to_string(), + parent_id: parent, + subprocedure_recovery: SubprocedureRecovery::Detach, + step: 7, + error: rollback.then(|| "Needs rollback".to_string()), + context: ProcedureContext::default(), + }; + if rollback { + manager + .procedure_store + .rollback_procedure(id, message) + .await + .unwrap(); + } else { + manager + .procedure_store + .store_procedure_message(id, &message) + .await + .unwrap(); + } + } + + manager.start().await.unwrap(); + assert_eq!(loads.load(Ordering::Relaxed), 2); + assert_eq!(recoveries.load(Ordering::Relaxed), 2); + assert_eq!(manager.manager_ctx.runner_tasks.lock().unwrap().len(), 2); + manager.stop().await.unwrap(); + } + } + + #[tokio::test] + async fn test_recover_roots_and_detached_children_over_limit() { + let dir = create_temp_dir("detached-recovery-limit"); + let manager = LocalManager::new( + ManagerConfig { + max_running_procedures: 1, + ..Default::default() + }, + Arc::new(ObjectStateStore::new(test_util::new_object_store(&dir))), + Arc::new(InMemoryPoisonStore::new()), + None, + None, + ); + manager + .register_loader( + "MockChildProcedure", + Box::new(|data| { + Ok(Box::new(MockChildProcedure { + checkpointed: data.parse().unwrap(), + init_state: InitProcedureState::Running, + entered: Arc::new(Notify::new()), + release: Arc::new(Notify::new()), + recoveries: Arc::new(AtomicUsize::new(0)), + rollbacks: Arc::new(AtomicUsize::new(0)), + })) + }), + ) + .unwrap(); + let root_id = ProcedureId::random(); + let child_ids = [ProcedureId::random(), ProcedureId::random()]; + let root = ProcedureMessage { + type_name: "MockChildProcedure".to_string(), + data: "true".to_string(), + parent_id: None, + subprocedure_recovery: SubprocedureRecovery::Discard, + step: 7, + error: None, + context: ProcedureContext::default(), + }; + manager + .procedure_store + .store_procedure_message(root_id, &root) + .await + .unwrap(); + for child_id in child_ids { + let child = ProcedureMessage { + parent_id: Some(root_id), + subprocedure_recovery: SubprocedureRecovery::Detach, + ..root.clone() + }; + manager + .procedure_store + .store_procedure_message(child_id, &child) + .await + .unwrap(); + } + + manager.start().await.unwrap(); + { + let procedures = manager.manager_ctx.procedures.read().unwrap(); + assert_eq!(procedures.len(), 3); + for id in [root_id, child_ids[0], child_ids[1]] { + let meta = &procedures[&id]; + assert_eq!(meta.parent_id, None); + assert_eq!(meta.num_children(), 0); + } + } + // Wait for detached children to checkpoint as roots, then verify that + // recovery retained their nonzero step rather than restarting from zero. + timeout(Duration::from_secs(5), async { + loop { + let stored = manager.procedure_store.load_messages().await.unwrap(); + if child_ids.iter().all(|id| { + stored + .messages + .get(id) + .is_some_and(|message| message.parent_id.is_none()) + }) { + for child_id in child_ids { + assert_eq!(stored.messages[&child_id].step, 7); + } + break; + } + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + manager.stop().await.unwrap(); + } + + async fn check_child_recovery(policy: SubprocedureRecovery, init_state: InitProcedureState) { + let dir = create_temp_dir("child-recovery"); + let state_store = Arc::new(ObjectStateStore::new(test_util::new_object_store(&dir))); + let manager = LocalManager::new( + ManagerConfig { + max_running_procedures: 1, + ..Default::default() + }, + state_store, + Arc::new(InMemoryPoisonStore::new()), + None, + None, + ); + let child_id = ProcedureId::random(); + let entered = Arc::new(Notify::new()); + let release = Arc::new(Notify::new()); + let recoveries = Arc::new(AtomicUsize::new(0)); + let rollbacks = Arc::new(AtomicUsize::new(0)); + let child = MockChildProcedure { + checkpointed: false, + init_state: init_state.clone(), + entered: entered.clone(), + release: release.clone(), + recoveries: recoveries.clone(), + rollbacks: rollbacks.clone(), + }; + let loaded_child = child.clone(); + manager + .register_loader( + "MockChildProcedure", + Box::new(move |data| { + assert_eq!( + policy, + SubprocedureRecovery::Detach, + "Discarded children must not be loaded" + ); + let mut child = loaded_child.clone(); + child.checkpointed = data.parse().unwrap(); + Ok(Box::new(child)) + }), + ) + .unwrap(); + manager.start().await.unwrap(); + let parent = ProcedureWithId::with_random_id(Box::new(MockParentProcedure { + child: Some(ProcedureWithId { + id: child_id, + procedure: Box::new(child), + context: ProcedureContext::default(), + }), + recovery: policy, + })) + .with_context(ProcedureContext { + actor: Some("alice".to_string()), + ..Default::default() + }); + let parent_id = parent.id; + manager.submit(parent).await.unwrap(); + timeout(Duration::from_secs(5), entered.notified()) + .await + .unwrap(); + + // The first child checkpoint carries the submission policy, even though + // Status::Suspended.persist was false and the parent has no checkpoint. + let stored = manager.procedure_store.load_messages().await.unwrap(); + let checkpoint = match init_state { + InitProcedureState::Running => &stored.messages[&child_id], + InitProcedureState::RollingBack => &stored.rollback_messages[&child_id], + } + .clone(); + assert_eq!(checkpoint.parent_id, Some(parent_id)); + assert_eq!(checkpoint.subprocedure_recovery, policy); + assert_eq!(checkpoint.context.actor.as_deref(), Some("alice")); + assert_eq!(checkpoint.step, 0); + if matches!(init_state, InitProcedureState::RollingBack) { + assert!(!stored.messages.contains_key(&child_id)); + assert_eq!(checkpoint.data, "false"); + } + assert!(!stored.messages.contains_key(&parent_id)); + manager.stop().await.unwrap(); + manager.start().await.unwrap(); + + if policy == SubprocedureRecovery::Discard { + assert!(manager.procedure_state(child_id).await.unwrap().is_none()); + assert_eq!(recoveries.load(Ordering::Relaxed), 0); + let stored = manager.procedure_store.load_messages().await.unwrap(); + let retained = match init_state { + InitProcedureState::Running => &stored.messages[&child_id], + InitProcedureState::RollingBack => &stored.rollback_messages[&child_id], + }; + assert_eq!(retained, &checkpoint); + manager.stop().await.unwrap(); + return; + } + + // The original parent is absent. The child owns its cleanup as a root, + // and remains recoverable across a second restart. + for restart in 1..=2 { + timeout(Duration::from_secs(5), entered.notified()) + .await + .unwrap(); + assert!(manager.procedure_state(parent_id).await.unwrap().is_none()); + let meta = manager.manager_ctx.procedures.read().unwrap()[&child_id].clone(); + assert_eq!(meta.parent_id, None); + assert_eq!(meta.context, checkpoint.context); + assert_eq!(recoveries.load(Ordering::Relaxed), restart); + let stored = manager.procedure_store.load_messages().await.unwrap(); + match init_state { + InitProcedureState::Running => { + let recovered = &stored.messages[&child_id]; + assert_eq!(recovered.parent_id, None); + assert_eq!(recovered.step, checkpoint.step); + assert_eq!(recovered.context, checkpoint.context); + } + InitProcedureState::RollingBack => { + assert!(meta.state().is_rolling_back()); + assert_eq!(stored.rollback_messages[&child_id], checkpoint); + } + } + if restart == 1 { + manager.stop().await.unwrap(); + manager.start().await.unwrap(); + } + } + release.notify_one(); + timeout(Duration::from_secs(5), async { + while manager + .manager_ctx + .runner_tasks + .lock() + .unwrap() + .contains_key(&child_id) + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let stored = manager.procedure_store.load_messages().await.unwrap(); + assert!(stored.messages.is_empty()); + assert!(stored.rollback_messages.is_empty()); + assert!(stored.finished_ids.is_empty()); + let state = manager.procedure_state(child_id).await.unwrap().unwrap(); + match init_state { + InitProcedureState::Running => { + assert!(state.is_done()); + assert_eq!(rollbacks.load(Ordering::Relaxed), 0); + } + InitProcedureState::RollingBack => { + assert!(state.is_failed()); + assert_eq!(rollbacks.load(Ordering::Relaxed), 3); + } + } + manager.stop().await.unwrap(); + } +} diff --git a/src/common/procedure/src/local/runner.rs b/src/common/procedure/src/local/runner.rs index 30b775dbd7d..082ff7e10b7 100644 --- a/src/common/procedure/src/local/runner.rs +++ b/src/common/procedure/src/local/runner.rs @@ -35,7 +35,7 @@ use crate::rwlock::OwnedKeyRwLockGuard; use crate::store::{ProcedureMessage, ProcedureStore}; use crate::{ BoxedProcedure, ChildSubmissionOutcome, Context, Error, EventContext, EventTrigger, Procedure, - ProcedureId, ProcedureState, ProcedureWithId, RetryPhase, Status, + ProcedureId, ProcedureState, ProcedureWithId, RetryPhase, Status, SubprocedureRecovery, }; /// A guard to cleanup procedure state. @@ -390,7 +390,11 @@ impl Runner { self.meta.set_state(ProcedureState::Running); } } - Status::Suspended { subprocedures, .. } => { + Status::Suspended { + subprocedures, + recovery, + .. + } => { let prev_state = self.meta.state(); if !matches!(prev_state, ProcedureState::Running) { info!( @@ -401,7 +405,7 @@ impl Runner { ); self.meta.set_state(ProcedureState::Running); } - self.on_suspended(subprocedures).await; + self.on_suspended(subprocedures, recovery).await; } Status::Done { output } => { if let Err(e) = self.commit_procedure().await { @@ -488,6 +492,7 @@ impl Runner { procedure_id: ProcedureId, procedure_state: ProcedureState, procedure: BoxedProcedure, + recovery: SubprocedureRecovery, ) -> (ChildSubmissionOutcome, Option) { if !self.running() { warn!( @@ -505,7 +510,7 @@ impl Runner { let step = 0; - let meta = Arc::new(ProcedureMeta::new( + let meta = ProcedureMeta::new( procedure_id, procedure_state, Some(self.meta.id), @@ -513,7 +518,9 @@ impl Runner { procedure.lock_key(), procedure.poison_keys(), procedure.type_name(), - )); + ) + .with_subprocedure_recovery(recovery); + let meta = Arc::new(meta); let runner = Runner { meta: meta.clone(), procedure, @@ -578,7 +585,11 @@ impl Runner { time::sleep(d).await; } - async fn on_suspended(&mut self, subprocedures: Vec) { + async fn on_suspended( + &mut self, + subprocedures: Vec, + recovery: SubprocedureRecovery, + ) { let has_child = !subprocedures.is_empty(); // Pre-check: detect potential deadlocks BEFORE submitting any subprocedure. @@ -629,6 +640,7 @@ impl Runner { subprocedure.id, ProcedureState::Running, subprocedure.procedure, + recovery, ); if let Some(event) = submitted_event && let Some(recorder) = self.event_recorder.as_ref() @@ -664,13 +676,17 @@ impl Runner { let data = self.procedure.dump()?; self.store - .store_procedure_with_context( + .store_procedure_message( self.meta.id, - self.step, - type_name, - data, - self.meta.parent_id, - self.meta.context.clone(), + &ProcedureMessage { + type_name, + data, + parent_id: self.meta.parent_id, + subprocedure_recovery: self.meta.subprocedure_recovery, + step: self.step, + error: None, + context: self.meta.context.clone(), + }, ) .await .map_err(|e| { @@ -709,6 +725,7 @@ impl Runner { type_name, data, parent_id: self.meta.parent_id, + subprocedure_recovery: self.meta.subprocedure_recovery, step: self.step, error: Some(error), context: self.meta.context.clone(), @@ -1061,6 +1078,7 @@ mod tests { let exec_fn = move |_| { async move { Ok(Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: Vec::new(), persist: false, }) @@ -1138,6 +1156,7 @@ mod tests { if times == 1 { // Submit subprocedures. Ok(Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: children_ids .into_iter() .zip(keys) @@ -1165,6 +1184,7 @@ mod tests { } else { // Return suspended to wait for notify. Ok(Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: Vec::new(), persist: false, }) @@ -1491,6 +1511,7 @@ mod tests { }; Ok(Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: vec![ProcedureWithId { id: child_id, procedure: Box::new(fail), @@ -1684,6 +1705,7 @@ mod tests { }; Ok(Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: vec![ProcedureWithId { id: child_id, procedure: Box::new(fail), @@ -1704,6 +1726,7 @@ mod tests { } else { // Return suspended to wait for notify. Ok(Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: Vec::new(), persist: false, }) @@ -2205,6 +2228,7 @@ mod tests { rollback_fn: None, }; Ok(Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: vec![ProcedureWithId { id: child_id, procedure: Box::new(child), @@ -2262,6 +2286,7 @@ mod tests { rollback_fn: None, }; Ok(Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: vec![ProcedureWithId { id: child_id, procedure: Box::new(child), diff --git a/src/common/procedure/src/procedure.rs b/src/common/procedure/src/procedure.rs index ba6a5d275cb..b43f275b8a2 100644 --- a/src/common/procedure/src/procedure.rs +++ b/src/common/procedure/src/procedure.rs @@ -56,6 +56,33 @@ impl ProcedureContext { } } +/// Controls how children submitted by [`Status::Suspended`] are handled after a restart. +/// +/// The policy is captured at submission and persisted with each child's checkpoints. +/// It does not change parent-child ownership during normal execution. A child without +/// a persisted checkpoint cannot be recovered, regardless of its policy. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SubprocedureRecovery { + /// Does not recover the child. The parent decides whether to resubmit its work. + /// This does not roll back side effects or delete the child's persisted records. + #[default] + Discard, + /// Resumes the child's persisted execution or rollback as an independent root. + /// Its original id and context are retained, but its parent link is removed. + /// Completion no longer notifies the former parent. + /// All eligible procedures are loaded and their recovery hooks are called before + /// any recovered runner starts. Runner execution is not ordered relative to the + /// former parent; callers must prevent conflicting work when the parent recovers. + Detach, +} + +impl SubprocedureRecovery { + /// Returns whether the child is excluded from recovery. + pub(crate) fn is_discard(&self) -> bool { + matches!(self, Self::Discard) + } +} + /// Procedure execution status. #[derive(Debug)] pub enum Status { @@ -69,6 +96,8 @@ pub enum Status { /// The procedure has suspended itself and is waiting for subprocedures. Suspended { subprocedures: Vec, + /// Recovery policy for every child in this submission, recorded at its first checkpoint. + recovery: SubprocedureRecovery, /// Whether the framework needs to persist the procedure. persist: bool, }, @@ -85,9 +114,11 @@ pub enum Status { impl Status { /// Returns a [Status::Suspended] with given `subprocedures` and `persist` flag. + /// Children default to [`SubprocedureRecovery::Discard`]. pub fn suspended(subprocedures: Vec, persist: bool) -> Status { Status::Suspended { subprocedures, + recovery: SubprocedureRecovery::Discard, persist, } } @@ -785,12 +816,14 @@ mod tests { assert!(status.need_clean_poisons()); let status = Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: Vec::new(), persist: false, }; assert!(!status.need_persist()); let status = Status::Suspended { + recovery: SubprocedureRecovery::Discard, subprocedures: Vec::new(), persist: true, }; diff --git a/src/common/procedure/src/store.rs b/src/common/procedure/src/store.rs index b97dab00d00..dd41c13e072 100644 --- a/src/common/procedure/src/store.rs +++ b/src/common/procedure/src/store.rs @@ -22,7 +22,7 @@ use snafu::ResultExt; use crate::error::{Result, ToJsonSnafu}; pub(crate) use crate::store::state_store::StateStoreRef; -use crate::{ProcedureContext, ProcedureId}; +use crate::{ProcedureContext, ProcedureId, SubprocedureRecovery}; pub mod poison_store; pub mod state_store; @@ -50,6 +50,9 @@ pub struct ProcedureMessage { pub data: String, /// Parent procedure id. pub parent_id: Option, + /// Recovery policy for a child submission, ignored for root procedures. + #[serde(default, skip_serializing_if = "SubprocedureRecovery::is_discard")] + pub subprocedure_recovery: SubprocedureRecovery, /// Current step. pub step: u32, /// Errors raised during the procedure. @@ -111,6 +114,7 @@ impl ProcedureStore { .await } + #[cfg(test)] pub(crate) async fn store_procedure_with_context( &self, procedure_id: ProcedureId, @@ -124,14 +128,24 @@ impl ProcedureStore { type_name, data, parent_id, + subprocedure_recovery: SubprocedureRecovery::Discard, step, error: None, context, }; + self.store_procedure_message(procedure_id, &message).await + } + + /// Persists a procedure checkpoint with its recovery policy and submission context. + pub(crate) async fn store_procedure_message( + &self, + procedure_id: ProcedureId, + message: &ProcedureMessage, + ) -> Result<()> { let key = ParsedKey { prefix: &self.proc_path, procedure_id, - step, + step: message.step, key_type: KeyType::Step, } .to_string(); @@ -486,6 +500,7 @@ mod tests { type_name: "TestMessage".to_string(), data: "no parent id".to_string(), parent_id: None, + subprocedure_recovery: SubprocedureRecovery::Discard, step: 4, error: None, context: ProcedureContext::default(), @@ -529,6 +544,20 @@ mod tests { assert_eq!(legacy.context, ProcedureContext::default()); } + #[test] + fn test_subprocedure_recovery_serialization() { + let legacy = r#"{"type_name":"TestMessage","data":"checkpoint","parent_id":null,"step":4}"#; + let mut message: ProcedureMessage = serde_json::from_str(legacy).unwrap(); + assert_eq!(message.subprocedure_recovery, SubprocedureRecovery::Discard); + assert_eq!(serde_json::to_string(&message).unwrap(), legacy); + message.subprocedure_recovery = SubprocedureRecovery::Detach; + let json = serde_json::to_string(&message).unwrap(); + assert_eq!( + serde_json::from_str::(&json).unwrap(), + message + ); + } + struct MockProcedure { data: String, } @@ -589,6 +618,7 @@ mod tests { type_name: "MockProcedure".to_string(), data: "test store procedure".to_string(), parent_id: None, + subprocedure_recovery: SubprocedureRecovery::Discard, step: 0, error: None, context: ProcedureContext::default(), @@ -638,6 +668,7 @@ mod tests { type_name, data, parent_id: None, + subprocedure_recovery: SubprocedureRecovery::Discard, step: 1, error: None, context: ProcedureContext::default(), From bd77b599cc25caf7980d3a1627cdd7727c888778 Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 28 Oct 2026 07:27:04 +0000 Subject: [PATCH 04/19] refactor(flow): remove tracked-write protocol (#9992) Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- Cargo.lock | 1 - licenserc-enterprise.toml | 5 - licenserc.toml | 5 - src/common/grpc/Cargo.toml | 4 - src/common/grpc/src/flow_write.rs | 477 --------- src/common/grpc/src/lib.rs | 2 - src/datanode/Cargo.toml | 2 +- src/datanode/src/region_server.rs | 19 - src/datanode/src/region_server/flow_write.rs | 969 ------------------ src/flow/Cargo.toml | 2 +- src/flow/src/batching_mode/frontend_client.rs | 98 -- .../frontend_client/flow_write.rs | 758 -------------- src/frontend/Cargo.toml | 2 - src/frontend/src/instance.rs | 31 - src/frontend/src/instance/builder.rs | 2 - src/frontend/src/instance/flow_write.rs | 227 ---- src/frontend/src/instance/grpc.rs | 14 - src/operator/Cargo.toml | 1 - src/operator/src/insert.rs | 43 - src/operator/src/insert/flow_write.rs | 391 ------- src/session/Cargo.toml | 3 - src/session/src/context.rs | 5 - 22 files changed, 2 insertions(+), 3059 deletions(-) delete mode 100644 src/common/grpc/src/flow_write.rs delete mode 100644 src/datanode/src/region_server/flow_write.rs delete mode 100644 src/flow/src/batching_mode/frontend_client/flow_write.rs delete mode 100644 src/frontend/src/instance/flow_write.rs delete mode 100644 src/operator/src/insert/flow_write.rs diff --git a/Cargo.lock b/Cargo.lock index 639a771816a..6ada3b0a295 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2588,7 +2588,6 @@ dependencies = [ "tokio-util", "tonic 0.14.2", "tower 0.5.2", - "uuid", "vec1", ] diff --git a/licenserc-enterprise.toml b/licenserc-enterprise.toml index 805358f1f1e..d11d344b64d 100644 --- a/licenserc-enterprise.toml +++ b/licenserc-enterprise.toml @@ -15,11 +15,6 @@ headerPath = "licenses/enterprise-header.txt" # with the "# enterprise" block in `licenserc.toml`'s `excludes` — both are # enforced by `make check-enterprise-license`. includes = [ - "src/common/grpc/src/flow_write.rs", - "src/frontend/src/instance/flow_write.rs", - "src/datanode/src/region_server/flow_write.rs", - "src/operator/src/insert/flow_write.rs", - "src/flow/src/batching_mode/frontend_client/flow_write.rs", "src/common/meta/src/rpc/ddl/trigger.rs", "src/operator/src/expr_helper/trigger.rs", "src/sql/src/statements/alter/trigger.rs", diff --git a/licenserc.toml b/licenserc.toml index e84d3a1f8ff..42e6464017c 100644 --- a/licenserc.toml +++ b/licenserc.toml @@ -31,11 +31,6 @@ excludes = [ # Keep this list in sync with that file's `includes`; enforced by # `make check-enterprise-license`. # enterprise:start - "src/common/grpc/src/flow_write.rs", - "src/frontend/src/instance/flow_write.rs", - "src/datanode/src/region_server/flow_write.rs", - "src/operator/src/insert/flow_write.rs", - "src/flow/src/batching_mode/frontend_client/flow_write.rs", "src/common/meta/src/rpc/ddl/trigger.rs", "src/operator/src/expr_helper/trigger.rs", "src/sql/src/statements/alter/trigger.rs", diff --git a/src/common/grpc/Cargo.toml b/src/common/grpc/Cargo.toml index fbfab1b6318..58bd04db093 100644 --- a/src/common/grpc/Cargo.toml +++ b/src/common/grpc/Cargo.toml @@ -7,9 +7,6 @@ license.workspace = true [lints] workspace = true -[features] -enterprise = [] - [dependencies] api.workspace = true arrow-flight.workspace = true @@ -35,7 +32,6 @@ tokio.workspace = true tokio-util.workspace = true tonic.workspace = true tower.workspace = true -uuid.workspace = true vec1 = "1.12" [dev-dependencies] diff --git a/src/common/grpc/src/flow_write.rs b/src/common/grpc/src/flow_write.rs deleted file mode 100644 index 6d085a500bd..00000000000 --- a/src/common/grpc/src/flow_write.rs +++ /dev/null @@ -1,477 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -use std::collections::HashMap; -use std::sync::{Arc, Mutex}; - -use common_error::ext::{ErrorExt, StackError}; -use common_error::status_code::StatusCode; - -use common_recordbatch::{RecordBatch, RecordBatches}; -use datatypes::arrow::array::{Array, StringArray}; -use datatypes::prelude::{ConcreteDataType, VectorRef}; -use datatypes::schema::{ColumnSchema, Schema}; -use datatypes::vectors::StringVector; -use serde::{Deserialize, Serialize}; -use tokio::sync::watch; -use uuid::Uuid; - -pub const COMMAND_KEY: &str = "flow_write_command"; -pub const CHILD_KEY: &str = "flow_write_child"; - -/// The control command carried by a Flow write request. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub enum Command { - Open { nonce: String }, - Write { capability: String }, - Close { capability: String }, -} - -impl Command { - /// Serializes this command as JSON. - pub fn encode(&self) -> serde_json::Result { - serde_json::to_string(self) - } - - /// Parses a serialized command. - pub fn decode(value: &str) -> serde_json::Result { - serde_json::from_str(value) - } -} - -/// A safe terminal application error. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct TerminalError { - pub code: u32, - pub message: String, -} - -impl std::fmt::Display for TerminalError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.message) - } -} - -impl std::error::Error for TerminalError {} - -impl StackError for TerminalError { - fn debug_fmt(&self, layer: usize, buf: &mut Vec) { - buf.push(format!("{layer}: {self:?}")); - } - - fn next(&self) -> Option<&dyn StackError> { - None - } -} - -impl ErrorExt for TerminalError { - fn status_code(&self) -> StatusCode { - StatusCode::from_u32(self.code).unwrap_or(StatusCode::Internal) - } - - fn as_any(&self) -> &dyn std::any::Any { - self - } -} - -/// A finite response for a tracked Flow write. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub enum Reply { - Opened { - capability: String, - }, - Closed, - Complete { - rows: usize, - cost: usize, - metrics: Option, - error: Option, - }, -} - -fn envelope_schema() -> Arc { - Arc::new(Schema::new(vec![ColumnSchema::new( - "envelope", - ConcreteDataType::string_datatype(), - false, - )])) -} - -fn response_error(reason: impl Into) -> common_recordbatch::error::Error { - common_recordbatch::error::Error::CreateRecordBatches { - reason: reason.into(), - location: snafu::Location::new(file!(), line!(), column!()), - } -} - -/// Encodes a reply in the finite one-string-column record-batch envelope. -pub fn reply_batches(reply: &Reply) -> common_recordbatch::error::Result { - let value = serde_json::to_string(reply).map_err(|e| response_error(e.to_string()))?; - let batch = RecordBatch::new( - envelope_schema(), - vec![Arc::new(StringVector::from(vec![value])) as VectorRef], - )?; - RecordBatches::try_new(batch.schema.clone(), vec![batch]) -} - -/// Decodes a reply from its finite one-string-column record-batch envelope. -pub fn decode_reply(batches: &RecordBatches) -> common_recordbatch::error::Result { - let batch = batches - .iter() - .next() - .ok_or_else(|| response_error("missing reply batch"))?; - if batches.iter().count() != 1 || batch.num_columns() != 1 || batch.num_rows() != 1 { - return Err(response_error("reply must be exactly one string value")); - } - let values = batch.columns()[0] - .as_any() - .downcast_ref::() - .ok_or_else(|| response_error("reply value is not a string"))?; - if values.is_null(0) { - return Err(response_error("reply value is null")); - } - let value = values.value(0); - serde_json::from_str(value).map_err(|e| response_error(e.to_string())) -} - -/// Errors that reject admission or indicate that an admitted writer was lost. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum RegistryError { - UnknownCapability, - Closing, - WriterLost, - PayloadMismatch, -} - -impl std::fmt::Display for RegistryError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{self:?}") - } -} - -impl std::error::Error for RegistryError {} - -impl StackError for RegistryError { - fn debug_fmt(&self, layer: usize, buf: &mut Vec) { - buf.push(format!("{layer}: {self:?}")); - } - - fn next(&self) -> Option<&dyn StackError> { - None - } -} - -impl ErrorExt for RegistryError { - fn status_code(&self) -> StatusCode { - StatusCode::InvalidArguments - } - - fn as_any(&self) -> &dyn std::any::Any { - self - } -} - -/// Result of atomically admitting or joining a payload. -#[derive(Debug)] -pub enum Admission { - Start(watch::Sender>>), - Join(watch::Receiver>>), -} - -#[derive(Debug)] -struct Entry { - payload: Option

, - sender: Option>>>, - receiver: watch::Receiver>>, - closing: bool, -} - -#[derive(Debug)] -struct State { - openers: HashMap, - entries: HashMap>, -} - -/// Receiver-issued capabilities for single-write admission and completion sharing. -#[derive(Debug)] -pub struct FlowWriteRegistry { - state: Mutex>, -} - -impl Default for FlowWriteRegistry { - fn default() -> Self { - Self { - state: Mutex::new(State { - openers: HashMap::new(), - entries: HashMap::new(), - }), - } - } -} - -impl FlowWriteRegistry { - /// Returns the active capability for this opener nonce, creating one if needed. - pub fn open(&self, nonce: &str) -> Result { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some(capability) = state.openers.get(nonce) { - if state - .entries - .get(capability) - .is_some_and(|entry| entry.closing) - { - return Err(RegistryError::Closing); - } - return Ok(capability.clone()); - } - let capability = Uuid::new_v4().to_string(); - let (sender, receiver) = watch::channel(None); - state.openers.insert(nonce.to_string(), capability.clone()); - state.entries.insert( - capability.clone(), - Entry { - payload: None, - sender: Some(sender), - receiver, - closing: false, - }, - ); - Ok(capability) - } - - /// Atomically starts one payload or joins its identical in-flight completion. - pub fn admit(&self, capability: &str, payload: P) -> Result, RegistryError> { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let entry = state - .entries - .get_mut(capability) - .ok_or(RegistryError::UnknownCapability)?; - if entry.closing { - return Err(RegistryError::Closing); - } - match &entry.payload { - Some(existing) if existing != &payload => Err(RegistryError::PayloadMismatch), - Some(_) => Ok(Admission::Join(entry.receiver.clone())), - None => { - entry.payload = Some(payload); - let sender = entry.sender.take().ok_or(RegistryError::Closing)?; - Ok(Admission::Start(sender)) - } - } - } - - /// Closes admission, drains an admitted writer, then deletes the capability. - pub async fn close(&self, capability: &str) -> Result<(), RegistryError> { - let receiver = { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let Some(entry) = state.entries.get_mut(capability) else { - return Ok(()); - }; - entry.closing = true; - if entry.payload.is_none() { - state.entries.remove(capability); - state.openers.retain(|_, value| value != capability); - return Ok(()); - } - entry.receiver.clone() - }; - wait_completion(receiver).await?; - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - state.entries.remove(capability); - state.openers.retain(|_, value| value != capability); - Ok(()) - } -} - -/// Waits for an admitted writer's positive terminal completion. -pub async fn wait_completion( - mut receiver: watch::Receiver>>, -) -> Result, RegistryError> { - loop { - if let Some(value) = receiver.borrow().clone() { - return Ok(value); - } - if receiver.changed().await.is_err() { - return Err(RegistryError::WriterLost); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Barrier; - use std::thread; - - #[tokio::test] - async fn concurrent_admission_has_one_owner_and_same_payload_joins() { - let registry = Arc::new(FlowWriteRegistry::::default()); - let cap = registry.open("nonce").unwrap(); - let barrier = Arc::new(Barrier::new(8)); - let mut workers = Vec::new(); - for _ in 0..8 { - let registry = registry.clone(); - let cap = cap.clone(); - let barrier = barrier.clone(); - workers.push(thread::spawn(move || { - barrier.wait(); - registry.admit(&cap, "payload".into()).unwrap() - })); - } - let admissions: Vec<_> = workers.into_iter().map(|w| w.join().unwrap()).collect(); - assert_eq!( - admissions - .iter() - .filter(|a| matches!(a, Admission::Start(_))) - .count(), - 1 - ); - let sender = admissions - .into_iter() - .find_map(|a| match a { - Admission::Start(s) => Some(s), - _ => None, - }) - .unwrap(); - sender.send(Some(Arc::new(7))).unwrap(); - registry.close(&cap).await.unwrap(); - } - - #[tokio::test] - async fn close_drains_active_writer_and_deletes_old_capability() { - let registry = Arc::new(FlowWriteRegistry::::default()); - let cap = registry.open("first").unwrap(); - let Admission::Start(sender) = registry.admit(&cap, "payload".into()).unwrap() else { - panic!() - }; - let close_registry = registry.clone(); - let close_cap = cap.clone(); - let close = tokio::spawn(async move { close_registry.close(&close_cap).await }); - tokio::task::yield_now().await; - assert!(matches!( - registry.admit(&cap, "payload".into()), - Err(RegistryError::Closing) - )); - assert!(!close.is_finished()); - sender.send(Some(Arc::new(9))).unwrap(); - close.await.unwrap().unwrap(); - assert!(matches!( - registry.admit(&cap, "payload".into()), - Err(RegistryError::UnknownCapability) - )); - registry.close(&cap).await.unwrap(); - let new_cap = registry.open("first").unwrap(); - assert_ne!(cap, new_cap); - assert!(matches!( - registry.admit(&cap, "late".into()), - Err(RegistryError::UnknownCapability) - )); - assert!(matches!( - registry.admit(&new_cap, "new".into()).unwrap(), - Admission::Start(_) - )); - } - - #[tokio::test] - async fn writer_loss_is_not_completion() { - let registry = FlowWriteRegistry::::default(); - let cap = registry.open("nonce").unwrap(); - let Admission::Start(sender) = registry.admit(&cap, "payload".into()).unwrap() else { - panic!() - }; - let Admission::Join(receiver) = registry.admit(&cap, "payload".into()).unwrap() else { - panic!() - }; - drop(sender); - assert_eq!( - wait_completion(receiver).await.unwrap_err(), - RegistryError::WriterLost - ); - assert_eq!( - registry.close(&cap).await.unwrap_err(), - RegistryError::WriterLost - ); - } - - #[test] - fn command_and_reply_envelope_round_trip_and_malformed_envelopes() { - let command = Command::Open { nonce: "n".into() }; - assert_eq!( - Command::decode(&command.encode().unwrap()).unwrap(), - command - ); - let reply = Reply::Complete { - rows: 2, - cost: 3, - metrics: Some(common_recordbatch::adapter::RecordBatchMetrics::default()), - error: Some(TerminalError { - code: 4, - message: "terminal".into(), - }), - }; - let batches = reply_batches(&reply).unwrap(); - let decoded = decode_reply(&batches).unwrap(); - assert!(matches!( - decoded, - Reply::Complete { - rows: 2, - cost: 3, - error: Some(_), - .. - } - )); - - let schema = envelope_schema(); - let two_rows = RecordBatch::new( - schema.clone(), - vec![Arc::new(StringVector::from(vec!["a", "b"])) as VectorRef], - ) - .unwrap(); - assert!( - decode_reply(&RecordBatches::try_new(schema.clone(), vec![two_rows]).unwrap()).is_err() - ); - let int_schema = Arc::new(Schema::new(vec![ColumnSchema::new( - "envelope", - ConcreteDataType::int32_datatype(), - false, - )])); - let non_string = RecordBatch::new( - int_schema.clone(), - vec![Arc::new(datatypes::vectors::Int32Vector::from(vec![Some(1)])) as VectorRef], - ) - .unwrap(); - assert!( - decode_reply(&RecordBatches::try_new(int_schema, vec![non_string]).unwrap()).is_err() - ); - let invalid_json = RecordBatch::new( - envelope_schema(), - vec![Arc::new(StringVector::from(vec!["not json"])) as VectorRef], - ) - .unwrap(); - assert!( - decode_reply( - &RecordBatches::try_new(invalid_json.schema.clone(), vec![invalid_json]).unwrap() - ) - .is_err() - ); - } -} diff --git a/src/common/grpc/src/lib.rs b/src/common/grpc/src/lib.rs index 0ac05863f3e..8527dd079b8 100644 --- a/src/common/grpc/src/lib.rs +++ b/src/common/grpc/src/lib.rs @@ -15,8 +15,6 @@ pub mod channel_manager; pub mod error; pub mod flight; -#[cfg(feature = "enterprise")] -pub mod flow_write; pub mod precision; pub mod reloadable_tls; pub mod select; diff --git a/src/datanode/Cargo.toml b/src/datanode/Cargo.toml index bef2641415e..0720a576b9c 100644 --- a/src/datanode/Cargo.toml +++ b/src/datanode/Cargo.toml @@ -6,7 +6,7 @@ license.workspace = true [features] testing = [] -enterprise = ["mito2/enterprise", "common-grpc/enterprise"] +enterprise = ["mito2/enterprise"] [lints] workspace = true diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index 06b9d42fd00..6055b07dbf6 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -13,10 +13,6 @@ // limitations under the License. mod catalog; -#[cfg(feature = "enterprise")] -mod flow_write; -#[cfg(feature = "enterprise")] -use flow_write::TrackedPayload; mod registrations; mod remote_dyn_filter; @@ -42,8 +38,6 @@ use async_trait::async_trait; use bytes::Bytes; use common_error::ext::{BoxedError, ErrorExt}; use common_error::status_code::StatusCode; -#[cfg(feature = "enterprise")] -use common_grpc::flow_write::{COMMAND_KEY, FlowWriteRegistry, Reply}; use common_meta::datanode::TopicStatsReporter; use common_query::OutputData; use common_query::request::QueryRequest; @@ -122,8 +116,6 @@ pub struct RegionServer { inner: Arc, flight_compression: FlightCompression, suspend: Arc, - #[cfg(feature = "enterprise")] - flow_write_registry: Arc>, } pub struct RegionStat { @@ -172,8 +164,6 @@ impl RegionServer { )), flight_compression, suspend: Arc::new(AtomicBool::new(false)), - #[cfg(feature = "enterprise")] - flow_write_registry: Arc::new(FlowWriteRegistry::default()), } } @@ -1069,15 +1059,6 @@ impl RegionServerHandler for RegionServer { &self, request: RegionRequestV1, ) -> ServerResult { - #[cfg(feature = "enterprise")] - if request - .header - .as_ref() - .and_then(|header| header.query_context.as_ref()) - .is_some_and(|context| context.extensions.contains_key(COMMAND_KEY)) - { - return self.handle_flow_write_request(request).await; - } let accept_partial_result = request .header .as_ref() diff --git a/src/datanode/src/region_server/flow_write.rs b/src/datanode/src/region_server/flow_write.rs deleted file mode 100644 index bc9bf65d69d..00000000000 --- a/src/datanode/src/region_server/flow_write.rs +++ /dev/null @@ -1,969 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -//! Datanode receiver for tracked Flow writes. -//! -//! A single immutable operation per receiver-issued capability: the first -//! admitted `Write` becomes the owner and executes the Inserts exactly once on -//! the region engines; concurrent or retried identical writers join the -//! owner's completion. Dropping a waiter (for example a lost RPC response) -//! never cancels the engine work, and closing a capability rejects later -//! writes with that capability. If the owner's outcome becomes unknown (a -//! child ingest worker was lost), no positive terminal completion is -//! published: waiters observe `WriterLost`; the capability admits no second -//! owner, so no overlapping engine write can be produced. - -use std::sync::Arc; - -use api::v1::region::RegionRequest as RegionRequestV1; -use api::v1::region::region_request; -use common_error::ext::ErrorExt; -use common_grpc::flow_write::{Admission, COMMAND_KEY, Command, Reply, TerminalError}; -use common_runtime::runtime::RuntimeTrait; -use common_telemetry::tracing_context::{FutureExt, TracingContext}; -use futures_util::future::join_all; -use prost::Message; -use servers::error::{InvalidQuerySnafu, Result as ServerResult}; -use snafu::OptionExt; - -use crate::region_server::RegionServer; - -/// Payload of a tracked write: encoded Inserts rows (exact bytes, so floats -/// keep bit equality even for NaN), schemas compared by protobuf equality, and -/// semantic header identity (dbname and command-free query context). Retrying -/// with different business data or context is rejected instead of joining. -pub(crate) type TrackedPayload = ( - Vec, - Vec>>, - String, - Option, -); - -fn tracked_payload(request: &RegionRequestV1) -> ServerResult { - let body = request.body.as_ref().context(InvalidQuerySnafu { - reason: "Expecting non-empty region request body.", - })?; - if !matches!(body, region_request::Body::Inserts(_)) { - return Err(servers::error::Error::InvalidQuery { - reason: "Tracked Flow write supports Inserts requests only.".to_string(), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - // Oneof is not `prost::Message`; the variant message itself is. Schema - // options contain unordered maps, so compare schemas separately rather than - // letting their wire ordering affect retries; retain encoded rows for NaN. - let (bytes, schemas) = match body { - region_request::Body::Inserts(inserts) => { - let mut inserts = inserts.clone(); - let schemas = inserts - .requests - .iter_mut() - .map(|request| { - request - .rows - .as_mut() - .map(|rows| std::mem::take(&mut rows.schema)) - }) - .collect(); - (inserts.encode_to_vec(), schemas) - } - _ => unreachable!("checked above"), - }; - let header = request.header.as_ref(); - let mut query_context = header.and_then(|header| header.query_context.clone()); - if let Some(context) = query_context.as_mut() { - // The command extension differs per control request, not per business. - context.extensions.remove(COMMAND_KEY); - } - Ok(( - bytes, - schemas, - header - .map(|header| header.dbname.clone()) - .unwrap_or_default(), - query_context, - )) -} - -fn ensure_empty_control_body(request: &RegionRequestV1) -> ServerResult<()> { - match request.body.as_ref() { - Some(region_request::Body::Inserts(inserts)) if inserts.requests.is_empty() => Ok(()), - _ => Err(servers::error::Error::InvalidQuery { - reason: "Tracked Flow write control requests must carry an empty Inserts body." - .to_string(), - location: snafu::Location::new(file!(), line!(), column!()), - }), - } -} - -fn registry_error(error: common_grpc::flow_write::RegistryError) -> servers::error::Error { - servers::error::Error::UnexpectedResult { - reason: format!("Tracked Flow write registry rejected request: {error:?}"), - location: snafu::Location::new(file!(), line!(), column!()), - } -} - -fn response(reply: Reply) -> ServerResult { - let encoded = - serde_json::to_vec(&reply).map_err(|error| servers::error::Error::UnexpectedResult { - reason: format!("Failed to encode tracked Flow write reply: {error}"), - location: snafu::Location::new(file!(), line!(), column!()), - })?; - let mut extensions = std::collections::HashMap::new(); - extensions.insert(COMMAND_KEY.to_string(), encoded); - Ok(api::v1::region::RegionResponse { - header: Some(api::v1::ResponseHeader { - status: Some(api::v1::Status { - status_code: common_error::status_code::StatusCode::Success as _, - ..Default::default() - }), - }), - affected_rows: 0, - extensions, - metadata: Vec::new(), - failures: Vec::new(), - }) -} - -impl RegionServer { - pub(crate) async fn handle_flow_write_request( - &self, - request: RegionRequestV1, - ) -> ServerResult { - let command = request - .header - .as_ref() - .and_then(|header| header.query_context.as_ref()) - .and_then(|context| context.extensions.get(COMMAND_KEY)) - .and_then(|value| Command::decode(value).ok()); - let command = match command { - Some(command) => command, - None => { - // The extension exists but is not a decodable command: reject - // before any ordinary DML dispatch. - return Err(InvalidQuerySnafu { - reason: "Malformed tracked Flow write command.", - } - .build()); - } - }; - - match command { - Command::Open { nonce } => { - ensure_empty_control_body(&request)?; - let capability = self - .flow_write_registry - .open(&nonce) - .map_err(registry_error)?; - response(Reply::Opened { capability }) - } - Command::Close { capability } => { - ensure_empty_control_body(&request)?; - self.flow_write_registry - .close(&capability) - .await - .map_err(registry_error)?; - response(Reply::Closed) - } - Command::Write { capability } => { - let payload = tracked_payload(&request)?; - let admission = self - .flow_write_registry - .admit(&capability, payload) - .map_err(registry_error)?; - let reply = match admission { - Admission::Start(owner) => { - // Subscribe before the owner sender moves into the - // spawned task: this caller stays a plain waiter whose - // drop cannot cancel the engine work. - let receiver = owner.subscribe(); - let server = self.clone(); - let body = request.body; - let header = request.header; - self.inner.runtime.spawn(async move { - let completion = server - .run_tracked_write(header, body) - .trace(TracingContext::from_current_span().attach( - common_telemetry::tracing::info_span!( - "RegionServer::tracked_flow_write" - ), - )) - .await; - match completion { - Some(reply) => { - let _ = owner.send(Some(Arc::new(reply))); - } - None => { - // Unknown worker outcome: no positive terminal - // result is published. Dropping the sender lets - // waiters observe `WriterLost`. - drop(owner); - } - } - }); - common_grpc::flow_write::wait_completion(receiver) - .await - .map_err(registry_error)? - } - Admission::Join(waiter) => common_grpc::flow_write::wait_completion(waiter) - .await - .map_err(registry_error)?, - }; - response((*reply).clone()) - } - } - } - - /// Executes one admitted tracked write. Returns `None` only when the - /// outcome is unknown (a child worker was lost); malformed request bodies - /// are terminal because no child was ever dispatched. - async fn run_tracked_write( - &self, - header: Option, - body: Option, - ) -> Option { - let requests = - match body.map(store_api::region_request::RegionRequest::try_from_request_body) { - Some(Ok(requests)) => requests, - Some(Err(error)) => { - return Some(Reply::Complete { - rows: 0, - cost: 0, - metrics: None, - error: Some(TerminalError { - code: error.status_code() as u32, - message: error.output_msg(), - }), - }); - } - // `None` is unreachable here: the Write path already rejected an - // empty body before admission. Treat it as unknown rather than - // inventing a terminal result. - None => return None, - }; - let tracing = header - .as_ref() - .map(|header| TracingContext::from_w3c(&header.tracing_context)) - .unwrap_or_default(); - - let mut unknown_worker = false; - let mut first_error: Option = None; - let mut affected_rows = 0usize; - - let tasks = requests.into_iter().map(|(region_id, request)| { - let span = tracing.attach(common_telemetry::tracing::info_span!( - "RegionServer::tracked_region_write", - region_id = region_id.to_string() - )); - async move { self.handle_request(region_id, request).trace(span).await } - }); - // Drain every per-region child before any terminal decision. A lost - // ingest worker (`RuntimeJoin`) is unknown and outranks any ordinary - // application error observed during the same drain. - for result in join_all(tasks).await { - match result { - Ok(response) => affected_rows += response.affected_rows, - Err(crate::error::Error::RuntimeJoin { .. }) => { - unknown_worker = true; - } - Err(error) if first_error.is_none() => first_error = Some(error), - Err(_) => {} - } - } - - if unknown_worker { - return None; - } - - Some(match first_error { - None => Reply::Complete { - rows: affected_rows, - cost: affected_rows, - metrics: None, - error: None, - }, - Some(error) => Reply::Complete { - rows: 0, - cost: 0, - metrics: None, - error: Some(TerminalError { - code: error.status_code() as u32, - message: error.output_msg(), - }), - }, - }) - } -} - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - use std::sync::Arc; - use std::sync::atomic::{AtomicUsize, Ordering}; - - use api::region::RegionResponse; - use api::v1::region::region_request::Body; - use api::v1::region::{ - InsertRequest, InsertRequests, RegionRequest as Request, RegionRequestHeader, - }; - use api::v1::{ColumnDataType, ColumnSchema, QueryContext, Row, Rows, SemanticType, Value}; - use common_grpc::flow_write::{self, Command, Reply}; - use servers::grpc::region_server::RegionServerHandler; - use store_api::region_engine::{RegionEngine, RegionEngineRef}; - use store_api::storage::RegionId; - use tokio::sync::Notify; - use tokio::time::{Duration, timeout}; - - use super::*; - use crate::tests::{MockRegionEngine, mock_region_server}; - - #[derive(Clone, Default)] - struct Gate { - entered: Arc, - notified: Arc, - open: Arc, - fail: bool, - } - - impl Gate { - async fn wait_entered(&self, count: usize) { - timeout(Duration::from_secs(5), async { - loop { - let notified = self.notified.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - if self.entered.load(Ordering::SeqCst) >= count { - break; - } - notified.await; - } - }) - .await - .unwrap(); - } - fn release(&self) { - self.open.store(1, Ordering::SeqCst); - self.notified.notify_waiters(); - } - async fn wait_open(&self) { - loop { - let notified = self.notified.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - if self.open.load(Ordering::SeqCst) != 0 { - break; - } - notified.await; - } - } - } - - struct GatedEngine { - gate: Gate, - inner: Arc, - panic_id: Option, - } - #[async_trait::async_trait] - impl RegionEngine for GatedEngine { - fn name(&self) -> &str { - self.inner.name() - } - async fn handle_request( - &self, - id: RegionId, - _request: store_api::region_request::RegionRequest, - ) -> Result { - self.gate.entered.fetch_add(1, Ordering::SeqCst); - self.gate.notified.notify_waiters(); - if self.panic_id == Some(id.as_u64()) { - panic!("test ingest panic"); - } - if self.gate.fail && id.as_u64() == 1 { - return Err(common_error::ext::BoxedError::new( - crate::error::RegionNotFoundSnafu { region_id: id }.build(), - )); - } - self.gate.wait_open().await; - Ok(RegionResponse::new(1)) - } - async fn handle_query( - &self, - id: RegionId, - req: store_api::storage::ScanRequest, - ) -> Result - { - self.inner.handle_query(id, req).await - } - async fn get_committed_sequence( - &self, - id: RegionId, - ) -> Result { - self.inner.get_committed_sequence(id).await - } - async fn get_metadata( - &self, - id: RegionId, - ) -> Result { - self.inner.get_metadata(id).await - } - fn region_statistic( - &self, - id: RegionId, - ) -> Option { - self.inner.region_statistic(id) - } - async fn stop(&self) -> Result<(), common_error::ext::BoxedError> { - self.inner.stop().await - } - fn set_region_role( - &self, - id: RegionId, - role: store_api::region_engine::RegionRole, - ) -> Result<(), common_error::ext::BoxedError> { - self.inner.set_region_role(id, role) - } - - fn set_region_role_with_lease( - &self, - id: RegionId, - role: store_api::region_engine::RegionRole, - deadline: std::time::Instant, - ) -> Result<(), common_error::ext::BoxedError> { - self.inner.set_region_role_with_lease(id, role, deadline) - } - async fn sync_region( - &self, - id: RegionId, - req: store_api::region_engine::SyncRegionFromRequest, - ) -> Result - { - self.inner.sync_region(id, req).await - } - async fn remap_manifests( - &self, - req: store_api::region_engine::RemapManifestsRequest, - ) -> Result - { - self.inner.remap_manifests(req).await - } - async fn set_region_role_state_gracefully( - &self, - id: RegionId, - state: store_api::region_engine::SettableRegionRoleState, - ) -> Result< - store_api::region_engine::SetRegionRoleStateResponse, - common_error::ext::BoxedError, - > { - self.inner.set_region_role_state_gracefully(id, state).await - } - fn role(&self, id: RegionId) -> Option { - self.inner.role(id) - } - fn as_any(&self) -> &dyn std::any::Any { - self - } - } - - fn body(ids: &[u64], nan: bool) -> Body { - Body::Inserts(InsertRequests { - requests: ids - .iter() - .map(|id| InsertRequest { - region_id: *id, - rows: Some(Rows { - schema: vec![ - ColumnSchema { - column_name: "ts".into(), - datatype: ColumnDataType::TimestampMillisecond as i32, - semantic_type: SemanticType::Timestamp as i32, - datatype_extension: None, - options: None, - }, - ColumnSchema { - column_name: "v".into(), - datatype: ColumnDataType::Float64 as i32, - semantic_type: SemanticType::Field as i32, - datatype_extension: None, - options: None, - }, - ], - rows: vec![Row { - values: vec![ - Value { - value_data: Some( - api::v1::value::ValueData::TimestampMillisecondValue(1), - ), - }, - Value { - value_data: Some(api::v1::value::ValueData::F64Value(if nan { - f64::NAN - } else { - 7. - })), - }, - ], - }], - }), - partition_expr_version: None, - skip_wal: false, - }) - .collect(), - }) - } - - fn request(cmd: Command, body: Option) -> Request { - let mut extensions = HashMap::new(); - extensions.insert(flow_write::COMMAND_KEY.into(), cmd.encode().unwrap()); - Request { - header: Some(RegionRequestHeader { - dbname: "db".into(), - tracing_context: Default::default(), - query_context: Some(QueryContext { - extensions, - ..Default::default() - }), - }), - body, - } - } - fn decode(resp: &api::v1::region::RegionResponse) -> Reply { - assert_eq!( - resp.header - .as_ref() - .unwrap() - .status - .as_ref() - .unwrap() - .status_code, - common_error::status_code::StatusCode::Success as u32 - ); - serde_json::from_slice(resp.extensions.get(flow_write::COMMAND_KEY).unwrap()).unwrap() - } - async fn open(s: &RegionServer) -> String { - match decode( - &s.handle_region_request(request( - Command::Open { nonce: "n".into() }, - Some(Body::Inserts(InsertRequests { requests: vec![] })), - )) - .await - .unwrap(), - ) { - Reply::Opened { capability } => capability, - x => panic!("{x:?}"), - } - } - fn setup(gate: Gate, panic_id: Option, ids: &[u64]) -> RegionServer { - let s = mock_region_server(); - let (inner, _) = MockRegionEngine::new("mock"); - let engine: RegionEngineRef = Arc::new(GatedEngine { - gate, - inner, - panic_id, - }); - for id in ids { - s.inner.region_map.insert( - RegionId::from_u64(*id), - super::super::RegionEngineWithStatus::Ready(engine.clone()), - ); - } - s - } - fn write(cap: &str, ids: &[u64], nan: bool) -> Request { - request( - Command::Write { - capability: cap.into(), - }, - Some(body(ids, nan)), - ) - } - - #[tokio::test] - async fn dropped_rpc_retry_and_close_drain_exactly_once() { - let gate = Gate::default(); - let s = setup(gate.clone(), None, &[1, 2]); - let cap = open(&s).await; - let w = write(&cap, &[1, 2], false); - let first = tokio::spawn({ - let s = s.clone(); - let w = w.clone(); - async move { s.handle_region_request(w).await } - }); - gate.wait_entered(2).await; - first.abort(); - // Exercise the same actual registry admission used by retry, before release. - let payload = tracked_payload(&w).unwrap(); - let Admission::Join(waiter) = s.flow_write_registry.admit(&cap, payload).unwrap() else { - panic!("retry did not join") - }; - let mut retry_waiter = tokio::spawn(common_grpc::flow_write::wait_completion(waiter)); - assert!( - timeout(Duration::from_millis(20), &mut retry_waiter) - .await - .is_err() - ); - let mut closer = tokio::spawn({ - let s = s.clone(); - let cap = cap.clone(); - async move { - s.handle_region_request(request( - Command::Close { capability: cap }, - Some(Body::Inserts(InsertRequests { requests: vec![] })), - )) - .await - } - }); - assert!( - timeout(Duration::from_millis(20), &mut closer) - .await - .is_err() - ); - gate.release(); - let joined = timeout(Duration::from_secs(5), &mut retry_waiter) - .await - .unwrap() - .unwrap() - .unwrap(); - assert!(matches!( - *joined, - Reply::Complete { - rows: 2, - error: None, - .. - } - )); - assert!(matches!( - decode( - &timeout(Duration::from_secs(5), &mut closer) - .await - .unwrap() - .unwrap() - .unwrap() - ), - Reply::Closed - )); - assert!( - s.handle_region_request(write(&cap, &[1], false)) - .await - .is_err() - ); - let cap2 = open(&s).await; - gate.release(); - let r = s - .handle_region_request(write(&cap2, &[1], false)) - .await - .unwrap(); - assert!(matches!(decode(&r), Reply::Complete { rows: 1, .. })); - assert!( - s.handle_region_request(write(&cap, &[1], false)) - .await - .is_err() - ); - assert_eq!(gate.entered.load(Ordering::SeqCst), 3); - let close2 = request( - Command::Close { capability: cap2 }, - Some(Body::Inserts(InsertRequests { requests: vec![] })), - ); - assert!(matches!( - decode(&s.handle_region_request(close2).await.unwrap()), - Reply::Closed - )); - } - - #[tokio::test] - async fn application_error_waits_for_sibling_and_panic_overrides_it() { - let gate = Gate { - fail: true, - ..Default::default() - }; - let s = setup(gate.clone(), None, &[1, 2]); - let cap = open(&s).await; - let task = tokio::spawn({ - let s = s.clone(); - async move { s.handle_region_request(write(&cap, &[1, 2], false)).await } - }); - gate.wait_entered(2).await; - // The ordinary error is immediate for region 1, but region 2 remains gated. - assert!(!task.is_finished()); - gate.release(); - let r = timeout(Duration::from_secs(5), task) - .await - .unwrap() - .unwrap() - .unwrap(); - assert!(matches!(decode(&r), Reply::Complete { error: Some(_), .. })); - - let gate = Gate { - fail: true, - ..Default::default() - }; - let s = setup(gate.clone(), Some(2), &[1, 2, 3]); - let cap = open(&s).await; - let task = tokio::spawn({ - let s = s.clone(); - let cap = cap.clone(); - async move { - s.handle_region_request(write(&cap, &[1, 2, 3], false)) - .await - } - }); - gate.wait_entered(3).await; - assert!(!task.is_finished()); - gate.release(); - assert!( - timeout(Duration::from_secs(5), task) - .await - .unwrap() - .unwrap() - .is_err() - ); - assert!( - s.handle_region_request(write(&cap, &[1, 2, 3], false)) - .await - .is_err() - ); - assert_eq!(gate.entered.load(Ordering::SeqCst), 3); - } - - #[tokio::test] - async fn decoded_schema_option_maps_join_live_nan_write() { - let gate = Gate::default(); - let s = setup(gate.clone(), None, &[1]); - let cap = open(&s).await; - let mut original = write(&cap, &[1], true); - let Body::Inserts(inserts) = original.body.as_mut().unwrap() else { - unreachable!() - }; - inserts.requests[0].rows.as_mut().unwrap().schema[1].options = - Some(api::v1::ColumnOptions { - options: [ - ("alpha".to_string(), "one".to_string()), - ("beta".to_string(), "two".to_string()), - ("gamma".to_string(), "three".to_string()), - ] - .into_iter() - .collect(), - }); - let encoded = original.encode_to_vec(); - let Body::Inserts(original_inserts) = original.body.as_ref().unwrap() else { - unreachable!() - }; - let original_rows = original_inserts.requests[0].rows.clone(); - let original_body_bytes = original_inserts.encode_to_vec(); - let mut retries = Vec::new(); - let mut found_different_wire_order = false; - for _ in 0..128 { - let decoded = Request::decode(encoded.as_slice()).unwrap(); - let Body::Inserts(decoded_inserts) = decoded.body.as_ref().unwrap() else { - unreachable!() - }; - assert_eq!( - decoded_inserts.requests[0].rows.as_ref().unwrap().schema, - original_rows.as_ref().unwrap().schema - ); - assert_eq!( - tracked_payload(&decoded).unwrap(), - tracked_payload(&original).unwrap() - ); - found_different_wire_order |= decoded_inserts.encode_to_vec() != original_body_bytes; - retries.push(decoded); - if found_different_wire_order && retries.len() >= 16 { - break; - } - } - assert!(found_different_wire_order); - - let owner = tokio::spawn({ - let s = s.clone(); - async move { s.handle_region_request(original).await } - }); - gate.wait_entered(1).await; - let retry_tasks: Vec<_> = retries - .into_iter() - .map(|retry| { - let s = s.clone(); - tokio::spawn(async move { s.handle_region_request(retry).await }) - }) - .collect(); - tokio::task::yield_now().await; - assert!(retry_tasks.iter().all(|retry| !retry.is_finished())); - assert_eq!(gate.entered.load(Ordering::SeqCst), 1); - gate.release(); - let owner_reply = decode( - &timeout(Duration::from_secs(5), owner) - .await - .unwrap() - .unwrap() - .unwrap(), - ); - assert!(matches!( - &owner_reply, - Reply::Complete { - rows: 1, - error: None, - .. - } - )); - let owner_reply_json = serde_json::to_string(&owner_reply).unwrap(); - for retry in retry_tasks { - let retry_reply = decode( - &timeout(Duration::from_secs(5), retry) - .await - .unwrap() - .unwrap() - .unwrap(), - ); - assert!(matches!( - &retry_reply, - Reply::Complete { - rows: 1, - error: None, - .. - } - )); - assert_eq!( - serde_json::to_string(&retry_reply).unwrap(), - owner_reply_json - ); - } - assert_eq!(gate.entered.load(Ordering::SeqCst), 1); - - let replay = Request::decode(encoded.as_slice()).unwrap(); - assert!(matches!( - decode(&s.handle_region_request(replay.clone()).await.unwrap()), - Reply::Complete { rows: 1, .. } - )); - let mut changed_schema = replay.clone(); - let Body::Inserts(inserts) = changed_schema.body.as_mut().unwrap() else { - unreachable!() - }; - inserts.requests[0].rows.as_mut().unwrap().schema[1] - .options - .as_mut() - .unwrap() - .options - .insert("gamma".into(), "changed".into()); - assert!(s.handle_region_request(changed_schema).await.is_err()); - let close = request( - Command::Close { - capability: cap.clone(), - }, - Some(Body::Inserts(InsertRequests { requests: vec![] })), - ); - assert!(matches!( - decode(&s.handle_region_request(close).await.unwrap()), - Reply::Closed - )); - assert!(s.handle_region_request(replay).await.is_err()); - assert_eq!(gate.entered.load(Ordering::SeqCst), 1); - } - - #[tokio::test] - async fn payload_identity_nan_semantics_and_pre_admission_rejection() { - let s = mock_region_server(); - let cap = open(&s).await; - let a = write(&cap, &[1], true); - let b = write(&cap, &[1], true); - assert_eq!(tracked_payload(&a).unwrap(), tracked_payload(&b).unwrap()); - let owner = match s - .flow_write_registry - .admit(&cap, tracked_payload(&a).unwrap()) - .unwrap() - { - Admission::Start(owner) => owner, - _ => panic!(), - }; - let mut semantic_mismatch = b.clone(); - semantic_mismatch.header.as_mut().unwrap().dbname = "other_db".into(); - assert_eq!( - s.flow_write_registry - .admit(&cap, tracked_payload(&semantic_mismatch).unwrap()) - .unwrap_err(), - flow_write::RegistryError::PayloadMismatch - ); - semantic_mismatch = b.clone(); - semantic_mismatch - .header - .as_mut() - .unwrap() - .query_context - .as_mut() - .unwrap() - .extensions - .insert("flow_lane".into(), "changed".into()); - assert_eq!( - s.flow_write_registry - .admit(&cap, tracked_payload(&semantic_mismatch).unwrap()) - .unwrap_err(), - flow_write::RegistryError::PayloadMismatch - ); - let Admission::Join(waiter) = s - .flow_write_registry - .admit(&cap, tracked_payload(&b).unwrap()) - .unwrap() - else { - panic!() - }; - let mut joined = tokio::spawn(common_grpc::flow_write::wait_completion(waiter)); - assert!( - timeout(Duration::from_millis(20), &mut joined) - .await - .is_err() - ); - owner - .send(Some(Arc::new(Reply::Complete { - rows: 1, - cost: 1, - metrics: None, - error: None, - }))) - .unwrap(); - assert!(matches!( - *timeout(Duration::from_secs(5), &mut joined) - .await - .unwrap() - .unwrap() - .unwrap(), - Reply::Complete { rows: 1, .. } - )); - s.flow_write_registry.close(&cap).await.unwrap(); - assert_ne!( - tracked_payload(&a).unwrap(), - tracked_payload(&write(&cap, &[1], false)).unwrap() - ); - assert!( - s.handle_region_request(request( - Command::Write { - capability: cap.clone() - }, - Some(Body::Deletes(Default::default())) - )) - .await - .is_err() - ); - let fresh = open(&s).await; - let mut bad = request( - Command::Write { - capability: fresh.clone(), - }, - Some(body(&[1], false)), - ); - bad.header - .as_mut() - .unwrap() - .query_context - .as_mut() - .unwrap() - .extensions - .insert(flow_write::COMMAND_KEY.into(), "not-json".into()); - assert!(s.handle_region_request(bad).await.is_err()); - s.flow_write_registry.close(&fresh).await.unwrap(); - } -} diff --git a/src/flow/Cargo.toml b/src/flow/Cargo.toml index 2cf316ad245..2d9ff283aa2 100644 --- a/src/flow/Cargo.toml +++ b/src/flow/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true [features] -enterprise = ["common-grpc/enterprise", "session/enterprise"] +enterprise = [] [lints] workspace = true diff --git a/src/flow/src/batching_mode/frontend_client.rs b/src/flow/src/batching_mode/frontend_client.rs index 8c74c6897f0..1a354c55e42 100644 --- a/src/flow/src/batching_mode/frontend_client.rs +++ b/src/flow/src/batching_mode/frontend_client.rs @@ -95,12 +95,8 @@ pub enum FrontendClient { control_channel_manager: ChannelManager, query: QueryOptions, batch_opts: BatchingModeOptions, - #[cfg(feature = "enterprise")] - tracked_writes: bool, }, Standalone { - #[cfg(feature = "enterprise")] - tracked_writes: bool, /// for the sake of simplicity still use grpc even in standalone mode /// notice the client here should all be lazy, so that can wait after frontend is booted then make conn database_client: HandlerMutable, @@ -109,26 +105,6 @@ pub enum FrontendClient { } impl FrontendClient { - #[cfg(feature = "enterprise")] - pub fn with_tracked_writes(&self) -> Self { - let mut client = self.clone(); - match &mut client { - Self::Distributed { tracked_writes, .. } | Self::Standalone { tracked_writes, .. } => { - *tracked_writes = true; - } - } - client - } - - #[cfg(feature = "enterprise")] - fn tracked_writes_enabled(&self) -> bool { - match self { - Self::Distributed { tracked_writes, .. } | Self::Standalone { tracked_writes, .. } => { - *tracked_writes - } - } - } - /// Create a new empty frontend client, with a `HandlerMutable` to set the grpc handler later pub fn from_empty_grpc_handler(query: QueryOptions) -> (Self, HandlerMutable) { let is_initialized = Arc::new(SetOnce::new()); @@ -140,8 +116,6 @@ impl FrontendClient { Self::Standalone { database_client: handler.clone(), query, - #[cfg(feature = "enterprise")] - tracked_writes: false, }, handler, ) @@ -178,8 +152,6 @@ impl FrontendClient { control_channel_manager, query, batch_opts, - #[cfg(feature = "enterprise")] - tracked_writes: false, }) } @@ -196,8 +168,6 @@ impl FrontendClient { Self::Standalone { database_client: handler, query, - #[cfg(feature = "enterprise")] - tracked_writes: false, } } } @@ -235,39 +205,7 @@ impl DatabaseWithPeer { } } -#[cfg(feature = "enterprise")] -pub(crate) mod flow_write; - impl FrontendClient { - /// Preflight tracked-write support by opening and closing a capability without writing. - #[cfg(feature = "enterprise")] - pub async fn check_tracked_writes(&self, catalog: &str, schema: &str) -> Result<(), Error> { - if !self.tracked_writes_enabled() { - return UnexpectedSnafu { - reason: "Tracked writes are not enabled on this frontend client", - } - .fail(); - } - flow_write::check_tracked_writes(self, catalog, schema).await - } - - /// Execute a finite SQL write with receiver-issued completion tracking. - #[cfg(feature = "enterprise")] - pub async fn tracked_sql_write( - &self, - catalog: &str, - schema: &str, - sql: &str, - ) -> Result { - if !self.tracked_writes_enabled() { - return UnexpectedSnafu { - reason: "Tracked writes are not enabled on this frontend client", - } - .fail(); - } - flow_write::tracked_sql_write(self, catalog, schema, sql).await - } - /// scan for available frontend from metadata pub(crate) async fn scan_for_frontend(&self) -> Result, Error> { let Self::Distributed { meta_client, .. } = self else { @@ -558,33 +496,6 @@ impl FrontendClient { peer_desc: &mut Option, ) -> Result { let flow_extensions = build_flow_extensions(extensions)?; - #[cfg(feature = "enterprise")] - if self.tracked_writes_enabled() && is_tracked_insert_request(&request) { - let effective_extensions: HashMap = extensions - .iter() - .map(|(key, value)| ((*key).to_string(), (*value).to_string())) - .collect(); - if effective_extensions.contains_key(common_grpc::flow_write::COMMAND_KEY) { - return UnexpectedSnafu { - reason: "Client-supplied tracked Flow command is forbidden", - } - .fail(); - } - let effective_extension_refs: Vec<(&str, &str)> = effective_extensions - .iter() - .map(|(key, value)| (key.as_str(), value.as_str())) - .collect(); - return flow_write::tracked_query( - self, - catalog, - schema, - Some(request), - &effective_extension_refs, - snapshot_seqs, - peer_desc, - ) - .await; - } match self { FrontendClient::Distributed { query, batch_opts, .. @@ -835,15 +746,6 @@ impl FrontendClient { } } -#[cfg(feature = "enterprise")] -fn is_tracked_insert_request(request: &QueryRequest) -> bool { - match request.query.as_ref() { - Some(Query::InsertIntoPlan(_)) => true, - Some(Query::Sql(sql)) => sql.trim_start().to_ascii_uppercase().starts_with("INSERT "), - _ => false, - } -} - fn build_flow_extensions(extensions: &[(&str, &str)]) -> Result { let flow_extensions = HashMap::from_iter( extensions diff --git a/src/flow/src/batching_mode/frontend_client/flow_write.rs b/src/flow/src/batching_mode/frontend_client/flow_write.rs deleted file mode 100644 index 0d7663ccd4d..00000000000 --- a/src/flow/src/batching_mode/frontend_client/flow_write.rs +++ /dev/null @@ -1,758 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -use std::collections::HashMap; -use std::sync::Arc; -use std::time::Duration; - -use api::v1::query_request::Query; -use api::v1::{QueryRequest, greptime_request::Request}; -use client::OutputWithMetrics; -use common_error::ext::{BoxedError, ErrorExt}; -use common_error::status_code::StatusCode; -use common_grpc::flow_write::{self, COMMAND_KEY, Command, Reply, TerminalError}; -use common_query::{Output, OutputData, OutputMeta}; -use common_telemetry::warn; -use session::context::{Channel, QueryContextBuilder, generate_remote_query_id}; -use snafu::OptionExt; -use tokio::time::sleep; - -use crate::Error; -use crate::batching_mode::frontend_client::{DatabaseWithPeer, FrontendClient, PeerDesc}; -use crate::error::UnexpectedSnafu; - -const RETRY_PACE: Duration = Duration::from_secs(1); - -pub(crate) async fn tracked_sql_write( - frontend: &FrontendClient, - catalog: &str, - schema: &str, - sql: &str, -) -> Result { - tracked_query( - frontend, - catalog, - schema, - Some(QueryRequest { - query: Some(Query::Sql(sql.to_string())), - }), - &[], - &HashMap::new(), - &mut None, - ) - .await -} - -pub(crate) async fn check_tracked_writes( - frontend: &FrontendClient, - catalog: &str, - schema: &str, -) -> Result<(), Error> { - tracked_query( - frontend, - catalog, - schema, - None, - &[], - &HashMap::new(), - &mut None, - ) - .await - .map(|_| ()) -} - -pub(crate) async fn tracked_query( - frontend: &FrontendClient, - catalog: &str, - schema: &str, - request: Option, - extensions: &[(&str, &str)], - snapshot_seqs: &HashMap, - peer_desc: &mut Option, -) -> Result { - let (selected, handler, parallelism, read_preference, timeout) = match frontend { - FrontendClient::Distributed { - query, batch_opts, .. - } => ( - Some( - frontend - .get_random_active_frontend(catalog, schema) - .await - .map_err(prewrite_error)?, - ), - None, - query.parallelism.to_string(), - Some(batch_opts.read_preference.as_ref().to_string()), - batch_opts.experimental_flight_do_get_timeout, - ), - FrontendClient::Standalone { - database_client, - query, - .. - } => { - let handler = database_client - .handler - .lock() - .map_err(|e| { - prewrite_reason( - format!("Failed to lock database client: {e}"), - StatusCode::Internal, - ) - })? - .as_ref() - .context(UnexpectedSnafu { - reason: "Standalone's frontend instance is not set", - }) - .map_err(prewrite_error)? - .upgrade() - .context(UnexpectedSnafu { - reason: "Failed to upgrade database client", - }) - .map_err(prewrite_error)?; - ( - None, - Some(handler), - query.parallelism.to_string(), - None, - RETRY_PACE, - ) - } - }; - *peer_desc = Some(match &selected { - Some(DatabaseWithPeer { peer, .. }) => PeerDesc::Dist { peer: peer.clone() }, - None => PeerDesc::Standalone, - }); - - let nonce = generate_remote_query_id(); - let mut command = Command::Open { nonce }; - let mut completion: Option<( - usize, - usize, - Option, - Option, - )> = None; - - loop { - let encoded = command.encode().map_err(|error| { - UnexpectedSnafu { - reason: format!("Failed to encode tracked Flow command: {error}"), - } - .build() - })?; - let mut operation_extensions: Vec<(String, String)> = extensions - .iter() - .filter(|(key, _)| *key != COMMAND_KEY) - .map(|(key, value)| ((*key).to_string(), (*value).to_string())) - .collect(); - operation_extensions.push((COMMAND_KEY.to_string(), encoded)); - let extension_refs: Vec<(&str, &str)> = operation_extensions - .iter() - .map(|(k, v)| (k.as_str(), v.as_str())) - .collect(); - let phase_request = match &command { - Command::Write { .. } => request - .as_ref() - .context(UnexpectedSnafu { - reason: "Tracked Flow write command has no request", - })? - .clone(), - Command::Open { .. } | Command::Close { .. } => QueryRequest { - query: Some(Query::Sql(String::new())), - }, - }; - let response = if let Some(DatabaseWithPeer { database, .. }) = &selected { - let mut hints = vec![( - query::datafusion::QUERY_PARALLELISM_HINT, - parallelism.as_str(), - )]; - if let Some(preference) = read_preference.as_deref() { - hints.push((session::hints::READ_PREFERENCE_HINT, preference)); - } - database - .flight_request() - .with_hints(&hints) - .with_flow_extensions(&extension_refs) - .with_snapshot_seqs(snapshot_seqs) - .with_timeout(timeout) - .query_with_terminal_metrics(phase_request) - .await - .map(|output| output.output) - .map_err(|e| (e.status_code(), e.to_string())) - } else { - let mut ctx_extensions: HashMap = - operation_extensions.into_iter().collect(); - ctx_extensions.insert( - query::datafusion::QUERY_PARALLELISM_HINT.to_string(), - parallelism.clone(), - ); - let ctx = QueryContextBuilder::default() - .current_catalog(catalog.to_string()) - .current_schema(schema.to_string()) - .channel(Channel::Internal) - .extensions(ctx_extensions) - .snapshot_seqs(Arc::new(std::sync::RwLock::new(snapshot_seqs.clone()))) - .build(); - let handler = handler.as_ref().ok_or_else(|| { - UnexpectedSnafu { - reason: "Standalone handler was not pinned", - } - .build() - })?; - handler - .do_query(Request::Query(phase_request), Arc::new(ctx)) - .await - .map_err(|e| (e.status_code(), e.to_string())) - }; - let reply = match response { - Ok(output) => match decode_output(output).await { - Ok(reply) => Some(reply), - Err(e) if matches!(&command, Command::Open { .. }) => { - return Err(prewrite_reason( - format!("Frontend does not support tracked Flow writes: {e}"), - StatusCode::Unsupported, - )); - } - Err(e) => { - warn!("Malformed tracked Flow {:?} reply: {}", command, e); - None - } - }, - Err((code, msg)) => { - // Only Open is pre-admission; definitive rejection there is safe to surface. - if matches!(&command, Command::Open { .. }) && is_definitive_rejection(code) { - return Err(prewrite_reason( - format!("Frontend rejected tracked Flow open: {msg}"), - code, - )); - } - warn!( - "Tracked Flow {:?} transport failure (code={:?}): {}", - command, code, msg - ); - None - } - }; - match (command.clone(), reply) { - (Command::Open { .. }, Some(Reply::Opened { capability: cap })) if !cap.is_empty() => { - command = if request.is_some() { - Command::Write { capability: cap } - } else { - Command::Close { capability: cap } - }; - continue; - } - (Command::Open { .. }, Some(other)) => { - return Err(prewrite_reason( - format!("Invalid tracked Flow open reply: {other:?}"), - StatusCode::InvalidArguments, - )); - } - ( - Command::Write { capability }, - Some(Reply::Complete { - rows, - cost, - metrics, - error, - }), - ) => { - completion = Some((rows, cost, metrics, error)); - command = Command::Close { capability }; - continue; - } - (Command::Write { .. }, Some(other)) => { - warn!("Unexpected tracked Flow write reply: {other:?}") - } - (Command::Close { .. }, Some(Reply::Closed)) => { - let Some((rows, cost, metrics, error)) = completion.take() else { - if request.is_none() { - return Ok(OutputWithMetrics::from_output(Output::new( - OutputData::AffectedRows(0), - OutputMeta::default(), - ))); - } - return UnexpectedSnafu { - reason: "Close completed without positive write result", - } - .fail(); - }; - if let Some(error) = error { - return Err(Error::External { - source: BoxedError::new(error), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - let output = OutputWithMetrics::from_output(Output::new( - OutputData::AffectedRows(rows), - OutputMeta { - cost, - ..Default::default() - }, - )); - output.metrics.update(metrics); - return Ok(output); - } - (Command::Close { .. }, Some(other)) => { - warn!("Unexpected tracked Flow close reply: {other:?}") - } - (_, None) => {} - } - sleep(RETRY_PACE).await; - } -} - -fn prewrite_error(error: Error) -> Error { - let status = error.status_code(); - prewrite_reason(error.to_string(), status) -} - -/// Returns true when a tracked Flow command error is a definitive, non-retryable -/// rejection from the frontend rather than an ambiguous transport failure. These -/// codes indicate the frontend itself refused the command (unsupported protocol, -/// malformed/empty command, or wrong channel), so retrying the same pinned -/// frontend can never succeed; the caller must fail fast instead of looping. -fn is_definitive_rejection(code: StatusCode) -> bool { - matches!( - code, - StatusCode::Unsupported | StatusCode::InvalidArguments | StatusCode::PermissionDenied - ) -} - -fn prewrite_reason(message: String, status: StatusCode) -> Error { - Error::External { - source: BoxedError::new(TerminalError { - code: status as u32, - message, - }), - location: snafu::Location::new(file!(), line!(), column!()), - } -} - -async fn decode_output(output: Output) -> Result { - let batches = match output.data { - OutputData::RecordBatches(batches) => batches, - OutputData::Stream(stream) => common_recordbatch::util::collect_batches(stream) - .await - .map_err(|e| e.to_string())?, - _ => return Err("tracked control request returned a non-record-batch result".to_string()), - }; - flow_write::decode_reply(&batches).map_err(|e| e.to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - - use common_error::ext::{BoxedError, PlainError}; - use common_error::status_code::StatusCode; - use session::context::QueryContextRef; - - #[derive(Debug, Default)] - struct LostReplyHandler { - opens: AtomicUsize, - writes: AtomicUsize, - closes: AtomicUsize, - executions: AtomicUsize, - registry: common_grpc::flow_write::FlowWriteRegistry, - capabilities: std::sync::Mutex>, - } - - #[async_trait::async_trait] - impl super::super::GrpcQueryHandlerWithBoxedError for LostReplyHandler { - async fn do_query( - &self, - request: Request, - ctx: QueryContextRef, - ) -> Result { - let encoded = ctx.extensions().get(COMMAND_KEY).cloned().ok_or_else(|| { - BoxedError::new(PlainError::new( - "missing command".into(), - StatusCode::Unexpected, - )) - })?; - match Command::decode(&encoded).map_err(|error| { - BoxedError::new(PlainError::new( - error.to_string(), - StatusCode::InvalidArguments, - )) - })? { - Command::Open { nonce } => { - let call = self.opens.fetch_add(1, Ordering::SeqCst); - let capability = self.registry.open(&nonce).unwrap(); - let previous = self - .capabilities - .lock() - .unwrap() - .insert(nonce, capability.clone()); - if let Some(previous) = previous { - assert_eq!(previous, capability); - } - if call == 0 { - return Err(transport_error("lost Open reply")); - } - assert_empty_sql(&request); - response(Reply::Opened { capability }) - } - Command::Write { capability } => { - let sql = request_sql(&request); - let call = self.writes.fetch_add(1, Ordering::SeqCst); - let admission = self.registry.admit(&capability, sql.clone()).unwrap(); - let result = match admission { - common_grpc::flow_write::Admission::Start(sender) => { - self.executions.fetch_add(1, Ordering::SeqCst); - let reply = Reply::Complete { - rows: 1, - cost: 9, - metrics: Some(common_recordbatch::adapter::RecordBatchMetrics { - region_watermarks: vec![ - common_recordbatch::adapter::RegionWatermarkEntry { - region_id: 41, - watermark: Some(17), - }, - ], - ..Default::default() - }), - error: None, - }; - sender.send(Some(Arc::new(reply.clone()))).unwrap(); - reply - } - common_grpc::flow_write::Admission::Join(receiver) => { - common_grpc::flow_write::wait_completion(receiver) - .await - .unwrap() - .as_ref() - .clone() - } - }; - if call == 0 { - return Err(transport_error("lost Write reply")); - } - response(result) - } - Command::Close { capability } => { - let call = self.closes.fetch_add(1, Ordering::SeqCst); - self.registry.close(&capability).await.unwrap(); - if call == 0 { - return Err(transport_error("lost Close reply")); - } - response(Reply::Closed) - } - } - } - } - - fn request_sql(request: &Request) -> String { - match request { - Request::Query(query) => match query.query.as_ref() { - Some(Query::Sql(sql)) => sql.clone(), - other => panic!("expected SQL INSERT, got {other:?}"), - }, - other => panic!("expected Query request, got {other:?}"), - } - } - - fn assert_empty_sql(request: &Request) { - assert!( - matches!(request, Request::Query(QueryRequest { query: Some(Query::Sql(sql)) }) if sql.is_empty()) - ); - } - - fn transport_error(message: &str) -> BoxedError { - BoxedError::new(PlainError::new( - message.to_string(), - StatusCode::StorageUnavailable, - )) - } - - fn response(reply: Reply) -> Result { - let batches = flow_write::reply_batches(&reply).map_err(BoxedError::new)?; - Ok(Output::new_with_record_batches(batches)) - } - - #[tokio::test] - async fn retries_same_open_write_and_close_capability_and_executes_once() { - let handler = Arc::new(LostReplyHandler::default()); - let trait_handler: Arc = handler.clone(); - let weak = Arc::downgrade(&trait_handler); - let frontend = - FrontendClient::from_grpc_handler(weak, query::options::QueryOptions::default()) - .with_tracked_writes(); - let output = frontend - .tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (7)") - .await - .unwrap(); - assert!(matches!(output.output.data, OutputData::AffectedRows(1))); - assert_eq!(output.output.meta.cost, 9); - assert_eq!( - output.metrics.region_watermark_map(), - Some(HashMap::from([(41, 17)])) - ); - assert_eq!(handler.opens.load(Ordering::SeqCst), 2); - assert_eq!(handler.writes.load(Ordering::SeqCst), 2); - assert_eq!(handler.closes.load(Ordering::SeqCst), 2); - assert_eq!(handler.executions.load(Ordering::SeqCst), 1); - let second = frontend - .tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (8)") - .await - .unwrap(); - assert!(matches!(second.output.data, OutputData::AffectedRows(1))); - assert_eq!(handler.executions.load(Ordering::SeqCst), 2); - } - - /// A legacy frontend that does not understand the tracked-write extension - /// processes `Open` as an ordinary empty-SQL query and rejects it with - /// `InvalidArguments`. That is a definitive application rejection, not an - /// ambiguous transport failure: the client must fail fast instead of - /// retrying the same pinned frontend forever. - #[derive(Debug, Default)] - struct LegacyRejectHandler { - opens: AtomicUsize, - } - - #[async_trait::async_trait] - impl super::super::GrpcQueryHandlerWithBoxedError for LegacyRejectHandler { - async fn do_query( - &self, - _request: Request, - _ctx: QueryContextRef, - ) -> Result { - self.opens.fetch_add(1, Ordering::SeqCst); - Err(BoxedError::new(PlainError::new( - "empty statements".to_string(), - StatusCode::InvalidArguments, - ))) - } - } - - #[derive(Debug)] - struct PreflightHandler { - opens: AtomicUsize, - closes: AtomicUsize, - reject_open: bool, - } - - #[async_trait::async_trait] - impl super::super::GrpcQueryHandlerWithBoxedError for PreflightHandler { - async fn do_query( - &self, - request: Request, - ctx: QueryContextRef, - ) -> Result { - let encoded = ctx.extensions().get(COMMAND_KEY).cloned().unwrap(); - assert_empty_sql(&request); - match Command::decode(&encoded).unwrap() { - Command::Open { .. } => { - self.opens.fetch_add(1, Ordering::SeqCst); - if self.reject_open { - Err(BoxedError::new(PlainError::new( - "preflight rejected".into(), - StatusCode::PermissionDenied, - ))) - } else { - response(Reply::Opened { - capability: "preflight-capability".into(), - }) - } - } - Command::Close { capability } => { - assert_eq!(capability, "preflight-capability"); - self.closes.fetch_add(1, Ordering::SeqCst); - response(Reply::Closed) - } - Command::Write { .. } => panic!("preflight must not write"), - } - } - } - - #[tokio::test] - async fn preflight_opens_and_closes_without_writing() { - let handler = Arc::new(PreflightHandler { - opens: AtomicUsize::default(), - closes: AtomicUsize::default(), - reject_open: false, - }); - let trait_handler: Arc = handler.clone(); - let frontend = FrontendClient::from_grpc_handler( - Arc::downgrade(&trait_handler), - query::options::QueryOptions::default(), - ) - .with_tracked_writes(); - tokio::time::timeout( - Duration::from_secs(10), - frontend.check_tracked_writes("greptime", "public"), - ) - .await - .expect("tracked-write preflight should finish within 10 seconds") - .unwrap(); - assert_eq!(handler.opens.load(Ordering::SeqCst), 1); - assert_eq!(handler.closes.load(Ordering::SeqCst), 1); - } - - #[tokio::test] - async fn preflight_preserves_definitive_open_error() { - let handler = Arc::new(PreflightHandler { - opens: AtomicUsize::default(), - closes: AtomicUsize::default(), - reject_open: true, - }); - let trait_handler: Arc = handler.clone(); - let frontend = FrontendClient::from_grpc_handler( - Arc::downgrade(&trait_handler), - query::options::QueryOptions::default(), - ) - .with_tracked_writes(); - let error = tokio::time::timeout( - Duration::from_secs(10), - frontend.check_tracked_writes("greptime", "public"), - ) - .await - .expect("tracked-write preflight rejection should finish within 10 seconds") - .unwrap_err(); - assert_eq!(error.status_code(), StatusCode::PermissionDenied); - assert!(matches!( - &error, - Error::External { source, .. } - if source.as_any().downcast_ref::().is_some_and(|terminal| { - terminal.code == StatusCode::PermissionDenied as u32 - && terminal.message.contains("preflight rejected") - }) - )); - assert_eq!(handler.opens.load(Ordering::SeqCst), 1); - assert_eq!(handler.closes.load(Ordering::SeqCst), 0); - } - - #[derive(Debug)] - struct RejectionRetryHandler { - status: StatusCode, - opens: AtomicUsize, - writes: AtomicUsize, - closes: AtomicUsize, - capability: std::sync::Mutex>, - } - - #[async_trait::async_trait] - impl super::super::GrpcQueryHandlerWithBoxedError for RejectionRetryHandler { - async fn do_query( - &self, - request: Request, - ctx: QueryContextRef, - ) -> Result { - let encoded = ctx.extensions().get(COMMAND_KEY).cloned().unwrap(); - match Command::decode(&encoded).unwrap() { - Command::Open { nonce } => { - assert_empty_sql(&request); - self.opens.fetch_add(1, Ordering::SeqCst); - let mut capability = self.capability.lock().unwrap(); - let value = capability.get_or_insert_with(|| nonce); - response(Reply::Opened { - capability: value.clone(), - }) - } - Command::Write { capability } => { - assert_eq!(request_sql(&request), "INSERT INTO t VALUES (11)"); - assert_eq!(self.capability.lock().unwrap().as_ref(), Some(&capability)); - if self.writes.fetch_add(1, Ordering::SeqCst) == 0 { - Err(BoxedError::new(PlainError::new( - "write rejection".into(), - self.status, - ))) - } else { - response(Reply::Complete { - rows: 2, - cost: 0, - metrics: None, - error: None, - }) - } - } - Command::Close { capability } => { - assert_empty_sql(&request); - assert_eq!(self.capability.lock().unwrap().as_ref(), Some(&capability)); - if self.closes.fetch_add(1, Ordering::SeqCst) == 0 { - Err(BoxedError::new(PlainError::new( - "close rejection".into(), - self.status, - ))) - } else { - response(Reply::Closed) - } - } - } - } - } - - #[tokio::test] - async fn post_admission_rejections_retry_same_capability_until_close() { - for status in [ - StatusCode::Unsupported, - StatusCode::InvalidArguments, - StatusCode::PermissionDenied, - ] { - let handler = Arc::new(RejectionRetryHandler { - status, - opens: AtomicUsize::default(), - writes: AtomicUsize::default(), - closes: AtomicUsize::default(), - capability: std::sync::Mutex::new(None), - }); - let trait_handler: Arc = - handler.clone(); - let frontend = FrontendClient::from_grpc_handler( - Arc::downgrade(&trait_handler), - query::options::QueryOptions::default(), - ) - .with_tracked_writes(); - let output = tokio::time::timeout( - Duration::from_secs(10), - frontend.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (11)"), - ) - .await - .expect("post-admission retries should finish within 10 seconds") - .unwrap(); - assert!(matches!(output.output.data, OutputData::AffectedRows(2))); - assert_eq!(handler.opens.load(Ordering::SeqCst), 1); - assert_eq!(handler.writes.load(Ordering::SeqCst), 2); - assert_eq!(handler.closes.load(Ordering::SeqCst), 2); - } - } - - #[tokio::test] - async fn fails_fast_on_definitive_open_rejection() { - let handler = Arc::new(LegacyRejectHandler::default()); - let trait_handler: Arc = handler.clone(); - let weak = Arc::downgrade(&trait_handler); - let frontend = - FrontendClient::from_grpc_handler(weak, query::options::QueryOptions::default()) - .with_tracked_writes(); - let result = tokio::time::timeout( - Duration::from_secs(10), - frontend.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (7)"), - ) - .await - .expect("definitive Open rejection should finish within 10 seconds"); - let err = result.expect_err("definitive Open rejection must not be retried forever"); - assert_eq!(err.status_code(), StatusCode::InvalidArguments); - // The durable-execution layer keys repair off a TerminalError inside - // Error::External; pin that exact shape so a refactor cannot silently - // downgrade the rejection to an unresolved (permanently stalled) error. - assert!( - matches!(&err, Error::External { source, .. } if source.as_any().is::()), - "expected Error::External carrying TerminalError, got {err:?}" - ); - assert_eq!( - handler.opens.load(Ordering::SeqCst), - 1, - "Open must not be retried after a definitive rejection" - ); - } -} diff --git a/src/frontend/Cargo.toml b/src/frontend/Cargo.toml index 1fd347c68e9..0e4a15e5d97 100644 --- a/src/frontend/Cargo.toml +++ b/src/frontend/Cargo.toml @@ -7,8 +7,6 @@ license.workspace = true [features] testing = [] enterprise = [ - "common-grpc/enterprise", - "session/enterprise", "common-meta/enterprise", "operator/enterprise", "sql/enterprise", diff --git a/src/frontend/src/instance.rs b/src/frontend/src/instance.rs index 67f1e6003a0..554a9677af7 100644 --- a/src/frontend/src/instance.rs +++ b/src/frontend/src/instance.rs @@ -17,8 +17,6 @@ mod copy_in; mod dashboard; mod entity_graph; mod export_database; -#[cfg(feature = "enterprise")] -mod flow_write; mod grpc; mod import_packed; mod influxdb; @@ -136,13 +134,6 @@ pub struct Instance { trace_aux_limiter: Option, otlp_resource_info: bool, suspend: Arc, - #[cfg(feature = "enterprise")] - flow_write_registry: Arc< - common_grpc::flow_write::FlowWriteRegistry< - flow_write::WritePayload, - common_grpc::flow_write::Reply, - >, - >, } impl Instance { @@ -332,17 +323,6 @@ impl Instance { timeout_recorder, ); - #[cfg(feature = "enterprise")] - let result = if query_ctx.channel() == Channel::Internal - && query_ctx.extension(common_grpc::flow_write::CHILD_KEY) == Some("1") - { - query_fut.await - } else { - CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) - .await - .map_err(|_| error::CancelledSnafu.build())? - }; - #[cfg(not(feature = "enterprise"))] let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) .await .map_err(|_| error::CancelledSnafu.build())?; @@ -913,17 +893,6 @@ impl Instance { let query_fut = self.exec_plan_with_timeout(plan, query_ctx.clone(), timeout_recorder); - #[cfg(feature = "enterprise")] - let result = if query_ctx.channel() == Channel::Internal - && query_ctx.extension(common_grpc::flow_write::CHILD_KEY) == Some("1") - { - query_fut.await - } else { - CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) - .await - .map_err(|_| error::CancelledSnafu.build())? - }; - #[cfg(not(feature = "enterprise"))] let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) .await .map_err(|_| error::CancelledSnafu.build())?; diff --git a/src/frontend/src/instance/builder.rs b/src/frontend/src/instance/builder.rs index 732c587e07b..05efd38d28a 100644 --- a/src/frontend/src/instance/builder.rs +++ b/src/frontend/src/instance/builder.rs @@ -438,8 +438,6 @@ impl FrontendBuilder { trace_aux_limiter, otlp_resource_info: self.options.otlp.experimental_enable_resource_info, suspend: Arc::new(AtomicBool::new(false)), - #[cfg(feature = "enterprise")] - flow_write_registry: Default::default(), }) } } diff --git a/src/frontend/src/instance/flow_write.rs b/src/frontend/src/instance/flow_write.rs deleted file mode 100644 index f908d438d4e..00000000000 --- a/src/frontend/src/instance/flow_write.rs +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -use std::sync::Arc; - -use api::v1::{greptime_request::Request, query_request::Query}; -use common_error::ext::ErrorExt; -use common_grpc::flow_write::{ - Admission, CHILD_KEY, COMMAND_KEY, Command, Reply, TerminalError, wait_completion, -}; -use common_query::{Output, OutputData}; -use servers::error::{self as server_error, Error as ServerError}; -use servers::interceptor::GrpcQueryInterceptor; -use servers::query_handler::grpc::GrpcQueryHandler; -use session::context::QueryContextRef; - -use crate::instance::Instance; - -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct WritePayload { - request: Request, - catalog: String, - schema: String, - snapshots: Vec<(u64, u64)>, - sst_min_sequences: Vec<(u64, u64)>, - extensions: Vec<(String, String)>, -} - -impl WritePayload { - fn new(request: &Request, ctx: &QueryContextRef) -> Result { - if !is_finite_insert(request) { - return Err("tracked flow writes require INSERT or InsertIntoPlan".to_string()); - } - let mut snapshots: Vec<_> = ctx.snapshots().into_iter().collect(); - snapshots.sort_unstable(); - let mut sst_min_sequences: Vec<_> = ctx.sst_min_sequences().into_iter().collect(); - sst_min_sequences.sort_unstable(); - let mut extensions: Vec<_> = ctx - .extensions() - .into_iter() - .filter(|(key, _)| { - key != COMMAND_KEY - && key != CHILD_KEY - && key != session::context::REMOTE_QUERY_ID_EXTENSION_KEY - }) - .collect(); - extensions.sort_unstable(); - Ok(Self { - request: request.clone(), - catalog: ctx.current_catalog().to_string(), - schema: ctx.current_schema(), - snapshots, - sst_min_sequences, - extensions, - }) - } -} - -fn is_finite_insert(request: &Request) -> bool { - match request { - Request::Query(query) => match query.query.as_ref() { - Some(Query::InsertIntoPlan(_)) => true, - Some(Query::Sql(sql)) => sql.split_whitespace().next().is_some_and(|statement| { - statement - .trim_end_matches(';') - .eq_ignore_ascii_case("INSERT") - }), - _ => false, - }, - _ => false, - } -} - -impl Instance { - fn intercept_control( - &self, - request: &Request, - ctx: &QueryContextRef, - ) -> server_error::Result<()> { - let interceptor = self - .plugins - .get::>(); - interceptor - .as_ref() - .pre_execute(request, ctx.clone()) - .map_err(|error| ServerError::ExecuteQuery { - source: common_error::ext::BoxedError::new(error), - location: snafu::Location::new(file!(), line!(), column!()), - }) - } - - pub(crate) async fn handle_flow_write_request( - &self, - request: Request, - ctx: QueryContextRef, - encoded_command: String, - ) -> server_error::Result { - let command = Command::decode(&encoded_command).map_err(|e| ServerError::InvalidQuery { - reason: e.to_string(), - location: snafu::Location::new(file!(), line!(), column!()), - })?; - let reply = match command { - Command::Open { nonce } => { - self.intercept_control(&request, &ctx)?; - if !is_empty_control(&request) { - return Err(ServerError::InvalidQuery { - reason: "Open requires an empty SQL request".into(), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - Reply::Opened { - capability: self - .flow_write_registry - .open(&nonce) - .map_err(registry_error)?, - } - } - Command::Close { capability } => { - self.intercept_control(&request, &ctx)?; - if !is_empty_control(&request) { - return Err(ServerError::InvalidQuery { - reason: "Close requires an empty SQL request".into(), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - self.flow_write_registry - .close(&capability) - .await - .map_err(registry_error)?; - Reply::Closed - } - Command::Write { capability } => { - let payload = WritePayload::new(&request, &ctx).map_err(|reason| { - ServerError::InvalidQuery { - reason, - location: snafu::Location::new(file!(), line!(), column!()), - } - })?; - match self - .flow_write_registry - .admit(&capability, payload) - .map_err(registry_error)? - { - Admission::Join(receiver) => { - (*wait_completion(receiver).await.map_err(registry_error)?).clone() - } - Admission::Start(sender) => { - let receiver = sender.subscribe(); - let instance = self.clone(); - let mut child_ctx = (*ctx).clone(); - child_ctx.remove_extension(COMMAND_KEY); - child_ctx.set_extension(CHILD_KEY, "1"); - let child_ctx = Arc::new(child_ctx); - common_runtime::spawn_global(async move { - let terminal = match instance.do_query(request, child_ctx).await { - Ok(output) => terminal_reply(output), - Err(error) => Reply::Complete { - rows: 0, - cost: 0, - metrics: None, - error: Some(TerminalError { - code: error.status_code() as u32, - message: error.output_msg(), - }), - }, - }; - let _ = sender.send(Some(Arc::new(terminal))); - }); - (*wait_completion(receiver).await.map_err(registry_error)?).clone() - } - } - } - }; - let batches = common_grpc::flow_write::reply_batches(&reply).map_err(|e| { - ServerError::InvalidQuery { - reason: e.to_string(), - location: snafu::Location::new(file!(), line!(), column!()), - } - })?; - Ok(Output::new_with_record_batches(batches)) - } -} - -fn is_empty_control(request: &Request) -> bool { - matches!(request, Request::Query(query) if matches!(&query.query, Some(Query::Sql(sql)) if sql.trim().is_empty())) -} - -fn terminal_reply(output: Output) -> Reply { - let (rows, cost) = output.extract_rows_and_cost(); - let metrics = output - .meta - .plan - .clone() - .and_then(query::metrics::terminal_recordbatch_metrics_from_plan); - match output.data { - OutputData::AffectedRows(_) => Reply::Complete { - rows, - cost, - metrics, - error: None, - }, - _ => Reply::Complete { - rows: 0, - cost, - metrics, - error: Some(TerminalError { - code: 1001, - message: "tracked INSERT did not produce finite affected rows".into(), - }), - }, - } -} - -fn registry_error(error: common_grpc::flow_write::RegistryError) -> ServerError { - ServerError::InvalidQuery { - reason: format!("flow write capability rejected: {error:?}"), - location: snafu::Location::new(file!(), line!(), column!()), - } -} diff --git a/src/frontend/src/instance/grpc.rs b/src/frontend/src/instance/grpc.rs index 3fb8a6feef8..7dfd97cd69d 100644 --- a/src/frontend/src/instance/grpc.rs +++ b/src/frontend/src/instance/grpc.rs @@ -66,20 +66,6 @@ impl GrpcQueryHandler for Instance { request: Request, ctx: QueryContextRef, ) -> server_error::Result { - #[cfg(feature = "enterprise")] - if let Some(command) = ctx - .extension(common_grpc::flow_write::COMMAND_KEY) - .map(str::to_string) - { - if ctx.channel() != session::context::Channel::Internal { - return Err(server_error::Error::InvalidQuery { - reason: "flow write commands are only accepted on the internal channel".into(), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - return self.handle_flow_write_request(request, ctx, command).await; - } - let result: Result = async { let interceptor_ref = self.plugins.get::>(); let interceptor = interceptor_ref.as_ref(); diff --git a/src/operator/Cargo.toml b/src/operator/Cargo.toml index 225f1bb6dec..b89bf4b13d3 100644 --- a/src/operator/Cargo.toml +++ b/src/operator/Cargo.toml @@ -7,7 +7,6 @@ license.workspace = true [features] testing = [] enterprise = [ - "common-grpc/enterprise", "common-meta/enterprise", "sql/enterprise", "query/enterprise", diff --git a/src/operator/src/insert.rs b/src/operator/src/insert.rs index 9a0cd64a828..88cb565c779 100644 --- a/src/operator/src/insert.rs +++ b/src/operator/src/insert.rs @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[cfg(feature = "enterprise")] -mod flow_write; mod otlp; pub use otlp::MetricInsertPreflight; @@ -857,47 +855,6 @@ impl Inserter { has_instant_rows, )?; - // Tracked Flow children use a same-capability write protocol. Keep the - // ordinary dispatch path unchanged for every other request. - #[cfg(feature = "enterprise")] - if flow_write::is_child(ctx) { - let dispatcher = self.write_dispatcher.clone(); - let request = request_factory.build_insert(normal_requests); - let writes = dispatcher.prepare(vec![request]).await?; - let tracked_tasks = writes.into_iter().map(|(peer, mut request)| { - let mut query_context = crate::utils::to_meta_query_context(ctx.clone()); - query_context.extensions.insert( - common_grpc::flow_write::CHILD_KEY.to_string(), - "1".to_string(), - ); - if let Some(header) = request.header.as_mut() { - header.query_context = Some(query_context.into()); - } - let node_manager = self.node_manager.clone(); - async move { flow_write::dispatch(&node_manager, &peer, request).await } - }); - let results = future::join_all(tracked_tasks).await; - let mut affected_rows = 0; - let mut first_error = None; - for result in results { - match result { - Ok(response) => affected_rows += response.affected_rows, - Err(error) if first_error.is_none() => first_error = Some(error), - Err(_) => {} - } - } - if let Some(error) = first_error { - return Err(error); - } - crate::metrics::DIST_INGEST_ROW_COUNT - .with_label_values(&[ctx.get_db_string().as_str()]) - .inc_by(affected_rows as u64); - return Ok(Output::new( - OutputData::AffectedRows(affected_rows), - OutputMeta::new_with_cost(write_cost as _), - )); - } - let dispatcher = self.write_dispatcher.clone(); let request = request_factory.build_insert(normal_requests); let writes = dispatcher.prepare(vec![request]).await?; diff --git a/src/operator/src/insert/flow_write.rs b/src/operator/src/insert/flow_write.rs deleted file mode 100644 index 62935e46981..00000000000 --- a/src/operator/src/insert/flow_write.rs +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -use std::time::Duration; - -use api::v1::region::RegionRequest; -use common_error::ext::BoxedError; -use common_grpc::flow_write::{self, Command, Reply}; -use common_meta::node_manager::{DatanodeRef, NodeManagerRef}; -use common_meta::peer::Peer; -use session::context::generate_remote_query_id; - -use crate::error::{Error, Result}; - -const RETRY_DELAY: Duration = Duration::from_secs(1); - -fn error(message: impl Into) -> Error { - Error::Unexpected { - violated: message.into(), - location: snafu::Location::new(file!(), line!(), column!()), - } -} - -fn command_request( - request: &RegionRequest, - command: &Command, - control: bool, -) -> Result { - let mut request = request.clone(); - if control { - request.body = Some(api::v1::region::region_request::Body::Inserts( - Default::default(), - )); - } - let header = request.header.get_or_insert_with(Default::default); - let query_context = header - .query_context - .get_or_insert_with(api::v1::QueryContext::default); - query_context.extensions.insert( - flow_write::COMMAND_KEY.to_string(), - command.encode().map_err(|e| error(e.to_string()))?, - ); - Ok(request) -} - -fn reply(response: &api::region::RegionResponse) -> Option { - response - .extensions - .get(flow_write::COMMAND_KEY) - .and_then(|value| std::str::from_utf8(value).ok()) - .and_then(|value| serde_json::from_str(value).ok()) -} - -pub(crate) async fn dispatch( - node_manager: &NodeManagerRef, - peer: &Peer, - request: RegionRequest, -) -> Result { - dispatch_datanode(node_manager.datanode(peer).await, request).await -} - -async fn dispatch_datanode( - datanode: DatanodeRef, - request: RegionRequest, -) -> Result { - let nonce = generate_remote_query_id(); - let open = command_request(&request, &Command::Open { nonce }, true)?; - let capability = loop { - match datanode.handle(open.clone()).await { - Ok(response) => match reply(&response) { - Some(Reply::Opened { capability }) if !capability.is_empty() => break capability, - _ => return Err(error("Datanode does not support tracked Flow writes")), - }, - Err(_) => tokio::time::sleep(RETRY_DELAY).await, - } - }; - - let write = command_request( - &request, - &Command::Write { - capability: capability.clone(), - }, - false, - )?; - let complete = loop { - match datanode.handle(write.clone()).await { - Ok(response) => match reply(&response) { - Some(Reply::Complete { - rows, - cost: _, - metrics: _, - error, - }) => break (response, rows, error), - _ => tokio::time::sleep(RETRY_DELAY).await, - }, - Err(_) => tokio::time::sleep(RETRY_DELAY).await, - } - }; - - let close = command_request( - &request, - &Command::Close { - capability: capability.clone(), - }, - true, - )?; - loop { - match datanode.handle(close.clone()).await { - Ok(response) if matches!(reply(&response), Some(Reply::Closed)) => break, - _ => tokio::time::sleep(RETRY_DELAY).await, - } - } - - let (mut response, rows, terminal_error) = complete; - if let Some(terminal_error) = terminal_error { - return Err(Error::External { - source: BoxedError::new(terminal_error), - location: snafu::location!(), - }); - } - response.affected_rows = rows as _; - Ok(response) -} - -pub(crate) fn is_child(ctx: &session::context::QueryContextRef) -> bool { - ctx.channel() == common_base::protocol::Channel::Internal - && ctx.extension(flow_write::CHILD_KEY) == Some("1") -} - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::{Arc, Mutex}; - - use api::region::RegionResponse; - use api::v1::region::{RegionRequest, region_request::Body}; - use common_error::ext::BoxedError; - use common_error::ext::ErrorExt; - use common_grpc::flow_write::{self, Command, Reply}; - use common_meta::node_manager::{Datanode, DatanodeRef}; - use common_query::request::QueryRequest; - use common_recordbatch::SendableRecordBatchStream; - use futures_util::future::join_all; - use tokio::sync::Notify; - - use super::dispatch_datanode; - - #[derive(Default)] - struct MockDatanode { - capabilities: Mutex>, - business_write_attempts: AtomicUsize, - write_commands: Mutex>, - requests: Mutex>, - drop_open_reply: AtomicUsize, - drop_write_reply: AtomicUsize, - drop_close_reply: AtomicUsize, - latch_write: bool, - terminal_error: bool, - write_started: Notify, - release_write: Notify, - close_started: Notify, - } - - impl MockDatanode { - fn response(reply: Reply) -> RegionResponse { - let mut response = RegionResponse::new(0); - response.extensions.insert( - flow_write::COMMAND_KEY.to_string(), - serde_json::to_vec(&reply).unwrap(), - ); - response - } - - fn command(request: &RegionRequest) -> Command { - let serialized = request - .header - .as_ref() - .and_then(|header| header.query_context.as_ref()) - .and_then(|context| context.extensions.get(flow_write::COMMAND_KEY)) - .unwrap(); - Command::decode(serialized).unwrap() - } - } - - #[async_trait::async_trait] - impl Datanode for MockDatanode { - async fn handle_request( - &self, - request: Arc, - ) -> common_meta::error::Result { - self.requests.lock().unwrap().push(request.as_ref().clone()); - match Self::command(&request) { - Command::Open { nonce } => { - if !matches!(request.body, Some(Body::Inserts(ref inserts)) if inserts.requests.is_empty()) - { - return Err(common_meta::error::Error::External { - source: BoxedError::new(common_error::mock::MockError::new( - common_error::status_code::StatusCode::InvalidArguments, - )), - location: snafu::location!(), - }); - } - let mut capabilities = self.capabilities.lock().unwrap(); - let capability = capabilities - .entry(nonce) - .or_insert_with(|| "cap-1".into()) - .clone(); - if self - .drop_open_reply - .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)) - .is_ok() - { - return Err(common_meta::error::Error::External { - source: BoxedError::new(common_error::mock::MockError::new( - common_error::status_code::StatusCode::TableUnavailable, - )), - location: snafu::location!(), - }); - } - Ok(Self::response(Reply::Opened { capability })) - } - Command::Write { capability } => { - self.write_commands.lock().unwrap().push(capability.clone()); - if matches!(request.body, Some(Body::Inserts(ref inserts)) if !inserts.requests.is_empty()) - && self.business_write_attempts.fetch_add(1, Ordering::SeqCst) == 0 - && self.latch_write - { - self.write_started.notify_one(); - self.release_write.notified().await; - } - if self - .drop_write_reply - .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)) - .is_ok() - { - return Err(common_meta::error::Error::External { - source: BoxedError::new(common_error::mock::MockError::new( - common_error::status_code::StatusCode::TableUnavailable, - )), - location: snafu::location!(), - }); - } - Ok(Self::response(Reply::Complete { - rows: 7, - cost: 0, - metrics: None, - error: self.terminal_error.then(|| flow_write::TerminalError { - code: common_error::status_code::StatusCode::TableNotFound as u32, - message: "terminal child error".to_string(), - }), - })) - } - Command::Close { .. } => { - self.close_started.notify_one(); - if self - .drop_close_reply - .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)) - .is_ok() - { - return Err(common_meta::error::Error::External { - source: BoxedError::new(common_error::mock::MockError::new( - common_error::status_code::StatusCode::TableUnavailable, - )), - location: snafu::location!(), - }); - } - Ok(Self::response(Reply::Closed)) - } - } - } - - async fn handle_query( - &self, - _: QueryRequest, - ) -> common_meta::error::Result { - unreachable!() - } - } - - fn request() -> RegionRequest { - RegionRequest { - header: None, - body: Some(Body::Inserts(api::v1::region::InsertRequests { - requests: vec![Default::default()], - })), - } - } - - #[tokio::test] - async fn lost_control_and_write_replies_reuse_capability_and_exact_request() { - let datanode = Arc::new(MockDatanode::default()); - datanode.drop_open_reply.store(1, Ordering::SeqCst); - datanode.drop_write_reply.store(1, Ordering::SeqCst); - datanode.drop_close_reply.store(1, Ordering::SeqCst); - let response = dispatch_datanode(datanode.clone(), request()) - .await - .unwrap(); - assert_eq!(response.affected_rows, 7); - assert_eq!(datanode.business_write_attempts.load(Ordering::SeqCst), 2); - let writes = datanode.write_commands.lock().unwrap(); - assert_eq!(writes.len(), 2); - assert!(writes.iter().all(|capability| capability == "cap-1")); - let requests = datanode.requests.lock().unwrap(); - let writes: Vec<_> = requests - .iter() - .filter(|request| matches!(MockDatanode::command(request), Command::Write { .. })) - .collect(); - assert_eq!(writes.len(), 2); - assert_eq!(writes[0].body, writes[1].body); - assert_eq!(writes[0].header, writes[1].header); - assert_eq!( - requests - .iter() - .filter(|request| matches!( - MockDatanode::command(request), - Command::Open { .. } | Command::Close { .. } - )) - .count(), - 4 - ); - assert!(requests - .iter() - .filter(|request| matches!(MockDatanode::command(request), Command::Open { .. } | Command::Close { .. })) - .all(|request| matches!(request.body, Some(Body::Inserts(ref inserts)) if inserts.requests.is_empty()))); - } - - #[tokio::test] - async fn unsupported_open_never_submits_business_request() { - struct Unsupported; - #[async_trait::async_trait] - impl Datanode for Unsupported { - async fn handle_request( - &self, - _: Arc, - ) -> common_meta::error::Result { - Ok(RegionResponse::new(0)) - } - async fn handle_query( - &self, - _: QueryRequest, - ) -> common_meta::error::Result { - unreachable!() - } - } - let datanode: DatanodeRef = Arc::new(Unsupported); - let error = dispatch_datanode(datanode, request()).await.unwrap_err(); - assert_eq!( - error.status_code(), - common_error::status_code::StatusCode::Unexpected - ); - } - - #[tokio::test] - async fn all_peer_writes_drain_before_terminal_error_returns() { - let failing = Arc::new(MockDatanode { - terminal_error: true, - ..Default::default() - }); - let latched = Arc::new(MockDatanode { - latch_write: true, - ..Default::default() - }); - let first_datanode: DatanodeRef = failing.clone(); - let second_datanode: DatanodeRef = latched.clone(); - let aggregate = tokio::spawn(async move { - join_all([ - dispatch_datanode(first_datanode, request()), - dispatch_datanode(second_datanode, request()), - ]) - .await - }); - latched.write_started.notified().await; - failing.close_started.notified().await; - assert!(!aggregate.is_finished()); - latched.release_write.notify_one(); - let results = aggregate.await.unwrap(); - assert_eq!(results.len(), 2); - assert_eq!(failing.business_write_attempts.load(Ordering::SeqCst), 1); - assert_eq!(latched.business_write_attempts.load(Ordering::SeqCst), 1); - assert!(results.into_iter().any(|result| result.is_err())); - } -} diff --git a/src/session/Cargo.toml b/src/session/Cargo.toml index 630d0713a62..93c46ff7ff7 100644 --- a/src/session/Cargo.toml +++ b/src/session/Cargo.toml @@ -4,9 +4,6 @@ version.workspace = true edition.workspace = true license.workspace = true -[features] -enterprise = [] - [lints] workspace = true diff --git a/src/session/src/context.rs b/src/session/src/context.rs index f46a2a590b2..02ee621e0e4 100644 --- a/src/session/src/context.rs +++ b/src/session/src/context.rs @@ -467,11 +467,6 @@ impl QueryContext { self.extensions.insert(key.into(), value.into()); } - #[cfg(feature = "enterprise")] - pub fn remove_extension(&mut self, key: &str) { - self.extensions.remove(key); - } - pub fn extension>(&self, key: S) -> Option<&str> { self.extensions.get(key.as_ref()).map(|v| v.as_str()) } From 4135e65a76cf7e9d832cd00b0ff7415e971ef478 Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 28 Oct 2026 10:40:43 +0000 Subject: [PATCH 05/19] fix(query): keep requested sort when filtering on a lossy cast (#10026) fix(query): pin DataFusion cast constraint propagation fix Update the pinned GreptimeTeam/datafusion revision from e3221b8 to cc55344 (the 55.1 fork carrying apache/datafusion#25531 plus a stronger regression test). CastExpr::propagate_constraints used to cast a filter's output interval straight back to the input type. For CAST(k AS BIGINT) = 1 the singleton output [1, 1] was inverted to [1.0, 1.0] although k = 1.5 matches too, so FilterExec advertised k as constant, the equivalence classes dropped the ordering required by ORDER BY k, and rows returned in scan order. The sqlness case keeps every #9600 assertion and the explicit ORDER BY, and adds ascending and descending checks for the partitioned table, the control table and a table whose matching rows are stored in neither ascending nor descending k order. Cargo.lock only rewrites the 35 datafusion source lines. Signed-off-by: discord9 --- Cargo.lock | 70 +++++++++--------- Cargo.toml | 32 ++++---- .../optimizer/partition_pruning_cast.result | 74 +++++++++++++++++++ .../optimizer/partition_pruning_cast.sql | 36 +++++++++ 4 files changed, 161 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6ada3b0a295..69996d9cbb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3756,7 +3756,7 @@ checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" [[package]] name = "datafusion" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -3808,7 +3808,7 @@ dependencies = [ [[package]] name = "datafusion-catalog" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3832,7 +3832,7 @@ dependencies = [ [[package]] name = "datafusion-catalog-listing" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3855,7 +3855,7 @@ dependencies = [ [[package]] name = "datafusion-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-ipc 59.2.0", @@ -3881,7 +3881,7 @@ dependencies = [ [[package]] name = "datafusion-common-runtime" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "futures", "log", @@ -3891,7 +3891,7 @@ dependencies = [ [[package]] name = "datafusion-datasource" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-compression", @@ -3927,7 +3927,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-arrow" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-ipc 59.2.0", @@ -3951,7 +3951,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-csv" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3974,7 +3974,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-json" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3997,7 +3997,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-parquet" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -4029,12 +4029,12 @@ dependencies = [ [[package]] name = "datafusion-doc" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" [[package]] name = "datafusion-execution" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-buffer 59.2.0", @@ -4059,7 +4059,7 @@ dependencies = [ [[package]] name = "datafusion-expr" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -4083,7 +4083,7 @@ dependencies = [ [[package]] name = "datafusion-expr-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4094,7 +4094,7 @@ dependencies = [ [[package]] name = "datafusion-functions" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-buffer 59.2.0", @@ -4125,7 +4125,7 @@ dependencies = [ [[package]] name = "datafusion-functions-aggregate" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4145,7 +4145,7 @@ dependencies = [ [[package]] name = "datafusion-functions-aggregate-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4156,7 +4156,7 @@ dependencies = [ [[package]] name = "datafusion-functions-nested" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-ord 59.2.0", @@ -4180,7 +4180,7 @@ dependencies = [ [[package]] name = "datafusion-functions-table" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -4195,7 +4195,7 @@ dependencies = [ [[package]] name = "datafusion-functions-window" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4211,7 +4211,7 @@ dependencies = [ [[package]] name = "datafusion-functions-window-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "datafusion-common", "datafusion-physical-expr-common", @@ -4220,7 +4220,7 @@ dependencies = [ [[package]] name = "datafusion-macros" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "datafusion-doc", "quote", @@ -4230,7 +4230,7 @@ dependencies = [ [[package]] name = "datafusion-optimizer" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "chrono", @@ -4278,7 +4278,7 @@ dependencies = [ [[package]] name = "datafusion-physical-expr" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -4301,7 +4301,7 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-adapter" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4315,7 +4315,7 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "chrono", @@ -4332,7 +4332,7 @@ dependencies = [ [[package]] name = "datafusion-physical-optimizer" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4351,7 +4351,7 @@ dependencies = [ [[package]] name = "datafusion-physical-plan" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-data 59.2.0", @@ -4388,7 +4388,7 @@ dependencies = [ [[package]] name = "datafusion-proto" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-catalog", @@ -4414,7 +4414,7 @@ dependencies = [ [[package]] name = "datafusion-proto-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4424,7 +4424,7 @@ dependencies = [ [[package]] name = "datafusion-proto-models" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "datafusion-common", "datafusion-proto-common", @@ -4434,7 +4434,7 @@ dependencies = [ [[package]] name = "datafusion-pruning" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4449,7 +4449,7 @@ dependencies = [ [[package]] name = "datafusion-session" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow-schema 59.2.0", "async-trait", @@ -4463,7 +4463,7 @@ dependencies = [ [[package]] name = "datafusion-sql" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "bigdecimal 0.4.8", @@ -4482,7 +4482,7 @@ dependencies = [ [[package]] name = "datafusion-substrait" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "async-recursion", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 0e75ddbd912..15539abb2c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -367,22 +367,22 @@ rev = "f743c3a5fe8c1f57363eac5866c356b7d91f9b39" [patch.crates-io] substrait = { git = "https://github.com/GreptimeTeam/substrait-rs.git", rev = "91ec978b0649417ad3da8390e7a515baec723b1b" } -datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } +datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } datafusion-pg-catalog = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" } arrow-pg = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" } sqlparser = { git = "https://github.com/GreptimeTeam/sqlparser-rs.git", rev = "9e9019bb1c7040ed956f654e39378dd42ab17884" } diff --git a/tests/cases/distributed/optimizer/partition_pruning_cast.result b/tests/cases/distributed/optimizer/partition_pruning_cast.result index 2b18475fda8..2fda5e7a12a 100644 --- a/tests/cases/distributed/optimizer/partition_pruning_cast.result +++ b/tests/cases/distributed/optimizer/partition_pruning_cast.result @@ -97,6 +97,80 @@ ORDER BY k; | 1970-01-01T00:00:01 | 1.5 | 15 | 1 | +---------------------+-----+----+--------+ +-- The same rows must also come back in descending order: a filter on a lossy +-- cast must not turn `k` into a constant and drop the requested sort. +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_partitioned +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + ++---------------------+-----+----+--------+ +| ts | k | v | cast_k | ++---------------------+-----+----+--------+ +| 1970-01-01T00:00:01 | 1.5 | 15 | 1 | +| 1970-01-01T00:00:01 | 1.0 | 10 | 1 | ++---------------------+-----+----+--------+ + +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_control +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + ++---------------------+-----+----+--------+ +| ts | k | v | cast_k | ++---------------------+-----+----+--------+ +| 1970-01-01T00:00:01 | 1.5 | 15 | 1 | +| 1970-01-01T00:00:01 | 1.0 | 10 | 1 | ++---------------------+-----+----+--------+ + +-- A table whose matching rows are stored in neither ascending nor descending +-- order, so a dropped sort cannot accidentally satisfy the ASC assertion. +CREATE TABLE partition_pruning_cast_unsorted ( + ts TIMESTAMP TIME INDEX, + k FLOAT PRIMARY KEY, + v BIGINT, +); + +Affected Rows: 0 + +INSERT INTO partition_pruning_cast_unsorted VALUES + (1000, 1.5, 15), + (1000, 2.5, 25), + (1000, 1.0, 10), + (1000, 1.25, 12); + +Affected Rows: 4 + +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_unsorted +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k; + ++---------------------+------+----+--------+ +| ts | k | v | cast_k | ++---------------------+------+----+--------+ +| 1970-01-01T00:00:01 | 1.0 | 10 | 1 | +| 1970-01-01T00:00:01 | 1.25 | 12 | 1 | +| 1970-01-01T00:00:01 | 1.5 | 15 | 1 | ++---------------------+------+----+--------+ + +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_unsorted +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + ++---------------------+------+----+--------+ +| ts | k | v | cast_k | ++---------------------+------+----+--------+ +| 1970-01-01T00:00:01 | 1.5 | 15 | 1 | +| 1970-01-01T00:00:01 | 1.25 | 12 | 1 | +| 1970-01-01T00:00:01 | 1.0 | 10 | 1 | ++---------------------+------+----+--------+ + +DROP TABLE partition_pruning_cast_unsorted; + +Affected Rows: 0 + -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED diff --git a/tests/cases/distributed/optimizer/partition_pruning_cast.sql b/tests/cases/distributed/optimizer/partition_pruning_cast.sql index 058045f733a..f72355b892d 100644 --- a/tests/cases/distributed/optimizer/partition_pruning_cast.sql +++ b/tests/cases/distributed/optimizer/partition_pruning_cast.sql @@ -43,6 +43,42 @@ FROM partition_pruning_cast_control WHERE CAST(k AS BIGINT) = 1 ORDER BY k; +-- The same rows must also come back in descending order: a filter on a lossy +-- cast must not turn `k` into a constant and drop the requested sort. +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_partitioned +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_control +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + +-- A table whose matching rows are stored in neither ascending nor descending +-- order, so a dropped sort cannot accidentally satisfy the ASC assertion. +CREATE TABLE partition_pruning_cast_unsorted ( + ts TIMESTAMP TIME INDEX, + k FLOAT PRIMARY KEY, + v BIGINT, +); + +INSERT INTO partition_pruning_cast_unsorted VALUES + (1000, 1.5, 15), + (1000, 2.5, 25), + (1000, 1.0, 10), + (1000, 1.25, 12); + +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_unsorted +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k; +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_unsorted +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + +DROP TABLE partition_pruning_cast_unsorted; + -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED From c818b6ac2a290a4b40802b959d8d687fdfa6efed Mon Sep 17 00:00:00 2001 From: Ning Sun Date: Wed, 28 Oct 2026 08:00:41 +0000 Subject: [PATCH 06/19] feat(postgres): influxdb line protocol ingest via COPY FROM STDIN (#9982) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(postgres): influxdb line protocol ingest via COPY FROM STDIN COPY FROM STDIN WITH (FORMAT influxdb [, precision 'ns']) ingests InfluxDB line protocol over the postgres wire protocol, reusing the HTTP ingestion pipeline wholesale for correctness and performance parity: the whole payload is buffered and completed once at CopyDone through the frontend's InfluxdbLineProtocolHandler::exec — conversion, permissions, line-protocol interceptors, timestamp alignment to table time-index units, merge mode and inserts are the same path an HTTP write of the same bytes takes, under the connection's regular postgres query context. Formats are an explicit, closed enum (CopyFormat::Csv | CopyFormat::Influxdb(options)); each variant states its own rules in the copy lifecycle's match arms — csv requires a target table and parses incrementally, influxdb forbids one (each line names its own measurement) and buffers one bounded request body. The COPY layer owns only the buffering: record boundaries, including newlines inside quoted field values and after escapes, belong to the line-protocol parser alone — one COPY statement is one bounded ingestion request (64 MiB; larger imports are multiple COPY statements). - Wiring: PostgresServer::with_influxdb_handler attaches the shared line-protocol handler; unwired servers reject the format when a copy starts. - Grammar: COPY FROM STDIN without a table is scanned (an unquoted FROM cannot be a table name); table-bound formats reject it with guidance, influxdb rejects a named table. - Options: precision accepts the HTTP endpoint's values via the shared parse_time_precision (moved to servers::influxdb), defaulting to nanoseconds. Review findings (fengjiachun) are fixed at the root by removing the pre-splitter rather than repairing it: the retired naive line splitter broke quoted multiline records at chunk/flush boundaries (found by removing record splitting entirely), drained the buffer quadratically (found by append-only buffering), and capped nothing (found by an explicit payload limit). e2e: multi-measurement ingest with chunked feeds; a 32,768-physical-line flush-threshold regression with a multiline quoted record split across CopyData chunks; precision 'ms' epoch verification; invalid UTF-8 and trailing-record-without-newline handling; payload limit; table-named rejection; malformed-line abort with connection recovery. Signed-off-by: Ning Sun * chore: typo --------- Signed-off-by: Ning Sun --- src/frontend/src/server.rs | 1 + src/servers/src/http/influxdb.rs | 23 +- src/servers/src/influxdb.rs | 23 +- src/servers/src/postgres.rs | 10 +- src/servers/src/postgres/copy_in/codec.rs | 118 +++---- src/servers/src/postgres/copy_in/csv.rs | 52 ++- src/servers/src/postgres/copy_in/influxdb.rs | 95 ++++++ src/servers/src/postgres/copy_in/mod.rs | 305 +++++++++++++----- src/servers/src/postgres/copy_in/parse.rs | 73 ++++- src/servers/src/postgres/server.rs | 27 +- tests-integration/src/test_util.rs | 69 ++-- .../src/tests/postgres_copy_in_test.rs | 300 +++++++++++++++++ 12 files changed, 851 insertions(+), 245 deletions(-) create mode 100644 src/servers/src/postgres/copy_in/influxdb.rs diff --git a/src/frontend/src/server.rs b/src/frontend/src/server.rs index 0b1e2b9713e..d84f01fce95 100644 --- a/src/frontend/src/server.rs +++ b/src/frontend/src/server.rs @@ -429,6 +429,7 @@ where user_provider.clone(), Some(self.instance.process_manager().clone()), ) + .with_influxdb_handler(instance.clone()) .with_batching_enabled(postgres_batching), ) as Box; diff --git a/src/servers/src/http/influxdb.rs b/src/servers/src/http/influxdb.rs index 671beb7bae2..44815cae3a1 100644 --- a/src/servers/src/http/influxdb.rs +++ b/src/servers/src/http/influxdb.rs @@ -24,7 +24,7 @@ use common_grpc::precision::Precision; use common_telemetry::tracing; use session::context::{Channel, QueryContext, QueryContextRef}; -use crate::error::{Result, TimePrecisionSnafu}; +use crate::error::Result; use crate::http::header::write_cost_header_map; use crate::influxdb::InfluxdbRequest; use crate::query_handler::InfluxdbLineProtocolHandlerRef; @@ -107,30 +107,13 @@ pub async fn influxdb_write( )) } -fn parse_time_precision(value: &str) -> Result { - // Precision conversion needs to be compatible with influxdb v1 v2 api. - // For details, see the Influxdb documents. - // https://docs.influxdata.com/influxdb/v1.8/tools/api/#apiv2write-http-endpoint - // https://docs.influxdata.com/influxdb/v1.8/tools/api/#write-http-endpoint - match value { - "n" | "ns" => Ok(Precision::Nanosecond), - "u" | "us" => Ok(Precision::Microsecond), - "ms" => Ok(Precision::Millisecond), - "s" => Ok(Precision::Second), - "m" => Ok(Precision::Minute), - "h" => Ok(Precision::Hour), - unknown => TimePrecisionSnafu { - name: unknown.to_string(), - } - .fail(), - } -} +pub(crate) use crate::influxdb::parse_time_precision; #[cfg(test)] mod tests { use common_grpc::precision::Precision; - use crate::http::influxdb::parse_time_precision; + use super::parse_time_precision; #[test] fn test_parse_time_precision() { diff --git a/src/servers/src/influxdb.rs b/src/servers/src/influxdb.rs index 9bff0bbc6e4..9dd26d9cda7 100644 --- a/src/servers/src/influxdb.rs +++ b/src/servers/src/influxdb.rs @@ -20,7 +20,7 @@ use hyper::Request; use influxdb_line_protocol::{FieldValue, parse_lines}; use snafu::ResultExt; -use crate::error::{Error, InfluxdbLineProtocolSnafu}; +use crate::error::{Error, InfluxdbLineProtocolSnafu, TimePrecisionSnafu}; use crate::row_writer::{self, MultiTableData}; const INFLUXDB_API_PATH_NAME: &str = "influxdb"; @@ -113,6 +113,27 @@ fn unwrap_or_default_precision(precision: Option) -> Precision { } } +/// Parses an InfluxDB time-precision name shared by the HTTP write +/// endpoints (v1/v2) and the `precision` option of COPY FROM STDIN. +pub(crate) fn parse_time_precision(value: &str) -> crate::error::Result { + // Precision conversion needs to be compatible with influxdb v1 v2 api. + // For details, see the Influxdb documents. + // https://docs.influxdata.com/influxdb/v1.8/tools/api/#apiv2write-http-endpoint + // https://docs.influxdata.com/influxdb/v1.8/tools/api/#write-http-endpoint + match value { + "n" | "ns" => Ok(Precision::Nanosecond), + "u" | "us" => Ok(Precision::Microsecond), + "ms" => Ok(Precision::Millisecond), + "s" => Ok(Precision::Second), + "m" => Ok(Precision::Minute), + "h" => Ok(Precision::Hour), + unknown => TimePrecisionSnafu { + name: unknown.to_string(), + } + .fail(), + } +} + #[cfg(test)] mod tests { use api::v1::value::ValueData; diff --git a/src/servers/src/postgres.rs b/src/servers/src/postgres.rs index e13ec7392d5..fbef2e9ac4c 100644 --- a/src/servers/src/postgres.rs +++ b/src/servers/src/postgres.rs @@ -43,8 +43,8 @@ use session::context::Channel; use self::auth_handler::{PgUserProviderSource, ZeroPidSecretKeyGenerator}; use self::handler::DefaultQueryParser; -use crate::query_handler::CopyInHandlerRef; use crate::query_handler::sql::ServerSqlQueryHandlerRef; +use crate::query_handler::{CopyInHandlerRef, InfluxdbLineProtocolHandlerRef}; pub(crate) struct GreptimeDBStartupParameters { version: String, @@ -81,6 +81,11 @@ pub struct PostgresServerHandlerInner { query_handler: ServerSqlQueryHandlerRef, auth_source: Option>, copy_in_handler: CopyInHandlerRef, + /// Executes influxdb line-protocol batches flushed by a table-less + /// COPY FROM STDIN — the same handler the HTTP write endpoints use. + /// Absent on servers not wired for it; such connections reject the + /// influxdb format when a copy starts. + influxdb_handler: Option, force_tls: bool, auth_driver: AuthDriver, UserInfoRef>, /// SCRAM selected; failures get the uniform metric label. @@ -99,6 +104,8 @@ pub struct PostgresServerHandlerInner { pub(crate) struct MakePostgresServerHandler { query_handler: ServerSqlQueryHandlerRef, copy_in_handler: CopyInHandlerRef, + #[builder(default)] + influxdb_handler: Option, user_provider: Option, #[builder(default = "Arc::new(GreptimeDBStartupParameters::new())")] param_provider: Arc, @@ -149,6 +156,7 @@ impl MakePostgresServerHandler { .clone() .map(|p| Arc::new(PgUserProviderSource::new(p))), copy_in_handler: self.copy_in_handler.clone(), + influxdb_handler: self.influxdb_handler.clone(), force_tls: self.force_tls, auth_driver: AuthDriver::new(self.param_provider.clone()) .with_pid_secret_key_generator(Arc::new(ZeroPidSecretKeyGenerator)), diff --git a/src/servers/src/postgres/copy_in/codec.rs b/src/servers/src/postgres/copy_in/codec.rs index 37a94811309..a7672c619ef 100644 --- a/src/servers/src/postgres/copy_in/codec.rs +++ b/src/servers/src/postgres/copy_in/codec.rs @@ -12,58 +12,63 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! The COPY FROM STDIN codec framework. +//! The COPY FROM STDIN formats. //! -//! A *codec* binds one COPY data format to its implementation. Codecs are -//! stateless strategies: they validate the options they accept at -//! statement-parse time, describe which column types they can ingest, and -//! create the stateful [`RecordParser`] per stream. -//! -//! Formats are not limited to PostgreSQL's own — GreptimeDB-specific -//! formats (a line protocol, a JSON-lines dialect, ...) register exactly -//! like `csv` does, and may define their own options through the open -//! `WITH (...)` clause. +//! [`CopyFormat`] is the closed, explicit set of supported formats — a +//! small enum over the real implementations rather than a generic +//! format framework. Each variant carries its validated options and +//! its rules are stated where they apply: a variant's match arms in +//! the copy lifecycle (see the parent module) decide whether a target +//! table is required, how the `CopyData` bytes are consumed, and which +//! existing ingestion pipeline completes the copy. Adding a format is +//! a normal extension: a new variant plus its arms. //! //! # Parsing and conversion //! -//! A [`RecordParser`] consumes raw `CopyData` bytes and emits complete, -//! insertable rows: one [`ParsedRow`] per record, in the order of the -//! targeted columns. Parsers validate record shape (field counts) and -//! convert field values themselves — `csv` delegates both splitting and -//! typed conversion to arrow-csv's incremental decoder (the engine -//! behind `COPY ... FROM 'file.csv'`) and turns decoded batches into -//! rows with the shared `api::helper::vectors_to_rows`. A future format -//! that carries values as text (e.g. a line protocol) would reintroduce -//! shared field-conversion helpers here; see the removed `text` codec in -//! git history for the shape they had. +//! Table-bound formats parse incrementally through a [`RecordParser`]: +//! it consumes raw `CopyData` bytes and emits complete, insertable +//! rows — one [`ParsedRow`] per record, in the order of the targeted +//! columns. `csv` delegates splitting and typed conversion to +//! arrow-csv's incremental decoder (the engine behind +//! `COPY ... FROM 'file.csv'`) and turns decoded batches into rows +//! with the shared `api::helper::vectors_to_rows`. +//! +//! Formats that delegate to an existing ingestion pipeline (the +//! influxdb line protocol) do not parse here at all: the whole payload +//! is buffered as one bounded request body and completed through that +//! pipeline, so record boundaries and values stay with the pipeline's +//! own parser. //! //! # Options //! //! The `WITH (...)` clause is open: every `KEY value` entry the client -//! writes is collected into a [`CopyOptionSet`] (see `options`) regardless -//! of whether any format understands it — the statement is parsed -//! textually (see `parse`) precisely so options beyond sqlparser's COPY -//! grammar can reach the codecs. A codec builder takes the options it -//! understands (`take_string`, `take_single_byte`, `take_flag`, or raw -//! `take_value` for codec-specific shapes) and rejects the rest with -//! `reject_leftovers`, so a future format like -//! `COPY t FROM STDIN WITH (FORMAT influxdb_line, precision 'ns')` only -//! needs its own codec and registry entry. -//! -//! To add a format: -//! -//! 1. implement [`CopyInCodec`] for a config struct holding the format's -//! validated options (see `csv::CsvCodec` for the example), -//! 2. write a builder `fn(CopyOptionSet) -> PgWireResult>` that applies defaults and rejects options the format -//! does not accept, -//! 3. register the builder under every accepted `FORMAT` name (including -//! aliases) in `REGISTERED_FORMATS` in the parent module. +//! writes is collected into a [`CopyOptionSet`] (see `options`) +//! regardless of whether any format understands it — the statement is +//! parsed textually (see `parse`) precisely so options beyond +//! sqlparser's COPY grammar can reach the formats. A format builder +//! takes the options it understands (`take_string`, +//! `take_single_byte`, `take_flag`, or raw `take_value` for +//! format-specific shapes) and rejects the rest with +//! `reject_leftovers`. -use datatypes::prelude::ConcreteDataType; -use datatypes::schema::ColumnSchema; use pgwire::error::PgWireResult; +use crate::postgres::copy_in::csv::CsvCodec; +use crate::postgres::copy_in::influxdb::InfluxdbOptions; + +/// A resolved COPY FROM STDIN format with its validated options. +#[derive(Debug, Clone)] +pub(super) enum CopyFormat { + /// Table-bound CSV: records are parsed incrementally against the + /// targeted table's columns and inserted in batches. + Csv(CsvCodec), + /// Table-less influxdb line protocol: the whole payload is one + /// bounded request body, completed through the line-protocol + /// pipeline the HTTP write endpoints use (one COPY statement is one + /// ingestion request; streaming ingest is not supported). + Influxdb(InfluxdbOptions), +} + /// A parsed, insertable row: one gRPC value per targeted column, in COPY /// field order. Every parser emits these directly, whatever mechanism it /// used to produce them. @@ -83,34 +88,3 @@ pub(super) trait RecordParser: Send { /// stream ended exactly at a record boundary. fn finish(&mut self) -> PgWireResult>; } - -/// A COPY FROM STDIN data format implementation. -/// -/// Implementations are shared per statement (hence `Send + Sync`) and must -/// be stateless; per-stream state belongs to the [`RecordParser`] they -/// create. Every method is tailored to the format: `check_column_type` -/// declares the types the format can decode (csv is bounded by what -/// arrow-csv supports). -pub(super) trait CopyInCodec: Send + Sync + std::fmt::Debug { - /// The canonical format name, used in error messages. - fn name(&self) -> &'static str; - /// The format code advertised in the `CopyInResponse` header: 0 when - /// the client sends textual data (the default), 1 for binary. - fn format_code(&self) -> i8 { - 0 - } - /// Validates that a column of `data_type` can be ingested by this - /// format. - fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()>; - /// Creates the stateful parser for one copy stream over the targeted - /// columns (in COPY field order). - /// - /// `timezone` is the session timezone (an IANA name or a UTC offset): - /// formats that parse offset-free timestamp strings from text should - /// interpret them in this zone, matching SQL INSERT. - fn create_parser( - &self, - columns: &[ColumnSchema], - timezone: &str, - ) -> PgWireResult>; -} diff --git a/src/servers/src/postgres/copy_in/csv.rs b/src/servers/src/postgres/copy_in/csv.rs index b2919210e3f..ab8f521098d 100644 --- a/src/servers/src/postgres/copy_in/csv.rs +++ b/src/servers/src/postgres/copy_in/csv.rs @@ -40,12 +40,12 @@ use datatypes::schema::{ColumnSchema, Schema as GreptimeSchema}; use datatypes::vectors::{BooleanVector, Helper, StringVector, Vector}; use pgwire::error::{PgWireError, PgWireResult}; -use crate::postgres::copy_in::codec::{CopyInCodec, ParsedRow, RecordParser}; +use crate::postgres::copy_in::codec::{CopyFormat, ParsedRow, RecordParser}; use crate::postgres::copy_in::options::CopyOptionSet; use crate::postgres::copy_in::{COPY_IN_FLUSH_ROWS, bad_copy_data, invalid_text_repr, unsupported}; /// The validated `csv` format configuration. -#[derive(Debug)] +#[derive(Debug, Clone)] pub(super) struct CsvCodec { delimiter: u8, quote: u8, @@ -54,7 +54,7 @@ pub(super) struct CsvCodec { } /// Builds the CSV codec from the parsed options. -pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult> { +pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult { let delimiter = options.take_single_byte("DELIMITER")?.unwrap_or(b','); let quote = options.take_single_byte("QUOTE")?.unwrap_or(b'"'); // In PostgreSQL the default escape character for CSV is the quote @@ -75,7 +75,7 @@ pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult PgWireResult &'static str { - "csv" - } - +impl CsvCodec { /// The column types arrow-csv can decode against. - fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> { + pub(super) fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> { let supported = matches!( data_type, ConcreteDataType::Boolean(_) @@ -117,7 +113,7 @@ impl CopyInCodec for CsvCodec { Ok(()) } - fn create_parser( + pub(super) fn create_parser( &self, columns: &[ColumnSchema], timezone: &str, @@ -292,9 +288,15 @@ mod tests { ] } + fn build_codec(set: CopyOptionSet) -> CsvCodec { + match build_csv_codec(set).unwrap() { + CopyFormat::Csv(codec) => codec, + other => panic!("expected csv format, got {other:?}"), + } + } + fn parser() -> Box { - build_csv_codec(CopyOptionSet::default()) - .unwrap() + build_codec(CopyOptionSet::default()) .create_parser(&test_columns(), "UTC") .unwrap() } @@ -308,8 +310,7 @@ mod tests { fn rows_with(mut set: CopyOptionSet) -> Box { set.take_format().unwrap(); - build_csv_codec(set) - .unwrap() + build_codec(set) .create_parser(&test_columns(), "UTC") .unwrap() } @@ -329,8 +330,8 @@ mod tests { #[test] fn test_build_defaults() { - let codec = build_csv_codec(CopyOptionSet::default()).unwrap(); - assert_eq!(codec.name(), "csv"); + let codec = build_codec(CopyOptionSet::default()); + assert!(matches!(codec, CsvCodec { .. })); } #[test] @@ -368,7 +369,7 @@ mod tests { #[test] fn test_check_column_type() { - let codec = build_csv_codec(CopyOptionSet::default()).unwrap(); + let codec = build_codec(CopyOptionSet::default()); assert!( codec .check_column_type(&ConcreteDataType::json_datatype()) @@ -524,8 +525,7 @@ mod tests { .into_bytes(); let check = |chunk: usize| { - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&sweep_columns, "UTC") .unwrap(); let mut ids: Vec = Vec::new(); @@ -560,8 +560,7 @@ mod tests { check(chunk); let mut shifted = payload.clone(); shifted.drain(..37); - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&sweep_columns, "UTC") .unwrap(); let mut count = 0usize; @@ -585,8 +584,7 @@ mod tests { false, ), ]; - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&columns, "UTC") .unwrap(); let rows = feed_all( @@ -628,8 +626,7 @@ mod tests { false, ), ]; - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&columns, "UTC") .unwrap(); parser.feed(b"maybe,2024-01-01 00:00:00\n").unwrap(); @@ -656,8 +653,7 @@ mod tests { false, ), ]; - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&columns, "Asia/Shanghai") .unwrap(); let rows = feed_all( diff --git a/src/servers/src/postgres/copy_in/influxdb.rs b/src/servers/src/postgres/copy_in/influxdb.rs new file mode 100644 index 00000000000..b4e2a9add30 --- /dev/null +++ b/src/servers/src/postgres/copy_in/influxdb.rs @@ -0,0 +1,95 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The `influxdb` line protocol format for COPY FROM STDIN. +//! +//! `COPY FROM STDIN WITH (FORMAT influxdb, precision 'ns')` ingests +//! [InfluxDB line protocol](https://docs.influxdata.com/influxdb/v1.8/write_protocols/line_protocol_reference/) +//! text. The format is table-less — each line names its own measurement +//! — and does not parse here at all: the COPY layer buffers the whole +//! payload (bounded by [`crate::postgres::copy_in::COPY_IN_MAX_PAYLOAD_BYTES`]) +//! and completes the copy by handing it to the frontend's line-protocol +//! write pipeline as one body, exactly like the HTTP +//! `/v1/influxdb/v1/write` endpoint receives one request body: +//! conversion, permissions, interceptors, timestamp alignment, merge +//! mode and inserts are the same path, and record boundaries (including +//! newlines inside quoted field values and after escapes) are decided +//! by the line-protocol parser alone — the COPY layer never splits +//! records. +//! +//! One COPY statement is therefore one bounded ingestion request; a +//! larger import is multiple COPY statements. +//! +//! The `precision` option carries the same values as the HTTP +//! `precision` query parameter (`ns`, `us`, `ms`, `s`, ...), defaults to +//! nanoseconds, and is resolved by the shared `parse_time_precision`. + +use common_grpc::precision::Precision; +use pgwire::error::PgWireResult; + +use crate::postgres::copy_in::bad_copy_data; +use crate::postgres::copy_in::codec::CopyFormat; +use crate::postgres::copy_in::options::CopyOptionSet; + +/// The format's validated options. A `None` precision carries the +/// pipeline's default (nanoseconds), exactly like an HTTP write without +/// a `precision` parameter. +#[derive(Debug, Clone)] +pub(super) struct InfluxdbOptions { + pub(super) precision: Option, +} + +pub(super) fn build_influxdb_codec(mut options: CopyOptionSet) -> PgWireResult { + let precision = match options.take_string("precision")? { + Some(value) => Some( + crate::influxdb::parse_time_precision(&value) + .map_err(|e| bad_copy_data(format!("invalid precision option: {e}")))?, + ), + None => None, + }; + options.reject_leftovers("influxdb")?; + Ok(CopyFormat::Influxdb(InfluxdbOptions { precision })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::postgres::copy_in::options::CopyOptionValue; + + #[test] + fn test_builder_options() { + let format = build_influxdb_codec(CopyOptionSet::default()).unwrap(); + assert!(matches!(format, CopyFormat::Influxdb(_))); + assert!(matches!(format, CopyFormat::Influxdb(_))); + + let mut set = CopyOptionSet::default(); + set.insert("precision".into(), CopyOptionValue::String("ms".into())) + .unwrap(); + assert!(matches!( + build_influxdb_codec(set).unwrap(), + CopyFormat::Influxdb(InfluxdbOptions { + precision: Some(Precision::Millisecond) + }) + )); + + let mut set = CopyOptionSet::default(); + set.insert("precision".into(), CopyOptionValue::String("bogus".into())) + .unwrap(); + assert!(build_influxdb_codec(set).is_err()); + + let mut set = CopyOptionSet::default(); + set.insert("unknown".into(), CopyOptionValue::Flag).unwrap(); + assert!(build_influxdb_codec(set).is_err()); + } +} diff --git a/src/servers/src/postgres/copy_in/mod.rs b/src/servers/src/postgres/copy_in/mod.rs index a3959a23830..92528d4ab2f 100644 --- a/src/servers/src/postgres/copy_in/mod.rs +++ b/src/servers/src/postgres/copy_in/mod.rs @@ -21,38 +21,42 @@ //! the data stream incrementally and flushes it into the query handler as //! [`RowInsertRequests`] batches. //! -//! # Format framework +//! # Formats //! -//! Each COPY data format is implemented as a [`codec::CopyInCodec`]: a -//! stateless strategy that validates its options at statement-parse time, -//! describes the column types it can ingest, and creates the stateful -//! record parser for one stream. Formats register a builder under every -//! accepted `FORMAT` name in [`REGISTERED_FORMATS`] — `csv` is the only -//! implemented format today; PostgreSQL's `text`/`binary` and -//! GreptimeDB-specific formats alike can be added the same way. See the -//! `codec` module docs. +//! The supported formats are the explicit [`codec::CopyFormat`] enum — +//! `csv` (table-bound, incremental row parsing) and `influxdb` +//! (table-less, one bounded whole-payload request). Each format states +//! its own target rule and ingestion shape in the match arms of the +//! copy lifecycle below; adding a format is a new variant plus its +//! arms. Builders resolve a `FORMAT` name (and its aliases) through +//! [`REGISTERED_FORMATS`]. See the `codec` module docs. mod codec; mod csv; +mod influxdb; mod options; mod parse; use std::fmt::Debug; use std::sync::Arc; +use crate::influxdb::InfluxdbRequest; use api::helper::ColumnDataTypeWrapper; use api::v1::column_def::options_from_column_schema; use api::v1::{ Row as GrpcRow, RowInsertRequest, RowInsertRequests, Rows as GrpcRows, SemanticType, }; use async_trait::async_trait; -use codec::{CopyInCodec, RecordParser}; +use codec::{CopyFormat, RecordParser}; +use common_grpc::precision::Precision; use common_query::OutputData; use common_telemetry::{info, warn}; +use csv::CsvCodec; use datafusion::sql::sqlparser::ast::{CopyTarget, Statement as SqlParserStatement}; use datatypes::data_type::DataType; use datatypes::schema::{ColumnSchema, SchemaRef}; use futures::{Sink, SinkExt, stream}; +use influxdb::InfluxdbOptions; use pgwire::api::copy::CopyHandler; use pgwire::api::results::{CopyResponse, Response, Tag}; use pgwire::api::{ClientInfo, PgWireConnectionState}; @@ -80,38 +84,43 @@ use crate::postgres::utils::convert_err; /// the per-batch fixed costs negligible. pub(crate) const COPY_IN_FLUSH_ROWS: usize = 32768; -/// Builds a codec from the format-neutral option set. -type CodecBuilder = fn(options::CopyOptionSet) -> PgWireResult>; +/// Upper bound of an influxdb COPY FROM STDIN payload. One COPY +/// statement is one bounded ingestion request (the whole payload is +/// buffered like one HTTP write body); a larger import is multiple COPY +/// statements. Streaming ingest may arrive later, with framing owned by +/// the shared line-protocol parser rather than the COPY layer. +pub(crate) const COPY_IN_MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024; + +/// Builds a format from the format-neutral option set. +type FormatBuilder = fn(options::CopyOptionSet) -> PgWireResult; /// The registered COPY FROM STDIN formats: accepted `FORMAT` name to /// builder. `csv` is the only implemented format; the others are /// registered so they report a clear "not supported yet" instead of an /// unknown-format error. -const REGISTERED_FORMATS: &[(&str, CodecBuilder)] = &[ +const REGISTERED_FORMATS: &[(&str, FormatBuilder)] = &[ ("csv", csv::build_csv_codec), + ("influxdb", influxdb::build_influxdb_codec), + ("influxdb_line", influxdb::build_influxdb_codec), ("text", build_unimplemented_text_codec), ("txt", build_unimplemented_text_codec), ("binary", build_unimplemented_binary_codec), ]; -fn build_unimplemented_text_codec( - _options: options::CopyOptionSet, -) -> PgWireResult> { +fn build_unimplemented_text_codec(_options: options::CopyOptionSet) -> PgWireResult { Err(unsupported( "the text format is not supported yet; use WITH (FORMAT csv)", )) } -fn build_unimplemented_binary_codec( - _options: options::CopyOptionSet, -) -> PgWireResult> { +fn build_unimplemented_binary_codec(_options: options::CopyOptionSet) -> PgWireResult { Err(unsupported( "COPY FROM STDIN WITH (FORMAT binary) is not supported yet", )) } -/// Resolves the format codec from the parsed options. -fn resolve_codec(options: &mut options::CopyOptionSet) -> PgWireResult> { +/// Resolves the format from the parsed options. +fn resolve_format(options: &mut options::CopyOptionSet) -> PgWireResult { let name = options.take_format()?.ok_or_else(|| { unsupported( "COPY FROM STDIN requires an explicit format in this version; use WITH (FORMAT csv)", @@ -133,15 +142,15 @@ pub(crate) struct CopyFromStdin { table: Vec, /// Requested column list; empty means all columns in table order. columns: Vec, - /// The resolved format codec, validated and ready to run. - codec: Arc, + /// The resolved format with its validated options. + format: CopyFormat, } fn copy_in_error(code: PgErrorCode, message: impl Into) -> PgWireError { PgWireError::UserError(Box::new(code.to_err_info(message.into()))) } -fn unsupported(message: impl Into) -> PgWireError { +pub(super) fn unsupported(message: impl Into) -> PgWireError { copy_in_error(PgErrorCode::Ec0A000, message) } @@ -174,11 +183,11 @@ pub(crate) fn copy_from_stdin_from_sql(sql: &str) -> PgWireResult raw, }; let mut option_set = raw.options; - let codec = resolve_codec(&mut option_set)?; + let format = resolve_format(&mut option_set)?; Ok(Some(CopyFromStdin { table: raw.table, columns: raw.columns, - codec, + format, })) } @@ -221,26 +230,49 @@ fn resolve_table_name( } /// Per-connection state of an in-progress COPY FROM STDIN. +/// +/// The payload shape follows the codec: table-bound formats (csv) parse +/// records into rows against the targeted table's columns; table-less +/// formats (influxdb line protocol) split the stream into complete +/// lines that each route to their own measurement, and flush through +/// the handler's line-protocol pipeline — the same one the HTTP write +/// endpoint uses. pub(crate) struct CopyInState { query_ctx: QueryContextRef, - /// The gRPC column schemas of the targeted columns. Cloned into each - /// flushed batch: `Rows.schema` is an owned `Vec` in the proto - /// request, so one copy per request is inherent. - grpc_schema: Vec, - table_name: String, - parser: Box, + payload: Payload, /// The resolved codec's name, for logging. codec_name: &'static str, /// The wire format code of the resolved codec. codec_format_code: i8, - /// Parsed rows not yet flushed to the handler. - rows: Vec, rows_written: u64, } +enum Payload { + /// Table-bound rows: parsed against `grpc_schema` and flushed to + /// `table_name` via `copy_in_insert`. The schema is cloned into each + /// flushed batch: `Rows.schema` is an owned `Vec` in the proto + /// request, so one copy per request is inherent. + Table { + grpc_schema: Vec, + table_name: String, + parser: Box, + /// Parsed rows not yet flushed to the handler. + rows: Vec, + }, + /// The whole buffered influxdb line-protocol payload with its + /// request precision. One COPY statement is one bounded ingestion + /// request, buffered until `CopyDone` — exactly like one HTTP write + /// body — and record boundaries belong to the line-protocol parser, + /// never to the COPY layer. + Influxdb { + data: Vec, + precision: Option, + }, +} + impl CopyInState { fn new( - codec: Arc, + codec: &CsvCodec, columns: Vec, table_info: Arc, query_ctx: QueryContextRef, @@ -249,7 +281,7 @@ impl CopyInState { let schema = table_info.meta.schema.clone(); let timestamp_index = schema.timestamp_index(); - let columns = resolve_columns(codec.as_ref(), columns, &schema, &table_info)?; + let columns = resolve_columns(codec, columns, &schema, &table_info)?; if let Some(ts_index) = timestamp_index { let ts_column = &schema.column_schemas()[ts_index]; if !columns.iter().any(|column| column.name == ts_column.name) { @@ -268,58 +300,122 @@ impl CopyInState { Ok(Self { query_ctx, - grpc_schema, - table_name, - parser, - codec_name: codec.name(), - codec_format_code: codec.format_code(), - rows: Vec::with_capacity(COPY_IN_FLUSH_ROWS), + payload: Payload::Table { + grpc_schema, + table_name, + parser, + rows: Vec::with_capacity(COPY_IN_FLUSH_ROWS), + }, + codec_name: "csv", + codec_format_code: 0, rows_written: 0, }) } + /// State for the influxdb format: the whole payload is buffered and + /// completed once at `CopyDone` through the line-protocol pipeline. + fn new_influxdb(options: &InfluxdbOptions, query_ctx: QueryContextRef) -> Self { + Self { + query_ctx, + payload: Payload::Influxdb { + data: Vec::new(), + precision: options.precision, + }, + codec_name: "influxdb", + codec_format_code: 0, + rows_written: 0, + } + } + /// The wire format code advertised to the client. pub(crate) fn format_code(&self) -> i8 { self.codec_format_code } - /// Feeds a `CopyData` chunk into the parser and buffers parsed rows. + /// Feeds a `CopyData` chunk into the parser and buffers parsed rows + /// (csv) or payload bytes (influxdb). fn feed(&mut self, data: &[u8]) -> PgWireResult<()> { - self.rows.extend(self.parser.feed(data)?); + match &mut self.payload { + Payload::Table { parser, rows, .. } => rows.extend(parser.feed(data)?), + Payload::Influxdb { data: buffered, .. } => { + if buffered.len() + data.len() > COPY_IN_MAX_PAYLOAD_BYTES { + return Err(bad_copy_data(format!( + "COPY FROM STDIN payload exceeds the {} limit; split the import into multiple COPY statements", + COPY_IN_MAX_PAYLOAD_BYTES + ))); + } + buffered.extend_from_slice(data); + } + } Ok(()) } /// Parses the buffered tail at `CopyDone`; a final record without a /// trailing newline is accepted. fn finish(&mut self) -> PgWireResult<()> { - self.rows.extend(self.parser.finish()?); + match &mut self.payload { + Payload::Table { parser, rows, .. } => rows.extend(parser.finish()?), + // The whole payload is one request body; nothing to finalize. + Payload::Influxdb { .. } => {} + } Ok(()) } fn should_flush(&self) -> bool { - self.rows.len() >= COPY_IN_FLUSH_ROWS + match &self.payload { + Payload::Table { rows, .. } => rows.len() >= COPY_IN_FLUSH_ROWS, + // Completed once at CopyDone, not mid-stream. + Payload::Influxdb { .. } => false, + } } /// Takes the buffered rows as an insert request, if any. fn take_requests(&mut self) -> Option { - if self.rows.is_empty() { + let Payload::Table { + grpc_schema, + table_name, + rows, + .. + } = &mut self.payload + else { + return None; + }; + if rows.is_empty() { return None; } let rows = GrpcRows { - schema: self.grpc_schema.clone(), - rows: std::mem::take(&mut self.rows), + schema: grpc_schema.clone(), + rows: std::mem::take(rows), }; Some(RowInsertRequests { inserts: vec![RowInsertRequest { - table_name: self.table_name.clone(), + table_name: table_name.clone(), rows: Some(rows), }], }) } + + /// Takes the buffered payload as one line-protocol request body, if + /// any — the same bytes an HTTP write of the same records would + /// carry. + fn take_lines(&mut self) -> PgWireResult> { + let Payload::Influxdb { data, precision } = &mut self.payload else { + return Ok(None); + }; + if data.is_empty() { + return Ok(None); + } + let lines = String::from_utf8(std::mem::take(data)) + .map_err(|e| bad_copy_data(format!("COPY FROM STDIN data is not valid UTF-8: {e}")))?; + Ok(Some(InfluxdbRequest { + precision: *precision, + lines, + })) + } } fn resolve_columns( - codec: &dyn CopyInCodec, + codec: &CsvCodec, columns: Vec, schema: &SchemaRef, table_info: &Arc, @@ -411,27 +507,63 @@ impl PostgresServerHandlerInner { // pending-rows batcher like SQL INSERT when it is enabled for // this connection. let query_ctx = self.new_query_context(); - let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?; - let Some(table_info) = self - .copy_in_handler - .copy_in_table(&catalog, &schema, &table, query_ctx.clone()) - .await - .map_err(convert_err)? - else { - return Err(copy_in_error( - PgErrorCode::Ec42P01, - format!("relation \"{}\" does not exist", stmt.table.join(".")), - )); + // Each format states its own target rule and ingestion shape + // explicitly. + let state = match &stmt.format { + // csv requires a target table: records are parsed against + // its columns and inserted in batches. + CopyFormat::Csv(codec) => { + if stmt.table.is_empty() { + return Err(unsupported( + "format csv requires a table: COPY tbl [(cols)] FROM STDIN WITH (FORMAT csv)", + )); + } + let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?; + + let Some(table_info) = self + .copy_in_handler + .copy_in_table(&catalog, &schema, &table, query_ctx.clone()) + .await + .map_err(convert_err)? + else { + return Err(copy_in_error( + PgErrorCode::Ec42P01, + format!("relation \"{}\" does not exist", stmt.table.join(".")), + )); + }; + + // The insert path resolves the bare table name against the + // query context, so point the context at the resolved + // catalog and schema when the COPY target is qualified. + let query_ctx = adjust_query_context(query_ctx, &catalog, &schema); + + CopyInState::new(codec, stmt.columns, table_info, query_ctx, table)? + } + // influxdb forbids a target table — each line names its own + // measurement — and completes through the line-protocol + // pipeline the HTTP write endpoints use; the server must be + // wired for it. + CopyFormat::Influxdb(options) => { + if !stmt.table.is_empty() { + return Err(unsupported(format!( + "format influxdb routes each record to its own table; \"COPY {} FROM STDIN\" must not name one", + stmt.table.join(".") + ))); + } + if self.influxdb_handler.is_none() { + return Err(unsupported( + "this server is not wired for the influxdb line protocol format", + )); + } + CopyInState::new_influxdb(options, query_ctx) + } + }; + let num_columns = match &state.payload { + Payload::Table { grpc_schema, .. } => grpc_schema.len(), + // No fixed column set: the format routes per record. + Payload::Influxdb { .. } => 0, }; - - // The insert path resolves the bare table name against the query - // context, so point the context at the resolved catalog and schema - // when the COPY target is qualified. - let query_ctx = adjust_query_context(query_ctx, &catalog, &schema); - - let state = CopyInState::new(stmt.codec, stmt.columns, table_info, query_ctx, table)?; - let num_columns = state.grpc_schema.len(); let format_code = state.format_code(); *self.copy_in_state.lock().await = Some(state); @@ -443,13 +575,34 @@ impl PostgresServerHandlerInner { ))) } - /// Flushes buffered rows of an in-progress copy. Returns the number of - /// rows written by the flushed batch. + /// Flushes the buffered payload of an in-progress copy. Returns the + /// number of rows written by the flushed batch. async fn flush_copy_in(&self, state: &mut CopyInState) -> PgWireResult { + let query_ctx = state.query_ctx.clone(); + // The buffered influxdb payload is completed through the + // line-protocol pipeline — the same handler the HTTP write + // endpoints use, so conversion, permissions, interceptors, + // timestamp alignment and inserts are identical to an HTTP + // write of the same bytes. The context stays this connection's + // postgres context. + if let Some(request) = state.take_lines()? { + let Some(influxdb_handler) = &self.influxdb_handler else { + return Err(unsupported( + "this server is not wired for the influxdb line protocol format", + )); + }; + let output = influxdb_handler + .exec(request, query_ctx) + .await + .map_err(convert_err)?; + return match output.data { + OutputData::AffectedRows(rows) => Ok(rows as u64), + OutputData::RecordBatches(_) | OutputData::Stream(_) => Ok(0), + }; + } let Some(requests) = state.take_requests() else { return Ok(0); }; - let query_ctx = state.query_ctx.clone(); let output = self .copy_in_handler .copy_in_insert(requests, query_ctx) @@ -587,8 +740,8 @@ mod tests { .unwrap(); assert_eq!(copy.table, vec!["t"]); assert!(copy.columns.is_empty()); - assert_eq!(copy.codec.name(), "csv"); - assert_eq!(copy.codec.format_code(), 0); + assert!(matches!(copy.format, CopyFormat::Csv(_))); + // Both formats are textual: format code 0. } #[test] @@ -599,7 +752,7 @@ mod tests { .unwrap() .unwrap(); assert_eq!(copy.columns, vec!["a", "b"]); - assert_eq!(copy.codec.name(), "csv"); + assert!(matches!(copy.format, CopyFormat::Csv(_))); } #[test] diff --git a/src/servers/src/postgres/copy_in/parse.rs b/src/servers/src/postgres/copy_in/parse.rs index 8139960bfa4..e9be443eea5 100644 --- a/src/servers/src/postgres/copy_in/parse.rs +++ b/src/servers/src/postgres/copy_in/parse.rs @@ -32,7 +32,7 @@ use pgwire::error::PgWireResult; use crate::postgres::copy_in::options::{CopyOptionSet, CopyOptionValue}; use crate::postgres::copy_in::{bad_copy_data, copy_in_must_run_alone_error}; -/// A scanned `COPY tbl [(cols)] FROM STDIN [WITH (...)]` statement. +/// A scanned `COPY [tbl [(cols)]] FROM STDIN [WITH (...)]` statement. /// /// Unquoted identifiers are folded to lowercase and quoted ones keep their /// case (`COPY Metrics` addresses the same table as `CREATE TABLE Metrics`, @@ -41,7 +41,9 @@ use crate::postgres::copy_in::{bad_copy_data, copy_in_must_run_alone_error}; #[derive(Debug)] pub(super) struct RawCopyFromStdin { /// Table name parts, as written (`t`, `schema.t`, - /// `catalog.schema.t`); quoted names keep their case. + /// `catalog.schema.t`); quoted names keep their case. Empty for + /// table-less formats whose records carry their own routing (e.g. + /// the influxdb line protocol names its measurement per line). pub(super) table: Vec, /// Requested column list; empty means all columns in table order. pub(super) columns: Vec, @@ -89,13 +91,27 @@ pub(super) fn scan_copy_from_stdin(sql: &str) -> PgWireResult { return Ok(CopyInScan::NotCopyIn); } - let table = match parse_object_name(&mut cursor) { - Some(table) => table, - None => return Ok(CopyInScan::NotCopyIn), + // Table-less statements (`COPY FROM STDIN WITH (FORMAT influxdb) ...`) + // are table-format specific: the codec decides whether a missing + // table is legal. An unquoted `FROM` cannot be a table name (SQL + // would require quoting it), so peek instead of letting the + // identifier parser swallow the keyword. A column list without a + // table is not. + let table = if cursor.peek_keyword("from") { + Vec::new() + } else { + match parse_object_name(&mut cursor) { + Some(table) => table, + None => return Ok(CopyInScan::NotCopyIn), + } }; - let columns = match parse_column_list(&mut cursor) { - Some(columns) => columns, - None => return Ok(CopyInScan::NotCopyIn), + let columns = if table.is_empty() { + Vec::new() + } else { + match parse_column_list(&mut cursor) { + Some(columns) => columns, + None => return Ok(CopyInScan::NotCopyIn), + } }; if !cursor.take_keyword("from") || !cursor.take_keyword("stdin") { @@ -151,16 +167,20 @@ impl<'a> Tokens<'a> { /// Consumes the next token if it is the unquoted keyword `keyword`. fn take_keyword(&mut self, keyword: &str) -> bool { - match self.peek() { - Some(Token::Word(w)) - if w.quote_style.is_none() && w.value.eq_ignore_ascii_case(keyword) => - { - self.pos += 1; - true - } - _ => false, + if self.peek_keyword(keyword) { + self.pos += 1; + true + } else { + false } } + + /// Whether the next token is the unquoted keyword `keyword`, without + /// consuming it. + fn peek_keyword(&self, keyword: &str) -> bool { + matches!(self.tokens.get(self.pos), Some(Token::Word(w)) + if w.quote_style.is_none() && w.value.eq_ignore_ascii_case(keyword)) + } } /// Returns the identifier with the SQL parser's canonicalization: quoted @@ -275,6 +295,27 @@ mod tests { }) } + #[test] + fn test_scan_tableless() { + // Table-less statements: the codec decides whether a missing + // table is legal (the influxdb line protocol names its + // measurement per line). + let raw = scan("COPY FROM STDIN WITH (FORMAT influxdb, precision 'ns')") + .unwrap() + .unwrap(); + assert!(raw.table.is_empty()); + assert!(raw.columns.is_empty()); + + let raw = scan("copy from stdin (format influxdb)").unwrap().unwrap(); + assert!(raw.table.is_empty()); + + // A column list without a table is not a copy-in statement. + assert!(scan("COPY (a, b) FROM STDIN").unwrap().is_none()); + // COPY OUT and file COPY are unaffected. + assert!(scan("COPY (SELECT 1) TO STDOUT").unwrap().is_none()); + assert!(scan("COPY t FROM '/tmp/x.csv'").unwrap().is_none()); + } + #[test] fn test_scan_basic() { let raw = scan("COPY t FROM STDIN").unwrap().unwrap(); diff --git a/src/servers/src/postgres/server.rs b/src/servers/src/postgres/server.rs index 7e3b3e2b7bd..3919081ba62 100644 --- a/src/servers/src/postgres/server.rs +++ b/src/servers/src/postgres/server.rs @@ -30,6 +30,7 @@ use tokio_rustls::TlsAcceptor; use crate::error::Result; use crate::postgres::{MakePostgresServerHandler, MakePostgresServerHandlerBuilder}; use crate::query_handler::CopyInHandlerRef; +use crate::query_handler::InfluxdbLineProtocolHandlerRef; use crate::query_handler::sql::ServerSqlQueryHandlerRef; use crate::server::{AbortableStream, BaseTcpServer, Server}; use crate::tls::ReloadableTlsServerConfig; @@ -40,6 +41,7 @@ pub struct PostgresServer { tls_server_config: Arc, keep_alive_secs: u64, batching_enabled: bool, + influxdb_handler: Option, bind_addr: Option, process_manager: Option, } @@ -77,6 +79,7 @@ impl PostgresServer { tls_server_config, keep_alive_secs, batching_enabled: false, + influxdb_handler: None, bind_addr: None, process_manager, } @@ -88,12 +91,34 @@ impl PostgresServer { self } + /// Wires the influxdb line-protocol handler used by table-less + /// `COPY FROM STDIN WITH (FORMAT influxdb)` flushes — the same + /// handler the HTTP influxdb write endpoints use, so a flushed batch + /// runs through the identical pipeline. + pub fn with_influxdb_handler(mut self, handler: InfluxdbLineProtocolHandlerRef) -> Self { + self.influxdb_handler = Some(handler); + self + } + fn accept( &self, io_runtime: Runtime, accepting_stream: AbortableStream, ) -> impl Future + use<> { - let handler_maker = self.make_handler.clone(); + // Assemble the per-connection handler directly, including any + // `with_*` wiring applied after construction (the influxdb + // line-protocol handler). Constructing the struct — instead of + // going through the builder — keeps this infallible: no + // `.build().unwrap()` on the hot accept path. + let make_handler = &self.make_handler; + let handler_maker = Arc::new(MakePostgresServerHandler { + query_handler: make_handler.query_handler.clone(), + copy_in_handler: make_handler.copy_in_handler.clone(), + influxdb_handler: self.influxdb_handler.clone(), + user_provider: make_handler.user_provider.clone(), + param_provider: make_handler.param_provider.clone(), + force_tls: make_handler.force_tls, + }); let batching_enabled = self.batching_enabled; let tls_server_config = self.tls_server_config.clone(); let process_manager = self.process_manager.clone(); diff --git a/tests-integration/src/test_util.rs b/tests-integration/src/test_util.rs index 3cc820619c6..3dd451b4716 100644 --- a/tests-integration/src/test_util.rs +++ b/tests-integration/src/test_util.rs @@ -1204,16 +1204,19 @@ pub async fn setup_pg_server_with_slow_query_threshold( .expect("Failed to load certificates and keys"), ); - let mut pg_server = Box::new(PostgresServer::new( - fe_instance_ref.clone(), - fe_instance_ref.clone(), - opts.tls.should_force_tls(), - tls_server_config, - 0, - runtime, - None, - None, - )); + let mut pg_server = Box::new( + PostgresServer::new( + fe_instance_ref.clone(), + fe_instance_ref.clone(), + opts.tls.should_force_tls(), + tls_server_config, + 0, + runtime, + None, + None, + ) + .with_influxdb_handler(fe_instance_ref.clone()), + ); pg_server .start(fe_pg_addr.parse::().unwrap()) @@ -1248,16 +1251,19 @@ pub async fn setup_pg_server_with_user_provider( .expect("Failed to load certificates and keys"), ); - let mut pg_server = Box::new(PostgresServer::new( - fe_instance_ref.clone(), - fe_instance_ref.clone(), - opts.tls.should_force_tls(), - tls_server_config, - 0, - runtime, - user_provider, - None, - )); + let mut pg_server = Box::new( + PostgresServer::new( + fe_instance_ref.clone(), + fe_instance_ref.clone(), + opts.tls.should_force_tls(), + tls_server_config, + 0, + runtime, + user_provider, + None, + ) + .with_influxdb_handler(fe_instance_ref.clone()), + ); pg_server .start(fe_pg_addr.parse::().unwrap()) @@ -1304,16 +1310,19 @@ pub async fn setup_pg_server_with_prom_native_histogram( .expect("Failed to load certificates and keys"), ); - let mut pg_server = Box::new(PostgresServer::new( - instance.fe_instance().clone(), - instance.fe_instance().clone(), - opts.tls.should_force_tls(), - tls_server_config, - 0, - runtime, - None, - None, - )); + let mut pg_server = Box::new( + PostgresServer::new( + instance.fe_instance().clone(), + instance.fe_instance().clone(), + opts.tls.should_force_tls(), + tls_server_config, + 0, + runtime, + None, + None, + ) + .with_influxdb_handler(instance.fe_instance().clone()), + ); pg_server .start(fe_pg_addr.parse::().unwrap()) diff --git a/tests-integration/src/tests/postgres_copy_in_test.rs b/tests-integration/src/tests/postgres_copy_in_test.rs index 82e076e7a65..94b19c1315d 100644 --- a/tests-integration/src/tests/postgres_copy_in_test.rs +++ b/tests-integration/src/tests/postgres_copy_in_test.rs @@ -316,6 +316,7 @@ async fn test_postgres_copy_in_failed_copy_then_new_copy() { Err(e) => e, }; assert!(err.as_db_error().is_some(), "{err}"); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; // The connection is usable and a NEW copy succeeds on it. let rows = feed_copy_in( @@ -519,3 +520,302 @@ async fn test_postgres_copy_in_empty_field_is_null() { server.shutdown().await.unwrap(); } + +/// `COPY FROM STDIN WITH (FORMAT influxdb)` ingests line protocol through +/// the same pipeline as the HTTP influxdb write endpoint: lines route to +/// their own measurements, tables are auto-created, and a batch behaves +/// like an HTTP write of the same bytes. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_line_protocol() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + let payload = b"monitor,host=hosta cpu=66.6,memory=1024 1663840496100023100\n\ + monitor,host=hostb memory=1027 1663840496400340001\n\ + weather,location=us-midwest temperature=82 1663840496100023102\n"; + + // Feed byte-by-byte-ish: lines and UTF-8 may span CopyData chunks. + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + payload.chunks(7).map(Bytes::copy_from_slice).collect(), + ) + .await + .unwrap(); + assert_eq!(rows, 3); + + let messages = client + .simple_query("SELECT host, cpu, memory FROM monitor ORDER BY host") + .await + .unwrap(); + let rows: Vec<(String, String, String)> = messages + .iter() + .filter_map(|m| { + let tokio_postgres::SimpleQueryMessage::Row(row) = m else { + return None; + }; + Some(( + row.get(0).unwrap_or("").to_string(), + row.get(1).unwrap_or("").to_string(), + row.get(2).unwrap_or("").to_string(), + )) + }) + .collect(); + assert_eq!( + rows, + vec![ + ("hosta".into(), "66.6".into(), "1024.0".into()), + ("hostb".into(), "".into(), "1027.0".into()), + ] + ); + + let messages = client + .simple_query("SELECT temperature FROM weather") + .await + .unwrap(); + let temps: Vec = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string), + _ => None, + }) + .collect(); + assert_eq!(temps, vec!["82.0".to_string()]); + + server.shutdown().await.unwrap(); +} + +/// The `precision` option carries the HTTP endpoint's semantics: +/// nanosecond timestamps by default, other units on request. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_precision() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_prec").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb, precision 'ms')", + vec![Bytes::from_static(b"prec,host=h v=1 1465839830100\n")], + ) + .await + .unwrap(); + assert_eq!(rows, 1); + + let messages = client + .simple_query("SELECT CAST(greptime_timestamp AS BIGINT) FROM prec") + .await + .unwrap(); + let ts: Vec = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string), + _ => None, + }) + .collect(); + // 1465839830100 ms == 1465839830100000000 ns + assert_eq!(ts.len(), 1); + let ts_ns: i64 = ts[0].parse().unwrap(); + assert_eq!(ts_ns, 1465839830100000000); + + server.shutdown().await.unwrap(); +} + +/// Records with newlines INSIDE quoted field values are one line-protocol +/// record: the parser owns record boundaries, so a CopyData chunk boundary +/// inside the quoted string — the case a naive line splitter breaks on — +/// must not split it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_multiline_quoted_field() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_ml").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + // A record whose string field value contains a physical newline, and + // one with a backslash right before the newline (the parser skips the + // escaped newline; also not a record boundary). + let payload: Vec = b"mlog,host=a line=\"first\nsecond\" 100\n\ + mlog,host=b line=\"tail\\\nmore\" 200\n" + .to_vec(); + + // Split exactly on the internal newline of the first record: chunk 1 + // ends after `first`, chunk 2 starts with the newline. + let split_at = payload.windows(6).position(|w| w == b"first\n").unwrap() + b"first".len(); + let (head, tail) = payload.split_at(split_at); + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + vec![Bytes::copy_from_slice(head), Bytes::copy_from_slice(tail)], + ) + .await + .unwrap(); + assert_eq!(rows, 2); + + let messages = client + .simple_query("SELECT line FROM mlog ORDER BY host") + .await + .unwrap(); + let lines: Vec = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string), + _ => None, + }) + .collect(); + // The quoted values keep their physical newlines: `first`, newline, + // `second`; and `tail`, backslash, newline, `more` (a backslash only + // escapes `\` and `"` in line-protocol strings, so it stays literal + // before the newline). + assert_eq!( + lines, + vec!["first\nsecond".to_string(), "tail\\\nmore".to_string()] + ); + + server.shutdown().await.unwrap(); +} + +/// The payload is bounded by the HTTP write endpoints' own body limit. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_payload_limit() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_cap").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + // The HTTP write endpoints' default body limit (64 MiB) — kept in + // sync with servers::http::DEFAULT_BODY_LIMIT. + let limit = 64 * 1024 * 1024; + // Several chunks over the limit, none containing a record boundary. + let chunk = vec![b'x'; 1024 * 1024]; + let mut sent = 0usize; + let mut sink = Box::pin( + client + .copy_in("COPY FROM STDIN WITH (FORMAT influxdb)") + .await + .unwrap(), + ); + while sent <= limit { + sink.as_mut() + .send(Bytes::from(chunk.clone())) + .await + .unwrap(); + sent += chunk.len(); + } + // The cap fires mid-stream; the error surfaces when the copy + // completes (the sink buffers sends locally). + let error = sink + .as_mut() + .finish() + .await + .expect_err("expected the oversized payload to fail"); + assert!( + error + .as_db_error() + .map(|d| d.message().contains("exceeds")) + .unwrap_or(false), + "unexpected error: {error}" + ); + + // The connection stays usable. + let messages = client.simple_query("SELECT 1").await.unwrap(); + assert!(!messages.is_empty()); + + server.shutdown().await.unwrap(); +} + +/// The regression for the retired line-splitter's failure mode: with +/// 32,767 ordinary records plus a multiline quoted record whose first +/// physical line lands exactly on the old 32,768-line flush threshold — +/// and a CopyData chunk boundary at the quoted value's internal newline — +/// the whole payload must still ingest as one request. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_flush_threshold_multiline() { + init_default_ut_logging(); + let (_guard, server) = + setup_pg_server(StorageType::File, "pg_copy_in_influxdb_threshold").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + // 32,767 ordinary records, then a record whose quoted value spans + // three physical lines. + let mut head = String::new(); + for i in 0..32_767 { + head.push_str(&format!( + "m,host=h{i} v={i} {} +", + 1_000 + i + )); + } + head.push_str("mlog,host=z line=\"first\nsecond\nthird\" 99999"); + let tail = " +" + .to_string(); + + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + vec![ + Bytes::from(head.into_bytes()), + Bytes::from(tail.into_bytes()), + ], + ) + .await + .unwrap(); + assert_eq!(rows, 32_768); + + let messages = client.simple_query("SELECT line FROM mlog").await.unwrap(); + let lines: Vec = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string), + _ => None, + }) + .collect(); + assert_eq!(lines, vec!["first\nsecond\nthird".to_string()]); + + server.shutdown().await.unwrap(); +} + +/// Invalid UTF-8 fails the copy with a clear error and the connection +/// stays usable; a trailing record without a newline is still ingested. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_invalid_utf8_and_trailing_record() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_utf8").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + // Trailing record without a newline: accepted. + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + vec![Bytes::from_static(b"m2,host=a v=7 300")], + ) + .await + .unwrap(); + assert_eq!(rows, 1); + + // Invalid UTF-8: the copy fails, the connection stays usable. + let error = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + vec![Bytes::from_static(b"m3 v=1 100\n\xff\xfe")], + ) + .await + .unwrap_err(); + assert!( + error + .as_db_error() + .map(|d| d.message().contains("not valid UTF-8")) + .unwrap_or(false), + "unexpected error: {error}" + ); + let messages = client.simple_query("SELECT 1").await.unwrap(); + assert!(!messages.is_empty()); + + server.shutdown().await.unwrap(); +} From df33737e9d093d2415df363f2942ff62ef904597 Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Wed, 28 Oct 2026 08:45:10 +0000 Subject: [PATCH 07/19] feat: add shared asynchronous cache primitives (#9790) Signed-off-by: WenyXu --- Cargo.lock | 10 + Cargo.toml | 1 + src/common/cache/Cargo.toml | 16 ++ src/common/cache/src/cache.rs | 473 ++++++++++++++++++++++++++++++++ src/common/cache/src/lib.rs | 21 ++ src/common/cache/src/metrics.rs | 194 +++++++++++++ 6 files changed, 715 insertions(+) create mode 100644 src/common/cache/Cargo.toml create mode 100644 src/common/cache/src/cache.rs create mode 100644 src/common/cache/src/lib.rs create mode 100644 src/common/cache/src/metrics.rs diff --git a/Cargo.lock b/Cargo.lock index 69996d9cbb2..8e4183994d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2340,6 +2340,16 @@ dependencies = [ "tokio", ] +[[package]] +name = "common-cache" +version = "1.4.0-alpha.0" +dependencies = [ + "futures", + "moka", + "prometheus 0.14.0", + "tokio", +] + [[package]] name = "common-catalog" version = "1.4.0-alpha.0" diff --git a/Cargo.toml b/Cargo.toml index 15539abb2c7..a5e3db37960 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ members = [ "src/cmd", "src/common/base", "src/common/batcher", + "src/common/cache", "src/common/catalog", "src/common/config", "src/common/datasource", diff --git a/src/common/cache/Cargo.toml b/src/common/cache/Cargo.toml new file mode 100644 index 00000000000..1e2f9d83a5a --- /dev/null +++ b/src/common/cache/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "common-cache" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +moka = { workspace = true, features = ["future"] } +prometheus.workspace = true + +[dev-dependencies] +futures.workspace = true +tokio = { workspace = true, features = ["macros", "rt", "sync"] } diff --git a/src/common/cache/src/cache.rs b/src/common/cache/src/cache.rs new file mode 100644 index 00000000000..98efb890f29 --- /dev/null +++ b/src/common/cache/src/cache.rs @@ -0,0 +1,473 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::borrow::Borrow; +use std::hash::Hash; +use std::sync::Arc; + +use crate::metrics::{CacheMetrics, CacheSizeMetric, CacheSizeRegistration}; + +/// Reason for releasing an entry from the cache. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RemovalCause { + /// The entry reached its expiration time. + Expired, + /// The entry was explicitly invalidated. + Explicit, + /// A new value replaced the entry. + Replaced, + /// The entry was removed to satisfy the capacity policy. + Size, +} + +impl RemovalCause { + /// Returns the established eviction metric label. + pub fn as_str(self) -> &'static str { + match self { + Self::Expired => "expired", + Self::Explicit => "explicit", + Self::Replaced => "replaced", + Self::Size => "size", + } + } +} + +impl From for RemovalCause { + fn from(value: moka::notification::RemovalCause) -> Self { + match value { + moka::notification::RemovalCause::Expired => Self::Expired, + moka::notification::RemovalCause::Explicit => Self::Explicit, + moka::notification::RemovalCause::Replaced => Self::Replaced, + moka::notification::RemovalCause::Size => Self::Size, + } + } +} + +/// A weighted memory cache with backend-provided asynchronous load deduplication. +/// Values should be inexpensive to clone, such as `Arc` or `Bytes`. +/// Capacity is maintained asynchronously; insertion does not guarantee retention. +#[derive(Clone)] +pub struct Cache { + inner: moka::future::Cache, + capacity: u64, + size_registration: Option, + metrics: Option>, +} + +impl Cache +where + K: Eq + Hash + Send + Sync + 'static, + V: Clone + Send + Sync + 'static, +{ + /// Creates a cache with the caller's weight and eviction accounting. + pub fn new(name: &str, capacity: u64, weigher: W, listener: L) -> Self + where + W: Fn(&K, &V) -> u32 + Send + Sync + 'static, + L: Fn(Arc, V, RemovalCause) + Send + Sync + 'static, + { + Self { + inner: moka::future::Cache::builder() + .name(name) + .max_capacity(capacity) + .support_invalidation_closures() + .weigher(weigher) + .eviction_listener(move |key, value, cause| listener(key, value, cause.into())) + .build(), + capacity, + size_registration: None, + metrics: None, + } + } + + /// Attaches caller-bound metrics without changing existing hit/miss accounting. + pub fn with_metrics(mut self, metrics: Arc) -> Self { + self.metrics = Some(metrics); + self + } + + /// Samples this cache's retained weight when the caller collects byte metrics. + pub fn with_size_metric(mut self, metric: CacheSizeMetric) -> Self { + let cache = self.inner.clone(); + self.size_registration = Some(metric.register(move || cache.weighted_size())); + self + } + + /// Gets a completed value without starting a load. + pub fn get<'a, Q>(&'a self, key: &'a Q) -> impl Future> + Send + 'a + where + K: Borrow, + Q: Hash + Eq + Sync + ?Sized, + { + self.inner.get(key) + } + + /// Shares a successful load among concurrent callers with the same key and error type. + /// Errors are shared with current waiters but are not retained as cached values. + /// Cancelling the active loader lets a remaining caller execute its own loader. + pub async fn try_get_with(&self, key: &Q, load: F) -> Result> + where + K: Borrow, + Q: ToOwned + Hash + Eq + ?Sized, + F: Future>, + E: Send + Sync + 'static, + { + let request = self + .metrics + .as_ref() + .map(|metrics| metrics.requests.start()); + let result = self + .inner + .try_get_with_by_ref(key, async { + // Only the backend-selected loader contributes physical load metrics. + let operation = self.metrics.as_ref().map(|metrics| metrics.loads.start()); + let result = load.await; + if let Some(operation) = operation { + operation.finish(&result); + } + result + }) + .await; + if let Some(request) = request { + request.finish(&result); + } + result + } + + /// Submits a completed value to the cache's admission and eviction policy. + pub async fn insert(&self, key: K, value: V) { + self.inner.insert(key, value).await; + } + + /// Invalidates a completed entry. This does not cancel a concurrent loader. + pub async fn invalidate(&self, key: &Q) + where + K: Borrow, + Q: Hash + Eq + ?Sized, + { + self.inner.invalidate(key).await; + } + + /// Invalidates completed entries matching a predicate. Pending loaders are not fenced. + /// Physical removal and eviction accounting run asynchronously. + pub fn invalidate_if(&self, predicate: F) -> std::io::Result<()> + where + F: Fn(&K, &V) -> bool + Send + Sync + 'static, + { + self.inner + .invalidate_entries_if(predicate) + .map(|_| ()) + .map_err(std::io::Error::other) + } + + /// Returns the configured weight capacity. + pub fn capacity(&self) -> u64 { + self.capacity + } + + /// Returns the approximate number of retained entries. + pub fn entry_count(&self) -> u64 { + self.inner.entry_count() + } + + /// Returns the approximate total retained weight. + pub fn weighted_size(&self) -> u64 { + self.inner.weighted_size() + } + + /// Applies pending admission, eviction, and accounting work. + pub async fn run_pending_tasks(&self) { + self.inner.run_pending_tasks().await; + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use tokio::sync::Notify; + + use super::*; + + // This is also a compile-time contract for generic callers crossing async-trait boundaries. + fn send_lookup<'a, K, V, Q>( + cache: &'a Cache, + key: &'a Q, + ) -> impl Future> + Send + 'a + where + K: Borrow + Eq + Hash + Send + Sync + 'static, + V: Clone + Send + Sync + 'static, + Q: Hash + Eq + Sync + ?Sized, + { + cache.get(key) + } + + #[tokio::test] + async fn test_borrowed_lookup_has_a_send_future() { + let cache = cache(1024); + cache + .insert("key".to_string(), Arc::new("value".to_string())) + .await; + let future: futures::future::BoxFuture<'_, Option>> = + Box::pin(send_lookup(&cache, "key")); + assert_eq!(future.await.as_deref().map(String::as_str), Some("value")); + } + + #[tokio::test] + async fn test_predicate_invalidation_preserves_other_entries() { + let cache = cache(1024); + cache + .insert("old".to_string(), Arc::new("a".to_string())) + .await; + cache + .insert("keep".to_string(), Arc::new("b".to_string())) + .await; + cache.run_pending_tasks().await; + cache.invalidate_if(|key, _| key == "old").unwrap(); + assert!(cache.get("old").await.is_none()); + assert_eq!( + cache.get("keep").await.as_deref().map(String::as_str), + Some("b") + ); + } + + fn cache(capacity: u64) -> Cache> { + Cache::new( + "test", + capacity, + |_, value: &Arc| value.len() as u32, + |_, _, _| {}, + ) + } + + fn operation_metrics(name: &str) -> crate::metrics::OperationMetrics { + use prometheus::{Histogram, HistogramOpts, IntCounter, IntGauge}; + + crate::metrics::OperationMetrics { + started: IntCounter::new(format!("{name}_started"), "test").unwrap(), + succeeded: IntCounter::new(format!("{name}_succeeded"), "test").unwrap(), + failed: IntCounter::new(format!("{name}_failed"), "test").unwrap(), + cancelled: IntCounter::new(format!("{name}_cancelled"), "test").unwrap(), + active: IntGauge::new(format!("{name}_active"), "test").unwrap(), + elapsed: Histogram::with_opts(HistogramOpts::new(format!("{name}_seconds"), "test")) + .unwrap(), + } + } + + fn instrumented_cache() -> (Cache>, Arc) { + let metrics = Arc::new(CacheMetrics { + requests: operation_metrics("requests"), + loads: operation_metrics("loads"), + }); + (cache(1024).with_metrics(metrics.clone()), metrics) + } + + #[tokio::test] + async fn test_metrics_distinguish_requests_from_executed_loads() { + let (cache, metrics) = instrumented_cache(); + // Merely constructing an async call does not start an operation. + drop(cache.try_get_with("unused", async { Ok::<_, ()>(Arc::new(String::new())) })); + assert_eq!(0, metrics.requests.started.get()); + let gate = Notify::new(); + let mut first = Box::pin(cache.try_get_with("key", async { + gate.notified().await; + Ok::<_, ()>(Arc::new("value".to_string())) + })); + let mut second = Box::pin(cache.try_get_with("key", async { Err::, _>(()) })); + assert!(futures::poll!(&mut first).is_pending()); + assert!(futures::poll!(&mut second).is_pending()); + assert_eq!(2, metrics.requests.active.get()); + assert_eq!(1, metrics.loads.active.get()); + gate.notify_waiters(); + let (first, second) = tokio::join!(first, second); + assert!(Arc::ptr_eq(&first.unwrap(), &second.unwrap())); + cache + .try_get_with("key", async { Err::, _>(()) }) + .await + .unwrap(); + assert_eq!(3, metrics.requests.started.get()); + assert_eq!(3, metrics.requests.succeeded.get()); + assert_eq!(1, metrics.loads.started.get()); + assert_eq!(1, metrics.loads.succeeded.get()); + assert_eq!(0, metrics.requests.active.get()); + assert_eq!(0, metrics.loads.active.get()); + assert_eq!(3, metrics.requests.elapsed.get_sample_count()); + assert_eq!(1, metrics.loads.elapsed.get_sample_count()); + assert_eq!(0, metrics.requests.failed.get()); + assert_eq!(0, metrics.requests.cancelled.get()); + } + + #[tokio::test] + async fn test_metrics_release_active_work_on_cancellation_and_error() { + let (cache, metrics) = instrumented_cache(); + let mut producer = + Box::pin(cache.try_get_with("key", std::future::pending::, ()>>())); + let mut waiter = + Box::pin(cache.try_get_with("key", std::future::pending::, ()>>())); + assert!(futures::poll!(&mut producer).is_pending()); + assert!(futures::poll!(&mut waiter).is_pending()); + drop(waiter); + assert_eq!(1, metrics.requests.cancelled.get()); + assert_eq!(0, metrics.loads.cancelled.get()); + drop(producer); + assert_eq!(2, metrics.requests.cancelled.get()); + assert_eq!(1, metrics.loads.cancelled.get()); + let result = cache + .try_get_with("key", async { Err::, _>(()) }) + .await; + assert!(result.is_err()); + assert_eq!(1, metrics.requests.failed.get()); + assert_eq!(1, metrics.loads.failed.get()); + assert_eq!(0, metrics.requests.active.get()); + assert_eq!(0, metrics.loads.active.get()); + assert_eq!(3, metrics.requests.elapsed.get_sample_count()); + assert_eq!(2, metrics.loads.elapsed.get_sample_count()); + } + + #[tokio::test] + async fn test_instrumented_loading_future_is_send() { + fn assert_send(value: T) -> T { + value + } + + let (cache, _) = instrumented_cache(); + assert_send( + cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("value".to_string())) }), + ) + .await + .unwrap(); + } + + #[tokio::test] + async fn test_shares_load_and_bypasses_loader_on_hit() { + let cache = cache(1024); + let calls = AtomicUsize::new(0); + let gate = Notify::new(); + let load = || async { + calls.fetch_add(1, Ordering::Relaxed); + gate.notified().await; + Ok::<_, ()>(Arc::new("value".to_string())) + }; + let mut first = Box::pin(cache.try_get_with("key", load())); + let mut second = Box::pin(cache.try_get_with("key", load())); + assert!(futures::poll!(&mut first).is_pending()); + assert!(futures::poll!(&mut second).is_pending()); + assert_eq!(1, calls.load(Ordering::Relaxed)); + gate.notify_waiters(); + let (first, second) = tokio::join!(first, second); + let first = first.unwrap(); + assert!(Arc::ptr_eq(&first, &second.unwrap())); + let hit = cache + .try_get_with("key", async { Err::, _>(()) }) + .await + .unwrap(); + assert!(Arc::ptr_eq(&first, &hit)); + } + + #[tokio::test] + async fn test_remaining_waiter_loads_after_producer_cancellation() { + let (cache, metrics) = instrumented_cache(); + let mut first = + Box::pin(cache.try_get_with("key", std::future::pending::, ()>>())); + assert!(futures::poll!(&mut first).is_pending()); + let mut second = Box::pin( + cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("retry".to_string())) }), + ); + assert!(futures::poll!(&mut second).is_pending()); + drop(first); + assert_eq!("retry", second.await.unwrap().as_str()); + assert_eq!(2, metrics.requests.started.get()); + assert_eq!(1, metrics.requests.cancelled.get()); + assert_eq!(1, metrics.requests.succeeded.get()); + assert_eq!(2, metrics.loads.started.get()); + assert_eq!(1, metrics.loads.cancelled.get()); + assert_eq!(1, metrics.loads.succeeded.get()); + assert_eq!(0, metrics.requests.active.get()); + assert_eq!(0, metrics.loads.active.get()); + } + + #[tokio::test] + async fn test_errors_are_shared_but_not_cached() { + let (cache, metrics) = instrumented_cache(); + let calls = AtomicUsize::new(0); + let gate = Notify::new(); + let load = || async { + calls.fetch_add(1, Ordering::Relaxed); + gate.notified().await; + Err::, _>("read failed") + }; + let mut first = Box::pin(cache.try_get_with("key", load())); + let mut second = Box::pin(cache.try_get_with("key", load())); + assert!(futures::poll!(&mut first).is_pending()); + assert!(futures::poll!(&mut second).is_pending()); + gate.notify_waiters(); + let (first, second) = tokio::join!(first, second); + assert!(Arc::ptr_eq(&first.unwrap_err(), &second.unwrap_err())); + assert_eq!(2, metrics.requests.failed.get()); + assert_eq!(1, metrics.loads.failed.get()); + assert_eq!(0, metrics.requests.active.get()); + assert_eq!(0, metrics.loads.active.get()); + assert_eq!(1, calls.load(Ordering::Relaxed)); + assert!(cache.get("key").await.is_none()); + assert_eq!( + "retry", + cache + .try_get_with("key", async { + Ok::<_, &'static str>(Arc::new("retry".to_string())) + }) + .await + .unwrap() + .as_str() + ); + } + + #[tokio::test] + async fn test_sampled_size_sums_instances_and_preserves_manual_bytes() { + use crate::metrics::CacheSizeMetrics; + use prometheus::Opts; + use prometheus::core::Collector; + + let metrics = + CacheSizeMetrics::new(Opts::new("test_cache_bytes", "test"), &["type"]).unwrap(); + let manual = metrics.with_label_values(&["shared"]); + manual.set(3); + let make_cache = || { + Cache::new("sampled", 100, |_: &u64, _: &Arc| 7, |_, _, _| {}) + .with_size_metric(metrics.bind(&["shared"])) + }; + let a = make_cache(); + let b = make_cache(); + let sample = || { + metrics.collect()[0].get_metric()[0] + .get_gauge() + .as_ref() + .map_or(0.0, |gauge| gauge.value()) + }; + a.insert(1, Arc::new("one".into())).await; + b.insert(2, Arc::new("two".into())).await; + a.run_pending_tasks().await; + b.run_pending_tasks().await; + assert_eq!(17.0, sample()); + assert_eq!(3, manual.get()); + let consumer = a.get(&1).await.unwrap(); + a.invalidate(&1).await; + a.run_pending_tasks().await; + assert_eq!(10.0, sample()); + drop(consumer); + let cloned = b.clone(); + drop(b); + assert_eq!(10.0, sample()); + drop(cloned); + assert_eq!(3.0, sample()); + } +} diff --git a/src/common/cache/src/lib.rs b/src/common/cache/src/lib.rs new file mode 100644 index 00000000000..58d54adee68 --- /dev/null +++ b/src/common/cache/src/lib.rs @@ -0,0 +1,21 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Shared memory cache primitives with native asynchronous load deduplication. + +mod cache; + +pub mod metrics; + +pub use cache::{Cache, RemovalCause}; diff --git a/src/common/cache/src/metrics.rs b/src/common/cache/src/metrics.rs new file mode 100644 index 00000000000..fd02c32b689 --- /dev/null +++ b/src/common/cache/src/metrics.rs @@ -0,0 +1,194 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::{Arc, Mutex, Weak}; +use std::time::Instant; + +use prometheus::core::{Collector, Desc}; +use prometheus::proto::{Gauge, MetricFamily}; +use prometheus::{Histogram, IntCounter, IntGauge, IntGaugeVec, Opts}; + +/// Caller-bound metrics for native cache loading. No collectors are registered here. +/// Requests count only `try_get_with` calls, including its cache hits and callers sharing +/// another request's load. Plain `get` calls are not counted. Loads count +/// only loader futures actually polled by the backend; their difference is not a waiter count. +#[derive(Clone)] +pub struct CacheMetrics { + pub requests: OperationMetrics, + pub loads: OperationMetrics, +} + +/// Metrics for one operation, with labels bound once when constructing a cache. +/// Completion counters are mutually exclusive. Dropping an unfinished future is cancellation. +#[derive(Clone)] +pub struct OperationMetrics { + pub started: IntCounter, + pub succeeded: IntCounter, + pub failed: IntCounter, + pub cancelled: IntCounter, + pub active: IntGauge, + /// Wall-clock lifetime, including suspended time, for every outcome. + pub elapsed: Histogram, +} + +impl OperationMetrics { + /// Starts tracking an operation and its elapsed time. + pub(crate) fn start(&self) -> OperationGuard<'_> { + self.started.inc(); + self.active.inc(); + OperationGuard { + metrics: self, + started: Instant::now(), + completed: false, + } + } +} + +/// Tracks an operation, recording cancellation if dropped before completion. +pub(crate) struct OperationGuard<'a> { + metrics: &'a OperationMetrics, + started: Instant, + completed: bool, +} + +impl OperationGuard<'_> { + /// Records success or failure and completes the operation. + pub(crate) fn finish(mut self, result: &Result) { + if result.is_ok() { + self.metrics.succeeded.inc(); + } else { + self.metrics.failed.inc(); + } + self.completed = true; + } +} + +impl Drop for OperationGuard<'_> { + fn drop(&mut self) { + if !self.completed { + self.metrics.cancelled.inc(); + } + self.metrics.active.dec(); + self.metrics + .elapsed + .observe(self.started.elapsed().as_secs_f64()); + } +} + +/// Cache byte metrics combining manually maintained gauges and sampled cache weights. +/// Sampling does not force backend maintenance or include pending loader values. +#[derive(Clone)] +pub struct CacheSizeMetrics { + gauges: IntGaugeVec, + sources: Arc>>, +} + +/// A byte metric with labels bound for one or more cache instances. +#[derive(Clone)] +pub struct CacheSizeMetric { + metrics: CacheSizeMetrics, + gauge: IntGauge, +} + +/// Keeps a cache instance registered for size sampling while any owner remains. +#[derive(Clone)] +pub struct CacheSizeRegistration { + _reader: Arc u64 + Send + Sync>, +} + +struct CacheSizeSource { + gauge: IntGauge, + read: Weak u64 + Send + Sync>, +} + +impl CacheSizeMetrics { + /// Creates an unregistered collector. Register a clone with the caller's registry. + pub fn new(opts: Opts, labels: &[&str]) -> prometheus::Result { + Ok(Self { + gauges: IntGaugeVec::new(opts, labels)?, + sources: Arc::new(Mutex::new(Vec::new())), + }) + } + + /// Returns the backing gauges for callers retaining manual accounting. + pub fn gauges(&self) -> &IntGaugeVec { + &self.gauges + } + + /// Returns a manually maintained gauge for existing non-cache accounting. + pub fn with_label_values(&self, labels: &[&str]) -> IntGauge { + self.gauges.with_label_values(labels) + } + + /// Binds labels for sampled cache weights. Instances sharing labels are summed. + pub fn bind(&self, labels: &[&str]) -> CacheSizeMetric { + CacheSizeMetric { + metrics: self.clone(), + gauge: self.gauges.with_label_values(labels), + } + } +} + +impl CacheSizeMetric { + /// Registers a cache-level weight reader without retaining it in the collector. + /// Keep the returned registration alongside the cache, including in its clones. + pub fn register( + &self, + read: impl Fn() -> u64 + Send + Sync + 'static, + ) -> CacheSizeRegistration { + let read: Arc u64 + Send + Sync> = Arc::new(read); + self.metrics + .sources + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(CacheSizeSource { + gauge: self.gauge.clone(), + read: Arc::downgrade(&read), + }); + CacheSizeRegistration { _reader: read } + } +} + +impl Collector for CacheSizeMetrics { + fn desc(&self) -> Vec<&Desc> { + self.gauges.desc() + } + + fn collect(&self) -> Vec { + let mut families = self.gauges.collect(); + let mut sources = self.sources.lock().unwrap_or_else(|e| e.into_inner()); + sources.retain(|source| { + let Some(read) = source.read.upgrade() else { + return false; + }; + let labels = source.gauge.collect(); + for family in &mut families { + for metric in family.mut_metric() { + if metric.get_label() == labels[0].get_metric()[0].get_label() { + let bytes = metric + .get_gauge() + .as_ref() + .map_or(0.0, |gauge| gauge.value()) + + read() as f64; + let mut gauge = Gauge::default(); + gauge.set_value(bytes); + metric.set_gauge(gauge); + } + } + } + true + }); + families + } +} From 05536cd7f52a3b5fbe96f3d3f672b6e9c3855b3e Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Wed, 28 Oct 2026 09:39:45 +0000 Subject: [PATCH 08/19] fix(meta): register failure detectors for regions switched before a rollback (#9989) * fix(meta): register failure detectors for regions switched before a rollback A region migration switches the routes of its tables one table at a time. If it aborts after some tables were switched, those regions are already served by the target, but the rollback deregistered the target's failure detectors for every region and registered only the source's. The target's next heartbeat registers them again, so if the target stopped before sending one, nothing detected its failure and the switched regions stayed unavailable until the metasrv leader changed or the target came back. The rollback now collects, from the routes it already reads, the regions whose leader is the target and resets the target's failure detectors for them at the end. It also skips a table whose route no longer exists, so a table dropped meanwhile no longer fails the rollback before the detectors are handled. Signed-off-by: jeremyhi * test(meta): roll back a downgrading leader in the rollback detector test The table that was not switched yet keeps a downgrading leader in a real abort, so the test now builds it that way and checks that the rollback clears it. Signed-off-by: jeremyhi * fix(meta): monitor regions switched before a rollback only on the target The rollback registered the source's failure detectors for every region of the migration, including the regions already switched to the target. Those regions are served by the target after the rollback, so their source detectors watched the wrong peer: when one fired, the failover found the leader had changed and only removed it. The rollback now registers the source's detectors only for the regions that were not switched, and keeps resetting the target's detectors for the others. Signed-off-by: jeremyhi * refactor(meta): rename reset_failure_detectors_for_candidate_regions to reset_failure_detectors Signed-off-by: jeremyhi --------- Signed-off-by: jeremyhi --- .../src/procedure/region_migration.rs | 110 ++++++++++++++++-- .../rollback_downgraded_region.rs | 3 +- .../upgrade_candidate_region.rs | 3 +- 3 files changed, 103 insertions(+), 13 deletions(-) diff --git a/src/meta-srv/src/procedure/region_migration.rs b/src/meta-srv/src/procedure/region_migration.rs index 75ab5c79397..4f7967dd3c4 100644 --- a/src/meta-srv/src/procedure/region_migration.rs +++ b/src/meta-srv/src/procedure/region_migration.rs @@ -630,13 +630,13 @@ impl Context { Ok(datanode_table_value) } - /// Notifies the RegionSupervisor to register failure detectors of failed region. + /// Notifies the RegionSupervisor to register failure detectors of the given regions on the + /// source peer. /// /// The original failure detector was removed once the procedure was triggered. /// Now, we need to register the failure detector for the failed region again. - pub async fn register_failure_detectors(&self) { + pub async fn register_failure_detectors(&self, region_ids: &[RegionId]) { let datanode_id = self.persistent_ctx.from_peer.id; - let region_ids = &self.persistent_ctx.region_ids; let detecting_regions = region_ids .iter() .map(|region_id| (datanode_id, *region_id)) @@ -650,10 +650,10 @@ impl Context { ); } - /// Notifies the RegionSupervisor to reset failure detectors of candidate regions. - pub async fn reset_failure_detectors_for_candidate_regions(&self) { + /// Notifies the RegionSupervisor to reset failure detectors of the given regions on the target + /// peer. + pub async fn reset_failure_detectors(&self, region_ids: &[RegionId]) { let datanode_id = self.persistent_ctx.to_peer.id; - let region_ids = &self.persistent_ctx.region_ids; let detecting_regions = region_ids .iter() .map(|region_id| (datanode_id, *region_id)) @@ -662,7 +662,7 @@ impl Context { .reset_failure_detectors(detecting_regions) .await; info!( - "Reset failure detectors after migration success for datanode {}, regions {:?}", + "Reset failure detectors of regions for datanode {}, regions {:?}", datanode_id, region_ids ); } @@ -878,12 +878,29 @@ impl RegionMigrationProcedure { .with_label_values(&["rollback"]) .start_timer(); let ctx = &self.context; + let to_peer_id = ctx.persistent_ctx.to_peer.id; let table_regions = ctx.persistent_ctx.table_regions(); + // Regions whose route was switched to the target before the procedure aborted. + let mut switched_regions = Vec::new(); for (table_id, regions) in table_regions { let table_lock = TableLock::Write(table_id).into(); let _guard = procedure_ctx.provider.acquire_lock(&table_lock).await; - let table_route = ctx.get_table_route_value(table_id).await?; + let table_route = match ctx.get_table_route_value(table_id).await { + Ok(table_route) => table_route, + // The table has been dropped meanwhile. + Err(error::Error::TableRouteNotFound { .. }) => continue, + Err(err) => return Err(err), + }; let region_routes = table_route.region_routes().unwrap(); + switched_regions.extend( + region_routes + .iter() + .filter(|route| regions.contains(&route.region.id)) + .filter(|route| { + route.leader_peer.as_ref().map(|peer| peer.id) == Some(to_peer_id) + }) + .map(|route| route.region.id), + ); let downgraded = region_routes .iter() .filter(|route| regions.contains(&route.region.id)) @@ -912,7 +929,24 @@ impl RegionMigrationProcedure { self.context .deregister_failure_detectors_for_candidate_regions() .await; - self.context.register_failure_detectors().await; + // The switched regions are served by the target, so they are monitored there instead. + let unswitched_regions = ctx + .persistent_ctx + .region_ids + .iter() + .filter(|region_id| !switched_regions.contains(region_id)) + .copied() + .collect::>(); + self.context + .register_failure_detectors(&unswitched_regions) + .await; + // The target's next heartbeat would register these detectors again, but nothing would if + // the target stopped before sending one. + if !switched_regions.is_empty() { + self.context + .reset_failure_detectors(&switched_regions) + .await; + } Ok(()) } @@ -1014,8 +1048,8 @@ mod tests { use common_meta::distributed_time_constants::default_distributed_time_constants; use common_meta::instruction::Instruction; - use common_meta::key::test_utils::new_test_table_info; - use common_meta::rpc::router::{Region, RegionRoute}; + use common_meta::key::test_utils::{new_test_table_info, new_test_table_info_with_name}; + use common_meta::rpc::router::{LeaderState, Region, RegionRoute}; use super::*; use crate::handler::HeartbeatMailbox; @@ -1025,12 +1059,66 @@ mod tests { new_downgrade_region_reply, new_flush_region_reply_for_region, new_open_region_reply, new_upgrade_region_reply, }; + use crate::region::supervisor::{Event, RegionFailureDetectorControl}; use crate::service::mailbox::Channel; fn new_persistent_context() -> PersistentContext { test_util::new_persistent_context(1, 2, RegionId::new(1024, 1)) } + #[tokio::test] + async fn test_rollback_registers_detectors_for_switched_regions() { + let env = TestingEnv::new(); + // The route switch aborted after the table of `switched` was switched to the target and + // before the table of `unswitched`, whose leader is still downgrading; the table of + // `dropped` has been dropped. + let switched = RegionId::new(1024, 1); + let unswitched = RegionId::new(1025, 1); + let dropped = RegionId::new(1026, 1); + for (region_id, leader) in [(switched, 2), (unswitched, 1)] { + let table_id = region_id.table_id(); + let table_info = new_test_table_info_with_name(table_id, &format!("table_{table_id}")); + let region_routes = vec![RegionRoute { + region: Region::new_test(region_id), + leader_peer: Some(Peer::empty(leader)), + leader_state: (region_id == unswitched).then_some(LeaderState::Downgrading), + ..Default::default() + }]; + env.create_physical_table_metadata(table_info, region_routes) + .await; + } + let mut persistent_ctx = new_persistent_context(); + persistent_ctx.region_ids = vec![switched, unswitched, dropped]; + let (tx, mut rx) = tokio::sync::mpsc::channel(8); + let mut context_factory = env.context_factory(); + context_factory.region_failure_detector_controller = + Arc::new(RegionFailureDetectorControl::new(tx)); + let mut procedure = RegionMigrationProcedure::new(persistent_ctx, context_factory, vec![]); + + procedure + .rollback_inner(&new_procedure_context()) + .await + .unwrap(); + + // The target's detectors are replaced by the source's, except for `switched`, which stays + // monitored on the target. + let target = [switched, unswitched, dropped].map(|region_id| (2, region_id)); + let source = [unswitched, dropped].map(|region_id| (1, region_id)); + assert_matches!(rx.try_recv(), Ok(Event::DeregisterFailureDetectors(r)) if r == target); + assert_matches!(rx.try_recv(), Ok(Event::RegisterFailureDetectors(r)) if r == source); + assert_matches!(rx.try_recv(), Ok(Event::ResetFailureDetectors(r)) if r == [(2, switched)]); + assert!(rx.try_recv().is_err()); + let table_route = env + .table_metadata_manager() + .table_route_manager() + .table_route_storage() + .get(unswitched.table_id()) + .await + .unwrap() + .unwrap(); + assert_eq!(table_route.region_routes().unwrap()[0].leader_state, None); + } + #[test] fn test_lock_key() { let persistent_context = new_persistent_context(); diff --git a/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs b/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs index 2f0ed0fbe9a..1c9c12a9bc1 100644 --- a/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs +++ b/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs @@ -64,7 +64,8 @@ impl UpdateMetadata { "Rolling back downgraded leader region table route success, table_id: {table_id}, regions: {regions:?}" ); } - ctx.register_failure_detectors().await; + ctx.register_failure_detectors(&ctx.persistent_ctx.region_ids) + .await; Ok(()) } diff --git a/src/meta-srv/src/procedure/region_migration/update_metadata/upgrade_candidate_region.rs b/src/meta-srv/src/procedure/region_migration/update_metadata/upgrade_candidate_region.rs index 5c55891e590..68931e21761 100644 --- a/src/meta-srv/src/procedure/region_migration/update_metadata/upgrade_candidate_region.rs +++ b/src/meta-srv/src/procedure/region_migration/update_metadata/upgrade_candidate_region.rs @@ -215,7 +215,8 @@ impl UpdateMetadata { } ctx.deregister_failure_detectors().await; - ctx.reset_failure_detectors_for_candidate_regions().await; + ctx.reset_failure_detectors(&ctx.persistent_ctx.region_ids) + .await; // Consumes the guard. ctx.volatile_ctx.opening_region_guards.clear(); From 89a5df31418add4a168c7318d4cae55b90ddce00 Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Wed, 28 Oct 2026 11:18:25 +0000 Subject: [PATCH 09/19] fix: ignore stale leader grants after a region is downgraded (#9987) * fix: ignore stale leader grants after a region is downgraded Signed-off-by: jeremyhi * fix: compare stale leader grants with the longest lease seen Signed-off-by: jeremyhi * fix: treat a lease too long to store as unknown A lease longer than a u64 of nanoseconds saturated to a shorter one, so the derived send time could be later than the real one. Now such a lease makes the send time unknown, which counts as earlier than any gate. Signed-off-by: jeremyhi * fix: address review comments on stale leader grants Scope the early send time claim to after a lease has been seen, drop the unused role parameter of demote, clarify a test comment and check that a fresh grant still makes a reopened region writable. Signed-off-by: jeremyhi * refactor: compare stale leader grants with the heartbeat send time Pass the send time of the heartbeat behind a lease to set_region_role_with_lease, and return whether the role was applied. Mito compares the send time with the grant gate directly, so it no longer derives it from the longest lease seen. The datanode finalizes leadership only when the grant was applied. Signed-off-by: jeremyhi * test: cover stale grants through the datanode and repeated downgrades Signed-off-by: jeremyhi * refactor: keep leader grant rules in one region method Apply a role grant in MitoRegion::apply_role_grant, which renews the lease and decides whether the role changes; the engine only looks up the region. Rename the gate to downgrade_started_at and demote to begin_downgrade, keep the field private, and copy it on reopen through inherit_downgrade_state_from. Signed-off-by: jeremyhi * refactor: drop a needless borrow Signed-off-by: jeremyhi * refactor: keep lease concepts in the engine and role ordering in the region ManifestContext, which owns the role, records when the role was last demoted and promotes a region only for a promotion issued after that. The time starts when the context is created, so a reopened region ignores grants for heartbeats sent before the reopen, without copying state. The engine translates leases: it renews the deadline and promotes with the heartbeat send time. MitoRegion keeps no grant state. Signed-off-by: jeremyhi * fix: keep the data region of a metric region off a grant its metadata region ignores The metric engine applies a grant to the metadata region first and stops if it is ignored, so the data region, whose role the engine reports, never becomes a leader that skips finalization. Also describe what promoting returns. Signed-off-by: jeremyhi * docs: describe when a lease grant is ignored and flatten the finalize check Signed-off-by: jeremyhi * refactor: move lease types out of the region and the Leader deadline into ManifestContext Signed-off-by: jeremyhi * refactor: name the promotion fence after the downgrade it records Signed-off-by: jeremyhi --------- Signed-off-by: jeremyhi --- src/datanode/src/alive_keeper.rs | 129 ++++++++++++++++++---- src/datanode/src/region_server.rs | 9 +- src/datanode/src/tests.rs | 8 +- src/file-engine/src/engine.rs | 5 +- src/metric-engine/src/engine.rs | 54 ++++++++-- src/metric-engine/src/engine/put.rs | 2 +- src/mito2/src/engine.rs | 12 ++- src/mito2/src/engine/lease_test.rs | 112 +++++++++++++++++++- src/mito2/src/lease.rs | 91 ++++++++++++++++ src/mito2/src/lib.rs | 1 + src/mito2/src/region.rs | 141 +++++++++++-------------- src/mito2/src/region/opener.rs | 2 - src/mito2/src/worker.rs | 12 ++- src/mito2/src/worker/handle_catchup.rs | 2 +- src/mito2/src/worker/handle_create.rs | 2 +- src/mito2/src/worker/handle_write.rs | 6 +- src/query/src/optimizer/test_util.rs | 3 +- src/store-api/src/region_engine.rs | 7 +- 18 files changed, 457 insertions(+), 141 deletions(-) create mode 100644 src/mito2/src/lease.rs diff --git a/src/datanode/src/alive_keeper.rs b/src/datanode/src/alive_keeper.rs index bef59d715c5..13af76202d5 100644 --- a/src/datanode/src/alive_keeper.rs +++ b/src/datanode/src/alive_keeper.rs @@ -134,13 +134,18 @@ impl RegionAliveKeeper { } } - /// Renews the lease of regions to `deadline`. - async fn renew_region_leases(&self, regions: &[GrantedRegion], deadline: Instant) { + /// Renews the lease of regions to `deadline`, granted for a heartbeat sent at `sent_at`. + async fn renew_region_leases( + &self, + regions: &[GrantedRegion], + sent_at: Instant, + deadline: Instant, + ) { for region in regions { let (role, region_id) = (region.role().into(), RegionId::from(region.region_id)); if let Some(handle) = self.find_handle(region_id).await { handle - .reset_deadline(role, deadline, region.extensions.clone()) + .reset_deadline(role, sent_at, deadline, region.extensions.clone()) .await; } else { warn!( @@ -281,7 +286,7 @@ impl HeartbeatResponseHandler for RegionAliveKeeper { if let Some(mito) = self.region_server.mito_engine() { mito.renew_node_lease(deadline.into_std()); } - self.renew_region_leases(®ion_lease.regions, deadline) + self.renew_region_leases(®ion_lease.regions, start_instant, deadline) .await; self.close_staled_regions(®ion_lease.closeable_region_ids) .await; @@ -296,8 +301,8 @@ enum CountdownCommand { /// 4 * `heartbeat_interval_millis` Start(u64), /// Reset countdown deadline to the given instance. - /// (NextRole, Deadline, ExtensionInfo) - Reset((RegionRole, Instant, HashMap>)), + /// (NextRole, HeartbeatSentAt, Deadline, ExtensionInfo) + Reset((RegionRole, Instant, Instant, HashMap>)), /// Returns the current deadline of the countdown task. #[cfg(test)] Deadline(oneshot::Sender), @@ -377,12 +382,18 @@ impl CountdownTaskHandle { async fn reset_deadline( &self, role: RegionRole, + sent_at: Instant, deadline: Instant, extension_info: HashMap>, ) { if let Err(e) = self .tx - .send(CountdownCommand::Reset((role, deadline, extension_info))) + .send(CountdownCommand::Reset(( + role, + sent_at, + deadline, + extension_info, + ))) .await { warn!( @@ -436,20 +447,25 @@ impl CountdownTask { started = true; } }, - Some(CountdownCommand::Reset((role, deadline, extension_info))) => { + Some(CountdownCommand::Reset((role, sent_at, deadline, extension_info))) => { let prev_role_leader = self.region_server.is_region_leader(self.region_id).unwrap_or(false); - if let Err(err) = self.region_server.set_region_role_with_lease(self.region_id, role, deadline.into_std()) { - if err.status_code() == StatusCode::RegionNotFound { - // Table metadata in metasrv is deleted after its regions are dropped. - // The datanode may still receive lease renewal responses that depend on the metadata - // during the short period before it is removed. - warn!(err; "Failed to set region role to {role} for region {region_id}"); - } else { - error!(err; "Failed to set region role to {role} for region {region_id}"); + let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std()) { + Ok(applied) => applied, + Err(err) => { + if err.status_code() == StatusCode::RegionNotFound { + // Table metadata in metasrv is deleted after its regions are dropped. + // The datanode may still receive lease renewal responses that depend on the metadata + // during the short period before it is removed. + warn!(err; "Failed to set region role to {role} for region {region_id}"); + } else { + error!(err; "Failed to set region role to {role} for region {region_id}"); + } + false } + }; - // Finalize leadership: persist backfilled metadata. - } else if !prev_role_leader && role == RegionRole::Leader + // Finalize leadership if the grant was applied: persist backfilled metadata. + if applied && !prev_role_leader && role == RegionRole::Leader && let Err(err) = self .region_server .set_region_role_state_gracefully(self.region_id, SettableRegionRoleState::Leader) @@ -503,26 +519,42 @@ impl CountdownTask { #[cfg(test)] mod test { + use std::sync::atomic::AtomicUsize; + use api::v1::Rows; use api::v1::meta::{HeartbeatResponse, RegionLease}; use common_meta::heartbeat::mailbox::HeartbeatMailbox; use mito2::config::MitoConfig; + use mito2::engine::MITO_ENGINE_NAME; use mito2::test_util::{CreateRequestBuilder, TestEnv, build_rows, rows_schema}; - use store_api::region_engine::RegionEngine; + use store_api::region_engine::{ + RegionEngine, SetRegionRoleStateResponse, SetRegionRoleStateSuccess, + }; use store_api::region_request::{ EnterStagingRequest, RegionPutRequest, StagingPartitionDirective, }; use super::*; - use crate::tests::mock_region_server; + use crate::tests::{MockRegionEngine, mock_region_server}; /// Handles a heartbeat response that grants `regions` for a heartbeat sent now. async fn handle_lease_response(alive_keeper: &RegionAliveKeeper, regions: Vec) { + let sent_at = alive_keeper.epoch().elapsed(); + handle_lease_response_sent_at(alive_keeper, sent_at, regions).await; + } + + /// Handles a heartbeat response that grants `regions` for a heartbeat sent at `sent_at` + /// after the epoch. + async fn handle_lease_response_sent_at( + alive_keeper: &RegionAliveKeeper, + sent_at: Duration, + regions: Vec, + ) { let (tx, _rx) = mpsc::channel(1); let response = HeartbeatResponse { region_lease: Some(RegionLease { regions, - duration_since_epoch: alive_keeper.epoch().elapsed().as_millis() as u64, + duration_since_epoch: sent_at.as_millis() as u64, // The countdown of a granted region does not expire during the test. lease_seconds: 86400, closeable_region_ids: vec![], @@ -534,6 +566,38 @@ mod test { alive_keeper.handle(&mut ctx).await.unwrap(); } + #[tokio::test(flavor = "multi_thread")] + async fn ignored_leader_grant_does_not_finalize_leadership() { + common_telemetry::init_default_ut_logging(); + let region_server = mock_region_server(); + let finalized = Arc::new(AtomicUsize::new(0)); + let (engine, _) = MockRegionEngine::with_custom_apply_fn(MITO_ENGINE_NAME, |engine| { + // The engine ignores the grant, so the region stays a follower. + engine.mock_role = Some(Some(RegionRole::Follower)); + let finalized = finalized.clone(); + engine.handle_set_readonly_gracefully_mock_fn = Some(Box::new(move |_| { + finalized.fetch_add(1, Ordering::Relaxed); + Ok(SetRegionRoleStateResponse::success( + SetRegionRoleStateSuccess::mito(0), + )) + })); + }); + let region_id = RegionId::new(1024, 1); + region_server.register_test_region(region_id, engine); + let alive_keeper = + RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100)); + alive_keeper.register_region(region_id).await; + let grant = GrantedRegion { + region_id: region_id.as_u64(), + role: api::v1::meta::RegionRole::Leader.into(), + extensions: HashMap::new(), + }; + handle_lease_response(&alive_keeper, vec![grant]).await; + // The countdown task has handled the grant once it answers. + alive_keeper.deadline(region_id).await.unwrap(); + assert_eq!(0, finalized.load(Ordering::Relaxed)); + } + #[tokio::test(flavor = "multi_thread")] async fn lease_responses_let_regions_write() { common_telemetry::init_default_ut_logging(); @@ -583,10 +647,26 @@ mod test { role: api::v1::meta::RegionRole::Leader.into(), extensions: HashMap::new(), }; - handle_lease_response(&alive_keeper, vec![grant]).await; + handle_lease_response(&alive_keeper, vec![grant.clone()]).await; // The countdown task has applied the grant once it answers. alive_keeper.deadline(region_id).await.unwrap(); put(region_id).await.unwrap(); + + // A grant for a heartbeat sent before a downgrade does not make the region a leader again. + let sent_before = alive_keeper.epoch().elapsed(); + region_server + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower) + .await + .unwrap(); + handle_lease_response_sent_at(&alive_keeper, sent_before, vec![grant.clone()]).await; + alive_keeper.deadline(region_id).await.unwrap(); + assert_eq!(region_server.is_region_leader(region_id), Some(false)); + + // Send times have millisecond precision, so the next heartbeat is sent after the downgrade. + tokio::time::sleep(Duration::from_millis(2)).await; + handle_lease_response(&alive_keeper, vec![grant]).await; + alive_keeper.deadline(region_id).await.unwrap(); + put(region_id).await.unwrap(); } #[tokio::test(flavor = "multi_thread")] @@ -641,6 +721,7 @@ mod test { role: api::v1::meta::RegionRole::Leader.into(), extensions: HashMap::new(), }], + Instant::now(), Instant::now() + Duration::from_millis(200), ) .await; @@ -694,6 +775,7 @@ mod test { countdown_handle .reset_deadline( RegionRole::Leader, + Instant::now(), Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5), HashMap::new(), ) @@ -744,6 +826,7 @@ mod test { role: api::v1::meta::RegionRole::StagingLeader.into(), extensions: HashMap::new(), }], + Instant::now(), Instant::now() + Duration::from_millis(3000), ) .await; @@ -792,6 +875,7 @@ mod test { role: api::v1::meta::RegionRole::Leader.into(), extensions: HashMap::new(), }], + Instant::now(), Instant::now() + Duration::from_millis(3000), ) .await; @@ -834,6 +918,7 @@ mod test { role: api::v1::meta::RegionRole::StagingLeader.into(), extensions: HashMap::new(), }], + Instant::now(), Instant::now() + Duration::from_millis(3000), ) .await; diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index 6055b07dbf6..9d4c4b375fb 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -461,20 +461,23 @@ impl RegionServer { .with_context(|_| HandleRegionRequestSnafu { region_id }) } - /// Sets the role of a region from a lease the metasrv grants until `deadline`. + /// Sets the role of a region from a lease the metasrv grants until `deadline`, in reply to a + /// heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because the + /// region was downgraded or (re)opened after `sent_at`. pub fn set_region_role_with_lease( &self, region_id: RegionId, role: RegionRole, + sent_at: std::time::Instant, deadline: std::time::Instant, - ) -> Result<()> { + ) -> Result { let engine = self .inner .region_map .get(®ion_id) .with_context(|| RegionNotFoundSnafu { region_id })?; engine - .set_region_role_with_lease(region_id, role, deadline) + .set_region_role_with_lease(region_id, role, sent_at, deadline) .with_context(|_| HandleRegionRequestSnafu { region_id }) } diff --git a/src/datanode/src/tests.rs b/src/datanode/src/tests.rs index 4fa247d07ca..a126d3429fd 100644 --- a/src/datanode/src/tests.rs +++ b/src/datanode/src/tests.rs @@ -292,10 +292,12 @@ impl RegionEngine for MockRegionEngine { fn set_region_role_with_lease( &self, _region_id: RegionId, - _role: RegionRole, + role: RegionRole, + _sent_at: std::time::Instant, _deadline: std::time::Instant, - ) -> Result<(), BoxedError> { - Ok(()) + ) -> Result { + // A mocked role stays, so a grant of another role is not applied. + Ok(self.mock_role.flatten().is_none_or(|mocked| mocked == role)) } async fn set_region_role_state_gracefully( diff --git a/src/file-engine/src/engine.rs b/src/file-engine/src/engine.rs index be1d141bcbd..98ad7409f43 100644 --- a/src/file-engine/src/engine.rs +++ b/src/file-engine/src/engine.rs @@ -137,9 +137,10 @@ impl RegionEngine for FileRegionEngine { &self, region_id: RegionId, role: RegionRole, + _sent_at: Instant, _deadline: Instant, - ) -> Result<(), BoxedError> { - self.set_region_role(region_id, role) + ) -> Result { + self.set_region_role(region_id, role).map(|_| true) } async fn set_region_role_state_gracefully( diff --git a/src/metric-engine/src/engine.rs b/src/metric-engine/src/engine.rs index 0c1b1114448..319ddc539d2 100644 --- a/src/metric-engine/src/engine.rs +++ b/src/metric-engine/src/engine.rs @@ -388,23 +388,27 @@ impl RegionEngine for MetricEngine { &self, region_id: RegionId, role: RegionRole, + sent_at: Instant, deadline: Instant, - ) -> Result<(), BoxedError> { - // ignore the region not found error + ) -> Result { + // The metadata region goes first. If it ignores the grant, the data region, whose role the + // engine reports, must not take it either. A region that is not found is ignored. for x in [ utils::to_metadata_region_id(region_id), utils::to_data_region_id(region_id), ] { - if let Err(e) = self + match self .inner .mito - .set_region_role_with_lease(x, role, deadline) - && e.status_code() != StatusCode::RegionNotFound + .set_region_role_with_lease(x, role, sent_at, deadline) { - return Err(e); + Ok(true) => {} + Ok(false) => return Ok(false), + Err(e) if e.status_code() != StatusCode::RegionNotFound => return Err(e), + Err(_) => {} } } - Ok(()) + Ok(true) } async fn sync_region( @@ -887,6 +891,42 @@ mod test { assert!(!object_store.exists(&data_region_dir).await.unwrap()); } + #[tokio::test] + async fn test_leader_grant_ignored_by_metadata_region_leaves_data_region() { + let env = TestEnv::new().await; + env.init_metric_region().await; + let (engine, mito) = (env.metric(), env.mito()); + let physical_region_id = env.default_physical_region_id(); + let lease = std::time::Duration::from_secs(10); + // The data region is downgraded before the heartbeat is sent, the metadata region after it. + let downgrade = |region_id| { + mito.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower) + }; + downgrade(utils::to_data_region_id(physical_region_id)) + .await + .unwrap(); + let sent_at = Instant::now(); + downgrade(utils::to_metadata_region_id(physical_region_id)) + .await + .unwrap(); + + let grant = |sent_at: Instant| { + engine + .set_region_role_with_lease( + physical_region_id, + RegionRole::Leader, + sent_at, + sent_at + lease, + ) + .unwrap() + }; + assert!(!grant(sent_at)); + assert_eq!(engine.role(physical_region_id), Some(RegionRole::Follower)); + + assert!(grant(Instant::now())); + assert_eq!(engine.role(physical_region_id), Some(RegionRole::Leader)); + } + #[tokio::test] async fn test_role() { let env = TestEnv::new().await; diff --git a/src/metric-engine/src/engine/put.rs b/src/metric-engine/src/engine/put.rs index e8098131612..eac38d0ab39 100644 --- a/src/metric-engine/src/engine/put.rs +++ b/src/metric-engine/src/engine/put.rs @@ -2379,7 +2379,7 @@ mod tests { let at = |n| start + n * Duration::from_secs(10); let grant = |n| { engine - .set_region_role_with_lease(physical_region_id, RegionRole::Leader, at(n)) + .set_region_role_with_lease(physical_region_id, RegionRole::Leader, start, at(n)) .unwrap() }; let expire = |n| mito.freeze_lease_clock(at(n)); diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 3791489d73f..c628b968b2b 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -1605,15 +1605,21 @@ impl RegionEngine for MitoEngine { &self, region_id: RegionId, role: RegionRole, + sent_at: Instant, deadline: Instant, - ) -> Result<(), BoxedError> { + ) -> Result { let region = self.inner.find_region(region_id).map_err(BoxedError::new)?; // Before the role, and even if the role leaves the region's state unchanged. if role.writable() { - region.leader_deadline.extend(deadline); + region.manifest_ctx.leader_deadline.extend(deadline); + } + if role == RegionRole::Leader { + return Ok(region + .manifest_ctx + .promote_unless_downgrade_started_after(sent_at, region_id)); } region.set_role(role); - Ok(()) + Ok(true) } async fn set_region_role_state_gracefully( diff --git a/src/mito2/src/engine/lease_test.rs b/src/mito2/src/engine/lease_test.rs index a0e68f7e94b..5fa0a897d63 100644 --- a/src/mito2/src/engine/lease_test.rs +++ b/src/mito2/src/engine/lease_test.rs @@ -13,8 +13,10 @@ // limitations under the License. //! Tests that a region acknowledges only writes whose WAL append completed within its leader -//! lease. +//! lease, and that Leader grants for heartbeats sent before a downgrade do not make it writable +//! again. +use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -24,8 +26,11 @@ use common_error::ext::{BoxedError, ErrorExt}; use common_recordbatch::RecordBatches; use rstest::rstest; use rstest_reuse::apply; -use store_api::region_engine::{RegionEngine, RegionRole}; -use store_api::region_request::{RegionCatchupRequest, RegionPutRequest, RegionRequest}; +use store_api::region_engine::{RegionEngine, RegionRole, SettableRegionRoleState}; +use store_api::region_request::{ + EnterStagingRequest, RegionCatchupRequest, RegionPutRequest, RegionRequest, + StagingPartitionDirective, +}; use store_api::storage::{RegionId, ScanRequest}; use tokio::task::JoinHandle; @@ -34,10 +39,11 @@ use crate::engine::MitoEngine; use crate::engine::basic_test::build_bulk_insert_request; use crate::engine::listener::WriteWalListener; use crate::error::Error; +use crate::region::{RegionLeaderState, RegionRoleState}; use crate::test_util::{ CreateRequestBuilder, LogStoreFactory, TestEnv, build_rows, kafka_log_store_factory, multiple_log_store_factories, prepare_test_for_kafka_log_store, raft_engine_log_store_factory, - rows_schema, + reopen_region, rows_schema, }; const LEASE: Duration = Duration::from_secs(10); @@ -66,10 +72,18 @@ async fn create_region( fn grant(engine: &MitoEngine, role: RegionRole, deadline: Instant) { engine - .set_region_role_with_lease(REGION_ID, role, deadline) + .set_region_role_with_lease(REGION_ID, role, Instant::now(), deadline) .unwrap(); } +/// Grants Leader for a heartbeat sent at `sent_at`, and returns whether the role was applied. +fn grant_leader_at(engine: &MitoEngine, sent_at: Instant) -> bool { + let deadline = Instant::now() + LEASE; + engine + .set_region_role_with_lease(REGION_ID, RegionRole::Leader, sent_at, deadline) + .unwrap() +} + /// Returns a request that writes rows `start..start + 3`. fn put_request(schema: &[ColumnSchema], start: usize) -> RegionRequest { let rows = Rows { @@ -282,3 +296,91 @@ async fn test_upgraded_region_writes_before_leader_grant() { .unwrap(); put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); } + +#[rstest] +#[case::downgrading(SettableRegionRoleState::DowngradingLeader)] +#[case::follower(SettableRegionRoleState::Follower)] +#[tokio::test] +async fn test_stale_leader_grant_after_downgrade(#[case] downgraded_to: SettableRegionRoleState) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("stale-leader-grant").await; + let (_listener, engine, _schema) = create_region(&mut env, None).await; + let sent_before = Instant::now() - Duration::from_millis(1); + engine + .set_region_role_state_gracefully(REGION_ID, downgraded_to) + .await + .unwrap(); + let downgraded = engine.get_region(REGION_ID).unwrap().state(); + // Another downgrade raises the gate again, though the role does not change. + let sent_between = Instant::now(); + engine + .set_region_role_state_gracefully(REGION_ID, downgraded_to) + .await + .unwrap(); + + // Grants for heartbeats sent before either downgrade arrive late. + assert!(!grant_leader_at(&engine, sent_before)); + assert!(!grant_leader_at(&engine, sent_between)); + assert_eq!(downgraded, engine.get_region(REGION_ID).unwrap().state()); + + assert!(grant_leader_at(&engine, Instant::now())); + assert!(engine.get_region(REGION_ID).unwrap().is_writable()); +} + +#[rstest] +#[case::catchup(false)] +#[case::close_and_open(true)] +#[tokio::test] +async fn test_reopened_region_ignores_earlier_grants(#[case] close: bool) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("reopened-region-grant").await; + let (_listener, engine, schema) = create_region(&mut env, None).await; + grant(&engine, RegionRole::Leader, Instant::now() + LEASE); + // The memtable is not empty, so the catchup below reopens the region. + put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); + let sent_before = Instant::now() - Duration::from_millis(1); + let region = engine.get_region(REGION_ID).unwrap(); + if close { + let table_dir = CreateRequestBuilder::new().build().table_dir; + reopen_region(&engine, REGION_ID, table_dir, false, HashMap::new()).await; + } else { + engine + .set_region_role_state_gracefully(REGION_ID, SettableRegionRoleState::Follower) + .await + .unwrap(); + let request = RegionRequest::Catchup(RegionCatchupRequest::default()); + engine.handle_request(REGION_ID, request).await.unwrap(); + } + assert!(!Arc::ptr_eq( + ®ion, + &engine.get_region(REGION_ID).unwrap() + )); + + assert!(!grant_leader_at(&engine, sent_before)); + assert!(!engine.get_region(REGION_ID).unwrap().is_writable()); + + grant(&engine, RegionRole::Leader, Instant::now() + LEASE); + assert!(engine.get_region(REGION_ID).unwrap().is_writable()); +} + +#[tokio::test] +async fn test_leader_grant_exits_staging() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("staging-leader-grant").await; + let (_listener, engine, _schema) = create_region(&mut env, None).await; + let request = EnterStagingRequest { + partition_directive: StagingPartitionDirective::RejectAllWrites, + }; + engine + .handle_request(REGION_ID, RegionRequest::EnterStaging(request)) + .await + .unwrap(); + let state = || engine.get_region(REGION_ID).unwrap().state(); + assert_eq!(RegionRoleState::Leader(RegionLeaderState::Staging), state()); + + grant(&engine, RegionRole::Leader, Instant::now() + LEASE); + assert_eq!( + RegionRoleState::Leader(RegionLeaderState::Writable), + state() + ); +} diff --git a/src/mito2/src/lease.rs b/src/mito2/src/lease.rs new file mode 100644 index 00000000000..95e076825eb --- /dev/null +++ b/src/mito2/src/lease.rs @@ -0,0 +1,91 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::LazyLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Instant; + +/// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64]. +static LEASE_EPOCH: LazyLock = LazyLock::new(Instant::now); + +fn lease_nanos(instant: Instant) -> u64 { + instant.saturating_duration_since(*LEASE_EPOCH).as_nanos() as u64 +} + +/// A lease deadline in nanoseconds since [LEASE_EPOCH]. It only moves forward; 0 means none. +#[derive(Debug, Default)] +pub(crate) struct Deadline(AtomicU64); + +impl Deadline { + pub(crate) fn extend(&self, deadline: Instant) { + self.0.fetch_max(lease_nanos(deadline), Ordering::Relaxed); + } + + pub(crate) fn get(&self) -> u64 { + self.0.load(Ordering::Relaxed) + } +} + +/// Lease of this node: the latest deadline of the heartbeat responses that carry region leases. +#[derive(Debug, Default)] +pub(crate) struct NodeLease { + /// Whether writes need a lease. Only a datanode the metasrv controls sets it. + enabled: AtomicBool, + deadline: Deadline, + /// The time of the lease checks while a test freezes it, in the unit of [Deadline]; 0 when + /// it is not frozen. + #[cfg(any(test, feature = "test"))] + frozen_now: AtomicU64, +} + +impl NodeLease { + pub(crate) fn enable(&self) { + self.enabled.store(true, Ordering::Relaxed); + } + + pub(crate) fn is_enabled(&self) -> bool { + self.enabled.load(Ordering::Relaxed) + } + + pub(crate) fn renew(&self, deadline: Instant) { + self.deadline.extend(deadline); + } + + /// Returns the current time in the unit of [Deadline]. + pub(crate) fn now(&self) -> u64 { + #[cfg(any(test, feature = "test"))] + { + let frozen_now = self.frozen_now.load(Ordering::Relaxed); + if frozen_now != 0 { + return frozen_now; + } + } + lease_nanos(Instant::now()) + } + + #[cfg(any(test, feature = "test"))] + pub(crate) fn freeze_clock(&self, at: Instant) { + self.frozen_now + .store(lease_nanos(at).max(1), Ordering::Relaxed); + } + + /// Lets a region created or upgraded on this node write until the node's deadline. The + /// metasrv granted that deadline before the creation or upgrade, so a later migration of the + /// region waits past it. Later responses do not extend it; the region's Leader grants do. + pub(crate) fn seed(&self, leader_deadline: &Deadline) { + leader_deadline + .0 + .fetch_max(self.deadline.get(), Ordering::Relaxed); + } +} diff --git a/src/mito2/src/lib.rs b/src/mito2/src/lib.rs index a01bca47dd7..116e8ed5833 100644 --- a/src/mito2/src/lib.rs +++ b/src/mito2/src/lib.rs @@ -31,6 +31,7 @@ pub mod error; pub mod extension; pub mod flush; pub mod gc; +mod lease; pub mod manifest; pub mod memtable; mod metrics; diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index ef5b24f9de5..923f223c8c7 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -23,8 +23,8 @@ pub(crate) mod version; use std::cell::OnceCell; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; -use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; -use std::sync::{Arc, LazyLock, Mutex, RwLock}; +use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, RwLock}; use std::time::Instant; use common_base::hash::partition_expr_version; @@ -59,6 +59,7 @@ use crate::error::{ FlushableRegionStateSnafu, InvalidPartitionExprSnafu, RegionNotFoundSnafu, RegionStateSnafu, RegionTruncatedSnafu, Result, UnexpectedSnafu, UpdateManifestSnafu, }; +use crate::lease::Deadline; use crate::manifest::action::{ RegionChange, RegionManifest, RegionMetaAction, RegionMetaActionList, }; @@ -186,8 +187,6 @@ pub struct MitoRegion { /// There are no WAL entries in range [flushed_entry_id, topic_latest_entry_id] for current region, /// which means these WAL entries maybe able to be pruned up to `topic_latest_entry_id`. pub(crate) topic_latest_entry_id: AtomicU64, - /// Deadline of the region's latest Leader or StagingLeader lease from the metasrv. - pub(crate) leader_deadline: Deadline, /// Region stats. pub(crate) region_stats: RegionStats, /// manifest stats @@ -224,80 +223,6 @@ impl RegionStats { pub type MitoRegionRef = Arc; -/// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64]. -static LEASE_EPOCH: LazyLock = LazyLock::new(Instant::now); - -fn lease_nanos(instant: Instant) -> u64 { - instant.saturating_duration_since(*LEASE_EPOCH).as_nanos() as u64 -} - -/// A lease deadline in nanoseconds since [LEASE_EPOCH]. It only moves forward; 0 means none. -#[derive(Debug, Default)] -pub(crate) struct Deadline(AtomicU64); - -impl Deadline { - pub(crate) fn extend(&self, deadline: Instant) { - self.0.fetch_max(lease_nanos(deadline), Ordering::Relaxed); - } - - pub(crate) fn get(&self) -> u64 { - self.0.load(Ordering::Relaxed) - } -} - -/// Lease of this node: the latest deadline of the heartbeat responses that carry region leases. -#[derive(Debug, Default)] -pub(crate) struct NodeLease { - /// Whether writes need a lease. Only a datanode the metasrv controls sets it. - enabled: AtomicBool, - deadline: Deadline, - /// The time of the lease checks while a test freezes it, in the unit of [Deadline]; 0 when - /// it is not frozen. - #[cfg(any(test, feature = "test"))] - frozen_now: AtomicU64, -} - -impl NodeLease { - pub(crate) fn enable(&self) { - self.enabled.store(true, Ordering::Relaxed); - } - - pub(crate) fn is_enabled(&self) -> bool { - self.enabled.load(Ordering::Relaxed) - } - - pub(crate) fn renew(&self, deadline: Instant) { - self.deadline.extend(deadline); - } - - /// Returns the current time in the unit of [Deadline]. - pub(crate) fn now(&self) -> u64 { - #[cfg(any(test, feature = "test"))] - { - let frozen_now = self.frozen_now.load(Ordering::Relaxed); - if frozen_now != 0 { - return frozen_now; - } - } - lease_nanos(Instant::now()) - } - - #[cfg(any(test, feature = "test"))] - pub(crate) fn freeze_clock(&self, at: Instant) { - self.frozen_now - .store(lease_nanos(at).max(1), Ordering::Relaxed); - } - - /// Lets a region created or upgraded on this node write until the node's deadline. The - /// metasrv granted that deadline before the creation or upgrade, so a later migration of the - /// region waits past it. Later responses do not extend it; the region's Leader grants do. - pub(crate) fn seed(&self, leader_deadline: &Deadline) { - leader_deadline - .0 - .fetch_max(self.deadline.get(), Ordering::Relaxed); - } -} - #[derive(Debug, Clone)] pub(crate) struct StagingPartitionInfo { pub(crate) partition_directive: StagingPartitionDirective, @@ -1290,6 +1215,17 @@ pub(crate) struct ManifestContext { /// The state of the region. The region checks the state before updating /// manifest. state: AtomicCell, + /// When the region last began a downgrade. A promotion issued before it does not apply. The + /// lock covers comparing or raising it and the role change. + /// + /// It starts at creation time, so promotions issued before the region was opened or reopened + /// do not apply. A context that replaces this one is created after the worker loop closes or + /// reopens the region, so after its last downgrade began. + downgrade_started_at: Mutex, + /// Deadline of the region's latest Leader or StagingLeader lease from the metasrv, which is how + /// long the Leader role stays valid. The engine extends it from those leases, and writes check + /// it. + pub(crate) leader_deadline: Deadline, /// Partition info of the region in staging mode. /// /// During the staging mode, the region metadata in [`VersionControlRef`] is not updated, @@ -1308,6 +1244,8 @@ impl ManifestContext { ManifestContext { manifest_manager: tokio::sync::RwLock::new(manager), state: AtomicCell::new(state), + downgrade_started_at: Mutex::new(Instant::now()), + leader_deadline: Deadline::default(), staging_partition_info: Mutex::new(None), hook, } @@ -1666,6 +1604,33 @@ impl ManifestContext { self.update_and_fire(manager, action_list, is_staging).await } + /// Raises the downgrade start time to now, then marks the region downgrading. + pub(crate) fn begin_downgrade(&self, region_id: RegionId) { + let mut downgrade_started_at = self.downgrade_started_at.lock().unwrap(); + *downgrade_started_at = Instant::now(); + self.set_role(RegionRole::DowngradingLeader, region_id); + } + + /// Promotes the region to a writable leader unless a downgrade started after `issued_at`. + /// Returns false if the promotion is ignored for that reason; otherwise the role changes as + /// [`Self::set_role`] allows. + pub(crate) fn promote_unless_downgrade_started_after( + &self, + issued_at: Instant, + region_id: RegionId, + ) -> bool { + // A writable leader needs no change; a staging leader is promoted below. + if self.state.load() == RegionRoleState::Leader(RegionLeaderState::Writable) { + return true; + } + let downgrade_started_at = self.downgrade_started_at.lock().unwrap(); + if issued_at < *downgrade_started_at { + return false; + } + self.set_role(RegionRole::Leader, region_id); + true + } + /// Sets the [`RegionRole`]. /// /// ```text @@ -2341,7 +2306,6 @@ mod tests { last_schedule_compaction_millis: Default::default(), time_provider: Arc::new(StdTimeProvider), topic_latest_entry_id: Default::default(), - leader_deadline: Default::default(), region_stats: RegionStats::new(), stats: ManifestStats::default(), } @@ -2457,6 +2421,24 @@ mod tests { } } + #[tokio::test] + async fn test_promoting_writable_leader_takes_no_lock() { + let env = SchedulerEnv::new().await; + let region = Arc::new(build_test_region(&env).await); + let _downgrade_started_at = region.manifest_ctx.downgrade_started_at.lock().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let promoted = region.clone(); + std::thread::spawn(move || { + let manifest_ctx = &promoted.manifest_ctx; + let issued_at = std::time::Instant::now(); + tx.send( + manifest_ctx.promote_unless_downgrade_started_after(issued_at, promoted.region_id), + ) + .unwrap(); + }); + assert!(rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap()); + } + #[tokio::test] async fn test_compaction_update_manifest_allows_editing_state() { let env = SchedulerEnv::new().await; @@ -2945,7 +2927,6 @@ mod tests { last_schedule_compaction_millis: Default::default(), time_provider: Arc::new(StdTimeProvider), topic_latest_entry_id: Default::default(), - leader_deadline: Default::default(), region_stats: RegionStats::new(), stats: ManifestStats::default(), }; diff --git a/src/mito2/src/region/opener.rs b/src/mito2/src/region/opener.rs index 947844c8f20..d10545198f7 100644 --- a/src/mito2/src/region/opener.rs +++ b/src/mito2/src/region/opener.rs @@ -459,7 +459,6 @@ impl RegionOpener { last_schedule_compaction_millis: AtomicI64::new(now), time_provider: self.time_provider.clone(), topic_latest_entry_id: AtomicU64::new(flushed_entry_id), - leader_deadline: Default::default(), region_stats: RegionStats::new(), stats: self.stats, })) @@ -698,7 +697,6 @@ impl RegionOpener { last_schedule_compaction_millis: AtomicI64::new(now), time_provider: self.time_provider.clone(), topic_latest_entry_id: AtomicU64::new(topic_latest_entry_id), - leader_deadline: Default::default(), region_stats: RegionStats::new(), stats: self.stats.clone(), }; diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index 50fb5bc0eb1..b93331d99dc 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -52,7 +52,7 @@ use rand::{Rng, rng}; use snafu::ResultExt; use store_api::logstore::LogStore; use store_api::region_engine::{ - RegionRole, SetRegionRoleStateResponse, SetRegionRoleStateSuccess, SettableRegionRoleState, + SetRegionRoleStateResponse, SetRegionRoleStateSuccess, SettableRegionRoleState, }; use store_api::storage::{FileId, RegionId}; use tokio::sync::mpsc::{Receiver, Sender}; @@ -67,12 +67,13 @@ use crate::config::MitoConfig; use crate::error::{self, CreateDirSnafu, JoinSnafu, Result, WorkerStoppedSnafu}; use crate::flush::{FlushScheduler, WriteBufferManagerImpl, WriteBufferManagerRef}; use crate::gc::{GcLimiter, GcLimiterRef}; +use crate::lease::NodeLease; use crate::memtable::MemtableBuilderProvider; use crate::metrics::{REGION_COUNT, REQUEST_WAIT_TIME, WRITE_STALLING}; use crate::region::opener::PartitionExprFetcherRef; use crate::region::{ - CatchupRegions, CatchupRegionsRef, MitoRegionRef, NodeLease, OpeningRegions, OpeningRegionsRef, - RegionMap, RegionMapRef, + CatchupRegions, CatchupRegionsRef, MitoRegionRef, OpeningRegions, OpeningRegionsRef, RegionMap, + RegionMapRef, }; use crate::request::{ BackgroundNotify, BulkInsertRequest, DdlRequest, OptionOutputTx, SenderBulkRequest, @@ -1516,8 +1517,9 @@ impl RegionWorkerLoop { ) { // Fence writes here: writes the worker handles later see // Downgrading, and earlier ones have finished. This only - // changes a writable or staging leader. - region.set_role(RegionRole::DowngradingLeader); + // changes a writable or staging leader, but always fences + // promotions issued before. + region.manifest_ctx.begin_downgrade(region_id); } #[cfg(feature = "hdfs-object-store")] let sweep_older_than = self.config.gc.unknown_file_lingering_time; diff --git a/src/mito2/src/worker/handle_catchup.rs b/src/mito2/src/worker/handle_catchup.rs index 65f20c5837a..0ca51b98a11 100644 --- a/src/mito2/src/worker/handle_catchup.rs +++ b/src/mito2/src/worker/handle_catchup.rs @@ -87,7 +87,7 @@ impl RegionWorkerLoop { if request.set_writable { // The region takes writes under the node lease until its next Leader // grant. - node_lease.seed(®ion.leader_deadline); + node_lease.seed(®ion.manifest_ctx.leader_deadline); region.set_role(RegionRole::Leader); // Finalize leadership: persist backfilled metadata. match region diff --git a/src/mito2/src/worker/handle_create.rs b/src/mito2/src/worker/handle_create.rs index 15641385e59..d2eab4a3f59 100644 --- a/src/mito2/src/worker/handle_create.rs +++ b/src/mito2/src/worker/handle_create.rs @@ -107,7 +107,7 @@ impl RegionWorkerLoop { } // The region takes writes under the node lease until its first Leader grant. - self.node_lease.seed(®ion.leader_deadline); + self.node_lease.seed(®ion.manifest_ctx.leader_deadline); // Insert the MitoRegion into the RegionMap. self.register_region(region); if let Some(state) = &self.series_index_task_state { diff --git a/src/mito2/src/worker/handle_write.rs b/src/mito2/src/worker/handle_write.rs index 6b8e5be4276..269859cb7e8 100644 --- a/src/mito2/src/worker/handle_write.rs +++ b/src/mito2/src/worker/handle_write.rs @@ -340,7 +340,7 @@ impl RegionWorkerLoop { match region.state() { RegionRoleState::Leader(RegionLeaderState::Writable) | RegionRoleState::Leader(RegionLeaderState::Staging) => { - let leader_deadline = region.leader_deadline.get(); + let leader_deadline = region.manifest_ctx.leader_deadline.get(); if lease_now.is_some_and(|now| now >= leader_deadline) { sender_req .sender @@ -497,7 +497,7 @@ impl RegionWorkerLoop { match region.state() { RegionRoleState::Leader(RegionLeaderState::Writable) | RegionRoleState::Leader(RegionLeaderState::Staging) => { - let leader_deadline = region.leader_deadline.get(); + let leader_deadline = region.manifest_ctx.leader_deadline.get(); if lease_now.is_some_and(|now| now >= leader_deadline) { bulk_req .sender @@ -606,7 +606,7 @@ impl RegionWorkerLoop { for (region_id, region_ctx) in region_ctxs.iter_mut() { // A Leader grant may have extended the deadline during the append. let expired = region_ctx.lease.as_ref().is_some_and(|(region, deadline)| { - now >= *deadline && now >= region.leader_deadline.get() + now >= *deadline && now >= region.manifest_ctx.leader_deadline.get() }); if !expired || region_ctx.is_failed() { continue; diff --git a/src/query/src/optimizer/test_util.rs b/src/query/src/optimizer/test_util.rs index a6b95ffdeba..09f72bb08b7 100644 --- a/src/query/src/optimizer/test_util.rs +++ b/src/query/src/optimizer/test_util.rs @@ -107,8 +107,9 @@ impl RegionEngine for MetaRegionEngine { &self, _region_id: RegionId, _role: RegionRole, + _sent_at: std::time::Instant, _deadline: std::time::Instant, - ) -> Result<(), BoxedError> { + ) -> Result { unimplemented!() } diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 6dffdd03c3b..2a2bc7b7f1f 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -1082,7 +1082,9 @@ pub trait RegionEngine: Send + Sync { /// take effect. fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<(), BoxedError>; - /// Sets [RegionRole] for a region from a lease the metasrv grants until `deadline`. + /// Sets [RegionRole] for a region from a lease the metasrv grants until `deadline`, in reply + /// to a heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because + /// the region was downgraded or (re)opened after `sent_at`. /// /// The region must not acknowledge a write whose WAL append completes at or after the /// deadline of its latest Leader or StagingLeader lease. Leases of other roles do not extend @@ -1091,8 +1093,9 @@ pub trait RegionEngine: Send + Sync { &self, region_id: RegionId, role: RegionRole, + sent_at: Instant, deadline: Instant, - ) -> Result<(), BoxedError>; + ) -> Result; /// Syncs the region manifest to the given manifest version. async fn sync_region( From ebb7e22566f8cb6246f39eab01e32488c682a2c8 Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Wed, 28 Oct 2026 12:51:52 +0000 Subject: [PATCH 10/19] chore(ci): gate fuzz, E2E and KV backends by diff scope (#9927) * ci: gate the integration CI long tail by diff scope `integration.yml` starts its long tail on every pull request: the three fuzz families, the chaos legs, the export/import E2E job and the two sqlness KvBackend legs. Most diffs cannot affect them, so a `scope` job now classifies the pull request and tells those jobs whether to start. The classifier is deterministic and fail-open. Forced modes (merge queue, `schedule`, `workflow_dispatch`, `ci:full`, `CI_SCOPE_FORCE_ALL`) and three floors -- always-run paths, an uncovered `src/` change, and a PromQL/flow filter -- can only widen the result; everything else is a glob match against the suite catalog. Every step of the job is `continue-on-error` and every gate reads `needs.scope.outputs. != 'false'`, so a classifier crash runs the jobs instead of skipping them. The rules are checked out from the pull request base, so a pull request cannot relax its own gate. The policy is data: `.github/ci/scope-rules.toml` holds the path groups, the suite catalog and the always-run list, with a `reason` on every exclusion. `ci_scope_rules.py` loads it with the stdlib `tomllib` and validates the shape (unknown or cyclic `@group` references, a `family` that disagrees with the suite id, an empty reason) and that every glob's literal prefix still exists, so a renamed crate cannot leave a rule that matches nothing. `make check-ci-scope` runs that check locally; the `CI Scope Rules` job runs it on `ubuntu-slim`, the same image the classifier uses. `.github/ci/scope-cases.toml` holds golden cases that `test_ci_scope.py` replays through the real classifier. The PostgreSQL and MySQL sqlness legs move into their own `sqlness-kvbackend` job so they can be gated: a job-level `if:` cannot read the matrix, and gating them inside `sqlness` would skip required checks and block the merge. They run the same cases as the required Basic leg, so only the backend itself matters. The verdict is visible where triage looks: one log line per suite, the exact gate values, `::warning::` when a lookup fails and the gate widens, and a job summary that lists each suite with the rule that decided it and the changed files that matched. Measured on 200 merged and open pull requests: 27.5% always run, 41% decided by path rules, 31.5% skip every gated job; 995 of 2600 suite selections are skipped, with no selection that a path rule makes. The classifier itself runs in about ten seconds on a single-vCPU runner. Signed-off-by: WenyXu * fix(ci): let the scope job read pull requests The `scope` job declared `permissions: contents: read`, and an explicit block sets every unlisted permission to `none`. `GET /pulls/{n}` therefore answered 403, `build_plan` widened to a full run as designed, and every gate read an absent output as "run": the gate could never skip anything. - `pull-requests: read` on the `scope` job. - `tests/runner/**` joins `@kv-backend`: the runner implements `--setup-pg`/`--setup-mysql`, which only the KV-backend legs pass, so a change there must not skip the only job that exercises it. The `UNMAPPED_CRATES` excuse is gone with it. - The README no longer claims a queue failure blocks the merge: the gated jobs are not required checks. Signed-off-by: WenyXu * fix(ci): run every suite when the kind registry script changes The distributed and chaos fuzz jobs start their cluster through `.github/actions/setup-kind`, which runs `.github/scripts/kind-with-registry.sh`. `.github/actions/**` is in `ALWAYS_RUN` but the script is not, so a change confined to it selected no suite at all and every gate stayed `false`: the jobs that exercise the changed cluster setup were skipped. The script joins `ALWAYS_RUN`, consistent with the action that calls it, and a golden case pins it. Signed-off-by: WenyXu * fix(ci): widen the gate for the fuzz corpus seeding script `fuzz-test/action.yaml` runs `.github/scripts/prepare-fuzz-corpus.sh` before the cache restore in every fuzz job, but the script was not in `ALWAYS_RUN`. A change confined to it therefore selected no suite: `any_fuzz` stayed `false` and every fuzz job that runs it was skipped. The script joins `ALWAYS_RUN` next to the other scripts the fuzz jobs execute, with a golden case for it. Both misses so far (this one and `kind-with-registry.sh`) came through a composite action, which the workflow never names. `WorkflowContractTests` now resolves `uses: ./.github/actions/` transitively for the gated jobs and fails when one of the scripts they run is not in `ALWAYS_RUN`. Signed-off-by: WenyXu --------- Signed-off-by: WenyXu --- .github/ci/README.md | 168 ++++ .github/ci/ci_scope.py | 623 ++++++++++++ .github/ci/ci_scope_rules.py | 277 ++++++ .github/ci/scope-rules.toml | 284 ++++++ .github/ci/tests/fixtures/scope-cases.toml | 158 +++ .github/ci/tests/test_ci_scope.py | 1018 ++++++++++++++++++++ .github/scripts/tests/test_ci_slash.py | 2 +- .github/workflows/checks.yml | 19 + .github/workflows/integration.yml | 161 +++- Makefile | 4 + 10 files changed, 2675 insertions(+), 39 deletions(-) create mode 100644 .github/ci/README.md create mode 100755 .github/ci/ci_scope.py create mode 100755 .github/ci/ci_scope_rules.py create mode 100644 .github/ci/scope-rules.toml create mode 100644 .github/ci/tests/fixtures/scope-cases.toml create mode 100755 .github/ci/tests/test_ci_scope.py diff --git a/.github/ci/README.md b/.github/ci/README.md new file mode 100644 index 00000000000..07de1fcae7b --- /dev/null +++ b/.github/ci/README.md @@ -0,0 +1,168 @@ +# Integration CI admission gate + +`integration.yml` runs its expensive jobs — fuzz, export/import E2E, the sqlness +KvBackend legs — on every non-draft pull request. Most pull requests cannot +affect any of them. This directory decides which of those jobs start, using only +the diff. + +The gate can only *skip* work, never add it, and it fails open: when the verdict +is missing or uncertain, every gated job runs. + +| File | Role | +|---|---| +| `ci_scope.py` | the classifier: reads the diff, writes `$GITHUB_OUTPUT` | +| `scope-rules.toml` | the policy: which paths select which suite, as data | +| `ci_scope_rules.py` | loads and validates the policy; `--check-paths` | +| `tests/` | unit tests, and `fixtures/scope-cases.toml` golden cases | + +Two words appear everywhere below. A **suite** is one matrix leg of a gated job, +named `/`. A **gate** is one `$GITHUB_OUTPUT` key that switches a +whole job. + +## What is gated + +Only `integration.yml`, and only these jobs: + +| Gated job | Runs | +|---|---| +| `prepare-fuzz-targets` | the fuzz targets only | +| `fuzztest` | standalone fuzz, 2 legs | +| `unstable-fuzztest` | unstable standalone create-table fuzz, 1 leg | +| `distributed-fuzztest` | distributed fuzz with remote WAL, 4 legs | +| `distributed-fuzztest-with-chaos` | Chaos Mesh, 3 legs | +| `build-greptime-ci` | the profile-CI binary only | +| `export-import-v2-e2e` | CLI `COPY DATABASE` export/import against S3 | +| `sqlness-kvbackend` | sqlness with PostgreSQL and MySQL as the metadata store | + +The legs themselves are the `matrix` entries in `integration.yml`; the rules +file repeats their ids so a verdict can name them. + +Everything else always runs: `rust.yml`, `checks.yml`, `docs.yml`, the debug +`build`, the required `sqlness` job (Basic, Remote WAL, Flat format), `compat` +and `compat-updater-check`. None of the gated jobs is in the required-check +matrix in `docs.yml`, so a skipped job can never block a merge. + +Two choices follow from that rule. The two KvBackend legs sit in their own +`sqlness-kvbackend` job because a job-level `if:` cannot read `matrix`, so +gating them inside `sqlness` would skip required checks and make the pull +request unmergeable. The multi-language SDK job stays ungated: it takes about +three minutes, less than the cost of getting its verdict wrong. + +## How a verdict is made + +First match wins: + +1. **Forced** — `merge_group`, `schedule`, `workflow_dispatch`, the `ci:full` + label or `CI_SCOPE_FORCE_ALL`. Everything runs. +2. **Too large to judge** — more than 300 changed files. Everything runs. +3. **Always-run file changed** — `Cargo.toml`, `Cargo.lock`, `tests-fuzz/**`, + this directory, or anything else that changes what the suites build or how + they start. Everything runs. +4. **Uncovered change** — a path under `src/` that no suite claims. This is the + net for a crate added, split or renamed after the rules were written. + Everything runs. +5. **Path rules** — the suites whose globs match the changed files, and only + those. + +The code is the source of truth for the details; its module docstring is worth +reading before changing it. + +## Why a check was skipped + +The run page's summary pane answers this without opening a log: one row per +suite, with its verdict, the rule that decided it, and up to three of the +changed files that matched. + +The step log of the `CI Scope` job has the same information in text form. It +starts with `CI scope: mode=… full=…` (`grep '^CI scope'` finds it), then one +line per suite — `run` or `skip`, source, reason — then `gates:` with the exact +values the jobs read. + +A degraded decision is never silent. A failed label or file lookup emits +`::warning::` and widens the gate to every suite. + +## Forcing a full run + +Add the `ci:full` label to the pull request and click "Re-run all jobs". The +label is read through the API at run time, not from the event payload, so one +added after the first run still counts. `/ci` dispatch +(`.github/scripts/ci-slash.py`), the `CI_SCOPE_FORCE_ALL` repository variable +and every merge-queue run also run everything: the classifier returns a forced +plan there, so a wrong skip is still exercised before the change lands. None of +the gated jobs is a required check, so a failure in the queue does not block the +merge by itself. + +`CI_SCOPE_FORCE_ALL` is the switch to flip while debugging the rules themselves. + +## Changing the rules + +`scope-rules.toml` is data, not code: `ci_scope_rules.py` loads it with the +standard library's `tomllib`. Two things are validated: + +- the shape — an unknown or cyclic `@group` reference, a `gate` that disagrees + with the suite id, a gate missing from `[gates]`, or an exemption without a + `reason` all raise; +- that every glob still points at something that exists, so a renamed or + deleted crate fails the check instead of silently matching nothing. + +Run both with `make check-ci-scope`, or the path half alone with +`python3 .github/ci/ci_scope_rules.py --check-paths`. The same command runs in +the `CI Scope Rules` job of `checks.yml`, on `ubuntu-slim` — the image the +classifier itself uses, so a path that exists there also exists when the verdict +is computed. + +A malformed file fails the classify step, and because every step of that job is +`continue-on-error`, every gated job runs instead. + +`[[matching.exempt]]` lists paths outside the gate's remit: they select no suite +and never widen the gate. Each one carries a `reason`, and the loader rejects an +empty one — what CI never runs is the part a reader must be able to justify. + +`tests/fixtures/scope-cases.toml` is test data, not configuration: a diff shape +and the suites it must start. `ScopeCaseTests` replays each case through the +classifier, so a rule edit that changes behaviour fails with the case name +instead of silently rerouting CI. The cases carry no pull request numbers; +`git log` has those. + +## Adding a suite + +1. Add a `[suites."/"]` table to `scope-rules.toml` with `gate`, + `paths` (globs or `@group` references) and a one-line `description`. The id + is `/`, and `gate` is that id with `-` replaced by `_`; + the loader and `test_suite_metadata` both enforce it. +2. Add the matching matrix leg to the job in `integration.yml`. +3. Gate the job's `if:` with the matching output, and list `scope` in its + `needs`. A new gate also needs a key in `derive_outputs` and in the `scope` + job's `outputs`; `test_every_gate_routes_to_an_output` fails when that + routing is missing. +4. Add a case to `tests/fixtures/scope-cases.toml` and run + `python3 .github/ci/tests/test_ci_scope.py`. `CrateCoverageTests` separately + fails when a workspace crate matches no suite and is not excused in + `UNMAPPED_CRATES`: the runtime net would run everything, but the rule table + is what should be updated. + +## Ground rules for the workflow + +These six rules keep the gate failing open. Break one and either CI runs jobs it +should have skipped, or a classifier failure takes CI down with it. + +- **Read the output as `!= 'false'`.** An absent output means "run"; writing + `== 'true'` inverts the failure direction. +- **Start every gate with `!cancelled()`.** Without a status function the + condition carries an implicit `success()` over `needs`, so a `scope` job that + times out would skip the gates. Other dependencies are therefore required + explicitly with `needs..result == 'success'`. +- **Every fallible step of `scope` is `continue-on-error: true`.** GitHub skips + the dependents of a *failed* job, so a classifier crash must leave the job + green with no outputs rather than take CI down with it. +- **Rules come from the base revision.** The `scope` job checks out + `pull_request.base.sha` (or `merge_group.base_sha`), so a pull request cannot + weaken its own gate. On the first pull request that introduces this directory + the base has no `ci_scope.py`: the step fails, no outputs are written, and + every gate runs. +- **One gate per job, never per leg.** GitHub does not expose `matrix` to + `jobs..if`. Per-suite verdicts stay visible in the log. +- **Pass the run's `head`/`base` SHAs and let the classifier compare them with + the pull request's live revisions.** A re-run keeps the original SHAs while + GitHub serves the *current* file list; without the comparison the new diff + would be judged against the old tree. With it, a mismatch runs everything. diff --git a/.github/ci/ci_scope.py b/.github/ci/ci_scope.py new file mode 100755 index 00000000000..571e975325a --- /dev/null +++ b/.github/ci/ci_scope.py @@ -0,0 +1,623 @@ +#!/usr/bin/env python3 +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Decide which integration CI suites must run for one pull request. + +Pipeline, in priority order: + +1. forced mode -- `merge_group`, `schedule`, `workflow_dispatch`, + `CI_SCOPE_FORCE_ALL`, or the `ci:full` label. Every suite runs. +2. always-run floor -- a changed file matches `ALWAYS_RUN`. Every suite runs. +3. uncovered build change -- a path under `SRC_TREE` that no suite claims, so a + crate added or renamed later still runs everything. +4. static path matches -- glob match of the changed files against the suite + catalog in `scope-rules.toml`. Paths under `EXEMPT_TREES` are outside the + gate's remit and are dropped first: `@server` claims `src/query/**`, which + would otherwise put a PromQL-only change through the whole fleet. + +The verdict is deterministic: the same diff always produces the same plan, and +a change that no rule explains falls through to "run everything". + +The plan maps to `$GITHUB_OUTPUT` keys that the `integration.yml` gate jobs +consume; `--dry-run` prints them as JSON. +""" + +import argparse +import json +import os +import re +import sys +import urllib.error +import urllib.request + +from ci_scope_rules import ( + ALWAYS_RUN, + EXEMPT_TREES, + SRC_TREE, + SUITES, + suite_group, + suite_paths, +) + +MAX_FILES = 300 +HTTP_TIMEOUT = 45 +FORCED_EVENTS = {"merge_group", "schedule", "workflow_dispatch"} +# A diff with no code, config or workflow file never needs a suite. +CODE_FILE = re.compile( + r"\.(rs|toml|lock|sh|ya?ml)$|(^|/)Makefile$|(^|/)Cargo\.toml$|\.sql$" +) +FUZZ_GATES = ("fuzz_standalone", "fuzz_distributed", "fuzz_chaos") + + +class ScopeError(Exception): + """A handled failure: the caller falls back instead of crashing.""" + + +# --------------------------------------------------------------------------- +# HTTP seam (tests replace `_request`) +# --------------------------------------------------------------------------- + + +def _request(method, url, headers, body=None, timeout=HTTP_TIMEOUT): + request = urllib.request.Request(url, data=body, headers=headers, method=method) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + return response.status, response.read() + except urllib.error.HTTPError as err: + return err.code, err.read() + except (urllib.error.URLError, TimeoutError, OSError) as err: + raise ScopeError(f"{method} {url}: {err}") from err + + +def _get(url, headers, timeout=HTTP_TIMEOUT): + return _request("GET", url, headers, None, timeout) + + +def _post(url, headers, body, timeout=HTTP_TIMEOUT): + return _request("POST", url, headers, body, timeout) + + +def get_json(url, headers, timeout=HTTP_TIMEOUT): + """GET returning (status, parsed json); transport failures raise `ScopeError`.""" + status, raw = _get(url, headers, timeout) + try: + payload = json.loads(raw.decode("utf-8", "replace")) if raw else None + except json.JSONDecodeError: + payload = None + return status, payload + + +# --------------------------------------------------------------------------- +# Path matching +# --------------------------------------------------------------------------- + + +def glob_to_regex(pattern): + """Translate a repo glob into an anchored regexp. + + `**/` also matches zero directories, `**` spans `/`, `*` and `?` do not. + """ + out = ["^"] + index = 0 + while index < len(pattern): + char = pattern[index] + if char == "*": + end = index + while end < len(pattern) and pattern[end] == "*": + end += 1 + if end - index >= 2: + if end < len(pattern) and pattern[end] == "/": + out.append("(?:.*/)?") + index = end + 1 + continue + out.append(".*") + else: + out.append("[^/]*") + index = end + elif char == "?": + out.append("[^/]") + index += 1 + else: + out.append(re.escape(char)) + index += 1 + out.append("$") + return re.compile("".join(out)) + + +def compile_patterns(patterns): + return [glob_to_regex(pattern) for pattern in patterns] + + +def matches_any(filename, compiled): + return any(regex.match(filename) for regex in compiled) + + +# --------------------------------------------------------------------------- +# GitHub API +# --------------------------------------------------------------------------- + + +def github_api(method, path, token, payload=None): + base = os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/") + url = base + path + headers = { + "Accept": "application/vnd.github+json", + "User-Agent": "greptimedb-ci-scope", + } + if token: + headers["Authorization"] = "Bearer " + token + body = None + if payload is not None: + body = json.dumps(payload).encode() + headers["Content-Type"] = "application/json" + if method == "GET": + return get_json(url, headers) + status, raw = _request(method, url, headers, body, HTTP_TIMEOUT) + try: + parsed = json.loads(raw.decode("utf-8", "replace")) if raw else None + except json.JSONDecodeError: + parsed = None + return status, parsed + + +def fetch_changed_files(repo, number, token): + """Return (files, truncated). `truncated` means the PR has more than MAX_FILES.""" + files = [] + page = 1 + while True: + status, payload = github_api( + "GET", f"/repos/{repo}/pulls/{number}/files?per_page=100&page={page}", token + ) + if status != 200 or not isinstance(payload, list): + raise ScopeError(f"cannot list pull request files (HTTP {status})") + for item in payload: + if not isinstance(item, dict): + continue + patch = item.get("patch") + files.append( + { + "filename": item.get("filename", ""), + "previous_filename": item.get("previous_filename") or "", + "status": item.get("status", "modified"), + "additions": item.get("additions", 0), + "deletions": item.get("deletions", 0), + "patch": patch if isinstance(patch, str) else "", + "patch_included": isinstance(patch, str) and bool(patch), + } + ) + if len(payload) < 100: + return files, False + if len(files) >= MAX_FILES: + # Keep `per_page=100`: with `per_page=1`, page N is item N, so the + # probe would answer "is there a file 4?" instead of "file 301?". + status, extra = github_api( + "GET", + f"/repos/{repo}/pulls/{number}/files?per_page=100&page={page + 1}", + token, + ) + if status != 200 or not isinstance(extra, list): + raise ScopeError( + "cannot confirm the changed file list is complete " + f"(HTTP {status})" + ) + del files[MAX_FILES:] + return files, bool(extra) + page += 1 + + +def fetch_pull(repo, number, token): + """Return (labels, head sha, base sha) for one pull request.""" + status, payload = github_api("GET", f"/repos/{repo}/pulls/{number}", token) + if status != 200 or not isinstance(payload, dict): + raise ScopeError(f"cannot read pull request (HTTP {status})") + labels = payload.get("labels") or [] + head = ((payload.get("head") or {}).get("sha") or "").strip() + base = ((payload.get("base") or {}).get("sha") or "").strip() + names = {label.get("name", "") for label in labels if isinstance(label, dict)} + return names, head, base + + +def revision_drift(args, head, base): + """Return a note when the tested revisions are no longer the live ones. + + A re-run keeps the run's original SHAs while the file list served by GitHub + is the pull request's current one. After a force-push the classifier would + judge the new diff for the old tree, so a mismatch runs every suite instead. + """ + for supplied, live, name in ( + (args.head_sha, head, "head"), + (args.base_sha, base, "base"), + ): + if supplied and live and supplied.lower() != live.lower(): + return ( + f"pull request {name} moved from {supplied[:12]} to " + f"{live[:12]} after this run started" + ) + return "" + + +# --------------------------------------------------------------------------- +# Decisions +# --------------------------------------------------------------------------- + + +def file_paths(item): + """Every path the change touched; a rename keeps the deleted side too.""" + names = [item["filename"]] + previous = item.get("previous_filename") + if previous and previous != item["filename"]: + names.append(previous) + return names + + +def gated_paths(item): + """The paths of one changed file that the gate judges. + + A path under `EXEMPT_TREES` is outside the remit: it selects no suite, and + it is not a change that "no rule covers", so it cannot widen the gate. + """ + return [name for name in file_paths(item) if not name.startswith(EXEMPT_TREES)] + + +def path_matches(files): + """Return (always_run_hits, {suite_id: [matching file paths]}).""" + always_compiled = compile_patterns(ALWAYS_RUN) + suite_matchers = { + suite_id: compile_patterns(suite_paths(suite)) + for suite_id, suite in SUITES.items() + } + always_hits = set() + matches = {suite_id: set() for suite_id in SUITES} + for item in files: + for name in file_paths(item): + if matches_any(name, always_compiled): + always_hits.add(name) + for name in gated_paths(item): + for suite_id, compiled in suite_matchers.items(): + if matches_any(name, compiled): + matches[suite_id].add(name) + return sorted(always_hits), { + suite_id: sorted(matched) for suite_id, matched in matches.items() + } + + +def uncovered_changes(files, matches): + """True when a change can reach code that no suite path claims. + + This is the net for a crate that was added, split or renamed after the rules + were written: without it such a change matches no suite and would skip every + gated job. A single unmatched path is enough, even when other paths in the + same diff match a suite. + """ + return first_uncovered(files, matches) is not None + + +def first_uncovered(files, matches): + """The first changed path that no suite claims, or None. + + Naming it is what makes the widening explainable in the log. + """ + matched = {name for names in matches.values() for name in names} + return next( + ( + name + for item in files + for name in gated_paths(item) + if name.startswith(SRC_TREE) and name not in matched + ), + None, + ) + + +def has_meaningful_changes(files): + return any(CODE_FILE.search(item["filename"]) for item in files) + + +def finalize(plan): + """`full` means every gated suite runs, whatever produced the decision.""" + plan["full"] = all(entry["run"] for entry in plan["suites"].values()) + return plan + + +def all_suites(run, reason, source): + return { + suite_id: {"run": run, "source": source, "reason": reason} + for suite_id in SUITES + } + + +def full_plan(plan, reason, source, mode="static"): + """Every suite runs; `finalize` derives `full` from the verdicts.""" + plan.update(mode=mode, suites=all_suites(True, reason, source)) + return finalize(plan) + + +def forced_reason(args, labels): + """Return why every suite must run, or an empty string.""" + event = args.event or os.environ.get("GITHUB_EVENT_NAME") or "pull_request" + if event in FORCED_EVENTS: + return f"event={event}" + if os.environ.get("CI_SCOPE_FORCE_ALL", "").strip().lower() in { + "1", + "true", + "yes", + "on", + }: + return "CI_SCOPE_FORCE_ALL" + if "ci:full" in labels: + return "label ci:full" + return "" + + +def build_plan(args, token): + notes = [] + plan = { + "mode": "static", + "head_sha": args.head_sha or "", + "base_sha": args.base_sha or "", + "full": False, + "suites": {}, + "matching": {}, + "notes": notes, + } + + # Events and variables that force a run need no GitHub call at all; the + # `ci:full` label is the only reason to read the pull request early. + forced = forced_reason(args, set()) + labels, head_live, base_live = set(), "", "" + if args.pr and not forced: + try: + labels, head_live, base_live = fetch_pull( + args.repo, args.pr, token + ) + except ScopeError as err: + # A failed lookup must widen the gate, never narrow it. + notes.append(f"pull request lookup failed: {err}") + return full_plan(plan, "pull request lookup failed", "always-run") + forced = forced_reason(args, labels) + + if forced: + notes.append(f"forced: {forced}") + return full_plan(plan, f"forced by {forced}", "forced", mode="forced") + + if not args.pr: + raise ScopeError("--pr is required unless the event forces every suite") + + drift = revision_drift(args, head_live, base_live) + if drift: + notes.append(drift) + return full_plan(plan, drift, "always-run") + + files, truncated = fetch_changed_files(args.repo, args.pr, token) + if truncated: + notes.append(f"changed file list truncated at {MAX_FILES}") + return full_plan( + plan, + f"pull request has more than {MAX_FILES} changed files", + "always-run", + ) + + always_hits, matches = path_matches(files) + # Keep the evidence: the step summary explains a verdict by naming the files + # that matched, which is what triage asks for first. + plan["matching"] = {suite_id: sorted(names) for suite_id, names in matches.items()} + if always_hits: + notes.append(f"always-run: {', '.join(sorted(always_hits)[:5])}") + return full_plan( + plan, + "always-run path: " + ", ".join(sorted(always_hits)[:3]), + "always-run", + ) + + first = first_uncovered(files, matches) + if first is not None: + notes.append(f"uncovered build change: {first}") + return full_plan(plan, f"uncovered build change: {first}", "uncovered") + + static_run = {suite_id: bool(matched) for suite_id, matched in matches.items()} + + if not has_meaningful_changes(files) and not any(static_run.values()): + plan.update( + mode="static", + full=False, + suites={ + suite_id: { + "run": False, + "source": "static", + "reason": "no code, config or workflow file changed", + } + for suite_id in SUITES + }, + ) + notes.append("no meaningful changes: skip every suite") + return finalize(plan) + + plan.update( + mode="static", + suites={ + suite_id: { + "run": static_run[suite_id], + "source": "static", + "reason": ("path rule: " + ", ".join(matches[suite_id][:3])) + if matches[suite_id] + else "no path rule matched", + } + for suite_id in SUITES + }, + ) + return finalize(plan) + + +def derive_outputs(plan): + """Flatten the plan into the `$GITHUB_OUTPUT` keys the workflow gates on. + + + Every gate in `SUITES` must route to a key here, otherwise its suites are + classified but never switch a job; `test_every_gate_routes_to_an_output` + asks this function directly, so a new gate fails there until it is routed. + + + Job-level `if:` cannot read the `matrix` context, so the workflow gates a + whole fuzz gate instead of individual matrix legs; the per-suite verdicts + stay visible in the step log. + """ + + def suites_of(gate): + return [ + suite_id + for suite_id, entry in plan["suites"].items() + if entry["run"] and SUITES[suite_id]["gate"] == gate + ] + + outputs = {} + legs = {} + for gate in FUZZ_GATES: + running = suites_of(gate) + legs[gate] = [suite_group(suite_id) for suite_id in running] + legs[gate] = [leg for leg in legs[gate] if leg] + outputs[gate] = "true" if running else "false" + unstable = bool(suites_of("fuzz_unstable")) + # Every gate outside the fuzz group switches exactly one job of its own. + for gate in sorted({suite["gate"] for suite in SUITES.values()}): + if gate not in FUZZ_GATES: + outputs[gate] = "true" if suites_of(gate) else "false" + outputs["any_fuzz"] = ( + "true" + if unstable or any(outputs[gate] == "true" for gate in FUZZ_GATES) + else "false" + ) + distributed = outputs["fuzz_distributed"] == "true" or outputs["fuzz_chaos"] == "true" + outputs["build_ci_needed"] = "true" if unstable or distributed else "false" + return outputs, legs + + +def render_log(plan): + """One line per suite plus the emitted gates, for the step log. + + Triage starts in the run log, so the verdict has to be readable there + without any other artifact. + """ + head = f"CI scope: mode={plan['mode']} full={'true' if plan['full'] else 'false'}" + lines = [head] + width = max((len(suite_id) for suite_id in plan["suites"]), default=0) + for suite_id, entry in plan["suites"].items(): + lines.append( + f" {'run ' if entry['run'] else 'skip'} {suite_id:<{width}} " + f"{entry['source']:<12} {entry['reason']}" + ) + outputs, _ = derive_outputs(plan) + lines.append( + " gates: " + " ".join(f"{key}={value}" for key, value in outputs.items()) + ) + for note in plan["notes"]: + lines.append(f" note: {note}") + return "\n".join(lines) + + +SUMMARY_MAX_FILES = 3 + + +def render_summary(plan): + """Markdown for the job summary: the matching evidence behind each verdict. + + The step log answers "what ran"; this answers "why", which is the question + when a pull request unexpectedly skips or starts a suite. + """ + lines = [ + f"### CI scope: mode={plan['mode']}, full={'true' if plan['full'] else 'false'}", + "", + "| suite | verdict | rule | matched files |", + "| --- | --- | --- | --- |", + ] + matching = plan.get("matching") or {} + for suite_id, entry in plan["suites"].items(): + matched = matching.get(suite_id) or [] + shown = ", ".join(f"`{name}`" for name in matched[:SUMMARY_MAX_FILES]) + if len(matched) > SUMMARY_MAX_FILES: + shown += f" +{len(matched) - SUMMARY_MAX_FILES} more" + lines.append( + f"| `{suite_id}` | {'run' if entry['run'] else 'skip'} | " + f"{entry['source']} | {shown or '—'} |" + ) + if plan["notes"]: + lines += ["", "

notes", ""] + lines += [f"- {note}" for note in plan["notes"]] + lines += ["", "
"] + return "\n".join(lines) + + +def log_annotations(plan): + """Workflow-run annotations for every degraded decision. + + A lookup failure widens the gate; it must be visible in the run list without + opening the job log, otherwise it looks like a confident verdict. + """ + annotations = [] + for note in plan["notes"]: + if note.startswith("pull request lookup failed"): + suffix = "every suite runs" + level = "warning" + else: + continue + message = f"CI scope: {note}; {suffix}"[:300] + annotations.append(f"::{level}::{message}") + return annotations + + +def emit(plan, args): + outputs, _ = derive_outputs(plan) + if args.dry_run: + print(json.dumps(outputs, indent=2)) + elif args.github_output: + with open(args.github_output, "a", encoding="utf-8") as handle: + for key, value in outputs.items(): + handle.write(f"{key}={value}\n") + if args.summary: + with open(args.summary, "a", encoding="utf-8") as handle: + handle.write(render_summary(plan) + "\n") + + +def parse_args(argv): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY", "")) + parser.add_argument("--pr", type=int) + parser.add_argument("--head-sha", default="") + parser.add_argument("--base-sha", default="") + parser.add_argument( + "--event", + choices=["pull_request", "merge_group", "schedule", "workflow_dispatch"], + ) + parser.add_argument("--github-output") + parser.add_argument( + "--summary", + help="append the markdown matching table to this file ($GITHUB_STEP_SUMMARY)", + ) + parser.add_argument("--dry-run", action="store_true") + return parser.parse_args(argv) + + +def main(argv=None): + args = parse_args(argv) + token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") or "" + plan = build_plan(args, token) + for annotation in log_annotations(plan): + print(annotation) + print(render_log(plan)) + emit(plan, args) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/ci/ci_scope_rules.py b/.github/ci/ci_scope_rules.py new file mode 100755 index 00000000000..c7453424848 --- /dev/null +++ b/.github/ci/ci_scope_rules.py @@ -0,0 +1,277 @@ +#!/usr/bin/env python3 +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Policy for the integration CI admission gate. + +The rules are data and live in `.github/ci/scope-rules.toml` so they can be +reviewed and changed without touching the classifier. This module parses that +file once at import, validates it, and exposes the names `ci_scope.py` uses. + +A malformed file raises at import: the classifier job's steps are +`continue-on-error`, so a broken rules file leaves the gate outputs empty and +every gated job runs. +""" + +import argparse +import pathlib +import sys +import tomllib + +RULES_PATH = pathlib.Path(__file__).resolve().with_name("scope-rules.toml") +# `.github/ci/scope-rules.toml`: parents[0] is `.github/ci`, parents[2] the repo. +REPO_ROOT = RULES_PATH.parents[2] + + + +class RulesError(ValueError): + """The rules file is missing, malformed or internally inconsistent.""" + + +def _require(table, key, where): + if key not in table: + raise RulesError(f"{where} is missing `{key}`") + return table[key] + + +def _strings(value, where): + if not isinstance(value, list) or not all(isinstance(item, str) for item in value): + raise RulesError(f"{where} must be an array of strings") + return list(value) + + +def _trees(entries, where): + """Normalise `[[matching.*_tree]]` tables into bare path prefixes. + + Each entry carries a `reason`: the exclusions decide what CI never runs, so + the justification is part of the contract, not a comment. + """ + if not isinstance(entries, list): + raise RulesError(f"{where} must be an array of tables") + paths = [] + for index, entry in enumerate(entries): + if not isinstance(entry, dict): + raise RulesError(f"{where}[{index}] is not a table") + path = _require(entry, "path", f"{where}[{index}]") + if not isinstance(path, str) or not path: + raise RulesError(f"{where}[{index}].path must be a non-empty string") + reason = _require(entry, "reason", f"{where}[{index}]") + if not isinstance(reason, str) or not reason.strip(): + raise RulesError(f"{where}[{index}].reason must explain the exclusion") + paths.append(path) + return paths + + +def validate(data): + """Check the shape of a parsed rules document and return it normalised.""" + if not isinstance(data, dict): + raise RulesError("rules document is not a table") + matching = _require(data, "matching", "the rules file") + gates_in = _require(data, "gates", "the rules file") + groups_in = _require(data, "groups", "the rules file") + suites_in = _require(data, "suites", "the rules file") + + groups = {} + for name, paths in groups_in.items(): + groups[name] = _strings(paths, f"groups.{name}") + + def expand(entries, stack=()): + out = [] + for entry in entries: + if not entry.startswith("@"): + out.append(entry) + continue + name = entry[1:] + if name not in groups: + raise RulesError(f"unknown path group `{entry}`") + if name in stack: + raise RulesError(f"path group cycle: {' -> '.join(stack + (name,))}") + out.extend(expand(groups[name], stack + (name,))) + return out + + for name in groups: + expand([f"@{name}"]) # every group must resolve on its own + + suites = {} + for suite_id, suite in suites_in.items(): + if not isinstance(suite, dict): + raise RulesError(f"suites.{suite_id} is not a table") + gate = _require(suite, "gate", f"suites.{suite_id}") + paths = _strings( + _require(suite, "paths", f"suites.{suite_id}"), f"suites.{suite_id}.paths" + ) + description = _require(suite, "description", f"suites.{suite_id}") + if not isinstance(description, str) or not description.strip(): + raise RulesError(f"suites.{suite_id}.description is empty") + # `gate/leg` for a matrix job, or a bare gate for a single-leg job. + prefix = suite_id.split("/", 1)[0].replace("-", "_") + if prefix != gate: + raise RulesError( + f"suites.{suite_id}.gate is `{gate}`, expected `{prefix}`" + ) + expand(paths) + suites[suite_id] = { + "gate": gate, + "paths": paths, + "description": description, + } + + gate_jobs = {} + for gate, job in gates_in.items(): + if not isinstance(job, str) or not job: + raise RulesError(f"gates.{gate} must name a job id") + gate_jobs[gate] = job + used = {suite["gate"] for suite in suites.values()} + unknown = sorted(used - set(gate_jobs)) + if unknown: + raise RulesError(f"suites use gates missing from [gates]: {', '.join(unknown)}") + dead = sorted(set(gate_jobs) - used) + if dead: + raise RulesError(f"[gates] names gates no suite uses: {', '.join(dead)}") + + return { + "always_run": _strings( + _require(matching, "always_run", "matching"), "matching.always_run" + ), + "src_tree": _require(matching, "src_tree", "matching"), + "exempt_trees": _trees( + _require(matching, "exempt", "matching"), "matching.exempt" + ), + "gates": gate_jobs, + "groups": groups, + "suites": suites, + } + + +def load(path=None): + """Parse and validate the rules file.""" + path = RULES_PATH if path is None else path + try: + raw = pathlib.Path(path).read_bytes() + except OSError as err: + raise RulesError(f"cannot read {path}: {err}") from err + try: + data = tomllib.loads(raw.decode("utf-8")) + except (tomllib.TOMLDecodeError, UnicodeDecodeError) as err: + raise RulesError(f"{path} is not valid TOML: {err}") from err + return validate(data) + + +_RULES = load() + +ALWAYS_RUN = _RULES["always_run"] +SRC_TREE = _RULES["src_tree"] +EXEMPT_TREES = tuple(_RULES["exempt_trees"]) +GATE_JOBS = _RULES["gates"] +PATH_GROUPS = _RULES["groups"] +SUITES = _RULES["suites"] + + +def main(argv=None): + """Validate the rules file and print what it holds; non-zero on failure.""" + parser = argparse.ArgumentParser(description="Validate the CI scope rules.") + parser.add_argument( + "--check-paths", + action="store_true", + help="also fail when a pattern's literal prefix does not exist", + ) + args = parser.parse_args(argv) + try: + rules = load() + except RulesError as err: + print(f"scope rules invalid: {err}", file=sys.stderr) + return 1 + if args.check_paths: + missing = missing_paths(rules) + for pattern, prefix in missing: + print(f"missing path: {pattern} (nothing under {prefix})", file=sys.stderr) + return 1 if missing else 0 + print( + f"scope rules ok: {len(rules['suites'])} suites, " + f"{len(rules['groups'])} path groups, " + f"{len(rules['always_run'])} always-run entries" + ) + return 0 + + +def suite_group(suite_id): + """Return the matrix group id encoded in a suite id, or None.""" + _, _, group = suite_id.partition("/") + return group or None + + +def expand_paths(entries, groups=None): + """Expand `@group` references, including groups nested in other groups.""" + groups = PATH_GROUPS if groups is None else groups + patterns = [] + for entry in entries: + if entry.startswith("@"): + patterns.extend(expand_paths(groups[entry[1:]], groups)) + else: + patterns.append(entry) + return patterns + + +def suite_paths(suite): + """Expand `@group` references in one suite definition into globs.""" + return expand_paths(suite["paths"]) + + +def _literal_prefix(pattern): + """Return the longest leading path that the glob cannot vary. + + Everything from the first `*`, `?` or `[` onwards is variable. When that + wildcard sits inside a segment the incomplete segment is dropped, so + `src/a/foo*.rs` yields `src/a/`; a wildcard in the very first segment (for + example `*.md`) yields `""` because the whole path is variable. + """ + cuts = [pattern.find(ch) for ch in "*?[" if ch in pattern] + if not cuts: + return pattern + prefix = pattern[: min(cuts)] + if "/" not in prefix: + return "" + return prefix.rsplit("/", 1)[0] + "/" + + +def _all_patterns(rules): + """Every glob the rules mention, with `@group` references expanded.""" + patterns = [] + for key in ("always_run", "exempt_trees"): + patterns.extend(expand_paths(rules[key], rules["groups"])) + for suite in rules["suites"].values(): + patterns.extend(expand_paths(suite["paths"], rules["groups"])) + return patterns + + +def missing_paths(rules=None, root=None): + """Return `(pattern, prefix)` for patterns whose literal prefix is absent. + + A rule that names a directory nobody renamed would otherwise match nothing + forever, silently narrowing the gate. A pattern with no fixed prefix is + skipped: there is nothing on disk to check. + """ + rules = _RULES if rules is None else rules + root = pathlib.Path(REPO_ROOT if root is None else root) + missing = set() + for pattern in _all_patterns(rules): + prefix = _literal_prefix(pattern) + if prefix and not (root / prefix).exists(): + missing.add((pattern, prefix)) + return sorted(missing) + + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/ci/scope-rules.toml b/.github/ci/scope-rules.toml new file mode 100644 index 00000000000..ba2b92deda2 --- /dev/null +++ b/.github/ci/scope-rules.toml @@ -0,0 +1,284 @@ +# Rules for the integration CI admission gate. +# +# Data only: `ci_scope_rules.py` loads this file with the stdlib `tomllib`, and +# `ci_scope.py` matches diffs against it. Edit this file, not the code, when a +# suite's paths change. +# +# Conventions +# ----------- +# - `**` crosses directories, `*` does not; a trailing `/**` covers everything +# under a directory. +# - `@name` inside `suites.*.paths` expands `[groups].name`, and groups may +# reference other groups. Expansion is recursive. +# - A suite id is `/`; `gate` is the `$GITHUB_OUTPUT` +# key that switches the job, and it must equal the id prefix with `-` +# replaced by `_`. +# - Everything here is a floor, never a filter: an unmatched `src/` path runs +# every suite, and a malformed file fails the classifier job, whose steps are +# `continue-on-error`, so the gated jobs run. + +[matching] +# A changed file matching one of these runs every suite. +# Put here anything that changes what the suites build or how they start. +always_run = [ + "Cargo.toml", + "Cargo.lock", + "rust-toolchain.toml", + ".cargo/**", + "tests-fuzz/**", + "tests-integration/**", + "config/**", + "docker/**", + ".github/ci/**", + ".github/workflows/integration.yml", + ".github/actions/**", + # Both run through a composite action, so neither appears in the workflow: + # `setup-kind` starts the cluster for the distributed and chaos jobs, and + # `fuzz-test` seeds the corpus every fuzz job starts from. + ".github/scripts/kind-with-registry.sh", + ".github/scripts/prepare-fuzz-corpus.sh", + ".github/scripts/run-fuzz-targets.sh", + ".github/scripts/collect-fuzz-target-artifacts.sh", + ".github/scripts/wait-kafka-ready.sh", + ".github/scripts/pull-test-deps-images.sh", +] + +# A change under `src/` that no suite claims runs every suite: that is the net +# for a crate added, split or renamed after these rules were written. +src_tree = "src/" + +# Paths outside the gate's remit. They select no suite, and they do not count as +# "no rule covers this" either, so they never widen the gate. Each needs a +# `reason`: what CI covers them instead. +[[matching.exempt]] +path = "src/promql/" +reason = "PromQL crate: rust.yml and the promql sqlness cases own it; the fuzz suites speak SQL." + +[[matching.exempt]] +path = "src/query/src/promql/" +reason = "PromQL module inside `src/query`, which `@server` claims as `src/query/**`." + +[[matching.exempt]] +path = "src/flow/" +reason = "Flow engine: rust.yml and the flow sqlness cases own it; no fuzz suite loads it." + +# Which job each gate switches. The keys are `$GITHUB_OUTPUT` names; the values +# are job ids in `integration.yml`. The classifier cannot read YAML, so the +# mapping is data here, and a test proves both directions line up. +[gates] +fuzz_standalone = "fuzztest" +fuzz_unstable = "unstable-fuzztest" +fuzz_distributed = "distributed-fuzztest" +fuzz_chaos = "distributed-fuzztest-with-chaos" +export_import_v2 = "export-import-v2-e2e" +sqlness_kvbackend = "sqlness-kvbackend" + +[groups] +server = [ + "src/operator/**", + "src/sql/**", + "src/catalog/**", + "src/datatypes/**", + "src/table/**", + "src/store-api/**", + "src/session/**", + "src/api/**", + "src/servers/**", + "src/frontend/**", + # Also covers `src/query/src/promql/`, which is exempt (see + # `[[matching.exempt]]`): a PromQL-only change must not run the fuzz fleet. + "src/query/**", + "src/partition/**", + "src/index/**", + "src/object-store/**", + "src/cache/**", + "src/puffin/**", + "src/auth/**", + "src/client/**", + "src/log-query/**", + "src/pipeline/**", + "src/plugins/**", + "src/cmd/**", + "src/standalone/**", + "src/datanode/**", + "src/common/base/**", + "src/common/batcher/**", + "src/common/catalog/**", + "src/common/config/**", + "src/common/datasource/**", + "src/common/decimal/**", + "src/common/error/**", + "src/common/event-recorder/**", + "src/common/frontend/**", + "src/common/function/**", + "src/common/grpc/**", + "src/common/grpc-expr/**", + "src/common/greptimedb-telemetry/**", + "src/common/macro/**", + "src/common/mem-prof/**", + "src/common/memory-manager/**", + "src/common/options/**", + "src/common/plugins/**", + "src/common/pprof/**", + "src/common/query/**", + "src/common/recordbatch/**", + "src/common/runtime/**", + "src/common/session/**", + "src/common/sql/**", + "src/common/stat/**", + "src/common/substrait/**", + "src/common/telemetry/**", + "src/common/test-util/**", + "src/common/time/**", + "src/common/version/**", + "src/common/workload/**", +] + +# Storage engines and WAL. +engine = [ + "src/mito2/**", + "src/mito-codec/**", + "src/metric-engine/**", + "src/file-engine/**", + "src/log-store/**", + "src/common/wal/**", +] + +# DDL and procedure code standalone executes in-process: it builds a +# `DdlManager` and runs `LocalProcedureExecutor` without any metasrv. +meta-core = [ + "src/common/meta/**", + "src/common/procedure/**", + "src/common/procedure-test/**", +] + +# Everything that sits on the KV backend the two sqlness KvBackend legs +# exercise: the backend implementations, the metadata service and the startup +# wiring that picks a backend. +kv-backend = [ + # The runner implements `--setup-pg`/`--setup-mysql`, which only these legs pass. + "tests/runner/**", + "src/common/meta/**", + "src/meta-srv/**", + "src/meta-client/**", + "src/common/procedure/**", + "src/cmd/**", + "src/common/config/**", + "src/common/options/**", +] + +# Adds the metasrv/meta-client crates on top of the in-process DDL code. +meta = [ + "src/meta-srv/**", + "src/meta-client/**", + "@meta-core", +] + +[suites."fuzz-standalone/database-and-regular-table"] +gate = "fuzz_standalone" +paths = [ + "@server", + "@engine", + "@meta-core", +] +description = "Standalone-server black-box fuzz of CREATE DATABASE/TABLE, ALTER, INSERT over MySQL." + +[suites."fuzz-standalone/logical-table"] +gate = "fuzz_standalone" +paths = [ + "@server", + "@engine", + "@meta-core", +] +description = "Standalone logical-table DDL/INSERT fuzz (mito2 logical tables)." + +[suites."fuzz-unstable/standalone"] +gate = "fuzz_unstable" +paths = [ + "@server", + "@engine", + "@meta-core", +] +description = "Unstable standalone create-table fuzz (nix build feature)." + +[suites."fuzz-distributed/database-and-regular-table"] +gate = "fuzz_distributed" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Distributed (frontend/datanode/metasrv, remote WAL) DDL/DML fuzz." + +[suites."fuzz-distributed/logical-table"] +gate = "fuzz_distributed" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Distributed logical-table fuzz." + +[suites."fuzz-distributed/repartition"] +gate = "fuzz_distributed" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Distributed repartition ALTER TABLE + GC fuzz." + +[suites."fuzz-distributed/logical-pruning"] +gate = "fuzz_distributed" +paths = [ + "@engine", + "@meta", +] +description = "Remote-WAL logical table pruning of stale manifests." + +[suites."fuzz-chaos/migration"] +gate = "fuzz_chaos" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Region migration under Chaos Mesh, mito and metric engines." + +[suites."fuzz-chaos/failover"] +gate = "fuzz_chaos" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Region failover under Chaos Mesh, mito and metric engines." + +[suites."fuzz-chaos/repartition"] +gate = "fuzz_chaos" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Repartition + GC under Chaos Mesh." + +[suites."export-import-v2"] +gate = "export_import_v2" +paths = [ + "src/cli/**", + "@server", + "@engine", + "@meta-core", +] +description = "CLI COPY DATABASE export/import v2 end-to-end against S3." + +[suites."sqlness-kvbackend/metasrv-postgres"] +gate = "sqlness_kvbackend" +paths = ["@kv-backend"] +description = "Sqlness with PostgreSQL as the metadata KV backend." + +[suites."sqlness-kvbackend/metasrv-mysql"] +gate = "sqlness_kvbackend" +paths = ["@kv-backend"] +description = "Sqlness with MySQL as the metadata KV backend." diff --git a/.github/ci/tests/fixtures/scope-cases.toml b/.github/ci/tests/fixtures/scope-cases.toml new file mode 100644 index 00000000000..d159bd3e32d --- /dev/null +++ b/.github/ci/tests/fixtures/scope-cases.toml @@ -0,0 +1,158 @@ +# Golden cases for the admission gate. +# +# `tests/test_ci_scope.py` replays every case through the real classifier, +# so an edit to `scope-rules.toml` that changes behaviour fails with the case +# name here. The cases encode intent, not implementation: each one says which +# suites a kind of change must start. +# +# `suites` is a list of globs over suite ids; `["*"]` means every suite and +# `[]` means none. + +[[case]] +name = "server crate: the whole fuzz fleet except the pruning suite" +note = "A change to `src/api` reaches every suite that builds the server binary." +paths = [ + "src/api/src/lib.rs", +] +suites = [ + "fuzz-standalone/database-and-regular-table", + "fuzz-standalone/logical-table", + "fuzz-unstable/standalone", + "fuzz-distributed/database-and-regular-table", + "fuzz-distributed/logical-table", + "fuzz-distributed/repartition", + "fuzz-chaos/migration", + "fuzz-chaos/failover", + "fuzz-chaos/repartition", + "export-import-v2", +] + +[[case]] +name = "storage engine: every fuzz suite, including remote-WAL pruning" +note = "logical-pruning needs engine and DDL code, so an engine change starts it." +paths = [ + "src/mito2/src/lib.rs", +] +suites = [ + "fuzz-standalone/*", + "fuzz-unstable/*", + "fuzz-distributed/*", + "fuzz-chaos/*", + "export-import-v2", +] + +[[case]] +name = "in-process DDL code registers the procedures standalone executes" +paths = [ + "src/common/meta/src/lib.rs", +] +suites = [ + "fuzz-standalone/*", + "fuzz-unstable/*", + "fuzz-distributed/*", + "fuzz-chaos/*", + "export-import-v2", + "sqlness-kvbackend/*", +] + +[[case]] +name = "metasrv only: distributed and chaos families" +note = "Standalone builds a DdlManager in-process and never links a metasrv." +paths = [ + "src/meta-srv/src/discovery/lease.rs", +] +suites = [ + "fuzz-distributed/database-and-regular-table", + "fuzz-distributed/logical-table", + "fuzz-distributed/repartition", + "fuzz-distributed/logical-pruning", + "fuzz-chaos/migration", + "fuzz-chaos/failover", + "fuzz-chaos/repartition", + "sqlness-kvbackend/*", +] + +[[case]] +name = "CLI only touches the export/import path" +paths = [ + "src/cli/src/lib.rs", +] +suites = [ + "export-import-v2", +] + +[[case]] +name = "PromQL crate: no suite" +note = "rust.yml and the promql sqlness cases own it; the fuzz suites speak SQL." +paths = [ + "src/promql/src/lib.rs", +] +suites = [] + +[[case]] +name = "PromQL module inside the query crate is not fuzzable either" +note = "`@server` claims `src/query/**`, so the module must be exempt." +paths = [ + "src/query/src/promql/src/lib.rs", +] +suites = [] + +[[case]] +name = "flow engine: no suite" +paths = [ + "src/flow/src/lib.rs", +] +suites = [] + +[[case]] +name = "mixed diff: the PromQL file subtracts nothing" +note = "The engine change still starts every suite." +paths = [ + "src/mito2/src/lib.rs", + "src/promql/src/lib.rs", +] +suites = [ + "fuzz-standalone/*", + "fuzz-unstable/*", + "fuzz-distributed/*", + "fuzz-chaos/*", + "export-import-v2", +] + +[[case]] +name = "crate added after the rules were written" +note = "No suite claims it, so the gate widens instead of skipping everything." +paths = [ + "src/brand-new/src/lib.rs", +] +suites = ["*"] + +[[case]] +name = "integration harness change" +paths = [ + "tests-integration/tests/fuzz.rs", +] +suites = ["*"] + +[[case]] +name = "documentation only" +paths = [ + "docs/readme.md", +] +suites = [] + +[[case]] +name = "kind registry setup: every suite" +note = "The distributed and chaos fuzz jobs start their cluster with this script." +paths = [ + ".github/scripts/kind-with-registry.sh", +] +suites = ["*"] + +[[case]] +name = "fuzz corpus seeding: every suite" +note = "Every fuzz job seeds its corpus through the `fuzz-test` action first." +paths = [ + ".github/scripts/prepare-fuzz-corpus.sh", +] +suites = ["*"] diff --git a/.github/ci/tests/test_ci_scope.py b/.github/ci/tests/test_ci_scope.py new file mode 100755 index 00000000000..77839aaaffa --- /dev/null +++ b/.github/ci/tests/test_ci_scope.py @@ -0,0 +1,1018 @@ +#!/usr/bin/env python3 +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Offline tests for the integration CI admission gate.""" + +import contextlib +import fnmatch +import io +import json +import os +import re +import pathlib +import sys +import tempfile +import tomllib +import unittest +from urllib.parse import parse_qs, urlparse + +GATE_DIR = pathlib.Path(__file__).resolve().parents[1] +WORKFLOWS = GATE_DIR.parent / "workflows" +REPO_ROOT = GATE_DIR.parents[1] +sys.path.insert(0, str(GATE_DIR)) + +import ci_scope # noqa: E402 +import ci_scope_rules # noqa: E402 + +SCOPE_CASES = pathlib.Path(__file__).resolve().parent / "fixtures" / "scope-cases.toml" +from ci_scope_rules import ( # noqa: E402 + ALWAYS_RUN, + PATH_GROUPS, + SUITES, + suite_paths, +) + +def file_entry(name, patch="@@ -1 +1 @@\n- old\n+ new\n", status="modified"): + entry = { + "filename": name, + "status": status, + "additions": 1, + "deletions": 1, + } + if patch is not None: + entry["patch"] = patch + return entry + + +class FakeHTTP: + """Records requests and serves canned GitHub API responses.""" + + def __init__(self): + self.calls = [] + self.file_pages = {1: []} + self.labels = [] + self.pull_status = 200 + self.draft = False + self.head_sha = "" + self.base_sha = "" + self.file_queries = [] + + def __call__(self, method, url, headers, body=None, timeout=None): + parsed = urlparse(url) + query = parse_qs(parsed.query) + self.calls.append((method, parsed.path, query.get("page", ["1"])[0])) + if parsed.path.endswith("/files"): + self.file_queries.append(dict(query)) + page = int(query.get("page", ["1"])[0]) + per_page = int(query.get("per_page", ["100"])[0]) + items = [] + for pageno in sorted(self.file_pages): + canned = self.file_pages[pageno] + if isinstance(canned, int): + # An int stands for an HTTP error status for that page. + if pageno == page: + return canned, b"{}" + continue + items.extend(canned) + # `file_pages` is stored at per_page=100; honour the requested + # window so a probe at per_page=1 cannot read past item 1. + start = (page - 1) * per_page + return 200, json.dumps(items[start : start + per_page]).encode() + if parsed.path.endswith("/pulls/1"): + if self.pull_status != 200: + return self.pull_status, b"{}" + return 200, json.dumps( + { + "labels": [{"name": name} for name in self.labels], + "head": {"sha": self.head_sha}, + "base": {"sha": self.base_sha}, + } + ).encode() + return 404, b"{}" + + +class ScopeTestCase(unittest.TestCase): + def setUp(self): + self.fake = FakeHTTP() + self._original = ci_scope._request + ci_scope._request = self.fake + self._environ = dict(os.environ) + for key in ["CI_SCOPE_FORCE_ALL"]: + os.environ.pop(key, None) + os.environ["GITHUB_API_URL"] = "https://api.github.com" + + def tearDown(self): + ci_scope._request = self._original + os.environ.clear() + os.environ.update(self._environ) + + def plan(self, files, pages=None, event="pull_request", extra_args=(), pr=1): + if pages is None: + pages = {1: files} + self.fake.file_pages = dict(pages) + args = ci_scope.parse_args( + ["--repo", "GreptimeTeam/greptimedb", "--pr", str(pr), "--event", event] + + list(extra_args) + ) + return ci_scope.build_plan(args, "token") + + def assert_all_run(self, plan): + for suite_id, entry in plan["suites"].items(): + self.assertTrue(entry["run"], suite_id) + + +class GlobTests(unittest.TestCase): + def test_double_star_crosses_directories(self): + regex = ci_scope.glob_to_regex("src/**/*.rs") + self.assertTrue(regex.match("src/a.rs")) + self.assertTrue(regex.match("src/a/b/c.rs")) + self.assertFalse(regex.match("tests/a.rs")) + + def test_single_star_stays_in_one_segment(self): + regex = ci_scope.glob_to_regex("src/*.rs") + self.assertTrue(regex.match("src/main.rs")) + self.assertFalse(regex.match("src/cmd/main.rs")) + self.assertFalse(regex.match("src/main.toml")) + + def test_question_mark_matches_one_character(self): + regex = ci_scope.glob_to_regex("a?.rs") + self.assertTrue(regex.match("ab.rs")) + self.assertFalse(regex.match("abc.rs")) + self.assertFalse(regex.match("a/.rs")) + + def test_suffix_glob(self): + regex = ci_scope.glob_to_regex(".cargo/**") + self.assertTrue(regex.match(".cargo/config.toml")) + self.assertFalse(regex.match("cargo/config.toml")) + + def test_suite_groups_expand(self): + for group in PATH_GROUPS: + self.assertTrue(PATH_GROUPS[group]) + self.assertTrue(any( + entry == "@" + group + for suite in SUITES.values() + for entry in suite["paths"] + ), group) + paths = suite_paths(SUITES["fuzz-distributed/repartition"]) + self.assertIn("src/mito2/**", paths) + self.assertIn("src/meta-srv/**", paths) + self.assertNotIn("@server", paths) + + def test_every_gate_routes_to_an_output(self): + # Ask the producer, not a copy of its key list: a new gate must fail + # here until `derive_outputs` routes it to a gate key. + plan = { + "mode": "static", + "full": True, + "notes": [], + "suites": { + suite_id: {"run": True, "source": "static", "reason": ""} + for suite_id in SUITES + }, + } + outputs, _ = ci_scope.derive_outputs(plan) + gates = {suite["gate"] for suite in SUITES.values()} + self.assertLessEqual(gates, set(outputs)) + + def test_suite_metadata(self): + for suite_id, suite in SUITES.items(): + self.assertEqual(suite_id, suite_id.strip()) + self.assertTrue(suite["description"]) + self.assertEqual(suite_id.split("/")[0].replace("-", "_"), suite["gate"]) + if suite["gate"] in ci_scope.FUZZ_GATES: + self.assertEqual(ci_scope.suite_group(suite_id), suite_id.split("/", 1)[1]) + + +class ForcedModeTests(ScopeTestCase): + def test_merge_group_forces_without_http(self): + plan = self.plan([], event="merge_group") + self.assertEqual(plan["mode"], "forced") + self.assert_all_run(plan) + self.assertEqual(self.fake.calls, []) + + def test_schedule_and_workflow_dispatch_force(self): + for event in ("schedule", "workflow_dispatch"): + plan = self.plan([], event=event) + self.assertEqual(plan["mode"], "forced", event) + + def test_force_all_env_forces(self): + os.environ["CI_SCOPE_FORCE_ALL"] = "true" + plan = self.plan([], event="pull_request") + self.assertEqual(plan["mode"], "forced") + + def test_ci_full_label_forces(self): + self.fake.labels = ["ci:full"] + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + self.assertEqual(plan["mode"], "forced") + self.assert_all_run(plan) + + +class UncoveredChangeTests(ScopeTestCase): + def test_uncovered_crate_runs_everything(self): + # `src/common/telemetry` is mapped by the server group; a crate added + # later is not, and must widen the gate. + plan = self.plan([file_entry("src/common/brand-new/src/lib.rs")]) + self.assertTrue(plan["full"], plan["notes"]) + self.assertEqual(plan["suites"]["export-import-v2"]["source"], "uncovered") + self.assertIn("uncovered build change", " ".join(plan["notes"])) + + def test_mapped_crate_keeps_the_path_decision(self): + plan = self.plan([file_entry("src/query/src/lib.rs")]) + self.assertFalse(plan["full"]) + self.assertTrue(plan["suites"]["fuzz-standalone/logical-table"]["run"]) + # `src/query` reaches `COPY DATABASE` and the chaos scenarios too. + self.assertTrue(plan["suites"]["export-import-v2"]["run"]) + self.assertTrue(plan["suites"]["fuzz-chaos/migration"]["run"]) + + def test_exempt_trees_do_not_widen(self): + plan = self.plan( + [file_entry("src/promql/src/lib.rs"), file_entry("src/flow/src/lib.rs")] + ) + self.assertFalse(plan["full"]) + for entry in plan["suites"].values(): + self.assertFalse(entry["run"], entry) + + def test_exempt_tree_is_not_claimed_by_a_broader_glob(self): + # `@server` claims `src/query/**`; the PromQL module under it must be + # dropped before matching, and must not count as uncovered either. + plan = self.plan([file_entry("src/query/src/promql/src/lib.rs")]) + self.assertFalse(plan["full"]) + for entry in plan["suites"].values(): + self.assertFalse(entry["run"], entry) + + +class StaticDecisionTests(ScopeTestCase): + def outputs(self, plan): + return ci_scope.derive_outputs(plan)[0] + + def test_always_run_forces_everything(self): + plan = self.plan([file_entry("Cargo.lock")]) + self.assertEqual(plan["mode"], "static") + self.assertTrue(plan["full"]) + self.assert_all_run(plan) + + def test_meta_only_skips_standalone_fuzz(self): + plan = self.plan([file_entry("src/meta-srv/src/lib.rs")]) + self.assertEqual(plan["mode"], "static") + outputs, legs = ci_scope.derive_outputs(plan) + self.assertEqual(outputs["fuzz_standalone"], "false") + self.assertEqual(outputs["fuzz_unstable"], "false") + self.assertIn("migration", legs["fuzz_chaos"]) + self.assertIn("logical-pruning", legs["fuzz_distributed"]) + self.assertEqual(outputs["export_import_v2"], "false") + self.assertEqual(outputs["any_fuzz"], "true") + self.assertEqual(outputs["build_ci_needed"], "true") + + def test_flow_and_promql_skip_every_gated_suite(self): + plan = self.plan( + [file_entry("src/flow/src/lib.rs"), file_entry("src/promql/src/lib.rs")] + ) + self.assertEqual(plan["mode"], "static") + for entry in plan["suites"].values(): + self.assertFalse(entry["run"], entry) + outputs, legs = ci_scope.derive_outputs(plan) + self.assertEqual(outputs["any_fuzz"], "false") + self.assertEqual(outputs["build_ci_needed"], "false") + self.assertEqual(outputs["export_import_v2"], "false") + for gate in ci_scope.FUZZ_GATES: + self.assertEqual(outputs[gate], "false") + self.assertTrue(all(not values for values in legs.values())) + + def test_docs_only_short_circuits(self): + plan = self.plan([file_entry("docs/readme.md")]) + self.assertEqual(plan["mode"], "static") + self.assertIn("no meaningful changes", " ".join(plan["notes"])) + + def test_mapped_change_records_the_path_rule_source(self): + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + self.assertEqual(plan["mode"], "static") + self.assertEqual(plan["suites"]["fuzz-standalone/logical-table"]["source"], "static") + + def test_file_cap_truncates(self): + files = [file_entry("src/mito2/f%d.rs" % index) for index in range(300)] + extra = [file_entry("src/mito2/overflow.rs")] + plan = self.plan(files, pages={1: files[:100], 2: files[100:200], 3: files[200:], 4: extra}) + self.assertTrue(plan["full"]) + self.assert_all_run(plan) + self.assertTrue(all(entry["source"] == "always-run" for entry in plan["suites"].values())) + + def test_exactly_max_files_is_not_truncated(self): + files = [file_entry("src/promql/f%d.rs" % index) for index in range(300)] + plan = self.plan([], pages={1: files[:100], 2: files[100:200], 3: files[200:], 4: []}) + self.assertFalse(plan["full"], plan["notes"]) + self.assertNotIn("truncated", " ".join(plan["notes"])) + self.assertEqual(len(self.fake.file_queries), 4) + self.assertEqual( + self.fake.file_queries[-1], {"per_page": ["100"], "page": ["4"]} + ) + + def test_force_push_after_the_run_widens_the_gate(self): + self.fake.head_sha = "b" * 40 + plan = self.plan( + [file_entry("src/promql/src/lib.rs")], + extra_args=("--head-sha", "a" * 40, "--base-sha", "c" * 40), + ) + self.assertTrue(plan["full"]) + self.assertIn("head moved from aaaaaaaaaaaa", " ".join(plan["notes"])) + + def test_matching_revisions_keep_the_static_verdict(self): + self.fake.head_sha = "a" * 40 + self.fake.base_sha = "c" * 40 + plan = self.plan( + [file_entry("src/promql/src/lib.rs")], + extra_args=("--head-sha", "a" * 40, "--base-sha", "c" * 40), + ) + self.assertFalse(plan["full"]) + self.assertNotIn("moved", " ".join(plan["notes"])) + + def test_pull_request_is_read_once_per_run(self): + self.plan([file_entry("src/mito2/src/lib.rs")]) + pulls = [ + path + for _, path, _ in self.fake.calls + if path.endswith("/pulls/1") + ] + self.assertEqual(len(pulls), 1) + + def test_failed_completeness_probe_fails_instead_of_narrowing(self): + # Raising leaves the gate outputs empty, which the workflow treats as + # "run everything"; returning False here would silently classify a + # truncated file list as complete. + files = [file_entry("src/mito2/f%d.rs" % index) for index in range(300)] + with self.assertRaises(ci_scope.ScopeError): + self.plan( + files, + pages={1: files[:100], 2: files[100:200], 3: files[200:], 4: 500}, + ) + + def test_file_list_pagination_stops_at_short_page(self): + files = [file_entry("src/mito2/f%d.rs" % index) for index in range(120)] + self.plan(files, pages={1: files[:100], 2: files[100:]}) + pages = [ + page for _, path, page in self.fake.calls if path.endswith("/files") + ] + self.assertEqual(pages, ["1", "2"]) + + +# Crates no gated suite exercises. Changing one either runs everything through +# the always-run floor, or reaches CI that is not gated here. +UNMAPPED_CRATES = { + "src/flow": "flow execution is covered by rust.yml and sqlness", + "src/promql": "PromQL execution is covered by rust.yml and sqlness", + "tests-fuzz": "in ALWAYS_RUN", + "tests-integration": "in ALWAYS_RUN", +} + + +def workspace_crates(): + """Every workspace member directory, so nested crates are not collapsed.""" + data = tomllib.loads((REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")) + return sorted(member.rstrip("/") for member in data["workspace"]["members"]) + + +def rules_doc(): + return { + "matching": { + "always_run": ["Cargo.toml"], + "src_tree": "src/", + "exempt": [{"path": "src/flow/", "reason": "test fixture"}], + }, + "gates": {"fuzz_x": "fuzztest"}, + "groups": {"server": ["src/a/**"]}, + "suites": { + "fuzz-x/g": { + "gate": "fuzz_x", + "paths": ["@server"], + "description": "a suite", + } + }, + } + + +class RulesFileTests(unittest.TestCase): + def test_repository_rules_are_valid(self): + rules = ci_scope_rules.load() + self.assertEqual(len(rules["suites"]), 13) + + def test_unknown_group_is_rejected(self): + doc = rules_doc() + doc["suites"]["fuzz-x/g"]["paths"] = ["@nope"] + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_group_cycle_is_rejected(self): + doc = rules_doc() + doc["groups"]["a"] = ["@b"] + doc["groups"]["b"] = ["@a"] + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_gate_must_match_the_suite_prefix(self): + doc = rules_doc() + doc["suites"]["fuzz-x/g"]["gate"] = "fuzz_y" + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_unknown_key_in_matching_is_ignored_but_missing_is_not(self): + doc = rules_doc() + del doc["matching"]["src_tree"] + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_validator_entry_point_succeeds_on_the_repository_rules(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(ci_scope_rules.main([]), 0) + self.assertIn("scope rules ok", out.getvalue()) + + def test_malformed_toml_names_the_file(self): + with tempfile.TemporaryDirectory() as tmp: + path = pathlib.Path(tmp) / "rules.toml" + path.write_text("this is not toml [[[") + with self.assertRaises(ci_scope_rules.RulesError) as ctx: + ci_scope_rules.load(path) + self.assertIn("not valid TOML", str(ctx.exception)) + + +def stub_rules(**overrides): + """A rules dict in the shape `validate` returns, naming only real paths.""" + rules = { + "always_run": ["Cargo.toml"], + "src_tree": "src/", + "exempt_trees": [], + "gates": {"fuzz_x": "fuzztest"}, + "groups": {"server": ["Cargo.toml"]}, + "suites": { + "fuzz-x": { + "gate": "fuzz_x", + "paths": ["@server"], + "description": "a suite", + } + }, + } + rules.update(overrides) + return rules + + +class PathCheckTests(unittest.TestCase): + def test_repository_rules_name_only_existing_paths(self): + self.assertEqual(ci_scope_rules.missing_paths(), []) + + def test_a_vanished_path_is_reported_with_its_prefix(self): + doc = stub_rules() + doc["suites"]["fuzz-x"]["paths"] = ["@server", "src/does-not-exist/**"] + self.assertEqual( + ci_scope_rules.missing_paths(doc), + [("src/does-not-exist/**", "src/does-not-exist/")], + ) + + def test_patterns_without_a_fixed_prefix_are_skipped(self): + doc = stub_rules(groups={"server": ["*.md"]}, always_run=["*.md"]) + self.assertEqual(ci_scope_rules.missing_paths(doc), []) + + + def test_cli_reports_a_missing_path(self): + text = """\ +[matching] +always_run = ["Cargo.toml"] +src_tree = "src/" + +[[matching.exempt]] +path = "src/flow/" +reason = "test fixture" + +[[matching.exempt]] +path = "src/promql/" +reason = "test fixture" + +[gates] +fuzz_x = "fuzztest" + +[groups] +server = ["src/does-not-exist/**"] + +[suites."fuzz-x"] +gate = "fuzz_x" +paths = ["@server"] +description = "a suite" +""" + with tempfile.TemporaryDirectory() as tmp: + path = pathlib.Path(tmp) / "scope-rules.toml" + path.write_text(text) + original = ci_scope_rules.RULES_PATH + ci_scope_rules.RULES_PATH = path + err = io.StringIO() + try: + with contextlib.redirect_stderr(err): + code = ci_scope_rules.main(["--check-paths"]) + finally: + ci_scope_rules.RULES_PATH = original + self.assertEqual(code, 1) + self.assertIn("missing path: src/does-not-exist/**", err.getvalue()) + + def test_cli_succeeds_on_the_repository_rules(self): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = ci_scope_rules.main(["--check-paths"]) + self.assertEqual(code, 0) + self.assertEqual(err.getvalue(), "") + + + +class RulesReasonTests(unittest.TestCase): + def test_exclusion_without_a_reason_is_rejected(self): + doc = rules_doc() + del doc["matching"]["exempt"][0]["reason"] + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_blank_reason_is_rejected(self): + doc = rules_doc() + doc["matching"]["exempt"][0]["reason"] = " " + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_repository_rules_explain_every_exclusion(self): + raw = tomllib.loads(ci_scope_rules.RULES_PATH.read_text()) + matching = raw["matching"] + self.assertTrue(matching["exempt"]) + for entry in matching["exempt"]: + self.assertTrue(entry["reason"].strip(), entry) + + +class ScopeCaseTests(ScopeTestCase): + """Replay `fixtures/scope-cases.toml` through the real classifier.""" + + @staticmethod + def cases(): + return tomllib.loads(SCOPE_CASES.read_text())["case"] + + def test_every_case_matches_the_classifier(self): + for case in self.cases(): + with self.subTest(case=case["name"]): + plan = self.plan([file_entry(path) for path in case["paths"]]) + expected = { + suite_id + for suite_id in ci_scope.SUITES + if any( + fnmatch.fnmatchcase(suite_id, pattern) + for pattern in case["suites"] + ) + } + actual = { + suite_id + for suite_id, entry in plan["suites"].items() + if entry["run"] + } + self.assertEqual(expected, actual, plan["notes"]) + + def test_cases_cover_every_suite(self): + covered = set() + for case in self.cases(): + covered |= { + suite_id + for suite_id in ci_scope.SUITES + if any( + fnmatch.fnmatchcase(suite_id, pattern) + for pattern in case["suites"] + ) + } + self.assertEqual(covered, set(ci_scope.SUITES)) + + +class SummaryTests(ScopeTestCase): + def summary(self, plan, path): + args = ci_scope.parse_args( + ["--repo", "GreptimeTeam/greptimedb", "--pr", "1", "--summary", path] + ) + ci_scope.emit(plan, args) + return pathlib.Path(path).read_text() + + def test_summary_names_the_files_that_matched(self): + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + with tempfile.TemporaryDirectory() as tmp: + text = self.summary(plan, str(pathlib.Path(tmp) / "summary.md")) + self.assertIn("### CI scope: mode=static", text) + row = next( + line + for line in text.splitlines() + if line.startswith("| `fuzz-standalone/logical-table`") + ) + self.assertIn("| run |", row) + self.assertIn("`src/mito2/src/lib.rs`", row) + + def test_summary_marks_a_skipped_suite_without_files(self): + plan = self.plan([file_entry("src/cli/src/lib.rs")]) + with tempfile.TemporaryDirectory() as tmp: + text = self.summary(plan, str(pathlib.Path(tmp) / "summary.md")) + row = next( + line + for line in text.splitlines() + if line.startswith("| `fuzz-standalone/database-and-regular-table`") + ) + self.assertIn("| skip |", row) + self.assertTrue(row.endswith("| — |"), row) + + def test_summary_truncates_long_file_lists(self): + files = [file_entry(f"src/mito2/src/f{index}.rs") for index in range(5)] + plan = self.plan(files) + with tempfile.TemporaryDirectory() as tmp: + text = self.summary(plan, str(pathlib.Path(tmp) / "summary.md")) + self.assertIn("+2 more", text) + + def test_summary_appends_instead_of_overwriting(self): + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + with tempfile.TemporaryDirectory() as tmp: + path = pathlib.Path(tmp) / "summary.md" + path.write_text("existing\n") + self.summary(plan, str(path)) + text = path.read_text() + self.assertTrue(text.startswith("existing\n")) + self.assertEqual(text.count("### CI scope"), 1) + + def test_summary_carries_the_notes(self): + plan = self.plan([file_entry("Cargo.lock")]) + with tempfile.TemporaryDirectory() as tmp: + text = self.summary(plan, str(pathlib.Path(tmp) / "summary.md")) + self.assertIn("
notes", text) + + +class CrateCoverageTests(unittest.TestCase): + """A new crate must not silently match no suite: the runtime net would + catch it by running everything, but the rule table should be updated.""" + + def test_every_workspace_crate_is_mapped_or_excused(self): + patterns = [ + ci_scope.glob_to_regex(path) + for suite in SUITES.values() + for path in suite_paths(suite) + ] + unmapped = [ + crate + for crate in workspace_crates() + if crate not in UNMAPPED_CRATES + and not any(p.match(crate + "/src/lib.rs") for p in patterns) + ] + self.assertEqual(unmapped, [], "crate matches no suite and no excuse") + + def test_excuses_reference_existing_crates(self): + stale = sorted(set(UNMAPPED_CRATES) - set(workspace_crates())) + self.assertEqual(stale, [], "excuse points at a crate that is gone") + + +class PathRuleCoverageTests(ScopeTestCase): + """A rule must select every suite the change can actually break.""" + + def test_copy_parser_selects_export_import(self): + plan = self.plan([file_entry("src/sql/src/parsers/copy_parser.rs")]) + self.assertTrue(plan["suites"]["export-import-v2"]["run"]) + + def test_shared_ddl_selects_standalone_fuzz(self): + plan = self.plan([file_entry("src/common/meta/src/ddl/create_table.rs")]) + for suite in ( + "fuzz-standalone/database-and-regular-table", + "fuzz-standalone/logical-table", + "fuzz-unstable/standalone", + ): + self.assertTrue(plan["suites"][suite]["run"], suite) + + def test_sqlness_runner_selects_the_kvbackend_legs(self): + # `--setup-pg` / `--setup-mysql` live in the runner and only these legs + # pass them, so a change there must not skip the only job that uses it. + plan = self.plan([file_entry("tests/runner/src/server_mode.rs")]) + for suite in ("sqlness-kvbackend/metasrv-postgres", "sqlness-kvbackend/metasrv-mysql"): + self.assertTrue(plan["suites"][suite]["run"], suite) + + def test_shared_ddl_selects_export_import(self): + # The E2E creates databases, tables and views and recreates them on + # import, all through the in-process DDL manager. + plan = self.plan([file_entry("src/common/procedure/src/lib.rs")]) + self.assertTrue(plan["suites"]["export-import-v2"]["run"]) + + def test_group_references_resolve_recursively(self): + self.assertIn("src/common/meta/**", ci_scope.suite_paths(SUITES["fuzz-chaos/migration"])) + + +class OutputTests(ScopeTestCase): + def test_flat_outputs(self): + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + outputs, legs = ci_scope.derive_outputs(plan) + self.assertEqual( + set(outputs), + { + "any_fuzz", + "build_ci_needed", + "fuzz_standalone", + "fuzz_distributed", + "fuzz_chaos", + "fuzz_unstable", + "export_import_v2", + "sqlness_kvbackend", + }, + ) + for key in outputs: + self.assertIn(outputs[key], ("true", "false"), key) + self.assertEqual( + sorted(legs["fuzz_standalone"]), + ["database-and-regular-table", "logical-table"], + ) + + def test_emit_writes_the_gate_outputs(self): + import tempfile + + with tempfile.TemporaryDirectory() as tmp: + out_path = os.path.join(tmp, "github_output") + args = ci_scope.parse_args( + [ + "--repo", + "GreptimeTeam/greptimedb", + "--pr", + "1", + "--event", + "merge_group", + "--github-output", + out_path, + ] + ) + ci_scope.emit(ci_scope.build_plan(args, "token"), args) + with open(out_path, encoding="utf-8") as handle: + text = handle.read() + self.assertIn("any_fuzz=true" + "\n", text) + self.assertIn("fuzz_unstable=true", text) + self.assertIn("fuzz_chaos=true", text) + self.assertEqual(text.count("\n"), 8) + + + +class GateJobContractTests(unittest.TestCase): + """The rules say which job each gate switches; prove the YAML agrees.""" + + WORKFLOW = WORKFLOWS / "integration.yml" + + def job_blocks(self): + blocks = {} + current = None + for line in self.WORKFLOW.read_text().splitlines(): + marker = re.match(r"^ ([A-Za-z0-9_-]+):$", line) + if marker: + current = marker.group(1) + blocks[current] = [] + elif current: + blocks[current].append(line) + return {name: "\n".join(lines) for name, lines in blocks.items()} + + def test_every_gate_names_a_job_that_reads_it(self): + blocks = self.job_blocks() + for gate, job in ci_scope_rules.GATE_JOBS.items(): + self.assertIn(job, blocks, gate) + self.assertIn(f"needs.scope.outputs.{gate} != 'false'", blocks[job], gate) + + def test_every_gated_job_is_named_by_a_gate(self): + derived = {"any_fuzz", "build_ci_needed"} + declared = set(ci_scope_rules.GATE_JOBS) + for name, block in self.job_blocks().items(): + for gate in re.findall(r"needs\.scope\.outputs\.([a-z0-9_]+)", block): + self.assertIn(gate, declared | derived, name) + + def test_a_suite_gate_missing_from_the_table_is_rejected(self): + doc = rules_doc() + del doc["gates"]["fuzz_x"] + with self.assertRaises(ci_scope_rules.RulesError) as ctx: + ci_scope_rules.validate(doc) + self.assertIn("missing from [gates]", str(ctx.exception)) + + def test_gates_no_suite_uses_are_rejected(self): + doc = rules_doc() + doc["gates"]["fuzz_y"] = "fuzztest" + with self.assertRaises(ci_scope_rules.RulesError) as ctx: + ci_scope_rules.validate(doc) + self.assertIn("no suite uses", str(ctx.exception)) + + +class WorkflowContractTests(unittest.TestCase): + """Keep the YAML gate contract in sync with the classifier outputs.""" + + WORKFLOW = WORKFLOWS / "integration.yml" + + def job_blocks(self): + text = self.WORKFLOW.read_text() + blocks = {} + current = None + for line in text.splitlines(): + marker = re.match(r"^ ([A-Za-z0-9_-]+):$", line) + if marker: + current = marker.group(1) + blocks[current] = [] + elif current: + blocks[current].append(line) + return {name: "\n".join(lines) for name, lines in blocks.items()} + + def test_every_script_a_gated_job_runs_is_always_run(self): + """A script a gated job executes must widen the gate. + + A change confined to such a script would otherwise select no suite, so + the jobs that run it are skipped exactly when they are worth running. + The reference is often not in the workflow: a composite action the job + `uses` can run the script, so the search follows those actions too. + """ + action_use = re.compile(r"uses:\s*\./(\.github/actions/[A-Za-z0-9_.-]+)") + script_ref = re.compile( + r"(?:\./)?(\.github/[A-Za-z0-9_./-]+\.(?:sh|py|js|cjs|ts))\b" + ) + always = [ci_scope.glob_to_regex(pattern) for pattern in ALWAYS_RUN] + + gated = [b for b in self.job_blocks().values() if "needs.scope.outputs" in b] + pending = {ref for block in gated for ref in script_ref.findall(block)} + pending |= {a for block in gated for a in action_use.findall(block)} + seen = set() + while pending: + reference = pending.pop() + if reference in seen: + continue + seen.add(reference) + if not reference.startswith(".github/actions/"): + continue + for suffix in ("action.yml", "action.yaml"): + path = REPO_ROOT / reference / suffix + if path.exists(): + text = path.read_text() + pending |= set(script_ref.findall(text)) + pending |= set(action_use.findall(text)) + break + uncovered = sorted( + ref for ref in seen if not any(pattern.match(ref) for pattern in always) + ) + self.assertEqual(uncovered, [], "a gated job runs a script ALWAYS_RUN misses") + + def test_gates_treat_a_missing_output_as_run(self): + blocks = self.job_blocks() + gated = [ + "export-import-v2-e2e", + "prepare-fuzz-targets", + "fuzztest", + "unstable-fuzztest", + "build-greptime-ci", + "distributed-fuzztest", + "distributed-fuzztest-with-chaos", + "sqlness-kvbackend", + ] + declared = set( + re.findall( + r"^ ([a-z0-9_]+): \$\{\{ steps\.classify\.outputs\.\1 \}\}$", + blocks["scope"], + re.MULTILINE, + ) + ) + self.assertIn("any_fuzz", declared) + seen = set() + for name in gated: + self.assertIn("scope", blocks[name], name) + match = re.search( + r"needs\.scope\.outputs\.([a-z0-9_]+) != 'false'", blocks[name] + ) + self.assertTrue(match, name) + seen.add(match.group(1)) + self.assertEqual(seen, declared) + + def test_gates_override_the_implicit_success_check(self): + # A condition without a status function carries an implicit success() + # over `needs`, so a scope job that times out or dies on the runner + # would skip the gates despite the fail-open output comparison. + blocks = self.job_blocks() + for name in ( + "export-import-v2-e2e", + "prepare-fuzz-targets", + "fuzztest", + "unstable-fuzztest", + "build-greptime-ci", + "distributed-fuzztest", + "distributed-fuzztest-with-chaos", + ): + block = blocks[name] + condition = re.search(r"^ if: \$\{\{ (.*?) \}\}$", block, re.M) + self.assertTrue(condition, name) + self.assertTrue(condition.group(1).startswith("!cancelled() && "), name) + needs = re.search(r"^ needs: \[(.*?)\]$", block, re.M) + self.assertTrue(needs, name) + for dep in [item.strip() for item in needs.group(1).split(",")]: + if not dep or dep == "scope": + continue + key = f"needs['{dep}'].result" if "-" in dep else f"needs.{dep}.result" + self.assertIn(key + " == 'success'", condition.group(1), name) + + def test_scope_job_cannot_fail_and_skip_the_gates(self): + block = self.job_blocks()["scope"] + self.assertNotIn("Fail-open defaults", block) + self.assertIn("github.event.merge_group.base_sha", block) + self.assertIn("CI_SCOPE_FORCE_ALL", block) + # Every step that can fail must be continue-on-error: a failed scope job + # would make GitHub skip the gated jobs instead of running them. + steps = block.split("\n - ") + guarded = [ + step + for step in steps + if step.startswith("uses: actions/checkout") + or step.startswith("name: Classify") + ] + self.assertEqual(len(guarded), 2) + for step in guarded: + self.assertIn("continue-on-error: true", step, step.splitlines()[0]) + + + +class LogRenderingTests(ScopeTestCase): + """The step log is where a triage starts; the verdict must be there.""" + + def sample_plan(self): + return { + "mode": "static", + "head_sha": "a" * 40, + "base_sha": "b" * 40, + "full": False, + "notes": ["always-run: Cargo.lock"], + "suites": { + "fuzz-standalone/logical-table": { + "run": True, + "source": "static", + "reason": "touches mito2", + }, + "fuzz-chaos/migration": { + "run": False, + "source": "static", + "reason": "meta docs only", + }, + }, + } + + def test_header_names_mode_and_full(self): + self.assertEqual( + ci_scope.render_log(self.sample_plan()).splitlines()[0], + "CI scope: mode=static full=false", + ) + + def test_one_line_per_suite_with_source_and_reason(self): + lines = ci_scope.render_log(self.sample_plan()).splitlines() + self.assertIn(" run fuzz-standalone/logical-table", lines[1]) + self.assertIn("static", lines[1]) + self.assertIn("touches mito2", lines[1]) + self.assertIn(" skip fuzz-chaos/migration", lines[2]) + self.assertIn("meta docs only", lines[2]) + + def test_gates_and_notes_are_printed(self): + log = ci_scope.render_log(self.sample_plan()) + self.assertIn(" gates: fuzz_standalone=true", log) + self.assertIn("any_fuzz=true", log) + self.assertIn("export_import_v2=false", log) + self.assertIn(" note: always-run: Cargo.lock", log) + + def test_a_failed_pull_request_lookup_is_annotated_and_runs_everything(self): + # Drive the real failure path: the label lookup and the revision + # comparison share one request, so a 500 here must widen the gate and + # still produce the warning the annotation promises. + self.fake.pull_status = 500 + plan = self.plan([file_entry("src/promql/src/lib.rs")]) + self.assertTrue(plan["full"]) + self.assertIn("pull request lookup failed", " ".join(plan["notes"])) + annotations = ci_scope.log_annotations(plan) + self.assertEqual(len(annotations), 1) + self.assertTrue(annotations[0].startswith("::warning::"), annotations) + self.assertIn("every suite runs", annotations[0]) + + def test_main_prints_the_log(self): + self.fake.file_pages = {1: [file_entry("src/mito2/src/lib.rs")]} + stdout = io.StringIO() + with contextlib.redirect_stdout(stdout): + self.assertEqual( + ci_scope.main( + [ + "--repo", + "GreptimeTeam/greptimedb", + "--pr", + "1", + "--event", + "pull_request", + "--dry-run", + ] + ), + 0, + ) + text = stdout.getvalue() + self.assertIn("CI scope: mode=", text) + self.assertIn(" run fuzz-standalone/logical-table", text) + self.assertIn("any_fuzz=true", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_ci_slash.py b/.github/scripts/tests/test_ci_slash.py index c8c01ceda15..e551a4f5297 100644 --- a/.github/scripts/tests/test_ci_slash.py +++ b/.github/scripts/tests/test_ci_slash.py @@ -136,7 +136,7 @@ class CiSlashTest(unittest.TestCase): def test_fork_rerun_gates_cover_standard_jobs(self): import re - for name, count in [("rust", 7), ("integration", 5), ("checks", 5), ("docs", 3)]: + for name, count in [("rust", 7), ("integration", 7), ("checks", 6), ("docs", 3)]: workflow = (SCRIPT.parents[1] / "workflows" / (name + ".yml")).read_text() gates = re.findall(r"^ if:.*github.run_attempt > 1.*$", workflow, re.MULTILINE) self.assertEqual(len(gates), count, name) diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 3bc54372d06..b3ff212ade4 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -92,6 +92,8 @@ jobs: run: .github/scripts/run-fuzz-targets-test.sh - name: Run CI comment-command tests run: python3 .github/scripts/tests/test_ci_slash.py + - name: Run CI scope gate tests + run: python3 .github/ci/tests/test_ci_scope.py - name: Run metric snapshot benchmark tests run: python3 -m unittest discover -s .github/scripts/tests -p 'test_metric_snapshot*.py' - name: Run query-regression Python tooling tests @@ -107,6 +109,23 @@ jobs: python3 tests/perf/test_agent_observability_summary.py python3 tests/perf/test_tracesbench_summary.py + scope-rules: + if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + name: CI Scope Rules + # Same runner image as the `scope` job in integration.yml: if the rules file + # stops parsing there, the gate silently runs every job, so this check exists + # to fail the pull request instead. + runs-on: ubuntu-slim + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Show the interpreter + run: python3 -VV + - name: Validate .github/ci/scope-rules.toml + run: python3 .github/ci/ci_scope_rules.py --check-paths + check: if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} name: Check diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index afce4a8c796..6106e5a2860 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -42,6 +42,57 @@ concurrency: cancel-in-progress: true jobs: + # Which jobs this gate skips, and why: .github/ci/README.md. + scope: + name: CI Scope + if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + # ubuntu-slim ships python3, git and curl; this job only classifies. + runs-on: ubuntu-slim + timeout-minutes: 10 + permissions: + contents: read + # `/pulls/{n}` and `/pulls/{n}/files`. An explicit block sets every + # unlisted permission to none, and a 403 here would silently widen every + # gate instead of classifying. + pull-requests: read + outputs: + any_fuzz: ${{ steps.classify.outputs.any_fuzz }} + build_ci_needed: ${{ steps.classify.outputs.build_ci_needed }} + fuzz_standalone: ${{ steps.classify.outputs.fuzz_standalone }} + fuzz_distributed: ${{ steps.classify.outputs.fuzz_distributed }} + fuzz_chaos: ${{ steps.classify.outputs.fuzz_chaos }} + fuzz_unstable: ${{ steps.classify.outputs.fuzz_unstable }} + export_import_v2: ${{ steps.classify.outputs.export_import_v2 }} + sqlness_kvbackend: ${{ steps.classify.outputs.sqlness_kvbackend }} + steps: + # Rules come from the pull request base (the queue base on merge_group), + # so a pull request cannot weaken its own gate. If this job or the Classify + # step fails, the outputs stay empty and every gate below treats an absent + # value as "run", which keeps CI fail-open. + - uses: actions/checkout@v4 + # A checkout failure leaves the outputs empty, which every gate treats + # as "run"; letting the step fail would skip the gates instead. + continue-on-error: true + with: + ref: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.sha }} + persist-credentials: false + - name: Classify + id: classify + continue-on-error: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CI_SCOPE_FORCE_ALL: ${{ vars.CI_SCOPE_FORCE_ALL || 'false' }} + run: | + args=(--repo "$GITHUB_REPOSITORY" --event "$GITHUB_EVENT_NAME" + --github-output "$GITHUB_OUTPUT" + --summary "$GITHUB_STEP_SUMMARY") + if [[ "${GITHUB_EVENT_NAME}" == "pull_request" ]]; then + args+=(--pr "${{ github.event.pull_request.number }}" + --head-sha "${{ github.event.pull_request.head.sha }}" + --base-sha "${{ github.event.pull_request.base.sha }}") + fi + python3 .github/ci/ci_scope.py "${args[@]}" + build: if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} name: Build GreptimeDB binaries @@ -116,28 +167,12 @@ jobs: - name: "Basic" opts: "" kafka: false - postgres: false - mysql: false - name: "Remote WAL" opts: "-w kafka -k 127.0.0.1:9092" kafka: true - postgres: false - mysql: false - - name: "PostgreSQL KvBackend" - opts: "--setup-pg postgresql://greptimedb:admin@127.0.0.1:5432/postgres" - kafka: false - postgres: true - mysql: false - - name: "MySQL KvBackend" - opts: "--setup-mysql mysql://greptimedb:admin@127.0.0.1:3306/mysql" - kafka: false - postgres: false - mysql: true - name: "Flat format" opts: "--enable-flat-format" kafka: false - postgres: false - mysql: false timeout-minutes: 60 steps: - uses: actions/checkout@v4 @@ -149,16 +184,6 @@ jobs: working-directory: tests-integration/fixtures run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait kafka - - if: matrix.mode.postgres - name: Setup PostgreSQL - working-directory: tests-integration/fixtures - run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait postgres - - - if: matrix.mode.mysql - name: Setup MySQL - working-directory: tests-integration/fixtures - run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait mysql - - name: Download pre-built binaries uses: actions/download-artifact@v4 with: @@ -183,10 +208,68 @@ jobs: /tmp/sqlness* retention-days: 3 + sqlness-kvbackend: + # The two foreign KV backends are the only sqlness legs that are not + # required checks, so they are the only ones this gate may skip. They run + # the same cases as the `Basic` leg, so the diff only matters when it can + # reach the backend itself; the merge queue runs them regardless. + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.sqlness_kvbackend != 'false' }} + name: Sqlness Test (${{ matrix.mode.name }}) + needs: [scope, build] + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ ubuntu-latest ] + mode: + - name: "Metasrv on PostgreSQL" + id: "metasrv-postgres" + opts: "--setup-pg postgresql://greptimedb:admin@127.0.0.1:5432/postgres" + postgres: true + mysql: false + - name: "Metasrv on MySQL" + id: "metasrv-mysql" + opts: "--setup-mysql mysql://greptimedb:admin@127.0.0.1:3306/mysql" + postgres: false + mysql: true + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - if: matrix.mode.postgres + name: Setup PostgreSQL + working-directory: tests-integration/fixtures + run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait postgres + + - if: matrix.mode.mysql + name: Setup MySQL + working-directory: tests-integration/fixtures + run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait mysql + + - name: Download pre-built binaries + uses: actions/download-artifact@v4 + with: + name: bins + path: . + - name: Unzip binaries + run: tar -xvf ./bins.tar.gz + - name: Run sqlness + run: RUST_BACKTRACE=1 ./bins/sqlness-runner bare ${{ matrix.mode.opts }} -c ./tests/cases --bins-dir ./bins --preserve-state + - name: Upload sqlness logs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: sqlness-logs-${{ matrix.mode.name }} + path: | + /tmp/sqlness* + retention-days: 3 + export-import-v2-e2e: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.export_import_v2 != 'false' }} name: Export/Import V2 E2E Test - needs: build + needs: [scope, build] runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -319,8 +402,9 @@ jobs: retention-days: 3 prepare-fuzz-targets: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile != 'none') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile != 'none') && needs.scope.outputs.any_fuzz != 'false' }} name: Prepare Fuzz Targets + needs: [scope] runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -433,9 +517,9 @@ jobs: if-no-files-found: error fuzztest: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') && needs.build.result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_standalone != 'false' }} name: Fuzz Test (Standalone, ${{ matrix.group.name }}) - needs: [build, prepare-fuzz-targets] + needs: [build, prepare-fuzz-targets, scope] runs-on: ubuntu-latest timeout-minutes: 60 strategy: @@ -514,9 +598,9 @@ jobs: artifact-name: fuzz-standalone-${{ matrix.group.id }} unstable-fuzztest: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_unstable != 'false' }} name: Unstable Fuzz Test - needs: [build-greptime-ci, prepare-fuzz-targets] + needs: [build-greptime-ci, prepare-fuzz-targets, scope] runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -574,8 +658,9 @@ jobs: artifact-name: fuzz-unstable-standalone build-greptime-ci: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command && inputs.fuzz_profile != 'none')) }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command && inputs.fuzz_profile != 'none') || github.event_name == 'merge_group') && needs.scope.outputs.build_ci_needed != 'false' }} name: Build GreptimeDB binary (profile-CI) + needs: [scope] runs-on: ${{ matrix.os }} strategy: matrix: @@ -634,10 +719,10 @@ jobs: version: current distributed-fuzztest: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all') && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_distributed != 'false' }} name: Fuzz Test (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }}) runs-on: ubuntu-latest - needs: [build-greptime-ci, prepare-fuzz-targets] + needs: [build-greptime-ci, prepare-fuzz-targets, scope] timeout-minutes: 60 strategy: fail-fast: false @@ -873,10 +958,10 @@ jobs: docker system prune -f distributed-fuzztest-with-chaos: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all') && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_chaos != 'false' }} name: Fuzz Test with Chaos (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }}) runs-on: ubuntu-latest - needs: [build-greptime-ci, prepare-fuzz-targets] + needs: [build-greptime-ci, prepare-fuzz-targets, scope] timeout-minutes: 60 strategy: fail-fast: false diff --git a/Makefile b/Makefile index 21c87cc3707..073a95cb1fa 100644 --- a/Makefile +++ b/Makefile @@ -249,6 +249,10 @@ fmt-check: ## Check code format. check-enterprise-license: ## Check enterprise-gated files are listed in both license configs. python3 scripts/check-enterprise-license.py +.PHONY: check-ci-scope +check-ci-scope: ## Check the CI scope rules still match existing paths. + python3 .github/ci/ci_scope_rules.py --check-paths + .PHONY: start-etcd start-etcd: ## Start single node etcd for testing purpose. docker run --rm -d --network=host -p 2379-2380:2379-2380 ${ETCD_IMAGE} From f646f06430516aa14a9dd78236c4cae4c27f9857 Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Wed, 28 Oct 2026 13:32:23 +0000 Subject: [PATCH 11/19] ci: enqueue eligible pull requests during the nightly window (#10040) * ci: enqueue eligible pull requests during the nightly window Signed-off-by: WenyXu * docs: hide nightly merge instructions in PR template Signed-off-by: WenyXu --------- Signed-off-by: WenyXu --- .github/nightly-merge.md | 43 ++++++ .github/pull_request_template.md | 11 ++ .github/scripts/tests/nightly-merge.test.cjs | 108 +++++++++++++++ .github/workflows/checks.yml | 2 +- .github/workflows/nightly-merge.yml | 138 +++++++++++++++++++ 5 files changed, 301 insertions(+), 1 deletion(-) create mode 100644 .github/nightly-merge.md create mode 100644 .github/scripts/tests/nightly-merge.test.cjs create mode 100644 .github/workflows/nightly-merge.yml diff --git a/.github/nightly-merge.md b/.github/nightly-merge.md new file mode 100644 index 00000000000..a8699a9b159 --- /dev/null +++ b/.github/nightly-merge.md @@ -0,0 +1,43 @@ +# Nightly merge + +The PR template opts new PRs into the `merge nightly` label. The Nightly Merge +workflow reconciles the label on PR creation, edits, and reopening. Existing PRs +without the checkbox are not opted in. Unchecking removes the label; it does not +request an immediate merge or cancel an existing queue entry/auto-merge request. + +Every day at 02:10, 03:10, 04:10, 05:10, 06:10, 07:10, and 08:10 +Asia/Shanghai (UTC+8), the workflow enqueues up to five eligible PRs targeting +`main` per run, oldest first. Already queued PRs do not count toward this limit. +GitHub may delay scheduled runs. +PRs must still have the checkbox and label, be approved and clean, and have all +review threads resolved. Drafts are skipped. +Already queued PRs and manually enabled auto-merge requests are left alone; +Maintainers can use **Merge when ready** to proceed earlier. Unready PRs wait for a later +scheduled run; this workflow never enables auto-merge on their behalf. + +## Repository setup + +- Create the `merge nightly` label before enabling the workflow. +- Require the merge queue, reviews, status checks, and conversation resolution + on `main`. Conversation resolution must also be enforced by GitHub to cover + new comments arriving between the script's check and enqueueing. +- Ensure the existing `GH_PERSONAL_ACCESS_TOKEN` automation secret can read PRs + and review threads and enqueue PRs in this repository. Do not grant it a + branch-rule bypass. This credential is already referenced by other workflows; + its actual permissions have not been validated by the local tests. +- Run **Nightly Merge** manually with the default `dry_run: true` first and + inspect its job summary. Setting it to false explicitly enqueues outside the + scheduled time as well. Merge queue build concurrency is configured separately + in GitHub; this workflow does not change it. + +The workflow never checks out or executes PR code. Label reconciliation uses +`GITHUB_TOKEN`; enqueueing uses the automation credential so downstream CI can +run. No runner remains allocated while waiting for the nightly schedule. + +## Local validation + +Run `actionlint .github/workflows/nightly-merge.yml .github/workflows/checks.yml` +and `node --test .github/scripts/tests/nightly-merge.test.cjs`. +The tests execute the actual inline workflow scripts with mocked GitHub APIs, +including one-factor comparisons against an eligible PR. They do not validate +live GitHub permissions, branch rules, or runner savings. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index a33531c2733..5b26f64ceb3 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -25,3 +25,14 @@ Please convert it to a draft if some of the following conditions are not met. - [ ] API changes are backward compatible. - [ ] Schema or data changes are backward compatible. - [ ] This PR needs to be backported to release branches, and I have added the `backport-` labels (e.g. `backport-v1.3` targets `release/v1.3`). + +## Merge timing + +- [x] Merge during the nightly window + + diff --git a/.github/scripts/tests/nightly-merge.test.cjs b/.github/scripts/tests/nightly-merge.test.cjs new file mode 100644 index 00000000000..885876f5610 --- /dev/null +++ b/.github/scripts/tests/nightly-merge.test.cjs @@ -0,0 +1,108 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Run with: node --test .github/scripts/tests/nightly-merge.test.cjs +const { readFileSync } = require('node:fs'); +const { resolve } = require('node:path'); +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; +const workflow = readFileSync(resolve(__dirname, '../../workflows/nightly-merge.yml'), 'utf8'); +const scripts = [...workflow.matchAll(/ script: \|\n((?: .*\n|\n)+)/g)] + .map(match => new AsyncFunction('github', 'context', 'core', 'process', match[1].replace(/^ /gm, ''))); +assert.equal(scripts.length, 2); +const checked = '- [x] Merge during the nightly window '; + +async function run({ sync = false, body = checked, labels = ['merge nightly'], + detail = {}, current = {}, threads = [[true]], count = 1, dryRun = false, + failFirst = false } = {}) { + const calls = []; + let page = 0; + const github = { + rest: { + pulls: { get: async () => ({ data: { state: 'open', draft: false, base: { ref: 'main' }, + body, labels: labels.map(name => ({ name })), ...current } }) }, + issues: { + listForRepo: () => {}, + addLabels: async args => calls.push(['add', args.labels]), + removeLabel: async args => calls.push(['remove', args.name]) + } + }, + paginate: async () => Array.from({ length: count }, (_, i) => ({ number: i + 1, pull_request: {} })), + graphql: async (query, args) => { + if (query.includes('mutation')) { + calls.push(['enqueue', args]); + if (failFirst && calls.filter(call => call[0] === 'enqueue').length === 1) throw Error('head changed'); + return {}; + } + if (query.includes('reviewThreads')) { + const index = page++ % threads.length; + calls.push(['threads', args.cursor]); + return { repository: { pullRequest: { reviewThreads: { + nodes: threads[index].map(isResolved => ({ isResolved })), + pageInfo: { hasNextPage: index + 1 < threads.length, endCursor: `page-${index}` } + } } } }; + } + return { repository: { pullRequest: { id: `PR_${args.number}`, headRefOid: 'abc', + reviewDecision: 'APPROVED', mergeStateStatus: 'CLEAN', ...detail } } }; + } + }; + const summary = { addHeading() { return this; }, addTable(rows) { calls.push(['summary', rows]); return this; }, async write() {} }; + await scripts[sync ? 0 : 1](github, + { repo: { owner: 'GreptimeTeam', repo: 'greptimedb' }, payload: { pull_request: { number: 1 } } }, + { summary, warning() {}, setFailed: message => calls.push(['failed', message]) }, + { env: { DRY_RUN: String(dryRun) } }); + return calls; +} + +test('template opts in and checkbox edits reconcile only the nightly label', async () => { + assert.ok(readFileSync(resolve(__dirname, '../../pull_request_template.md'), 'utf8').includes(checked)); + assert.deepEqual(await run({ sync: true, labels: ['bug'] }), [['add', ['merge nightly']]]); + assert.deepEqual(await run({ sync: true }), []); + for (const body of [checked.replace('[x]', '[ ]'), '', null, `> ${checked}`]) { + assert.deepEqual(await run({ sync: true, body }), [['remove', 'merge nightly']]); + } + assert.deepEqual(await run({ sync: true, body: checked.replace('[x]', '[X]'), labels: [] }), [['add', ['merge nightly']]]); +}); + +test('eligible PR is enqueued with its checked head; dry run performs no mutation', async () => { + assert.deepEqual((await run()).filter(c => c[0] === 'enqueue'), [['enqueue', { id: 'PR_1', sha: 'abc' }]]); + assert.equal((await run({ dryRun: true })).some(c => c[0] === 'enqueue'), false); +}); + +test('each eligibility gate independently prevents enqueueing', async () => { + for (const options of [ + { body: checked.replace('[x]', '[ ]') }, { labels: [] }, + { current: { draft: true } }, { current: { state: 'closed' } }, { current: { base: { ref: 'release/v1.3' } } }, + { detail: { reviewDecision: 'REVIEW_REQUIRED' } }, { detail: { reviewDecision: 'CHANGES_REQUESTED' } }, + { detail: { mergeStateStatus: 'BLOCKED' } }, { detail: { mergeStateStatus: 'UNKNOWN' } }, + { detail: { mergeQueueEntry: { id: 'entry' } } }, { detail: { autoMergeRequest: { enabledAt: 'now' } } }, + { threads: [[false]] }, { threads: [[true], [false]] } + ]) { + assert.equal((await run(options)).some(c => c[0] === 'enqueue'), false, JSON.stringify(options)); + } +}); + +test('all thread pages are checked before enqueueing', async () => { + const calls = await run({ threads: [[true], [true]] }); + assert.deepEqual(calls.filter(c => c[0] === 'threads'), [['threads', null], ['threads', 'page-0']]); + assert.equal(calls.filter(c => c[0] === 'enqueue').length, 1); +}); + +test('per-run cap and individual failures do not prevent later candidates', async () => { + assert.equal((await run({ count: 8 })).filter(c => c[0] === 'enqueue').length, 5); + const calls = await run({ count: 2, failFirst: true }); + assert.equal(calls.filter(c => c[0] === 'enqueue').length, 2); + assert.equal(calls.filter(c => c[0] === 'failed').length, 1); +}); diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index b3ff212ade4..941f36d9726 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -75,7 +75,7 @@ jobs: with: node-version: 24 - name: Run Node GitHub script tests - run: node --test .github/scripts/query-regression-comment.test.cjs + run: node --test .github/scripts/query-regression-comment.test.cjs .github/scripts/tests/nightly-merge.test.cjs - name: Setup uv uses: astral-sh/setup-uv@v3 with: diff --git a/.github/workflows/nightly-merge.yml b/.github/workflows/nightly-merge.yml new file mode 100644 index 00000000000..ff6d5874ff1 --- /dev/null +++ b/.github/workflows/nightly-merge.yml @@ -0,0 +1,138 @@ +# Setup and behavior: .github/nightly-merge.md +name: Nightly Merge + +on: + pull_request_target: + types: [opened, edited, reopened] + schedule: + # Hourly from 02:10 through 08:10 Asia/Shanghai (UTC+8), inclusive. + # GitHub may delay scheduled runs. + - cron: '10 0,18-23 * * *' + workflow_dispatch: + inputs: + dry_run: + description: List eligible PRs without adding them to the merge queue + type: boolean + default: true + +permissions: {} + +jobs: + sync-label: + if: github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'pull_request_target' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + pull-requests: read + issues: write + concurrency: + group: nightly-merge-label-${{ github.event.pull_request.number }} + cancel-in-progress: false + steps: + # No checkout: PR contents are untrusted data, never executable code. + - uses: actions/github-script@v7 + with: + script: | + const { owner, repo } = context.repo; + const issue_number = context.payload.pull_request.number; + const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: issue_number }); + const selected = /^- \[[xX]\] Merge during the nightly window \s*$/m.test(pr.body || ''); + const label = 'merge nightly'; + const labeled = pr.labels.some(item => item.name === label); + if (selected && !labeled) { + await github.rest.issues.addLabels({ owner, repo, issue_number, labels: [label] }); + } else if (!selected && labeled) { + await github.rest.issues.removeLabel({ owner, repo, issue_number, name: label }); + } + + enqueue: + if: github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'pull_request_target' + runs-on: ubuntu-latest + timeout-minutes: 10 + concurrency: + group: nightly-merge-enqueue + cancel-in-progress: false + steps: + # Reuses the automation credential used by backport and compat updates. + # A PAT (or App token) lets subsequent merge_group workflows run. + - uses: actions/github-script@v7 + env: + DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} + with: + github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }} + script: | + const { owner, repo } = context.repo; + const dryRun = process.env.DRY_RUN === 'true'; + const candidates = await github.paginate(github.rest.issues.listForRepo, { + owner, repo, state: 'open', labels: 'merge nightly', + sort: 'created', direction: 'asc', per_page: 100 + }); + const rows = []; + let enqueued = 0; + for (const candidate of candidates) { + if (!candidate.pull_request || enqueued >= 5) continue; + const number = candidate.number; + try { + // Fetch current body/labels, not the earlier list snapshot. + const { data: current } = await github.rest.pulls.get({ owner, repo, pull_number: number }); + if (current.state !== 'open' || current.draft || current.base.ref !== 'main' || + !current.labels.some(label => label.name === 'merge nightly') || + !/^- \[[xX]\] Merge during the nightly window \s*$/m.test(current.body || '')) { + rows.push([String(number), 'Skipped: not opted in, draft, closed, or not targeting main']); + continue; + } + const { repository: { pullRequest: pr } } = await github.graphql(` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + id headRefOid reviewDecision mergeStateStatus + mergeQueueEntry { id } + autoMergeRequest { enabledAt } + } + } + }`, { owner, repo, number }); + if (pr.mergeQueueEntry || pr.autoMergeRequest || + pr.reviewDecision !== 'APPROVED' || pr.mergeStateStatus !== 'CLEAN') { + rows.push([String(number), 'Skipped: already queued/auto-merge enabled, or not approved and clean']); + continue; + } + let cursor = null; + let unresolved = false; + do { + const { repository: { pullRequest: { reviewThreads } } } = await github.graphql(` + query($owner: String!, $repo: String!, $number: Int!, $cursor: String) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + reviewThreads(first: 100, after: $cursor) { + nodes { isResolved } + pageInfo { hasNextPage endCursor } + } + } + } + }`, { owner, repo, number, cursor }); + unresolved = reviewThreads.nodes.some(thread => !thread.isResolved); + cursor = reviewThreads.pageInfo.hasNextPage ? reviewThreads.pageInfo.endCursor : null; + } while (cursor && !unresolved); + if (unresolved) { + rows.push([String(number), 'Skipped: unresolved review threads']); + continue; + } + if (!dryRun) { + // GitHub enforces branch rules; never bypass or enable auto-merge. + await github.graphql(` + mutation($id: ID!, $sha: GitObjectID!) { + enqueuePullRequest(input: {pullRequestId: $id, expectedHeadOid: $sha}) { + mergeQueueEntry { id } + } + }`, { id: pr.id, sha: pr.headRefOid }); + } + enqueued++; + rows.push([String(number), dryRun ? 'Would enqueue' : 'Enqueued']); + } catch (error) { + core.warning(`PR #${number}: ${error.message}`); + rows.push([String(number), 'Failed: see workflow logs']); + core.setFailed('Some PRs could not be processed; see workflow logs.'); + } + } + await core.summary.addHeading(dryRun ? 'Nightly merge (dry run)' : 'Nightly merge') + .addTable([['PR', 'Result'], ...rows]).write(); From 8e16710425da8fde4be4b87614864e8367005348 Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Wed, 28 Oct 2026 13:33:39 +0000 Subject: [PATCH 12/19] fix(log-store): accept a retried first create of the conditional create probe (#10034) * fix(log-store): accept a retried first create of the conditional create probe The startup probe of the object store WAL wrote its first create by hand and failed on any error. When that create is stored but its response is lost, the retry layer repeats it, the repeat meets the object, and the probe reported a failed write, so the WAL refused to open. Move the create of put_if_absent, which reads the object back and accepts identical content, into a path-based core and use it for the probe's first create too. The second create, which the store must refuse, is unchanged. Signed-off-by: jeremyhi * test(log-store): reuse LosingWriter for the retried probe create test Move LosingWriter from the fault matrix into the test module and use it, armed with the lose_next pattern, in place of RetriedWriter. Say why the probe's second create bypasses put_path_if_absent: a read-back would find the first create's object and let an overwriting store pass. Signed-off-by: jeremyhi --------- Signed-off-by: jeremyhi --- src/log-store/src/object_store_wal/io.rs | 35 ++++++----- src/log-store/src/object_store_wal/store.rs | 69 +++++++++++++++------ 2 files changed, 70 insertions(+), 34 deletions(-) diff --git a/src/log-store/src/object_store_wal/io.rs b/src/log-store/src/object_store_wal/io.rs index 0c087141c52..c14a078f833 100644 --- a/src/log-store/src/object_store_wal/io.rs +++ b/src/log-store/src/object_store_wal/io.rs @@ -96,16 +96,15 @@ impl ObjectStoreIo { /// call, twice, and then deletes it. pub(crate) async fn probe_conditional_create(&self) -> Result<()> { let path = format!("{}{}", self.probe_prefix, Uuid::new_v4()); - let create = || { - self.store - .write_with(&path, PROBE_CONTENT) - .if_not_exists(true) - }; - create().await.context(WalObjectStoreSnafu { - operation: "write", - path: path.clone(), - })?; - let recreated = create().await; + self.put_path_if_absent(path.clone(), Bytes::from_static(PROBE_CONTENT)) + .await?; + // Sent directly: only the store's own refusal shows that it honours + // the condition, and a read-back would find the first create's object. + let recreated = self + .store + .write_with(&path, PROBE_CONTENT) + .if_not_exists(true) + .await; if let Err(error) = self.store.delete(&path).await { warn!(error; "Failed to delete the conditional create probe {path} of the object store WAL"); } @@ -134,15 +133,23 @@ impl ObjectStoreIo { } } - /// Creates the object `object_seq` unless it already exists. A retry with - /// the same content is accepted, different content is rejected. + /// Creates the object `object_seq` unless it already exists, see + /// [`Self::put_path_if_absent`]. + pub(crate) async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result { + self.put_path_if_absent(self.object_path(object_seq), content) + .await + } + + /// Creates `path` unless it already exists. A retry with the same content + /// is accepted, different content is rejected: a create the store stored + /// but whose response was lost can be retried, by the caller or by the + /// retry layer, and then finds its own object. /// /// When the store reports that the object exists but the read that /// compares its content fails, the read failure is returned, so that its /// retry hint says whether comparing again may settle the outcome. Any /// other create failure is returned as the write failure it is. - pub(crate) async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result { - let path = self.object_path(object_seq); + async fn put_path_if_absent(&self, path: String, content: Bytes) -> Result { let write_result = self .store .write_with(&path, content.clone()) diff --git a/src/log-store/src/object_store_wal/store.rs b/src/log-store/src/object_store_wal/store.rs index a741c337d88..354521f38d2 100644 --- a/src/log-store/src/object_store_wal/store.rs +++ b/src/log-store/src/object_store_wal/store.rs @@ -4038,6 +4038,25 @@ mod tests { } } + /// A writer that writes the object and then reports a failure, as a + /// create whose response is lost. + struct LosingWriter(oio::Writer); + + impl oio::Write for LosingWriter { + async fn write(&mut self, buffer: mock::Buffer) -> mock::Result<()> { + self.0.write(buffer).await + } + + async fn close(&mut self) -> mock::Result { + self.0.close().await?; + Err(mock::Error::new(mock::ErrorKind::Unexpected, "lost response").set_temporary()) + } + + async fn abort(&mut self) -> mock::Result<()> { + self.0.abort().await + } + } + async fn keys(object_store: &ObjectStore) -> Vec { let mut keys = object_store .list_with(&format!("{PREFIX}/")) @@ -4096,6 +4115,35 @@ mod tests { assert!(keys(&object_store).await.is_empty()); } + #[tokio::test] + async fn test_store_open_accepts_a_retried_first_probe_create() { + let _serialized = SERIALIZED.lock().await; + let object_store = memory_store(); + let lose_next = Arc::new(AtomicBool::new(true)); + let losing = lose_next.clone(); + let retrying = object_store.clone().layer( + MockLayerBuilder::default() + .writer_factory(Arc::new(move |_, _, inner| { + if losing.swap(false, Ordering::SeqCst) { + Box::new(LosingWriter(inner)) + } else { + inner + } + })) + .build() + .unwrap(), + ); + + // The first write of the open is the first create of the probe. + let store = open(retrying, &eager()).await; + assert!(!lose_next.load(Ordering::SeqCst)); + store.stop().await.unwrap(); + assert_eq!( + vec![object_path(&object_store, 0)], + keys(&object_store).await + ); + } + #[tokio::test] async fn test_store_recovery_ignores_a_probe_left_behind() { let _serialized = SERIALIZED.lock().await; @@ -10500,7 +10548,7 @@ mod tests { /// object store access through the store, one case per fault, and checks /// that every row of the *Failure matrix* has one. mod fault_matrix { - use object_store::layers::mock::{self, MockLayerBuilder, oio}; + use object_store::layers::mock::MockLayerBuilder; use prometheus::Histogram; use super::*; @@ -11459,25 +11507,6 @@ mod tests { assert!(!lose_next.load(Ordering::SeqCst)); } - /// A writer that writes the object and then reports a failure, as a - /// create whose response is lost. - struct LosingWriter(oio::Writer); - - impl oio::Write for LosingWriter { - async fn write(&mut self, buffer: mock::Buffer) -> mock::Result<()> { - self.0.write(buffer).await - } - - async fn close(&mut self) -> mock::Result { - self.0.close().await?; - Err(mock::Error::new(mock::ErrorKind::Unexpected, "lost response").set_temporary()) - } - - async fn abort(&mut self) -> mock::Result<()> { - self.0.abort().await - } - } - /// Object 2 is created and object 3 in flight when object 1 fails. async fn create_fails_transiently_durable() { let (store, io, mut parked) = open_parking_creates(memory_store(), &eager()).await; From 4c37ed4a0e44a1cb968ba9dc1e3a88c7c97cfa2b Mon Sep 17 00:00:00 2001 From: Yvan Wang <131545713+BootstrapperSBL@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:09:21 +0000 Subject: [PATCH 13/19] feat(pipeline): add logfmt processor (#9586) Add a built-in pipeline processor that parses logfmt lines (https://brandur.org/logfmt) into structured objects, with support for quoted values, escapes, bare-key flags, and ignore_missing. Closes #5049 Signed-off-by: Yvan Wang <131545713+BootstrapperSBL@users.noreply.github.com> --- src/pipeline/src/error.rs | 8 + src/pipeline/src/etl/processor.rs | 4 + src/pipeline/src/etl/processor/logfmt.rs | 328 +++++++++++++++++++++++ src/pipeline/tests/logfmt.rs | 122 +++++++++ 4 files changed, 462 insertions(+) create mode 100644 src/pipeline/src/etl/processor/logfmt.rs create mode 100644 src/pipeline/tests/logfmt.rs diff --git a/src/pipeline/src/error.rs b/src/pipeline/src/error.rs index 0da65d25436..534dcc14512 100644 --- a/src/pipeline/src/error.rs +++ b/src/pipeline/src/error.rs @@ -619,6 +619,13 @@ pub enum Error { #[snafu(implicit)] location: Location, }, + #[snafu(display("Failed to parse logfmt input: {input}, reason: {reason}"))] + LogfmtParse { + input: String, + reason: String, + #[snafu(implicit)] + location: Location, + }, #[snafu(display("Failed to parse json"))] JsonParse { #[snafu(source)] @@ -1010,6 +1017,7 @@ impl ErrorExt for Error { | UnsupportedIndexType { .. } | IdentifyPipelineColumnTypeMismatch { .. } | JsonParse { .. } + | LogfmtParse { .. } | JsonPathParse { .. } | JsonPathParseResultIndex { .. } | FieldRequiredForDispatcher diff --git a/src/pipeline/src/etl/processor.rs b/src/pipeline/src/etl/processor.rs index 8c999cd13ee..911bd5b9136 100644 --- a/src/pipeline/src/etl/processor.rs +++ b/src/pipeline/src/etl/processor.rs @@ -25,6 +25,7 @@ pub mod join; pub mod json_parse; pub mod json_path; pub mod letter; +pub mod logfmt; pub mod regex; pub mod select; pub mod simple_extract; @@ -45,6 +46,7 @@ use gsub::GsubProcessor; use join::JoinProcessor; use json_path::JsonPathProcessor; use letter::LetterProcessor; +use logfmt::LogfmtProcessor; use regex::RegexProcessor; use snafu::{OptionExt, ResultExt}; use urlencoding::UrlEncodingProcessor; @@ -143,6 +145,7 @@ pub enum ProcessorKind { Date(DateProcessor), JsonPath(JsonPathProcessor), JsonParse(JsonParseProcessor), + Logfmt(LogfmtProcessor), SimpleJsonPath(SimpleExtractProcessor), Decolorize(DecolorizeProcessor), Digest(DigestProcessor), @@ -226,6 +229,7 @@ fn parse_processor(doc: &yaml_rust::Yaml, allow_vrl_host_access: bool) -> Result json_parse::PROCESSOR_JSON_PARSE => { ProcessorKind::JsonParse(JsonParseProcessor::try_from(value)?) } + logfmt::PROCESSOR_LOGFMT => ProcessorKind::Logfmt(LogfmtProcessor::try_from(value)?), vrl_processor::PROCESSOR_VRL => { ProcessorKind::Vrl(VrlProcessor::from_yaml(value, allow_vrl_host_access)?) } diff --git a/src/pipeline/src/etl/processor/logfmt.rs b/src/pipeline/src/etl/processor/logfmt.rs new file mode 100644 index 00000000000..efe804fe869 --- /dev/null +++ b/src/pipeline/src/etl/processor/logfmt.rs @@ -0,0 +1,328 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The `logfmt` processor parses a [logfmt](https://brandur.org/logfmt) line, +//! such as `level=info msg="hello world" duration=12ms`, into an object. + +use std::collections::BTreeMap; + +use snafu::OptionExt as _; +use vrl::prelude::Bytes; +use vrl::value::{KeyString, Value as VrlValue}; + +use crate::Processor; +use crate::error::{ + Error, FieldMustBeTypeSnafu, KeyMustBeStringSnafu, LogfmtParseSnafu, + ProcessorMissingFieldSnafu, Result, ValueMustBeMapSnafu, +}; +use crate::etl::field::Fields; +use crate::etl::processor::{ + FIELD_NAME, FIELDS_NAME, IGNORE_MISSING_NAME, yaml_bool, yaml_new_field, yaml_new_fields, +}; + +pub(crate) const PROCESSOR_LOGFMT: &str = "logfmt"; + +/// Parses logfmt strings into objects. +/// +/// Every `key=value` pair becomes an entry of the output object with a string +/// value. A bare key without `=` (e.g. `debug` in `debug msg=hi`) is treated +/// as a flag and set to `true`. When a key appears more than once, the last +/// value wins. The output is written to the target field, or replaces the +/// input field in place when no target is given. +#[derive(Debug, Default)] +pub struct LogfmtProcessor { + fields: Fields, + ignore_missing: bool, +} + +impl TryFrom<&yaml_rust::yaml::Hash> for LogfmtProcessor { + type Error = Error; + + fn try_from(value: &yaml_rust::yaml::Hash) -> std::result::Result { + let mut fields = Fields::default(); + let mut ignore_missing = false; + + for (k, v) in value.iter() { + let key = k + .as_str() + .with_context(|| KeyMustBeStringSnafu { k: k.clone() })?; + match key { + FIELD_NAME => { + fields = Fields::one(yaml_new_field(v, FIELD_NAME)?); + } + FIELDS_NAME => { + fields = yaml_new_fields(v, FIELDS_NAME)?; + } + IGNORE_MISSING_NAME => { + ignore_missing = yaml_bool(v, IGNORE_MISSING_NAME)?; + } + _ => {} + } + } + + Ok(LogfmtProcessor { + fields, + ignore_missing, + }) + } +} + +impl LogfmtProcessor { + fn process_field(&self, val: &VrlValue) -> Result { + let Some(line) = val.as_str() else { + return FieldMustBeTypeSnafu { + field: val.to_string(), + ty: "string", + } + .fail(); + }; + let pairs = parse_logfmt(&line).map_err(|reason| { + LogfmtParseSnafu { + input: line.to_string(), + reason, + } + .build() + })?; + Ok(VrlValue::Object(pairs)) + } +} + +impl Processor for LogfmtProcessor { + fn kind(&self) -> &str { + PROCESSOR_LOGFMT + } + + fn ignore_missing(&self) -> bool { + self.ignore_missing + } + + fn exec_mut(&self, mut val: VrlValue) -> Result { + for field in self.fields.iter() { + let index = field.input_field(); + let val = val.as_object_mut().context(ValueMustBeMapSnafu)?; + match val.get(index) { + Some(VrlValue::Null) | None => { + if !self.ignore_missing { + return ProcessorMissingFieldSnafu { + processor: self.kind(), + field: field.input_field(), + } + .fail(); + } + } + Some(v) => { + let processed = self.process_field(v)?; + let output_index = field.target_or_input_field(); + val.insert(KeyString::from(output_index.to_string()), processed); + } + } + } + Ok(val) + } +} + +/// Parses a logfmt line into key-value pairs. +/// +/// Follows the grammar used by common logfmt implementations (e.g. go-logfmt): +/// - pairs are separated by whitespace; +/// - a key is a run of printable characters other than `=`, `"` and whitespace; +/// - a value is either unquoted (ends at the next whitespace) or double-quoted, +/// where `\"`, `\\`, `\n`, `\r`, `\t`, `\/`, `\b`, `\f` and `\uXXXX` escapes are supported; +/// - `key=` yields an empty string and a bare `key` yields `true`. +fn parse_logfmt(line: &str) -> std::result::Result, String> { + let mut output = BTreeMap::new(); + let mut chars = line.char_indices().peekable(); + + loop { + // Skip separators. + while chars.next_if(|(_, c)| c.is_whitespace()).is_some() {} + let Some(&(key_start, first)) = chars.peek() else { + break; + }; + if first == '=' || first == '"' { + return Err(format!("unexpected '{first}' at position {key_start}")); + } + + let mut key_end = line.len(); + while let Some(&(i, c)) = chars.peek() { + if c == '=' || c.is_whitespace() { + key_end = i; + break; + } + if c == '"' || c.is_control() { + return Err(format!("invalid character {c:?} in key at position {i}")); + } + chars.next(); + } + let key = KeyString::from(&line[key_start..key_end]); + + if chars.next_if(|(_, c)| *c == '=').is_none() { + // Bare key, e.g. `debug`. + output.insert(key, VrlValue::Boolean(true)); + continue; + } + + let value = match chars.peek() { + Some(&(_, '"')) => { + chars.next(); + parse_quoted_value(&mut chars)? + } + Some(&(value_start, _)) => { + let mut value_end = line.len(); + while let Some(&(i, c)) = chars.peek() { + if c.is_whitespace() { + value_end = i; + break; + } + if c == '"' || c == '=' { + return Err(format!( + "unexpected '{c}' in unquoted value at position {i}" + )); + } + chars.next(); + } + line[value_start..value_end].to_string() + } + None => String::new(), + }; + output.insert(key, VrlValue::Bytes(Bytes::from(value))); + } + + Ok(output) +} + +/// Parses the rest of a double-quoted value; the opening quote is already consumed. +fn parse_quoted_value( + chars: &mut std::iter::Peekable>, +) -> std::result::Result { + let mut value = String::new(); + loop { + let Some((i, c)) = chars.next() else { + return Err("unterminated quoted value".to_string()); + }; + match c { + '"' => { + if let Some(&(j, next)) = chars.peek() + && !next.is_whitespace() + { + return Err(format!( + "expect whitespace after quoted value at position {j}, found '{next}'" + )); + } + return Ok(value); + } + '\\' => { + let Some((_, escaped)) = chars.next() else { + return Err("unterminated escape sequence".to_string()); + }; + match escaped { + '"' => value.push('"'), + '\\' => value.push('\\'), + '/' => value.push('/'), + 'n' => value.push('\n'), + 'r' => value.push('\r'), + 't' => value.push('\t'), + 'b' => value.push('\u{8}'), + 'f' => value.push('\u{c}'), + 'u' => { + let hex: String = chars.by_ref().take(4).map(|(_, c)| c).collect(); + let decoded = (hex.len() == 4) + .then(|| u32::from_str_radix(&hex, 16).ok()) + .flatten() + .and_then(char::from_u32) + .ok_or_else(|| format!("invalid unicode escape '\\u{hex}'"))?; + value.push(decoded); + } + other => { + return Err(format!("invalid escape '\\{other}' at position {i}")); + } + } + } + c => value.push(c), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn obj(pairs: &[(&str, VrlValue)]) -> BTreeMap { + pairs + .iter() + .map(|(k, v)| (KeyString::from(*k), v.clone())) + .collect() + } + + fn s(v: &str) -> VrlValue { + VrlValue::Bytes(Bytes::from(v.to_string())) + } + + #[test] + fn test_parse_logfmt() { + let parsed = parse_logfmt( + r#"ts=2026-10-14T10:00:00Z level=info msg="hello \"world\"" path=/api/v1 empty= debug"#, + ) + .unwrap(); + assert_eq!( + parsed, + obj(&[ + ("ts", s("2026-10-14T10:00:00Z")), + ("level", s("info")), + ("msg", s(r#"hello "world""#)), + ("path", s("/api/v1")), + ("empty", s("")), + ("debug", VrlValue::Boolean(true)), + ]) + ); + } + + #[test] + fn test_parse_logfmt_whitespace_escapes_and_duplicates() { + let parsed = parse_logfmt(" a=1\tb=\"x\\ny\\u00e9\" a=2 ").unwrap(); + assert_eq!(parsed, obj(&[("a", s("2")), ("b", s("x\nyé"))])); + assert!(parse_logfmt("").unwrap().is_empty()); + assert!(parse_logfmt(" ").unwrap().is_empty()); + assert_eq!(parse_logfmt("k=\"\"").unwrap(), obj(&[("k", s(""))])); + assert_eq!(parse_logfmt("k=").unwrap(), obj(&[("k", s(""))])); + } + + #[test] + fn test_parse_logfmt_invalid() { + for input in [ + "=value", + "\"key\"=value", + "msg=\"unterminated", + "msg=\"bad\\q\"", + "msg=\"a\"b", + "k=a\"b", + "k=a=b", + "msg=\"\\u12\"", + ] { + assert!(parse_logfmt(input).is_err(), "expect error for {input:?}"); + } + } + + #[test] + fn test_logfmt_processor() { + let processor = LogfmtProcessor::default(); + let result = processor.process_field(&s("level=warn code=42")).unwrap(); + assert_eq!( + result, + VrlValue::Object(obj(&[("code", s("42")), ("level", s("warn"))])) + ); + assert!(processor.process_field(&VrlValue::Integer(1)).is_err()); + assert!(processor.process_field(&s("msg=\"oops")).is_err()); + } +} diff --git a/src/pipeline/tests/logfmt.rs b/src/pipeline/tests/logfmt.rs new file mode 100644 index 00000000000..891721c8402 --- /dev/null +++ b/src/pipeline/tests/logfmt.rs @@ -0,0 +1,122 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod common; + +use common_query::prelude::greptime_timestamp; +use greptime_proto::v1::value::ValueData; +use greptime_proto::v1::{ColumnDataType, SemanticType}; + +#[test] +fn test_logfmt() { + let input_value_str = r#" +[ + { + "message": "level=info msg=\"user logged in\" user=alice duration=12ms cached" + } +] +"#; + + let pipeline_yaml = r#" +--- +processors: + - logfmt: + field: message, parsed + - simple_extract: + field: parsed, level + key: "level" + - simple_extract: + field: parsed, msg + key: "msg" + - simple_extract: + field: parsed, user + key: "user" + - simple_extract: + field: parsed, cached + key: "cached" + +transform: + - fields: + - level + - msg + - user + type: string + - field: cached + type: boolean +"#; + + let output = common::parse_and_exec(input_value_str, pipeline_yaml); + + let expected_schema = vec![ + common::make_column_schema( + "level".to_string(), + ColumnDataType::String, + SemanticType::Field, + ), + common::make_column_schema( + "msg".to_string(), + ColumnDataType::String, + SemanticType::Field, + ), + common::make_column_schema( + "user".to_string(), + ColumnDataType::String, + SemanticType::Field, + ), + common::make_column_schema( + "cached".to_string(), + ColumnDataType::Boolean, + SemanticType::Field, + ), + common::make_column_schema( + greptime_timestamp().to_string(), + ColumnDataType::TimestampNanosecond, + SemanticType::Timestamp, + ), + ]; + assert_eq!(output.schema, expected_schema); + + let values = &output.rows[0].values; + assert_eq!( + values[0].value_data, + Some(ValueData::StringValue("info".to_string())) + ); + assert_eq!( + values[1].value_data, + Some(ValueData::StringValue("user logged in".to_string())) + ); + assert_eq!( + values[2].value_data, + Some(ValueData::StringValue("alice".to_string())) + ); + assert_eq!(values[3].value_data, Some(ValueData::BoolValue(true))); +} + +#[test] +fn test_logfmt_ignore_missing() { + let pipeline_yaml = r#" +--- +processors: + - logfmt: + field: message + ignore_missing: true + +transform: + - field: message + type: string +"#; + + let output = common::parse_and_exec(r#"[{"other": "x"}]"#, pipeline_yaml); + assert_eq!(output.rows[0].values[0].value_data, None); +} From b83ceb5e7bf260dd9cbd1e11b63ac8187ba0ff0a Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Wed, 28 Oct 2026 17:09:23 +0000 Subject: [PATCH 14/19] feat: add reusable paged byte cache (#9791) * feat: add reusable paged byte cache Signed-off-by: WenyXu * fix(ci): include common cache in scope rules Signed-off-by: WenyXu --------- Signed-off-by: WenyXu --- .github/ci/scope-rules.toml | 1 + Cargo.lock | 3 + src/common/cache/Cargo.toml | 5 +- src/common/cache/src/lib.rs | 2 + src/common/cache/src/page.rs | 156 +++++++++ src/common/cache/src/paged.rs | 384 ++++++++++++++++++++++ src/common/cache/src/paged/tests.rs | 492 ++++++++++++++++++++++++++++ 7 files changed, 1042 insertions(+), 1 deletion(-) create mode 100644 src/common/cache/src/page.rs create mode 100644 src/common/cache/src/paged.rs create mode 100644 src/common/cache/src/paged/tests.rs diff --git a/.github/ci/scope-rules.toml b/.github/ci/scope-rules.toml index ba2b92deda2..0c9920d5711 100644 --- a/.github/ci/scope-rules.toml +++ b/.github/ci/scope-rules.toml @@ -103,6 +103,7 @@ server = [ "src/datanode/**", "src/common/base/**", "src/common/batcher/**", + "src/common/cache/**", "src/common/catalog/**", "src/common/config/**", "src/common/datasource/**", diff --git a/Cargo.lock b/Cargo.lock index 8e4183994d4..f68dfbe2334 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2344,6 +2344,9 @@ dependencies = [ name = "common-cache" version = "1.4.0-alpha.0" dependencies = [ + "async-trait", + "bytes", + "common-base", "futures", "moka", "prometheus 0.14.0", diff --git a/src/common/cache/Cargo.toml b/src/common/cache/Cargo.toml index 1e2f9d83a5a..afa9a8f3623 100644 --- a/src/common/cache/Cargo.toml +++ b/src/common/cache/Cargo.toml @@ -8,9 +8,12 @@ license.workspace = true workspace = true [dependencies] +bytes.workspace = true +common-base.workspace = true +futures.workspace = true moka = { workspace = true, features = ["future"] } prometheus.workspace = true [dev-dependencies] -futures.workspace = true +async-trait.workspace = true tokio = { workspace = true, features = ["macros", "rt", "sync"] } diff --git a/src/common/cache/src/lib.rs b/src/common/cache/src/lib.rs index 58d54adee68..228f0ca3cf9 100644 --- a/src/common/cache/src/lib.rs +++ b/src/common/cache/src/lib.rs @@ -17,5 +17,7 @@ mod cache; pub mod metrics; +pub mod page; +pub mod paged; pub use cache::{Cache, RemovalCause}; diff --git a/src/common/cache/src/page.rs b/src/common/cache/src/page.rs new file mode 100644 index 00000000000..19568debc5e --- /dev/null +++ b/src/common/cache/src/page.rs @@ -0,0 +1,156 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Fixed-size byte page layout for immutable cached content. + +use std::io; +use std::num::NonZeroU64; +use std::ops::Range; + +/// Fixed-size logical byte pages within one immutable file. +#[derive(Debug, Clone, Copy)] +pub struct PageLayout { + page_size: NonZeroU64, + file_size: u64, +} + +impl PageLayout { + /// Creates a layout. The final page is clipped to the file size. + pub fn new(page_size: NonZeroU64, file_size: u64) -> Self { + Self { + page_size, + file_size, + } + } + + /// Returns the half-open page-ID range intersecting a byte request. + /// + /// Requests are clipped at EOF. Empty or wholly out-of-file requests return + /// an empty range; reversed ranges are rejected. This does not allocate one + /// entry per page, even for large files. + pub fn page_ids(&self, request: Range) -> io::Result> { + validate_range(&request)?; + let start = request.start.min(self.file_size); + let end = request.end.min(self.file_size); + let first = start / self.page_size.get(); + if start == end { + return Ok(first..first); + } + // end > 0 here. Unlike (end + page_size - 1) / page_size, + // this expression cannot overflow at the end of a large file. + let last = (end - 1) / self.page_size.get(); + Ok(first..last + 1) + } + + /// Returns a page's file byte range, or `None` for a page outside the file. + pub fn page_range(&self, page_id: u64) -> Option> { + let start = page_id.checked_mul(self.page_size.get())?; + if start >= self.file_size { + return None; + } + let len = self.page_size.get().min(self.file_size - start); + Some(start..start + len) + } + + /// Returns the requested slice relative to a page's buffer. + /// + /// Returns `None` if the page and request do not intersect. The caller can + /// borrow this slice for an immediate response; caching a slice of a much + /// larger I/O buffer may retain that entire allocation and needs a copy. + pub fn request_slice( + &self, + page_id: u64, + request: Range, + ) -> io::Result>> { + validate_range(&request)?; + let Some(page) = self.page_range(page_id) else { + return Ok(None); + }; + let start = request.start.max(page.start); + let end = request.end.min(page.end); + if start >= end { + return Ok(None); + } + Ok(Some( + to_usize(start - page.start)?..to_usize(end - page.start)?, + )) + } +} + +fn validate_range(range: &Range) -> io::Result<()> { + if range.start > range.end { + return Err(invalid_input("Byte range start exceeds end")); + } + Ok(()) +} + +fn to_usize(value: u64) -> io::Result { + usize::try_from(value).map_err(|_| invalid_input("Byte offset exceeds addressable memory")) +} + +fn invalid_input(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidInput, message) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn nonzero(value: u64) -> NonZeroU64 { + NonZeroU64::new(value).unwrap() + } + + #[test] + fn test_page_alignment_and_eof() { + let layout = PageLayout::new(nonzero(64), 150); + for (request, expected) in [ + (0..0, 0..0), + (0..64, 0..1), + (32..96, 0..2), + (64..128, 1..2), + (128..200, 2..3), + (150..200, 2..2), + ] { + assert_eq!(layout.page_ids(request).unwrap(), expected); + } + assert_eq!(layout.page_range(2), Some(128..150)); + assert_eq!(layout.page_range(3), None); + assert_eq!(layout.request_slice(0, 32..96).unwrap(), Some(32..64)); + assert_eq!(layout.request_slice(1, 32..96).unwrap(), Some(0..32)); + assert_eq!(layout.request_slice(2, 128..200).unwrap(), Some(0..22)); + assert_eq!(layout.request_slice(1, 0..64).unwrap(), None); + assert_eq!(PageLayout::new(nonzero(64), 0).page_range(0), None); + assert!(layout.page_ids(Range { start: 2, end: 1 }).is_err()); + assert!(layout.request_slice(0, Range { start: 2, end: 1 }).is_err()); + } + + #[test] + fn test_large_file_boundaries() { + let layout = PageLayout::new(nonzero(1), u64::MAX); + assert_eq!(layout.page_ids(0..u64::MAX).unwrap(), 0..u64::MAX); + assert_eq!( + layout.page_range(u64::MAX - 1), + Some(u64::MAX - 1..u64::MAX) + ); + assert_eq!(layout.page_range(u64::MAX), None); + let layout = PageLayout::new(nonzero(64), u64::MAX); + assert_eq!(layout.page_range(u64::MAX), None); + let last = u64::MAX / 64; + assert_eq!(layout.page_range(last), Some(last * 64..u64::MAX)); + assert_eq!( + layout.page_ids(u64::MAX - 1..u64::MAX).unwrap(), + last..last + 1 + ); + } +} diff --git a/src/common/cache/src/paged.rs b/src/common/cache/src/paged.rs new file mode 100644 index 00000000000..f2e8a659ddf --- /dev/null +++ b/src/common/cache/src/paged.rs @@ -0,0 +1,384 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Immutable byte pages backed by native cache loading and direct range reads. + +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, BTreeSet}; +use std::future::Future; +use std::hash::Hash; +use std::io; +use std::num::NonZeroU64; +use std::ops::Range; +use std::sync::Arc; +use std::task::Poll; + +use bytes::{Bytes, BytesMut}; +use common_base::range_read::RangeReader; +use futures::channel::{mpsc, oneshot}; +use futures::{StreamExt, future}; + +use crate::metrics::{CacheMetrics, CacheSizeMetric}; +use crate::page::PageLayout; +use crate::{Cache, RemovalCause}; + +/// Business-level events; callers retain their existing hit/miss metric units. +pub enum PageEvent { + /// Unique logical page lookups in one request, before any missing loads execute. + Lookup { hits: usize, misses: usize }, + /// One successful native page loader, excluding waiters and hits. + Loaded { bytes: u64 }, + /// Backend weight, not process RSS; sampled after fetch/maintenance. + Residency { usage: u64, capacity: u64 }, + /// Backend eviction, excluding unadmitted values released by their owners. + Evicted { cause: RemovalCause }, +} + +/// Caller-bound metrics without storage-engine dependencies or global registrations. +#[derive(Clone)] +pub struct PageCacheObserver { + pub bytes: CacheSizeMetric, + pub loads: Option>, + pub events: Arc, +} + +/// Byte accounting for one successful fetch. Hits are initial lookups, not waiters. +#[derive(Debug, Default)] +pub struct PageFetchStats { + pub cache_hit: usize, + pub cache_miss: usize, + /// Requested intersections already cached; overlapping requests count repeatedly. + pub cached_bytes: u64, + pub cached_fragments: usize, + /// Original request lengths, including duplicates and overlaps. + pub requested_bytes: u64, + /// Sum of unique logical page lengths, clipped at EOF, including cache hits. + pub aligned_bytes: u64, + /// Union of original request byte ranges, excluding overlaps. + pub unique_requested_bytes: u64, +} + +/// Caches fixed-size byte pages of immutable content identified by `K`. +/// File identity must include any version needed to distinguish different contents. +/// Missing pages elected by this fetch are submitted through [`RangeReader::read_vec`]. +pub struct PagedCache { + cache: Cache<(K, u64), Arc>, + page_size: u64, + observer: PageCacheObserver, +} + +impl PagedCache { + /// Creates an independent cache budget. Zero page size is rejected by fetch. + pub fn new( + name: &str, + capacity: u64, + page_size: u64, + weigher: impl Fn(&(K, u64), &Bytes) -> u32 + Send + Sync + 'static, + observer: PageCacheObserver, + ) -> Self { + let events = observer.events.clone(); + let mut cache = Cache::new( + name, + capacity, + move |key, value: &Arc| weigher(key, &value.bytes), + move |_, _, cause| { + events(PageEvent::Evicted { cause }); + }, + ) + .with_size_metric(observer.bytes.clone()); + if let Some(metrics) = &observer.loads { + cache = cache.with_metrics(metrics.clone()); + } + Self { + cache, + page_size, + observer, + } + } + + /// Invalidates completed pages. Concurrent loads are not fenced. + pub fn invalidate_if( + &self, + predicate: impl Fn(&K) -> bool + Send + Sync + 'static, + ) -> io::Result<()> { + self.cache + .invalidate_if(move |(file, _), _| predicate(file)) + } + + /// Looks up a completed page without updating business lookup counters. + pub async fn contains(&self, file: &K, page_id: u64) -> bool { + self.cache.get(&(file.clone(), page_id)).await.is_some() + } + + /// Recovers immutable file size from a requested page already in memory. + pub async fn known_file_size(&self, file: &K, ranges: &[Range]) -> Option { + let layout = PageLayout::new(NonZeroU64::new(self.page_size)?, u64::MAX); + for range in ranges { + for id in layout.page_ids(range.clone()).ok()? { + if let Some(page) = self.cache.get(&(file.clone(), id)).await { + return Some(page.file_size); + } + } + } + None + } + + /// Applies pending cache admission and eviction work. + pub async fn run_pending_tasks(&self) { + self.cache.run_pending_tasks().await; + self.observe_residency(); + } + + /// Fetches bytes in input order. The reader must address the same immutable + /// content as `file`. Each successful loader reads one complete missing page. + pub async fn fetch( + &self, + file: K, + file_size: u64, + ranges: &[Range], + reader: &R, + ) -> Result<(Vec, PageFetchStats), Arc> { + if ranges.iter().any(|r| r.start > r.end || r.end > file_size) { + return Err(invalid_request()); + } + let page_size = NonZeroU64::new(self.page_size).ok_or_else(invalid_request)?; + let layout = PageLayout::new(page_size, file_size); + let mut stats = PageFetchStats::default(); + let mut ids = BTreeSet::new(); + for range in ranges { + stats.requested_bytes = stats + .requested_bytes + .checked_add(range.end - range.start) + .ok_or_else(invalid_request)?; + ids.extend(layout.page_ids(range.clone()).map_err(Arc::new)?); + } + stats.unique_requested_bytes = unique_requested_bytes(ranges); + let mut pages = BTreeMap::new(); + let mut missing = Vec::new(); + for id in ids { + let range = layout.page_range(id).ok_or_else(invalid_request)?; + stats.aligned_bytes += range.end - range.start; + if let Some(page) = self.cache.get(&(file.clone(), id)).await { + check_file_size(&page, file_size)?; + pages.insert(id, page.bytes.clone()); + } else { + missing.push(id); + } + } + for range in ranges { + for id in layout.page_ids(range.clone()).map_err(Arc::new)? { + if pages.contains_key(&id) { + let slice = layout + .request_slice(id, range.clone()) + .map_err(Arc::new)? + .ok_or_else(invalid_request)?; + stats.cached_bytes += slice.len() as u64; + stats.cached_fragments += 1; + } + } + } + stats.cache_hit = pages.len(); + stats.cache_miss = missing.len(); + (self.observer.events)(PageEvent::Lookup { + hits: stats.cache_hit, + misses: stats.cache_miss, + }); + if !missing.is_empty() { + let (requests, receiver) = mpsc::unbounded(); + let batch_size = missing.len().max(1); + let mut loads = missing + .into_iter() + .map(|id| { + let requests = requests.clone(); + let key = (file.clone(), id); + Box::pin(future::maybe_done(async move { + let range = layout.page_range(id).ok_or_else(invalid_request)?; + let page = self + .cache + .try_get_with(&key, async { + let (send, receive) = + oneshot::channel::>>(); + requests + .unbounded_send((range.clone(), send)) + .map_err(|_| io::Error::other("Page read batch closed"))?; + let bytes = receive + .await + .map_err(|_| io::Error::other("Page read batch cancelled"))? + .map_err(|error: Arc| { + io::Error::new(error.kind(), error) + })?; + if bytes.len() as u64 != range.end - range.start { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "Invalid page response length", + )); + } + // Detach readers' shared backing buffers from cache accounting. + Ok(self + .create_cached_page(file_size, Bytes::copy_from_slice(&bytes))) + }) + .await?; + check_file_size(&page, file_size)?; + Ok::<_, Arc>((id, page.bytes.clone())) + })) + }) + .collect::>(); + // Poll every page before driving I/O, so executor fairness limits do not + // split one fetch's immediately available misses into separate batches. + let loads = future::poll_fn(move |cx| { + let mut complete = true; + for load in &mut loads { + complete &= load.as_mut().poll(cx).is_ready(); + if let Some(Err(error)) = load.as_mut().output_mut() { + return Poll::Ready(Err(error.clone())); + } + } + if !complete { + return Poll::Pending; + } + Poll::Ready( + loads + .iter_mut() + .map(|load| load.as_mut().take_output().ok_or_else(invalid_request)?) + .collect::, _>>(), + ) + }); + // The channel contains only loaders elected by Moka for this fetch. Waiters + // enqueue nothing; a waiter promoted after cancellation can enqueue later. + drop(requests); + let read_batches = async { + let mut batches = receiver.ready_chunks(batch_size); + while let Some(batch) = batches.next().await { + let (ranges, replies): (Vec<_>, Vec<_>) = batch.into_iter().unzip(); + let result = reader.read_vec(&ranges).await.and_then(|bytes| { + if bytes.len() == ranges.len() { + Ok(bytes) + } else { + Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid page response count", + )) + } + }); + match result { + Ok(bytes) => { + for (reply, bytes) in replies.into_iter().zip(bytes) { + let _ = reply.send(Ok(bytes)); + } + } + Err(error) => { + let error = Arc::new(error); + for reply in replies { + let _ = reply.send(Err(error.clone())); + } + } + } + } + Ok::<(), Arc>(()) + }; + let (loaded, ()) = future::try_join(loads, read_batches).await?; + pages.extend(loaded); + } + let mut output = Vec::with_capacity(ranges.len()); + for range in ranges { + if range.is_empty() { + output.push(Bytes::new()); + continue; + } + let ids = layout.page_ids(range.clone()).map_err(Arc::new)?; + if ids.end - ids.start == 1 { + let slice = layout + .request_slice(ids.start, range.clone()) + .map_err(Arc::new)? + .ok_or_else(invalid_request)?; + let page = pages.get(&ids.start).ok_or_else(invalid_request)?; + if slice.end > page.len() { + return Err(invalid_request()); + } + output.push(page.slice(slice)); + continue; + } + let len = usize::try_from(range.end - range.start).map_err(|_| invalid_request())?; + let mut assembled = BytesMut::with_capacity(len); + for id in ids { + let slice = layout + .request_slice(id, range.clone()) + .map_err(Arc::new)? + .ok_or_else(invalid_request)?; + let page = pages.get(&id).ok_or_else(invalid_request)?; + if slice.end > page.len() { + return Err(invalid_request()); + } + assembled.extend_from_slice(&page[slice]); + } + if assembled.len() != len { + return Err(invalid_request()); + } + output.push(assembled.freeze()); + } + self.observe_residency(); + Ok((output, stats)) + } + + fn create_cached_page(&self, file_size: u64, bytes: Bytes) -> Arc { + (self.observer.events)(PageEvent::Loaded { + bytes: bytes.len() as u64, + }); + Arc::new(CachedPage { file_size, bytes }) + } + + fn observe_residency(&self) { + (self.observer.events)(PageEvent::Residency { + usage: self.cache.weighted_size(), + capacity: self.cache.capacity(), + }); + } +} + +struct CachedPage { + file_size: u64, + bytes: Bytes, +} + +fn invalid_request() -> Arc { + Arc::new(io::Error::new( + io::ErrorKind::InvalidInput, + "Invalid cached page range", + )) +} + +fn check_file_size(page: &CachedPage, expected: u64) -> Result<(), Arc> { + if page.file_size != expected { + return Err(Arc::new(io::Error::new( + io::ErrorKind::InvalidInput, + "Cached content identity used with inconsistent file sizes", + ))); + } + Ok(()) +} + +/// Counts the union of request ranges already validated by fetch. +fn unique_requested_bytes(ranges: &[Range]) -> u64 { + let mut ranges = ranges.to_vec(); + ranges.sort_unstable_by_key(|range| range.start); + let mut end = 0; + let mut bytes = 0; + for range in ranges { + bytes += range.end.saturating_sub(range.start.max(end)); + end = end.max(range.end); + } + bytes +} diff --git a/src/common/cache/src/paged/tests.rs b/src/common/cache/src/paged/tests.rs new file mode 100644 index 00000000000..556455ebfb1 --- /dev/null +++ b/src/common/cache/src/paged/tests.rs @@ -0,0 +1,492 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::future::Future; +use std::pin::Pin; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use async_trait::async_trait; +use common_base::range_read::Metadata; +use tokio::sync::Semaphore; + +use super::*; + +#[derive(Default)] +struct Reader { + reads: Mutex>>, + batches: Mutex>>>, + gate: Option, + error: Option, +} + +impl Reader { + fn gated() -> Self { + Self { + gate: Some(Semaphore::new(0)), + ..Default::default() + } + } + + fn count(&self) -> usize { + self.reads.lock().unwrap().len() + } + + fn release(&self) { + self.gate.as_ref().unwrap().add_permits(64); + } +} + +#[async_trait] +impl RangeReader for Reader { + async fn metadata(&self) -> io::Result { + Ok(Metadata { content_length: 16 }) + } + + async fn read_vec(&self, ranges: &[Range]) -> io::Result> { + self.batches.lock().unwrap().push(ranges.to_vec()); + future::try_join_all(ranges.iter().map(|range| self.read(range.clone()))).await + } + + async fn read(&self, range: Range) -> io::Result { + self.reads.lock().unwrap().push(range.clone()); + if let Some(gate) = &self.gate { + gate.acquire().await.unwrap().forget(); + } + if let Some(kind) = self.error { + return Err(io::Error::new(kind, "backend failed")); + } + Ok(Bytes::from(range.map(|n| n as u8).collect::>())) + } +} + +struct Observation { + loaded: AtomicUsize, + bytes: crate::metrics::CacheSizeMetrics, +} + +impl Observation { + fn bytes(&self) -> i64 { + use prometheus::core::Collector; + self.bytes.collect()[0].get_metric()[0] + .get_gauge() + .as_ref() + .unwrap() + .value() as i64 + } +} + +fn cache() -> (PagedCache, Arc) { + let observation = Arc::new(Observation { + loaded: AtomicUsize::new(0), + bytes: crate::metrics::CacheSizeMetrics::new( + prometheus::Opts::new("test_page_bytes", "test"), + &[], + ) + .unwrap(), + }); + let events = observation.clone(); + let observer = PageCacheObserver { + bytes: observation.bytes.bind(&[]), + loads: None, + events: Arc::new(move |event| { + if let PageEvent::Loaded { .. } = event { + events.loaded.fetch_add(1, Ordering::Relaxed); + } + }), + }; + ( + PagedCache::new("pages", 1024, 4, |_, bytes| bytes.len() as u32, observer), + observation, + ) +} + +async fn start_read(mut future: Pin<&mut F>, reader: &Reader, count: usize) { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + assert!(futures::poll!(future.as_mut()).is_pending()); + if reader.count() >= count { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn test_partial_hits_overlaps_and_eof_preserve_order() { + let (cache, observation) = cache(); + let reader = Reader::default(); + let (first, stats) = cache.fetch(1, 10, &[2..6, 4..5], &reader).await.unwrap(); + assert_eq!( + first, + vec![Bytes::from_static(&[2, 3, 4, 5]), Bytes::from_static(&[4])] + ); + assert_eq!((stats.cache_hit, stats.cache_miss), (0, 2)); + assert_eq!( + ( + stats.requested_bytes, + stats.unique_requested_bytes, + stats.aligned_bytes + ), + (5, 4, 8) + ); + let (second, stats) = cache + .fetch(1, 10, &[6..10, 1..3, 10..10], &reader) + .await + .unwrap(); + assert_eq!( + second, + vec![ + Bytes::from_static(&[6, 7, 8, 9]), + Bytes::from_static(&[1, 2]), + Bytes::new() + ] + ); + assert_eq!((stats.cache_hit, stats.cache_miss), (2, 1)); + assert_eq!((stats.cached_bytes, stats.cached_fragments), (4, 2)); + assert_eq!(observation.loaded.load(Ordering::Relaxed), 3); + assert_eq!( + cache + .known_file_size(&1, std::slice::from_ref(&(8..9))) + .await, + Some(10) + ); + assert_eq!(*reader.reads.lock().unwrap(), vec![0..4, 4..8, 8..10]); + cache.run_pending_tasks().await; + assert_eq!(observation.bytes(), 10); + cache.invalidate_if(|file| *file == 1).unwrap(); + cache.run_pending_tasks().await; + assert!(!cache.contains(&1, 0).await); + assert_eq!(observation.bytes(), 0); + // Returned values remain valid after invalidation, while cache accounting is released. + assert_eq!(&second[0][..], &[6, 7, 8, 9]); +} + +#[tokio::test] +async fn test_overlapping_fetches_share_pages_and_only_read_missing_bytes() { + let (cache, observation) = cache(); + let reader = Reader::gated(); + let first_range = 0..8; + let first_ranges = std::slice::from_ref(&first_range); + let second_range = 4..12; + let second_ranges = std::slice::from_ref(&second_range); + let mut first = Box::pin(cache.fetch(1, 16, first_ranges, &reader)); + start_read(first.as_mut(), &reader, 2).await; + let mut second = Box::pin(cache.fetch(1, 16, second_ranges, &reader)); + start_read(second.as_mut(), &reader, 3).await; + reader.release(); + let (first, second) = tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(first, second) + }) + .await + .unwrap(); + assert_eq!(&first.unwrap().0[0][..], &(0..8).collect::>()); + assert_eq!(&second.unwrap().0[0][..], &(4..12).collect::>()); + assert_eq!(*reader.reads.lock().unwrap(), vec![0..4, 4..8, 8..12]); + assert_eq!(observation.loaded.load(Ordering::Relaxed), 3); +} + +#[tokio::test] +async fn test_cancelling_owner_allows_waiter_to_finish() { + let (cache, observation) = cache(); + let reader = Reader::gated(); + let range = 0..4; + let ranges = std::slice::from_ref(&range); + let mut owner = Box::pin(cache.fetch(1, 16, ranges, &reader)); + start_read(owner.as_mut(), &reader, 1).await; + let mut waiter = Box::pin(cache.fetch(1, 16, ranges, &reader)); + assert!(futures::poll!(&mut waiter).is_pending()); + assert_eq!(reader.count(), 1); + drop(owner); + reader.release(); + let result = tokio::time::timeout(Duration::from_secs(5), waiter) + .await + .unwrap() + .unwrap(); + assert_eq!(&result.0[0][..], &[0, 1, 2, 3]); + assert_eq!(reader.count(), 2); + assert_eq!(observation.loaded.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn test_cancelling_waiter_does_not_cancel_owner() { + let (cache, _) = cache(); + let reader = Reader::gated(); + let range = 0..4; + let ranges = std::slice::from_ref(&range); + let mut owner = Box::pin(cache.fetch(1, 16, ranges, &reader)); + start_read(owner.as_mut(), &reader, 1).await; + let mut waiter = Box::pin(cache.fetch(1, 16, ranges, &reader)); + assert!(futures::poll!(&mut waiter).is_pending()); + drop(waiter); + reader.release(); + let result = tokio::time::timeout(Duration::from_secs(5), owner) + .await + .unwrap() + .unwrap(); + assert_eq!(&result.0[0][..], &[0, 1, 2, 3]); + assert_eq!(reader.count(), 1); +} + +#[tokio::test] +async fn test_backend_error_is_shared_and_not_cached() { + let (cache, observation) = cache(); + let reader = Reader { + error: Some(io::ErrorKind::BrokenPipe), + ..Reader::gated() + }; + let range = 0..4; + let ranges = std::slice::from_ref(&range); + let mut owner = Box::pin(cache.fetch(1, 16, ranges, &reader)); + start_read(owner.as_mut(), &reader, 1).await; + let mut waiter = Box::pin(cache.fetch(1, 16, ranges, &reader)); + assert!(futures::poll!(&mut waiter).is_pending()); + reader.release(); + let (owner, waiter) = tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(owner, waiter) + }) + .await + .unwrap(); + for result in [owner, waiter] { + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::BrokenPipe); + assert!(error.to_string().contains("backend failed")); + } + assert_eq!(reader.count(), 1); + assert_eq!(observation.loaded.load(Ordering::Relaxed), 0); + // The failed load was not cached. + let healthy = Reader::default(); + assert!(cache.fetch(1, 16, ranges, &healthy).await.is_ok()); + assert_eq!(healthy.count(), 1); +} + +#[tokio::test] +async fn test_completed_page_rejects_conflicting_file_size() { + let (cache, _) = cache(); + let reader = Reader::default(); + let range = 0..4; + let ranges = std::slice::from_ref(&range); + cache.fetch(1, 16, ranges, &reader).await.unwrap(); + assert!(cache.fetch(1, 12, ranges, &reader).await.is_err()); + assert_eq!(reader.count(), 1); + // A different identity remains independent. + assert!(cache.fetch(2, 12, ranges, &reader).await.is_ok()); +} + +#[tokio::test] +async fn test_shared_load_rejects_conflicting_file_size() { + let (cache, _) = cache(); + let reader = Reader::gated(); + let range = 0..4; + let ranges = std::slice::from_ref(&range); + let mut owner = Box::pin(cache.fetch(1, 16, ranges, &reader)); + start_read(owner.as_mut(), &reader, 1).await; + let mut conflicting = Box::pin(cache.fetch(1, 12, ranges, &reader)); + assert!(futures::poll!(&mut conflicting).is_pending()); + reader.release(); + let (owner, conflicting) = tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(owner, conflicting) + }) + .await + .unwrap(); + assert!(owner.is_ok()); + assert!(conflicting.is_err()); + assert_eq!(reader.count(), 1); +} + +#[tokio::test] +async fn test_empty_and_invalid_requests_do_not_issue_reads() { + let (cache, _) = cache(); + let reader = Reader::default(); + assert!(cache.fetch(1, 0, &[], &reader).await.unwrap().0.is_empty()); + assert_eq!( + cache.fetch(1, 0, &[0..0, 0..0], &reader).await.unwrap().0, + vec![Bytes::new(), Bytes::new()] + ); + for ranges in [vec![Range { start: 2, end: 1 }], vec![0..17, 0..0]] { + assert!(cache.fetch(1, 16, &ranges, &reader).await.is_err()); + } + assert_eq!(reader.count(), 0); +} + +// Keep the Send contract visible before a caller erases this future in async-trait. +fn send_fetch<'a, K, R>( + cache: &'a PagedCache, + file: K, + ranges: &'a [Range], + reader: &'a R, +) -> impl Future, PageFetchStats), Arc>> + Send + 'a +where + K: Hash + Eq + Clone + Send + Sync + 'static, + R: RangeReader + ?Sized, +{ + cache.fetch(file, 16, ranges, reader) +} + +#[tokio::test] +async fn test_generic_page_fetch_has_a_send_future() { + let (cache, _) = cache(); + let reader = Reader::default(); + let range = 1..7; + let ranges = std::slice::from_ref(&range); + let future: futures::future::BoxFuture<'_, _> = + Box::pin(send_fetch(&cache, 1, ranges, &reader)); + let (bytes, _) = future.await.unwrap(); + assert_eq!(bytes, vec![Bytes::from_static(&[1, 2, 3, 4, 5, 6])]); +} + +#[tokio::test] +async fn test_direct_page_rejects_wrong_lengths_without_caching() { + struct FixedReader(usize); + #[async_trait] + impl RangeReader for FixedReader { + async fn metadata(&self) -> io::Result { + unreachable!("fetch already has the immutable file size") + } + async fn read(&self, _: Range) -> io::Result { + Ok(Bytes::from(vec![7; self.0])) + } + } + for response_size in [3, 5] { + let (cache, observation) = cache(); + let range = 0..4; + let ranges = std::slice::from_ref(&range); + let error = cache + .fetch(1, 8, ranges, &FixedReader(response_size)) + .await + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); + assert_eq!(observation.loaded.load(Ordering::Relaxed), 0); + assert!(!cache.contains(&1, 0).await); + let reader = Reader::default(); + assert!(cache.fetch(1, 8, ranges, &reader).await.is_ok()); + assert_eq!(reader.count(), 1); + } +} + +#[tokio::test] +async fn test_direct_page_detaches_shared_backing_buffer() { + struct SliceReader(Bytes); + #[async_trait] + impl RangeReader for SliceReader { + async fn metadata(&self) -> io::Result { + unreachable!("fetch already has the immutable file size") + } + async fn read(&self, range: Range) -> io::Result { + Ok(self.0.slice(range.start as usize..range.end as usize)) + } + } + let (cache, observation) = cache(); + let reader = SliceReader(Bytes::from(vec![7; 1024])); + let range = 0..4; + let (output, _) = cache + .fetch(1, 1024, std::slice::from_ref(&range), &reader) + .await + .unwrap(); + assert_eq!(output[0].as_ref(), [7; 4]); + assert_ne!(output[0].as_ptr(), reader.0.as_ptr()); + cache.run_pending_tasks().await; + assert_eq!(observation.bytes(), 4); +} + +#[tokio::test] +async fn test_direct_page_larger_than_eight_mib_is_not_split() { + let (base, _) = cache(); + let page_size = 9 * 1024 * 1024; + let cache = PagedCache::new( + "large_pages", + page_size * 2, + page_size, + |_: &(u64, u64), bytes: &Bytes| bytes.len() as u32, + base.observer.clone(), + ); + let reader = Reader::default(); + let range = 0..1; + let (output, _) = cache + .fetch(1, page_size, std::slice::from_ref(&range), &reader) + .await + .unwrap(); + assert_eq!(output[0].as_ref(), [0]); + assert_eq!( + reader.reads.lock().unwrap().as_slice(), + std::slice::from_ref(&(0..page_size)) + ); +} + +#[test] +fn test_unique_requested_bytes() { + for (ranges, expected) in [ + (vec![], 0), + (vec![4..4, 0..0], 0), + (vec![8..12, 2..6, 4..10, 2..6], 10), + (vec![0..4, 4..8, 12..16], 12), + (vec![0..u64::MAX, 1..2], u64::MAX), + ] { + assert_eq!(unique_requested_bytes(&ranges), expected); + } +} + +#[tokio::test] +async fn test_missing_pages_use_batch_reads() { + let (cache, _) = cache(); + let reader = Reader::default(); + let range = 0..512; + let ranges = std::slice::from_ref(&range); + let (bytes, _) = cache.fetch(1, 512, ranges, &reader).await.unwrap(); + assert_eq!( + bytes[0], + Bytes::from((0..512).map(|n| n as u8).collect::>()) + ); + assert_eq!( + *reader.batches.lock().unwrap(), + vec![(0..128).map(|n| n * 4..n * 4 + 4).collect::>()] + ); + cache.fetch(1, 512, ranges, &reader).await.unwrap(); + assert_eq!(reader.batches.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn test_shared_error_cancels_other_pending_batch() { + let (cache, _) = cache(); + let failed = Reader { + error: Some(io::ErrorKind::BrokenPipe), + ..Reader::gated() + }; + let blocked = Reader::gated(); + let owner_range = 0..4; + let waiter_range = 0..8; + let mut owner = Box::pin(cache.fetch(1, 16, std::slice::from_ref(&owner_range), &failed)); + start_read(owner.as_mut(), &failed, 1).await; + let mut waiter = Box::pin(cache.fetch(1, 16, std::slice::from_ref(&waiter_range), &blocked)); + start_read(waiter.as_mut(), &blocked, 1).await; + failed.release(); + assert_eq!(owner.await.unwrap_err().kind(), io::ErrorKind::BrokenPipe); + // The unrelated page stays blocked; the shared error must cancel its I/O. + let error = tokio::time::timeout(Duration::from_secs(5), waiter) + .await + .unwrap() + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::BrokenPipe); + let healthy = Reader::default(); + assert!( + cache + .fetch(1, 16, std::slice::from_ref(&waiter_range), &healthy) + .await + .is_ok() + ); +} From 045cf74c3f41e29d63b52c7e708b5f023fe2e039 Mon Sep 17 00:00:00 2001 From: "Lei, HUANG" <6406592+v0y4g3r@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:09:26 +0000 Subject: [PATCH 15/19] perf(mito2): pipeline compaction and parallelize decoding and encoding (#9945) * perf(mito2): merge compaction inputs on a separate task Compaction read, merged and encoded each output on a single task, so parquet encoding waited for the merge and the merge waited for encoding. The merge now runs on its own compaction runtime task and hands merged batches to the SST writer through a bounded channel. The channel also closes when that task panics, so the reading side awaits the task before reporting the end of the input. A panic fails the compaction instead of producing a truncated SST. One output of 4.8M rows took 1.28s instead of 1.65s. Signed-off-by: Lei, HUANG * perf(mito2): parallelize decoding and encoding of compaction outputs Parquet encoding took about two thirds of a compaction output's time and ran on a single thread. When `experimental_compaction_output_parallelism` is above 1, the SST writer encodes the columns of each row group on up to that many blocking threads of the compaction runtime while the next row group is buffered, and the merge decodes up to that many input files ahead of it on compaction runtime tasks. The parallel writer feeds every column writer the same input as `ArrowWriter`, so the SSTs are byte-identical. The bytes of a row group reach the object store writer one row group later, so `max_file_size` may split a file one row group later. The option defaults to 1, which keeps today's CPU usage. One output of 4.8M rows took 0.44s with 4 and 0.38s with 8, against 1.28s with 1. Signed-off-by: Lei, HUANG * fix(mito2): cancel compaction producers before consumer polling Signed-off-by: Lei, HUANG * feat(mito2): support per-table compaction output parallelism Signed-off-by: Lei, HUANG * fix(mito2): drain encoding tasks before returning failures Abort remaining queued encoding tasks and await running tasks before propagating the first error, keeping row-group work inside the caller's compaction memory budget lifetime. Add deterministic error and panic tests for queued cancellation, running-task cleanup, budget retention, and original error preservation. Signed-off-by: Lei, HUANG * fix(mito2): drain encoders on SST write errors Add asynchronous abort cleanup to both SST write entry points so source errors cannot detach in-flight encoding work after its compaction memory budget is released. Share encoder task cleanup with the encoding-failure path and preserve the original write error. Cover source-read failures in flat and primary-key writers with deterministic running and queued tasks. Signed-off-by: Lei, HUANG * fix(mito2): drain compaction outputs on cancellation Stop scheduling new output batches on cancellation instead of aborting active writers. Await started outputs and retain successful SSTs, draining sibling tasks before propagating join failures. Add deterministic cancellation regressions covering blocking encoder lifetime, budget retention, output ownership, join failures, and cancellation before work starts. Signed-off-by: Lei, HUANG --------- Signed-off-by: Lei, HUANG --- config/config.md | 2 + config/datanode.example.toml | 7 + config/standalone.example.toml | 7 + .../src/bin/query_perf_fixture/direct_sst.rs | 1 + src/mito2/src/compaction/compactor.rs | 307 ++++++--- src/mito2/src/compaction/reader.rs | 16 + src/mito2/src/compaction/window.rs | 1 + src/mito2/src/config.rs | 5 + src/mito2/src/engine/alter_test.rs | 65 ++ src/mito2/src/engine/compaction_test.rs | 31 +- src/mito2/src/read.rs | 8 + src/mito2/src/read/scan_region.rs | 11 + src/mito2/src/read/seq_scan.rs | 24 +- src/mito2/src/read/stream.rs | 275 +++++++- src/mito2/src/region/options.rs | 65 ++ src/mito2/src/sst/parquet.rs | 60 +- src/mito2/src/sst/parquet/parallel_writer.rs | 648 ++++++++++++++++++ src/mito2/src/sst/parquet/writer.rs | 230 ++++++- src/mito2/src/worker/handle_alter.rs | 6 + src/store-api/src/mito_engine_options.rs | 7 + src/store-api/src/region_request.rs | 73 +- src/table/src/metadata.rs | 68 +- tests-integration/tests/http.rs | 1 + .../compaction_output_parallelism.result | 140 ++++ .../alter/compaction_output_parallelism.sql | 35 + .../compaction_output_parallelism/case.toml | 8 + .../compaction_output_parallelism/setup.sql | 7 + .../verify.result | 90 +++ .../compaction_output_parallelism/verify.sql | 15 + 29 files changed, 2072 insertions(+), 141 deletions(-) create mode 100644 src/mito2/src/sst/parquet/parallel_writer.rs create mode 100644 tests/cases/standalone/common/alter/compaction_output_parallelism.result create mode 100644 tests/cases/standalone/common/alter/compaction_output_parallelism.sql create mode 100644 tests/compatibility/cases/compaction_output_parallelism/case.toml create mode 100644 tests/compatibility/cases/compaction_output_parallelism/setup.sql create mode 100644 tests/compatibility/cases/compaction_output_parallelism/verify.result create mode 100644 tests/compatibility/cases/compaction_output_parallelism/verify.sql diff --git a/config/config.md b/config/config.md index 15cd4915f9d..711fe019a19 100644 --- a/config/config.md +++ b/config/config.md @@ -193,6 +193,7 @@ | `region_engine.mito.max_background_purges` | Integer | Auto | Max number of running background purge jobs (default: number of cpu cores). | | `region_engine.mito.experimental_compaction_memory_limit` | String | 0 | Memory budget for compaction tasks.
Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").
Setting it to 0 or "unlimited" disables the limit. | | `region_engine.mito.experimental_compaction_on_exhausted` | String | wait | Behavior when compaction cannot acquire memory from the budget.
Options: "wait" (default, 10s), "wait()", "fail" | +| `region_engine.mito.experimental_compaction_output_parallelism` | Integer | 1 | Default per-output parallelism for input decoding and SST column encoding.
Each stage is bounded independently; this is not a global thread limit.
Values below 2 disable parallel decoding/encoding, but not the merge pipeline.
Tables can override it with 'compaction.experimental_output_parallelism' (positive integer). | | `region_engine.mito.auto_flush_interval` | String | `10m` | Interval to auto flush a region if it has not flushed yet. | | `region_engine.mito.global_write_buffer_size` | String | Auto | Global write buffer size for all regions. If not set, it's default to 1/8 of OS memory with a max limitation of 1GB. | | `region_engine.mito.global_write_buffer_reject_size` | String | Auto | Global write buffer size threshold to reject write requests. If not set, it's default to 2 times of `global_write_buffer_size`. | @@ -672,6 +673,7 @@ | `region_engine.mito.max_background_purges` | Integer | Auto | Max number of running background purge jobs (default: number of cpu cores). | | `region_engine.mito.experimental_compaction_memory_limit` | String | 0 | Memory budget for compaction tasks.
Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").
Setting it to 0 or "unlimited" disables the limit. | | `region_engine.mito.experimental_compaction_on_exhausted` | String | wait | Behavior when compaction cannot acquire memory from the budget.
Options: "wait" (default, 10s), "wait()", "fail" | +| `region_engine.mito.experimental_compaction_output_parallelism` | Integer | 1 | Default per-output parallelism for input decoding and SST column encoding.
Each stage is bounded independently; this is not a global thread limit.
Values below 2 disable parallel decoding/encoding, but not the merge pipeline.
Tables can override it with 'compaction.experimental_output_parallelism' (positive integer). | | `region_engine.mito.auto_flush_interval` | String | `10m` | Interval to auto flush a region if it has not flushed yet. | | `region_engine.mito.global_write_buffer_size` | String | Auto | Global write buffer size for all regions. If not set, it's default to 1/8 of OS memory with a max limitation of 1GB. | | `region_engine.mito.global_write_buffer_reject_size` | String | Auto | Global write buffer size threshold to reject write requests. If not set, it's default to 2 times of `global_write_buffer_size` | diff --git a/config/datanode.example.toml b/config/datanode.example.toml index acc65582e81..a2457302a10 100644 --- a/config/datanode.example.toml +++ b/config/datanode.example.toml @@ -590,6 +590,13 @@ compress_manifest = false ## @toml2docs:none-default="wait" #+ experimental_compaction_on_exhausted = "wait" +## Default per-output parallelism for input decoding and SST column encoding. +## Each stage is bounded independently; this is not a global thread limit. +## Values below 2 disable parallel decoding/encoding, but not the merge pipeline. +## Tables can override it with 'compaction.experimental_output_parallelism' (positive integer). +## @toml2docs:none-default="1" +#+ experimental_compaction_output_parallelism = 1 + ## Interval to auto flush a region if it has not flushed yet. auto_flush_interval = "10m" diff --git a/config/standalone.example.toml b/config/standalone.example.toml index 5cfbb95729e..d047952538c 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -805,6 +805,13 @@ compress_manifest = false ## @toml2docs:none-default="wait" #+ experimental_compaction_on_exhausted = "wait" +## Default per-output parallelism for input decoding and SST column encoding. +## Each stage is bounded independently; this is not a global thread limit. +## Values below 2 disable parallel decoding/encoding, but not the merge pipeline. +## Tables can override it with 'compaction.experimental_output_parallelism' (positive integer). +## @toml2docs:none-default="1" +#+ experimental_compaction_output_parallelism = 1 + ## Interval to auto flush a region if it has not flushed yet. auto_flush_interval = "10m" diff --git a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs index 27a6b4109cd..0b09d1634ca 100644 --- a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs +++ b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs @@ -470,6 +470,7 @@ pub(super) async fn run_direct_sst(args: DirectArgs) { row_group_size: scenario.layout.row_group_size, max_file_size: None, float_field_encoding: Default::default(), + ..Default::default() }; let infos = match format { FormatType::Flat => writer.write_all_flat(source, Some(sequence), &opts).await, diff --git a/src/mito2/src/compaction/compactor.rs b/src/mito2/src/compaction/compactor.rs index 527750bf33e..1673721ec9b 100644 --- a/src/mito2/src/compaction/compactor.rs +++ b/src/mito2/src/compaction/compactor.rs @@ -17,9 +17,9 @@ use std::sync::Arc; use std::time::Duration; use common_base::Plugins; -use common_base::cancellation::{CancellableFuture, CancellationHandle}; +use common_base::cancellation::CancellationHandle; use common_meta::key::SchemaMetadataManagerRef; -use common_telemetry::{debug, info, warn}; +use common_telemetry::{info, warn}; use common_time::TimeToLive; use either::Either; use itertools::Itertools; @@ -37,7 +37,7 @@ use crate::access_layer::{ }; use crate::cache::{CacheManager, CacheManagerRef}; use crate::compaction::picker::PickerOutput; -use crate::compaction::reader::CompactionSstReaderBuilder; +use crate::compaction::reader::{CompactionSstReaderBuilder, spawn_merge}; use crate::compaction::unit::CompactionUnit; use crate::compaction::{CompactionOutput, find_dynamic_options}; use crate::config::MitoConfig; @@ -59,6 +59,7 @@ use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::PuffinManagerFactory; use crate::sst::location::region_dir_from_table_dir; use crate::sst::parquet::metadata::extract_primary_key_range; +use crate::sst::parquet::parallel_writer::EncodeRuntime; use crate::sst::parquet::{SstInfo, WriteOptions}; use crate::sst::version::{SstVersion, SstVersionRef}; @@ -590,8 +591,9 @@ impl SstMerger for DefaultSstMerger { filter_deleted: output.filter_deleted, time_range: output.output_time_range, merge_mode, + read_parallelism: write_opts.encode_parallelism, }; - let source = builder.build_flat_sst_reader().await?; + let source = spawn_merge(builder.build_flat_sst_reader().await?); let mut metrics = Metrics::new(WriteType::Compaction); let region_metadata = context.region_metadata.clone(); @@ -705,6 +707,10 @@ impl DefaultCompactor { /// /// This is the public entry point for external crates that want a /// cancellable compactor without opting into uncommitted-SST tracking. + /// + /// Cancellation stops new output batches. Already spawned outputs finish, + /// and their successful SSTs remain in the returned [`MergeOutput`]. This + /// can delay cancellation until the current batch completes. pub fn new_with_cancel_handle(cancel_handle: Arc) -> Self { Self { merger: DefaultSstMerger, @@ -753,6 +759,14 @@ impl DefaultCompactor { max_file_size: unit.max_file_size, row_group_size: context.region_options.row_group_size(), float_field_encoding: context.region_options.float_field_encoding, + encode_parallelism: context + .region_options + .compaction_output_parallelism_or( + context + .engine_config + .experimental_compaction_output_parallelism, + ), + encode_runtime: EncodeRuntime::Compact, }, ) .await?; @@ -796,6 +810,14 @@ where max_file_size: picker_output.max_file_size, row_group_size: compaction_region.region_options.row_group_size(), float_field_encoding: compaction_region.region_options.float_field_encoding, + encode_parallelism: compaction_region + .region_options + .compaction_output_parallelism_or( + compaction_region + .engine_config + .experimental_compaction_output_parallelism, + ), + encode_runtime: EncodeRuntime::Compact, }; let merger = self.merger.clone(); let context = context.clone(); @@ -820,7 +842,7 @@ where + picker_output.expired_ssts.len(), ); - while !tasks.is_empty() { + while !tasks.is_empty() && !self.cancel_handle.is_cancelled() { let mut chunk: Vec<(Vec, _)> = Vec::with_capacity(internal_parallelism); for _ in 0..internal_parallelism { if let Some(task) = tasks.pop() { @@ -835,61 +857,41 @@ where }) .collect(); - while let Some((inputs, mut handle)) = spawned.pop() { - let abort_handle = handle.abort_handle(); - match CancellableFuture::new(&mut handle, self.cancel_handle.clone()).await { - Ok(Ok(Ok((files, infos)))) => { + // Like merge_unit, cancellation must not drop a writer mid-output: + // its blocking encoders would detach and finalized SSTs could lose + // their owner. Join the whole batch and retain every successful output. + let mut join_error = None; + while let Some((inputs, handle)) = spawned.pop() { + match handle.await { + Ok(Ok((files, infos))) => { output_files.extend(files); if hook.is_some() { all_sst_infos.extend(infos); } compacted_inputs.extend(inputs); } - Ok(Ok(Err(e))) => { + Ok(Err(e)) => { warn!( e; "Failed to merge compaction output for region: {}, inputs: [{}]", region_id, inputs.iter().map(|f| f.file_id.to_string()).join(",") ); } - Ok(Err(e)) => { + Err(e) => { warn!( - "Region {} compaction task join error for inputs: [{}], skipping: {}", + "Region {} compaction task join error for inputs: [{}]: {}", region_id, inputs.iter().map(|f| f.file_id.to_string()).join(","), e ); - // If the cancel handle is cancelled, - // cancel the remaining tasks before returns the error. - if self.cancel_handle.is_cancelled() { - abort_handle.abort(); - for (_, handle) in &spawned { - handle.abort(); - } - for (_, handle) in spawned { - let _ = handle.await; - } - } - return Err(e).context(error::JoinSnafu); - } - Err(_) => { - debug!( - "Compaction merge cancelled for region: {}, aborting remaining {} spawned tasks", - region_id, - spawned.len(), - ); - abort_handle.abort(); - for (_, handle) in &spawned { - handle.abort(); - } - let _ = handle.await; - for (_, handle) in spawned { - let _ = handle.await; - } - break; + // Drain siblings before propagating the first join error. + join_error.get_or_insert(e); } } } + if let Some(e) = join_error { + return Err(e).context(error::JoinSnafu); + } if self.cancel_handle.is_cancelled() { info!("Compaction merge cancelled for region: {}", region_id); @@ -927,17 +929,22 @@ where #[cfg(test)] mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::{Arc, Mutex}; + use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; + use datatypes::arrow::record_batch::RecordBatch; + use parquet::arrow::ArrowWriter; use store_api::storage::{FileId, RegionId}; - use tokio::time::sleep; + use tokio::sync::{mpsc, oneshot}; + use tokio::time::timeout; use super::{DefaultCompactor, *}; + use crate::compaction::memory_manager::new_compaction_memory_manager; use crate::compaction::picker::PickerOutput; use crate::error::Result; use crate::sst::file::FileHandle; use crate::sst::file_purger::NoopFilePurger; + use crate::test_util::sst_util::new_record_batch_by_range; fn dummy_file_meta() -> FileMeta { FileMeta { @@ -1244,6 +1251,7 @@ mod tests { filter_deleted: true, time_range: None, merge_mode: MergeMode::LastRow, + read_parallelism: 1, } .build_flat_sst_reader() .await @@ -1503,85 +1511,182 @@ mod tests { ); } + #[derive(Debug)] + struct PendingEncoding { + input_id: FileId, + output_id: FileId, + batch: Weak, + release: oneshot::Sender<()>, + } + + /// A merger with real blocking Parquet encoding and deterministic lifetime gates. #[derive(Clone)] - struct BlockingMerger { - call_idx: Arc, + struct GatedEncodingMerger { + started: mpsc::UnboundedSender, + panic_input: Option, } #[async_trait::async_trait] - impl SstMerger for BlockingMerger { + impl SstMerger for GatedEncodingMerger { async fn merge_single_output( &self, _context: CompactionContext, - _output: CompactionOutput, + output: CompactionOutput, _write_opts: WriteOptions, ) -> Result<(Vec, Vec)> { - self.call_idx.fetch_add(1, Ordering::SeqCst); - std::future::pending().await + let input_id = output.inputs[0].meta_ref().file_id; + let mut file = dummy_file_meta(); + let batch = Arc::new(new_record_batch_by_range(&["a", "b"], 0, 4)); + let (release, wait) = oneshot::channel(); + let pending = PendingEncoding { + input_id, + output_id: file.file_id, + batch: Arc::downgrade(&batch), + release, + }; + let started = self.started.clone(); + file.file_size = common_runtime::spawn_blocking_compact(move || { + started.send(pending).unwrap(); + wait.blocking_recv().unwrap(); + let mut bytes = Vec::new(); + let mut writer = ArrowWriter::try_new(&mut bytes, batch.schema(), None)?; + writer.write(&batch)?; + writer.close()?; + Ok::<_, parquet::errors::ParquetError>(bytes.len() as u64) + }) + .await + .context(error::JoinSnafu)? + .context(error::WriteParquetSnafu)?; + if self.panic_input == Some(input_id) { + panic!("merge task panicked"); + } + Ok((vec![file], Vec::new())) } } - #[tokio::test(flavor = "multi_thread")] - async fn test_merge_ssts_cancels_spawned_tasks() { - common_telemetry::init_default_ut_logging(); - - let mut compaction_region = new_test_compaction_region().await; - compaction_region.max_parallelism = 2; - + #[rstest::rstest] + #[case::successful_outputs(false)] + #[case::join_error(true)] + #[tokio::test] + async fn test_merge_ssts_cancellation_waits_for_encoders(#[case] panic_merge: bool) { + let mut region = new_test_compaction_region().await; + region.max_parallelism = 2; + region.region_options.compaction_output_parallelism = Some(2); + let inputs: Vec<_> = (0..3).map(|_| dummy_file_meta()).collect(); + let picker_output = PickerOutput { + outputs: inputs + .iter() + .map(|input| CompactionOutput { + output_level: 1, + inputs: vec![new_file_handle(input.clone())], + filter_deleted: false, + output_time_range: None, + }) + .collect(), + ..Default::default() + }; let cancel_handle = Arc::new(CancellationHandle::default()); - let call_idx = Arc::new(AtomicUsize::new(0)); + let (started_tx, mut started_rx) = mpsc::unbounded_channel(); let compactor = DefaultCompactor { - merger: BlockingMerger { - call_idx: call_idx.clone(), + merger: GatedEncodingMerger { + started: started_tx, + // Outputs are popped from the back, then joined in reverse order. + panic_input: panic_merge.then_some(inputs[1].file_id), }, cancel_handle: cancel_handle.clone(), uncommitted: None, }; - - let picker_output = PickerOutput { - outputs: vec![ - CompactionOutput { - output_level: 1, - inputs: vec![new_file_handle(dummy_file_meta())], - filter_deleted: false, - output_time_range: None, - }, - CompactionOutput { - output_level: 1, - inputs: vec![new_file_handle(dummy_file_meta())], - filter_deleted: false, - output_time_range: None, - }, - CompactionOutput { - output_level: 1, - inputs: vec![new_file_handle(dummy_file_meta())], - filter_deleted: false, - output_time_range: None, - }, - ], - expired_ssts: vec![], - time_window_size: 3600, - max_file_size: None, - }; - - let task = tokio::spawn(async move { - compactor - .merge_ssts(&compaction_region, picker_output) - .await + let memory = new_compaction_memory_manager(1024 * 1024); + let budget = memory.try_acquire(memory.limit_bytes()).unwrap(); + let mut merge = Box::pin(async { + let _budget = budget; + compactor.merge_ssts(®ion, picker_output).await }); - - sleep(Duration::from_millis(100)).await; + assert!(futures::poll!(merge.as_mut()).is_pending()); + let mut encoders = Vec::new(); + for _ in 0..2 { + encoders.push( + timeout(Duration::from_secs(10), started_rx.recv()) + .await + .unwrap() + .unwrap(), + ); + } cancel_handle.cancel(); + assert!(futures::poll!(merge.as_mut()).is_pending()); + assert!(memory.try_acquire(memory.limit_bytes()).is_none()); + assert!( + encoders + .iter() + .all(|encoder| encoder.batch.upgrade().is_some()) + ); + let retained_batches: Vec<_> = encoders + .iter() + .map(|encoder| encoder.batch.clone()) + .collect(); + let mut expected_inputs: Vec<_> = encoders.iter().map(|encoder| encoder.input_id).collect(); + let mut expected_outputs: Vec<_> = + encoders.iter().map(|encoder| encoder.output_id).collect(); + for encoder in encoders { + encoder.release.send(()).unwrap(); + } + let result = timeout(Duration::from_secs(10), merge).await.unwrap(); + assert!( + retained_batches + .iter() + .all(|batch| batch.upgrade().is_none()) + ); + assert!(memory.try_acquire(memory.limit_bytes()).is_some()); + assert!( + started_rx.try_recv().is_err(), + "cancelled work must not start another output" + ); + if panic_merge { + assert!(matches!(result, Err(error::Error::Join { error, .. }) if error.is_panic())); + } else { + let merged = result.unwrap(); + let mut removed: Vec<_> = merged + .files_to_remove + .iter() + .map(|file| file.file_id) + .collect(); + let mut added: Vec<_> = merged + .files_to_add + .iter() + .map(|file| file.file_id) + .collect(); + for ids in [ + &mut removed, + &mut added, + &mut expected_inputs, + &mut expected_outputs, + ] { + ids.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + } + assert_eq!(expected_inputs, removed); + assert_eq!(expected_outputs, added); + assert!(merged.files_to_add.iter().all(|file| file.file_size > 0)); + } + } - let merge_output = task - .await - .expect("merge_ssts should stop after cancellation") - .unwrap(); - - let started = call_idx.load(Ordering::SeqCst); - - assert!(merge_output.files_to_add.is_empty()); - assert!(merge_output.files_to_remove.is_empty()); - assert_eq!(started, 2); + #[tokio::test] + async fn test_merge_ssts_cancelled_before_start_skips_outputs() { + let region = new_test_compaction_region().await; + let merger = MockMerger::new(vec![Ok(vec![dummy_file_meta()])]); + let calls = merger.call_idx.clone(); + let compactor = DefaultCompactor::with_merger(merger); + compactor.cancel_handle.cancel(); + let picker_output = PickerOutput { + outputs: vec![CompactionOutput { + output_level: 1, + inputs: vec![new_file_handle(dummy_file_meta())], + filter_deleted: false, + output_time_range: None, + }], + ..Default::default() + }; + let merged = compactor.merge_ssts(®ion, picker_output).await.unwrap(); + assert!(merged.is_empty()); + assert_eq!(0, calls.load(Ordering::SeqCst)); } } diff --git a/src/mito2/src/compaction/reader.rs b/src/mito2/src/compaction/reader.rs index 159ebe2f22a..0968f0e7a60 100644 --- a/src/mito2/src/compaction/reader.rs +++ b/src/mito2/src/compaction/reader.rs @@ -36,6 +36,7 @@ use crate::read::flat_projection::FlatProjectionMapper; use crate::read::read_columns::ReadColumns; use crate::read::scan_region::{PredicateGroup, ScanInput}; use crate::read::seq_scan::SeqScan; +use crate::read::stream::spawn_compact_stream; use crate::region::options::MergeMode; use crate::sst::file::FileHandle; use crate::sst::parquet::reader::MetadataCacheMetrics; @@ -51,6 +52,8 @@ pub(crate) struct CompactionSstReaderBuilder<'a> { pub(crate) filter_deleted: bool, pub(crate) time_range: Option, pub(crate) merge_mode: MergeMode, + /// Max number of inputs decoded concurrently ahead of the merge. + pub(crate) read_parallelism: usize, } impl CompactionSstReaderBuilder<'_> { @@ -131,6 +134,7 @@ impl CompactionSstReaderBuilder<'_> { .with_json2_rewrite_targets(targets) .with_files(self.inputs.to_vec()) .with_compaction(true) + .with_compaction_read_parallelism(self.read_parallelism) .with_batch_size(batch_size) .with_append_mode(self.append_mode) // We use special cache strategy for compaction. @@ -180,6 +184,17 @@ impl CompactionSstReaderBuilder<'_> { } } +/// Number of merged batches buffered between the merge task and the SST writer. +const MERGED_BATCH_CHANNEL_SIZE: usize = 2; + +/// Reads and merges `source` on a separate task, so the SST writer can encode +/// merged batches while the next ones are being read and merged. +pub(crate) fn spawn_merge(source: FlatSource) -> FlatSource { + let schema = source.schema().clone(); + let stream = spawn_compact_stream(source.into_stream(), MERGED_BATCH_CHANNEL_SIZE, None); + FlatSource::new_stream(schema, stream) +} + /// Converts time range to predicates so that rows outside the range will be filtered. fn time_range_to_predicate( range: TimestampRange, @@ -304,6 +319,7 @@ mod tests { filter_deleted: true, time_range: None, merge_mode: MergeMode::LastRow, + read_parallelism: 1, } .build_flat_sst_reader() .await diff --git a/src/mito2/src/compaction/window.rs b/src/mito2/src/compaction/window.rs index ab7ac0a5f9a..b2c4ceaa12a 100644 --- a/src/mito2/src/compaction/window.rs +++ b/src/mito2/src/compaction/window.rs @@ -356,6 +356,7 @@ mod tests { auto_flush_interval: None, compaction: Default::default(), compaction_override: false, + compaction_output_parallelism: None, storage: None, append_mode: false, skip_wal: false, diff --git a/src/mito2/src/config.rs b/src/mito2/src/config.rs index 98b4ba4be42..67df74d7160 100644 --- a/src/mito2/src/config.rs +++ b/src/mito2/src/config.rs @@ -129,6 +129,10 @@ pub struct MitoConfig { pub experimental_compaction_memory_limit: MemoryLimit, /// Behavior when compaction cannot acquire memory from the budget. pub experimental_compaction_on_exhausted: OnExhaustedPolicy, + /// Default per-output parallelism for input decoding and SST column encoding, + /// bounded independently per stage. Values below 2 disable both. + /// Tables can override it with `compaction.experimental_output_parallelism`. + pub experimental_compaction_output_parallelism: usize, // Flush configs: /// Interval to auto flush a region if it has not flushed yet (default 10 min). @@ -247,6 +251,7 @@ impl Default for MitoConfig { max_background_purges: get_total_cpu_cores(), experimental_compaction_memory_limit: MemoryLimit::Unlimited, experimental_compaction_on_exhausted: OnExhaustedPolicy::default(), + experimental_compaction_output_parallelism: 1, auto_flush_interval: Duration::from_secs(10 * 60), global_write_buffer_size: ReadableSize::gb(1), global_write_buffer_reject_size: ReadableSize::gb(2), diff --git a/src/mito2/src/engine/alter_test.rs b/src/mito2/src/engine/alter_test.rs index aee05880125..757da327d36 100644 --- a/src/mito2/src/engine/alter_test.rs +++ b/src/mito2/src/engine/alter_test.rs @@ -2073,6 +2073,68 @@ async fn test_alter_twcs_option_enables_compaction_override() { assert!(compaction_override()); } +#[tokio::test] +async fn test_alter_compaction_output_parallelism_preserves_existing_snapshots() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + engine + .handle_request( + region_id, + RegionRequest::Create( + CreateRequestBuilder::new() + .insert_option("compaction.experimental_output_parallelism", "4") + .build(), + ), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let initial_version = region.version(); + assert_eq!( + Some(4), + initial_version.options.compaction_output_parallelism + ); + for (kind, expected) in [ + ( + AlterKind::SetRegionOptions { + options: vec![SetRegionOption::CompactionOutputParallelism(Some(1))], + }, + Some(1), + ), + ( + AlterKind::UnsetRegionOptions { + keys: vec![UnsetRegionOption::CompactionOutputParallelism], + }, + None, + ), + ] { + engine + .handle_request(region_id, RegionRequest::Alter(RegionAlterRequest { kind })) + .await + .unwrap(); + let version = region.version(); + assert_eq!(expected, version.options.compaction_output_parallelism); + assert!(!version.options.compaction_override); + assert_eq!( + initial_version.options.compaction, + version.options.compaction + ); + assert_eq!( + Some(4), + initial_version.options.compaction_output_parallelism + ); + } + // Direct engine callers must get the same validation as SQL callers. + let invalid = RegionRequest::Alter(RegionAlterRequest { + kind: AlterKind::SetRegionOptions { + options: vec![SetRegionOption::CompactionOutputParallelism(Some(0))], + }, + }); + assert!(engine.handle_request(region_id, invalid).await.is_err()); + assert_eq!(None, region.version().options.compaction_output_parallelism); +} + #[tokio::test] async fn test_mixed_region_options_are_published_after_flush() { let mut env = TestEnv::new().await; @@ -2122,6 +2184,7 @@ async fn test_mixed_region_options_are_published_after_flush() { "2h".to_string(), ), SetRegionOption::MaxRowGroupRowCount(Some(1024)), + SetRegionOption::CompactionOutputParallelism(Some(4)), ], }, }), @@ -2135,6 +2198,7 @@ async fn test_mixed_region_options_are_published_after_flush() { assert_eq!(None, version.options.ttl); assert!(!version.options.compaction_override); assert_eq!(None, version.options.max_row_group_row_count); + assert_eq!(None, version.options.compaction_output_parallelism); listener.wake_flush(); alter_job.await.unwrap(); @@ -2143,6 +2207,7 @@ async fn test_mixed_region_options_are_published_after_flush() { assert_eq!(Some(Duration::from_secs(500).into()), version.options.ttl); assert!(version.options.compaction_override); assert_eq!(Some(1024), version.options.max_row_group_row_count); + assert_eq!(Some(4), version.options.compaction_output_parallelism); } #[tokio::test(flavor = "multi_thread")] diff --git a/src/mito2/src/engine/compaction_test.rs b/src/mito2/src/engine/compaction_test.rs index b6594ddc136..ec9ddc5cf12 100644 --- a/src/mito2/src/engine/compaction_test.rs +++ b/src/mito2/src/engine/compaction_test.rs @@ -2890,16 +2890,29 @@ async fn test_worker_shutdown_fails_picking_waiter() { #[tokio::test] async fn test_compaction_region() { - test_compaction_region_with_format(false).await; - test_compaction_region_with_format(true).await; + for (engine_parallelism, table_parallelism) in [ + (1, None), + (4, None), + (1, Some(4)), + (4, Some(1)), + (1, Some(usize::MAX)), + ] { + test_compaction_region_with_format(false, engine_parallelism, table_parallelism).await; + test_compaction_region_with_format(true, engine_parallelism, table_parallelism).await; + } } -async fn test_compaction_region_with_format(flat_format: bool) { +async fn test_compaction_region_with_format( + flat_format: bool, + output_parallelism: usize, + table_parallelism: Option, +) { common_telemetry::init_default_ut_logging(); let mut env = TestEnv::new().await; let engine = env .create_engine(MitoConfig { default_flat_format: flat_format, + experimental_compaction_output_parallelism: output_parallelism, ..Default::default() }) .await; @@ -2916,10 +2929,16 @@ async fn test_compaction_region_with_format(flat_format: bool) { ) .await; - let request = CreateRequestBuilder::new() + let mut builder = CreateRequestBuilder::new() .insert_option("compaction.type", "twcs") - .insert_option("experimental_sst_float_field_encoding", "byte_stream_split") - .build(); + .insert_option("experimental_sst_float_field_encoding", "byte_stream_split"); + if let Some(parallelism) = table_parallelism { + builder = builder.insert_option( + "compaction.experimental_output_parallelism", + ¶llelism.to_string(), + ); + } + let request = builder.build(); let column_schemas = request .column_metadatas diff --git a/src/mito2/src/read.rs b/src/mito2/src/read.rs index 65d356d79f2..4d742121a4f 100644 --- a/src/mito2/src/read.rs +++ b/src/mito2/src/read.rs @@ -1013,6 +1013,14 @@ impl FlatSource { self.inner.next_batch().await } + /// Converts the source into a stream of its batches. + pub(crate) fn into_stream(self) -> BoxedRecordBatchStream { + match self.inner { + FlatSourceInner::Iter(iter) => Box::pin(futures::stream::iter(iter)), + FlatSourceInner::Stream(stream) => stream, + } + } + #[cfg(test)] pub(crate) fn take_iter(self) -> BoxedRecordBatchIterator { match self.inner { diff --git a/src/mito2/src/read/scan_region.rs b/src/mito2/src/read/scan_region.rs index da4e1c82bf9..31db8581b27 100644 --- a/src/mito2/src/read/scan_region.rs +++ b/src/mito2/src/read/scan_region.rs @@ -971,6 +971,9 @@ pub struct ScanInput { pub(crate) sequence_range: Option, /// Whether this scan is for compaction. pub(crate) compaction: bool, + /// Max number of compaction inputs decoded concurrently ahead of the merge. + /// Values below 2 decode inputs on the merging task. + pub(crate) compaction_read_parallelism: usize, /// Compaction-only JSON2 physical rewrite targets. json2_rewrite_targets: Json2RewriteTargets, /// Counters that should receive query-load metrics. @@ -1036,6 +1039,7 @@ impl ScanInput { snapshot_sequence: None, sequence_range: None, compaction: false, + compaction_read_parallelism: 1, json2_rewrite_targets: Arc::default(), query_stat_counters: None, #[cfg(feature = "enterprise")] @@ -1393,6 +1397,13 @@ impl ScanInputBuilder { self } + /// Sets the max number of compaction inputs decoded concurrently. + #[must_use] + pub(crate) fn with_compaction_read_parallelism(mut self, parallelism: usize) -> Self { + self.input.compaction_read_parallelism = parallelism; + self + } + /// Sets compaction-only JSON2 physical rewrite targets. #[must_use] pub(crate) fn with_json2_rewrite_targets(mut self, targets: Json2RewriteTargets) -> Self { diff --git a/src/mito2/src/read/seq_scan.rs b/src/mito2/src/read/seq_scan.rs index b57622e07e7..d8759ffaace 100644 --- a/src/mito2/src/read/seq_scan.rs +++ b/src/mito2/src/read/seq_scan.rs @@ -49,7 +49,7 @@ use crate::read::scan_util::{ SplitRecordBatchStream, compute_parallel_channel_size, prepare_flat_mem_stream, scan_flat_file_ranges, scan_flat_mem_ranges, should_split_flat_batches_for_merge, }; -use crate::read::stream::{ConvertBatchStream, ScanBatch, ScanBatchStream}; +use crate::read::stream::{ConvertBatchStream, ScanBatch, ScanBatchStream, spawn_compact_stream}; use crate::read::{BoxedRecordBatchStream, ScannerMetrics, scan_util}; use crate::region::options::MergeMode; use crate::sst::parquet::DEFAULT_READ_BATCH_SIZE; @@ -198,15 +198,19 @@ impl SeqScan { partition_ranges.len(), sources.len() ); - Self::build_flat_reader_from_sources( - stream_ctx, - sources, - None, - None, - false, - compute_parallel_channel_size(DEFAULT_READ_BATCH_SIZE), - ) - .await + let channel_size = compute_parallel_channel_size(DEFAULT_READ_BATCH_SIZE); + let parallelism = stream_ctx.input.compaction_read_parallelism; + if parallelism > 1 && sources.len() > 1 { + // More permits than inputs cannot increase concurrency. Clamping also + // keeps oversized user settings below the semaphore's permit limit. + let semaphore = Arc::new(Semaphore::new(parallelism.min(sources.len()))); + sources = sources + .into_iter() + .map(|source| spawn_compact_stream(source, channel_size, Some(semaphore.clone()))) + .collect(); + } + Self::build_flat_reader_from_sources(stream_ctx, sources, None, None, false, channel_size) + .await } /// Builds a flat reader to read sources that returns RecordBatch. diff --git a/src/mito2/src/read/stream.rs b/src/mito2/src/read/stream.rs index 0c882d374d2..19ed37cf65f 100644 --- a/src/mito2/src/read/stream.rs +++ b/src/mito2/src/read/stream.rs @@ -18,15 +18,19 @@ use std::sync::Arc; use std::task::{Context, Poll}; use std::time::Instant; +use async_stream::try_stream; use common_error::ext::BoxedError; use common_recordbatch::error::ExternalSnafu; use common_recordbatch::{DfRecordBatch, RecordBatch}; use futures::stream::BoxStream; use futures::{Stream, StreamExt}; use snafu::ResultExt; +use tokio::sync::{Semaphore, mpsc}; +use tokio::task::AbortHandle; use crate::cache::CacheStrategy; -use crate::error::Result; +use crate::error::{JoinSnafu, Result, UnexpectedSnafu}; +use crate::read::BoxedRecordBatchStream; use crate::read::flat_projection::FlatProjectionMapper; use crate::read::scan_util::PartitionMetrics; use crate::read::series_scan::SeriesBatch; @@ -122,3 +126,272 @@ impl Stream for ConvertBatchStream { Poll::Ready(Some(record_batch)) } } + +/// Polls `stream` on its own compaction runtime task, buffering up to +/// `capacity` batches ahead of the consumer. While polling, the task holds a +/// permit of `semaphore` if one is given. +/// +/// The channel also closes if the task panics, so the returned stream checks +/// how the task ended before reporting the end of the input. Dropping the +/// returned stream aborts the task. +pub(crate) fn spawn_compact_stream( + mut stream: BoxedRecordBatchStream, + capacity: usize, + semaphore: Option>, +) -> BoxedRecordBatchStream { + let (sender, mut receiver) = mpsc::channel(capacity); + let task = common_runtime::spawn_compact(async move { + loop { + // Releases the permit before sending, so a full channel never holds it. + let permit = match &semaphore { + Some(semaphore) => match semaphore.acquire().await { + Ok(permit) => Some(permit), + Err(e) => { + let reason = format!("Failed to acquire a stream permit: {e}"); + let _ = sender.send(UnexpectedSnafu { reason }.fail()).await; + break; + } + }, + None => None, + }; + let next = stream.next().await; + drop(permit); + let Some(result) = next else { + break; + }; + // Stops after forwarding the first error or once the consumer is gone. + let failed = result.is_err(); + if sender.send(result).await.is_err() || failed { + break; + } + } + }); + // Own the guard before the lazy stream can be dropped without being polled. + let abort = AbortOnDrop(task.abort_handle()); + Box::pin(try_stream! { + let _abort = abort; + while let Some(batch) = receiver.recv().await { + yield batch?; + } + task.await.context(JoinSnafu)?; + }) +} + +/// Aborts a task when its consumer is dropped before the end. +struct AbortOnDrop(AbortHandle); + +impl Drop for AbortOnDrop { + fn drop(&mut self) { + self.0.abort(); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::task::Poll; + use std::time::Duration; + + use datatypes::arrow::array::{ArrayRef, AsArray, Int64Array}; + use datatypes::arrow::datatypes::{DataType, Field, Int64Type, Schema}; + use datatypes::arrow::record_batch::RecordBatch; + use tokio::sync::oneshot; + use tokio::time::timeout; + + use super::*; + use crate::error::{Error, InvalidRecordBatchSnafu}; + use crate::read::flat_merge::FlatMergeReader; + + /// Keeps the producer pending and exposes when its source is polled and dropped. + struct PendingStream { + polled: Option>, + dropped: Option>, + } + + impl PendingStream { + fn new() -> (Self, oneshot::Receiver<()>, oneshot::Receiver<()>) { + let (polled_tx, polled_rx) = oneshot::channel(); + let (dropped_tx, dropped_rx) = oneshot::channel(); + ( + Self { + polled: Some(polled_tx), + dropped: Some(dropped_tx), + }, + polled_rx, + dropped_rx, + ) + } + } + + impl Stream for PendingStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + if let Some(polled) = self.polled.take() { + let _ = polled.send(()); + } + Poll::Pending + } + } + + impl Drop for PendingStream { + fn drop(&mut self) { + if let Some(dropped) = self.dropped.take() { + let _ = dropped.send(()); + } + } + } + + async fn wait_for_signal(signal: oneshot::Receiver<()>) { + // Notifications establish ordering; the timeout only bounds a broken test. + timeout(Duration::from_secs(10), signal) + .await + .expect("timed out waiting for the source") + .expect("source dropped without sending the signal"); + } + + fn batch(value: i64) -> RecordBatch { + let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int64, false)])); + let column = Arc::new(Int64Array::from(vec![value])) as ArrayRef; + RecordBatch::try_new(schema, vec![column]).unwrap() + } + + fn values_stream(values: std::ops::Range) -> BoxedRecordBatchStream { + Box::pin(futures::stream::iter(values.map(|value| Ok(batch(value))))) + } + + /// Drains `stream`, returning the values read before it ended or failed. + async fn drain(mut stream: BoxedRecordBatchStream) -> (Vec, Option) { + let mut values = Vec::new(); + while let Some(result) = stream.next().await { + match result { + Ok(batch) => values.push(batch.column(0).as_primitive::().value(0)), + Err(e) => return (values, Some(e)), + } + } + (values, None) + } + + #[tokio::test] + async fn test_spawn_compact_stream_forwards_batches_in_order() { + let (values, error) = drain(spawn_compact_stream(values_stream(0..5), 2, None)).await; + + assert_eq!(vec![0, 1, 2, 3, 4], values); + assert!(error.is_none()); + } + + #[tokio::test] + async fn test_spawn_compact_stream_stops_at_first_error() { + let stream = futures::stream::iter(vec![ + Ok(batch(0)), + InvalidRecordBatchSnafu { reason: "boom" }.fail(), + Ok(batch(2)), + ]); + + let (values, error) = drain(spawn_compact_stream(Box::pin(stream), 2, None)).await; + + assert_eq!(vec![0], values); + assert!( + matches!(error, Some(Error::InvalidRecordBatch { .. })), + "{error:?}" + ); + } + + #[tokio::test] + async fn test_spawn_compact_stream_reports_panic_instead_of_end() { + let mut polled = false; + let stream = futures::stream::poll_fn(move |_| { + if std::mem::replace(&mut polled, true) { + panic!("source panicked"); + } + Poll::Ready(Some(Ok(batch(0)))) + }); + + let (values, error) = drain(spawn_compact_stream(Box::pin(stream), 2, None)).await; + + // A truncated input must never look like a complete one. + assert_eq!(vec![0], values); + assert!(matches!(error, Some(Error::Join { .. })), "{error:?}"); + } + + #[rstest::rstest] + #[case::before_first_poll(false)] + #[case::after_first_poll(true)] + #[tokio::test] + async fn test_dropped_consumer_cancels_pending_source(#[case] poll_consumer: bool) { + let (source, polled, dropped) = PendingStream::new(); + let semaphore = Arc::new(Semaphore::new(1)); + let mut consumer = spawn_compact_stream(Box::pin(source), 1, Some(semaphore.clone())); + wait_for_signal(polled).await; + assert_eq!(0, semaphore.available_permits()); + if poll_consumer { + assert!(futures::poll!(consumer.next()).is_pending()); + } + + // A guard created inside the lazy stream misses the before-first-poll case. + drop(consumer); + wait_for_signal(dropped).await; + let _permit = timeout(Duration::from_secs(10), semaphore.acquire()) + .await + .expect("producer retained its permit") + .unwrap(); + } + + #[tokio::test] + async fn test_merge_initialization_error_cancels_unpolled_source() { + let (source, polled, dropped) = PendingStream::new(); + let consumer = spawn_compact_stream(Box::pin(source), 1, None); + wait_for_signal(polled).await; + let error_stream = Box::pin(futures::stream::iter(vec![ + InvalidRecordBatchSnafu { reason: "boom" }.fail(), + ])); + let sources = vec![spawn_compact_stream(error_stream, 1, None), consumer]; + + let result = FlatMergeReader::new(batch(0).schema(), sources, 1024, None).await; + + assert!(matches!(result, Err(Error::InvalidRecordBatch { .. }))); + wait_for_signal(dropped).await; + } + + #[tokio::test] + async fn test_cancelled_merge_initialization_drops_all_sources() { + let (first, first_polled, first_dropped) = PendingStream::new(); + let (second, second_polled, second_dropped) = PendingStream::new(); + let sources = vec![ + spawn_compact_stream(Box::pin(first), 1, None), + spawn_compact_stream(Box::pin(second), 1, None), + ]; + wait_for_signal(first_polled).await; + wait_for_signal(second_polled).await; + let mut initialization = + Box::pin(FlatMergeReader::new(batch(0).schema(), sources, 1024, None)); + assert!(futures::poll!(&mut initialization).is_pending()); + + // Only the first consumer has been polled by the sequential initialization. + drop(initialization); + + wait_for_signal(first_dropped).await; + wait_for_signal(second_dropped).await; + } + + #[tokio::test] + async fn test_spawn_compact_streams_share_semaphore() { + let semaphore = Arc::new(Semaphore::new(1)); + let streams: Vec<_> = (0..3) + .map(|i| { + spawn_compact_stream( + values_stream(i * 10..i * 10 + 3), + 1, + Some(semaphore.clone()), + ) + }) + .collect(); + + for (i, stream) in streams.into_iter().enumerate() { + let start = i as i64 * 10; + let (values, error) = drain(stream).await; + assert_eq!((start..start + 3).collect::>(), values); + assert!(error.is_none()); + } + } +} diff --git a/src/mito2/src/region/options.rs b/src/mito2/src/region/options.rs index 42f4adcd04a..58fdec15ad5 100644 --- a/src/mito2/src/region/options.rs +++ b/src/mito2/src/region/options.rs @@ -95,6 +95,11 @@ pub struct RegionOptions { /// Compaction options. pub compaction: CompactionOptions, pub compaction_override: bool, + /// Per-output decode and encode parallelism. Falls back to the engine config + /// when unset; 1 disables parallelism without disabling the merge pipeline. + /// Independent of TWCS options and their database-level inheritance. + #[serde(skip_serializing_if = "Option::is_none")] + pub compaction_output_parallelism: Option, /// Custom storage. Uses default storage if it is `None`. pub storage: Option, /// If append mode is enabled, the region keeps duplicate rows. @@ -162,6 +167,14 @@ impl RegionOptions { } ); } + if let Some(parallelism) = self.compaction_output_parallelism { + ensure!( + parallelism > 0, + InvalidRegionOptionsSnafu { + reason: "compaction.experimental_output_parallelism must be greater than 0", + } + ); + } if let Some(row_count) = self.max_row_group_row_count { ensure!( row_count > 0 && row_count <= MAX_ROW_GROUP_ROW_COUNT_LIMIT, @@ -243,6 +256,11 @@ impl RegionOptions { self.auto_flush_interval.unwrap_or(default) } + /// Returns the per-output compaction parallelism, falling back to the engine default. + pub fn compaction_output_parallelism_or(&self, default: usize) -> usize { + self.compaction_output_parallelism.unwrap_or(default) + } + /// Returns the `primary_key_encoding` if it is set, otherwise returns the default [`PrimaryKeyEncoding`]. pub fn primary_key_encoding(&self) -> PrimaryKeyEncoding { self.primary_key_encoding.unwrap_or_default() @@ -346,6 +364,7 @@ impl RegionOptions { auto_flush_interval: options.auto_flush_interval, compaction, compaction_override, + compaction_output_parallelism: options.compaction_output_parallelism, storage: options.storage, append_mode: options.append_mode, skip_wal: options.skip_wal, @@ -495,6 +514,9 @@ struct RegionOptionsWithoutEnum { ttl: Option, #[serde(with = "humantime_serde")] auto_flush_interval: Option, + #[serde(rename = "compaction.experimental_output_parallelism")] + #[serde_as(as = "NoneAsEmptyString")] + compaction_output_parallelism: Option, storage: Option, #[serde_as(as = "DisplayFromStr")] append_mode: bool, @@ -520,6 +542,7 @@ impl Default for RegionOptionsWithoutEnum { write_buffer_size: options.write_buffer_size, ttl: options.ttl, auto_flush_interval: options.auto_flush_interval, + compaction_output_parallelism: options.compaction_output_parallelism, storage: options.storage, append_mode: options.append_mode, skip_wal: options.skip_wal, @@ -1146,6 +1169,7 @@ mod tests { fallback_to_local: true, }), compaction_override: true, + compaction_output_parallelism: None, storage: Some("S3".to_string()), append_mode: false, skip_wal: false, @@ -1226,6 +1250,7 @@ mod tests { max_row_group_row_count: None, primary_key_encoding: None, write_buffer_size: Some(ReadableSize::mb(128)), + compaction_output_parallelism: Some(4), preserve_row_sequence: true, float_field_encoding: FloatFieldEncoding::default(), }; @@ -1238,6 +1263,8 @@ mod tests { let old_region_options_json_str = r#"{"ttl":null}"#; let got: RegionOptions = serde_json::from_str(old_region_options_json_str).unwrap(); assert_eq!(None, got.write_buffer_size); + assert_eq!(None, got.compaction_output_parallelism); + assert_eq!(4, got.compaction_output_parallelism_or(4)); assert!(!got.preserve_row_sequence); assert_eq!(FloatFieldEncoding::Default, got.float_field_encoding); let CompactionOptions::Twcs(twcs) = got.compaction; @@ -1305,12 +1332,50 @@ mod tests { max_row_group_row_count: None, primary_key_encoding: None, write_buffer_size: None, + compaction_output_parallelism: None, preserve_row_sequence: false, float_field_encoding: FloatFieldEncoding::default(), }; assert_eq!(options, got); } + #[test] + fn test_compaction_output_parallelism_preserves_strategy_inheritance() { + for parallelism in [None, Some(1), Some(4)] { + let mut map = make_map(&[]); + if let Some(parallelism) = parallelism { + map.insert( + "compaction.experimental_output_parallelism".to_string(), + parallelism.to_string(), + ); + } + let options = RegionOptions::try_from_options(RegionId::new(0, 0), &map).unwrap(); + assert_eq!(parallelism, options.compaction_output_parallelism); + assert_eq!( + parallelism.unwrap_or(8), + options.compaction_output_parallelism_or(8) + ); + assert!(!options.compaction_override); + + map.insert("compaction.type".to_string(), "twcs".to_string()); + map.insert("compaction.twcs.time_window".to_string(), "2h".to_string()); + let options = RegionOptions::try_from_options(RegionId::new(0, 0), &map).unwrap(); + assert_eq!(parallelism, options.compaction_output_parallelism); + assert_eq!( + Some(Duration::from_secs(7200)), + options.compaction.time_window() + ); + } + } + + #[test] + fn test_invalid_compaction_output_parallelism() { + for parallelism in ["0", "-1", "1.5", "invalid", "18446744073709551616"] { + let map = make_map(&[("compaction.experimental_output_parallelism", parallelism)]); + assert!(RegionOptions::try_from_options(RegionId::new(0, 0), &map).is_err()); + } + } + #[test] fn test_max_row_group_row_count() { // Default falls back to DEFAULT_ROW_GROUP_SIZE. diff --git a/src/mito2/src/sst/parquet.rs b/src/mito2/src/sst/parquet.rs index b1b459a595a..fec4ede14df 100644 --- a/src/mito2/src/sst/parquet.rs +++ b/src/mito2/src/sst/parquet.rs @@ -35,6 +35,7 @@ use crate::error::{CompressionOptionsSnafu, Result, WriteParquetSnafu}; use crate::sst::DEFAULT_WRITE_BUFFER_SIZE; use crate::sst::file::FileTimeRange; use crate::sst::index::IndexOutput; +use crate::sst::parquet::parallel_writer::EncodeRuntime; pub mod file_range; pub mod flat_format; @@ -44,6 +45,7 @@ pub(crate) mod index_reader; pub(crate) mod index_writer; pub(crate) mod json_align; pub mod metadata; +pub mod parallel_writer; pub mod prefilter; pub mod push_decoder; pub mod read_columns; @@ -190,6 +192,11 @@ pub struct WriteOptions { pub max_file_size: Option, /// Encoding policy for direct floating-point field columns. pub float_field_encoding: FloatFieldEncoding, + /// Maximum number of blocking tasks that encode the columns of a row group. + /// Values below 2 encode on the writing task. + pub encode_parallelism: usize, + /// Runtime whose blocking pool runs the parallel column encoding. + pub encode_runtime: EncodeRuntime, } impl Default for WriteOptions { @@ -199,6 +206,8 @@ impl Default for WriteOptions { row_group_size: DEFAULT_ROW_GROUP_SIZE, max_file_size: None, float_field_encoding: FloatFieldEncoding::default(), + encode_parallelism: 1, + encode_runtime: EncodeRuntime::default(), } } } @@ -492,7 +501,8 @@ mod tests { } } - struct NoopIndexBuilder; + /// Builds an indexer with no enabled indexes for SST writer tests. + pub(crate) struct NoopIndexBuilder; #[async_trait::async_trait] impl IndexerBuilder for NoopIndexBuilder { @@ -506,6 +516,54 @@ mod tests { } } + #[tokio::test] + async fn test_parallel_encoding_writes_identical_file() { + let mut env = TestEnv::new().await; + let object_store = env.init_object_store_manager(); + let metadata = Arc::new(sst_region_metadata()); + let mut contents = Vec::new(); + for encode_parallelism in [1, 3] { + let handle = sst_file_handle(0, 1000); + let file_path = FixedPathProvider { + region_file_id: handle.file_id(), + }; + let path = file_path.build_sst_file_path(handle.file_id()); + let source = new_flat_source_from_record_batches(vec![ + new_record_batch_by_range(&["a", "d"], 0, 60), + new_record_batch_by_range(&["b", "f"], 0, 40), + new_record_batch_by_range(&["b", "h"], 100, 200), + ]); + let write_opts = WriteOptions { + row_group_size: 50, + encode_parallelism, + ..Default::default() + }; + + let mut metrics = Metrics::new(WriteType::Flush); + let mut writer = ParquetWriter::new_with_object_store( + object_store.clone(), + metadata.clone(), + IndexConfig::default(), + NoopIndexBuilder, + file_path, + &mut metrics, + ) + .await; + let info = writer + .write_all_flat(source, None, &write_opts) + .await + .unwrap() + .remove(0); + assert_eq!(200, info.num_rows); + assert_eq!(4, info.num_row_groups); + contents.push(object_store.read(&path).await.unwrap().to_vec()); + } + assert!( + contents[0] == contents[1], + "parallel encoding changed the SST" + ); + } + #[tokio::test] async fn test_write_read() { let mut env = TestEnv::new().await; diff --git a/src/mito2/src/sst/parquet/parallel_writer.rs b/src/mito2/src/sst/parquet/parallel_writer.rs new file mode 100644 index 00000000000..d257574cb79 --- /dev/null +++ b/src/mito2/src/sst/parquet/parallel_writer.rs @@ -0,0 +1,648 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Arrow to Parquet writer that encodes the columns of a row group in parallel. + +use std::mem; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use common_runtime::JoinHandle; +use datatypes::arrow::datatypes::SchemaRef; +use datatypes::arrow::record_batch::RecordBatch; +use parquet::arrow::ArrowWriter; +use parquet::arrow::arrow_writer::{ + ArrowColumnChunk, ArrowColumnWriter, ArrowRowGroupWriterFactory, compute_leaves, +}; +use parquet::arrow::async_writer::AsyncFileWriter; +use parquet::errors::{ParquetError, Result}; +use parquet::file::metadata::ParquetMetaData; +use parquet::file::properties::WriterProperties; +use parquet::file::writer::SerializedFileWriter; + +/// Runtime whose blocking pool encodes the columns of a writer. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum EncodeRuntime { + /// The global runtime. + #[default] + Global, + /// The compaction runtime. + Compact, +} + +impl EncodeRuntime { + fn spawn(self, f: F) -> JoinHandle + where + F: FnOnce() -> R + Send + 'static, + R: Send + 'static, + { + match self { + EncodeRuntime::Global => common_runtime::spawn_blocking_global(f), + EncodeRuntime::Compact => common_runtime::spawn_blocking_compact(f), + } + } +} + +/// Column writers of one top-level field: its index and its leaf writers. +type FieldWriters = (usize, Vec<(usize, ArrowColumnWriter)>); + +/// Output of one encode task: column chunks by leaf index, and the time spent +/// on each field. +type EncodedFields = (Vec<(usize, ArrowColumnChunk)>, Vec<(usize, Duration)>); + +/// Writes Parquet like [`parquet::arrow::AsyncArrowWriter`], but encodes the +/// columns of each row group on up to `parallelism` blocking tasks. +/// +/// A row group encodes in the background while the next one is buffered, so at +/// most two row groups of input are held in memory. Every column writer sees the +/// same input as with [`ArrowWriter`], so the output is byte-for-byte identical. +/// The bytes of a row group reach the async writer when the next row group +/// starts or on [`Self::flush`], one row group later than with `AsyncArrowWriter`. +pub struct ParallelArrowWriter { + /// Assembles row groups and the footer into an in-memory buffer. + file_writer: SerializedFileWriter>, + /// Creates the column writers of each row group. + factory: Arc, + arrow_schema: SchemaRef, + /// Top-level field of each leaf column. + leaf_fields: Vec, + /// Encode time of each field in the last row group, used to balance tasks. + field_costs: Vec, + async_writer: W, + max_row_group_rows: usize, + parallelism: usize, + runtime: EncodeRuntime, + /// Slices of input buffered for the next row group. + buffered: Vec, + buffered_rows: usize, + /// Tasks encoding the previous row group. + encoding: Vec>>, + num_row_groups: usize, +} + +impl ParallelArrowWriter { + /// Returns whether the writer can reproduce [`ArrowWriter`]'s row groups for + /// `props`, which holds only when row groups are limited by row count alone. + pub fn supports(props: &WriterProperties) -> bool { + props.max_row_group_row_count().is_some() && props.max_row_group_bytes().is_none() + } + + /// Creates a writer. `props` must be [supported](Self::supports). + pub fn try_new( + async_writer: W, + arrow_schema: SchemaRef, + props: WriterProperties, + parallelism: usize, + runtime: EncodeRuntime, + ) -> Result { + let max_row_group_rows = match props.max_row_group_row_count() { + Some(rows) if Self::supports(&props) => rows.max(1), + _ => { + return Err(ParquetError::General( + "parallel writer requires a row-count-only row group limit".to_string(), + )); + } + }; + let (file_writer, factory) = + ArrowWriter::try_new(Vec::new(), arrow_schema.clone(), Some(props))? + .into_serialized_writer()?; + let schema = file_writer.schema_descr(); + let leaf_fields = (0..schema.num_columns()) + .map(|leaf| schema.get_column_root_idx(leaf)) + .collect(); + let num_fields = arrow_schema.fields().len(); + Ok(Self { + file_writer, + factory: Arc::new(factory), + arrow_schema, + leaf_fields, + field_costs: vec![Duration::ZERO; num_fields], + async_writer, + max_row_group_rows, + parallelism: parallelism.max(1), + runtime, + buffered: Vec::new(), + buffered_rows: 0, + encoding: Vec::new(), + num_row_groups: 0, + }) + } + + /// Buffers `batch`, starting to encode each row group once it is full. + pub async fn write(&mut self, batch: &RecordBatch) -> Result<()> { + let mut offset = 0; + while offset < batch.num_rows() { + let len = (self.max_row_group_rows - self.buffered_rows).min(batch.num_rows() - offset); + self.buffered.push(batch.slice(offset, len)); + self.buffered_rows += len; + offset += len; + if self.buffered_rows == self.max_row_group_rows { + self.encode_buffered().await?; + } + } + Ok(()) + } + + /// Writes all buffered rows as a row group, like [`ArrowWriter::flush`]. + pub async fn flush(&mut self) -> Result<()> { + if self.buffered_rows > 0 { + self.encode_buffered().await?; + } + self.finish_encoding().await + } + + /// Writes the remaining rows and the footer, then completes the async writer. + pub async fn close(mut self) -> Result { + self.flush().await?; + let metadata = self.file_writer.finish()?; + self.write_buffered_bytes().await?; + self.async_writer.complete().await?; + Ok(metadata) + } + + /// Discards buffered input and waits for encoders without writing a failed SST. + pub(crate) async fn abort(mut self) { + self.buffered.clear(); + abort_encoding_tasks(&mut self.encoding).await; + } + + /// Installs controlled tasks to test SST write-error cleanup independently of codec timing. + #[cfg(test)] + pub(crate) fn set_encoding_tasks_for_test( + &mut self, + tasks: Vec>>, + ) { + assert!(self.encoding.is_empty()); + self.encoding = tasks; + } + + /// Starts encoding the buffered rows once the previous row group is written. + async fn encode_buffered(&mut self) -> Result<()> { + self.finish_encoding().await?; + + let batches: Arc<[RecordBatch]> = mem::take(&mut self.buffered).into(); + self.buffered_rows = 0; + let writers = self.factory.create_column_writers(self.num_row_groups)?; + self.num_row_groups += 1; + + // One array produces all leaves of a field, so a field is never split. + let mut fields: Vec = (0..self.arrow_schema.fields().len()) + .map(|field| (field, Vec::new())) + .collect(); + for (leaf, writer) in writers.into_iter().enumerate() { + fields[self.leaf_fields[leaf]].1.push((leaf, writer)); + } + self.encoding = assign_fields(fields, &self.field_costs, self.parallelism) + .into_iter() + .map(|fields| { + let batches = batches.clone(); + let schema = self.arrow_schema.clone(); + self.runtime + .spawn(move || encode_fields(&schema, &batches, fields)) + }) + .collect(); + Ok(()) + } + + /// Waits for the row group being encoded and appends it to the file. + async fn finish_encoding(&mut self) -> Result<()> { + if self.encoding.is_empty() { + return Ok(()); + } + let mut chunks = Vec::with_capacity(self.leaf_fields.len()); + let mut tasks = mem::take(&mut self.encoding).into_iter(); + while let Some(task) = tasks.next() { + let encoded = task + .await + .map_err(|e| ParquetError::External(Box::new(e))) + .and_then(|encoded| encoded); + let (task_chunks, costs) = match encoded { + Ok(encoded) => encoded, + Err(error) => { + abort_encoding_tasks(tasks.as_mut_slice()).await; + return Err(error); + } + }; + chunks.extend(task_chunks); + for (field, cost) in costs { + self.field_costs[field] = cost; + } + } + chunks.sort_unstable_by_key(|(leaf, _)| *leaf); + let mut row_group = self.file_writer.next_row_group()?; + for (_, chunk) in chunks { + chunk.append_to_row_group(&mut row_group)?; + } + row_group.close()?; + self.write_buffered_bytes().await + } + + /// Moves the bytes assembled so far to the async writer. + async fn write_buffered_bytes(&mut self) -> Result<()> { + let bytes = mem::take(self.file_writer.inner_mut()); + if bytes.is_empty() { + return Ok(()); + } + self.async_writer.write(Bytes::from(bytes)).await + } +} + +/// Aborts queued blocking work and joins running work before its budget is released. +async fn abort_encoding_tasks(tasks: &mut [JoinHandle>]) { + for task in tasks.iter() { + task.abort(); + } + for task in tasks { + // Cleanup failures must not replace the original encoding or source error. + let _ = task.await; + } +} + +/// Splits `fields` into at most `parallelism` tasks, giving the most expensive +/// field to the least loaded task first. Fields cost nothing before any row +/// group is measured, which spreads them evenly. +fn assign_fields( + mut fields: Vec, + costs: &[Duration], + parallelism: usize, +) -> Vec> { + let num_tasks = parallelism.min(fields.len()).max(1); + fields.sort_by_key(|(field, _)| std::cmp::Reverse(costs[*field])); + let mut tasks: Vec<(Duration, Vec)> = (0..num_tasks) + .map(|_| (Duration::ZERO, Vec::new())) + .collect(); + for field in fields { + let key = |(load, fields): &(Duration, Vec)| (*load, fields.len()); + let mut lightest = 0; + for task in 1..tasks.len() { + if key(&tasks[task]) < key(&tasks[lightest]) { + lightest = task; + } + } + tasks[lightest].0 += costs[field.0]; + tasks[lightest].1.push(field); + } + tasks + .into_iter() + .map(|(_, fields)| fields) + .filter(|fields| !fields.is_empty()) + .collect() +} + +/// Encodes `fields` of all `batches` and closes their column writers. +fn encode_fields( + schema: &SchemaRef, + batches: &[RecordBatch], + fields: Vec, +) -> Result { + let mut chunks = Vec::new(); + let mut costs = Vec::with_capacity(fields.len()); + for (field, mut writers) in fields { + let start = Instant::now(); + for batch in batches { + let leaves = compute_leaves(schema.field(field), batch.column(field))?; + if leaves.len() != writers.len() { + return Err(ParquetError::General(format!( + "field {} has {} leaf arrays but {} column writers", + schema.field(field).name(), + leaves.len(), + writers.len() + ))); + } + for (leaf, (_, writer)) in leaves.iter().zip(writers.iter_mut()) { + writer.write(leaf)?; + } + } + for (leaf, writer) in writers { + chunks.push((leaf, writer.close()?)); + } + costs.push((field, start.elapsed())); + } + Ok((chunks, costs)) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + + use common_runtime::runtime::{BuilderBuild, RuntimeTrait}; + use datatypes::arrow::array::{ + ArrayRef, DictionaryArray, Float64Array, Int32Array, Int64Array, StringArray, StructArray, + }; + use datatypes::arrow::datatypes::{DataType, Field, Fields, Schema, UInt32Type}; + use parquet::basic::{Compression, ZstdLevel}; + use tokio::sync::oneshot; + use tokio::time::timeout; + + use super::*; + use crate::compaction::memory_manager::new_compaction_memory_manager; + + fn schema() -> SchemaRef { + let nested = Fields::from(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Utf8, true), + ]); + Arc::new(Schema::new(vec![ + Field::new("int", DataType::Int64, false), + Field::new("float", DataType::Float64, true), + Field::new( + "tag", + DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)), + false, + ), + Field::new("nested", DataType::Struct(nested), true), + ])) + } + + fn batch(start: usize, len: usize) -> RecordBatch { + let rows = start..start + len; + let ints = Int64Array::from_iter_values(rows.clone().map(|i| i as i64 * 7)); + let floats = Float64Array::from_iter( + rows.clone() + .map(|i| (i % 5 != 0).then_some((i % 13) as f64 / 3.0)), + ); + let tags: DictionaryArray = rows + .clone() + .map(|i| format!("tag-{}", i % 3)) + .collect::>() + .iter() + .map(String::as_str) + .collect(); + let nested = StructArray::from(vec![ + ( + Arc::new(Field::new("a", DataType::Int32, true)), + Arc::new(Int32Array::from_iter( + rows.clone().map(|i| (i % 4 != 0).then_some(i as i32)), + )) as ArrayRef, + ), + ( + Arc::new(Field::new("b", DataType::Utf8, true)), + Arc::new(StringArray::from_iter( + rows.map(|i| (i % 6 != 0).then(|| format!("v{i}"))), + )) as ArrayRef, + ), + ]); + RecordBatch::try_new( + schema(), + vec![ + Arc::new(ints), + Arc::new(floats), + Arc::new(tags), + Arc::new(nested), + ], + ) + .unwrap() + } + + fn props(row_group_rows: usize) -> WriterProperties { + WriterProperties::builder() + .set_compression(Compression::ZSTD(ZstdLevel::default())) + .set_max_row_group_row_count(Some(row_group_rows)) + .set_data_page_row_count_limit(16) + .build() + } + + /// One step of a write sequence: a batch of `len` rows, or a flush. + #[derive(Clone, Copy)] + enum Step { + Write(usize), + Flush, + } + + fn write_serial(steps: &[Step], props: WriterProperties) -> Vec { + let mut buf = Vec::new(); + let mut writer = ArrowWriter::try_new(&mut buf, schema(), Some(props)).unwrap(); + let mut start = 0; + for step in steps { + match *step { + Step::Write(len) => { + writer.write(&batch(start, len)).unwrap(); + start += len; + } + Step::Flush => writer.flush().unwrap(), + } + } + writer.close().unwrap(); + buf + } + + async fn write_parallel( + steps: &[Step], + props: WriterProperties, + parallelism: usize, + ) -> Vec { + let mut buf = Vec::new(); + let mut writer = ParallelArrowWriter::try_new( + &mut buf, + schema(), + props, + parallelism, + EncodeRuntime::Global, + ) + .unwrap(); + let mut start = 0; + for step in steps { + match *step { + Step::Write(len) => { + writer.write(&batch(start, len)).await.unwrap(); + start += len; + } + Step::Flush => writer.flush().await.unwrap(), + } + } + writer.close().await.unwrap(); + buf + } + + #[tokio::test] + async fn test_parallel_writer_matches_arrow_writer() { + use Step::*; + let cases: Vec<(&str, Vec)> = vec![ + ("empty", vec![]), + ("partial row group", vec![Write(10)]), + ("exact row groups", vec![Write(64), Write(64)]), + ( + "batches across row groups", + vec![Write(7), Write(100), Write(3), Write(250), Write(1)], + ), + ("batch spanning many row groups", vec![Write(1000)]), + ( + "explicit flushes", + vec![Write(10), Flush, Flush, Write(70), Flush, Write(5)], + ), + ]; + for (name, steps) in cases { + let expected = write_serial(&steps, props(64)); + for parallelism in [1, 2, 3, 16] { + let actual = write_parallel(&steps, props(64), parallelism).await; + assert!( + expected == actual, + "case {name}, parallelism {parallelism}: {} bytes != {} bytes", + expected.len(), + actual.len() + ); + } + } + } + + #[rstest::rstest] + #[case::encode_error(false)] + #[case::encode_panic(true)] + #[tokio::test] + async fn test_encode_failure_drains_tasks_before_releasing_budget(#[case] panics: bool) { + let runtime: common_runtime::Runtime = common_runtime::Builder::default() + .worker_threads(1) + .max_blocking_threads(1) + .build() + .unwrap(); + let mut writer = ParallelArrowWriter::try_new( + Vec::new(), + schema(), + props(64), + 3, + EncodeRuntime::Compact, + ) + .unwrap(); + let memory = new_compaction_memory_manager(1024 * 1024); + let budget = memory.try_acquire(memory.limit_bytes()).unwrap(); + let batches: Arc<[RecordBatch]> = vec![batch(0, 4)].into(); + let retained_batches = Arc::downgrade(&batches); + + let failed = runtime.spawn_blocking(move || -> Result { + if panics { + panic!("encode task failed"); + } + Err(ParquetError::General("encode task failed".to_string())) + }); + let (started_tx, started_rx) = oneshot::channel(); + let (release_tx, release_rx) = oneshot::channel(); + let column = writer.factory.create_column_writers(0).unwrap().remove(0); + let running_batches = batches.clone(); + let running = runtime.spawn_blocking(move || { + started_tx.send(()).unwrap(); + release_rx.blocking_recv().unwrap(); + let _encoded = + encode_fields(&schema(), &running_batches, vec![(0, vec![(0, column)])])?; + Err(ParquetError::General("later encoding failure".to_string())) + }); + // With one blocking thread, this also proves the first task has ended. + timeout(Duration::from_secs(10), started_rx) + .await + .unwrap() + .unwrap(); + let queued_started = Arc::new(AtomicBool::new(false)); + let queued_started_task = queued_started.clone(); + let queued = runtime.spawn_blocking(move || { + queued_started_task.store(true, Ordering::SeqCst); + drop(batches); + Ok((Vec::new(), Vec::new())) + }); + writer.encoding = vec![failed, running, queued]; + + // Model the compaction caller's guard: it is released when flush returns. + let mut finish = Box::pin(async { + let _budget = budget; + writer.flush().await + }); + assert!(futures::poll!(finish.as_mut()).is_pending()); + assert!(memory.try_acquire(memory.limit_bytes()).is_none()); + assert!(retained_batches.upgrade().is_some()); + + release_tx.send(()).unwrap(); + let error = timeout(Duration::from_secs(10), finish) + .await + .unwrap() + .unwrap_err(); + if panics { + let ParquetError::External(source) = error else { + panic!("expected the original task panic, got {error}"); + }; + assert!( + source + .downcast_ref::() + .unwrap() + .is_panic() + ); + } else { + assert!( + matches!(error, ParquetError::General(message) if message == "encode task failed") + ); + } + assert!(!queued_started.load(Ordering::SeqCst)); + assert!(retained_batches.upgrade().is_none()); + assert!(memory.try_acquire(memory.limit_bytes()).is_some()); + assert!(writer.file_writer.flushed_row_groups().is_empty()); + assert!(writer.async_writer.is_empty()); + } + + #[test] + fn test_parallel_writer_requires_row_count_limit() { + assert!(ParallelArrowWriter::>::supports(&props(64))); + let byte_limited = WriterProperties::builder() + .set_max_row_group_bytes(Some(1024)) + .build(); + assert!(!ParallelArrowWriter::>::supports(&byte_limited)); + let unlimited = WriterProperties::builder() + .set_max_row_group_row_count(None) + .build(); + assert!(!ParallelArrowWriter::>::supports(&unlimited)); + assert!( + ParallelArrowWriter::try_new(Vec::new(), schema(), unlimited, 2, EncodeRuntime::Global) + .is_err() + ); + } + + #[test] + fn test_assign_fields_balances_measured_costs() { + let (file_writer, factory) = ArrowWriter::try_new(Vec::new(), schema(), Some(props(64))) + .unwrap() + .into_serialized_writer() + .unwrap(); + let schema_descr = file_writer.schema_descr(); + let mut fields: Vec = (0..4).map(|field| (field, Vec::new())).collect(); + for (leaf, writer) in factory + .create_column_writers(0) + .unwrap() + .into_iter() + .enumerate() + { + fields[schema_descr.get_column_root_idx(leaf)] + .1 + .push((leaf, writer)); + } + // The nested field owns both struct leaves. + assert_eq!(2, fields[3].1.len()); + + let costs = [10, 9, 1, 1].map(Duration::from_millis); + let tasks = assign_fields(fields, &costs, 2); + let mut loads: Vec<_> = tasks + .iter() + .map(|task| { + task.iter() + .map(|(field, _)| costs[*field]) + .sum::() + }) + .collect(); + loads.sort(); + assert_eq!( + vec![Duration::from_millis(10), Duration::from_millis(11)], + loads + ); + let mut assigned: Vec<_> = tasks.iter().flatten().map(|(field, _)| *field).collect(); + assigned.sort(); + assert_eq!(vec![0, 1, 2, 3], assigned); + } +} diff --git a/src/mito2/src/sst/parquet/writer.rs b/src/mito2/src/sst/parquet/writer.rs index 69a89e5802b..d7656d8c354 100644 --- a/src/mito2/src/sst/parquet/writer.rs +++ b/src/mito2/src/sst/parquet/writer.rs @@ -36,8 +36,9 @@ use datatypes::arrow::record_batch::RecordBatch; use datatypes::extension::json::is_json2_extension_type; use object_store::{FuturesAsyncWriter, ObjectStore}; use parquet::arrow::AsyncArrowWriter; +use parquet::arrow::async_writer::AsyncFileWriter; use parquet::basic::{Compression, Encoding, ZstdLevel}; -use parquet::file::metadata::KeyValue; +use parquet::file::metadata::{KeyValue, ParquetMetaData}; use parquet::file::properties::WriterProperties; use smallvec::smallvec; use snafu::{OptionExt, ResultExt}; @@ -59,6 +60,7 @@ use crate::sst::parquet::flat_format::{ FlatWriteFormat, primary_key_column_index, time_index_column_index, }; use crate::sst::parquet::format::{PrimaryKeyArray, PrimaryKeyWriteFormat}; +use crate::sst::parquet::parallel_writer::ParallelArrowWriter; use crate::sst::parquet::{ COLUMN_INDEX_TRUNCATE_LENGTH, PARQUET_METADATA_KEY, SstInfo, WriteOptions, apply_column_compression, apply_float_field_encoding, apply_internal_column_encoding, @@ -154,11 +156,48 @@ fn split_at_next_series( }) } +/// Arrow writer of the current SST file. +enum SstArrowWriter { + /// Encodes on the writing task. + Serial(AsyncArrowWriter), + /// Encodes the columns of each row group on blocking tasks. + Parallel(ParallelArrowWriter), +} + +impl SstArrowWriter { + async fn write(&mut self, batch: &RecordBatch) -> parquet::errors::Result<()> { + match self { + SstArrowWriter::Serial(writer) => writer.write(batch).await, + SstArrowWriter::Parallel(writer) => writer.write(batch).await, + } + } + + async fn flush(&mut self) -> parquet::errors::Result<()> { + match self { + SstArrowWriter::Serial(writer) => writer.flush().await, + SstArrowWriter::Parallel(writer) => writer.flush().await, + } + } + + async fn close(self) -> parquet::errors::Result { + match self { + SstArrowWriter::Serial(writer) => writer.close().await, + SstArrowWriter::Parallel(writer) => writer.close().await, + } + } + + async fn abort(self) { + if let SstArrowWriter::Parallel(writer) = self { + writer.abort().await; + } + } +} + /// Parquet SST writer. pub struct ParquetWriter<'a, F: WriterFactory, I: IndexerBuilder, P: FilePathProvider> { /// Path provider that creates SST and index file paths according to file id. path_provider: P, - writer: Option>>, + writer: Option>>, /// Current active file id. current_file: FileId, writer_factory: F, @@ -374,10 +413,7 @@ where ); let res = self.write_all_flat_inner(source, &converter, opts).await; if res.is_err() { - let file_id = self.current_file; - if let Some(cleaner) = &self.file_cleaner { - cleaner.clean_by_file_id(file_id).await; - } + self.abort_current_file().await; } res } @@ -402,10 +438,7 @@ where }; let res = self.write_all_flat_inner(source, &converter, opts).await; if res.is_err() { - let file_id = self.current_file; - if let Some(cleaner) = &self.file_cleaner { - cleaner.clean_by_file_id(file_id).await; - } + self.abort_current_file().await; } res } @@ -520,6 +553,16 @@ where .is_some_and(|max_size| self.bytes_written.load(Ordering::Relaxed) >= max_size) } + /// Joins encoders before dropping the writer and deleting its failed output. + async fn abort_current_file(&mut self) { + if let Some(writer) = self.writer.take() { + writer.abort().await; + } + if let Some(cleaner) = &self.file_cleaner { + cleaner.clean_by_file_id(self.current_file).await; + } + } + async fn abort_current_indexer(&mut self) { if let Some(indexer) = &mut self.current_indexer { indexer.abort().await; @@ -530,7 +573,7 @@ where &mut self, schema: &SchemaRef, opts: &WriteOptions, - ) -> Result<&mut AsyncArrowWriter>> { + ) -> Result<&mut SstArrowWriter>> { if let Some(ref mut w) = self.writer { Ok(w) } else { @@ -564,9 +607,26 @@ where .await?, self.bytes_written.clone(), ); - let arrow_writer = - AsyncArrowWriter::try_new(writer, maybe_wrap_schema(schema)?, Some(writer_props)) - .context(WriteParquetSnafu)?; + let schema = maybe_wrap_schema(schema)?; + let arrow_writer = if opts.encode_parallelism > 1 + && ParallelArrowWriter::>::supports(&writer_props) + { + SstArrowWriter::Parallel( + ParallelArrowWriter::try_new( + writer, + schema, + writer_props, + opts.encode_parallelism, + opts.encode_runtime, + ) + .context(WriteParquetSnafu)?, + ) + } else { + SstArrowWriter::Serial( + AsyncArrowWriter::try_new(writer, schema, Some(writer_props)) + .context(WriteParquetSnafu)?, + ) + }; self.writer = Some(arrow_writer); let indexer = self @@ -732,3 +792,145 @@ where Pin::new(&mut self.inner).poll_shutdown(cx) } } + +#[cfg(test)] +mod tests { + use std::sync::atomic::AtomicBool; + use std::time::Duration; + + use common_runtime::runtime::{BuilderBuild, RuntimeTrait}; + use parquet::arrow::ArrowWriter; + use parquet::errors::ParquetError; + use store_api::region_request::PathType; + use tokio::sync::oneshot; + use tokio::time::timeout; + + use super::*; + use crate::access_layer::{RegionFilePathFactory, WriteType}; + use crate::compaction::memory_manager::new_compaction_memory_manager; + use crate::error::Error; + use crate::sst::FormatType; + use crate::sst::parquet::tests::NoopIndexBuilder; + use crate::test_util::TestEnv; + use crate::test_util::sst_util::{new_record_batch_by_range, sst_region_metadata}; + + #[rstest::rstest] + #[case::flat(FormatType::Flat)] + #[case::primary_key(FormatType::PrimaryKey)] + #[tokio::test] + async fn test_source_error_waits_for_encoding_cleanup(#[case] format: FormatType) { + let mut env = TestEnv::new().await; + let metadata = Arc::new(sst_region_metadata()); + let mut metrics = Metrics::new(WriteType::Compaction); + let mut writer = ParquetWriter::new_with_object_store( + env.init_object_store_manager(), + metadata.clone(), + IndexConfig::default(), + NoopIndexBuilder, + RegionFilePathFactory::new("".to_string(), PathType::Bare), + &mut metrics, + ) + .await; + let opts = WriteOptions { + row_group_size: 8, + encode_parallelism: 2, + ..Default::default() + }; + let batch = new_record_batch_by_range(&["a", "b"], 0, 4); + let retained_field = Arc::downgrade(batch.column(2)); + let converter = match format { + FormatType::Flat => FlatBatchConverter::Flat(FlatWriteFormat::new( + metadata.clone(), + &FlatSchemaOptions::default(), + )), + FormatType::PrimaryKey => FlatBatchConverter::PrimaryKey { + format: PrimaryKeyWriteFormat::new(metadata.clone()), + num_fields: metadata.field_columns().count(), + }, + }; + let encoding_batch = converter.convert_batch(&batch).unwrap(); + let encoding_schema = encoding_batch.schema(); + let (_, factory) = ArrowWriter::try_new(Vec::new(), encoding_schema.clone(), None) + .unwrap() + .into_serialized_writer() + .unwrap(); + let columns = factory.create_column_writers(0).unwrap(); + let runtime: common_runtime::Runtime = common_runtime::Builder::default() + .worker_threads(1) + .max_blocking_threads(1) + .build() + .unwrap(); + let (started_tx, started_rx) = oneshot::channel(); + let (release_tx, release_rx) = oneshot::channel(); + let queued_batch = encoding_batch.clone(); + let running = runtime.spawn_blocking(move || { + started_tx.send(()).unwrap(); + release_rx.blocking_recv().unwrap(); + drop((encoding_batch, columns)); + Err(ParquetError::General( + "cleanup encoding failure".to_string(), + )) + }); + timeout(Duration::from_secs(10), started_rx) + .await + .unwrap() + .unwrap(); + let queued_started = Arc::new(AtomicBool::new(false)); + let queued_started_task = queued_started.clone(); + let queued = runtime.spawn_blocking(move || { + queued_started_task.store(true, Ordering::SeqCst); + drop(queued_batch); + Ok((Vec::new(), Vec::new())) + }); + let SstArrowWriter::Parallel(parallel) = writer + .maybe_init_writer(&encoding_schema, &opts) + .await + .unwrap() + else { + panic!("expected parallel encoding"); + }; + // Controlled real tasks represent the previous row group in flight. + parallel.set_encoding_tasks_for_test(vec![running, queued]); + let source = FlatSource::new_stream( + batch.schema(), + Box::pin(futures::stream::iter(vec![ + Ok(batch), + InvalidRecordBatchSnafu { + reason: "source read failed", + } + .fail(), + ])), + ); + let memory = new_compaction_memory_manager(1024 * 1024); + let budget = memory.try_acquire(memory.limit_bytes()).unwrap(); + let mut write = Box::pin(async { + let _budget = budget; + match format { + FormatType::Flat => writer.write_all_flat(source, None, &opts).await, + FormatType::PrimaryKey => { + writer + .write_all_flat_as_primary_key(source, None, &opts) + .await + } + } + }); + // The next row group is buffered, then the source fails. No codec timing + // or I/O wait can make the old indexer-only cleanup pass this assertion. + assert!(futures::poll!(write.as_mut()).is_pending()); + assert!(memory.try_acquire(memory.limit_bytes()).is_none()); + assert!(retained_field.upgrade().is_some()); + release_tx.send(()).unwrap(); + let error = timeout(Duration::from_secs(10), write) + .await + .unwrap() + .unwrap_err(); + assert!( + matches!(error, Error::InvalidRecordBatch { reason, .. } if reason == "source read failed") + ); + assert!(!queued_started.load(Ordering::SeqCst)); + assert!(retained_field.upgrade().is_none()); + assert!(memory.try_acquire(memory.limit_bytes()).is_some()); + assert!(writer.writer.is_none()); + assert_eq!(0, writer.bytes_written.load(Ordering::Relaxed)); + } +} diff --git a/src/mito2/src/worker/handle_alter.rs b/src/mito2/src/worker/handle_alter.rs index 1798f9a79bf..580e55f1bed 100644 --- a/src/mito2/src/worker/handle_alter.rs +++ b/src/mito2/src/worker/handle_alter.rs @@ -311,6 +311,11 @@ impl RegionWorkerLoop { current_options.auto_flush_interval = new_interval; } } + SetRegionOption::CompactionOutputParallelism(parallelism) => { + // New compactions use the updated options; running ones retain + // their snapshot. No memtable flush is needed. + current_options.compaction_output_parallelism = parallelism; + } SetRegionOption::MaxRowGroupRowCount(new_row_count) => { if let Some(row_count) = new_row_count { ensure!( @@ -431,6 +436,7 @@ fn new_region_options_on_empty_memtable( | SetRegionOption::Ttl(_) | SetRegionOption::Twsc(_, _) | SetRegionOption::AutoFlushInterval(_) + | SetRegionOption::CompactionOutputParallelism(_) | SetRegionOption::SkipWal(_) => (), SetRegionOption::Format(format_str) => { // Safety: handle_alter_region_options_fast() has validated this. diff --git a/src/store-api/src/mito_engine_options.rs b/src/store-api/src/mito_engine_options.rs index 457b33665c3..1f680aff995 100644 --- a/src/store-api/src/mito_engine_options.rs +++ b/src/store-api/src/mito_engine_options.rs @@ -29,6 +29,9 @@ pub const MERGE_MODE_KEY: &str = "merge_mode"; pub const TTL_KEY: &str = "ttl"; /// Option key for the per-table auto flush interval. pub const AUTO_FLUSH_INTERVAL_KEY: &str = "auto_flush_interval"; +/// Per-table override for each compaction output's decode and encode parallelism. +pub const COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM: &str = + "compaction.experimental_output_parallelism"; /// Option key for compaction type. pub const COMPACTION_TYPE: &str = "compaction.type"; /// Option key for forcing compaction options override. @@ -166,6 +169,7 @@ pub fn is_mito_engine_option_key(key: &str) -> bool { "ttl", WRITE_BUFFER_SIZE_KEY, AUTO_FLUSH_INTERVAL_KEY, + COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM, "storage", "index.inverted_index.ignore_column_ids", "index.inverted_index.segment_row_count", @@ -200,6 +204,9 @@ mod tests { assert!(is_mito_engine_option_key("ttl")); assert!(is_mito_engine_option_key("write_buffer_size")); assert!(is_mito_engine_option_key("auto_flush_interval")); + assert!(is_mito_engine_option_key( + "compaction.experimental_output_parallelism" + )); assert!(is_mito_engine_option_key("compaction.type")); assert!(is_mito_engine_option_key("compaction.override")); assert!(is_mito_engine_option_key( diff --git a/src/store-api/src/region_request.rs b/src/store-api/src/region_request.rs index 937fb9d950f..787d6c5afe1 100644 --- a/src/store-api/src/region_request.rs +++ b/src/store-api/src/region_request.rs @@ -60,11 +60,12 @@ use crate::metadata::{ use crate::metric_engine_consts::PHYSICAL_TABLE_METADATA_KEY; use crate::metrics; use crate::mito_engine_options::{ - APPEND_MODE_KEY, AUTO_FLUSH_INTERVAL_KEY, MAX_ROW_GROUP_ROW_COUNT, - MAX_ROW_GROUP_ROW_COUNT_LIMIT, PRESERVE_ROW_SEQUENCE, SKIP_WAL_KEY, SST_FORMAT_KEY, TTL_KEY, - TWCS_ACTIVE_WINDOW_L1_MERGE_TRIGGER, TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, - TWCS_INACTIVE_WINDOW_L1_MERGE_TRIGGER, TWCS_INACTIVE_WINDOW_TRIGGER_FILE_NUM, - TWCS_MAX_OUTPUT_FILE_SIZE, TWCS_TIME_WINDOW, TWCS_TRIGGER_FILE_NUM, WRITE_BUFFER_SIZE_KEY, + APPEND_MODE_KEY, AUTO_FLUSH_INTERVAL_KEY, COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM, + MAX_ROW_GROUP_ROW_COUNT, MAX_ROW_GROUP_ROW_COUNT_LIMIT, PRESERVE_ROW_SEQUENCE, SKIP_WAL_KEY, + SST_FORMAT_KEY, TTL_KEY, TWCS_ACTIVE_WINDOW_L1_MERGE_TRIGGER, + TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, TWCS_INACTIVE_WINDOW_L1_MERGE_TRIGGER, + TWCS_INACTIVE_WINDOW_TRIGGER_FILE_NUM, TWCS_MAX_OUTPUT_FILE_SIZE, TWCS_TIME_WINDOW, + TWCS_TRIGGER_FILE_NUM, WRITE_BUFFER_SIZE_KEY, }; use crate::path_utils::table_dir; use crate::storage::{ColumnId, RegionId}; @@ -1603,6 +1604,8 @@ pub enum SetRegionOption { PreserveRowSequence(bool), // Whether to skip writing new WAL entries. SkipWal(bool), + /// Overrides per-output compaction parallelism; None restores the engine default. + CompactionOutputParallelism(Option), } #[derive(Serialize, Deserialize)] @@ -1616,6 +1619,7 @@ enum SetRegionOptionSerde { MaxRowGroupRowCount(Option), PreserveRowSequence(bool), SkipWal(bool), + CompactionOutputParallelism(Option), } impl Serialize for SetRegionOption { @@ -1638,6 +1642,9 @@ impl Serialize for SetRegionOption { Self::MaxRowGroupRowCount(value) => SetRegionOptionSerde::MaxRowGroupRowCount(*value), Self::PreserveRowSequence(value) => SetRegionOptionSerde::PreserveRowSequence(*value), Self::SkipWal(value) => SetRegionOptionSerde::SkipWal(*value), + Self::CompactionOutputParallelism(value) => { + SetRegionOptionSerde::CompactionOutputParallelism(*value) + } }; option.serialize(serializer) } @@ -1667,6 +1674,9 @@ impl From for SetRegionOption { SetRegionOptionSerde::MaxRowGroupRowCount(value) => Self::MaxRowGroupRowCount(value), SetRegionOptionSerde::PreserveRowSequence(value) => Self::PreserveRowSequence(value), SetRegionOptionSerde::SkipWal(value) => Self::SkipWal(value), + SetRegionOptionSerde::CompactionOutputParallelism(value) => { + Self::CompactionOutputParallelism(value) + } } } } @@ -1733,6 +1743,17 @@ impl TryFrom<&PbOption> for SetRegionOption { } Ok(Self::AutoFlushInterval(Some(interval))) } + COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM => { + if value.is_empty() { + return Ok(Self::CompactionOutputParallelism(None)); + } + let parallelism = value + .parse::() + .ok() + .filter(|parallelism| *parallelism > 0) + .ok_or_else(|| InvalidSetRegionOptionRequestSnafu { key, value }.build())?; + Ok(Self::CompactionOutputParallelism(Some(parallelism))) + } MAX_ROW_GROUP_ROW_COUNT => { if value.is_empty() { return Ok(Self::MaxRowGroupRowCount(None)); @@ -1791,6 +1812,9 @@ impl From<&UnsetRegionOption> for SetRegionOption { UnsetRegionOption::MaxRowGroupRowCount => SetRegionOption::MaxRowGroupRowCount(None), UnsetRegionOption::WriteBufferSize => SetRegionOption::WriteBufferSize(None), UnsetRegionOption::PreserveRowSequence => SetRegionOption::PreserveRowSequence(false), + UnsetRegionOption::CompactionOutputParallelism => { + SetRegionOption::CompactionOutputParallelism(None) + } } } } @@ -1811,6 +1835,7 @@ impl TryFrom<&str> for UnsetRegionOption { TWCS_TIME_WINDOW => Ok(Self::TwcsTimeWindow), MAX_ROW_GROUP_ROW_COUNT => Ok(Self::MaxRowGroupRowCount), PRESERVE_ROW_SEQUENCE => Ok(Self::PreserveRowSequence), + COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM => Ok(Self::CompactionOutputParallelism), _ => InvalidUnsetRegionOptionRequestSnafu { key }.fail(), } } @@ -1829,6 +1854,7 @@ pub enum UnsetRegionOption { WriteBufferSize, PreserveRowSequence, TwcsActiveWindowL1MergeTrigger, + CompactionOutputParallelism, } impl UnsetRegionOption { @@ -1845,6 +1871,7 @@ impl UnsetRegionOption { Self::TwcsTimeWindow => TWCS_TIME_WINDOW, Self::MaxRowGroupRowCount => MAX_ROW_GROUP_ROW_COUNT, Self::PreserveRowSequence => PRESERVE_ROW_SEQUENCE, + Self::CompactionOutputParallelism => COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM, } } } @@ -2218,6 +2245,42 @@ mod tests { .unwrap_err(); } + #[test] + fn test_compaction_output_parallelism_set_unset_and_serde() { + for (raw, expected) in [("", None), ("1", Some(1)), ("4", Some(4))] { + let option = SetRegionOption::try_from(&PbOption { + key: COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM.to_string(), + value: raw.to_string(), + }) + .unwrap(); + assert_eq!( + SetRegionOption::CompactionOutputParallelism(expected), + option + ); + let json = serde_json::to_string(&option).unwrap(); + assert_eq!( + option, + serde_json::from_str::(&json).unwrap() + ); + } + for raw in ["0", "-1", "1.5", "invalid", "18446744073709551616"] { + assert!( + SetRegionOption::try_from(&PbOption { + key: COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM.to_string(), + value: raw.to_string(), + }) + .is_err() + ); + } + let unset = + UnsetRegionOption::try_from(COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM).unwrap(); + assert_eq!(COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM, unset.as_str()); + assert_eq!( + SetRegionOption::CompactionOutputParallelism(None), + (&unset).into() + ); + } + #[test] fn test_set_region_option_auto_flush_interval_try_from() { use std::time::Duration; diff --git a/src/table/src/metadata.rs b/src/table/src/metadata.rs index 57a4548160a..c94275c9e8a 100644 --- a/src/table/src/metadata.rs +++ b/src/table/src/metadata.rs @@ -31,9 +31,10 @@ use serde::{Deserialize, Deserializer, Serialize}; use snafu::{OptionExt, ResultExt, ensure}; use store_api::metric_engine_consts::PHYSICAL_TABLE_METADATA_KEY; use store_api::mito_engine_options::{ - APPEND_MODE_KEY, AUTO_FLUSH_INTERVAL_KEY, COMPACTION_TYPE, COMPACTION_TYPE_TWCS, - MAX_ROW_GROUP_ROW_COUNT, MERGE_MODE_KEY, PRESERVE_ROW_SEQUENCE, SKIP_WAL_KEY, SST_FORMAT_KEY, - TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, TWCS_TRIGGER_FILE_NUM, + APPEND_MODE_KEY, AUTO_FLUSH_INTERVAL_KEY, COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM, + COMPACTION_TYPE, COMPACTION_TYPE_TWCS, MAX_ROW_GROUP_ROW_COUNT, MERGE_MODE_KEY, + PRESERVE_ROW_SEQUENCE, SKIP_WAL_KEY, SST_FORMAT_KEY, TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, + TWCS_TRIGGER_FILE_NUM, }; use store_api::region_request::{SetRegionOption, UnsetRegionOption}; use store_api::storage::{ColumnDescriptor, ColumnDescriptorBuilder, ColumnId}; @@ -415,6 +416,18 @@ impl TableMeta { new_options.extra_options.remove(AUTO_FLUSH_INTERVAL_KEY); } } + SetRegionOption::CompactionOutputParallelism(parallelism) => { + if let Some(parallelism) = parallelism { + new_options.extra_options.insert( + COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM.to_string(), + parallelism.to_string(), + ); + } else { + new_options + .extra_options + .remove(COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM); + } + } SetRegionOption::MaxRowGroupRowCount(row_count) => { if let Some(row_count) = row_count { new_options @@ -2571,6 +2584,55 @@ mod tests { ); } + #[test] + fn test_compaction_output_parallelism_persistence_and_unset() { + let mut meta = TableMetaBuilder::empty() + .schema(Arc::new(new_test_schema())) + .primary_key_indices(vec![0]) + .engine("mito") + .next_column_id(3) + .options(TableOptions::default()) + .build() + .unwrap(); + for (kind, expected) in [ + ( + AlterKind::SetTableOptions { + options: vec![SetRegionOption::CompactionOutputParallelism(Some(4))], + }, + Some("4"), + ), + ( + AlterKind::SetTableOptions { + options: vec![SetRegionOption::CompactionOutputParallelism(Some(1))], + }, + Some("1"), + ), + ( + AlterKind::UnsetTableOptions { + keys: vec![UnsetRegionOption::CompactionOutputParallelism], + }, + None, + ), + ] { + meta = meta + .builder_with_alter_kind("my_table", &kind) + .unwrap() + .build() + .unwrap(); + // Restart uses the persisted table options to reopen regions. + let json = serde_json::to_string(&meta.options).unwrap(); + let restored: TableOptions = serde_json::from_str(&json).unwrap(); + assert_eq!( + expected, + restored + .extra_options + .get(COMPACTION_EXPERIMENTAL_OUTPUT_PARALLELISM) + .map(String::as_str) + ); + assert!(!restored.extra_options.contains_key(COMPACTION_TYPE)); + } + } + #[test] fn test_set_auto_flush_interval() { let schema = Arc::new(new_test_schema()); diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index 1827e8b6581..c13ada351ea 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -3573,6 +3573,7 @@ experimental_series_index_maintenance_interval = "5m" experimental_series_index_bucket_width = "5days" experimental_compaction_memory_limit = "unlimited" experimental_compaction_on_exhausted = "wait" +experimental_compaction_output_parallelism = 1 auto_flush_interval = "10m" default_region_write_buffer_size = "0KiB" enable_write_cache = false diff --git a/tests/cases/standalone/common/alter/compaction_output_parallelism.result b/tests/cases/standalone/common/alter/compaction_output_parallelism.result new file mode 100644 index 00000000000..d8e04bc7837 --- /dev/null +++ b/tests/cases/standalone/common/alter/compaction_output_parallelism.result @@ -0,0 +1,140 @@ +-- Execution parallelism does not require compaction.type. +CREATE TABLE compaction_output_parallelism ( + ts TIMESTAMP TIME INDEX, + val INT +) WITH ('compaction.experimental_output_parallelism' = '4'); + +Affected Rows: 0 + +INSERT INTO compaction_output_parallelism VALUES (0, 10); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('compaction_output_parallelism'); + ++----------------------------------------------------+ +| ADMIN FLUSH_TABLE('compaction_output_parallelism') | ++----------------------------------------------------+ +| 0 | ++----------------------------------------------------+ + +INSERT INTO compaction_output_parallelism VALUES (1000, 20); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('compaction_output_parallelism'); + ++----------------------------------------------------+ +| ADMIN FLUSH_TABLE('compaction_output_parallelism') | ++----------------------------------------------------+ +| 0 | ++----------------------------------------------------+ + +ADMIN COMPACT_TABLE('compaction_output_parallelism'); + ++------------------------------------------------------+ +| ADMIN COMPACT_TABLE('compaction_output_parallelism') | ++------------------------------------------------------+ +| 0 | ++------------------------------------------------------+ + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE compaction_output_parallelism; + ++-------------------------------+--------------------------------------------------------------+ +| Table | Create Table | ++-------------------------------+--------------------------------------------------------------+ +| compaction_output_parallelism | CREATE TABLE IF NOT EXISTS "compaction_output_parallelism" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "val" INT NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | 'compaction.experimental_output_parallelism' = '4' | +| | ) | ++-------------------------------+--------------------------------------------------------------+ + +SELECT * FROM compaction_output_parallelism ORDER BY ts; + ++---------------------+-----+ +| ts | val | ++---------------------+-----+ +| 1970-01-01T00:00:00 | 10 | +| 1970-01-01T00:00:01 | 20 | ++---------------------+-----+ + +-- A table can disable parallel encoding even when the engine default enables it. +ALTER TABLE compaction_output_parallelism SET 'compaction.experimental_output_parallelism' = '1'; + +Affected Rows: 0 + +SHOW CREATE TABLE compaction_output_parallelism; + ++-------------------------------+--------------------------------------------------------------+ +| Table | Create Table | ++-------------------------------+--------------------------------------------------------------+ +| compaction_output_parallelism | CREATE TABLE IF NOT EXISTS "compaction_output_parallelism" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "val" INT NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | 'compaction.experimental_output_parallelism' = '1' | +| | ) | ++-------------------------------+--------------------------------------------------------------+ + +ALTER TABLE compaction_output_parallelism SET 'compaction.experimental_output_parallelism' = '0'; + +Error: 1004(InvalidArguments), Invalid set table option request: Invalid set region option request, key: compaction.experimental_output_parallelism, value: 0 + +ALTER TABLE compaction_output_parallelism SET 'compaction.experimental_output_parallelism' = '-1'; + +Error: 1004(InvalidArguments), Invalid set table option request: Invalid set region option request, key: compaction.experimental_output_parallelism, value: -1 + +ALTER TABLE compaction_output_parallelism SET 'compaction.experimental_output_parallelism' = 'invalid'; + +Error: 1004(InvalidArguments), Invalid set table option request: Invalid set region option request, key: compaction.experimental_output_parallelism, value: invalid + +-- UNSET removes the override without introducing compaction.type or compaction.override. +ALTER TABLE compaction_output_parallelism UNSET 'compaction.experimental_output_parallelism'; + +Affected Rows: 0 + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE compaction_output_parallelism; + ++-------------------------------+--------------------------------------------------------------+ +| Table | Create Table | ++-------------------------------+--------------------------------------------------------------+ +| compaction_output_parallelism | CREATE TABLE IF NOT EXISTS "compaction_output_parallelism" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "val" INT NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | | ++-------------------------------+--------------------------------------------------------------+ + +SELECT * FROM compaction_output_parallelism ORDER BY ts; + ++---------------------+-----+ +| ts | val | ++---------------------+-----+ +| 1970-01-01T00:00:00 | 10 | +| 1970-01-01T00:00:01 | 20 | ++---------------------+-----+ + +DROP TABLE compaction_output_parallelism; + +Affected Rows: 0 + +CREATE TABLE invalid_parallelism (ts TIMESTAMP TIME INDEX) +WITH ('compaction.experimental_output_parallelism' = '0'); + +Error: 1004(InvalidArguments), Invalid region options, compaction.experimental_output_parallelism must be greater than 0 + diff --git a/tests/cases/standalone/common/alter/compaction_output_parallelism.sql b/tests/cases/standalone/common/alter/compaction_output_parallelism.sql new file mode 100644 index 00000000000..7772c197379 --- /dev/null +++ b/tests/cases/standalone/common/alter/compaction_output_parallelism.sql @@ -0,0 +1,35 @@ +-- Execution parallelism does not require compaction.type. +CREATE TABLE compaction_output_parallelism ( + ts TIMESTAMP TIME INDEX, + val INT +) WITH ('compaction.experimental_output_parallelism' = '4'); + +INSERT INTO compaction_output_parallelism VALUES (0, 10); +ADMIN FLUSH_TABLE('compaction_output_parallelism'); +INSERT INTO compaction_output_parallelism VALUES (1000, 20); +ADMIN FLUSH_TABLE('compaction_output_parallelism'); +ADMIN COMPACT_TABLE('compaction_output_parallelism'); + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE compaction_output_parallelism; + +SELECT * FROM compaction_output_parallelism ORDER BY ts; + +-- A table can disable parallel encoding even when the engine default enables it. +ALTER TABLE compaction_output_parallelism SET 'compaction.experimental_output_parallelism' = '1'; +SHOW CREATE TABLE compaction_output_parallelism; + +ALTER TABLE compaction_output_parallelism SET 'compaction.experimental_output_parallelism' = '0'; +ALTER TABLE compaction_output_parallelism SET 'compaction.experimental_output_parallelism' = '-1'; +ALTER TABLE compaction_output_parallelism SET 'compaction.experimental_output_parallelism' = 'invalid'; + +-- UNSET removes the override without introducing compaction.type or compaction.override. +ALTER TABLE compaction_output_parallelism UNSET 'compaction.experimental_output_parallelism'; +-- SQLNESS ARG restart=true +SHOW CREATE TABLE compaction_output_parallelism; + +SELECT * FROM compaction_output_parallelism ORDER BY ts; +DROP TABLE compaction_output_parallelism; + +CREATE TABLE invalid_parallelism (ts TIMESTAMP TIME INDEX) +WITH ('compaction.experimental_output_parallelism' = '0'); diff --git a/tests/compatibility/cases/compaction_output_parallelism/case.toml b/tests/compatibility/cases/compaction_output_parallelism/case.toml new file mode 100644 index 00000000000..9e3bc1d8e91 --- /dev/null +++ b/tests/compatibility/cases/compaction_output_parallelism/case.toml @@ -0,0 +1,8 @@ +name = "compaction_output_parallelism" +reason = "Verify old table options reopen with inherited output parallelism and support setting and clearing the new per-table override." +introduced_by = "PR #9945" +topologies = ["distributed", "standalone"] +from_range = ["*"] +to_range = [">=v1.4.0-alpha.0"] +features = ["table", "metadata", "alter", "compaction"] +owner = "storage" diff --git a/tests/compatibility/cases/compaction_output_parallelism/setup.sql b/tests/compatibility/cases/compaction_output_parallelism/setup.sql new file mode 100644 index 00000000000..a3dd0a23f92 --- /dev/null +++ b/tests/compatibility/cases/compaction_output_parallelism/setup.sql @@ -0,0 +1,7 @@ +CREATE TABLE compaction_parallelism ( + ts TIMESTAMP TIME INDEX, + val INT +) ENGINE=mito; + +INSERT INTO compaction_parallelism VALUES (0, 10), (1000, 20); +ADMIN FLUSH_TABLE('compaction_parallelism'); diff --git a/tests/compatibility/cases/compaction_output_parallelism/verify.result b/tests/compatibility/cases/compaction_output_parallelism/verify.result new file mode 100644 index 00000000000..646761ec763 --- /dev/null +++ b/tests/compatibility/cases/compaction_output_parallelism/verify.result @@ -0,0 +1,90 @@ +SELECT * FROM compaction_parallelism ORDER BY ts; + ++---------------------+-----+ +| ts | val | ++---------------------+-----+ +| 1970-01-01T00:00:00 | 10 | +| 1970-01-01T00:00:01 | 20 | ++---------------------+-----+ + +ALTER TABLE compaction_parallelism SET 'compaction.experimental_output_parallelism' = '4'; + +Affected Rows: 0 + +INSERT INTO compaction_parallelism VALUES (2000, 30); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('compaction_parallelism'); + ++---------------------------------------------+ +| ADMIN FLUSH_TABLE('compaction_parallelism') | ++---------------------------------------------+ +| 0 | ++---------------------------------------------+ + +ADMIN COMPACT_TABLE('compaction_parallelism'); + ++-----------------------------------------------+ +| ADMIN COMPACT_TABLE('compaction_parallelism') | ++-----------------------------------------------+ +| 0 | ++-----------------------------------------------+ + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE compaction_parallelism; + ++------------------------+-------------------------------------------------------+ +| Table | Create Table | ++------------------------+-------------------------------------------------------+ +| compaction_parallelism | CREATE TABLE IF NOT EXISTS "compaction_parallelism" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "val" INT NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | 'compaction.experimental_output_parallelism' = '4' | +| | ) | ++------------------------+-------------------------------------------------------+ + +SELECT * FROM compaction_parallelism ORDER BY ts; + ++---------------------+-----+ +| ts | val | ++---------------------+-----+ +| 1970-01-01T00:00:00 | 10 | +| 1970-01-01T00:00:01 | 20 | +| 1970-01-01T00:00:02 | 30 | ++---------------------+-----+ + +ALTER TABLE compaction_parallelism UNSET 'compaction.experimental_output_parallelism'; + +Affected Rows: 0 + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE compaction_parallelism; + ++------------------------+-------------------------------------------------------+ +| Table | Create Table | ++------------------------+-------------------------------------------------------+ +| compaction_parallelism | CREATE TABLE IF NOT EXISTS "compaction_parallelism" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "val" INT NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | | ++------------------------+-------------------------------------------------------+ + +SELECT * FROM compaction_parallelism ORDER BY ts; + ++---------------------+-----+ +| ts | val | ++---------------------+-----+ +| 1970-01-01T00:00:00 | 10 | +| 1970-01-01T00:00:01 | 20 | +| 1970-01-01T00:00:02 | 30 | ++---------------------+-----+ diff --git a/tests/compatibility/cases/compaction_output_parallelism/verify.sql b/tests/compatibility/cases/compaction_output_parallelism/verify.sql new file mode 100644 index 00000000000..814a4c45ceb --- /dev/null +++ b/tests/compatibility/cases/compaction_output_parallelism/verify.sql @@ -0,0 +1,15 @@ +SELECT * FROM compaction_parallelism ORDER BY ts; + +ALTER TABLE compaction_parallelism SET 'compaction.experimental_output_parallelism' = '4'; +INSERT INTO compaction_parallelism VALUES (2000, 30); +ADMIN FLUSH_TABLE('compaction_parallelism'); +ADMIN COMPACT_TABLE('compaction_parallelism'); + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE compaction_parallelism; +SELECT * FROM compaction_parallelism ORDER BY ts; + +ALTER TABLE compaction_parallelism UNSET 'compaction.experimental_output_parallelism'; +-- SQLNESS ARG restart=true +SHOW CREATE TABLE compaction_parallelism; +SELECT * FROM compaction_parallelism ORDER BY ts; From b21cd16f1d62a213bb7b90bb8198e3840ce7593f Mon Sep 17 00:00:00 2001 From: Dragon Roar <2181719471@qq.com> Date: Wed, 28 Oct 2026 17:09:29 +0000 Subject: [PATCH 16/19] feat(datanode): probe object storage at startup (#9954) * feat(datanode): self-test object storage at startup Signed-off-by: lczllx <2181719471@qq.com> * fix(datanode): harden the startup object storage self-test Signed-off-by: lczllx <2181719471@qq.com> * test(datanode): cover the File store skip in the object store self-test Signed-off-by: lczllx <2181719471@qq.com> * refactor(datanode): rename the object storage self-test to probe Signed-off-by: lczllx <2181719471@qq.com> * test(datanode): disable object store self-test in sqlness and integration tests Signed-off-by: lczllx <2181719471@qq.com> * docs(datanode): correct what the object storage probe claims to cover Signed-off-by: lczllx <2181719471@qq.com> --------- Signed-off-by: lczllx <2181719471@qq.com> --- Cargo.lock | 1 + config/config.md | 2 + config/datanode.example.toml | 8 + config/standalone.example.toml | 8 + src/datanode/Cargo.toml | 1 + src/datanode/src/config.rs | 22 +++ src/datanode/src/datanode.rs | 164 ++++++++++++++++- src/datanode/src/error.rs | 28 ++- src/datanode/src/store.rs | 221 ++++++++++++++++++++++- tests-integration/src/test_util.rs | 1 + tests-integration/tests/http.rs | 2 + tests/conf/datanode-test.toml.template | 1 + tests/conf/standalone-test.toml.template | 1 + 13 files changed, 447 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f68dfbe2334..d40ca8b5baa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4566,6 +4566,7 @@ dependencies = [ "prometheus 0.14.0", "prost 0.14.1", "query", + "rand 0.9.4", "reqwest 0.13.4", "serde", "serde_json", diff --git a/config/config.md b/config/config.md index 711fe019a19..cd2b518f12c 100644 --- a/config/config.md +++ b/config/config.md @@ -153,6 +153,7 @@ | `storage` | -- | -- | The data storage options. | | `storage.data_home` | String | `./greptimedb_data` | The working home directory. | | `storage.copy_root` | String | `./greptimedb_data/copy` | Root directory for standalone SQL access to local files.
Relative SQL paths are resolved below this directory. Absolute paths are accepted only when
they are inside this directory. Defaults to `/copy`.
Distributed deployments always reject SQL access to local files.
Upgrade note: COPY commands and existing external tables that reference paths outside this
directory will fail. Move those files below the copy root, set this option to a dedicated
directory containing them, or migrate the files to object storage before upgrading. | +| `storage.probe_on_startup` | Bool | `true` | Whether to probe every remote object storage when the datanode starts.
The probe writes, reads, overwrites, lists and deletes an object under
`.greptime_probe/`, and a failure aborts startup. The probe lives at the storage
root, so the credentials must allow writes and deletes below the root. Disable it
when the credentials are scoped to narrower prefixes or when the storage may be
unavailable at startup. | | `storage.type` | String | `File` | The storage type used to store the data.
- `File`: the data is stored in the local file system.
- `S3`: the data is stored in the S3 object storage.
- `Gcs`: the data is stored in the Google Cloud Storage.
- `Azblob`: the data is stored in the Azure Blob Storage.
- `Oss`: the data is stored in the Aliyun OSS.
- `Hdfs`: the data is stored in the Hadoop Distributed File System. | | `storage.bucket` | String | Unset | The S3 bucket name.
**It's only used when the storage type is `S3`, `Oss` and `Gcs`**. | | `storage.root` | String | Unset | The directory or object prefix under which data is stored.
**It's only used when the storage type is `S3`, `Oss`, `Gcs`, `Azblob` and `Hdfs`**. | @@ -631,6 +632,7 @@ | `query.experimental_spill_compression` | String | `uncompressed` | Compression for spilled data files: "uncompressed" (default), "lz4_frame", "zstd".
Ignored unless mode is "custom". | | `storage` | -- | -- | The data storage options. | | `storage.data_home` | String | `./greptimedb_data` | The working home directory. | +| `storage.probe_on_startup` | Bool | `true` | Whether to probe every remote object storage when the datanode starts.
The probe writes, reads, overwrites, lists and deletes an object under
`.greptime_probe/`, and a failure aborts startup. The probe lives at the storage
root, so the credentials must allow writes and deletes below the root. Disable it
when the credentials are scoped to narrower prefixes or when the storage may be
unavailable at startup. | | `storage.type` | String | `File` | The storage type used to store the data.
- `File`: the data is stored in the local file system.
- `S3`: the data is stored in the S3 object storage.
- `Gcs`: the data is stored in the Google Cloud Storage.
- `Azblob`: the data is stored in the Azure Blob Storage.
- `Oss`: the data is stored in the Aliyun OSS.
- `Hdfs`: the data is stored in the Hadoop Distributed File System. | | `storage.bucket` | String | Unset | The S3 bucket name.
**It's only used when the storage type is `S3`, `Oss` and `Gcs`**. | | `storage.root` | String | Unset | The directory or object prefix under which data is stored.
**It's only used when the storage type is `S3`, `Oss`, `Gcs`, `Azblob` and `Hdfs`**. | diff --git a/config/datanode.example.toml b/config/datanode.example.toml index a2457302a10..a7e9417717f 100644 --- a/config/datanode.example.toml +++ b/config/datanode.example.toml @@ -375,6 +375,14 @@ memory_pool_size = "50%" ## The working home directory. data_home = "./greptimedb_data" +## Whether to probe every remote object storage when the datanode starts. +## The probe writes, reads, overwrites, lists and deletes an object under +## `.greptime_probe/`, and a failure aborts startup. The probe lives at the storage +## root, so the credentials must allow writes and deletes below the root. Disable it +## when the credentials are scoped to narrower prefixes or when the storage may be +## unavailable at startup. +probe_on_startup = true + ## The storage type used to store the data. ## - `File`: the data is stored in the local file system. ## - `S3`: the data is stored in the S3 object storage. diff --git a/config/standalone.example.toml b/config/standalone.example.toml index d047952538c..0fa5907f95b 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -603,6 +603,14 @@ data_home = "./greptimedb_data" ## directory containing them, or migrate the files to object storage before upgrading. #+ copy_root = "./greptimedb_data/copy" +## Whether to probe every remote object storage when the datanode starts. +## The probe writes, reads, overwrites, lists and deletes an object under +## `.greptime_probe/`, and a failure aborts startup. The probe lives at the storage +## root, so the credentials must allow writes and deletes below the root. Disable it +## when the credentials are scoped to narrower prefixes or when the storage may be +## unavailable at startup. +probe_on_startup = true + ## The storage type used to store the data. ## - `File`: the data is stored in the local file system. ## - `S3`: the data is stored in the S3 object storage. diff --git a/src/datanode/Cargo.toml b/src/datanode/Cargo.toml index 0720a576b9c..45cdc783197 100644 --- a/src/datanode/Cargo.toml +++ b/src/datanode/Cargo.toml @@ -61,6 +61,7 @@ partition.workspace = true prometheus.workspace = true prost.workspace = true query.workspace = true +rand.workspace = true reqwest.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/src/datanode/src/config.rs b/src/datanode/src/config.rs index 34a41ce2801..cc7ebf8a0ce 100644 --- a/src/datanode/src/config.rs +++ b/src/datanode/src/config.rs @@ -44,6 +44,14 @@ pub struct StorageConfig { /// Defaults to `/copy` when `data_home` is a local path. /// Distributed deployments always disable SQL access to local files. pub copy_root: Option, + /// Whether to probe every remote object storage when the datanode starts. + /// + /// The probe writes, reads, overwrites, lists and deletes an object under + /// `.greptime_probe/`, and a failure aborts startup. The probe lives at the + /// storage root, so the credentials must allow writes and deletes below the root. + /// Disable it when the credentials are scoped to narrower prefixes or when the + /// storage may be unavailable at startup. + pub probe_on_startup: bool, #[serde(flatten)] pub store: ObjectStoreConfig, /// Object storage providers @@ -62,6 +70,7 @@ impl Default for StorageConfig { Self { data_home: DEFAULT_DATA_HOME.to_string(), copy_root: None, + probe_on_startup: true, store: ObjectStoreConfig::default(), providers: vec![], } @@ -203,6 +212,19 @@ mod tests { let _parsed: DatanodeOptions = toml::from_str(&toml_string).unwrap(); } + #[test] + fn test_probe_on_startup() { + assert!(DatanodeOptions::default().storage.probe_on_startup); + + let toml_str = r#" + [storage] + type = "File" + probe_on_startup = false + "#; + let opts: DatanodeOptions = toml::from_str(toml_str).unwrap(); + assert!(!opts.storage.probe_on_startup); + } + #[test] fn test_secstr() { let toml_str = r#" diff --git a/src/datanode/src/datanode.rs b/src/datanode/src/datanode.rs index c304aaa6e00..6ebe7ffe05d 100644 --- a/src/datanode/src/datanode.rs +++ b/src/datanode/src/datanode.rs @@ -44,6 +44,7 @@ use common_wal::config::kafka::DatanodeKafkaConfig; use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION}; use common_wal::config::raft_engine::RaftEngineConfig; use file_engine::engine::FileRegionEngine; +use futures::future::join_all; use log_store::ObjectStoreLogStore; use log_store::kafka::log_store::KafkaLogStore; use log_store::noop::log_store::NoopLogStore; @@ -466,20 +467,83 @@ impl DatanodeBuilder { .await } - /// Builds [ObjectStoreManager] from [StorageConfig]. - pub async fn build_object_store_manager(cfg: &StorageConfig) -> Result { + /// Builds [ObjectStoreManager] from [StorageConfig] and probes every remote + /// object store it contains, unless `probe_on_startup` is disabled. + /// + /// The probe fails the build when a store rejects any of the operations the + /// engines rely on, so a misconfigured storage surfaces here instead of failing + /// on the first write. + pub async fn build_object_store_manager( + cfg: &StorageConfig, + node_id: u64, + ) -> Result { let object_store = store::new_object_store(cfg.store.clone(), &cfg.data_home).await?; let default_name = cfg.store.config_name(); - let mut object_store_manager = ObjectStoreManager::new(default_name, object_store); - for store in &cfg.providers { - object_store_manager.add( - store.config_name(), - store::new_object_store(store.clone(), &cfg.data_home).await?, - ); + let mut checks = Vec::with_capacity(1 + cfg.providers.len()); + if cfg.store.is_object_storage() { + checks.push((default_name.to_string(), object_store.clone())); } + let mut object_store_manager = ObjectStoreManager::new(default_name, object_store); + for provider in &cfg.providers { + let name = provider.config_name(); + let object_store = store::new_object_store(provider.clone(), &cfg.data_home).await?; + if provider.is_object_storage() { + checks.push((name.to_string(), object_store.clone())); + } + object_store_manager.add(name, object_store); + } + + if cfg.probe_on_startup && !checks.is_empty() { + let prefix = store::probe_key_prefix(node_id); + Self::run_probes(&checks, &prefix).await?; + } + Ok(Arc::new(object_store_manager)) } + /// Probes every store in `checks` under its own key prefix. + /// + /// Providers often share one object storage, so when there is more than one + /// store each probe starts after a random delay rather than all at once. + /// + /// Each check is bounded by [`store::PROBE_TIMEOUT`], so a store that accepts + /// connections but never answers fails startup instead of blocking it, after a + /// best-effort removal of its probe. + async fn run_probes(checks: &[(String, ObjectStore)], prefix: &str) -> Result<()> { + let stagger = checks.len() > 1; + let checks = checks + .iter() + .enumerate() + .map(|(index, (name, object_store))| { + let prefix = format!("{prefix}/{index}"); + async move { + if stagger { + tokio::time::sleep(store::probe_start_delay()).await; + } + match tokio::time::timeout( + store::PROBE_TIMEOUT, + store::probe_object_store(object_store, name, &prefix), + ) + .await + { + Ok(result) => result, + Err(_) => { + store::remove_probe_object(object_store, &prefix).await; + error::ObjectStoreProbeTimeoutSnafu { + name, + timeout: store::PROBE_TIMEOUT, + } + .fail() + } + } + } + }); + for result in join_all(checks).await { + result?; + } + Ok(()) + } + #[cfg(test)] /// Open all regions belong to this datanode. async fn initialize_region_server( @@ -573,7 +637,11 @@ impl DatanodeBuilder { ); region_server.install_remote_dyn_filter_receiver_injector(&self.plugins); - let object_store_manager = Self::build_object_store_manager(&opts.storage).await?; + let object_store_manager = Self::build_object_store_manager( + &opts.storage, + opts.node_id.context(MissingNodeIdSnafu)?, + ) + .await?; let engines = self .build_store_engines( object_store_manager, @@ -1074,6 +1142,7 @@ mod tests { use cache::build_datanode_layered_cache_registry; use common_base::Plugins; use common_base::readable_size::ReadableSize; + use common_base::secrets::SecretString; use common_config::Configurable; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; @@ -1092,6 +1161,7 @@ mod tests { use mito2::engine::MITO_ENGINE_NAME; use mito2::test_util::{CreateRequestBuilder, build_rows, rows_schema}; use object_store::ObjectStore; + use object_store::config::{S3Config, S3Connection}; use object_store::manager::ObjectStoreManager; use partition::manager::PartitionRuleManagerRef; use query::region_query::{RegionQueryHandlerFactory, RegionQueryHandlerFactoryRef}; @@ -1100,7 +1170,7 @@ mod tests { use store_api::region_request::{PathType, RegionOpenRequest, RegionPutRequest, RegionRequest}; use store_api::storage::RegionId; - use crate::config::{DatanodeOptions, RegionEngineConfig, StorageConfig}; + use crate::config::{DatanodeOptions, ObjectStoreConfig, RegionEngineConfig, StorageConfig}; use crate::datanode::{ Datanode, DatanodeBuilder, validate_object_store_wal_config, validate_region_engine_config, wal_object_store, @@ -1460,6 +1530,80 @@ mod tests { ); } + #[tokio::test] + async fn test_object_store_probe_can_be_disabled() { + // The endpoint does not accept connections, so this only succeeds when the + // probe does not run. + let storage = StorageConfig { + store: ObjectStoreConfig::S3(S3Config { + connection: S3Connection { + bucket: "test".to_string(), + endpoint: Some("http://127.0.0.1:1".to_string()), + region: Some("us-east-1".to_string()), + access_key_id: SecretString::from("test".to_string()), + secret_access_key: SecretString::from("test".to_string()), + ..Default::default() + }, + ..Default::default() + }), + probe_on_startup: false, + ..Default::default() + }; + + DatanodeBuilder::build_object_store_manager(&storage, 1) + .await + .unwrap(); + } + + #[tokio::test] + async fn test_file_store_is_not_probed() { + // The probe is enabled by default, but a File store must skip it. + let data_home = create_temp_dir("object-store-probe-file"); + let storage = StorageConfig { + data_home: data_home.path().to_str().unwrap().to_string(), + ..Default::default() + }; + + DatanodeBuilder::build_object_store_manager(&storage, 1) + .await + .unwrap(); + + // The probe would leave this directory behind if it ran. + assert!(!data_home.path().join(".greptime_probe").exists()); + } + + #[tokio::test] + async fn test_object_store_probe_failure_aborts_build() { + // The endpoint does not accept connections, so the probe write fails and the + // build must fail with it. + let storage = StorageConfig { + store: ObjectStoreConfig::S3(S3Config { + connection: S3Connection { + bucket: "test".to_string(), + endpoint: Some("http://127.0.0.1:1".to_string()), + region: Some("us-east-1".to_string()), + access_key_id: SecretString::from("test".to_string()), + secret_access_key: SecretString::from("test".to_string()), + ..Default::default() + }, + ..Default::default() + }), + ..Default::default() + }; + + let err = DatanodeBuilder::build_object_store_manager(&storage, 1) + .await + .unwrap_err(); + assert_matches!( + err, + Error::ObjectStoreProbe { + name, + step: "write", + .. + } if name == storage.store.config_name() + ); + } + struct CountingRegionQueryHandlerFactory(Arc); impl RegionQueryHandlerFactory for CountingRegionQueryHandlerFactory { diff --git a/src/datanode/src/error.rs b/src/datanode/src/error.rs index aaf1ff4d8df..d5037c2874e 100644 --- a/src/datanode/src/error.rs +++ b/src/datanode/src/error.rs @@ -14,6 +14,7 @@ use std::any::Any; use std::sync::Arc; +use std::time::Duration; use common_error::define_into_tonic_status; use common_error::ext::{BoxedError, ErrorExt, RetryHint}; @@ -472,6 +473,24 @@ pub enum Error { location: Location, }, + #[snafu(display("Failed to run object storage probe for provider '{name}' at step '{step}'"))] + ObjectStoreProbe { + name: String, + step: &'static str, + #[snafu(source)] + error: object_store::Error, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Object storage probe for provider '{name}' timed out after {timeout:?}"))] + ObjectStoreProbeTimeout { + name: String, + timeout: Duration, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Not yet implemented: {what}"))] NotYetImplemented { what: String }, } @@ -554,6 +573,9 @@ impl ErrorExt for Error { SerializeJson { .. } => StatusCode::Internal, ObjectStore { source, .. } => source.status_code(), + ObjectStoreProbe { .. } | ObjectStoreProbeTimeout { .. } => { + StatusCode::StorageUnavailable + } } } @@ -569,7 +591,8 @@ impl ErrorExt for Error { RegionNotReady { .. } | RegionNotFound { .. } => RetryHint::RetryAfterRouteRefresh, RegionBusy { .. } | ConcurrentQueryLimiterClosed { .. } - | ConcurrentQueryLimiterTimeout { .. } => RetryHint::Retryable, + | ConcurrentQueryLimiterTimeout { .. } + | ObjectStoreProbeTimeout { .. } => RetryHint::Retryable, NewPlanDecoder { source, .. } | ExecuteLogicalPlan { source, .. } => { source.retry_hint() } @@ -593,6 +616,9 @@ impl ErrorExt for Error { BuildMetricEngine { source, .. } => source.retry_hint(), ListStorageSsts { source, .. } => source.retry_hint(), ObjectStore { source, .. } => source.retry_hint(), + ObjectStoreProbe { error, .. } => { + object_store::error::retry_hint_from_opendal_error(error) + } _ => RetryHint::NonRetryable, } } diff --git a/src/datanode/src/store.rs b/src/datanode/src/store.rs index 3369de5aedc..484a5ec26c2 100644 --- a/src/datanode/src/store.rs +++ b/src/datanode/src/store.rs @@ -14,11 +14,14 @@ //! object storage utilities +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + use common_telemetry::{info, warn}; +use futures::TryStreamExt; use object_store::factory::new_raw_object_store; use object_store::util::{clean_temp_dir, join_dir, with_instrument_layers, with_retry_layers}; -use object_store::{ATOMIC_WRITE_DIR, ObjectStore}; -use snafu::prelude::*; +use object_store::{ATOMIC_WRITE_DIR, Error as ObjectStoreError, ErrorKind, ObjectStore}; +use snafu::{IntoError, prelude::*}; use crate::config::ObjectStoreConfig; use crate::error::{self, Result}; @@ -84,3 +87,217 @@ pub async fn new_object_store(store: ObjectStoreConfig, data_home: &str) -> Resu let object_store = with_instrument_layers(object_store, true); Ok(object_store) } + +/// The content written by [`probe_object_store`]. +const PROBE_CONTENT: &[u8] = b"greptimedb object store probe"; + +/// The content appended by [`probe_object_store`] to exercise read-modify-write. +const PROBE_SUFFIX: &[u8] = b" - read-modify-write"; + +/// The directory that holds the objects created by [`probe_object_store`]. +const PROBE_DIR: &str = ".greptime_probe"; + +/// The budget of one [`probe_object_store`] call, including the retries an object +/// store makes on top of its 30s request timeout. +pub(crate) const PROBE_TIMEOUT: Duration = Duration::from_secs(180); + +/// The maximum random delay before a probe starts. It is short enough that startup +/// waits at most this delay, and it spreads out the probes of providers that share +/// an object storage. +const PROBE_STAGGER: Duration = Duration::from_millis(500); + +/// The budget of the best-effort cleanup after a timed-out probe, kept short so an +/// unresponsive store cannot block startup a second time. +const PROBE_CLEANUP_TIMEOUT: Duration = Duration::from_secs(10); + +/// Returns a random delay in `[0, PROBE_STAGGER)`. +pub(crate) fn probe_start_delay() -> Duration { + Duration::from_nanos(rand::random_range(0..PROBE_STAGGER.as_nanos() as u64)) +} + +/// Returns a unique key prefix for [`probe_object_store`], so datanodes sharing +/// the same bucket and root do not collide. +pub(crate) fn probe_key_prefix(node_id: u64) -> String { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + format!("{PROBE_DIR}/{node_id}-{}-{nanos}", std::process::id()) +} + +/// Returns the object key [`probe_object_store`] probes under `prefix`. +fn probe_object_key(prefix: &str) -> String { + format!("{prefix}/probe") +} + +/// Checks that `store` supports the operations the storage engines rely on: write, +/// read, overwrite, list and delete. +/// +/// The probe object is removed before returning, after a failed step too. A caller +/// that abandons the check early must call [`remove_probe_object`]. +pub(crate) async fn probe_object_store( + store: &ObjectStore, + name: &str, + prefix: &str, +) -> Result<()> { + let key = probe_object_key(prefix); + + let check = async { + store + .write(&key, PROBE_CONTENT) + .await + .context(error::ObjectStoreProbeSnafu { + name, + step: "write", + })?; + verify_content(store, name, &key, PROBE_CONTENT).await?; + + // Object stores cannot append in place, so this reads the object, appends to + // it and overwrites it, exercising an overwrite of an existing object. + let mut content = store + .read(&key) + .await + .context(error::ObjectStoreProbeSnafu { name, step: "read" })? + .to_vec(); + content.extend_from_slice(PROBE_SUFFIX); + store + .write(&key, content.clone()) + .await + .context(error::ObjectStoreProbeSnafu { + name, + step: "overwrite", + })?; + verify_content(store, name, &key, &content).await?; + + let mut lister = store + .lister_with(&format!("{prefix}/")) + .await + .context(error::ObjectStoreProbeSnafu { name, step: "list" })?; + while let Some(entry) = lister + .try_next() + .await + .context(error::ObjectStoreProbeSnafu { name, step: "list" })? + { + if entry.path() == key { + return Ok(()); + } + } + + Err( + error::ObjectStoreProbeSnafu { name, step: "list" }.into_error(ObjectStoreError::new( + ErrorKind::Unexpected, + format!("'{key}' is not visible in the listing"), + )), + ) + } + .await; + + match store.delete(&key).await { + Ok(()) => check, + Err(err) if check.is_err() => { + warn!( + err; + "Failed to remove the object storage probe object '{}' of provider '{}'", + key, + name + ); + check + } + Err(err) => Err(err).context(error::ObjectStoreProbeSnafu { + name, + step: "delete", + }), + } +} + +async fn verify_content(store: &ObjectStore, name: &str, key: &str, expected: &[u8]) -> Result<()> { + let got = store + .read(key) + .await + .context(error::ObjectStoreProbeSnafu { name, step: "read" })?; + if got.to_vec() != expected { + return Err( + error::ObjectStoreProbeSnafu { name, step: "read" }.into_error(ObjectStoreError::new( + ErrorKind::Unexpected, + format!("content of '{key}' differs from what was written"), + )), + ); + } + Ok(()) +} + +/// Removes the probe object of a probe that did not finish. +/// +/// It has its own short budget, and failures only log: the caller reports the timeout. +pub(crate) async fn remove_probe_object(store: &ObjectStore, prefix: &str) { + let key = probe_object_key(prefix); + match tokio::time::timeout(PROBE_CLEANUP_TIMEOUT, store.delete(&key)).await { + Ok(Ok(())) => {} + Ok(Err(err)) => warn!( + err; + "Failed to remove the object storage probe object '{}'", key + ), + Err(_) => warn!( + "Timed out removing the object storage probe object '{}'", + key + ), + } +} + +#[cfg(test)] +mod tests { + use common_test_util::temp_dir::create_temp_dir; + use object_store::services::Fs; + + use super::*; + + fn new_fs_store(root: &str) -> ObjectStore { + ObjectStore::new(Fs::default().root(root)).unwrap() + } + + #[tokio::test] + async fn test_probe_object_store() { + let dir = create_temp_dir("object-store-probe"); + let store = new_fs_store(dir.path().to_str().unwrap()); + let prefix = probe_key_prefix(1); + + probe_object_store(&store, "fs", &prefix).await.unwrap(); + + // The lister also returns the listed directory itself, so only check that the + // probe object is gone. + let key = format!("{prefix}/probe"); + let mut lister = store.lister_with(&format!("{prefix}/")).await.unwrap(); + while let Some(entry) = lister.try_next().await.unwrap() { + assert_ne!(entry.path(), key); + } + } + + #[tokio::test] + async fn test_probe_object_store_write_failure() { + let dir = create_temp_dir("object-store-probe-write-failure"); + let root = dir.path().join("not-a-directory"); + std::fs::write(&root, b"").unwrap(); + let store = new_fs_store(root.to_str().unwrap()); + + let err = probe_object_store(&store, "broken", &probe_key_prefix(1)) + .await + .unwrap_err(); + assert!( + err.to_string() + .contains("probe for provider 'broken' at step 'write'") + ); + } + + #[tokio::test] + async fn test_remove_probe_object() { + let dir = create_temp_dir("object-store-probe-cleanup"); + let store = new_fs_store(dir.path().to_str().unwrap()); + let prefix = probe_key_prefix(1); + let key = probe_object_key(&prefix); + store.write(&key, PROBE_CONTENT).await.unwrap(); + + remove_probe_object(&store, &prefix).await; + + assert!(store.read(&key).await.is_err()); + } +} diff --git a/tests-integration/src/test_util.rs b/tests-integration/src/test_util.rs index 3dd451b4716..da8d8add687 100644 --- a/tests-integration/src/test_util.rs +++ b/tests-integration/src/test_util.rs @@ -578,6 +578,7 @@ pub(crate) fn create_datanode_opts( storage: StorageConfig { data_home: home_dir, copy_root: None, + probe_on_startup: false, providers, store: default_store, }, diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index c13ada351ea..c7ba62a473f 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -3390,6 +3390,7 @@ pub async fn test_config_api(store_type: StorageType) { let storage = if store_type != StorageType::File { format!( r#"[storage] +probe_on_startup = false type = "{}" providers = [] @@ -3404,6 +3405,7 @@ skip_ssl_validation = false"#, } else { format!( r#"[storage] +probe_on_startup = false type = "{}" providers = []"#, store_type diff --git a/tests/conf/datanode-test.toml.template b/tests/conf/datanode-test.toml.template index 907fcee4ddf..7b0dcebf081 100644 --- a/tests/conf/datanode-test.toml.template +++ b/tests/conf/datanode-test.toml.template @@ -33,6 +33,7 @@ overwrite_entry_start_id = true [storage] type = 'File' data_home = '{data_home}' +probe_on_startup = false [meta_client_options] metasrv_addrs = ['{addrs.metasrv_addr}'] diff --git a/tests/conf/standalone-test.toml.template b/tests/conf/standalone-test.toml.template index 8d7e307d511..149d53ffde6 100644 --- a/tests/conf/standalone-test.toml.template +++ b/tests/conf/standalone-test.toml.template @@ -28,6 +28,7 @@ broker_endpoints = {kafka_wal_broker_endpoints | unescaped} type = 'File' data_home = '{data_home}' copy_root = '{copy_root}' +probe_on_startup = false [grpc] bind_addr = '{addrs.grpc_addr}' From efed847ca6dadd37a76fbbaca2a454621c505a92 Mon Sep 17 00:00:00 2001 From: shuiyisong <113876041+shuiyisong@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:09:33 +0000 Subject: [PATCH 17/19] fix!: enforce sparse primary key schema (#10020) * fix: preserve required sorting for ordinary sparse scans Signed-off-by: shuiyisong * fix: enforce sparse primary key schema Signed-off-by: shuiyisong * test: fix Signed-off-by: shuiyisong --------- Signed-off-by: shuiyisong --- .../function/src/scalars/primary_key.rs | 16 ++- src/mito2/benches/bench_index_update.rs | 3 +- src/mito2/benches/bench_pk_tag_column.rs | 6 +- src/mito2/src/engine/create_test.rs | 40 ++++++ src/mito2/src/memtable/bulk/part.rs | 102 ++++--------- src/mito2/src/read/compat.rs | 64 +++++++-- src/mito2/src/sst/parquet/flat_format.rs | 9 +- src/store-api/src/metadata.rs | 134 +++++++++++++++++- src/table/src/table/scan.rs | 14 ++ .../create/create_with_compression.result | 2 +- 10 files changed, 294 insertions(+), 96 deletions(-) diff --git a/src/common/function/src/scalars/primary_key.rs b/src/common/function/src/scalars/primary_key.rs index f090575f166..37dc5bacde5 100644 --- a/src/common/function/src/scalars/primary_key.rs +++ b/src/common/function/src/scalars/primary_key.rs @@ -354,7 +354,11 @@ mod tests { builder.primary_key_encoding(encoding); for (id, name, ty) in columns { builder.push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new((*name).to_string(), ty.clone(), true), + column_schema: ColumnSchema::new( + (*name).to_string(), + ty.clone(), + !ReservedColumnId::is_reserved(*id), + ), semantic_type: SemanticType::Tag, column_id: *id, }); @@ -440,6 +444,16 @@ mod tests { #[test] fn test_decode_sparse_primary_key() { let columns = vec![ + ( + ReservedColumnId::table_id(), + "__table_id", + ConcreteDataType::uint32_datatype(), + ), + ( + ReservedColumnId::tsid(), + "__tsid", + ConcreteDataType::uint64_datatype(), + ), (10, "k0", ConcreteDataType::string_datatype()), (11, "k1", ConcreteDataType::string_datatype()), ]; diff --git a/src/mito2/benches/bench_index_update.rs b/src/mito2/benches/bench_index_update.rs index a76241fa53f..0d0b1ef6c23 100644 --- a/src/mito2/benches/bench_index_update.rs +++ b/src/mito2/benches/bench_index_update.rs @@ -60,7 +60,8 @@ fn input(shape: &Shape) -> (RegionMetadataRef, HashSet, RecordBatch) { let mut pk = vec![ReservedColumnId::table_id(), ReservedColumnId::tsid()]; let mut inverted_columns = HashSet::new(); let mut add_tag = |id, name: String, data_type, indexed| { - let mut schema = ColumnSchema::new(name, data_type, true).with_inverted_index(false); + let mut schema = ColumnSchema::new(name, data_type, !ReservedColumnId::is_reserved(id)) + .with_inverted_index(false); if indexed && shape.inverted { inverted_columns.insert(id); } diff --git a/src/mito2/benches/bench_pk_tag_column.rs b/src/mito2/benches/bench_pk_tag_column.rs index 9e191a69511..2279067dfdc 100644 --- a/src/mito2/benches/bench_pk_tag_column.rs +++ b/src/mito2/benches/bench_pk_tag_column.rs @@ -77,7 +77,11 @@ fn metadata(tags: u32) -> RegionMetadataRef { primary_key.push(column_id); builder.push_column_metadata(ColumnMetadata { column_id, - column_schema: ColumnSchema::new(name, data_type, true), + column_schema: ColumnSchema::new( + name, + data_type, + !ReservedColumnId::is_reserved(column_id), + ), semantic_type: SemanticType::Tag, }); } diff --git a/src/mito2/src/engine/create_test.rs b/src/mito2/src/engine/create_test.rs index 05696ad6109..57c0c3fa7c2 100644 --- a/src/mito2/src/engine/create_test.rs +++ b/src/mito2/src/engine/create_test.rs @@ -117,6 +117,46 @@ async fn test_engine_column_compression_validation() { assert_eq!(StatusCode::InvalidArguments, err.status_code()); } +#[tokio::test] +async fn test_engine_create_sparse_requires_reserved_columns() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + let mut request = CreateRequestBuilder::new() + .insert_option("primary_key_encoding", "sparse") + .insert_option("sst_format", "flat") + .build(); + let error = engine + .handle_request(region_id, RegionRequest::Create(request.clone())) + .await + .unwrap_err(); + assert_eq!(StatusCode::InvalidArguments, error.status_code()); + assert!( + error + .output_msg() + .contains("sparse primary keys must start with (__table_id, __tsid)") + ); + assert!(!engine.is_region_exists(region_id)); + + let metadata = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse); + request.column_metadatas = metadata.column_metadatas; + request.primary_key = metadata.primary_key; + engine + .handle_request(region_id, RegionRequest::Create(request.clone())) + .await + .unwrap(); + let expected = engine.get_region(region_id).unwrap().metadata(); + reopen_region( + &engine, + region_id, + request.table_dir, + false, + request.options, + ) + .await; + assert_eq!(expected, engine.get_region(region_id).unwrap().metadata()); +} + #[tokio::test] async fn test_engine_create_new_region() { test_engine_create_new_region_with_format(false).await; diff --git a/src/mito2/src/memtable/bulk/part.rs b/src/mito2/src/memtable/bulk/part.rs index 9bcc4238b45..5852d072197 100644 --- a/src/mito2/src/memtable/bulk/part.rs +++ b/src/mito2/src/memtable/bulk/part.rs @@ -1858,19 +1858,17 @@ impl MultiBulkPart { #[cfg(test)] mod tests { - use api::v1::{Row, SemanticType, WriteHint}; + use api::v1::{Row, WriteHint}; use datafusion_common::ScalarValue; use datatypes::arrow::array::{ BinaryArray, DictionaryArray, Float64Array, TimestampMillisecondArray, }; use datatypes::arrow::datatypes::UInt32Type; use datatypes::prelude::{ConcreteDataType, Value}; - use datatypes::schema::ColumnSchema; use mito_codec::row_converter::build_primary_key_codec; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; - use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; - use store_api::storage::RegionId; + use store_api::metadata::RegionMetadataBuilder; use store_api::storage::consts::ReservedColumnId; use table::predicate::Predicate; @@ -2594,47 +2592,30 @@ mod tests { KeyValues::new(metadata.as_ref(), mutation).unwrap() } + fn sparse_metadata_for_test() -> RegionMetadataRef { + let mut metadata = metadata_for_test().as_ref().clone(); + metadata.column_metadatas[1].column_schema.data_type = ConcreteDataType::string_datatype(); + let mut builder = RegionMetadataBuilder::from_existing(metadata); + let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding( + PrimaryKeyEncoding::Sparse, + ); + for column in reserved.column_metadatas.into_iter().take(2) { + builder.push_column_metadata(column); + } + builder + .primary_key(vec![ + ReservedColumnId::table_id(), + ReservedColumnId::tsid(), + 0, + 1, + ]) + .primary_key_encoding(PrimaryKeyEncoding::Sparse); + Arc::new(builder.build().unwrap()) + } + #[test] fn test_bulk_part_converter_sparse_primary_key_encoding() { - use api::v1::SemanticType; - use datatypes::schema::ColumnSchema; - use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; - use store_api::storage::RegionId; - - let mut builder = RegionMetadataBuilder::new(RegionId::new(123, 456)); - builder - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("k0", ConcreteDataType::string_datatype(), false), - semantic_type: SemanticType::Tag, - column_id: 0, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("k1", ConcreteDataType::string_datatype(), false), - semantic_type: SemanticType::Tag, - column_id: 1, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ), - semantic_type: SemanticType::Timestamp, - column_id: 2, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("v0", ConcreteDataType::int64_datatype(), true), - semantic_type: SemanticType::Field, - column_id: 3, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("v1", ConcreteDataType::float64_datatype(), true), - semantic_type: SemanticType::Field, - column_id: 4, - }) - .primary_key(vec![0, 1]) - .primary_key_encoding(PrimaryKeyEncoding::Sparse); - let metadata = Arc::new(builder.build().unwrap()); + let metadata = sparse_metadata_for_test(); let primary_key_codec = build_primary_key_codec(&metadata); let schema = to_flat_sst_arrow_schema( @@ -2923,40 +2904,7 @@ mod tests { #[test] fn test_convert_bulk_part_sparse_encoding() { - let mut builder = RegionMetadataBuilder::new(RegionId::new(123, 456)); - builder - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("k0", ConcreteDataType::string_datatype(), false), - semantic_type: SemanticType::Tag, - column_id: 0, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("k1", ConcreteDataType::string_datatype(), false), - semantic_type: SemanticType::Tag, - column_id: 1, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ), - semantic_type: SemanticType::Timestamp, - column_id: 2, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("v0", ConcreteDataType::int64_datatype(), true), - semantic_type: SemanticType::Field, - column_id: 3, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("v1", ConcreteDataType::float64_datatype(), true), - semantic_type: SemanticType::Field, - column_id: 4, - }) - .primary_key(vec![0, 1]) - .primary_key_encoding(PrimaryKeyEncoding::Sparse); - let metadata = Arc::new(builder.build().unwrap()); + let metadata = sparse_metadata_for_test(); let primary_key_codec = build_primary_key_codec(&metadata); diff --git a/src/mito2/src/read/compat.rs b/src/mito2/src/read/compat.rs index 6f9a4a36e50..1d4a7f5457b 100644 --- a/src/mito2/src/read/compat.rs +++ b/src/mito2/src/read/compat.rs @@ -1344,8 +1344,19 @@ mod tests { ], &[], ); + let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding( + PrimaryKeyEncoding::Sparse, + ); + actual_metadata.primary_key = reserved.primary_key.into_iter().take(2).collect(); + actual_metadata + .column_metadatas + .extend(reserved.column_metadatas.into_iter().take(2)); actual_metadata.primary_key_encoding = PrimaryKeyEncoding::Sparse; - let actual_metadata = Arc::new(actual_metadata); + let actual_metadata = Arc::new( + RegionMetadataBuilder::from_existing(actual_metadata) + .build() + .unwrap(), + ); let mut expected_metadata = (*actual_metadata).clone(); for column in expected_metadata.column_metadatas.iter_mut() { @@ -1373,7 +1384,10 @@ mod tests { .unwrap() .unwrap(); - let sparse_k1 = encode_sparse_key(&[]); + let mut sparse_k1 = Vec::new(); + SparsePrimaryKeyCodec::schemaless() + .encode_internal(42, 7, &mut sparse_k1) + .unwrap(); let input_columns: Vec = vec![ Arc::new(Int64Array::from(vec![100, 200])), Arc::new(TimestampMillisecondArray::from_iter_values([1000, 2000])), @@ -1384,8 +1398,10 @@ mod tests { OpType::Put as u8, ])), ]; - let input_schema = - to_flat_sst_arrow_schema(&actual_metadata, &FlatSchemaOptions::default()); + let input_schema = to_flat_sst_arrow_schema( + &actual_metadata, + &FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Sparse), + ); let input_batch = RecordBatch::try_new(input_schema, input_columns).unwrap(); let result = compat_batch.compat(input_batch).unwrap(); @@ -1402,8 +1418,10 @@ mod tests { OpType::Put as u8, ])), ]; - let output_schema = - to_flat_sst_arrow_schema(&expected_metadata, &FlatSchemaOptions::default()); + let output_schema = to_flat_sst_arrow_schema( + &expected_metadata, + &FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Sparse), + ); let expected_batch = RecordBatch::try_new(output_schema, expected_columns).unwrap(); assert_eq!(expected_batch, result); @@ -1520,6 +1538,16 @@ mod tests { columns[0] = json; let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)?; for encoding in [PrimaryKeyEncoding::Dense, PrimaryKeyEncoding::Sparse] { + let batch = if encoding == PrimaryKeyEncoding::Sparse { + let mut key = Vec::new(); + SparsePrimaryKeyCodec::schemaless().encode_internal(42, 7, &mut key)?; + let mut columns = batch.columns().to_vec(); + columns[primary_key_column_index(batch.num_columns())] = + build_flat_test_pk_array(&[&key, &key]); + RecordBatch::try_new(batch.schema(), columns)? + } else { + batch.clone() + }; for missing_json in [false, true] { let source = if missing_json { new_metadata( @@ -1533,12 +1561,12 @@ mod tests { } else { metadata.as_ref().clone() }; - let mut builder = RegionMetadataBuilder::from_existing(source); - builder.primary_key_encoding(encoding); - let actual = Arc::new(builder.build()?); - let mut builder = RegionMetadataBuilder::from_existing(metadata.as_ref().clone()); - builder.primary_key_encoding(encoding); - builder.push_column_metadata(ColumnMetadata { + let mut actual_builder = RegionMetadataBuilder::from_existing(source); + actual_builder.primary_key_encoding(encoding); + let mut expected_builder = + RegionMetadataBuilder::from_existing(metadata.as_ref().clone()); + expected_builder.primary_key_encoding(encoding); + expected_builder.push_column_metadata(ColumnMetadata { column_schema: ColumnSchema::new( "added", ConcreteDataType::int64_datatype(), @@ -1550,7 +1578,17 @@ mod tests { semantic_type: SemanticType::Field, column_id: 2, }); - let expected = Arc::new(builder.build()?); + if encoding == PrimaryKeyEncoding::Sparse { + let reserved = test_util::sst_util::sst_region_metadata_with_encoding(encoding); + for builder in [&mut actual_builder, &mut expected_builder] { + builder.primary_key(reserved.primary_key[..2].to_vec()); + for column in reserved.column_metadatas.iter().take(2) { + builder.push_column_metadata(column.clone()); + } + } + } + let actual = Arc::new(actual_builder.build()?); + let expected = Arc::new(expected_builder.build()?); let read_columns = ReadColumns::new([0, 1, 2]); let mapper = FlatProjectionMapper::new_with_json2_rewrite_targets( &expected, diff --git a/src/mito2/src/sst/parquet/flat_format.rs b/src/mito2/src/sst/parquet/flat_format.rs index 3abba4d2db6..3f40f7ab3a1 100644 --- a/src/mito2/src/sst/parquet/flat_format.rs +++ b/src/mito2/src/sst/parquet/flat_format.rs @@ -1355,7 +1355,14 @@ mod tests { column_id: col_id, }); - let primary_key: Vec = (0..num_tags as u32).collect(); + let mut primary_key: Vec = (0..num_tags as u32).collect(); + if encoding == PrimaryKeyEncoding::Sparse { + let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding(encoding); + primary_key.splice(0..0, reserved.primary_key.into_iter().take(2)); + for column in reserved.column_metadatas.into_iter().take(2) { + builder.push_column_metadata(column); + } + } builder.primary_key(primary_key); builder.primary_key_encoding(encoding); builder.build().unwrap() diff --git a/src/store-api/src/metadata.rs b/src/store-api/src/metadata.rs index 55ff240ee4a..f2bac9785f3 100644 --- a/src/store-api/src/metadata.rs +++ b/src/store-api/src/metadata.rs @@ -31,6 +31,7 @@ use common_macro::stack_trace_debug; use datatypes::arrow; use datatypes::arrow::datatypes::FieldRef; use datatypes::extension::json::json2_metadata_with_updated_settings; +use datatypes::prelude::ConcreteDataType; use datatypes::schema::{ColumnSchema, FulltextOptions, Schema, SchemaRef}; use datatypes::types::TimestampType; use itertools::Itertools; @@ -39,10 +40,11 @@ use serde::{Deserialize, Deserializer, Serialize}; use snafu::{Location, OptionExt, ResultExt, Snafu, ensure}; use crate::codec::PrimaryKeyEncoding; +use crate::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME}; use crate::region_request::{ AddColumn, AddColumnLocation, AlterKind, ModifyColumnType, SetIndexOption, UnsetIndexOption, }; -use crate::storage::consts::is_internal_column; +use crate::storage::consts::{ReservedColumnId, is_internal_column}; use crate::storage::{ColumnId, RegionId}; pub type Result = std::result::Result; @@ -476,6 +478,16 @@ impl RegionMetadata { } ); + if self.primary_key_encoding == PrimaryKeyEncoding::Sparse { + ensure!( + self.primary_key + .starts_with(&[ReservedColumnId::table_id(), ReservedColumnId::tsid()]), + InvalidMetaSnafu { + reason: "sparse primary keys must start with (__table_id, __tsid)", + } + ); + } + if !self.primary_key.is_empty() { let mut pk_ids = HashSet::with_capacity(self.primary_key.len()); // Checks column ids in the primary key is valid. @@ -523,6 +535,27 @@ impl RegionMetadata { } ); + if self.primary_key_encoding == PrimaryKeyEncoding::Sparse { + let schema = &column.column_schema; + let valid = if *column_id == ReservedColumnId::table_id() { + schema.name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME + && schema.data_type == ConcreteDataType::uint32_datatype() + && !schema.is_nullable() + } else if *column_id == ReservedColumnId::tsid() { + schema.name == DATA_SCHEMA_TSID_COLUMN_NAME + && schema.data_type == ConcreteDataType::uint64_datatype() + && !schema.is_nullable() + } else { + !ReservedColumnId::is_reserved(*column_id) && schema.data_type.is_string() + }; + ensure!( + valid, + InvalidMetaSnafu { + reason: format!("invalid sparse primary key column {}", schema.name), + } + ); + } + pk_ids.insert(column_id); } } @@ -1388,6 +1421,105 @@ mod test { builder.build().unwrap() } + #[test] + fn test_sparse_primary_key_requires_reserved_columns() { + for primary_key in [vec![], vec![1]] { + let mut metadata = build_test_region_metadata(); + if primary_key.is_empty() { + metadata.column_metadatas[0].semantic_type = SemanticType::Field; + } + metadata.primary_key = primary_key; + let mut builder = RegionMetadataBuilder::from_existing(metadata); + builder.primary_key_encoding(PrimaryKeyEncoding::Sparse); + let error = builder.build().unwrap_err(); + assert_eq!(error.status_code(), StatusCode::InvalidArguments); + assert!( + error + .to_string() + .contains("sparse primary keys must start with (__table_id, __tsid)") + ); + } + } + + #[test] + fn test_sparse_reserved_primary_key_contract() { + let mut builder = RegionMetadataBuilder::from_existing(build_test_region_metadata()); + builder.primary_key_encoding(PrimaryKeyEncoding::Sparse); + builder.column_metadatas[0].column_schema.data_type = ConcreteDataType::string_datatype(); + for (name, column_id, data_type) in [ + ( + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, + ReservedColumnId::table_id(), + ConcreteDataType::uint32_datatype(), + ), + ( + DATA_SCHEMA_TSID_COLUMN_NAME, + ReservedColumnId::tsid(), + ConcreteDataType::uint64_datatype(), + ), + ] { + builder.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new(name, data_type, false), + semantic_type: SemanticType::Tag, + column_id, + }); + } + builder.primary_key(vec![ + ReservedColumnId::table_id(), + ReservedColumnId::tsid(), + 1, + ]); + let metadata = builder.build().unwrap(); + let json = serde_json::to_string(&metadata).unwrap(); + assert_eq!( + metadata, + serde_json::from_str::(&json).unwrap() + ); + + for case in 0..12 { + let mut builder = RegionMetadataBuilder::from_existing(metadata.clone()); + match case { + 0 => builder.primary_key.swap(0, 1), + 1 => { + builder.primary_key.remove(0); + builder.column_metadatas.remove(3); + } + 2 => builder.column_metadatas[3].column_schema.set_nullable(), + 3 => { + builder.column_metadatas[3].column_schema.data_type = + ConcreteDataType::uint64_datatype() + } + 4 => builder.column_metadatas[4].column_schema.name = "wrong_name".into(), + 5 => { + builder.column_metadatas[0].column_schema.data_type = + ConcreteDataType::int64_datatype() + } + 6 => { + builder.primary_key.remove(1); + builder.column_metadatas.remove(4); + } + 7 => builder.column_metadatas[4].column_schema.set_nullable(), + 8 => { + builder.column_metadatas[4].column_schema.data_type = + ConcreteDataType::uint32_datatype() + } + 9 => builder.column_metadatas[3].semantic_type = SemanticType::Field, + 10 => builder.column_metadatas[4].semantic_type = SemanticType::Field, + 11 => { + builder.primary_key[0] = 10; + builder.primary_key[1] = 11; + builder.column_metadatas[3].column_id = 10; + builder.column_metadatas[4].column_id = 11; + } + _ => unreachable!(), + } + assert_eq!( + builder.build().unwrap_err().status_code(), + StatusCode::InvalidArguments + ); + } + } + #[test] fn test_region_metadata() { let region_metadata = build_test_region_metadata(); diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs index cae9f5f042c..2dd501e678f 100644 --- a/src/table/src/table/scan.rs +++ b/src/table/src/table/scan.rs @@ -717,6 +717,7 @@ mod test { use datatypes::schema::{ColumnSchema, Schema, SchemaRef}; use datatypes::vectors::{Int32Vector, TimestampMillisecondVector, VectorRef}; use futures::TryStreamExt; + use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME; use store_api::region_engine::{ @@ -1108,7 +1109,14 @@ mod test { /// order or hash partition columns. #[test] fn test_metric_projection_claims_only_projected_row_key_prefix() { + for encoding in [PrimaryKeyEncoding::Dense, PrimaryKeyEncoding::Sparse] { + check_metric_projection_ordering(encoding); + } + } + + fn check_metric_projection_ordering(encoding: PrimaryKeyEncoding) { let mut builder = RegionMetadataBuilder::new(RegionId::new(1234, 5691)); + builder.primary_key_encoding(encoding); for (name, column_id) in [ ( DATA_SCHEMA_TABLE_ID_COLUMN_NAME, @@ -1139,6 +1147,12 @@ mod test { let metadata = Arc::new(builder.build().unwrap()); for (projection, partitioned_by_tsid, claimed, unclaimed) in [ + ( + vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME, "A", "ts"], + false, + vec![vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME]], + vec![vec!["A"], vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME, "ts"]], + ), // The logical projection drops the row key prefix, so `A` is not a prefix of the // row key and neither `A` nor `ts` is ordered. ( diff --git a/tests/cases/standalone/common/create/create_with_compression.result b/tests/cases/standalone/common/create/create_with_compression.result index 77a21288c94..a1c91a6e7ea 100644 --- a/tests/cases/standalone/common/create/create_with_compression.result +++ b/tests/cases/standalone/common/create/create_with_compression.result @@ -109,7 +109,7 @@ CREATE TABLE bad ( host STRING PRIMARY KEY COMPRESSION WITH (level = 3) ) WITH ('primary_key_encoding' = 'sparse'); -Error: 1004(InvalidArguments), Invalid region options, COMPRESSION on tag column host requires flat SST format and dense primary key encoding +Error: 1004(InvalidArguments), Invalid metadata, sparse primary keys must start with (__table_id, __tsid) CREATE TABLE compressed_tags ( ts TIMESTAMP TIME INDEX, From e87766d7ef64a33ea02fce31d2cb2700903f0cef Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Thu, 29 Oct 2026 00:00:07 +0000 Subject: [PATCH 18/19] ci: reduce repeated Windows and fuzz tests on pull requests (#10043) * ci: reduce repeated Windows and fuzz tests on pull requests Signed-off-by: WenyXu * ci: use the nightly merge label as the enqueue opt-in Signed-off-by: WenyXu * ci: log nightly merge decisions for dry-run verification Signed-off-by: WenyXu * ci: gate expensive jobs on GitHub script tests Signed-off-by: WenyXu * ci: grant pull request write permission for nightly label sync Signed-off-by: WenyXu * ci: run platform checks on schedule or manual dispatch Signed-off-by: WenyXu * test(ci): update PR gate count for scheduled platform checks Signed-off-by: WenyXu --------- Signed-off-by: WenyXu --- .../actions/github-script-tests/action.yml | 52 +++++++++ .github/ci/README.md | 12 +- .github/heavy-ci.md | 28 +++++ .github/nightly-merge.md | 6 +- .github/scripts/heavy-ci-policy.test.cjs | 105 ++++++++++++++++++ .github/scripts/tests/nightly-merge.test.cjs | 23 +++- .github/scripts/tests/test_ci_slash.py | 2 +- .github/workflows/checks.yml | 41 +------ .github/workflows/integration.yml | 62 +++++++---- .github/workflows/nightly-merge.yml | 14 ++- .github/workflows/rust.yml | 71 ++++-------- 11 files changed, 290 insertions(+), 126 deletions(-) create mode 100644 .github/actions/github-script-tests/action.yml create mode 100644 .github/heavy-ci.md create mode 100644 .github/scripts/heavy-ci-policy.test.cjs diff --git a/.github/actions/github-script-tests/action.yml b/.github/actions/github-script-tests/action.yml new file mode 100644 index 00000000000..4e3d797a95c --- /dev/null +++ b/.github/actions/github-script-tests/action.yml @@ -0,0 +1,52 @@ +name: GitHub Script Tests +description: Validate CI scripts before starting expensive jobs +runs: + using: composite + steps: + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Run Node GitHub script tests + shell: bash + run: node --test .github/scripts/query-regression-comment.test.cjs .github/scripts/heavy-ci-policy.test.cjs .github/scripts/tests/nightly-merge.test.cjs + - name: Setup uv + uses: astral-sh/setup-uv@v3 + with: + version: "latest" + - name: Run check-version script tests + shell: bash + run: uv run --no-project python .github/scripts/check-version-test.py + - name: Run release Linux architecture tests + shell: bash + run: python3 .github/scripts/release-linux-architectures-test.py + - name: Run previous-release-tag script tests + shell: bash + run: python3 .github/scripts/previous-release-tag-test.py + - name: Run enterprise license check tests + shell: bash + run: python3 scripts/check-enterprise-license-test.py + - name: Run fuzz orchestration script tests + shell: bash + run: .github/scripts/run-fuzz-targets-test.sh + - name: Run CI comment-command tests + shell: bash + run: python3 .github/scripts/tests/test_ci_slash.py + - name: Run CI scope gate tests + shell: bash + run: python3 .github/ci/tests/test_ci_scope.py + - name: Run metric snapshot benchmark tests + shell: bash + run: python3 -m unittest discover -s .github/scripts/tests -p 'test_metric_snapshot*.py' + - name: Run query-regression Python tooling tests + shell: bash + run: | + python3 tests/perf/test_query_regression_runner_compaction_toctou.py + python3 tests/perf/test_query_regression_runner_otlp_trace_load.py + python3 tests/perf/test_query_regression_summary_otlp.py + python3 tests/perf/test_query_regression_case_selection.py + python3 tests/perf/test_query_regression_nightly_refs.py + python3 tests/perf/test_query_regression_slash.py + python3 tests/perf/test_aliyun_ecs_runner_scripts.py + python3 tests/perf/test_ci_runner_scripts.py + python3 tests/perf/test_agent_observability_summary.py + python3 tests/perf/test_tracesbench_summary.py diff --git a/.github/ci/README.md b/.github/ci/README.md index 07de1fcae7b..1ead30842ec 100644 --- a/.github/ci/README.md +++ b/.github/ci/README.md @@ -1,9 +1,10 @@ # Integration CI admission gate -`integration.yml` runs its expensive jobs — fuzz, export/import E2E, the sqlness -KvBackend legs — on every non-draft pull request. Most pull requests cannot -affect any of them. This directory decides which of those jobs start, using only -the diff. +`integration.yml` filters its expensive jobs — fuzz, export/import E2E, and the +sqlness KvBackend legs — by the diff. Fuzz additionally follows the event policy +in [Heavy CI scheduling](../heavy-ci.md): PR opening or ready-for-review events, +scheduled runs, and explicit manual profiles. A scope verdict cannot override +that event policy. The gate can only *skip* work, never add it, and it fails open: when the verdict is missing or uncertain, every gated job runs. @@ -53,7 +54,8 @@ three minutes, less than the cost of getting its verdict wrong. First match wins: 1. **Forced** — `merge_group`, `schedule`, `workflow_dispatch`, the `ci:full` - label or `CI_SCOPE_FORCE_ALL`. Everything runs. + label or `CI_SCOPE_FORCE_ALL`. All scope outputs allow execution; job event + conditions and manual profile selection still apply. 2. **Too large to judge** — more than 300 changed files. Everything runs. 3. **Always-run file changed** — `Cargo.toml`, `Cargo.lock`, `tests-fuzz/**`, this directory, or anything else that changes what the suites build or how diff --git a/.github/heavy-ci.md b/.github/heavy-ci.md new file mode 100644 index 00000000000..4b0d17bc3a3 --- /dev/null +++ b/.github/heavy-ci.md @@ -0,0 +1,28 @@ +# Heavy CI scheduling + +Checks, Rust CI, and Integration CI each run the shared GitHub script test +action before expensive builds and tests. A failed, skipped, or cancelled +script-test job blocks those jobs, including manually dispatched runs. Each +workflow runs its own preflight so it does not wait on another workflow run. + +Rust CI keeps the Windows compilation check on PRs and merge groups. Windows +nextest and Windows SQLness run in the existing Nightly CI workflow, which also +supports manual dispatch. Its existing schedule is Tuesday through Friday at +07:00 Asia/Shanghai, not every day. No new Windows test job is added. + +Integration CI admits fuzz when a non-draft PR is opened or marked ready for +review, selecting suites with the existing diff-scope classifier. Its weekday +schedule (23:00 Asia/Shanghai, Monday through Friday) runs all fuzz suites. Ordinary pushes and reopening do not run fuzz; core +integration checks still run. Merge groups continue to skip fuzz. + +Re-running an ordinary push-triggered Integration CI run does not enable fuzz. +A new push can cancel an earlier ready-for-review run. Use an explicit fuzz +profile through the CI entry points below when later changes need fuzz coverage. + +For a same-repository branch, use **Run workflow** and select `fuzz_profile` +(`standalone`, `distributed`, `chaos`, or `all`). The default `none` runs core +integration without fuzz. The existing `/ci fuzz ...` commands remain available +for same-repository draft PRs with their existing authorization rules. + +Validate job admission with `node --test .github/scripts/heavy-ci-policy.test.cjs`. +These tests verify triggering decisions, not runner availability or performance. diff --git a/.github/nightly-merge.md b/.github/nightly-merge.md index a8699a9b159..08b523dbab2 100644 --- a/.github/nightly-merge.md +++ b/.github/nightly-merge.md @@ -2,14 +2,16 @@ The PR template opts new PRs into the `merge nightly` label. The Nightly Merge workflow reconciles the label on PR creation, edits, and reopening. Existing PRs -without the checkbox are not opted in. Unchecking removes the label; it does not +without the checkbox can opt in by adding the label manually; label sync leaves +their labels unchanged. Unchecking removes the label; it does not request an immediate merge or cancel an existing queue entry/auto-merge request. Every day at 02:10, 03:10, 04:10, 05:10, 06:10, 07:10, and 08:10 Asia/Shanghai (UTC+8), the workflow enqueues up to five eligible PRs targeting `main` per run, oldest first. Already queued PRs do not count toward this limit. GitHub may delay scheduled runs. -PRs must still have the checkbox and label, be approved and clean, and have all +The label alone controls nightly opt-in; the enqueue job does not check the PR +body. PRs must be approved and clean, and have all review threads resolved. Drafts are skipped. Already queued PRs and manually enabled auto-merge requests are left alone; Maintainers can use **Merge when ready** to proceed earlier. Unready PRs wait for a later diff --git a/.github/scripts/heavy-ci-policy.test.cjs b/.github/scripts/heavy-ci-policy.test.cjs new file mode 100644 index 00000000000..093ff8c636b --- /dev/null +++ b/.github/scripts/heavy-ci-policy.test.cjs @@ -0,0 +1,105 @@ +const { readFileSync } = require('node:fs'); +const { resolve } = require('node:path'); +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const workflows = resolve(__dirname, '../workflows'); +const integration = readFileSync(resolve(workflows, 'integration.yml'), 'utf8'); +const suites = ['fuzztest', 'unstable-fuzztest', 'distributed-fuzztest', 'distributed-fuzztest-with-chaos']; +const prerequisites = ['prepare-fuzz-targets', 'build-greptime-ci']; +function enabled(job, { event = 'pull_request', action = 'synchronize', draft = false, attempt = 1, profile = 'none', repository = 'GreptimeTeam/greptimedb', outputs = {}, results = {}, cancelled = false, workflow = integration } = {}) { + const block = workflow.split(` ${job}:\n`)[1].split(/\n [a-z][\w-]*:/)[0]; + if (block.includes("needs['github-script-tests']")) { + assert.match(block, /^ needs: \[.*github-script-tests.*\]/m); + } + const expression = block.match(/^ if: \$\{\{ (.+) \}\}/m)[1]; + // These job guards use only operators whose semantics match JS for this fixture. + return new Function('github', 'inputs', 'needs', 'cancelled', `return (${expression});`)( + { repository, event_name: event, event: { action, pull_request: { draft } }, run_attempt: attempt }, + { fuzz_profile: profile, ci_command: false }, + { scope: { outputs }, ...Object.fromEntries(['github-script-tests', 'build', ...prerequisites].map(name => [name, { result: results[name] || 'success' }])) }, + () => cancelled + ); +} +test('fuzz event policy on ready PR admission and schedule, not every update', () => { + for (const job of [...suites, ...prerequisites]) { + for (const action of ['opened', 'ready_for_review']) assert.equal(enabled(job, { action }), true, job); + for (const action of ['synchronize', 'reopened']) assert.equal(enabled(job, { action }), false, job); + assert.equal(enabled(job, { event: 'schedule' }), true, job); + assert.equal(enabled(job, { event: 'merge_group' }), false, job); + assert.equal(enabled(job, { attempt: 2 }), false, job); + assert.equal(enabled(job, { action: 'opened', draft: true }), false, job); + assert.equal(enabled(job, { attempt: 2, draft: true }), false, job); + assert.equal(enabled(job, { event: 'schedule', repository: 'fork/greptimedb' }), false, job); + } +}); +test('manual profiles select only their suite and all required build jobs', () => { + const expected = { none: [], standalone: suites.slice(0, 2), distributed: [suites[2]], chaos: [suites[3]], all: suites }; + for (const [profile, jobs] of Object.entries(expected)) { + assert.deepEqual(suites.filter(job => enabled(job, { event: 'workflow_dispatch', profile })), jobs); + for (const job of prerequisites) assert.equal(enabled(job, { event: 'workflow_dispatch', profile }), profile !== 'none'); + } +}); +test('core integration tests still run on PR updates and merge groups', () => { + for (const job of ['build', 'sqlness', 'export-import-v2-e2e', 'run-multi-lang-tests']) { + assert.equal(enabled(job), true, job); + assert.equal(enabled(job, { event: 'merge_group' }), true, job); + } +}); +test('Windows compilation stays in Rust CI; test coverage remains in Nightly CI', () => { + const rust = readFileSync(resolve(workflows, 'rust.yml'), 'utf8'); + const nightly = readFileSync(resolve(workflows, 'nightly-ci.yml'), 'utf8'); + assert.match(rust, /^ check-windows:/m); + assert.doesNotMatch(rust, /^ test-windows:/m); + assert.match(nightly, /^ test-on-windows:/m); + assert.match(nightly, /^ sqlness-windows:/m); + assert.match(nightly, /cargo nextest run -F dashboard/); + assert.match(nightly, /^ workflow_dispatch:/m); +}); + +test('scope exclusions and dependency failures compose with the event policy', () => { + const gates = { + 'prepare-fuzz-targets': 'any_fuzz', 'build-greptime-ci': 'build_ci_needed', + fuzztest: 'fuzz_standalone', 'unstable-fuzztest': 'fuzz_unstable', + 'distributed-fuzztest': 'fuzz_distributed', 'distributed-fuzztest-with-chaos': 'fuzz_chaos' + }; + for (const [job, gate] of Object.entries(gates)) { + assert.equal(enabled(job, { action: 'opened', outputs: { [gate]: 'false' } }), false, job); + assert.equal(enabled(job, { action: 'opened', outputs: {} }), true, job); + assert.equal(enabled(job, { outputs: { [gate]: 'true' } }), false, job); + assert.equal(enabled(job, { action: 'opened', cancelled: true }), false, job); + } + for (const job of suites) { + for (const result of ['failure', 'skipped', 'cancelled']) { + assert.equal(enabled(job, { action: 'opened', results: { 'prepare-fuzz-targets': result } }), false, job); + const build = job === 'fuzztest' ? 'build' : 'build-greptime-ci'; + assert.equal(enabled(job, { action: 'opened', results: { [build]: result } }), false, job); + } + } +}); + +test('script tests must pass before any expensive integration job can start', () => { + const jobs = ['build', 'sqlness', 'sqlness-kvbackend', 'export-import-v2-e2e', + 'run-multi-lang-tests', 'compat', ...prerequisites, ...suites]; + for (const job of jobs) { + assert.equal(enabled(job, { action: 'opened' }), true, job); + for (const result of ['failure', 'skipped', 'cancelled']) { + assert.equal(enabled(job, { action: 'opened', results: { 'github-script-tests': result } }), false, job); + } + } +}); + +test('script tests gate expensive Rust and Checks jobs', () => { + for (const [file, jobs] of [ + ['rust.yml', ['clippy', 'check-riscv64', 'check-windows', 'test', 'coverage']], + ['checks.yml', ['check']] + ]) { + const workflow = readFileSync(resolve(workflows, file), 'utf8'); + for (const job of jobs) { + const event = job === 'coverage' ? 'merge_group' : 'workflow_dispatch'; + assert.equal(enabled(job, { workflow, event }), true, job); + for (const result of ['failure', 'skipped', 'cancelled']) { + assert.equal(enabled(job, { workflow, event, results: { 'github-script-tests': result } }), false, job); + } + } + } +}); diff --git a/.github/scripts/tests/nightly-merge.test.cjs b/.github/scripts/tests/nightly-merge.test.cjs index 885876f5610..753b458ebce 100644 --- a/.github/scripts/tests/nightly-merge.test.cjs +++ b/.github/scripts/tests/nightly-merge.test.cjs @@ -61,16 +61,22 @@ async function run({ sync = false, body = checked, labels = ['merge nightly'], const summary = { addHeading() { return this; }, addTable(rows) { calls.push(['summary', rows]); return this; }, async write() {} }; await scripts[sync ? 0 : 1](github, { repo: { owner: 'GreptimeTeam', repo: 'greptimedb' }, payload: { pull_request: { number: 1 } } }, - { summary, warning() {}, setFailed: message => calls.push(['failed', message]) }, + { summary, info() {}, warning() {}, setFailed: message => calls.push(['failed', message]) }, { env: { DRY_RUN: String(dryRun) } }); return calls; } +test('label sync grants PR label write permission without checking out PR code', () => { + const syncJob = workflow.split(' sync-label:\n')[1].split(' enqueue:\n')[0]; + assert.match(syncJob, /^ pull-requests: write$/m); + assert.doesNotMatch(syncJob, /uses: actions\/checkout/); +}); + test('template opts in and checkbox edits reconcile only the nightly label', async () => { assert.ok(readFileSync(resolve(__dirname, '../../pull_request_template.md'), 'utf8').includes(checked)); assert.deepEqual(await run({ sync: true, labels: ['bug'] }), [['add', ['merge nightly']]]); assert.deepEqual(await run({ sync: true }), []); - for (const body of [checked.replace('[x]', '[ ]'), '', null, `> ${checked}`]) { + for (const body of [checked.replace('[x]', '[ ]')]) { assert.deepEqual(await run({ sync: true, body }), [['remove', 'merge nightly']]); } assert.deepEqual(await run({ sync: true, body: checked.replace('[x]', '[X]'), labels: [] }), [['add', ['merge nightly']]]); @@ -83,7 +89,7 @@ test('eligible PR is enqueued with its checked head; dry run performs no mutatio test('each eligibility gate independently prevents enqueueing', async () => { for (const options of [ - { body: checked.replace('[x]', '[ ]') }, { labels: [] }, + { labels: [] }, { current: { draft: true } }, { current: { state: 'closed' } }, { current: { base: { ref: 'release/v1.3' } } }, { detail: { reviewDecision: 'REVIEW_REQUIRED' } }, { detail: { reviewDecision: 'CHANGES_REQUESTED' } }, { detail: { mergeStateStatus: 'BLOCKED' } }, { detail: { mergeStateStatus: 'UNKNOWN' } }, @@ -106,3 +112,14 @@ test('per-run cap and individual failures do not prevent later candidates', asyn assert.equal(calls.filter(c => c[0] === 'enqueue').length, 2); assert.equal(calls.filter(c => c[0] === 'failed').length, 1); }); + +test('label-only opt-in survives PRs without a template and does not require a checkbox', async () => { + for (const body of ['', null, 'Existing PR description', `> ${checked}`]) { + assert.deepEqual(await run({ sync: true, body }), []); + assert.deepEqual(await run({ sync: true, body, labels: [] }), []); + assert.equal((await run({ body })).filter(call => call[0] === 'enqueue').length, 1); + assert.equal((await run({ body, labels: [] })).some(call => call[0] === 'enqueue'), false); + } + // The label is authoritative for admission, even before checkbox synchronization. + assert.equal((await run({ body: checked.replace('[x]', '[ ]') })).some(call => call[0] === 'enqueue'), true); +}); diff --git a/.github/scripts/tests/test_ci_slash.py b/.github/scripts/tests/test_ci_slash.py index e551a4f5297..2d9c7bccc84 100644 --- a/.github/scripts/tests/test_ci_slash.py +++ b/.github/scripts/tests/test_ci_slash.py @@ -136,7 +136,7 @@ class CiSlashTest(unittest.TestCase): def test_fork_rerun_gates_cover_standard_jobs(self): import re - for name, count in [("rust", 7), ("integration", 7), ("checks", 6), ("docs", 3)]: + for name, count in [("rust", 6), ("integration", 8), ("checks", 6), ("docs", 3)]: workflow = (SCRIPT.parents[1] / "workflows" / (name + ".yml")).read_text() gates = re.findall(r"^ if:.*github.run_attempt > 1.*$", workflow, re.MULTILINE) self.assertEqual(len(gates), count, name) diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 941f36d9726..1f14d8851cc 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -71,43 +71,7 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: 24 - - name: Run Node GitHub script tests - run: node --test .github/scripts/query-regression-comment.test.cjs .github/scripts/tests/nightly-merge.test.cjs - - name: Setup uv - uses: astral-sh/setup-uv@v3 - with: - version: "latest" - - name: Run check-version script tests - run: uv run --no-project python .github/scripts/check-version-test.py - - name: Run release Linux architecture tests - run: python3 .github/scripts/release-linux-architectures-test.py - - name: Run previous-release-tag script tests - run: python3 .github/scripts/previous-release-tag-test.py - - name: Run enterprise license check tests - run: python3 scripts/check-enterprise-license-test.py - - name: Run fuzz orchestration script tests - run: .github/scripts/run-fuzz-targets-test.sh - - name: Run CI comment-command tests - run: python3 .github/scripts/tests/test_ci_slash.py - - name: Run CI scope gate tests - run: python3 .github/ci/tests/test_ci_scope.py - - name: Run metric snapshot benchmark tests - run: python3 -m unittest discover -s .github/scripts/tests -p 'test_metric_snapshot*.py' - - name: Run query-regression Python tooling tests - run: | - python3 tests/perf/test_query_regression_runner_compaction_toctou.py - python3 tests/perf/test_query_regression_runner_otlp_trace_load.py - python3 tests/perf/test_query_regression_summary_otlp.py - python3 tests/perf/test_query_regression_case_selection.py - python3 tests/perf/test_query_regression_nightly_refs.py - python3 tests/perf/test_query_regression_slash.py - python3 tests/perf/test_aliyun_ecs_runner_scripts.py - python3 tests/perf/test_ci_runner_scripts.py - python3 tests/perf/test_agent_observability_summary.py - python3 tests/perf/test_tracesbench_summary.py + - uses: ./.github/actions/github-script-tests scope-rules: if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} @@ -127,7 +91,8 @@ jobs: run: python3 .github/ci/ci_scope_rules.py --check-paths check: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + needs: [github-script-tests] name: Check runs-on: ${{ matrix.os }} strategy: diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 6106e5a2860..00c3f52a034 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -21,7 +21,7 @@ on: default: false type: boolean fuzz_profile: - description: Fuzz profile selected by /ci fuzz + description: Fuzz profile for a manual run or /ci fuzz required: false default: none type: choice @@ -42,6 +42,17 @@ concurrency: cancel-in-progress: true jobs: + github-script-tests: + if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + name: GitHub Script Tests (Integration CI) + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: ./.github/actions/github-script-tests + # Which jobs this gate skips, and why: .github/ci/README.md. scope: name: CI Scope @@ -94,7 +105,8 @@ jobs: python3 .github/ci/ci_scope.py "${args[@]}" build: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + needs: [github-script-tests] name: Build GreptimeDB binaries runs-on: ${{ matrix.os }} strategy: @@ -155,9 +167,9 @@ jobs: version: current sqlness: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} name: Sqlness Test (${{ matrix.mode.name }}) - needs: build + needs: [github-script-tests, build] runs-on: ${{ matrix.os }} strategy: fail-fast: false @@ -213,9 +225,9 @@ jobs: # required checks, so they are the only ones this gate may skip. They run # the same cases as the `Basic` leg, so the diff only matters when it can # reach the backend itself; the merge queue runs them regardless. - if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.sqlness_kvbackend != 'false' }} + if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.sqlness_kvbackend != 'false' }} name: Sqlness Test (${{ matrix.mode.name }}) - needs: [scope, build] + needs: [github-script-tests, scope, build] runs-on: ${{ matrix.os }} strategy: fail-fast: false @@ -267,9 +279,9 @@ jobs: retention-days: 3 export-import-v2-e2e: - if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.export_import_v2 != 'false' }} + if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.export_import_v2 != 'false' }} name: Export/Import V2 E2E Test - needs: [scope, build] + needs: [github-script-tests, scope, build] runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -337,9 +349,9 @@ jobs: retention-days: 3 run-multi-lang-tests: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} name: Run Multi-language SDK Tests - needs: build + needs: [github-script-tests, build] uses: ./.github/workflows/run-multi-lang-tests.yml with: artifact-name: bins @@ -362,9 +374,9 @@ jobs: run: python3 .github/scripts/update-compat-versions.py --check --published-only --check-anchors compat: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule' || (github.event_name == 'pull_request' && (github.event.action == 'ready_for_review' || (github.event.action == 'opened' && github.event.pull_request.draft == false)))) }} + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule' || (github.event_name == 'pull_request' && (github.event.action == 'ready_for_review' || (github.event.action == 'opened' && github.event.pull_request.draft == false)))) }} name: Compatibility Test (recent releases) - needs: build + needs: [github-script-tests, build] runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -401,10 +413,12 @@ jobs: path: /tmp/sqlness-compat* retention-days: 3 + # Fuzz runs on opening a ready PR, marking it ready, manual dispatch, and + # the scheduled main run. Synchronize events keep the core integration tests. prepare-fuzz-targets: - if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile != 'none') && needs.scope.outputs.any_fuzz != 'false' }} + if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile != 'none'))) && needs.scope.outputs.any_fuzz != 'false' }} name: Prepare Fuzz Targets - needs: [scope] + needs: [github-script-tests, scope] runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -517,9 +531,9 @@ jobs: if-no-files-found: error fuzztest: - if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') && needs.build.result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_standalone != 'false' }} + if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all'))) && needs.build.result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_standalone != 'false' }} name: Fuzz Test (Standalone, ${{ matrix.group.name }}) - needs: [build, prepare-fuzz-targets, scope] + needs: [github-script-tests, build, prepare-fuzz-targets, scope] runs-on: ubuntu-latest timeout-minutes: 60 strategy: @@ -598,9 +612,9 @@ jobs: artifact-name: fuzz-standalone-${{ matrix.group.id }} unstable-fuzztest: - if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_unstable != 'false' }} + if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all'))) && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_unstable != 'false' }} name: Unstable Fuzz Test - needs: [build-greptime-ci, prepare-fuzz-targets, scope] + needs: [github-script-tests, build-greptime-ci, prepare-fuzz-targets, scope] runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -658,9 +672,9 @@ jobs: artifact-name: fuzz-unstable-standalone build-greptime-ci: - if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command && inputs.fuzz_profile != 'none') || github.event_name == 'merge_group') && needs.scope.outputs.build_ci_needed != 'false' }} + if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile != 'none'))) && needs.scope.outputs.build_ci_needed != 'false' }} name: Build GreptimeDB binary (profile-CI) - needs: [scope] + needs: [github-script-tests, scope] runs-on: ${{ matrix.os }} strategy: matrix: @@ -719,10 +733,10 @@ jobs: version: current distributed-fuzztest: - if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all') && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_distributed != 'false' }} + if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all'))) && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_distributed != 'false' }} name: Fuzz Test (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }}) runs-on: ubuntu-latest - needs: [build-greptime-ci, prepare-fuzz-targets, scope] + needs: [github-script-tests, build-greptime-ci, prepare-fuzz-targets, scope] timeout-minutes: 60 strategy: fail-fast: false @@ -958,10 +972,10 @@ jobs: docker system prune -f distributed-fuzztest-with-chaos: - if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all') && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_chaos != 'false' }} + if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all'))) && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_chaos != 'false' }} name: Fuzz Test with Chaos (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }}) runs-on: ubuntu-latest - needs: [build-greptime-ci, prepare-fuzz-targets, scope] + needs: [github-script-tests, build-greptime-ci, prepare-fuzz-targets, scope] timeout-minutes: 60 strategy: fail-fast: false diff --git a/.github/workflows/nightly-merge.yml b/.github/workflows/nightly-merge.yml index ff6d5874ff1..6188d12cd3f 100644 --- a/.github/workflows/nightly-merge.yml +++ b/.github/workflows/nightly-merge.yml @@ -23,7 +23,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 permissions: - pull-requests: read + # PR label mutations require pull-request write permission. + pull-requests: write issues: write concurrency: group: nightly-merge-label-${{ github.event.pull_request.number }} @@ -36,7 +37,10 @@ jobs: const { owner, repo } = context.repo; const issue_number = context.payload.pull_request.number; const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: issue_number }); - const selected = /^- \[[xX]\] Merge during the nightly window \s*$/m.test(pr.body || ''); + const checkbox = /^- \[([ xX])\] Merge during the nightly window \s*$/m.exec(pr.body || ''); + // PRs without the template manage their opt-in through the label. + if (!checkbox) return; + const selected = checkbox[1].toLowerCase() === 'x'; const label = 'merge nightly'; const labeled = pr.labels.some(item => item.name === label); if (selected && !labeled) { @@ -73,11 +77,10 @@ jobs: if (!candidate.pull_request || enqueued >= 5) continue; const number = candidate.number; try { - // Fetch current body/labels, not the earlier list snapshot. + // Fetch current labels and PR state, not the earlier list snapshot. const { data: current } = await github.rest.pulls.get({ owner, repo, pull_number: number }); if (current.state !== 'open' || current.draft || current.base.ref !== 'main' || - !current.labels.some(label => label.name === 'merge nightly') || - !/^- \[[xX]\] Merge during the nightly window \s*$/m.test(current.body || '')) { + !current.labels.some(label => label.name === 'merge nightly')) { rows.push([String(number), 'Skipped: not opted in, draft, closed, or not targeting main']); continue; } @@ -134,5 +137,6 @@ jobs: core.setFailed('Some PRs could not be processed; see workflow logs.'); } } + for (const [number, result] of rows) core.info(`PR #${number}: ${result}`); await core.summary.addHeading(dryRun ? 'Nightly merge (dry run)' : 'Nightly merge') .addTable([['PR', 'Result'], ...rows]).write(); diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index d1b93a60e43..842fa306c4e 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -31,6 +31,17 @@ concurrency: cancel-in-progress: true jobs: + github-script-tests: + if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + name: GitHub Script Tests (Rust CI) + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: ./.github/actions/github-script-tests + fmt: if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} name: Rustfmt @@ -50,7 +61,8 @@ jobs: run: make fmt-check clippy: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + needs: [github-script-tests] name: Clippy runs-on: ubuntu-latest timeout-minutes: 60 @@ -94,7 +106,9 @@ jobs: run: make check-udeps check-riscv64: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + # Keep platform coverage on the weekday schedule and allow manual checks. + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') }} + needs: [github-script-tests] name: Check riscv64 build runs-on: ubuntu-latest timeout-minutes: 90 @@ -120,7 +134,9 @@ jobs: run: cargo check --locked --workspace --all-targets --features servers/dashboard --target riscv64gc-unknown-linux-gnu check-windows: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + # Keep platform coverage on the weekday schedule and allow manual checks. + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') }} + needs: [github-script-tests] name: Check Windows build runs-on: windows-2022 timeout-minutes: 60 @@ -148,48 +164,6 @@ jobs: env: RUSTFLAGS: "-D warnings" - test-windows: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false) }} - name: Test Windows - runs-on: windows-2022 - timeout-minutes: 90 - env: - CARGO_INCREMENTAL: 0 - CARGO_PROFILE_DEV_DEBUG: 0 - CARGO_PROFILE_TEST_DEBUG: 0 - RUSTFLAGS: "-D warnings -C linker=lld-link" - RUST_BACKTRACE: 1 - RUST_MIN_STACK: 8388608 # 8MB - steps: - - run: git config --global core.autocrlf false - - uses: actions/checkout@v4 - with: - persist-credentials: false - - uses: ./.github/actions/setup-cyborg - - uses: taiki-e/install-action@v2 - with: - tool: protoc@3.23.4 - - uses: KyleMayes/install-llvm-action@v1 - with: - version: "14.0" - - uses: actions-rust-lang/setup-rust-toolchain@v1 - with: - cache: false - - name: Rust Cache - uses: Swatinem/rust-cache@v2 - with: - shared-key: "test-windows" - cache-all-crates: "true" - save-if: ${{ github.ref == 'refs/heads/main' }} - - name: Install Cargo Nextest - uses: taiki-e/install-action@nextest - - name: Install WSL distribution - uses: Vampire/setup-wsl@v2 - with: - distribution: Ubuntu-22.04 - - name: Run Windows tests - run: cargo nextest run --locked --workspace -F dashboard --no-fail-fast - conflict-check: if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} name: Check for conflict @@ -202,10 +176,10 @@ jobs: uses: olivernybroe/action-conflict-finder@v4.0 test: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'merge_group' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'merge_group' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} runs-on: ubuntu-22.04-arm timeout-minutes: 60 - needs: [conflict-check, clippy, fmt, check-udeps] + needs: [github-script-tests, conflict-check, clippy, fmt, check-udeps] steps: - uses: actions/checkout@v4 with: @@ -258,7 +232,8 @@ jobs: UNITTEST_LOG_DIR: "__unittest_logs" coverage: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'merge_group' }} + if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'merge_group' }} + needs: [github-script-tests] runs-on: ubuntu-22.04-8-cores timeout-minutes: 60 steps: From ec240ad7e64f92f0a1c308d9c3f6834ba605edb2 Mon Sep 17 00:00:00 2001 From: shuiyisong <113876041+shuiyisong@users.noreply.github.com> Date: Thu, 29 Oct 2026 05:45:07 +0000 Subject: [PATCH 19/19] feat(mito): preserve ordinary sparse keys across writes and schema changes (#9920) * feat(mito): support ordinary sparse append tables Ordinary append tables need sparse keys for optional series tags, including JSON2 values written through row and bulk paths. This change validates sparse tag schemas and defaults, keeps key identity stable when nullable tags are added, selects flat SST storage, and preserves append-mode semantics when reopening regions. Includes storage, bulk-write, schema-evolution and repartition tests, plus SQL and mixed-version fixtures. Existing metric-engine sparse key handling remains supported. This is the storage prerequisite for exemplar ingestion; it introduces no exemplar protocol endpoint. Signed-off-by: shuiyisong * fix(mito): preserve reserved sparse key semantics Signed-off-by: shuiyisong * fix(mito): clarify sparse errors and avoid panics Signed-off-by: shuiyisong * perf(mito): reduce sparse key validation overhead Signed-off-by: shuiyisong * fix: sqlness Signed-off-by: shuiyisong * perf(mito-codec): reduce sparse validation cost Signed-off-by: shuiyisong * refactor(mito): remove ordinary sparse support Signed-off-by: shuiyisong --------- Signed-off-by: shuiyisong --- src/datatypes/src/extension/json.rs | 3 +- src/metric-engine/src/engine/read.rs | 121 ++++- src/mito-codec/src/row_converter.rs | 27 +- src/mito-codec/src/row_converter/sparse.rs | 326 ++++++++++-- .../src/row_converter/sparse/checked.rs | 13 +- src/mito2/Cargo.toml | 4 + src/mito2/benches/bench_sparse_write.rs | 391 +++++++++++++++ src/mito2/src/compaction/scheduler_test.rs | 1 + .../src/engine/bulk_insert_validation_test.rs | 309 +++++++++++- src/mito2/src/engine/create_test.rs | 23 +- src/mito2/src/engine/scan_test.rs | 265 ++++++++++ src/mito2/src/manifest/manager.rs | 7 +- src/mito2/src/memtable/bulk/part.rs | 468 ++++++++++++++++-- src/mito2/src/read/compat.rs | 274 +++++++--- src/mito2/src/region.rs | 3 + src/mito2/src/region/opener.rs | 36 +- src/mito2/src/region/options.rs | 44 +- src/mito2/src/request.rs | 18 +- src/mito2/src/sst/primary_key.rs | 23 +- src/mito2/src/test_util.rs | 1 + src/mito2/src/test_util/scheduler_util.rs | 1 + src/store-api/src/mito_engine_options.rs | 2 +- src/store-api/src/region_engine.rs | 11 +- src/table/src/table/scan.rs | 42 +- tests-integration/src/tests/instance_test.rs | 37 ++ .../common/types/json/exemplar_sparse.result | 47 ++ .../common/types/json/exemplar_sparse.sql | 15 + .../cases/exemplar_legacy_keys/case.toml | 8 + .../cases/exemplar_legacy_keys/setup.sql | 17 + .../cases/exemplar_legacy_keys/verify.result | 85 ++++ .../cases/exemplar_legacy_keys/verify.sql | 13 + 31 files changed, 2370 insertions(+), 265 deletions(-) create mode 100644 src/mito2/benches/bench_sparse_write.rs create mode 100644 tests/cases/standalone/common/types/json/exemplar_sparse.result create mode 100644 tests/cases/standalone/common/types/json/exemplar_sparse.sql create mode 100644 tests/compatibility/cases/exemplar_legacy_keys/case.toml create mode 100644 tests/compatibility/cases/exemplar_legacy_keys/setup.sql create mode 100644 tests/compatibility/cases/exemplar_legacy_keys/verify.result create mode 100644 tests/compatibility/cases/exemplar_legacy_keys/verify.sql diff --git a/src/datatypes/src/extension/json.rs b/src/datatypes/src/extension/json.rs index 2e86d7791c5..ef72f40e997 100644 --- a/src/datatypes/src/extension/json.rs +++ b/src/datatypes/src/extension/json.rs @@ -117,7 +117,8 @@ fn parse_version(metadata: &str) -> crate::error::Result> { } /// Returns the remainder field of a JSON2 v2 root. -pub(crate) fn json2_remainder_field(field: &Field) -> crate::error::Result> { +/// Validates the layout version and remainder type, returning `None` for legacy layouts. +pub fn json2_remainder_field(field: &Field) -> crate::error::Result> { let layout = Json2PhysicalLayout::try_from_root(field)?; if !layout.is_version_2() { return Ok(None); diff --git a/src/metric-engine/src/engine/read.rs b/src/metric-engine/src/engine/read.rs index 8d8d32fcc6c..b10fcfb12ad 100644 --- a/src/metric-engine/src/engine/read.rs +++ b/src/metric-engine/src/engine/read.rs @@ -16,7 +16,8 @@ use std::sync::Arc; use api::v1::SemanticType; use common_telemetry::{debug, error, tracing}; -use datafusion::logical_expr::{self, Expr}; +use datafusion::common::ScalarValue; +use datafusion::logical_expr::{self, Expr, Operator}; use snafu::{OptionExt, ResultExt}; use store_api::metadata::{RegionMetadataBuilder, RegionMetadataRef}; use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME; @@ -60,10 +61,31 @@ impl MetricEngineInner { .with_label_values(&["read_physical"]) .start_timer(); - self.mito + // PromQL scans physical regions with a table-ID filter to access `__tsid`. + let logical_region = request + .filters + .iter() + .flat_map(logical_expr::utils::split_conjunction) + .any(|expr| { + let Expr::BinaryExpr(expr) = expr else { + return false; + }; + expr.op == Operator::Eq + && matches!( + (expr.left.as_ref(), expr.right.as_ref()), + (Expr::Column(column), Expr::Literal(ScalarValue::UInt32(Some(_)), _)) + | (Expr::Literal(ScalarValue::UInt32(Some(_)), _), Expr::Column(column)) + if column.name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME + ) + }); + let mut scanner = self + .mito .handle_query(region_id, request) .await - .context(MitoReadOperationSnafu) + .context(MitoReadOperationSnafu)?; + scanner.set_logical_region(logical_region); + + Ok(scanner) } async fn read_logical_region( @@ -399,6 +421,99 @@ mod test { ); } + #[tokio::test] + async fn test_single_logical_region_scan_properties() { + let env = TestEnv::new().await; + env.init_metric_region().await; + + let physical_region_id = env.default_physical_region_id(); + let logical_region_id = env.default_logical_region_id(); + let table_id = logical_expr::col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME); + let table_filter = table_id + .clone() + .eq(logical_expr::lit(logical_region_id.table_id())); + let job_filter = logical_expr::col("job").eq(logical_expr::lit("api")); + for (filters, logical_region) in [ + (vec![], false), + (vec![table_filter.clone()], true), + ( + vec![logical_expr::lit(logical_region_id.table_id()).eq(table_id.clone())], + true, + ), + (vec![job_filter.clone(), table_filter.clone()], true), + (vec![job_filter.clone().and(table_filter.clone())], true), + ( + vec![ + table_filter.clone().and( + job_filter + .clone() + .or(logical_expr::col("job").eq(logical_expr::lit("db"))), + ), + ], + true, + ), + ( + vec![ + table_filter + .clone() + .or(table_id.clone().eq(logical_expr::lit(4u32))), + ], + false, + ), + (vec![table_filter.clone().or(job_filter.clone())], false), + ( + vec![table_id.clone().not_eq(logical_expr::lit(4u32))], + false, + ), + (vec![table_id.clone().gt(logical_expr::lit(4u32))], false), + ( + vec![table_id.eq(logical_expr::lit(ScalarValue::UInt32(None)))], + false, + ), + (vec![job_filter], false), + ] { + let scanner = env + .metric() + .handle_query( + physical_region_id, + ScanRequest { + filters: filters.clone(), + distribution: Some(TimeSeriesDistribution::PerSeries), + ..Default::default() + }, + ) + .await + .unwrap(); + assert_eq!( + scanner.properties().is_logical_region(), + logical_region, + "{filters:?}" + ); + } + + let scanner = env + .metric() + .handle_query(logical_region_id, ScanRequest::default()) + .await + .unwrap(); + assert!(scanner.properties().is_logical_region()); + + // A table-ID filter alone cannot grant metric guarantees to a Mito scan. + let scanner = env + .mito() + .handle_query( + utils::to_data_region_id(physical_region_id), + ScanRequest { + filters: vec![table_filter], + distribution: Some(TimeSeriesDistribution::PerSeries), + ..Default::default() + }, + ) + .await + .unwrap(); + assert!(!scanner.properties().is_logical_region()); + } + #[tokio::test] async fn test_transform_scan_req() { let env = TestEnv::new().await; diff --git a/src/mito-codec/src/row_converter.rs b/src/mito-codec/src/row_converter.rs index 60bbf1935e0..8a42c1f1190 100644 --- a/src/mito-codec/src/row_converter.rs +++ b/src/mito-codec/src/row_converter.rs @@ -175,24 +175,35 @@ pub fn build_primary_key_codec_with_fields( /// Finds the checked boundary of an Option, shared by Dense and Sparse. /// This validates framing, not UTF-8; consumers decoding strings validate UTF-8. pub(crate) fn encoded_string_len(bytes: &[u8]) -> memcomparable::Result { + encoded_string_info::(bytes).map(|(len, _)| len) +} + +/// Checks string framing and optionally detects ASCII in the same pass. +/// Framing-only readers compile out payload inspection and ignore the ASCII result. +pub(crate) fn encoded_string_info( + bytes: &[u8], +) -> memcomparable::Result<(usize, bool)> { match bytes.first().copied().ok_or(memcomparable::Error::Eof)? { - 0 => return Ok(1), + 0 => return Ok((1, true)), 1 => {} marker => return Err(memcomparable::Error::InvalidTagEncoding(marker as usize)), } match bytes.get(1).copied().ok_or(memcomparable::Error::Eof)? { - 0 => return Ok(2), + 0 => return Ok((2, true)), 1 => {} marker => return Err(memcomparable::Error::InvalidBytesEncoding(marker)), } - let mut end = 2; - loop { - let chunk = bytes.get(end..end + 9).ok_or(memcomparable::Error::Eof)?; - end += 9; - match chunk[8] { - 1..=8 => return Ok(end), + let mut ascii_bits = 0_u64; + for (index, chunk) in bytes[2..].as_chunks::<9>().0.iter().enumerate() { + let [word @ .., marker] = *chunk; + if CHECK_ASCII { + ascii_bits |= u64::from_ne_bytes(word); + } + match marker { + 1..=8 => return Ok((2 + (index + 1) * 9, ascii_bits & 0x8080_8080_8080_8080 == 0)), 9 => {} marker => return Err(memcomparable::Error::InvalidBytesEncoding(marker)), } } + Err(memcomparable::Error::Eof) } diff --git a/src/mito-codec/src/row_converter/sparse.rs b/src/mito-codec/src/row_converter/sparse.rs index 5497a7dc034..9cb16f406cd 100644 --- a/src/mito-codec/src/row_converter/sparse.rs +++ b/src/mito-codec/src/row_converter/sparse.rs @@ -23,7 +23,7 @@ use datatypes::prelude::ConcreteDataType; use datatypes::value::{Value, ValueRef}; use memcomparable::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; -use snafu::{ResultExt, ensure}; +use snafu::{OptionExt, ResultExt, ensure}; use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::RegionMetadataRef; use store_api::storage::ColumnId; @@ -39,30 +39,28 @@ use crate::row_converter::dense::SortField; pub use crate::row_converter::sparse::checked::SparsePrimaryKeyView; use crate::row_converter::{CompositeValues, PrimaryKeyCodec, PrimaryKeyFilter}; -/// A codec for sparse key of metrics. +/// A codec for sparse keys with reserved table ID and TSID columns. /// /// ## Encoding format /// Each primary key is encoded as a sequence of `(column_id, value)` pairs: -/// - The first two fields are always the reserved `table_id` (uint32) and `tsid` (uint64). -/// - User-defined labels follow, sorted by **column name** in lexicographical order. -/// - Null values are omitted (not encoded). +/// - Keys start with reserved `table_id` (uint32) and `tsid` (uint64). +/// - String tags follow the reserved prefix; null tags are omitted. /// /// The `column_id` is encoded as a 4-byte big-endian integer, and the value is encoded /// using memcomparable serialization. /// -/// `decode_leftmost` always decodes the first value from the encoded bytes (i.e., the -/// `table_id` field). +/// `decode_leftmost` returns the reserved `table_id` value. /// /// ## Requirements -/// It requires the input primary key columns are sorted by the column name in lexicographical order. -/// It encodes the column id of the physical region. +/// Encoders supply columns in the layout's order using stable physical-region IDs. #[derive(Clone, Debug)] pub struct SparsePrimaryKeyCodec { inner: Arc, } -#[derive(Debug)] +#[derive(Debug, Clone)] struct SparsePrimaryKeyCodecInner { + fields: Option>, // Internal fields table_id_field: SortField, // Internal fields @@ -146,6 +144,66 @@ const TSID_VALUE_OFFSET: usize = COLUMN_ID_ENCODE_SIZE + 5 + COLUMN_ID_ENCODE_SI /// Byte offset where tag columns start (after 9-byte table_id + 13-byte tsid entries). const TAGS_START_OFFSET: usize = COLUMN_ID_ENCODE_SIZE + 5 + COLUMN_ID_ENCODE_SIZE + 9; +/// Validates complete sparse keys without materializing their values. +/// +/// Scratch buffers retain capacity between keys; validation does not depend on region metadata. +#[derive(Default)] +pub struct SparsePrimaryKeyValidator { + column_ids: Vec, + label_buf: Vec, +} + +impl SparsePrimaryKeyValidator { + /// Checks the prefix, all label framing and UTF-8, and rejects duplicate or reserved labels. + pub fn validate(&mut self, bytes: &[u8]) -> Result<()> { + self.column_ids.clear(); + validate_prefix(bytes)?; + let mut remaining = &bytes[TAGS_START_OFFSET..]; + while !remaining.is_empty() { + let id = remaining.first_chunk::().context( + InvalidSparsePrimaryKeySnafu { + reason: "truncated label column id", + }, + )?; + let column_id = u32::from_be_bytes(*id); + ensure!( + !ReservedColumnId::is_reserved(column_id), + InvalidSparsePrimaryKeySnafu { + reason: "reserved column id in sparse labels", + } + ); + self.column_ids.push(column_id); + let encoded = &remaining[COLUMN_ID_ENCODE_SIZE..]; + let (length, ascii) = crate::row_converter::encoded_string_info::(encoded) + .context(DeserializeFieldSnafu)?; + let encoded = &encoded[..length]; + // Framing is already checked; ASCII needs no unchunking to establish valid UTF-8. + if !ascii { + self.label_buf.clear(); + self.label_buf.reserve(length); + Deserializer::new(&encoded[1..]) + .read_bytes_into(&mut self.label_buf) + .context(DeserializeFieldSnafu)?; + std::str::from_utf8(&self.label_buf).map_err(|_| { + InvalidSparsePrimaryKeySnafu { + reason: "label is not valid UTF-8", + } + .build() + })?; + } + remaining = &remaining[COLUMN_ID_ENCODE_SIZE + length..]; + } + self.column_ids.sort_unstable(); + ensure!( + !self.column_ids.windows(2).any(|pair| pair[0] == pair[1]), + InvalidSparsePrimaryKeySnafu { + reason: "duplicate column id in sparse key", + } + ); + Ok(()) + } +} + /// Inline capacity for the small-vec fast path of [`SparseOffsetsCache`]. /// /// Most sparse primary keys carry only a handful of tags, so a linear scan @@ -225,6 +283,7 @@ impl SparsePrimaryKeyCodec { let columns = columns_ids.collect(); Self { inner: Arc::new(SparsePrimaryKeyCodecInner { + fields: None, table_id_field: SortField::new(ConcreteDataType::uint32_datatype()), tsid_field: SortField::new(ConcreteDataType::uint64_datatype()), label_field: SortField::new(ConcreteDataType::string_datatype()), @@ -235,7 +294,16 @@ impl SparsePrimaryKeyCodec { /// Creates a new [`SparsePrimaryKeyCodec`] instance. pub fn new(region_metadata: &RegionMetadataRef) -> Self { - Self::from_columns(region_metadata.primary_key_columns().map(|c| c.column_id)) + let fields = region_metadata + .primary_key_columns() + .map(|c| { + ( + c.column_id, + SortField::new(c.column_schema.data_type.clone()), + ) + }) + .collect(); + Self::with_fields(fields) } /// Returns a new [`SparsePrimaryKeyCodec`] instance. @@ -244,6 +312,7 @@ impl SparsePrimaryKeyCodec { pub fn schemaless() -> Self { Self { inner: Arc::new(SparsePrimaryKeyCodecInner { + fields: None, table_id_field: SortField::new(ConcreteDataType::uint32_datatype()), tsid_field: SortField::new(ConcreteDataType::uint64_datatype()), label_field: SortField::new(ConcreteDataType::string_datatype()), @@ -252,27 +321,20 @@ impl SparsePrimaryKeyCodec { } } - /// Creates a new [`SparsePrimaryKeyCodec`] instance with additional label `fields`. + /// Creates a schema-aware sparse codec. pub fn with_fields(fields: Vec<(ColumnId, SortField)>) -> Self { - Self { - inner: Arc::new(SparsePrimaryKeyCodecInner { - columns: Some(fields.iter().map(|f| f.0).collect()), - table_id_field: SortField::new(ConcreteDataType::uint32_datatype()), - tsid_field: SortField::new(ConcreteDataType::uint64_datatype()), - label_field: SortField::new(ConcreteDataType::string_datatype()), - }), - } + let mut codec = Self::from_columns(fields.iter().map(|f| f.0)); + Arc::make_mut(&mut codec.inner).fields = Some(fields); + codec } /// Returns the field of the given column id. fn get_field(&self, column_id: ColumnId) -> Option<&SortField> { - // if the `columns` is not specified, all unknown columns is primary key(label field). if let Some(columns) = &self.inner.columns && !columns.contains(&column_id) { return None; } - match column_id { RESERVED_COLUMN_ID_TABLE_ID => Some(&self.inner.table_id_field), RESERVED_COLUMN_ID_TSID => Some(&self.inner.tsid_field), @@ -405,32 +467,50 @@ impl SparsePrimaryKeyCodec { /// Decodes the given bytes into a [`SparseValues`]. fn decode_sparse(&self, bytes: &[u8]) -> Result { - let mut deserializer = Deserializer::new(bytes); let mut values = SparseValues::with_capacity(16); - - let column_id = u32::deserialize(&mut deserializer).context(DeserializeFieldSnafu)?; - let value = self.inner.table_id_field.deserialize(&mut deserializer)?; - values.insert(column_id, value); - - let column_id = u32::deserialize(&mut deserializer).context(DeserializeFieldSnafu)?; - let value = self.inner.tsid_field.deserialize(&mut deserializer)?; - values.insert(column_id, value); - while deserializer.has_remaining() { - let column_id = u32::deserialize(&mut deserializer).context(DeserializeFieldSnafu)?; - let value = self.inner.label_field.deserialize(&mut deserializer)?; + let (table_id, tsid) = self.decode_ids(bytes)?; + values.insert(RESERVED_COLUMN_ID_TABLE_ID, Value::UInt32(table_id)); + values.insert(RESERVED_COLUMN_ID_TSID, Value::UInt64(tsid)); + let mut remaining = &bytes[TAGS_START_OFFSET..]; + while !remaining.is_empty() { + let id = remaining.first_chunk::().context( + InvalidSparsePrimaryKeySnafu { + reason: "truncated label column id", + }, + )?; + let column_id = u32::from_be_bytes(*id); + ensure!( + !ReservedColumnId::is_reserved(column_id), + InvalidSparsePrimaryKeySnafu { + reason: "reserved column id in sparse labels" + } + ); + let encoded = &remaining[COLUMN_ID_ENCODE_SIZE..]; + let length = + crate::row_converter::encoded_string_len(encoded).context(DeserializeFieldSnafu)?; + let value = self + .inner + .label_field + .deserialize(&mut Deserializer::new(&encoded[..length]))?; + ensure!( + values.get(&column_id).is_none(), + InvalidSparsePrimaryKeySnafu { + reason: "duplicate column id in sparse key", + } + ); values.insert(column_id, value); + remaining = &encoded[length..]; } - Ok(values) } - /// Decodes the given bytes into a [`Value`]. + /// Decodes the reserved table ID from the key prefix. fn decode_leftmost(&self, bytes: &[u8]) -> Result> { - let mut deserializer = Deserializer::new(bytes); - // Skip the column id. - deserializer.advance(COLUMN_ID_ENCODE_SIZE); - let value = self.inner.table_id_field.deserialize(&mut deserializer)?; - Ok(Some(value)) + if bytes.is_empty() { + return Ok(None); + } + self.decode_ids(bytes) + .map(|(table_id, _)| Some(Value::UInt32(table_id))) } /// Returns the offset of the given column id in the given primary key. @@ -529,11 +609,18 @@ impl SparsePrimaryKeyCodec { } impl PrimaryKeyCodec for SparsePrimaryKeyCodec { - fn encode_key_value(&self, _key_value: &KeyValue, _buffer: &mut Vec) -> Result<()> { - UnsupportedOperationSnafu { - err_msg: "The encode_key_value method is not supported in SparsePrimaryKeyCodec.", - } - .fail() + fn encode_key_value(&self, key_value: &KeyValue, buffer: &mut Vec) -> Result<()> { + let fields = self + .inner + .fields + .as_ref() + .context(UnsupportedOperationSnafu { + err_msg: "raw row encoding requires primary key metadata", + })?; + self.encode_to_vec( + fields.iter().map(|f| f.0).zip(key_value.primary_keys()), + buffer, + ) } fn encode_values(&self, values: &[(ColumnId, Value)], buffer: &mut Vec) -> Result<()> { @@ -581,6 +668,21 @@ impl PrimaryKeyCodec for SparsePrimaryKeyCodec { } } +fn validate_prefix(pk: &[u8]) -> Result<()> { + ensure!( + pk.len() >= TAGS_START_OFFSET + && pk[..COLUMN_ID_ENCODE_SIZE] == RESERVED_COLUMN_ID_TABLE_ID.to_be_bytes() + && pk[TSID_VALUE_OFFSET - COLUMN_ID_ENCODE_SIZE..TSID_VALUE_OFFSET] + == RESERVED_COLUMN_ID_TSID.to_be_bytes() + && pk[TABLE_ID_VALUE_OFFSET] == 1 + && pk[TSID_VALUE_OFFSET] == 1, + InvalidSparsePrimaryKeySnafu { + reason: "invalid table_id/tsid prefix" + } + ); + Ok(()) +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -846,6 +948,12 @@ mod tests { assert!(!buffer.is_empty()); let result = codec.decode_leftmost(&buffer).unwrap().unwrap(); assert_eq!(result, Value::UInt32(42)); + assert_eq!(codec.decode_leftmost(&[]).unwrap(), None); + assert!( + codec + .decode_leftmost(&buffer[..TAGS_START_OFFSET - 1]) + .is_err() + ); } #[test] @@ -863,6 +971,132 @@ mod tests { assert!(codec.decode_ids(&buffer[..buffer.len() - 1]).is_err()); } + #[test] + fn test_sparse_validator_matches_decoder() { + let codec = SparsePrimaryKeyCodec::schemaless(); + let mut validator = SparsePrimaryKeyValidator::default(); + let mut prefix = Vec::new(); + codec.encode_internal(0, 0, &mut prefix).unwrap(); + let mut cases = vec![prefix.clone()]; + let mut max_prefix = Vec::new(); + codec + .encode_internal(u32::MAX, u64::MAX, &mut max_prefix) + .unwrap(); + cases.push(max_prefix); + + for label in ["", "a", "12345678", "123456789", "1234567🦀末尾", "日本語"] + .into_iter() + .map(String::from) + .chain([ + "a".repeat(128), + format!("{}🦀", "a".repeat(127)), + format!("🦀{}", "a".repeat(127)), + ]) + { + let mut key = prefix.clone(); + codec + .encode_raw_tag_value([(37, label.as_bytes())].into_iter(), &mut key) + .unwrap(); + assert!(validator.validate(&key).is_ok()); + cases.push(key); + } + + // Null labels, unknown IDs and arbitrary label order are accepted by the decoder. + let mut labels = prefix.clone(); + labels.extend_from_slice(&12_u32.to_be_bytes()); + labels.push(0); + codec + .encode_raw_tag_value( + [(999, b"unknown".as_slice()), (0, b"first".as_slice())].into_iter(), + &mut labels, + ) + .unwrap(); + assert!(validator.validate(&labels).is_ok()); + cases.push(labels.clone()); + + // Padding outside the significant bytes has never been required to be zero. + let mut padded = cases[3].clone(); + let padding_offset = padded.len() - 2; + padded[padding_offset] = 0xff; + assert!(codec.decode(&padded).is_ok()); + assert!(validator.validate(&padded).is_ok()); + cases.push(padded); + + for id in [ + 12, + RESERVED_COLUMN_ID_TABLE_ID, + RESERVED_COLUMN_ID_TSID, + u32::MAX, + ] { + let mut invalid = labels.clone(); + invalid.extend_from_slice(&id.to_be_bytes()); + invalid.push(0); + assert!(codec.decode(&invalid).is_err()); + assert!(validator.validate(&invalid).is_err()); + cases.push(invalid); + } + for label in [ + b"\xff".as_slice(), + b"\xc0\xaf", + b"\xed\xa0\x80", + b"1234567\xf4\x90\x80\x80", + ] { + let mut invalid = prefix.clone(); + codec + .encode_raw_tag_value([(37, label)].into_iter(), &mut invalid) + .unwrap(); + assert!(codec.decode(&invalid).is_err()); + assert!(validator.validate(&invalid).is_err()); + cases.push(invalid); + } + + // Reuse the same scratch state across successes and failures, including every + // truncation and byte substitution in this corpus of framing and UTF-8 boundaries. + let mut compare = |bytes: &[u8]| { + assert_eq!( + validator.validate(bytes).is_ok(), + codec.decode(bytes).is_ok(), + "{bytes:02x?}" + ); + }; + for key in cases { + compare(&key); + for end in 0..key.len() { + compare(&key[..end]); + } + for offset in 0..key.len() { + let mut mutated = key.clone(); + for byte in 0..=u8::MAX { + mutated[offset] = byte; + compare(&mutated); + } + } + } + } + + #[test] + fn test_sparse_validator_reuses_state_for_unordered_columns() { + let codec = SparsePrimaryKeyCodec::schemaless(); + let mut validator = SparsePrimaryKeyValidator::default(); + for num_tags in [512, 32, 1] { + let mut key = Vec::new(); + codec.encode_internal(0, 0, &mut key).unwrap(); + codec + .encode_raw_tag_value( + (0..num_tags).map(|index| (index * 17 % num_tags, "1234567🦀".as_bytes())), + &mut key, + ) + .unwrap(); + assert!(validator.validate(&key).is_ok()); + + let mut duplicate = key.clone(); + duplicate.extend_from_slice(&0_u32.to_be_bytes()); + duplicate.push(0); + assert!(validator.validate(&duplicate).is_err()); + assert!(validator.validate(&key).is_ok()); + } + } + #[test] fn test_has_column() { let region_metadata = test_region_metadata(); diff --git a/src/mito-codec/src/row_converter/sparse/checked.rs b/src/mito-codec/src/row_converter/sparse/checked.rs index fec89b74e0d..3a3aac097c6 100644 --- a/src/mito-codec/src/row_converter/sparse/checked.rs +++ b/src/mito-codec/src/row_converter/sparse/checked.rs @@ -21,6 +21,7 @@ use crate::row_converter::encoded_string_len; use crate::row_converter::sparse::{ COLUMN_ID_ENCODE_SIZE, RESERVED_COLUMN_ID_TABLE_ID, RESERVED_COLUMN_ID_TSID, SparseOffsetsCache, TABLE_ID_VALUE_OFFSET, TAGS_START_OFFSET, TSID_VALUE_OFFSET, + validate_prefix, }; /// A borrowing view of one sparse primary key, with checked, lazy field lookup. @@ -35,17 +36,7 @@ pub struct SparsePrimaryKeyView<'a, 'b> { impl<'a, 'b> SparsePrimaryKeyView<'a, 'b> { /// Validates the fixed prefix and binds fresh offset discovery to this key. pub fn new(pk: &'a [u8], cache: &'b mut SparseOffsetsCache) -> Result { - ensure!( - pk.len() >= TAGS_START_OFFSET - && pk[..COLUMN_ID_ENCODE_SIZE] == RESERVED_COLUMN_ID_TABLE_ID.to_be_bytes() - && pk[TSID_VALUE_OFFSET - COLUMN_ID_ENCODE_SIZE..TSID_VALUE_OFFSET] - == RESERVED_COLUMN_ID_TSID.to_be_bytes() - && pk[TABLE_ID_VALUE_OFFSET] == 1 - && pk[TSID_VALUE_OFFSET] == 1, - InvalidSparsePrimaryKeySnafu { - reason: "invalid table_id/tsid prefix" - } - ); + validate_prefix(pk)?; cache.clear(); Ok(Self { pk, cache }) } diff --git a/src/mito2/Cargo.toml b/src/mito2/Cargo.toml index ba6cbe5d8cb..a5e26fcd60f 100644 --- a/src/mito2/Cargo.toml +++ b/src/mito2/Cargo.toml @@ -159,3 +159,7 @@ required-features = ["testing"] name = "bench_compaction_merge" harness = false required-features = ["test"] + +[[bench]] +name = "bench_sparse_write" +harness = false diff --git a/src/mito2/benches/bench_sparse_write.rs b/src/mito2/benches/bench_sparse_write.rs new file mode 100644 index 00000000000..4a641b46a1e --- /dev/null +++ b/src/mito2/benches/bench_sparse_write.rs @@ -0,0 +1,391 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Measures the sparse row and bulk conversion paths used by ingestion and WAL replay. +//! Input preparation, TSID calculation, protocol decoding, and I/O are excluded. + +use std::hint::black_box; +use std::sync::Arc; + +use api::helper::{ColumnDataTypeWrapper, to_grpc_value}; +use api::v1::value::ValueData; +use api::v1::{ColumnDataType, Mutation, OpType, Row, Rows, SemanticType, WriteHint}; +use criterion::{BatchSize, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; +use datatypes::arrow::array::{ + ArrayRef, BinaryArray, BinaryDictionaryBuilder, Float64Array, TimestampMillisecondArray, +}; +use datatypes::arrow::compute; +use datatypes::arrow::datatypes::{DataType, Field, Schema, UInt32Type}; +use datatypes::arrow::record_batch::RecordBatch; +use datatypes::data_type::ConcreteDataType; +use datatypes::schema::ColumnSchema; +use mito_codec::key_values::KeyValues; +use mito_codec::row_converter::{self, CompositeValues, PrimaryKeyCodec, SparsePrimaryKeyCodec}; +use mito2::memtable::bulk::part::{self, BulkPart, BulkPartConverter}; +use mito2::sst::{self, FlatSchemaOptions}; +use store_api::codec::PrimaryKeyEncoding; +use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef}; +use store_api::metric_engine_consts::{ + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, +}; +use store_api::storage::RegionId; +use store_api::storage::consts::{PRIMARY_KEY_COLUMN_NAME, ReservedColumnId}; + +const ROWS_PER_BATCH: usize = 4096; +const TABLE_ID: u32 = 1024; + +fn build_metadata(num_tags: u32) -> RegionMetadataRef { + let mut builder = RegionMetadataBuilder::new(RegionId::new(TABLE_ID, 0)); + let mut primary_key = vec![ReservedColumnId::table_id(), ReservedColumnId::tsid()]; + for (name, data_type, column_id) in [ + ( + DATA_SCHEMA_TABLE_ID_COLUMN_NAME, + ConcreteDataType::uint32_datatype(), + ReservedColumnId::table_id(), + ), + ( + DATA_SCHEMA_TSID_COLUMN_NAME, + ConcreteDataType::uint64_datatype(), + ReservedColumnId::tsid(), + ), + ] { + builder.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new(name, data_type, false), + semantic_type: SemanticType::Tag, + column_id, + }); + } + for index in 0..num_tags { + let column_id = index * 17 % num_tags; + builder.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + format!("tag_{column_id}"), + ConcreteDataType::string_datatype(), + true, + ), + semantic_type: SemanticType::Tag, + column_id, + }); + primary_key.push(column_id); + } + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: num_tags, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true), + semantic_type: SemanticType::Field, + column_id: num_tags + 1, + }) + .primary_key(primary_key) + .primary_key_encoding(PrimaryKeyEncoding::Sparse); + Arc::new(builder.build().unwrap()) +} + +fn build_keys(num_series: usize, num_tags: u32, value_bytes: usize, unicode: bool) -> Vec> { + let codec = SparsePrimaryKeyCodec::schemaless(); + (0..num_series) + .map(|series| { + let tags: Vec<_> = (0..num_tags) + .map(|index| { + // Label name order need not match physical column ID order. + let column_id = index * 17 % num_tags; + let mut value = format!("{series:08x}{column_id:08x}").into_bytes(); + assert!(value.len() <= value_bytes); + value.resize(value_bytes, b'x'); + if unicode { + // The code point crosses an eight-byte encoding chunk boundary. + let start = value_bytes - 9; + value[start..start + 4].copy_from_slice("🦀".as_bytes()); + } + (column_id, value) + }) + .collect(); + let mut key = Vec::new(); + // Permute distinct TSIDs so even one-row-per-series input needs sorting. + let tsid = (series * 17 % num_series) as u64; + codec.encode_internal(TABLE_ID, tsid, &mut key).unwrap(); + codec + .encode_raw_tag_value( + tags.iter().map(|(id, value)| (*id, value.as_slice())), + &mut key, + ) + .unwrap(); + assert_eq!(codec.decode_ids(&key).unwrap(), (TABLE_ID, tsid)); + key + }) + .collect() +} + +fn build_rows(metadata: &RegionMetadataRef, keys: &[Vec]) -> KeyValues { + let schema = [ + ( + PRIMARY_KEY_COLUMN_NAME, + ColumnDataType::Binary, + SemanticType::Tag, + ), + ( + "ts", + ColumnDataType::TimestampMillisecond, + SemanticType::Timestamp, + ), + ("value", ColumnDataType::Float64, SemanticType::Field), + ] + .into_iter() + .map(|(name, data_type, semantic_type)| api::v1::ColumnSchema { + column_name: name.to_string(), + datatype: data_type as i32, + semantic_type: semantic_type as i32, + ..Default::default() + }) + .collect(); + let rows = (0..ROWS_PER_BATCH) + .map(|row| Row { + values: vec![ + ValueData::BinaryValue(keys[row % keys.len()].clone()).into(), + ValueData::TimestampMillisecondValue((row / keys.len()) as i64 * 1000).into(), + ValueData::F64Value(row as f64).into(), + ], + }) + .collect(); + KeyValues::new( + metadata, + Mutation { + op_type: OpType::Put as i32, + sequence: 1, + rows: Some(Rows { schema, rows }), + write_hint: Some(WriteHint { + primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(), + }), + }, + ) + .unwrap() +} + +fn build_bulk(keys: &[Vec], dictionary: bool) -> BulkPart { + let key_column: ArrayRef = if dictionary { + let mut builder = BinaryDictionaryBuilder::::new(); + for row in 0..ROWS_PER_BATCH { + builder.append(&keys[row % keys.len()]).unwrap(); + } + let array = builder.finish(); + assert_eq!(array.values().len(), keys.len()); + Arc::new(array) + } else { + Arc::new(BinaryArray::from_iter_values( + (0..ROWS_PER_BATCH).map(|row| &keys[row % keys.len()]), + )) + }; + let columns: Vec = vec![ + key_column, + Arc::new(TimestampMillisecondArray::from_iter_values( + (0..ROWS_PER_BATCH).map(|row| (row / keys.len()) as i64 * 1000), + )), + Arc::new(Float64Array::from_iter_values( + (0..ROWS_PER_BATCH).map(|row| row as f64), + )), + ]; + let schema = Arc::new(Schema::new( + [PRIMARY_KEY_COLUMN_NAME, "ts", "value"] + .into_iter() + .zip(&columns) + .map(|(name, column)| Field::new(name, column.data_type().clone(), false)) + .collect::>(), + )); + BulkPart { + batch: RecordBatch::try_new(schema, columns).unwrap(), + min_timestamp: 0, + max_timestamp: (ROWS_PER_BATCH / keys.len() - 1) as i64 * 1000, + sequence: 1, + min_sequence: 1, + timestamp_index: 1, + raw_data: None, + } +} + +fn build_raw_rows(metadata: &RegionMetadataRef, keys: &[Vec]) -> KeyValues { + let codec = SparsePrimaryKeyCodec::schemaless(); + let tags: Vec> = keys + .iter() + .map(|key| { + let CompositeValues::Sparse(values) = codec.decode(key).unwrap() else { + unreachable!() + }; + metadata + .primary_key + .iter() + .map(|id| to_grpc_value(values.get(id).unwrap().clone())) + .collect() + }) + .collect(); + let schema = metadata + .column_metadatas + .iter() + .map(|column| api::v1::ColumnSchema { + column_name: column.column_schema.name.clone(), + datatype: ColumnDataTypeWrapper::try_from(column.column_schema.data_type.clone()) + .unwrap() + .datatype() as i32, + semantic_type: column.semantic_type as i32, + ..Default::default() + }) + .collect(); + let rows = (0..ROWS_PER_BATCH) + .map(|row| { + let mut values = tags[row % tags.len()].clone(); + values.push( + ValueData::TimestampMillisecondValue((row / tags.len()) as i64 * 1000).into(), + ); + values.push(ValueData::F64Value(row as f64).into()); + Row { values } + }) + .collect(); + KeyValues::new( + metadata, + Mutation { + op_type: OpType::Put as i32, + sequence: 1, + rows: Some(Rows { schema, rows }), + write_hint: None, + }, + ) + .unwrap() +} + +// Check every output row outside timing, including repeated series and the sort order. +fn check_output(part: &BulkPart, keys: &[Vec]) { + assert_eq!(part.batch.num_rows(), ROWS_PER_BATCH); + let encoded = compute::cast( + part.batch.column_by_name(PRIMARY_KEY_COLUMN_NAME).unwrap(), + &DataType::Binary, + ) + .unwrap(); + let encoded = encoded.as_any().downcast_ref::().unwrap(); + let timestamps = part + .batch + .column_by_name("ts") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let values = part + .batch + .column_by_name("value") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let rows_per_series = ROWS_PER_BATCH / keys.len(); + let mut series_order: Vec<_> = (0..keys.len()).collect(); + series_order.sort_unstable_by_key(|&series| &keys[series]); + for row in 0..ROWS_PER_BATCH { + let series = series_order[row / rows_per_series]; + let sample = row % rows_per_series; + assert_eq!(encoded.value(row), keys[series]); + assert_eq!(timestamps.value(row), sample as i64 * 1000); + assert_eq!(values.value(row), (sample * keys.len() + series) as f64); + } +} + +fn bench_sparse_write(c: &mut Criterion) { + let mut group = c.benchmark_group("sparse_write"); + group.throughput(Throughput::Elements(ROWS_PER_BATCH as u64)); + + for (num_tags, value_bytes, unicode) in [ + (8, 16, false), + (32, 16, false), + (32, 128, false), + (32, 128, true), + (512, 16, true), + ] { + let metadata = build_metadata(num_tags); + let codec = row_converter::build_primary_key_codec(&metadata); + let schema = sst::to_flat_sst_arrow_schema( + &metadata, + &FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Sparse), + ); + for num_series in [64, ROWS_PER_BATCH] { + let suffix = if unicode { "_unicode" } else { "" }; + let name = format!("{num_tags}tags_{value_bytes}bytes_{num_series}series{suffix}"); + let keys = build_keys(num_series, num_tags, value_bytes, unicode); + let rows = build_rows(&metadata, &keys); + let new_converter = || { + BulkPartConverter::new( + &metadata, + schema.clone(), + ROWS_PER_BATCH, + codec.clone(), + true, + ) + }; + + let mut converter = new_converter(); + converter.append_key_values(&rows).unwrap(); + check_output(&converter.convert().unwrap(), &keys); + group.bench_function(BenchmarkId::new("rows", &name), |b| { + b.iter_batched( + new_converter, + |mut converter| { + converter.append_key_values(black_box(&rows)).unwrap(); + black_box(converter.convert().unwrap()) + }, + // A wide-label batch can own tens of MiB; do not retain many outputs. + BatchSize::PerIteration, + ); + }); + + for (input, dictionary) in [("bulk_binary", false), ("bulk_dictionary", true)] { + let part = build_bulk(&keys, dictionary); + let convert = |part| { + part::convert_bulk_part(part, &metadata, codec.clone(), schema.clone(), true) + .unwrap() + .unwrap() + }; + check_output(&convert(part.clone()), &keys); + group.bench_function(BenchmarkId::new(input, &name), |b| { + b.iter_batched( + || part.clone(), + |part| black_box(convert(part)), + BatchSize::PerIteration, + ); + }); + } + + let raw_rows = build_raw_rows(&metadata, &keys); + let mut converter = new_converter(); + converter.append_key_values(&raw_rows).unwrap(); + check_output(&converter.convert().unwrap(), &keys); + group.bench_function(BenchmarkId::new("raw_rows", &name), |b| { + b.iter_batched( + new_converter, + |mut converter| { + converter.append_key_values(black_box(&raw_rows)).unwrap(); + black_box(converter.convert().unwrap()) + }, + BatchSize::PerIteration, + ); + }); + } + } + group.finish(); +} + +criterion_group!(benches, bench_sparse_write); +criterion_main!(benches); diff --git a/src/mito2/src/compaction/scheduler_test.rs b/src/mito2/src/compaction/scheduler_test.rs index 2cd556ad7c3..8f00fd80817 100644 --- a/src/mito2/src/compaction/scheduler_test.rs +++ b/src/mito2/src/compaction/scheduler_test.rs @@ -1846,6 +1846,7 @@ async fn test_compaction_bypass_in_staging_mode() { manifest_cache: None, }, FormatType::PrimaryKey, + false, &Default::default(), ) .await diff --git a/src/mito2/src/engine/bulk_insert_validation_test.rs b/src/mito2/src/engine/bulk_insert_validation_test.rs index 9652152031f..31b5473b73e 100644 --- a/src/mito2/src/engine/bulk_insert_validation_test.rs +++ b/src/mito2/src/engine/bulk_insert_validation_test.rs @@ -22,8 +22,8 @@ use common_error::status_code::StatusCode; use common_recordbatch::{DfRecordBatch, RecordBatches}; use common_test_util::flight::encode_to_flight_data; use datatypes::arrow::array::{ - ArrayRef, Float64Array, Int64Array, LargeStringArray, ListArray, StringArray, StringViewArray, - TimestampMillisecondArray, TimestampSecondArray, + ArrayRef, BinaryArray, Float64Array, Int64Array, LargeStringArray, ListArray, StringArray, + StringViewArray, TimestampMillisecondArray, TimestampSecondArray, }; use datatypes::arrow::datatypes::{Field, Int64Type, Schema}; use datatypes::prelude::ConcreteDataType; @@ -91,6 +91,101 @@ async fn scan_num_rows(engine: &MitoEngine, region_id: RegionId) -> usize { batches.iter().map(|batch| batch.num_rows()).sum() } +#[tokio::test] +async fn test_encoded_sparse_keys_reject_whole_batch_and_replay() { + use api::v1::value::ValueData; + use api::v1::{ColumnDataType, WriteHint}; + use mito_codec::row_converter::SparsePrimaryKeyCodec; + + for bulk in [false, true] { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + let mut create = CreateRequestBuilder::new() + .insert_option("primary_key_encoding", "sparse") + .build(); + let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding( + store_api::codec::PrimaryKeyEncoding::Sparse, + ); + create + .column_metadatas + .extend(reserved.column_metadatas.into_iter().take(2)); + create + .primary_key + .splice(0..0, reserved.primary_key.into_iter().take(2)); + let table_dir = create.table_dir.clone(); + let options = create.options.clone(); + let mut schema = rows_schema(&create); + schema.truncate(3); + schema[0].column_name = "__primary_key".to_string(); + schema[0].datatype = ColumnDataType::Binary as i32; + schema.swap(1, 2); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + + let codec = SparsePrimaryKeyCodec::schemaless(); + let mut key = Vec::new(); + codec.encode_internal(42, 7, &mut key).unwrap(); + codec + .encode_raw_tag_value([(0, "1234567🦀".as_bytes())].into_iter(), &mut key) + .unwrap(); + let mut malformed = key.clone(); + malformed.push(0); // A truncated label ID after a valid Unicode label. + let request = |second: &[u8]| { + if bulk { + bulk_request( + region_id, + vec![ + column( + "__primary_key", + Arc::new(BinaryArray::from_vec(vec![key.as_slice(), second])), + ), + field(), + ts(), + ], + ) + } else { + let mut rows = build_rows(0, 2); + for (row, key) in rows.iter_mut().zip([key.as_slice(), second]) { + row.values[0].value_data = Some(ValueData::BinaryValue(key.to_vec())); + row.values.swap(1, 2); + } + RegionRequest::Put(RegionPutRequest { + rows: Rows { + schema: schema.clone(), + rows, + }, + hint: Some(WriteHint { + primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse as i32, + }), + skip_wal: false, + partition_expr_version: None, + }) + } + }; + let error = engine + .handle_request(region_id, request(&malformed)) + .await + .unwrap_err(); + assert_eq!(StatusCode::InvalidArguments, error.status_code()); + assert_eq!(0, scan_num_rows(&engine, region_id).await); + // Byte validation follows WAL append; replay must also discard the malformed batch. + reopen_region(&engine, region_id, table_dir.clone(), true, options.clone()).await; + assert_eq!(0, scan_num_rows(&engine, region_id).await); + engine + .handle_request(region_id, request(&key)) + .await + .unwrap(); + assert_eq!(2, scan_num_rows(&engine, region_id).await); + + reopen_region(&engine, region_id, table_dir, true, options).await; + assert_eq!(2, scan_num_rows(&engine, region_id).await); + engine.stop().await.unwrap(); + } +} + /// Batches that do not match the region schema are rejected before they are /// appended to the WAL, and the region keeps accepting writes. #[tokio::test] @@ -128,6 +223,28 @@ async fn test_bulk_insert_rejects_batches_not_matching_schema() { column("ts", Arc::new(TimestampSecondArray::from(vec![0, 1]))), ], vec![tag(), field()], + vec![field(), ts()], + vec![ + column("tag_0", Arc::new(Int64Array::from(vec![1, 2]))), + field(), + ts(), + ], + vec![ + column( + "__primary_key", + Arc::new(Float64Array::from(vec![1.0, 2.0])), + ), + field(), + ts(), + ], + vec![ + column( + "__primary_key", + Arc::new(BinaryArray::from(vec![None::<&[u8]>; 2])), + ), + field(), + ts(), + ], vec![ tag(), column("field_0", Arc::new(StringArray::from(vec!["1", "2"]))), @@ -301,6 +418,7 @@ async fn test_bulk_insert_fills_columns_missing_from_aligned_batch() { let engine = env.create_engine(MitoConfig::default()).await; let region_id = RegionId::new(1, i as u32 + 1); let request = CreateRequestBuilder::new() + .tag_num(2) .insert_option("sst_format", sst_format) .build(); let table_dir = request.table_dir.clone(); @@ -325,5 +443,192 @@ async fn test_bulk_insert_fills_columns_missing_from_aligned_batch() { assert_eq!(2, response.affected_rows, "{sst_format}"); reopen_region(&engine, region_id, table_dir, true, options).await; assert_eq!(2, scan_num_rows(&engine, region_id).await, "{sst_format}"); + let stream = engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(); + let batches = RecordBatches::try_collect(stream).await.unwrap(); + for batch in batches.iter() { + let tag = batch.column_by_name("tag_1").unwrap(); + assert_eq!(tag.null_count(), batch.num_rows()); + } + } +} + +#[tokio::test] +async fn test_bulk_insert_json2_physical_layout() { + use datatypes::arrow::array::{NullArray, StructArray}; + use datatypes::arrow::datatypes::DataType; + use datatypes::extension::json::{Json2ExtensionType, JsonMetadata}; + use datatypes::json::JsonSettings; + use datatypes::types::json_type::JsonNativeType; + + for encoding in ["dense", "sparse"] { + for layout in ["v2", "legacy", "missing"] { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + let settings = JsonSettings::default(); + let mut request = CreateRequestBuilder::new() + .field_datatype(ConcreteDataType::json2(JsonNativeType::Null)) + .insert_option("sst_format", "flat") + .insert_option("primary_key_encoding", encoding) + .build(); + if encoding == "sparse" { + let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding( + store_api::codec::PrimaryKeyEncoding::Sparse, + ); + request + .column_metadatas + .extend(reserved.column_metadatas.into_iter().take(2)); + request + .primary_key + .splice(0..0, reserved.primary_key.into_iter().take(2)); + } + let key_columns = if encoding == "sparse" { + let codec = mito_codec::row_converter::SparsePrimaryKeyCodec::schemaless(); + let keys: Vec<_> = (1..=2) + .map(|tsid| { + let mut key = Vec::new(); + codec.encode_internal(42, tsid, &mut key).unwrap(); + key + }) + .collect(); + vec![ + column( + "__primary_key", + Arc::new(BinaryArray::from_iter_values(&keys)), + ), + ts(), + ] + } else { + vec![tag(), ts()] + }; + let json_column = &mut request.column_metadatas[1].column_schema; + json_column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( + settings.clone(), + )))); + let mut columns = key_columns.clone(); + if layout != "missing" { + let (array, metadata) = if layout == "legacy" { + let array = Arc::new(StructArray::from(vec![( + Arc::new(Field::new("trace_id", DataType::Utf8, true)), + Arc::new(StringArray::from(vec!["abc", "def"])) as ArrayRef, + )])) as ArrayRef; + (array, JsonMetadata::new_v1(settings.clone())) + } else { + let mut builder = json_column.create_mutable_vector(2); + for id in ["abc", "def"] { + let value = settings + .encode(serde_json::json!({"trace_id": id})) + .unwrap(); + builder.try_push_value_ref(&value.as_value_ref()).unwrap(); + } + ( + builder.to_vector().to_arrow_array(), + JsonMetadata::new(settings.clone()), + ) + }; + let field = Field::new("field_0", array.data_type().clone(), true) + .with_extension_type(Json2ExtensionType::new(Arc::new(metadata))); + columns.push((field, array)); + } + let table_dir = request.table_dir.clone(); + let options = request.options.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + if layout == "v2" { + let malformed = Arc::new(StructArray::from(vec![( + Arc::new(Field::new( + datatypes::json::JSON2_REMAINDER_FIELD_NAME, + DataType::Int64, + true, + )), + Arc::new(Int64Array::from(vec![1, 2])) as ArrayRef, + )])) as ArrayRef; + for malformed in [ + malformed, + Arc::new(StringArray::from(vec!["abc", "def"])) as ArrayRef, + ] { + let malformed_field = + Field::new("field_0", malformed.data_type().clone(), true) + .with_extension_type(Json2ExtensionType::new(Arc::new( + JsonMetadata::new(settings.clone()), + ))); + let error = engine + .handle_request( + region_id, + bulk_request( + region_id, + [key_columns.clone(), vec![(malformed_field, malformed)]].concat(), + ), + ) + .await + .unwrap_err(); + assert_eq!(error.status_code(), StatusCode::InvalidArguments); + } + let mut invalid_layout = + serde_json::to_value(JsonMetadata::new(settings.clone())).unwrap(); + invalid_layout["layout_version"] = serde_json::json!(3); + let mut null_field = Field::new("field_0", DataType::Null, true) + .with_extension_type(Json2ExtensionType::new(Arc::new(JsonMetadata::new( + settings.clone(), + )))); + null_field.metadata_mut().insert( + arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY.to_string(), + invalid_layout.to_string(), + ); + let error = engine + .handle_request( + region_id, + bulk_request( + region_id, + [ + key_columns.clone(), + vec![(null_field, Arc::new(NullArray::new(2)) as ArrayRef)], + ] + .concat(), + ), + ) + .await + .unwrap_err(); + assert_eq!(error.status_code(), StatusCode::InvalidArguments); + } + let response = engine + .handle_request(region_id, bulk_request(region_id, columns)) + .await + .unwrap(); + assert_eq!(response.affected_rows, 2); + for phase in 0..3 { + if phase == 1 { + reopen_region(&engine, region_id, table_dir.clone(), true, options.clone()) + .await; + } else if phase == 2 { + crate::test_util::flush_region(&engine, region_id, None).await; + } + let stream = engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(); + let batches = RecordBatches::try_collect(stream).await.unwrap(); + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 2); + let printed = batches.pretty_print().unwrap(); + if layout != "missing" { + assert!( + printed.contains("abc") && printed.contains("def"), + "{encoding}/{layout}/{phase}: {printed}" + ); + } else { + for batch in batches.iter() { + assert_eq!( + batch.column_by_name("field_0").unwrap().null_count(), + batch.num_rows() + ); + } + } + } + } } } diff --git a/src/mito2/src/engine/create_test.rs b/src/mito2/src/engine/create_test.rs index 57c0c3fa7c2..895d15b4195 100644 --- a/src/mito2/src/engine/create_test.rs +++ b/src/mito2/src/engine/create_test.rs @@ -510,7 +510,7 @@ async fn test_engine_create_preserves_manifest_on_open_error() -> WhateverResult } #[tokio::test] -async fn test_engine_create_json2_sparse_requires_flat() -> WhateverResult<()> { +async fn test_engine_create_json2_sparse_forces_flat() -> WhateverResult<()> { let mut env = TestEnv::with_prefix("create-json2-sparse").await; let engine = env.create_engine(MitoConfig::default()).await; let region_id = RegionId::new(1, 1); @@ -529,21 +529,18 @@ async fn test_engine_create_json2_sparse_requires_flat() -> WhateverResult<()> { request.column_metadatas = metadata.column_metadatas.clone(); request.primary_key = metadata.primary_key.clone(); request.column_metadatas[4].column_schema = json_column; - let err = engine - .handle_request(region_id, RegionRequest::Create(request.clone())) - .await - .unwrap_err(); - assert_eq!(StatusCode::InvalidArguments, err.status_code()); - assert!( - err.output_msg() - .contains("JSON2 columns require sst_format=flat") - ); - assert!(!engine.is_region_exists(region_id)); - - request.options.insert("sst_format".into(), "flat".into()); engine .handle_request(region_id, RegionRequest::Create(request.clone())) .await?; + assert_eq!( + Some(FormatType::Flat), + engine + .get_region(region_id) + .unwrap() + .version() + .options + .sst_format + ); let schema = rows_schema(&request); let mut pk_schema = schema[0].clone(); pk_schema.column_name = PRIMARY_KEY_COLUMN_NAME.into(); diff --git a/src/mito2/src/engine/scan_test.rs b/src/mito2/src/engine/scan_test.rs index 81b9b016772..0651fd2dd4c 100644 --- a/src/mito2/src/engine/scan_test.rs +++ b/src/mito2/src/engine/scan_test.rs @@ -73,6 +73,271 @@ use crate::test_util; use crate::test_util::sst_util::{new_sparse_primary_key, sst_region_metadata_with_encoding}; use crate::test_util::{CreateRequestBuilder, TestEnv, reopen_region}; +#[tokio::test] +async fn test_sparse_upsert_after_adding_nullable_tag() -> WhateverResult<()> { + use datatypes::schema::ColumnSchema; + use store_api::metadata::ColumnMetadata; + use store_api::region_request::AddColumn; + + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let mut request = CreateRequestBuilder::new() + .tag_num(1) + .field_num(1) + .insert_option("primary_key_encoding", "sparse") + .build(); + let reserved = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse); + request + .column_metadatas + .extend(reserved.column_metadatas.into_iter().take(2)); + request + .primary_key + .splice(0..0, reserved.primary_key.into_iter().take(2)); + let schema = test_util::rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await?; + let mut rows = Rows { + schema, + rows: vec![row(vec![ + ValueData::StringValue("api".into()), + ValueData::F64Value(1.0), + ValueData::TimestampMillisecondValue(1000), + ValueData::U32Value(42), + ValueData::U64Value(7), + ])], + }; + test_util::put_rows(&engine, region_id, rows.clone()).await; + test_util::flush_region(&engine, region_id, None).await; + engine + .handle_request( + region_id, + RegionRequest::Alter(RegionAlterRequest { + kind: AlterKind::AddColumns { + columns: vec![AddColumn { + column_metadata: ColumnMetadata { + column_schema: ColumnSchema::new( + "zone", + ConcreteDataType::string_datatype(), + true, + ), + semantic_type: SemanticType::Tag, + column_id: 3, + }, + location: None, + }], + }, + }), + ) + .await?; + + // The old SST and the new write must still identify the same series before compaction. + rows.rows[0].values[1].value_data = Some(ValueData::F64Value(2.0)); + test_util::put_rows(&engine, region_id, rows).await; + for flush in [false, true] { + if flush { + test_util::flush_region(&engine, region_id, None).await; + } + let stream = engine + .scan_to_stream( + region_id, + ScanRequest { + projection: Some(vec![0, 1, 2, 5]), + ..Default::default() + }, + ) + .await?; + let batches = RecordBatches::try_collect(stream).await?; + let expected = "\ ++-------+---------+---------------------+------+ +| tag_0 | field_0 | ts | zone | ++-------+---------+---------------------+------+ +| api | 2.0 | 1970-01-01T00:00:01 | | ++-------+---------+---------------------+------+"; + assert_eq!(batches.pretty_print()?, expected); + } + engine.stop().await?; + Ok(()) +} + +#[tokio::test] +async fn test_exemplar_sparse_storage_lifecycle() -> WhateverResult<()> { + use datatypes::schema::ColumnSchema; + use store_api::metadata::ColumnMetadata; + use store_api::region_request::AddColumn; + use store_api::storage::consts::ReservedColumnId; + + for default_flat_format in [false, true] { + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + default_flat_format, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1024, 0); + let mut request = CreateRequestBuilder::new() + .tag_num(2) + .field_num(2) + .insert_option("primary_key_encoding", "sparse") + .insert_option("append_mode", "true") + .insert_option("sst_format", "primary_key") + .build(); + request.column_metadatas[3].column_schema.data_type = + ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new())); + request.column_metadatas[3] + .column_schema + .with_extension_type(&Json2ExtensionType::default()); + for (name, column_id, data_type) in [ + ( + "__table_id", + ReservedColumnId::table_id(), + ConcreteDataType::uint32_datatype(), + ), + ( + "__tsid", + ReservedColumnId::tsid(), + ConcreteDataType::uint64_datatype(), + ), + ] { + request.column_metadatas.push(ColumnMetadata { + column_schema: ColumnSchema::new(name, data_type, false), + semantic_type: SemanticType::Tag, + column_id, + }); + } + request.primary_key.splice( + 0..0, + [ReservedColumnId::table_id(), ReservedColumnId::tsid()], + ); + let table_dir = request.table_dir.clone(); + let schema = test_util::rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await?; + let mut rows = Rows { + schema: schema.clone(), + rows: vec![row(vec![ + ValueData::StringValue("metric".into()), + ValueData::StringValue("api".into()), + ValueData::F64Value(1.5), + ValueData::JsonValue(encode_json_value(JsonValue::from( + json!({"trace_id":"abc"}), + ))), + ValueData::TimestampMillisecondValue(1), + ])], + }; + rows.rows[0].values.extend([ + ValueData::U32Value(42).into(), + ValueData::U64Value(7).into(), + ]); + // Equal series/timestamp observations are preserved in append mode. + rows.rows.push(rows.rows[0].clone()); + let mut null_row = rows.rows[0].clone(); + null_row.values[0].value_data = None; + null_row.values[1].value_data = None; + // Different source metrics can have the same TSID. + null_row.values[5] = ValueData::U32Value(43).into(); + rows.rows.push(null_row); + test_util::put_rows(&engine, region_id, rows.clone()).await; + + // Reopen without encoding options, replaying raw rows from WAL. + reopen_region(&engine, region_id, table_dir.clone(), true, HashMap::new()).await; + assert_eq!( + engine.get_primary_key_encoding(region_id).unwrap(), + PrimaryKeyEncoding::Sparse + ); + test_util::flush_region(&engine, region_id, None).await; + engine + .handle_request( + region_id, + RegionRequest::Alter(RegionAlterRequest { + kind: AlterKind::AddColumns { + columns: vec![AddColumn { + column_metadata: ColumnMetadata { + column_schema: ColumnSchema::new( + "new_tag", + ConcreteDataType::string_datatype(), + true, + ), + semantic_type: SemanticType::Tag, + column_id: 5, + }, + location: None, + }], + }, + }), + ) + .await?; + // A stale writer omits the newly added nullable tag. + test_util::put_rows(&engine, region_id, rows).await; + test_util::flush_region(&engine, region_id, None).await; + engine + .handle_request( + region_id, + RegionRequest::Compact(RegionCompactRequest { + options: compact_request::Options::StrictWindow(StrictWindow { + window_seconds: 86400, + }), + ..Default::default() + }), + ) + .await?; + reopen_region( + &engine, + region_id, + table_dir.clone(), + true, + HashMap::from([ + ("primary_key_encoding".into(), "dense".into()), + ("sst_format".into(), "primary_key".into()), + ]), + ) + .await; + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + assert_eq!( + engine.get_primary_key_encoding(region_id).unwrap(), + PrimaryKeyEncoding::Sparse + ); + let mut cases = vec![ + (vec![], 6), + (vec![col("tag_0").eq(lit("metric"))], 4), + (vec![col("tag_0").is_null()], 2), + ]; + cases.extend([ + (vec![col("__table_id").eq(lit(42u32))], 4), + (vec![col("__table_id").eq(lit(43u32))], 2), + (vec![col("__tsid").eq(lit(7u64))], 6), + ]); + for (filters, expected) in cases { + let scanner = engine + .scanner( + region_id, + ScanRequest { + filters, + json_type_hint: HashMap::from([( + "field_1".into(), + JsonNativeType::Variant, + )]), + ..Default::default() + }, + ) + .await?; + let batches = RecordBatches::try_collect(scanner.scan().await?).await?; + assert_eq!( + batches.iter().map(|b| b.num_rows()).sum::(), + expected + ); + for batch in batches.iter() { + let label_index = batch.schema.column_index_by_name("new_tag").unwrap(); + assert_eq!(batch.column(label_index).null_count(), batch.num_rows()); + } + } + } + Ok(()) +} + #[tokio::test] async fn test_nullable_label_filters_in_memtables_and_ssts() { use datafusion_expr::{BinaryExpr as LogicalBinaryExpr, Cast, Expr}; diff --git a/src/mito2/src/manifest/manager.rs b/src/mito2/src/manifest/manager.rs index 436488f3c3c..5471b1883a9 100644 --- a/src/mito2/src/manifest/manager.rs +++ b/src/mito2/src/manifest/manager.rs @@ -170,6 +170,7 @@ impl RegionManifestManager { flushed_entry_id: u64, options: RegionManifestOptions, sst_format: FormatType, + append_mode: bool, stats: &ManifestStats, ) -> Result { // construct storage @@ -195,7 +196,7 @@ impl RegionManifestManager { RegionChange { metadata: metadata.clone(), sst_format, - append_mode: None, + append_mode: Some(append_mode), }, ); let manifest = manifest_builder.try_build()?; @@ -209,7 +210,7 @@ impl RegionManifestManager { let mut actions = vec![RegionMetaAction::Change(RegionChange { metadata, sst_format, - append_mode: None, + append_mode: Some(append_mode), })]; if flushed_entry_id > 0 { actions.push(RegionMetaAction::Edit(RegionEdit { @@ -1068,6 +1069,6 @@ mod test { // get manifest size again let manifest_size = manager.manifest_usage(); - assert_eq!(manifest_size, 1397); + assert_eq!(manifest_size, 1398); } } diff --git a/src/mito2/src/memtable/bulk/part.rs b/src/mito2/src/memtable/bulk/part.rs index 5852d072197..50954f1c6db 100644 --- a/src/mito2/src/memtable/bulk/part.rs +++ b/src/mito2/src/memtable/bulk/part.rs @@ -45,13 +45,14 @@ use datatypes::prelude::{MutableVector, Vector}; use datatypes::value::ValueRef; use datatypes::vectors::Helper; use mito_codec::key_values::{KeyValue, KeyValues}; +use mito_codec::row_converter::sparse::SparsePrimaryKeyValidator; use mito_codec::row_converter::{PrimaryKeyCodec, SortField, build_primary_key_codec_with_fields}; use parquet::arrow::ArrowWriter; use parquet::basic::{Compression, ZstdLevel}; use parquet::file::metadata::ParquetMetaData; use parquet::file::properties::WriterProperties; use smallvec::SmallVec; -use snafu::{OptionExt, ResultExt}; +use snafu::{OptionExt, ResultExt, ensure}; use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::{RegionMetadata, RegionMetadataRef}; use store_api::mito_engine_options::FloatFieldEncoding; @@ -223,7 +224,7 @@ impl BulkPart { let mut columns_to_fill = Vec::new(); for column_meta in ®ion_metadata.column_metadatas { // Sparse bulk batches already carry tags in the encoded primary key. - if region_metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse + if batch_columns.contains(PRIMARY_KEY_COLUMN_NAME) && column_meta.semantic_type == SemanticType::Tag { continue; @@ -266,13 +267,14 @@ impl BulkPart { ), })?; let arrow_array = default_vector.to_arrow_array(); - column_meta.column_schema.data_type.as_arrow_type(); - - new_fields.push(Arc::new(Field::new( - column_meta.column_schema.name.clone(), - column_meta.column_schema.data_type.as_arrow_type(), - column_meta.column_schema.is_nullable(), - ))); + new_fields.push(Arc::new( + Field::new( + column_meta.column_schema.name.clone(), + arrow_array.data_type().clone(), + column_meta.column_schema.is_nullable(), + ) + .with_metadata(column_meta.column_schema.metadata().clone()), + )); new_columns.push(arrow_array); } @@ -598,6 +600,8 @@ pub struct BulkPartConverter { key_buf: Vec, /// Primary key array builder. key_array_builder: PrimaryKeyArrayBuilder, + /// Whether any input key was supplied pre-encoded and still needs validation. + has_pre_encoded_keys: bool, /// Builders for non-primary key columns. value_builder: ValueBuilder, /// Builders for individual primary key columns. @@ -644,6 +648,7 @@ impl BulkPartConverter { primary_key_codec, key_buf: Vec::new(), key_array_builder: PrimaryKeyArrayBuilder::new(), + has_pre_encoded_keys: false, value_builder: ValueBuilder::new(region_metadata, capacity), primary_key_column_builders, min_ts: i64::MAX, @@ -664,10 +669,16 @@ impl BulkPartConverter { /// Appends a [KeyValue] to builders. /// - /// If the primary key uses sparse encoding, callers must encoded the primary key in the [KeyValue]. + /// Metric-sparse hints carry encoded keys; raw tags use the destination codec. fn append_key_value(&mut self, kv: &KeyValue) -> Result<()> { // Handles primary key based on encoding type - if self.primary_key_codec.encoding() == PrimaryKeyEncoding::Sparse { + if kv.primary_key_encoding() == PrimaryKeyEncoding::Sparse { + ensure!( + self.primary_key_codec.encoding() == PrimaryKeyEncoding::Sparse, + error::InvalidRecordBatchSnafu { + reason: "pre-encoded primary keys require a sparse destination layout", + } + ); // For sparse encoding, the primary key is already encoded in the KeyValue // Gets the first (and only) primary key value which contains the encoded key let mut primary_keys = kv.primary_keys(); @@ -682,13 +693,15 @@ impl BulkPartConverter { self.key_array_builder .append(encoded) .context(ComputeArrowSnafu)?; + self.has_pre_encoded_keys = true; } else { - self.key_array_builder - .append("") - .context(ComputeArrowSnafu)?; + return error::InvalidRecordBatchSnafu { + reason: "encoded metric primary key must not be null", + } + .fail(); } } else { - // For dense encoding, we need to encode the primary key columns + // Encode raw primary key columns with the destination codec. self.key_buf.clear(); self.primary_key_codec .encode_key_value(kv, &mut self.key_buf) @@ -752,6 +765,9 @@ impl BulkPartConverter { columns.push(values.timestamp.to_arrow_array()); // Primary key. let pk_array = self.key_array_builder.finish(); + if self.has_pre_encoded_keys { + validate_sparse_dictionary(&pk_array)?; + } columns.push(Arc::new(pk_array)); // Sequence and op type. columns.push(values.sequence.to_arrow_array()); @@ -776,6 +792,35 @@ impl BulkPartConverter { } } +/// Validates each referenced key once; sliced dictionaries may retain unused invalid values. +fn validate_sparse_dictionary(keys: &PrimaryKeyArray) -> Result<()> { + let values = keys + .values() + .as_any() + .downcast_ref::() + .context(error::InvalidRecordBatchSnafu { + reason: "encoded primary keys must be binary", + })?; + ensure!( + keys.logical_null_count() == 0, + error::InvalidRecordBatchSnafu { + reason: "encoded primary key must not be null", + } + ); + let mut validated = vec![false; values.len()]; + let mut validator = SparsePrimaryKeyValidator::default(); + for &index in keys.keys().values() { + let index = index as usize; + if !validated[index] { + validator + .validate(values.value(index)) + .context(EncodeSnafu)?; + validated[index] = true; + } + } + Ok(()) +} + fn new_primary_key_column_builders( metadata: &RegionMetadata, capacity: usize, @@ -972,12 +1017,12 @@ fn lexsort_primary_key_indices(batch: &RecordBatch) -> Result { datatypes::arrow::compute::lexsort_to_indices(&sort_columns, None).context(ComputeArrowSnafu) } -/// Converts a `BulkPart` that is unordered and without encoded primary keys into a `BulkPart` +/// Converts an unordered `BulkPart` with raw tags or encoded primary keys into a `BulkPart` /// with the same format as produced by [BulkPartConverter]. /// /// This function takes a `BulkPart` where: -/// - For dense encoding: Primary key columns may be stored as individual columns -/// - For sparse encoding: The `__primary_key` column should already be present with encoded keys +/// - Raw primary key columns are stored individually and encoded with the destination codec +/// - Sparse destinations also accept encoded keys in a `__primary_key` column /// - The batch may not be sorted /// /// And produces a `BulkPart` where: @@ -1023,13 +1068,36 @@ pub fn convert_bulk_part( // Determines the structure of the input batch by looking up columns by name let mut output_columns = Vec::new(); - // Extracts primary key columns if we need to encode them (dense encoding) - let pk_array = if is_sparse { - // For sparse encoding, the input should already have the __primary_key column - // We need to find it in the input batch - None + // Encoded input is explicit; otherwise encode raw tags with the destination codec. + let pk_dictionary: ArrayRef = if column_indices.contains_key(PRIMARY_KEY_COLUMN_NAME) { + ensure!( + is_sparse, + error::InvalidRecordBatchSnafu { + reason: "pre-encoded bulk keys require a sparse destination layout" + } + ); + let column = part.batch.column(column_indices[PRIMARY_KEY_COLUMN_NAME]); + ensure!( + column.data_type() == &ArrowDataType::Binary + || matches!(column.data_type(), ArrowDataType::Dictionary(_, value) if value.as_ref() == &ArrowDataType::Binary), + error::InvalidRecordBatchSnafu { + reason: "encoded primary keys must be binary" + } + ); + let target_type = ArrowDataType::Dictionary( + Box::new(ArrowDataType::UInt32), + Box::new(ArrowDataType::Binary), + ); + let column = arrow::compute::cast(column, &target_type).context(ComputeArrowSnafu)?; + let keys = column.as_any().downcast_ref::().context( + error::InvalidRecordBatchSnafu { + reason: "encoded primary keys must be a UInt32 binary dictionary", + }, + )?; + validate_sparse_dictionary(keys)?; + column } else { - // For dense encoding, extract and encode primary key columns by name + // Extract and encode primary key columns by name. let pk_vectors: Result> = region_metadata .primary_key_columns() .map(|col_meta| { @@ -1068,7 +1136,7 @@ pub fn convert_bulk_part( .context(ComputeArrowSnafu)?; } - Some(key_array_builder.finish()) + Arc::new(key_array_builder.finish()) }; // Adds primary key columns if storing them (only for dense encoding) @@ -1121,24 +1189,6 @@ pub fn convert_bulk_part( output_columns.push(part.batch.column(*ts_col_idx).clone()); // Adds encoded primary key dictionary column - let pk_dictionary = if let Some(pk_dict_array) = pk_array { - Arc::new(pk_dict_array) as ArrayRef - } else { - let pk_col_idx = - column_indices - .get(PRIMARY_KEY_COLUMN_NAME) - .context(ColumnNotFoundSnafu { - column: PRIMARY_KEY_COLUMN_NAME, - })?; - let col = part.batch.column(*pk_col_idx); - - // Casts to dictionary type if needed - let target_type = ArrowDataType::Dictionary( - Box::new(ArrowDataType::UInt32), - Box::new(ArrowDataType::Binary), - ); - arrow::compute::cast(col, &target_type).context(ComputeArrowSnafu)? - }; output_columns.push(pk_dictionary); let sequence_array = UInt64Array::from(vec![part.sequence; num_rows]); @@ -1147,6 +1197,46 @@ pub fn convert_bulk_part( let op_type_array = UInt8Array::from(vec![OpType::Put as u8; num_rows]); output_columns.push(Arc::new(op_type_array) as ArrayRef); + // JSON2 arrays carry a data-dependent shape and their own physical layout version. + // Keep that layout metadata while retaining the destination's column IDs. + let schema = if region_metadata + .field_columns() + .any(|c| c.column_schema.data_type.is_json2()) + { + let fields = schema + .fields() + .iter() + .map(|field| { + if !datatypes::extension::json::is_json2_extension_type(field) { + return field.clone(); + } + let source = input_schema.field(column_indices[field.name().as_str()]); + let mut metadata = field.metadata().clone(); + if datatypes::extension::json::is_json2_extension_type(source) { + for key in [ + arrow_schema::extension::EXTENSION_TYPE_NAME_KEY, + arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY, + ] { + if let Some(value) = source.metadata().get(key) { + metadata.insert(key.to_string(), value.clone()); + } else { + metadata.remove(key); + } + } + } + Arc::new( + field + .as_ref() + .clone() + .with_data_type(source.data_type().clone()) + .with_metadata(metadata), + ) + }) + .collect::>(); + Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone())) + } else { + schema + }; let batch = RecordBatch::try_new(schema, output_columns).context(NewRecordBatchSnafu)?; // Sorts the batch by (primary_key, timestamp, sequence desc) @@ -2490,7 +2580,6 @@ mod tests { #[allow(clippy::too_many_arguments)] fn build_key_values_with_sparse_encoding( metadata: &RegionMetadataRef, - primary_key_codec: &Arc, table_id: u32, tsid: u64, k0: String, @@ -2507,7 +2596,7 @@ mod tests { (1, Value::String(k1.clone().into())), ]; let mut encoded_key = Vec::new(); - primary_key_codec + mito_codec::row_converter::SparsePrimaryKeyCodec::schemaless() .encode_values(&pk_values, &mut encoded_key) .unwrap(); assert!(!encoded_key.is_empty()); @@ -2627,12 +2716,16 @@ mod tests { assert_eq!(primary_key_codec.encoding(), PrimaryKeyEncoding::Sparse); let capacity = 100; - let mut converter = - BulkPartConverter::new(&metadata, schema, capacity, primary_key_codec.clone(), true); + let mut converter = BulkPartConverter::new( + &metadata, + schema.clone(), + capacity, + primary_key_codec.clone(), + true, + ); let key_values1 = build_key_values_with_sparse_encoding( &metadata, - &primary_key_codec, 2048u32, // table_id 100u64, // tsid "key11".to_string(), @@ -2642,9 +2735,8 @@ mod tests { 1, ); - let key_values2 = build_key_values_with_sparse_encoding( + let mut key_values2 = build_key_values_with_sparse_encoding( &metadata, - &primary_key_codec, 4096u32, // table_id 200u64, // tsid "key12".to_string(), @@ -2653,6 +2745,101 @@ mod tests { vec![Some(3.0)].into_iter(), 2, ); + key_values2.mutation.op_type = OpType::Delete as i32; + + let mut raw_mutation = key_values1.mutation.clone(); + raw_mutation.write_hint = None; + let rows = raw_mutation.rows.as_mut().unwrap(); + rows.schema.splice( + 0..1, + ["k0", "k1"].map(|name| api::v1::ColumnSchema { + column_name: name.to_string(), + datatype: api::v1::ColumnDataType::String as i32, + semantic_type: SemanticType::Tag as i32, + ..Default::default() + }), + ); + for row in &mut rows.rows { + row.values.splice( + 0..1, + ["raw🦀", ""] + .map(|value| api::v1::value::ValueData::StringValue(value.to_string()).into()), + ); + } + rows.schema.extend( + [ + ("__table_id", api::v1::ColumnDataType::Uint32), + ("__tsid", api::v1::ColumnDataType::Uint64), + ] + .map(|(name, datatype)| api::v1::ColumnSchema { + column_name: name.into(), + datatype: datatype as i32, + semantic_type: SemanticType::Tag as i32, + ..Default::default() + }), + ); + for row in &mut rows.rows { + row.values.extend([ + api::v1::value::ValueData::U32Value(2048).into(), + api::v1::value::ValueData::U64Value(100).into(), + ]); + } + let raw = KeyValues::new(&metadata, raw_mutation).unwrap(); + let mut raw_converter = BulkPartConverter::new( + &metadata, + schema.clone(), + capacity, + primary_key_codec.clone(), + true, + ); + raw_converter.append_key_values(&raw).unwrap(); + let raw_part = raw_converter.convert().unwrap(); + assert_eq!(2, raw_part.num_rows()); + let keys = arrow::compute::cast( + raw_part + .batch + .column_by_name(PRIMARY_KEY_COLUMN_NAME) + .unwrap(), + &ArrowDataType::Binary, + ) + .unwrap(); + let keys = keys.as_any().downcast_ref::().unwrap(); + for key in keys.iter().flatten() { + let decoded = primary_key_codec.decode(key).unwrap().into_sparse(); + assert_eq!( + Some(&Value::UInt32(2048)), + decoded.get(&ReservedColumnId::table_id()) + ); + assert_eq!( + Some(&Value::UInt64(100)), + decoded.get(&ReservedColumnId::tsid()) + ); + assert_eq!(Some(&Value::from("raw🦀")), decoded.get(&0)); + assert_eq!(Some(&Value::from("")), decoded.get(&1)); + } + + for op_type in [OpType::Put, OpType::Delete] { + let mut mutation = key_values1.mutation.clone(); + mutation.op_type = op_type as i32; + mutation.rows.as_mut().unwrap().rows[1].values[0].value_data = Some( + api::v1::value::ValueData::BinaryValue(b"truncated".to_vec()), + ); + let invalid = KeyValues::new(&metadata, mutation).unwrap(); + // Raw rows before or after encoded input must not disable its validation. + for batches in [vec![&invalid], vec![&raw, &invalid], vec![&invalid, &raw]] { + let mut invalid_converter = BulkPartConverter::new( + &metadata, + schema.clone(), + capacity, + primary_key_codec.clone(), + true, + ); + for batch in batches { + invalid_converter.append_key_values(batch).unwrap(); + } + assert!(invalid_converter.convert().is_err()); + } + } converter.append_key_values(&key_values1).unwrap(); converter.append_key_values(&key_values2).unwrap(); @@ -2664,6 +2851,26 @@ mod tests { assert_eq!(bulk_part.max_timestamp, 2000); assert_eq!(bulk_part.sequence, 2); assert_eq!(bulk_part.timestamp_index, bulk_part.batch.num_columns() - 4); + assert_eq!( + bulk_part + .batch + .column_by_name("__sequence") + .unwrap() + .as_ref(), + &UInt64Array::from(vec![1, 2, 2]) as &dyn Array, + ); + assert_eq!( + bulk_part + .batch + .column_by_name("__op_type") + .unwrap() + .as_ref(), + &UInt8Array::from(vec![ + OpType::Put as u8, + OpType::Put as u8, + OpType::Delete as u8 + ]) as &dyn Array, + ); // For sparse encoding, primary key columns should NOT be stored individually // even when store_primary_key_columns is true, because sparse encoding @@ -2909,10 +3116,16 @@ mod tests { let primary_key_codec = build_primary_key_codec(&metadata); // Create input batch with __primary_key column (sparse encoding) - let pk_array = Arc::new(arrow::array::BinaryArray::from(vec![ - b"encoded_key_1".as_slice(), - b"encoded_key_2".as_slice(), - ])); + let keys = (1..=2) + .map(|tsid| { + let mut key = Vec::new(); + mito_codec::row_converter::SparsePrimaryKeyCodec::schemaless() + .encode_internal(123, tsid, &mut key) + .unwrap(); + key + }) + .collect::>(); + let pk_array = Arc::new(BinaryArray::from_iter_values(&keys)); let v0_array = Arc::new(arrow::array::Int64Array::from(vec![100, 200])); let v1_array = Arc::new(arrow::array::Float64Array::from(vec![1.0, 2.0])); let ts_array = Arc::new(TimestampMillisecondArray::from(vec![1000, 2000])); @@ -2947,6 +3160,153 @@ mod tests { &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding), ); + let dictionary_values = Arc::new(BinaryArray::from(vec![ + Some(keys[0].as_slice()), + Some(keys[1].as_slice()), + Some(b"truncated".as_slice()), + None, + Some(keys[0].as_slice()), + ])); + let with_keys = |keys: ArrayRef| { + let mut input = part.clone(); + let mut fields = input.batch.schema().fields().to_vec(); + fields[0] = Arc::new(Field::new( + PRIMARY_KEY_COLUMN_NAME, + keys.data_type().clone(), + true, + )); + let mut columns = input.batch.columns().to_vec(); + columns[0] = keys; + input.batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap(); + input + }; + // Slicing retains malformed/null dictionary values outside the selected rows. + let sliced = DictionaryArray::try_new( + UInt32Array::from(vec![2, 0, 1, 3]), + dictionary_values.clone(), + ) + .unwrap() + .slice(1, 2); + for key_type in [ + ArrowDataType::Int8, + ArrowDataType::Int16, + ArrowDataType::Int32, + ArrowDataType::Int64, + ArrowDataType::UInt8, + ArrowDataType::UInt16, + ArrowDataType::UInt32, + ArrowDataType::UInt64, + ] { + let keys = arrow::compute::cast( + &sliced, + &ArrowDataType::Dictionary(Box::new(key_type), Box::new(ArrowDataType::Binary)), + ) + .unwrap(); + let converted = convert_bulk_part( + with_keys(keys), + &metadata, + primary_key_codec.clone(), + output_schema.clone(), + true, + ) + .unwrap() + .unwrap(); + let keys = arrow::compute::cast( + converted + .batch + .column_by_name(PRIMARY_KEY_COLUMN_NAME) + .unwrap(), + &ArrowDataType::Binary, + ) + .unwrap(); + assert_eq!(keys.as_ref(), part.batch.column(0).as_ref()); + for (name, index) in [("v0", 1), ("v1", 2), ("ts", 3)] { + assert_eq!( + converted.batch.column_by_name(name).unwrap().as_ref(), + part.batch.column(index).as_ref() + ); + } + assert_eq!( + converted + .batch + .column_by_name("__sequence") + .unwrap() + .as_ref(), + &UInt64Array::from(vec![7, 7]) as &dyn Array + ); + assert_eq!( + converted + .batch + .column_by_name("__op_type") + .unwrap() + .as_ref(), + &UInt8Array::from(vec![OpType::Put as u8; 2]) as &dyn Array + ); + } + // Equal bytes under distinct dictionary slots remain separate observations. + let repeated = + DictionaryArray::try_new(UInt32Array::from(vec![0, 4]), dictionary_values.clone()) + .unwrap(); + assert_eq!( + convert_bulk_part( + with_keys(Arc::new(repeated)), + &metadata, + primary_key_codec.clone(), + output_schema.clone(), + true + ) + .unwrap() + .unwrap() + .num_rows(), + 2 + ); + for indices in [ + vec![Some(0), Some(2)], + vec![Some(0), Some(3)], + vec![Some(0), None], + ] { + let dictionary = + DictionaryArray::try_new(UInt32Array::from(indices), dictionary_values.clone()) + .unwrap(); + assert!( + convert_bulk_part( + with_keys(Arc::new(dictionary)), + &metadata, + primary_key_codec.clone(), + output_schema.clone(), + true + ) + .is_err() + ); + } + + for invalid_keys in [ + Arc::new(arrow::array::StringArray::from(vec!["invalid"; 2])) as ArrayRef, + Arc::new(BinaryArray::from(vec![None::<&[u8]>; 2])), + Arc::new(BinaryArray::from_iter_values([b"truncated"; 2])), + ] { + let mut invalid = part.clone(); + let mut fields = invalid.batch.schema().fields().to_vec(); + fields[0] = Arc::new(Field::new( + PRIMARY_KEY_COLUMN_NAME, + invalid_keys.data_type().clone(), + true, + )); + let mut columns = invalid.batch.columns().to_vec(); + columns[0] = invalid_keys; + invalid.batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap(); + assert!( + convert_bulk_part( + invalid, + &metadata, + primary_key_codec.clone(), + output_schema.clone(), + true, + ) + .is_err() + ); + } + let result = convert_bulk_part( part, &metadata, diff --git a/src/mito2/src/read/compat.rs b/src/mito2/src/read/compat.rs index 1d4a7f5457b..377b096db26 100644 --- a/src/mito2/src/read/compat.rs +++ b/src/mito2/src/read/compat.rs @@ -113,7 +113,7 @@ impl FlatCompatBatch { if actual.primary_key_encoding == PrimaryKeyEncoding::Sparse && compaction { // Special handling for sparse encoding in compaction. - return FlatCompatBatch::try_new_compact_sparse(mapper, actual); + return FlatCompatBatch::try_new_compact_sparse(mapper, actual, &actual_schema); } let (index_or_defaults, fields) = Self::compute_index_and_fields( @@ -225,33 +225,49 @@ impl FlatCompatBatch { fn try_new_compact_sparse( mapper: &FlatProjectionMapper, actual: &RegionMetadataRef, + actual_schema: &[(ColumnId, ConcreteDataType)], ) -> Result> { // Currently, we don't support converting sparse encoding back to dense encoding in // flat format. ensure!( - mapper.metadata().primary_key_encoding == PrimaryKeyEncoding::Sparse, + mapper.metadata().primary_key_encoding == actual.primary_key_encoding, UnsupportedOperationSnafu { err_msg: "Flat format doesn't support converting sparse encoding back to dense encoding" } ); - // For sparse encoding, we don't need to check the primary keys. - // Since this is for compaction, we always read all columns. - let actual_schema: Vec<_> = actual - .field_columns() - .chain([actual.time_index_column()]) - .map(|col| (col.column_id, col.column_schema.data_type.clone())) - .collect(); - let expect_schema: Vec<_> = mapper - .metadata() - .field_columns() - .chain([mapper.metadata().time_index_column()]) - .map(|col| (col.column_id, col.column_schema.data_type.clone())) - .collect(); + // Encoded sparse tags are not materialized during compaction. Preserve + // the projected JSON2 types: metadata only describes their logical shape. + let mut actual_fields = Vec::with_capacity(actual_schema.len()); + for (id, data_type) in actual_schema { + let column = actual + .column_by_id(*id) + .with_context(|| CompatReaderSnafu { + region_id: actual.region_id, + reason: format!("column {id} is absent from region metadata"), + })?; + if column.semantic_type != SemanticType::Tag { + actual_fields.push((*id, data_type.clone())); + } + } + let mut expect_fields = Vec::with_capacity(mapper.batch_schema().len()); + for (id, data_type) in mapper.batch_schema() { + let column = + mapper + .metadata() + .column_by_id(*id) + .with_context(|| CompatReaderSnafu { + region_id: mapper.metadata().region_id, + reason: format!("column {id} is absent from region metadata"), + })?; + if column.semantic_type != SemanticType::Tag { + expect_fields.push((*id, data_type.clone())); + } + } let (index_or_defaults, fields) = Self::compute_index_and_fields( - &actual_schema, - &expect_schema, + &actual_fields, + &expect_fields, mapper.metadata(), mapper.input_arrow_schema(true).fields(), )?; @@ -552,14 +568,12 @@ impl FlatCompatPrimaryKey { debug_assert!(!fields.is_empty()); // Create converter to append values. - let converter = Some(build_primary_key_codec_with_fields( - expect.primary_key_encoding, - fields.into_iter(), - )); + let converter = + build_primary_key_codec_with_fields(expect.primary_key_encoding, fields.into_iter()); Ok(Self { rewriter, - converter, + converter: Some(converter), values, }) } @@ -675,6 +689,7 @@ mod tests { use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; use store_api::storage::RegionId; + use store_api::storage::consts::ReservedColumnId; use super::*; use crate::read::flat_projection::FlatProjectionMapper; @@ -683,6 +698,7 @@ mod tests { use crate::sst::parquet::{Json2RewriteTargets, Json2TargetLayout}; use crate::sst::{FlatSchemaOptions, to_flat_sst_arrow_schema}; use crate::test_util; + use crate::test_util::sst_util::sst_region_metadata_with_encoding; /// Creates a new [RegionMetadata]. fn new_metadata( @@ -691,7 +707,7 @@ mod tests { ) -> RegionMetadata { let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1)); for (id, semantic_type, data_type) in semantic_types { - let column_schema = match semantic_type { + let mut column_schema = match semantic_type { SemanticType::Tag => { ColumnSchema::new(format!("tag_{id}"), data_type.clone(), true) } @@ -700,6 +716,11 @@ mod tests { } SemanticType::Timestamp => ColumnSchema::new("ts", data_type.clone(), false), }; + if data_type.is_json2() { + column_schema.with_extension_type( + &datatypes::extension::json::Json2ExtensionType::default(), + ); + } builder.push_column_metadata(ColumnMetadata { column_schema, @@ -711,6 +732,24 @@ mod tests { builder.build().unwrap() } + fn with_sparse_encoding(metadata: RegionMetadata) -> RegionMetadata { + let reserved = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse); + let primary_key = reserved + .primary_key + .into_iter() + .take(2) + .chain(metadata.primary_key.iter().copied()) + .collect(); + let mut builder = RegionMetadataBuilder::from_existing(metadata); + for column in reserved.column_metadatas.into_iter().take(2) { + builder.push_column_metadata(column); + } + builder + .primary_key(primary_key) + .primary_key_encoding(PrimaryKeyEncoding::Sparse); + builder.build().unwrap() + } + /// Encode primary key. fn encode_key(keys: &[Option<&str>]) -> Vec { let fields = (0..keys.len()) @@ -727,10 +766,7 @@ mod tests { /// Encode sparse primary key. fn encode_sparse_key(keys: &[(ColumnId, Option<&str>)]) -> Vec { - let fields = (0..keys.len()) - .map(|_| (1, SortField::new(ConcreteDataType::string_datatype()))) - .collect(); - let converter = SparsePrimaryKeyCodec::with_fields(fields); + let converter = SparsePrimaryKeyCodec::schemaless(); let row = keys .iter() .map(|(id, str_opt)| match str_opt { @@ -739,6 +775,7 @@ mod tests { }) .collect::>(); let mut buffer = vec![]; + converter.encode_internal(42, 7, &mut buffer).unwrap(); converter.encode_value_refs(&row, &mut buffer).unwrap(); buffer } @@ -839,10 +876,15 @@ mod tests { assert_eq!(expected_batch, result); } - #[test] - fn test_flat_compat_batch_uses_projected_json2_type() -> Result<()> { + #[rstest::rstest] + #[case(PrimaryKeyEncoding::Dense, false)] + #[case(PrimaryKeyEncoding::Sparse, true)] + fn test_flat_compat_batch_uses_projected_json2_type( + #[case] encoding: PrimaryKeyEncoding, + #[case] compaction: bool, + ) -> Result<()> { let json2 = ConcreteDataType::json2(JsonNativeType::object()); - let actual_metadata = Arc::new(new_metadata( + let mut actual_metadata = Arc::new(new_metadata( &[ ( 0, @@ -853,7 +895,7 @@ mod tests { ], &[], )); - let expected_metadata = Arc::new(new_metadata( + let mut expected_metadata = Arc::new(new_metadata( &[ ( 0, @@ -865,6 +907,10 @@ mod tests { ], &[], )); + if encoding == PrimaryKeyEncoding::Sparse { + actual_metadata = Arc::new(with_sparse_encoding((*actual_metadata).clone())); + expected_metadata = Arc::new(with_sparse_encoding((*expected_metadata).clone())); + } let read_columns = ReadColumns::new([0, 1, 2]) .with_json_target_types(BTreeMap::from([(1, JsonNativeType::Variant)])); let mapper = FlatProjectionMapper::new_with_read_columns( @@ -874,7 +920,7 @@ mod tests { )?; let read_format = FlatReadFormat::new(actual_metadata, read_columns, None, "test", false)?; - let compat = FlatCompatBatch::try_new(&mapper, &read_format, false)?.unwrap(); + let compat = FlatCompatBatch::try_new(&mapper, &read_format, compaction)?.unwrap(); let json_index = mapper .batch_schema() .iter() @@ -887,6 +933,10 @@ mod tests { .. } )); + assert_eq!( + compat.arrow_schema.field(json_index).data_type(), + &datatypes::arrow::datatypes::DataType::Binary + ); Ok(()) } @@ -995,6 +1045,7 @@ mod tests { ], &[1], ); + actual_metadata = with_sparse_encoding(actual_metadata); actual_metadata.primary_key_encoding = PrimaryKeyEncoding::Dense; let actual_metadata = Arc::new(actual_metadata); @@ -1011,13 +1062,20 @@ mod tests { ], &[1, 3], ); - expected_metadata.primary_key_encoding = PrimaryKeyEncoding::Sparse; + expected_metadata = with_sparse_encoding(expected_metadata); let expected_metadata = Arc::new(expected_metadata); let mapper = FlatProjectionMapper::all(&expected_metadata).unwrap(); let read_format = FlatReadFormat::new( actual_metadata.clone(), - ReadColumns::new([0, 1, 2, 3]), + ReadColumns::new([ + 0, + 1, + 2, + 3, + ReservedColumnId::table_id(), + ReservedColumnId::tsid(), + ]), None, "test", false, @@ -1034,8 +1092,20 @@ mod tests { tag1_builder.append_value("tag1"); let tag1_dict_array = Arc::new(tag1_builder.finish()); - let k1 = encode_key(&[Some("tag1")]); + let mut k1 = Vec::new(); + build_primary_key_codec(&actual_metadata) + .encode_values( + &[ + (ReservedColumnId::table_id(), Value::UInt32(42)), + (ReservedColumnId::tsid(), Value::UInt64(7)), + (1, Value::from("tag1")), + ], + &mut k1, + ) + .unwrap(); let input_columns: Vec = vec![ + Arc::new(datatypes::arrow::array::UInt32Array::from(vec![42, 42])), + Arc::new(UInt64Array::from(vec![7, 7])), tag1_dict_array.clone(), Arc::new(Int64Array::from(vec![100, 200])), Arc::new(TimestampMillisecondArray::from_iter_values([1000, 2000])), @@ -1057,6 +1127,8 @@ mod tests { null_tag_builder.append_nulls(2); let null_tag_dict_array = Arc::new(null_tag_builder.finish()); let expected_columns: Vec = vec![ + Arc::new(datatypes::arrow::array::UInt32Array::from(vec![42, 42])), + Arc::new(UInt64Array::from(vec![7, 7])), tag1_dict_array.clone(), null_tag_dict_array, Arc::new(Int64Array::from(vec![100, 200])), @@ -1075,6 +1147,52 @@ mod tests { assert_eq!(expected_batch, result); } + #[test] + fn test_compat_sparse_primary_key_with_new_nullable_tag() { + let actual = Arc::new(sst_region_metadata_with_encoding( + PrimaryKeyEncoding::Sparse, + )); + let mut builder = RegionMetadataBuilder::from_existing((*actual).clone()); + let mut primary_key = actual.primary_key.clone(); + primary_key.push(4); + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "new_tag", + ConcreteDataType::string_datatype(), + true, + ), + semantic_type: SemanticType::Tag, + column_id: 4, + }) + .primary_key(primary_key); + let expected = Arc::new(builder.build().unwrap()); + let compat = FlatCompatPrimaryKey::new(&expected, &actual).unwrap(); + + let values = vec![ + (ReservedColumnId::table_id(), Value::UInt32(23)), + (ReservedColumnId::tsid(), Value::UInt64(42)), + (0, Value::from("api")), + (1, Value::Null), + ]; + let mut key = Vec::new(); + build_primary_key_codec(&actual) + .encode_values(&values, &mut key) + .unwrap(); + + // Adding a NULL sparse tag must preserve the existing key, including metric IDs. + let dictionary_key = build_flat_test_pk_array(&[&key, &key]); + let binary_key: ArrayRef = Arc::new(BinaryArray::from(vec![ + Some(key.as_slice()), + None, + Some(key.as_slice()), + ])); + for input in [dictionary_key, binary_key] { + let result = compat.compat(&input).unwrap(); + assert_eq!(result.as_ref(), input.as_ref()); + } + } + #[test] fn test_compat_primary_key_with_different_encoding_only() { let mut actual_metadata = new_metadata( @@ -1089,6 +1207,7 @@ mod tests { ], &[1], ); + actual_metadata = with_sparse_encoding(actual_metadata); actual_metadata.primary_key_encoding = PrimaryKeyEncoding::Dense; let actual_metadata = Arc::new(actual_metadata); @@ -1098,8 +1217,14 @@ mod tests { let mapper = FlatProjectionMapper::all(&expected_metadata).unwrap(); let read_format = FlatReadFormat::new( - actual_metadata, - ReadColumns::new([0, 1, 2]), + actual_metadata.clone(), + ReadColumns::new([ + 0, + 1, + 2, + ReservedColumnId::table_id(), + ReservedColumnId::tsid(), + ]), None, "test", false, @@ -1109,7 +1234,17 @@ mod tests { .unwrap() .unwrap(); - let dense_key = encode_key(&[Some("tag1")]); + let mut dense_key = Vec::new(); + build_primary_key_codec(&actual_metadata) + .encode_values( + &[ + (ReservedColumnId::table_id(), Value::UInt32(42)), + (ReservedColumnId::tsid(), Value::UInt64(7)), + (1, Value::from("tag1")), + ], + &mut dense_key, + ) + .unwrap(); let sparse_key = encode_sparse_key(&[(1, Some("tag1"))]); let dictionary_key = build_flat_test_pk_array(&[&dense_key, &dense_key]); @@ -1344,19 +1479,8 @@ mod tests { ], &[], ); - let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding( - PrimaryKeyEncoding::Sparse, - ); - actual_metadata.primary_key = reserved.primary_key.into_iter().take(2).collect(); - actual_metadata - .column_metadatas - .extend(reserved.column_metadatas.into_iter().take(2)); - actual_metadata.primary_key_encoding = PrimaryKeyEncoding::Sparse; - let actual_metadata = Arc::new( - RegionMetadataBuilder::from_existing(actual_metadata) - .build() - .unwrap(), - ); + actual_metadata = with_sparse_encoding(actual_metadata); + let actual_metadata = Arc::new(actual_metadata); let mut expected_metadata = (*actual_metadata).clone(); for column in expected_metadata.column_metadatas.iter_mut() { @@ -1440,7 +1564,7 @@ mod tests { ], &[], ); - actual_metadata.primary_key_encoding = PrimaryKeyEncoding::Sparse; + actual_metadata = with_sparse_encoding(actual_metadata); let actual_metadata = Arc::new(actual_metadata); let mut expected_metadata = new_metadata( @@ -1455,7 +1579,7 @@ mod tests { ], &[], ); - expected_metadata.primary_key_encoding = PrimaryKeyEncoding::Sparse; + expected_metadata = with_sparse_encoding(expected_metadata); let expected_metadata = Arc::new(expected_metadata); let mapper = FlatProjectionMapper::all(&expected_metadata).unwrap(); @@ -1483,8 +1607,10 @@ mod tests { OpType::Put as u8, ])), ]; - let input_schema = - to_flat_sst_arrow_schema(&actual_metadata, &FlatSchemaOptions::default()); + let input_schema = to_flat_sst_arrow_schema( + &actual_metadata, + &FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Sparse), + ); let input_batch = RecordBatch::try_new(input_schema, input_columns).unwrap(); let result = compat_batch.compat(input_batch).unwrap(); @@ -1500,8 +1626,10 @@ mod tests { OpType::Put as u8, ])), ]; - let output_schema = - to_flat_sst_arrow_schema(&expected_metadata, &FlatSchemaOptions::default()); + let output_schema = to_flat_sst_arrow_schema( + &expected_metadata, + &FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Sparse), + ); let expected_batch = RecordBatch::try_new(output_schema, expected_columns).unwrap(); assert_eq!(expected_batch, result); @@ -1561,12 +1689,18 @@ mod tests { } else { metadata.as_ref().clone() }; - let mut actual_builder = RegionMetadataBuilder::from_existing(source); - actual_builder.primary_key_encoding(encoding); - let mut expected_builder = - RegionMetadataBuilder::from_existing(metadata.as_ref().clone()); - expected_builder.primary_key_encoding(encoding); - expected_builder.push_column_metadata(ColumnMetadata { + let actual = Arc::new(if encoding == PrimaryKeyEncoding::Sparse { + with_sparse_encoding(source) + } else { + source + }); + let expected = if encoding == PrimaryKeyEncoding::Sparse { + with_sparse_encoding(metadata.as_ref().clone()) + } else { + metadata.as_ref().clone() + }; + let mut builder = RegionMetadataBuilder::from_existing(expected); + builder.push_column_metadata(ColumnMetadata { column_schema: ColumnSchema::new( "added", ConcreteDataType::int64_datatype(), @@ -1578,21 +1712,11 @@ mod tests { semantic_type: SemanticType::Field, column_id: 2, }); - if encoding == PrimaryKeyEncoding::Sparse { - let reserved = test_util::sst_util::sst_region_metadata_with_encoding(encoding); - for builder in [&mut actual_builder, &mut expected_builder] { - builder.primary_key(reserved.primary_key[..2].to_vec()); - for column in reserved.column_metadatas.iter().take(2) { - builder.push_column_metadata(column.clone()); - } - } - } - let actual = Arc::new(actual_builder.build()?); - let expected = Arc::new(expected_builder.build()?); + let expected = Arc::new(builder.build()?); let read_columns = ReadColumns::new([0, 1, 2]); let mapper = FlatProjectionMapper::new_with_json2_rewrite_targets( &expected, - vec![0, 1, 2], + vec![0, 1, expected.column_index_by_id(2).unwrap()], read_columns.clone(), &targets, )?; diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index 923f223c8c7..819f32cf7e8 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -2282,6 +2282,7 @@ mod tests { manifest_cache: None, }, FormatType::PrimaryKey, + false, &Default::default(), ) .await @@ -2835,6 +2836,7 @@ mod tests { manifest_cache: None, }, FormatType::PrimaryKey, + false, &Default::default(), ) .await @@ -2903,6 +2905,7 @@ mod tests { manifest_cache: None, }, FormatType::PrimaryKey, + false, &Default::default(), ) .await diff --git a/src/mito2/src/region/opener.rs b/src/mito2/src/region/opener.rs index d10545198f7..ba4fe615951 100644 --- a/src/mito2/src/region/opener.rs +++ b/src/mito2/src/region/opener.rs @@ -403,6 +403,7 @@ impl RegionOpener { flushed_entry_id, region_manifest_options, sst_format, + options.append_mode, &self.stats, ) .await?; @@ -795,6 +796,20 @@ pub(crate) fn version_builder_from_manifest( /// Updates region options by persistent options. pub(crate) fn sanitize_region_options(manifest: &RegionManifest, options: &mut RegionOptions) { + if let Some(encoding) = options.primary_key_encoding + && encoding != manifest.metadata.primary_key_encoding + { + common_telemetry::warn!( + "Overriding primary key encoding from {:?} to {:?} for region {}", + encoding, + manifest.metadata.primary_key_encoding, + manifest.metadata.region_id, + ); + } + options.primary_key_encoding = Some(manifest.metadata.primary_key_encoding); + if manifest.metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse { + options.sst_format = Some(FormatType::Flat); + } // Caller options take precedence over the manifest, except JSON2 always requires flat output. let format = options.sst_format.unwrap_or(manifest.sst_format); // Older versions allowed JSON2 with primary-key output; recover without rewriting its history. @@ -1009,9 +1024,7 @@ where // columns like the write path, otherwise the memtable rejects the // batch. Skips sparse batches as they don't carry tag columns by // design. - if region_metadata.primary_key_encoding != PrimaryKeyEncoding::Sparse { - part.fill_missing_columns(®ion_metadata)?; - } + part.fill_missing_columns(®ion_metadata)?; rows_replayed += part.num_rows(); // During replay, we should adopt the sequence from WAL. let bulk_sequence_from_wal = part.sequence; @@ -1447,6 +1460,7 @@ fn can_load_cache(state: RegionRoleState) -> bool { mod tests { use std::collections::HashMap; use std::sync::Arc; + use store_api::codec::PrimaryKeyEncoding; use arrow_schema::extension::ExtensionType; use common_base::readable_size::ReadableSize; @@ -1627,6 +1641,22 @@ mod tests { )); } + #[test] + fn test_sparse_reopen_uses_persisted_encoding_and_flat_sst() { + for supplied in [None, Some(PrimaryKeyEncoding::Dense)] { + let mut manifest = build_test_manifest(FormatType::PrimaryKey); + Arc::make_mut(&mut manifest.metadata).primary_key_encoding = PrimaryKeyEncoding::Sparse; + let mut options = RegionOptions { + primary_key_encoding: supplied, + sst_format: Some(FormatType::PrimaryKey), + ..Default::default() + }; + sanitize_region_options(&manifest, &mut options); + assert_eq!(options.primary_key_encoding(), PrimaryKeyEncoding::Sparse); + assert_eq!(options.sst_format, Some(FormatType::Flat)); + } + } + #[test] fn test_sanitize_region_options_options_format_wins() { // Manifest persisted PrimaryKey, but the re-parsed options now request Flat diff --git a/src/mito2/src/region/options.rs b/src/mito2/src/region/options.rs index 58fdec15ad5..85cb79928cd 100644 --- a/src/mito2/src/region/options.rs +++ b/src/mito2/src/region/options.rs @@ -120,7 +120,7 @@ pub struct RegionOptions { /// Max number of rows in a parquet row group. Uses [DEFAULT_ROW_GROUP_SIZE] if `None`. #[serde(skip_serializing_if = "Option::is_none")] pub max_row_group_row_count: Option, - /// Internal primary key encoding override used by metric-engine. + /// Primary key encoding. Sparse regions require reserved table ID and TSID columns. #[serde(skip_serializing_if = "Option::is_none")] pub primary_key_encoding: Option, /// Per-region write buffer size. A positive size flushes/stalls this region @@ -313,6 +313,19 @@ impl RegionOptions { None }; + let primary_key_encoding = options_map + .get(PRIMARY_KEY_ENCODING) + .or_else(|| options_map.get(MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING)) + .map(|v| match v.to_lowercase().as_str() { + "dense" => Ok(PrimaryKeyEncoding::Dense), + "sparse" => Ok(PrimaryKeyEncoding::Sparse), + _ => Err(InvalidRegionOptionsSnafu { + reason: format!("Invalid primary key encoding: {v}"), + } + .build()), + }) + .transpose()?; + // The partition tree memtable has been removed. Besides falling back to // the default memtable, also override the SST format to flat. let mut sst_format = options.sst_format; @@ -327,7 +340,9 @@ impl RegionOptions { // Bulk memtable produces flat-encoded ranges and flushes them through // `put_sst()`, so the SST format must be flat to match. - if matches!(memtable, Some(MemtableOptions::Bulk(_))) { + if matches!(memtable, Some(MemtableOptions::Bulk(_))) + || primary_key_encoding == Some(PrimaryKeyEncoding::Sparse) + { if let Some(format) = sst_format && format != FormatType::Flat { @@ -346,18 +361,6 @@ impl RegionOptions { .map(|v| matches!(v.to_lowercase().as_str(), "true" | "1")) .unwrap_or(false); let compaction_override = has_compaction_type || compaction_override_flag; - let primary_key_encoding = options_map - .get(PRIMARY_KEY_ENCODING) - .or_else(|| options_map.get(MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING)) - .map(|v| match v.to_lowercase().as_str() { - "dense" => Ok(PrimaryKeyEncoding::Dense), - "sparse" => Ok(PrimaryKeyEncoding::Sparse), - _ => Err(InvalidRegionOptionsSnafu { - reason: format!("Invalid primary key encoding: {v}"), - } - .build()), - }) - .transpose()?; let opts = RegionOptions { ttl: options.ttl, @@ -1029,6 +1032,19 @@ mod tests { assert_eq!(expect, options); } + #[test] + fn test_sparse_forces_flat_sst() { + for format in [None, Some("primary_key"), Some("flat")] { + let mut map = make_map(&[("primary_key_encoding", "sparse")]); + if let Some(format) = format { + map.insert("sst_format".into(), format.into()); + } + let options = RegionOptions::try_from_options(RegionId::new(0, 0), &map).unwrap(); + assert_eq!(options.primary_key_encoding(), PrimaryKeyEncoding::Sparse); + assert_eq!(options.sst_format, Some(FormatType::Flat)); + } + } + #[test] fn test_primary_key_encoding() { // New top-level key. diff --git a/src/mito2/src/request.rs b/src/mito2/src/request.rs index d7e12a5da60..9c0178710f1 100644 --- a/src/mito2/src/request.rs +++ b/src/mito2/src/request.rs @@ -526,6 +526,7 @@ impl RequestColumn for RowColumn<'_> { /// A column of the batch of a bulk insert. struct BulkColumn<'a> { array: &'a ArrayRef, + field: &'a datatypes::arrow::datatypes::Field, } impl RequestColumn for BulkColumn<'_> { @@ -539,6 +540,11 @@ impl RequestColumn for BulkColumn<'_> { actual => actual.is_string(), }; } + if data_type.is_json2() && datatypes::extension::json::is_json2_extension_type(self.field) { + return matches!(actual, ArrowDataType::Struct(_) | ArrowDataType::Null) + && datatypes::extension::json::json2_remainder_field(self.field).is_ok() + && datatypes::types::json_type::JsonNativeType::try_from(actual).is_ok(); + } *actual == data_type.as_arrow_type() } @@ -559,7 +565,7 @@ impl RequestColumn for BulkColumn<'_> { /// [WriteRequest::check_schema] applies to rows: column names are unique, every /// column is a column of the region with its Arrow type and contains nulls only /// if the region column is nullable, and a missing column is nullable or has a -/// default value. Tags may use any string encoding. Sparse batches carry the +/// default value. Tags may use any string encoding. Sparse batches may carry the /// tags in one encoded primary key column instead. Returns whether the batch /// misses columns that the writer fills. pub fn check_bulk_insert_batch(metadata: &RegionMetadata, batch: &RecordBatch) -> Result { @@ -572,7 +578,7 @@ pub fn check_bulk_insert_batch(metadata: &RegionMetadata, batch: &RecordBatch) - primary_key.replace(array).is_some() } else { columns - .insert(field.name().as_str(), BulkColumn { array }) + .insert(field.name().as_str(), BulkColumn { array, field }) .is_some() }; ensure!( @@ -583,11 +589,7 @@ pub fn check_bulk_insert_batch(metadata: &RegionMetadata, batch: &RecordBatch) - } ); } - if sparse { - let primary_key = primary_key.with_context(|| InvalidRequestSnafu { - region_id, - reason: format!("missing column {PRIMARY_KEY_COLUMN_NAME}"), - })?; + if let Some(primary_key) = primary_key { // The writer casts the encoded primary key to a dictionary of binary. let type_matches = match primary_key.data_type() { ArrowDataType::Binary => true, @@ -609,7 +611,7 @@ pub fn check_bulk_insert_batch(metadata: &RegionMetadata, batch: &RecordBatch) - } let mut needs_fill = false; check_request_columns(region_id, metadata, columns, |column| { - if sparse && column.semantic_type == SemanticType::Tag { + if primary_key.is_some() && column.semantic_type == SemanticType::Tag { Ok(()) } else { needs_fill = true; diff --git a/src/mito2/src/sst/primary_key.rs b/src/mito2/src/sst/primary_key.rs index 7752a652f80..2d3f8c90e3b 100644 --- a/src/mito2/src/sst/primary_key.rs +++ b/src/mito2/src/sst/primary_key.rs @@ -654,12 +654,27 @@ mod tests { #[test] fn test_sparse_ranges_keep_their_original_encoding() { use mito_codec::row_converter::SparsePrimaryKeyCodec; - let mut metadata = (*metadata(&[Value::from(""), Value::Null])).clone(); - metadata.primary_key_encoding = PrimaryKeyEncoding::Sparse; - let metadata = Arc::new(metadata); + let metadata = Arc::new( + crate::test_util::sst_util::sst_region_metadata_with_encoding( + PrimaryKeyEncoding::Sparse, + ), + ); let mut bytes = Vec::new(); SparsePrimaryKeyCodec::new(&metadata) - .encode_values(&[(0, Value::from("a"))], &mut bytes) + .encode_values( + &[ + ( + store_api::storage::consts::ReservedColumnId::table_id(), + Value::UInt32(42), + ), + ( + store_api::storage::consts::ReservedColumnId::tsid(), + Value::UInt64(7), + ), + (0, Value::from("a")), + ], + &mut bytes, + ) .unwrap(); let key = Bytes::from(bytes); let mapper = PrimaryKeyRangeMapper::new(metadata); diff --git a/src/mito2/src/test_util.rs b/src/mito2/src/test_util.rs index f265494058a..1d742505df4 100644 --- a/src/mito2/src/test_util.rs +++ b/src/mito2/src/test_util.rs @@ -841,6 +841,7 @@ impl TestEnv { 0, manifest_opts, FormatType::PrimaryKey, + false, &Default::default(), ) .await diff --git a/src/mito2/src/test_util/scheduler_util.rs b/src/mito2/src/test_util/scheduler_util.rs index f97886b4ea2..3185a9895a3 100644 --- a/src/mito2/src/test_util/scheduler_util.rs +++ b/src/mito2/src/test_util/scheduler_util.rs @@ -147,6 +147,7 @@ impl SchedulerEnv { manifest_cache: None, }, FormatType::PrimaryKey, + false, &Default::default(), ) .await diff --git a/src/store-api/src/mito_engine_options.rs b/src/store-api/src/mito_engine_options.rs index 1f680aff995..6a0d2b13d02 100644 --- a/src/store-api/src/mito_engine_options.rs +++ b/src/store-api/src/mito_engine_options.rs @@ -182,7 +182,7 @@ pub fn is_mito_engine_option_key(key: &str) -> bool { MEMTABLE_PARTITION_TREE_INDEX_MAX_KEYS_PER_SHARD, MEMTABLE_PARTITION_TREE_DATA_FREEZE_THRESHOLD, MEMTABLE_PARTITION_TREE_FORK_DICTIONARY_BYTES, - // We don't allow to create a mito table with sparse primary key encoding directly. + crate::metric_engine_consts::PRIMARY_KEY_ENCODING, APPEND_MODE_KEY, MERGE_MODE_KEY, SST_FORMAT_KEY, diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 2a2bc7b7f1f..fb3c7f01b90 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -318,7 +318,8 @@ pub struct ScannerProperties { /// The target partitions of the scanner. 0 indicates using the number of partitions as target partitions. target_partitions: usize, - /// Whether the scanner is scanning a logical region. + /// Whether the scanner reads one logical metric region, including a physical + /// metric region constrained by a table-ID filter. logical_region: bool, /// Region id that should receive query-load metrics for this scanner. @@ -392,7 +393,8 @@ impl ScannerProperties { self.total_rows_is_exact } - /// Returns whether the scanner is scanning a logical region. + /// Returns whether the scanner reads one logical metric region, including a + /// physical metric region constrained by a table-ID filter. pub fn is_logical_region(&self) -> bool { self.logical_region } @@ -406,7 +408,7 @@ impl ScannerProperties { } } - /// Sets whether the scanner is reading a logical region. + /// Sets whether the scanner reads one logical metric region. pub fn set_logical_region(&mut self, logical_region: bool) { self.logical_region = logical_region; } @@ -535,7 +537,8 @@ pub trait RegionScanner: Debug + DisplayAs + Send { /// The default is a no-op and does not make inherently one-shot sources replayable. fn reset_state(&mut self) {} - /// Sets whether the scanner is reading a logical region. + /// Sets whether the scanner reads one logical metric region, including a + /// physical metric region constrained by a table-ID filter. fn set_logical_region(&mut self, logical_region: bool); /// Sets the region id that should receive query-load metrics. diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs index 2dd501e678f..80878fae5bc 100644 --- a/src/table/src/table/scan.rs +++ b/src/table/src/table/scan.rs @@ -185,16 +185,14 @@ impl RegionScanExec { } orderings.push(pk_time_ordering); - // Metric engine physical tables keep tag columns alongside `__tsid`. When `__tsid` - // is present, the scan output is also ordered by `(__tsid, time index)` which can - // help eliminate redundant sorts for promql plans (e.g. SeriesDivide). - // - // `pk_time_ordering` and the potential `(__tsid, time index)` ordering are actually - // the same thing, thus present in one `OrderingEquivalenceClass`. - if let (Ok(tsid_col), Some(ts)) = ( - Column::new_with_schema(DATA_SCHEMA_TSID_COLUMN_NAME, &arrow_schema), - ts_col.clone(), - ) { + // Only logical metric scans constrain the physical key to one source table. + // A shared table can have the same TSID under different table IDs. + if scanner_props.is_logical_region() + && let (Ok(tsid_col), Some(ts)) = ( + Column::new_with_schema(DATA_SCHEMA_TSID_COLUMN_NAME, &arrow_schema), + ts_col.clone(), + ) + { orderings.push(vec![ PhysicalSortExpr::new( Arc::new(tsid_col) as _, @@ -225,13 +223,13 @@ impl RegionScanExec { let partitioning = match request.distribution { Some(TimeSeriesDistribution::PerSeries) => { match Column::new_with_schema(DATA_SCHEMA_TSID_COLUMN_NAME, &arrow_schema) { - Ok(tsid_col) => { + Ok(tsid_col) if scanner_props.is_logical_region() => { Partitioning::Hash(vec![Arc::new(tsid_col) as _], num_output_partition) } - Err(_) if pk_columns.len() == pk_names.len() => { + _ if pk_columns.len() == pk_names.len() => { Partitioning::Hash(pk_columns.clone(), num_output_partition) } - Err(_) => Partitioning::UnknownPartitioning(num_output_partition), + _ => Partitioning::UnknownPartitioning(num_output_partition), } } Some(TimeSeriesDistribution::TimeWindowed) | None => { @@ -1146,10 +1144,11 @@ mod test { ]); let metadata = Arc::new(builder.build().unwrap()); - for (projection, partitioned_by_tsid, claimed, unclaimed) in [ + for (projection, logical_region, partitioned_by_tsid, claimed, unclaimed) in [ ( vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME, "A", "ts"], false, + false, vec![vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME]], vec![vec!["A"], vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME, "ts"]], ), @@ -1157,6 +1156,7 @@ mod test { // row key and neither `A` nor `ts` is ordered. ( vec!["A", "marker", "ts"], + true, false, vec![], vec![vec!["A"], vec!["marker"], vec!["ts"], vec!["A", "ts"]], @@ -1165,12 +1165,24 @@ mod test { ( vec![DATA_SCHEMA_TSID_COLUMN_NAME, "A", "marker", "ts"], true, + true, vec![ vec![DATA_SCHEMA_TSID_COLUMN_NAME], vec![DATA_SCHEMA_TSID_COLUMN_NAME, "ts"], ], vec![vec!["A"], vec!["ts"], vec!["A", "ts"]], ), + // Shared exemplar tables project TSID too, but span multiple source tables. + ( + vec![DATA_SCHEMA_TSID_COLUMN_NAME, "A", "marker", "ts"], + false, + false, + vec![], + vec![ + vec![DATA_SCHEMA_TSID_COLUMN_NAME], + vec![DATA_SCHEMA_TSID_COLUMN_NAME, "ts"], + ], + ), ] { let schema = Arc::new(Schema::new( projection @@ -1179,7 +1191,7 @@ mod test { .collect(), )); let mut properties = ScannerProperties::new(vec![vec![], vec![]], false, 0); - properties.set_logical_region(true); + properties.set_logical_region(logical_region); let scanner = Box::new(RepeatableScanner { batches: RecordBatches::try_new(schema, vec![]).unwrap(), properties, diff --git a/tests-integration/src/tests/instance_test.rs b/tests-integration/src/tests/instance_test.rs index 3b3dca0bbd0..4f6cd5a3fab 100644 --- a/tests-integration/src/tests/instance_test.rs +++ b/tests-integration/src/tests/instance_test.rs @@ -43,6 +43,43 @@ use crate::tests::test_util::{ standalone_instance_case, standalone_with_multiple_object_stores, }; +#[apply(both_instances_cases)] +async fn test_sparse_primary_key_schema_validation(instance: Arc) { + let instance = instance.frontend(); + for columns in [ + "host STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, val DOUBLE", + "host BIGINT PRIMARY KEY, ts TIMESTAMP TIME INDEX, val DOUBLE", + "ts TIMESTAMP TIME INDEX, val DOUBLE", + "__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, ts TIMESTAMP TIME INDEX, PRIMARY KEY (__table_id, __tsid)", + ] { + let error = try_execute_sql( + &instance, + &format!("CREATE TABLE sparse_tags ({columns}) WITH ('primary_key_encoding'='sparse')"), + ) + .await + .unwrap_err(); + assert!( + error + .output_msg() + .contains("sparse primary keys must start with (__table_id, __tsid)"), + "{error:?}" + ); + } + + // Reusing the name verifies that rejected creation did not persist the invalid schema. + execute_sql( + &instance, + "CREATE TABLE sparse_tags (host STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, val DOUBLE)", + ) + .await; + execute_sql(&instance, "INSERT INTO sparse_tags VALUES ('a', 1000, 2.0)").await; + let output = execute_sql(&instance, "SELECT COUNT(*) FROM sparse_tags").await; + assert_eq!( + output.data.pretty_print().await, + "+----------+\n| count(*) |\n+----------+\n| 1 |\n+----------+" + ); +} + #[apply(both_instances_cases)] async fn test_create_database_and_insert_query(instance: Arc) { let instance = instance.frontend(); diff --git a/tests/cases/standalone/common/types/json/exemplar_sparse.result b/tests/cases/standalone/common/types/json/exemplar_sparse.result new file mode 100644 index 00000000000..6836e12813f --- /dev/null +++ b/tests/cases/standalone/common/types/json/exemplar_sparse.result @@ -0,0 +1,47 @@ +-- A shared table's TSID does not imply ordering across source table IDs. +CREATE TABLE exemplar_tsid_order ( + __table_id INT UNSIGNED, + __tsid BIGINT UNSIGNED, + greptime_metric STRING, + ts TIMESTAMP TIME INDEX, + greptime_value DOUBLE, + PRIMARY KEY (__table_id, __tsid, greptime_metric) +) WITH ('append_mode'='true'); + +Affected Rows: 0 + +INSERT INTO exemplar_tsid_order VALUES + (1, 7, 'cpu', 20, 1), (2, 7, 'memory', 10, 2); + +Affected Rows: 2 + +SELECT __tsid, ts, greptime_value FROM exemplar_tsid_order ORDER BY __tsid, ts; + ++--------+-------------------------+----------------+ +| __tsid | ts | greptime_value | ++--------+-------------------------+----------------+ +| 7 | 1970-01-01T00:00:00.010 | 2.0 | +| 7 | 1970-01-01T00:00:00.020 | 1.0 | ++--------+-------------------------+----------------+ + +ADMIN FLUSH_TABLE('exemplar_tsid_order'); + ++------------------------------------------+ +| ADMIN FLUSH_TABLE('exemplar_tsid_order') | ++------------------------------------------+ +| 0 | ++------------------------------------------+ + +SELECT __tsid, ts, greptime_value FROM exemplar_tsid_order ORDER BY __tsid, ts; + ++--------+-------------------------+----------------+ +| __tsid | ts | greptime_value | ++--------+-------------------------+----------------+ +| 7 | 1970-01-01T00:00:00.010 | 2.0 | +| 7 | 1970-01-01T00:00:00.020 | 1.0 | ++--------+-------------------------+----------------+ + +DROP TABLE exemplar_tsid_order; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/types/json/exemplar_sparse.sql b/tests/cases/standalone/common/types/json/exemplar_sparse.sql new file mode 100644 index 00000000000..20958fc20e3 --- /dev/null +++ b/tests/cases/standalone/common/types/json/exemplar_sparse.sql @@ -0,0 +1,15 @@ +-- A shared table's TSID does not imply ordering across source table IDs. +CREATE TABLE exemplar_tsid_order ( + __table_id INT UNSIGNED, + __tsid BIGINT UNSIGNED, + greptime_metric STRING, + ts TIMESTAMP TIME INDEX, + greptime_value DOUBLE, + PRIMARY KEY (__table_id, __tsid, greptime_metric) +) WITH ('append_mode'='true'); +INSERT INTO exemplar_tsid_order VALUES + (1, 7, 'cpu', 20, 1), (2, 7, 'memory', 10, 2); +SELECT __tsid, ts, greptime_value FROM exemplar_tsid_order ORDER BY __tsid, ts; +ADMIN FLUSH_TABLE('exemplar_tsid_order'); +SELECT __tsid, ts, greptime_value FROM exemplar_tsid_order ORDER BY __tsid, ts; +DROP TABLE exemplar_tsid_order; diff --git a/tests/compatibility/cases/exemplar_legacy_keys/case.toml b/tests/compatibility/cases/exemplar_legacy_keys/case.toml new file mode 100644 index 00000000000..89b629d1766 --- /dev/null +++ b/tests/compatibility/cases/exemplar_legacy_keys/case.toml @@ -0,0 +1,8 @@ +name = "exemplar_legacy_keys" +reason = "Reserved sparse key validation must preserve existing dense and metric-engine sparse data." +introduced_by = "persistent_metric_exemplars" +topologies = ["standalone", "distributed"] +from_range = [">=v1.2.1"] +to_range = [">=v1.4.0-alpha.0"] +features = ["metric", "sparse", "table", "read"] +owner = "mito2" diff --git a/tests/compatibility/cases/exemplar_legacy_keys/setup.sql b/tests/compatibility/cases/exemplar_legacy_keys/setup.sql new file mode 100644 index 00000000000..c063ecf04a5 --- /dev/null +++ b/tests/compatibility/cases/exemplar_legacy_keys/setup.sql @@ -0,0 +1,17 @@ +CREATE TABLE dense_keys (ts TIMESTAMP TIME INDEX, host STRING PRIMARY KEY, val DOUBLE); +INSERT INTO dense_keys (ts, host, val) VALUES (1, 'api', 1.5), (2, NULL, 2.5); +ADMIN FLUSH_TABLE('dense_keys'); +CREATE TABLE metric_keys (ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric +WITH ('physical_metric_table'='', 'memtable.type'='bulk', 'primary_key_encoding'='sparse'); +CREATE TABLE logical_keys (ts TIMESTAMP TIME INDEX, host STRING PRIMARY KEY, val DOUBLE) ENGINE=metric +WITH ('on_physical_table'='metric_keys'); +INSERT INTO logical_keys (ts, host, val) VALUES (1, 'api', 3.5), (2, NULL, 4.5); +ADMIN FLUSH_TABLE('metric_keys'); +-- Historical OTLP infinity labels must retain their identity after upgrade. +CREATE TABLE otlp_upgrade_bucket ( + greptime_timestamp TIMESTAMP(3) TIME INDEX, + le STRING PRIMARY KEY, + greptime_value DOUBLE +); +INSERT INTO otlp_upgrade_bucket VALUES (10000, 'inf', 1), (20000, 'inf', 2); +ADMIN FLUSH_TABLE('otlp_upgrade_bucket'); diff --git a/tests/compatibility/cases/exemplar_legacy_keys/verify.result b/tests/compatibility/cases/exemplar_legacy_keys/verify.result new file mode 100644 index 00000000000..59d7b04ccac --- /dev/null +++ b/tests/compatibility/cases/exemplar_legacy_keys/verify.result @@ -0,0 +1,85 @@ +SELECT ts, host, val FROM dense_keys ORDER BY ts; + ++-------------------------+------+-----+ +| ts | host | val | ++-------------------------+------+-----+ +| 1970-01-01T00:00:00.001 | api | 1.5 | +| 1970-01-01T00:00:00.002 | | 2.5 | ++-------------------------+------+-----+ + +SELECT ts, host, val FROM logical_keys ORDER BY ts; + ++-------------------------+------+-----+ +| ts | host | val | ++-------------------------+------+-----+ +| 1970-01-01T00:00:00.001 | api | 3.5 | +| 1970-01-01T00:00:00.002 | | 4.5 | ++-------------------------+------+-----+ + +INSERT INTO dense_keys (ts, host, val) VALUES (3, 'new', 5.5); + +Affected Rows: 1 + +INSERT INTO logical_keys (ts, host, val) VALUES (3, 'new', 6.5); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('dense_keys'); + ++---------------------------------+ +| ADMIN FLUSH_TABLE('dense_keys') | ++---------------------------------+ +| 0 | ++---------------------------------+ + +ADMIN FLUSH_TABLE('metric_keys'); + ++----------------------------------+ +| ADMIN FLUSH_TABLE('metric_keys') | ++----------------------------------+ +| 0 | ++----------------------------------+ + +SELECT COUNT(*) FROM dense_keys; + ++----------+ +| count(*) | ++----------+ +| 3 | ++----------+ + +SELECT COUNT(*) FROM logical_keys; + ++----------+ +| count(*) | ++----------+ +| 3 | ++----------+ + +-- New OTLP writes retain the historical infinity label across upgrade. +INSERT INTO otlp_upgrade_bucket VALUES (30000, 'inf', 3), (40000, 'inf', 4); + +Affected Rows: 2 + +SELECT greptime_timestamp, le, greptime_value FROM otlp_upgrade_bucket ORDER BY greptime_timestamp; + ++---------------------+-----+----------------+ +| greptime_timestamp | le | greptime_value | ++---------------------+-----+----------------+ +| 1970-01-01T00:00:10 | inf | 1.0 | +| 1970-01-01T00:00:20 | inf | 2.0 | +| 1970-01-01T00:00:30 | inf | 3.0 | +| 1970-01-01T00:00:40 | inf | 4.0 | ++---------------------+-----+----------------+ + +-- SQLNESS SORT_RESULT 3 1 +TQL EVAL (10, 40, '10s') otlp_upgrade_bucket{le="inf"}; + ++---------------------+-----+----------------+ +| greptime_timestamp | le | greptime_value | ++---------------------+-----+----------------+ +| 1970-01-01T00:00:10 | inf | 1.0 | +| 1970-01-01T00:00:20 | inf | 2.0 | +| 1970-01-01T00:00:30 | inf | 3.0 | +| 1970-01-01T00:00:40 | inf | 4.0 | ++---------------------+-----+----------------+ diff --git a/tests/compatibility/cases/exemplar_legacy_keys/verify.sql b/tests/compatibility/cases/exemplar_legacy_keys/verify.sql new file mode 100644 index 00000000000..115119d9686 --- /dev/null +++ b/tests/compatibility/cases/exemplar_legacy_keys/verify.sql @@ -0,0 +1,13 @@ +SELECT ts, host, val FROM dense_keys ORDER BY ts; +SELECT ts, host, val FROM logical_keys ORDER BY ts; +INSERT INTO dense_keys (ts, host, val) VALUES (3, 'new', 5.5); +INSERT INTO logical_keys (ts, host, val) VALUES (3, 'new', 6.5); +ADMIN FLUSH_TABLE('dense_keys'); +ADMIN FLUSH_TABLE('metric_keys'); +SELECT COUNT(*) FROM dense_keys; +SELECT COUNT(*) FROM logical_keys; +-- New OTLP writes retain the historical infinity label across upgrade. +INSERT INTO otlp_upgrade_bucket VALUES (30000, 'inf', 3), (40000, 'inf', 4); +SELECT greptime_timestamp, le, greptime_value FROM otlp_upgrade_bucket ORDER BY greptime_timestamp; +-- SQLNESS SORT_RESULT 3 1 +TQL EVAL (10, 40, '10s') otlp_upgrade_bucket{le="inf"};