1use std::any::Any;
18use std::collections::{BTreeSet, HashMap};
19use std::fmt::{Debug, Display};
20use std::pin::Pin;
21use std::sync::{Arc, Mutex};
22use std::time::Instant;
23
24use api::greptime_proto::v1::meta::{GrantedRegion as PbGrantedRegion, RegionRole as PbRegionRole};
25use api::region::RegionResponse;
26use async_trait::async_trait;
27use common_error::ext::BoxedError;
28use common_recordbatch::adapter::RegionQueryStatCounters;
29use common_recordbatch::{EmptyRecordBatchStream, QueryMemoryTracker, SendableRecordBatchStream};
30use common_time::Timestamp;
31use datafusion_execution::memory_pool::{MemoryPool, UnboundedMemoryPool};
32use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
33use datafusion_physical_plan::{DisplayAs, DisplayFormatType, PhysicalExpr};
34use datatypes::schema::SchemaRef;
35use datatypes::series::SeriesOrdering;
36use datatypes::series::frame::LabelDecodeSpec;
37use datatypes::series::raw::RawSeriesChunk;
38use datatypes::series::samples::SeriesSchema;
39use futures::FutureExt;
40use futures::Stream;
41use futures::future::{BoxFuture, join_all};
42use serde::{Deserialize, Serialize};
43use tokio::sync::Semaphore;
44
45use crate::logstore::entry;
46use crate::metadata::RegionMetadataRef;
47use crate::region_request::{
48 BatchRegionDdlRequest, RegionCatchupRequest, RegionOpenRequest, RegionPutRequest, RegionRequest,
49};
50use crate::storage::{ColumnId, FileId, RegionId, ScanRequest, SequenceNumber};
51
52#[derive(Debug, PartialEq, Eq, Clone, Copy)]
54pub enum SettableRegionRoleState {
55 Follower,
56 DowngradingLeader,
57 Leader,
59 StagingLeader,
61}
62
63impl Display for SettableRegionRoleState {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 match self {
66 SettableRegionRoleState::Follower => write!(f, "Follower"),
67 SettableRegionRoleState::DowngradingLeader => write!(f, "Leader(Downgrading)"),
68 SettableRegionRoleState::Leader => write!(f, "Leader"),
69 SettableRegionRoleState::StagingLeader => write!(f, "Leader(Staging)"),
70 }
71 }
72}
73
74impl From<SettableRegionRoleState> for RegionRole {
75 fn from(value: SettableRegionRoleState) -> Self {
76 match value {
77 SettableRegionRoleState::Follower => RegionRole::Follower,
78 SettableRegionRoleState::DowngradingLeader => RegionRole::DowngradingLeader,
79 SettableRegionRoleState::Leader => RegionRole::Leader,
80 SettableRegionRoleState::StagingLeader => RegionRole::StagingLeader,
81 }
82 }
83}
84
85#[derive(Debug, PartialEq, Eq)]
87pub struct SetRegionRoleStateRequest {
88 region_id: RegionId,
89 region_role_state: SettableRegionRoleState,
90}
91
92#[derive(Debug, PartialEq, Eq)]
94pub enum SetRegionRoleStateSuccess {
95 File,
96 Relational,
97 Mito {
98 last_entry_id: entry::Id,
99 },
100 Metric {
101 last_entry_id: entry::Id,
102 metadata_last_entry_id: entry::Id,
103 },
104}
105
106impl SetRegionRoleStateSuccess {
107 pub fn file() -> Self {
109 Self::File
110 }
111
112 pub fn relational() -> Self {
114 Self::Relational
115 }
116
117 pub fn mito(last_entry_id: entry::Id) -> Self {
119 SetRegionRoleStateSuccess::Mito { last_entry_id }
120 }
121
122 pub fn metric(last_entry_id: entry::Id, metadata_last_entry_id: entry::Id) -> Self {
124 SetRegionRoleStateSuccess::Metric {
125 last_entry_id,
126 metadata_last_entry_id,
127 }
128 }
129}
130
131impl SetRegionRoleStateSuccess {
132 pub fn last_entry_id(&self) -> Option<entry::Id> {
134 match self {
135 SetRegionRoleStateSuccess::File | SetRegionRoleStateSuccess::Relational => None,
136 SetRegionRoleStateSuccess::Mito { last_entry_id } => Some(*last_entry_id),
137 SetRegionRoleStateSuccess::Metric { last_entry_id, .. } => Some(*last_entry_id),
138 }
139 }
140
141 pub fn metadata_last_entry_id(&self) -> Option<entry::Id> {
143 match self {
144 SetRegionRoleStateSuccess::File | SetRegionRoleStateSuccess::Relational => None,
145 SetRegionRoleStateSuccess::Mito { .. } => None,
146 SetRegionRoleStateSuccess::Metric {
147 metadata_last_entry_id,
148 ..
149 } => Some(*metadata_last_entry_id),
150 }
151 }
152}
153
154#[derive(Debug)]
156pub enum SetRegionRoleStateResponse {
157 Success(SetRegionRoleStateSuccess),
158 NotFound,
159 InvalidTransition(BoxedError),
160}
161
162impl SetRegionRoleStateResponse {
163 pub fn success(success: SetRegionRoleStateSuccess) -> Self {
165 Self::Success(success)
166 }
167
168 pub fn invalid_transition(error: BoxedError) -> Self {
170 Self::InvalidTransition(error)
171 }
172
173 pub fn is_not_found(&self) -> bool {
175 matches!(self, SetRegionRoleStateResponse::NotFound)
176 }
177
178 pub fn is_invalid_transition(&self) -> bool {
180 matches!(self, SetRegionRoleStateResponse::InvalidTransition(_))
181 }
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct GrantedRegion {
186 pub region_id: RegionId,
187 pub region_role: RegionRole,
188 pub candidate_lease_id: Option<u64>,
195 pub extensions: HashMap<String, Vec<u8>>,
196}
197
198impl GrantedRegion {
199 pub fn new(region_id: RegionId, region_role: RegionRole) -> Self {
200 Self {
201 region_id,
202 region_role,
203 candidate_lease_id: None,
204 extensions: HashMap::new(),
205 }
206 }
207}
208
209impl From<GrantedRegion> for PbGrantedRegion {
210 fn from(value: GrantedRegion) -> Self {
211 PbGrantedRegion {
212 region_id: value.region_id.as_u64(),
213 role: PbRegionRole::from(value.region_role).into(),
214 candidate_lease_id: value.candidate_lease_id.unwrap_or_default(),
215 extensions: value.extensions,
216 }
217 }
218}
219
220impl From<PbGrantedRegion> for GrantedRegion {
221 fn from(value: PbGrantedRegion) -> Self {
222 GrantedRegion {
223 region_id: RegionId::from_u64(value.region_id),
224 region_role: value.role().into(),
225 candidate_lease_id: (value.candidate_lease_id != 0).then_some(value.candidate_lease_id),
227 extensions: value.extensions,
228 }
229 }
230}
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
235pub enum RegionRole {
236 Follower,
238 Leader,
240 StagingLeader,
245 DowngradingLeader,
249}
250
251impl Display for RegionRole {
252 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253 match self {
254 RegionRole::Follower => write!(f, "Follower"),
255 RegionRole::Leader => write!(f, "Leader"),
256 RegionRole::StagingLeader => write!(f, "Leader(Staging)"),
257 RegionRole::DowngradingLeader => write!(f, "Leader(Downgrading)"),
258 }
259 }
260}
261
262impl RegionRole {
263 pub fn writable(&self) -> bool {
264 matches!(self, RegionRole::Leader | RegionRole::StagingLeader)
265 }
266}
267
268impl From<RegionRole> for PbRegionRole {
269 fn from(value: RegionRole) -> Self {
270 match value {
271 RegionRole::Follower => PbRegionRole::Follower,
272 RegionRole::Leader => PbRegionRole::Leader,
273 RegionRole::StagingLeader => PbRegionRole::StagingLeader,
274 RegionRole::DowngradingLeader => PbRegionRole::DowngradingLeader,
275 }
276 }
277}
278
279impl From<PbRegionRole> for RegionRole {
280 fn from(value: PbRegionRole) -> Self {
281 match value {
282 PbRegionRole::Leader => RegionRole::Leader,
283 PbRegionRole::StagingLeader => RegionRole::StagingLeader,
284 PbRegionRole::Follower => RegionRole::Follower,
285 PbRegionRole::DowngradingLeader => RegionRole::DowngradingLeader,
286 }
287 }
288}
289
290#[derive(Debug)]
292pub enum ScannerPartitioning {
293 Unknown(usize),
295}
296
297impl ScannerPartitioning {
298 pub fn num_partitions(&self) -> usize {
300 match self {
301 ScannerPartitioning::Unknown(num_partitions) => *num_partitions,
302 }
303 }
304}
305
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct PartitionRange {
309 pub start: Timestamp,
311 pub end: Timestamp,
313 pub num_rows: usize,
315 pub identifier: usize,
317}
318
319#[derive(Debug, Default)]
321pub struct ScannerProperties {
322 pub partitions: Vec<Vec<PartitionRange>>,
327
328 append_mode: bool,
330
331 total_rows: usize,
334
335 total_rows_is_exact: bool,
337
338 exact_num_rows: Option<usize>,
341
342 pub distinguish_partition_range: bool,
344
345 target_partitions: usize,
347
348 logical_region: bool,
351
352 query_load_region_id: Option<RegionId>,
354 query_stat_counters: Option<RegionQueryStatCounters>,
356}
357
358impl ScannerProperties {
359 pub fn with_append_mode(mut self, append_mode: bool) -> Self {
361 self.append_mode = append_mode;
362 self
363 }
364
365 pub fn with_total_rows(mut self, total_rows: usize) -> Self {
367 self.total_rows = total_rows;
368 self
369 }
370
371 pub fn with_total_rows_is_exact(mut self, exact: bool) -> Self {
373 self.total_rows_is_exact = exact;
374 self
375 }
376
377 pub fn with_exact_num_rows(mut self, rows: Option<usize>) -> Self {
379 self.exact_num_rows = rows;
380 self
381 }
382
383 pub fn exact_num_rows(&self) -> Option<usize> {
385 self.exact_num_rows
386 }
387
388 pub fn clear_exact_num_rows(&mut self) {
390 self.exact_num_rows = None;
391 }
392
393 pub fn new(partitions: Vec<Vec<PartitionRange>>, append_mode: bool, total_rows: usize) -> Self {
395 Self {
396 partitions,
397 append_mode,
398 total_rows,
399 total_rows_is_exact: false,
400 exact_num_rows: None,
401 distinguish_partition_range: false,
402 target_partitions: 0,
403 logical_region: false,
404 query_load_region_id: None,
405 query_stat_counters: None,
406 }
407 }
408
409 pub fn prepare(&mut self, request: PrepareRequest) {
411 if let Some(ranges) = request.ranges {
412 if (self.exact_num_rows.is_some() || self.total_rows_is_exact)
413 && !same_partition_ranges(&self.partitions, &ranges)
414 {
415 self.exact_num_rows = None;
416 self.total_rows_is_exact = false;
417 }
418 self.partitions = ranges;
419 }
420 if let Some(distinguish_partition_range) = request.distinguish_partition_range {
421 self.distinguish_partition_range = distinguish_partition_range;
422 }
423 if let Some(target_partitions) = request.target_partitions {
424 self.target_partitions = target_partitions;
425 }
426 }
427
428 pub fn num_partitions(&self) -> usize {
430 self.partitions.len()
431 }
432
433 pub fn append_mode(&self) -> bool {
434 self.append_mode
435 }
436
437 pub fn total_rows(&self) -> usize {
438 self.total_rows
439 }
440
441 pub fn total_rows_is_exact(&self) -> bool {
443 self.total_rows_is_exact
444 }
445
446 pub fn is_logical_region(&self) -> bool {
449 self.logical_region
450 }
451
452 pub fn target_partitions(&self) -> usize {
454 if self.target_partitions == 0 {
455 self.num_partitions()
456 } else {
457 self.target_partitions
458 }
459 }
460
461 pub fn set_logical_region(&mut self, logical_region: bool) {
463 self.logical_region = logical_region;
464 }
465
466 pub fn query_load_region_id(&self) -> Option<RegionId> {
468 self.query_load_region_id
469 }
470
471 pub fn query_stat_counters(&self) -> Option<RegionQueryStatCounters> {
473 self.query_stat_counters.clone()
474 }
475
476 pub fn set_query_load_region_id(&mut self, region_id: RegionId) {
478 self.query_load_region_id = Some(region_id);
479 }
480
481 pub fn set_query_stat_counters(&mut self, counters: RegionQueryStatCounters) {
483 self.query_stat_counters = Some(counters);
484 }
485}
486
487fn same_partition_ranges(left: &[Vec<PartitionRange>], right: &[Vec<PartitionRange>]) -> bool {
489 let mut left: Vec<_> = left.iter().flatten().collect();
490 let mut right: Vec<_> = right.iter().flatten().collect();
491 if left.len() != right.len() {
492 return false;
493 }
494 let key = |range: &&PartitionRange| (range.identifier, range.start, range.end, range.num_rows);
495 left.sort_unstable_by_key(key);
496 right.sort_unstable_by_key(key);
497 left == right
498}
499
500#[derive(Default)]
502pub struct PrepareRequest {
503 pub ranges: Option<Vec<Vec<PartitionRange>>>,
506 pub distinguish_partition_range: Option<bool>,
508 pub target_partitions: Option<usize>,
510}
511
512impl PrepareRequest {
513 pub fn with_ranges(mut self, ranges: Vec<Vec<PartitionRange>>) -> Self {
515 self.ranges = Some(ranges);
516 self
517 }
518
519 pub fn with_distinguish_partition_range(mut self, distinguish_partition_range: bool) -> Self {
521 self.distinguish_partition_range = Some(distinguish_partition_range);
522 self
523 }
524
525 pub fn with_target_partitions(mut self, target_partitions: usize) -> Self {
527 self.target_partitions = Some(target_partitions);
528 self
529 }
530}
531
532#[derive(Clone)]
536pub struct QueryScanContext {
537 pub explain_verbose: bool,
539 pub memory_pool: Arc<dyn MemoryPool>,
541}
542
543impl Default for QueryScanContext {
544 fn default() -> Self {
545 Self {
546 explain_verbose: false,
547 memory_pool: Arc::new(UnboundedMemoryPool::default()),
548 }
549 }
550}
551
552#[derive(Clone, Debug)]
554pub struct BoundTag {
555 pub column_id: ColumnId,
557 pub name: Arc<str>,
559}
560
561#[derive(Clone, Debug)]
563pub enum RawLabelSource {
564 PrimaryKey {
567 metric_name: Arc<str>,
569 physical_metadata: RegionMetadataRef,
571 logical_tags: Arc<[BoundTag]>,
573 },
574 Explicit,
579}
580
581pub const NO_BOUND_LABEL_SOURCE: RawLabelSource = RawLabelSource::Explicit;
589
590pub trait RawSeriesStream: Stream<Item = Result<RawSeriesChunk, BoxedError>> + Send {
604 fn schema(&self) -> &Arc<SeriesSchema>;
606 fn label_source(&self) -> &RawLabelSource;
616 fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> {
627 None
628 }
629 fn ordering(&self) -> SeriesOrdering;
631}
632
633pub type SendableRawSeriesStream = Pin<Box<dyn RawSeriesStream>>;
635
636#[derive(Clone, Debug)]
638pub struct SeriesInfo {
639 pub primary_key: datatypes::arrow::buffer::Buffer,
642 pub metric: Option<datatypes::series::SeriesLabels>,
645}
646
647pub trait PreparedSeriesSource: Send + Sync {
668 fn num_series(&self) -> usize;
670
671 fn label_source(&self) -> &RawLabelSource;
674
675 fn series_info(&self, ordinal: usize) -> Result<SeriesInfo, BoxedError>;
677
678 fn read_series(
680 &self,
681 range: std::ops::Range<usize>,
682 ) -> Result<SendableRawSeriesStream, BoxedError>;
683}
684
685pub trait RegionScanner: Debug + DisplayAs + Send {
690 fn name(&self) -> &str;
691
692 fn properties(&self) -> &ScannerProperties;
694
695 fn schema(&self) -> SchemaRef;
697
698 fn metadata(&self) -> RegionMetadataRef;
700
701 fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError>;
705
706 fn scan_partition(
711 &self,
712 ctx: &QueryScanContext,
713 metrics_set: &ExecutionPlanMetricsSet,
714 partition: usize,
715 ) -> Result<SendableRecordBatchStream, BoxedError>;
716
717 fn raw_series_schema(
726 &self,
727 _label_source: &RawLabelSource,
728 ) -> Result<Option<Arc<SeriesSchema>>, BoxedError> {
729 Ok(None)
730 }
731
732 fn raw_series_has_explicit_labels(&self, _labels: &RawLabelSource) -> Result<bool, BoxedError> {
736 Ok(false)
737 }
738
739 fn raw_series_ordering(&self) -> Result<SeriesOrdering, BoxedError> {
744 Ok(SeriesOrdering::Contiguous)
745 }
746
747 fn scan_series_partition(
767 &self,
768 _ctx: &QueryScanContext,
769 _metrics_set: &ExecutionPlanMetricsSet,
770 _partition: usize,
771 _label_source: &RawLabelSource,
772 ) -> Result<Option<SendableRawSeriesStream>, BoxedError> {
773 todo!()
774 }
775
776 fn prepare_series(
783 &self,
784 _ctx: &QueryScanContext,
785 _metrics_set: &ExecutionPlanMetricsSet,
786 _label_source: &RawLabelSource,
787 ) -> futures::future::BoxFuture<
788 'static,
789 Result<Option<Arc<dyn PreparedSeriesSource>>, BoxedError>,
790 > {
791 Box::pin(async { Ok(None) })
792 }
793
794 fn has_predicate_without_region(&self) -> bool;
796
797 fn add_dyn_filter_to_predicate(
802 &mut self,
803 filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
804 ) -> Vec<bool>;
805
806 fn reset_state(&mut self) {}
813
814 fn set_logical_region(&mut self, logical_region: bool);
817
818 fn set_query_load_region_id(&mut self, region_id: RegionId);
820
821 fn snapshot_sequence(&self) -> Option<SequenceNumber> {
822 None
823 }
824}
825
826pub type RegionScannerRef = Box<dyn RegionScanner>;
827
828pub type BatchResponses = Vec<(RegionId, Result<RegionResponse, BoxedError>)>;
829
830pub type BatchPutResponse = (
833 Vec<RegionId>,
834 BoxFuture<'static, Result<RegionResponse, BoxedError>>,
835);
836
837#[derive(Debug, Deserialize, Serialize, Default)]
839pub struct RegionStatistic {
840 #[serde(default)]
845 pub num_rows: u64,
846 pub memtable_size: u64,
848 pub wal_size: u64,
850 pub manifest_size: u64,
855 pub sst_size: u64,
859 pub sst_num: u64,
863 #[serde(default)]
867 pub index_size: u64,
868 #[serde(default)]
870 pub manifest: RegionManifestInfo,
871 #[serde(default)]
872 pub written_bytes: u64,
874 #[serde(default, alias = "flushed_parquet_bytes")]
881 pub ingested_parquet_bytes: u64,
882 #[serde(default)]
886 pub query_cpu_time: u64,
887 #[serde(default)]
889 pub query_scanned_bytes: u64,
890 #[serde(default)]
894 pub min_timestamp: Option<Timestamp>,
895 #[serde(default)]
897 pub max_timestamp: Option<Timestamp>,
898 #[serde(default)]
902 pub data_topic_latest_entry_id: u64,
903 #[serde(default)]
904 pub metadata_topic_latest_entry_id: u64,
905 #[serde(default, skip_serializing_if = "crate::is_false")]
908 pub has_pending_tails: bool,
909}
910
911#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
913pub enum RegionManifestInfo {
914 Mito {
915 manifest_version: u64,
916 flushed_entry_id: u64,
917 file_removed_cnt: u64,
919 },
920 Metric {
921 data_manifest_version: u64,
922 data_flushed_entry_id: u64,
923 metadata_manifest_version: u64,
924 metadata_flushed_entry_id: u64,
925 },
926}
927
928impl RegionManifestInfo {
929 pub fn mito(manifest_version: u64, flushed_entry_id: u64, file_removal_rate: u64) -> Self {
931 Self::Mito {
932 manifest_version,
933 flushed_entry_id,
934 file_removed_cnt: file_removal_rate,
935 }
936 }
937
938 pub fn metric(
940 data_manifest_version: u64,
941 data_flushed_entry_id: u64,
942 metadata_manifest_version: u64,
943 metadata_flushed_entry_id: u64,
944 ) -> Self {
945 Self::Metric {
946 data_manifest_version,
947 data_flushed_entry_id,
948 metadata_manifest_version,
949 metadata_flushed_entry_id,
950 }
951 }
952
953 pub fn is_mito(&self) -> bool {
955 matches!(self, RegionManifestInfo::Mito { .. })
956 }
957
958 pub fn is_metric(&self) -> bool {
960 matches!(self, RegionManifestInfo::Metric { .. })
961 }
962
963 pub fn data_flushed_entry_id(&self) -> u64 {
965 match self {
966 RegionManifestInfo::Mito {
967 flushed_entry_id, ..
968 } => *flushed_entry_id,
969 RegionManifestInfo::Metric {
970 data_flushed_entry_id,
971 ..
972 } => *data_flushed_entry_id,
973 }
974 }
975
976 pub fn data_manifest_version(&self) -> u64 {
978 match self {
979 RegionManifestInfo::Mito {
980 manifest_version, ..
981 } => *manifest_version,
982 RegionManifestInfo::Metric {
983 data_manifest_version,
984 ..
985 } => *data_manifest_version,
986 }
987 }
988
989 pub fn metadata_manifest_version(&self) -> Option<u64> {
991 match self {
992 RegionManifestInfo::Mito { .. } => None,
993 RegionManifestInfo::Metric {
994 metadata_manifest_version,
995 ..
996 } => Some(*metadata_manifest_version),
997 }
998 }
999
1000 pub fn metadata_flushed_entry_id(&self) -> Option<u64> {
1002 match self {
1003 RegionManifestInfo::Mito { .. } => None,
1004 RegionManifestInfo::Metric {
1005 metadata_flushed_entry_id,
1006 ..
1007 } => Some(*metadata_flushed_entry_id),
1008 }
1009 }
1010
1011 pub fn encode_list(manifest_infos: &[(RegionId, Self)]) -> serde_json::Result<Vec<u8>> {
1013 serde_json::to_vec(manifest_infos)
1014 }
1015
1016 pub fn decode_list(value: &[u8]) -> serde_json::Result<Vec<(RegionId, Self)>> {
1018 serde_json::from_slice(value)
1019 }
1020}
1021
1022impl Default for RegionManifestInfo {
1023 fn default() -> Self {
1024 Self::Mito {
1025 manifest_version: 0,
1026 flushed_entry_id: 0,
1027 file_removed_cnt: 0,
1028 }
1029 }
1030}
1031
1032impl RegionStatistic {
1033 pub fn deserialize_from_slice(value: &[u8]) -> Option<RegionStatistic> {
1037 serde_json::from_slice(value).ok()
1038 }
1039
1040 pub fn serialize_to_vec(&self) -> Option<Vec<u8>> {
1044 serde_json::to_vec(self).ok()
1045 }
1046}
1047
1048impl RegionStatistic {
1049 pub fn estimated_disk_size(&self) -> u64 {
1051 self.wal_size + self.sst_size + self.manifest_size + self.index_size
1052 }
1053}
1054
1055#[cfg(test)]
1056#[path = "region_engine/prepared_series_tests.rs"]
1057mod prepared_series_tests;
1058
1059#[cfg(test)]
1060mod tests {
1061 use common_recordbatch::{RecordBatch, RecordBatches};
1062 use datatypes::prelude::ConcreteDataType;
1063 use datatypes::schema::ColumnSchema;
1064 use datatypes::vectors::{Int32Vector, TimestampMillisecondVector, VectorRef};
1065 use futures::TryStreamExt;
1066 use serde_json::json;
1067
1068 use super::*;
1069
1070 #[test]
1071 fn test_metadata_aggr_partition_range_assignment() {
1072 let range = PartitionRange {
1073 start: Timestamp::new_millisecond(0),
1074 end: Timestamp::new_millisecond(1),
1075 num_rows: 5,
1076 identifier: 0,
1077 };
1078 let later = PartitionRange {
1079 start: range.end,
1080 end: Timestamp::new_millisecond(2),
1081 identifier: 1,
1082 ..range
1083 };
1084 let original = vec![vec![range, later]];
1085 for (replacement, exact) in [
1086 (vec![vec![later], vec![range]], true),
1087 (vec![vec![later]], false),
1088 (vec![vec![range, range]], false),
1089 (
1090 vec![vec![
1091 PartitionRange {
1092 num_rows: 4,
1093 ..range
1094 },
1095 later,
1096 ]],
1097 false,
1098 ),
1099 ] {
1100 let mut properties = ScannerProperties::new(original.clone(), true, 10)
1101 .with_exact_num_rows(Some(10))
1102 .with_total_rows_is_exact(true);
1103 properties.prepare(PrepareRequest::default().with_ranges(replacement));
1104 assert_eq!(properties.exact_num_rows(), exact.then_some(10));
1105 assert_eq!(properties.total_rows_is_exact(), exact);
1106 }
1107 }
1108
1109 #[tokio::test]
1110 async fn single_partition_scanner_raw_scan_panics_and_preserves_legacy_read() {
1111 use std::panic::{AssertUnwindSafe, catch_unwind};
1112
1113 use api::v1::SemanticType;
1114 use datatypes::arrow::array::Int32Array;
1115 use datatypes::schema::Schema as ArrowSchema;
1116
1117 use crate::metadata::{ColumnMetadata, RegionMetadataBuilder};
1118
1119 let schema = Arc::new(ArrowSchema::new(vec![
1120 ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false),
1121 ColumnSchema::new(
1122 "ts",
1123 ConcreteDataType::timestamp_millisecond_datatype(),
1124 false,
1125 ),
1126 ]));
1127 let columns: Vec<VectorRef> = vec![
1128 Arc::new(Int32Vector::from_slice([42])),
1129 Arc::new(TimestampMillisecondVector::from_slice([7])),
1130 ];
1131 let batch = RecordBatch::new(schema.clone(), columns).unwrap();
1132 let batches = RecordBatches::try_new(schema, vec![batch]).unwrap();
1133 let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1234, 1));
1134 metadata_builder.push_column_metadata(ColumnMetadata {
1135 column_schema: ColumnSchema::new("value", ConcreteDataType::int32_datatype(), false),
1136 semantic_type: SemanticType::Field,
1137 column_id: 1,
1138 });
1139 metadata_builder.push_column_metadata(ColumnMetadata {
1140 column_schema: ColumnSchema::new(
1141 "ts",
1142 ConcreteDataType::timestamp_millisecond_datatype(),
1143 false,
1144 ),
1145 semantic_type: SemanticType::Timestamp,
1146 column_id: 2,
1147 });
1148 let metadata = Arc::new(metadata_builder.build().unwrap());
1149 let scanner = SinglePartitionScanner::new(batches.as_stream(), false, metadata, None);
1150 let ctx = QueryScanContext::default();
1151 let metrics = ExecutionPlanMetricsSet::new();
1152
1153 assert!(
1156 scanner
1157 .raw_series_schema(&RawLabelSource::Explicit)
1158 .unwrap()
1159 .is_none()
1160 );
1161 assert!(
1162 scanner
1163 .prepare_series(&ctx, &metrics, &RawLabelSource::Explicit)
1164 .await
1165 .unwrap()
1166 .is_none()
1167 );
1168 assert_eq!(
1169 scanner.raw_series_ordering().unwrap(),
1170 SeriesOrdering::Contiguous
1171 );
1172
1173 let raw_scan = catch_unwind(AssertUnwindSafe(|| {
1175 scanner.scan_series_partition(&ctx, &metrics, 0, &RawLabelSource::Explicit)
1176 }));
1177 assert!(raw_scan.is_err());
1178 let legacy = scanner.scan_partition(&ctx, &metrics, 0).unwrap();
1179 let legacy_batches = legacy.try_collect::<Vec<_>>().await.unwrap();
1180 assert_eq!(legacy_batches.len(), 1);
1181 assert_eq!(legacy_batches[0].num_rows(), 1);
1182 assert_eq!(
1183 legacy_batches[0]
1184 .column(0)
1185 .as_ref()
1186 .as_any()
1187 .downcast_ref::<Int32Array>()
1188 .unwrap()
1189 .value(0),
1190 42
1191 );
1192 }
1193
1194 #[test]
1195 fn test_legacy_granted_region_wire() {
1196 use prost::Message;
1197
1198 let legacy_bytes: &[u8] = include_bytes!(
1199 "../../../tests/compatibility/wire/candidate_lease_id/legacy_granted_region.pb"
1200 );
1201 let granted = GrantedRegion::from(PbGrantedRegion::decode(legacy_bytes).unwrap());
1202 assert_eq!(
1203 granted,
1204 GrantedRegion {
1205 candidate_lease_id: None,
1206 extensions: HashMap::from([("plugin".to_string(), b"payload".to_vec())]),
1207 ..GrantedRegion::new(RegionId::new(1024, 1), RegionRole::Follower)
1208 }
1209 );
1210
1211 assert_eq!(PbGrantedRegion::from(granted).encode_to_vec(), legacy_bytes);
1212 }
1213
1214 #[test]
1215 fn test_granted_region_candidate_lease_id_wire() {
1216 use prost::Message;
1217
1218 let granted = GrantedRegion {
1219 candidate_lease_id: Some(7),
1220 ..GrantedRegion::new(RegionId::new(1024, 1), RegionRole::Follower)
1221 };
1222 let bytes: &[u8] = &[
1225 0x08, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01, 0x10, 0x01, 0x18, 0x07,
1226 ];
1227 assert_eq!(
1228 PbGrantedRegion::from(granted.clone()).encode_to_vec(),
1229 bytes
1230 );
1231 assert_eq!(
1232 GrantedRegion::from(PbGrantedRegion::decode(bytes).unwrap()),
1233 granted
1234 );
1235 }
1236
1237 #[test]
1238 fn region_statistic_flush_bytes_compatibility() {
1239 let legacy_bytes = br#"{
1240 "num_rows": 1,
1241 "memtable_size": 2,
1242 "wal_size": 3,
1243 "manifest_size": 4,
1244 "sst_size": 5,
1245 "sst_num": 6,
1246 "index_size": 7,
1247 "manifest": {
1248 "Mito": {
1249 "manifest_version": 8,
1250 "flushed_entry_id": 9,
1251 "file_removed_cnt": 10
1252 }
1253 },
1254 "written_bytes": 11
1255 }"#;
1256 let mut statistic = RegionStatistic::deserialize_from_slice(legacy_bytes).unwrap();
1257 assert_eq!(statistic.ingested_parquet_bytes, 0);
1258 statistic.ingested_parquet_bytes = 1234;
1259 let encoded = statistic.serialize_to_vec().unwrap();
1260 let decoded = RegionStatistic::deserialize_from_slice(&encoded).unwrap();
1261 assert_eq!(decoded.ingested_parquet_bytes, 1234);
1262 let legacy: serde_json::Value = serde_json::from_slice(legacy_bytes).unwrap();
1263 let mut current: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
1264 assert_eq!(current["ingested_parquet_bytes"], 1234);
1265 assert!(current.get("flushed_parquet_bytes").is_none());
1266 let mut old_wire = current.clone();
1267 let bytes = old_wire
1268 .as_object_mut()
1269 .unwrap()
1270 .remove("ingested_parquet_bytes")
1271 .unwrap();
1272 old_wire["flushed_parquet_bytes"] = bytes;
1273 assert_eq!(
1274 serde_json::from_value::<RegionStatistic>(old_wire)
1275 .unwrap()
1276 .ingested_parquet_bytes,
1277 1234
1278 );
1279 for (key, value) in legacy.as_object().unwrap() {
1280 assert_eq!(¤t[key], value);
1281 }
1282 current
1283 .as_object_mut()
1284 .unwrap()
1285 .remove("ingested_parquet_bytes");
1286 assert_eq!(
1287 serde_json::from_value::<RegionStatistic>(current)
1288 .unwrap()
1289 .ingested_parquet_bytes,
1290 0
1291 );
1292 }
1293
1294 #[test]
1295 fn region_statistic_deserializes_without_query_stats() {
1296 let statistic: RegionStatistic = serde_json::from_value(json!({
1297 "num_rows": 1,
1298 "memtable_size": 2,
1299 "wal_size": 3,
1300 "manifest_size": 4,
1301 "sst_size": 5,
1302 "sst_num": 6,
1303 "index_size": 7,
1304 "manifest": {
1305 "Mito": {
1306 "manifest_version": 8,
1307 "flushed_entry_id": 9,
1308 "file_removed_cnt": 10
1309 }
1310 },
1311 "written_bytes": 11
1312 }))
1313 .unwrap();
1314
1315 assert_eq!(statistic.query_cpu_time, 0);
1316 assert_eq!(statistic.query_scanned_bytes, 0);
1317 }
1318}
1319
1320#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1322pub enum SyncRegionFromRequest {
1323 FromManifest(RegionManifestInfo),
1326 FromRegion {
1332 source_region_id: RegionId,
1334 parallelism: usize,
1336 },
1337}
1338
1339impl From<RegionManifestInfo> for SyncRegionFromRequest {
1340 fn from(manifest_info: RegionManifestInfo) -> Self {
1341 SyncRegionFromRequest::FromManifest(manifest_info)
1342 }
1343}
1344
1345impl SyncRegionFromRequest {
1346 pub fn from_manifest(manifest_info: RegionManifestInfo) -> Self {
1348 SyncRegionFromRequest::FromManifest(manifest_info)
1349 }
1350
1351 pub fn from_region(source_region_id: RegionId, parallelism: usize) -> Self {
1353 SyncRegionFromRequest::FromRegion {
1354 source_region_id,
1355 parallelism,
1356 }
1357 }
1358
1359 pub fn is_from_manifest(&self) -> bool {
1361 matches!(self, SyncRegionFromRequest::FromManifest { .. })
1362 }
1363
1364 pub fn into_region_manifest_info(self) -> Option<RegionManifestInfo> {
1368 match self {
1369 SyncRegionFromRequest::FromManifest(manifest_info) => Some(manifest_info),
1370 SyncRegionFromRequest::FromRegion { .. } => None,
1371 }
1372 }
1373}
1374
1375#[derive(Debug)]
1377pub enum SyncRegionFromResponse {
1378 NotSupported,
1379 Mito {
1380 synced: bool,
1382 },
1383 Metric {
1384 metadata_synced: bool,
1386 data_synced: bool,
1388 new_opened_logical_region_ids: Vec<RegionId>,
1391 },
1392}
1393
1394impl SyncRegionFromResponse {
1395 pub fn is_data_synced(&self) -> bool {
1397 match self {
1398 SyncRegionFromResponse::NotSupported => false,
1399 SyncRegionFromResponse::Mito { synced } => *synced,
1400 SyncRegionFromResponse::Metric { data_synced, .. } => *data_synced,
1401 }
1402 }
1403
1404 pub fn is_mito(&self) -> bool {
1406 matches!(self, SyncRegionFromResponse::Mito { .. })
1407 }
1408
1409 pub fn is_metric(&self) -> bool {
1411 matches!(self, SyncRegionFromResponse::Metric { .. })
1412 }
1413
1414 pub fn new_opened_logical_region_ids(self) -> Option<Vec<RegionId>> {
1416 match self {
1417 SyncRegionFromResponse::Metric {
1418 new_opened_logical_region_ids,
1419 ..
1420 } => Some(new_opened_logical_region_ids),
1421 _ => None,
1422 }
1423 }
1424}
1425
1426pub fn sources_sharing_a_target(mapping: &HashMap<RegionId, Vec<RegionId>>) -> Vec<RegionId> {
1444 let mut sources_per_target: HashMap<RegionId, BTreeSet<RegionId>> = HashMap::new();
1445 for (source, targets) in mapping {
1446 for target in targets {
1447 sources_per_target
1448 .entry(*target)
1449 .or_default()
1450 .insert(*source);
1451 }
1452 }
1453 let mut shared: BTreeSet<RegionId> = BTreeSet::new();
1454 for sources in sources_per_target
1455 .values()
1456 .filter(|sources| sources.len() > 1)
1457 {
1458 shared.extend(sources.iter().copied());
1459 }
1460 shared.into_iter().collect()
1461}
1462
1463pub fn every_target_has_a_single_source(mapping: &HashMap<RegionId, Vec<RegionId>>) -> bool {
1468 sources_sharing_a_target(mapping).is_empty()
1469}
1470
1471#[derive(Debug, Clone, Default)]
1473pub struct RemapManifestsRequest {
1474 pub region_id: RegionId,
1479 pub input_regions: Vec<RegionId>,
1481 pub region_mapping: HashMap<RegionId, Vec<RegionId>>,
1483 pub new_partition_exprs: HashMap<RegionId, String>,
1485 pub validate_only: bool,
1492}
1493
1494#[derive(Debug, Clone)]
1496pub struct RemapManifestsResponse {
1497 pub manifest_paths: HashMap<RegionId, String>,
1502}
1503
1504#[derive(Debug, Clone)]
1506pub struct MitoCopyRegionFromRequest {
1507 pub source_region_id: RegionId,
1509 pub parallelism: usize,
1511}
1512
1513#[derive(Debug, Clone)]
1514pub struct MitoCopyRegionFromResponse {
1515 pub copied_file_ids: Vec<FileId>,
1520}
1521
1522#[async_trait]
1523pub trait RegionEngine: Send + Sync {
1524 fn name(&self) -> &str;
1526
1527 async fn handle_batch_open_requests(
1529 &self,
1530 parallelism: usize,
1531 requests: Vec<(RegionId, RegionOpenRequest)>,
1532 ) -> Result<BatchResponses, BoxedError> {
1533 let semaphore = Arc::new(Semaphore::new(parallelism));
1534 let mut tasks = Vec::with_capacity(requests.len());
1535
1536 for (region_id, request) in requests {
1537 let semaphore_moved = semaphore.clone();
1538
1539 tasks.push(async move {
1540 let _permit = semaphore_moved.acquire().await.unwrap();
1542 let result = self
1543 .handle_request(region_id, RegionRequest::Open(request))
1544 .await;
1545 (region_id, result)
1546 });
1547 }
1548
1549 Ok(join_all(tasks).await)
1550 }
1551
1552 async fn handle_batch_catchup_requests(
1553 &self,
1554 parallelism: usize,
1555 requests: Vec<(RegionId, RegionCatchupRequest)>,
1556 ) -> Result<BatchResponses, BoxedError> {
1557 let semaphore = Arc::new(Semaphore::new(parallelism));
1558 let mut tasks = Vec::with_capacity(requests.len());
1559
1560 for (region_id, request) in requests {
1561 let semaphore_moved = semaphore.clone();
1562
1563 tasks.push(async move {
1564 let _permit = semaphore_moved.acquire().await.unwrap();
1566 let result = self
1567 .handle_request(region_id, RegionRequest::Catchup(request))
1568 .await;
1569 (region_id, result)
1570 });
1571 }
1572
1573 Ok(join_all(tasks).await)
1574 }
1575
1576 fn handle_batch_put_requests(
1584 self: Arc<Self>,
1585 requests: Vec<(RegionId, RegionPutRequest)>,
1586 ) -> Vec<BatchPutResponse>
1587 where
1588 Self: 'static,
1589 {
1590 requests
1591 .into_iter()
1592 .map(|(region_id, request)| {
1593 let engine = self.clone();
1594 let response = async move {
1595 engine
1596 .handle_request(region_id, RegionRequest::Put(request))
1597 .await
1598 }
1599 .boxed();
1600 (vec![region_id], response)
1601 })
1602 .collect()
1603 }
1604
1605 async fn handle_batch_ddl_requests(
1606 &self,
1607 request: BatchRegionDdlRequest,
1608 ) -> Result<RegionResponse, BoxedError> {
1609 let requests = request.into_region_requests();
1610
1611 let mut affected_rows = 0;
1612 let mut extensions = HashMap::new();
1613
1614 for (region_id, request) in requests {
1615 let result = self.handle_request(region_id, request).await?;
1616 affected_rows += result.affected_rows;
1617 extensions.extend(result.extensions);
1618 }
1619
1620 Ok(RegionResponse {
1621 affected_rows,
1622 extensions,
1623 metadata: Vec::new(),
1624 })
1625 }
1626
1627 async fn handle_request(
1629 &self,
1630 region_id: RegionId,
1631 request: RegionRequest,
1632 ) -> Result<RegionResponse, BoxedError>;
1633
1634 async fn get_committed_sequence(
1636 &self,
1637 region_id: RegionId,
1638 ) -> Result<SequenceNumber, BoxedError>;
1639
1640 async fn handle_query(
1642 &self,
1643 region_id: RegionId,
1644 request: ScanRequest,
1645 ) -> Result<RegionScannerRef, BoxedError>;
1646
1647 fn query_memory_tracker(&self) -> Option<QueryMemoryTracker> {
1649 None
1650 }
1651
1652 async fn get_metadata(&self, region_id: RegionId) -> Result<RegionMetadataRef, BoxedError>;
1654
1655 fn region_statistic(&self, region_id: RegionId) -> Option<RegionStatistic>;
1657
1658 async fn stop(&self) -> Result<(), BoxedError>;
1660
1661 fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<(), BoxedError>;
1667
1668 fn set_region_role_with_lease(
1681 &self,
1682 region_id: RegionId,
1683 role: RegionRole,
1684 sent_at: Instant,
1685 deadline: Instant,
1686 candidate_lease_id: Option<u64>,
1687 ) -> Result<bool, BoxedError>;
1688
1689 async fn sync_region(
1691 &self,
1692 region_id: RegionId,
1693 request: SyncRegionFromRequest,
1694 ) -> Result<SyncRegionFromResponse, BoxedError>;
1695
1696 async fn remap_manifests(
1698 &self,
1699 request: RemapManifestsRequest,
1700 ) -> Result<RemapManifestsResponse, BoxedError>;
1701
1702 async fn set_region_role_state_gracefully(
1706 &self,
1707 region_id: RegionId,
1708 region_role_state: SettableRegionRoleState,
1709 ) -> Result<SetRegionRoleStateResponse, BoxedError>;
1710
1711 fn role(&self, region_id: RegionId) -> Option<RegionRole>;
1715
1716 fn is_confirmed_leader(&self, region_id: RegionId) -> Option<bool> {
1727 self.role(region_id)
1728 .map(|role| role != RegionRole::Follower)
1729 }
1730
1731 fn as_any(&self) -> &dyn Any;
1732}
1733
1734pub type RegionEngineRef = Arc<dyn RegionEngine>;
1735
1736pub struct SinglePartitionScanner {
1738 stream: Mutex<Option<SendableRecordBatchStream>>,
1739 schema: SchemaRef,
1740 properties: ScannerProperties,
1741 metadata: RegionMetadataRef,
1742 snapshot_sequence: Option<SequenceNumber>,
1743}
1744
1745impl SinglePartitionScanner {
1746 pub fn new(
1748 stream: SendableRecordBatchStream,
1749 append_mode: bool,
1750 metadata: RegionMetadataRef,
1751 snapshot_sequence: Option<SequenceNumber>,
1752 ) -> Self {
1753 let schema = stream.schema();
1754 Self {
1755 stream: Mutex::new(Some(stream)),
1756 schema,
1757 properties: ScannerProperties::default().with_append_mode(append_mode),
1758 metadata,
1759 snapshot_sequence,
1760 }
1761 }
1762}
1763
1764impl Debug for SinglePartitionScanner {
1765 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1766 write!(f, "SinglePartitionScanner: <SendableRecordBatchStream>")
1767 }
1768}
1769
1770impl RegionScanner for SinglePartitionScanner {
1771 fn name(&self) -> &str {
1772 "SinglePartition"
1773 }
1774
1775 fn properties(&self) -> &ScannerProperties {
1776 &self.properties
1777 }
1778
1779 fn schema(&self) -> SchemaRef {
1780 self.schema.clone()
1781 }
1782
1783 fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
1784 self.properties.prepare(request);
1785 Ok(())
1786 }
1787
1788 fn scan_partition(
1789 &self,
1790 _ctx: &QueryScanContext,
1791 _metrics_set: &ExecutionPlanMetricsSet,
1792 _partition: usize,
1793 ) -> Result<SendableRecordBatchStream, BoxedError> {
1794 let mut stream = self.stream.lock().unwrap();
1795 let result = stream
1796 .take()
1797 .or_else(|| Some(Box::pin(EmptyRecordBatchStream::new(self.schema.clone()))));
1798 Ok(result.unwrap())
1799 }
1800
1801 fn has_predicate_without_region(&self) -> bool {
1802 false
1803 }
1804
1805 fn add_dyn_filter_to_predicate(
1806 &mut self,
1807 filter_exprs: Vec<Arc<dyn datafusion_physical_plan::PhysicalExpr>>,
1808 ) -> Vec<bool> {
1809 vec![false; filter_exprs.len()]
1810 }
1811
1812 fn metadata(&self) -> RegionMetadataRef {
1813 self.metadata.clone()
1814 }
1815
1816 fn set_logical_region(&mut self, logical_region: bool) {
1817 self.properties.set_logical_region(logical_region);
1818 }
1819
1820 fn set_query_load_region_id(&mut self, region_id: RegionId) {
1821 self.properties.set_query_load_region_id(region_id);
1822 }
1823
1824 fn snapshot_sequence(&self) -> Option<SequenceNumber> {
1825 self.snapshot_sequence
1826 }
1827}
1828
1829impl DisplayAs for SinglePartitionScanner {
1830 fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1831 write!(f, "{:?}", self)
1832 }
1833}