1use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19use arrow::array::UInt32Array;
20use arrow::compute::concat_batches;
21use arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema};
22use arrow::record_batch::RecordBatch;
23use common_query::prelude::{greptime_timestamp, greptime_value};
24use metric_engine::batch_modifier::{TagColumnInfo, modify_batch_sparse};
25use smallvec::SmallVec;
26use snafu::{OptionExt, ResultExt, ensure};
27use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME;
28use table::metadata::TableId;
29
30use crate::error;
31use crate::error::Result;
32use crate::metrics::PENDING_ROWS_BATCH_FLUSH_STAGE_ELAPSED;
33
34#[derive(Debug, Clone)]
36pub struct RecordBatchWithTsIdx {
37 pub(in crate::batcher::logical_table) progress:
38 Option<Arc<session::write_progress::WriteProgress>>,
39 pub(in crate::batcher::logical_table) owner: usize,
40 pub(in crate::batcher::logical_table) batch: RecordBatch,
42 pub(in crate::batcher::logical_table) timestamp_index: usize,
44}
45
46impl RecordBatchWithTsIdx {
47 pub fn try_new(batch: RecordBatch, timestamp_index: usize) -> Result<Self> {
49 let schema = batch.schema();
50 let timestamp_field = schema.fields().get(timestamp_index).with_context(|| {
51 error::InvalidPromRemoteRequestSnafu {
52 msg: format!(
53 "Timestamp column index {} is out of bounds for record batch with {} columns",
54 timestamp_index,
55 batch.num_columns()
56 ),
57 }
58 })?;
59 ensure!(
60 matches!(timestamp_field.data_type(), ArrowDataType::Timestamp(_, _)),
61 error::InvalidPromRemoteRequestSnafu {
62 msg: format!(
63 "Column at index {} is not a timestamp column: {:?}",
64 timestamp_index,
65 timestamp_field.data_type()
66 ),
67 }
68 );
69
70 Ok(Self {
71 progress: None,
72 owner: 0,
73 batch,
74 timestamp_index,
75 })
76 }
77
78 #[cfg(test)]
79 pub(crate) fn into_parts(self) -> (RecordBatch, usize) {
80 (self.batch, self.timestamp_index)
81 }
82}
83
84#[derive(Debug, Clone)]
85pub struct TableBatch {
86 pub table_name: String,
87 pub table_id: TableId,
88 pub batches: Vec<RecordBatchWithTsIdx>,
89 pub row_count: usize,
90}
91
92pub(in crate::batcher::logical_table) fn columns_taxonomy(
101 batch_schema: &Arc<ArrowSchema>,
102 table_name: &str,
103 name_to_ids: &HashMap<String, u32>,
104 partition_columns: &HashSet<&str>,
105) -> Result<(Vec<TagColumnInfo>, SmallVec<[usize; 3]>)> {
106 let mut tag_columns = Vec::new();
107 let mut essential_column_indices =
108 SmallVec::<[usize; 3]>::with_capacity(2 + partition_columns.len());
109 essential_column_indices.push(0);
111 essential_column_indices.push(0);
112
113 let mut timestamp_index = None;
114 let mut value_index = None;
115
116 for (index, field) in batch_schema.fields().iter().enumerate() {
117 match field.data_type() {
118 ArrowDataType::Utf8 => {
119 let column_id = name_to_ids.get(field.name()).copied().with_context(|| {
120 error::InvalidPromRemoteRequestSnafu {
121 msg: format!(
122 "Column '{}' from logical table '{}' not found in physical table column IDs",
123 field.name(),
124 table_name
125 ),
126 }
127 })?;
128 tag_columns.push(TagColumnInfo {
129 name: field.name().clone(),
130 index,
131 column_id,
132 });
133
134 if partition_columns.contains(field.name().as_str()) {
135 essential_column_indices.push(index);
136 }
137 }
138 ArrowDataType::Timestamp(_, _) => {
139 ensure!(
140 timestamp_index.replace(index).is_none(),
141 error::InvalidPromRemoteRequestSnafu {
142 msg: format!(
143 "Duplicated timestamp column in logical table '{}' batch schema",
144 table_name
145 ),
146 }
147 );
148 }
149 ArrowDataType::Float64 => {
150 ensure!(
151 value_index.replace(index).is_none(),
152 error::InvalidPromRemoteRequestSnafu {
153 msg: format!(
154 "Duplicated value column in logical table '{}' batch schema",
155 table_name
156 ),
157 }
158 );
159 }
160 datatype => {
161 return error::InvalidPromRemoteRequestSnafu {
162 msg: format!(
163 "Unexpected data type '{datatype:?}' in logical table '{}' batch schema",
164 table_name
165 ),
166 }
167 .fail();
168 }
169 }
170 }
171
172 let timestamp_index =
173 timestamp_index.with_context(|| error::InvalidPromRemoteRequestSnafu {
174 msg: format!(
175 "Missing essential column '{}' in logical table '{}' batch schema",
176 greptime_timestamp(),
177 table_name
178 ),
179 })?;
180 let value_index = value_index.with_context(|| error::InvalidPromRemoteRequestSnafu {
181 msg: format!(
182 "Missing essential column '{}' in logical table '{}' batch schema",
183 greptime_value(),
184 table_name
185 ),
186 })?;
187
188 tag_columns.sort_by(|a, b| a.name.cmp(&b.name));
189
190 essential_column_indices[0] = timestamp_index;
191 essential_column_indices[1] = value_index;
192
193 Ok((tag_columns, essential_column_indices))
194}
195
196pub(in crate::batcher::logical_table) fn transform_logical_batches_to_physical(
203 table_batches: &[TableBatch],
204 name_to_ids: &HashMap<String, u32>,
205 partition_columns_set: &HashSet<&str>,
206) -> Result<Vec<RecordBatch>> {
207 let mut modified_batches: Vec<RecordBatch> =
208 Vec::with_capacity(table_batches.iter().map(|b| b.batches.len()).sum());
209
210 let mut modify_elapsed = Duration::ZERO;
211 let mut columns_taxonomy_elapsed = Duration::ZERO;
212
213 for table_batch in table_batches {
214 let table_id = table_batch.table_id;
215
216 for batch in &table_batch.batches {
217 let batch = &batch.batch;
218 let batch_schema = batch.schema();
219 let start = Instant::now();
220 let (tag_columns, essential_col_indices) = columns_taxonomy(
221 &batch_schema,
222 &table_batch.table_name,
223 name_to_ids,
224 partition_columns_set,
225 )?;
226
227 columns_taxonomy_elapsed += start.elapsed();
228 let modified = {
229 let start = Instant::now();
230 let batch = modify_batch_sparse(
232 batch.clone(),
233 table_id,
234 &tag_columns,
235 &essential_col_indices,
236 )?;
237 modify_elapsed += start.elapsed();
238 batch
239 };
240
241 modified_batches.push(modified);
242 }
243 }
244
245 PENDING_ROWS_BATCH_FLUSH_STAGE_ELAPSED
246 .with_label_values(&["flush_physical_modify_batch"])
247 .observe(modify_elapsed.as_secs_f64());
248 PENDING_ROWS_BATCH_FLUSH_STAGE_ELAPSED
249 .with_label_values(&["flush_physical_columns_taxonomy"])
250 .observe(columns_taxonomy_elapsed.as_secs_f64());
251
252 ensure!(
253 !modified_batches.is_empty(),
254 error::InternalSnafu {
255 err_msg: "No batches can be transformed during pending flush",
256 }
257 );
258 Ok(modified_batches)
259}
260
261pub(in crate::batcher::logical_table) fn concat_modified_batches(
269 modified_batches: &[RecordBatch],
270 table_batches: &[TableBatch],
271) -> Result<RecordBatch> {
272 let combined_schema = modified_batches[0].schema();
273 let _timer = PENDING_ROWS_BATCH_FLUSH_STAGE_ELAPSED
274 .with_label_values(&["flush_physical_concat_all"])
275 .start_timer();
276 let combined = concat_batches(&combined_schema, modified_batches).context(error::ArrowSnafu)?;
277 let mut table_ids = Vec::with_capacity(combined.num_rows());
280 for table in table_batches {
281 for batch in &table.batches {
282 table_ids.extend(std::iter::repeat_n(table.table_id, batch.batch.num_rows()));
283 }
284 }
285 ensure!(
286 table_ids.len() == combined.num_rows(),
287 error::InternalSnafu {
288 err_msg: "Logical table ids do not match combined rows",
289 }
290 );
291 let mut fields = combined.schema().fields().to_vec();
292 fields.push(Arc::new(Field::new(
293 DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
294 ArrowDataType::UInt32,
295 false,
296 )));
297 let mut columns = combined.columns().to_vec();
298 columns.push(Arc::new(UInt32Array::from(table_ids)));
299 RecordBatch::try_new(Arc::new(ArrowSchema::new(fields)), columns).context(error::ArrowSnafu)
300}
301
302#[cfg(test)]
303mod tests {
304 use std::collections::{HashMap, HashSet};
305 use std::sync::Arc;
306
307 use arrow::array::{Array, StringArray, TimestampMillisecondArray};
308 use arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema};
309 use arrow::record_batch::RecordBatch;
310 use metric_engine::batch_modifier::modify_batch_sparse;
311 use smallvec::SmallVec;
312
313 use crate::batcher::logical_table::batch_convert::{
314 TableBatch, columns_taxonomy, concat_modified_batches,
315 transform_logical_batches_to_physical,
316 };
317 use crate::batcher::logical_table::test_util::mock_aligned_tag_batch;
318 use crate::error::Error;
319
320 #[test]
321 fn test_collect_tag_columns_and_non_tag_indices_keeps_partition_tag_column() {
322 let schema = Arc::new(ArrowSchema::new(vec![
323 Field::new(
324 "greptime_timestamp",
325 ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
326 false,
327 ),
328 Field::new("greptime_value", ArrowDataType::Float64, true),
329 Field::new("host", ArrowDataType::Utf8, true),
330 Field::new("region", ArrowDataType::Utf8, true),
331 ]));
332 let name_to_ids =
333 HashMap::from([("host".to_string(), 1_u32), ("region".to_string(), 2_u32)]);
334 let partition_columns = HashSet::from(["host"]);
335
336 let (tag_columns, non_tag_indices) =
337 columns_taxonomy(&schema, "cpu", &name_to_ids, &partition_columns).unwrap();
338
339 assert_eq!(2, tag_columns.len());
340 assert_eq!(&[0, 1, 2], non_tag_indices.as_slice());
341 }
342
343 #[test]
344 fn test_collect_tag_columns_and_non_tag_indices_prioritizes_essential_columns() {
345 let schema = Arc::new(ArrowSchema::new(vec![
346 Field::new("host", ArrowDataType::Utf8, true),
347 Field::new("greptime_value", ArrowDataType::Float64, true),
348 Field::new(
349 "greptime_timestamp",
350 ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
351 false,
352 ),
353 Field::new("region", ArrowDataType::Utf8, true),
354 ]));
355 let name_to_ids =
356 HashMap::from([("host".to_string(), 1_u32), ("region".to_string(), 2_u32)]);
357 let partition_columns = HashSet::from(["host", "region"]);
358
359 let (_tag_columns, non_tag_indices): (_, SmallVec<[usize; 3]>) =
360 columns_taxonomy(&schema, "cpu", &name_to_ids, &partition_columns).unwrap();
361
362 assert_eq!(&[2, 1, 0, 3], non_tag_indices.as_slice());
363 }
364
365 #[test]
366 fn test_collect_tag_columns_and_non_tag_indices_rejects_unexpected_data_type() {
367 let schema = Arc::new(ArrowSchema::new(vec![
368 Field::new(
369 "greptime_timestamp",
370 ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
371 false,
372 ),
373 Field::new("greptime_value", ArrowDataType::Float64, true),
374 Field::new("host", ArrowDataType::Utf8, true),
375 Field::new("invalid", ArrowDataType::Boolean, true),
376 ]));
377 let name_to_ids = HashMap::from([("host".to_string(), 1_u32)]);
378 let partition_columns = HashSet::from(["host"]);
379
380 let result = columns_taxonomy(&schema, "cpu", &name_to_ids, &partition_columns);
381
382 assert!(matches!(
383 result,
384 Err(Error::InvalidPromRemoteRequest { .. })
385 ));
386 }
387
388 #[test]
389 fn test_collect_tag_columns_and_non_tag_indices_rejects_int64_timestamp_column() {
390 let schema = Arc::new(ArrowSchema::new(vec![
391 Field::new("greptime_timestamp", ArrowDataType::Int64, false),
392 Field::new("greptime_value", ArrowDataType::Float64, true),
393 Field::new("host", ArrowDataType::Utf8, true),
394 ]));
395 let name_to_ids = HashMap::from([("host".to_string(), 1_u32)]);
396 let partition_columns = HashSet::from(["host"]);
397
398 let result = columns_taxonomy(&schema, "cpu", &name_to_ids, &partition_columns);
399
400 assert!(matches!(
401 result,
402 Err(Error::InvalidPromRemoteRequest { .. })
403 ));
404 }
405
406 #[test]
407 fn test_collect_tag_columns_and_non_tag_indices_rejects_duplicated_timestamp_column() {
408 let schema = Arc::new(ArrowSchema::new(vec![
409 Field::new(
410 "ts1",
411 ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
412 false,
413 ),
414 Field::new(
415 "ts2",
416 ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
417 false,
418 ),
419 Field::new("greptime_value", ArrowDataType::Float64, true),
420 Field::new("host", ArrowDataType::Utf8, true),
421 ]));
422 let name_to_ids = HashMap::from([("host".to_string(), 1_u32)]);
423 let partition_columns = HashSet::from(["host"]);
424
425 let result = columns_taxonomy(&schema, "cpu", &name_to_ids, &partition_columns);
426
427 assert!(matches!(
428 result,
429 Err(Error::InvalidPromRemoteRequest { .. })
430 ));
431 }
432
433 #[test]
434 fn test_collect_tag_columns_and_non_tag_indices_rejects_duplicated_value_column() {
435 let schema = Arc::new(ArrowSchema::new(vec![
436 Field::new(
437 "greptime_timestamp",
438 ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
439 false,
440 ),
441 Field::new("value1", ArrowDataType::Float64, true),
442 Field::new("value2", ArrowDataType::Float64, true),
443 Field::new("host", ArrowDataType::Utf8, true),
444 ]));
445 let name_to_ids = HashMap::from([("host".to_string(), 1_u32)]);
446 let partition_columns = HashSet::from(["host"]);
447
448 let result = columns_taxonomy(&schema, "cpu", &name_to_ids, &partition_columns);
449
450 assert!(matches!(
451 result,
452 Err(Error::InvalidPromRemoteRequest { .. })
453 ));
454 }
455
456 #[test]
457 fn test_modify_batch_sparse_with_taxonomy_per_batch() {
458 use arrow::array::BinaryArray;
459
460 let schema1 = Arc::new(ArrowSchema::new(vec![
461 Field::new(
462 "greptime_timestamp",
463 ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
464 false,
465 ),
466 Field::new("greptime_value", ArrowDataType::Float64, true),
467 Field::new("tag1", ArrowDataType::Utf8, true),
468 ]));
469
470 let schema2 = Arc::new(ArrowSchema::new(vec![
471 Field::new(
472 "greptime_timestamp",
473 ArrowDataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None),
474 false,
475 ),
476 Field::new("greptime_value", ArrowDataType::Float64, true),
477 Field::new("tag1", ArrowDataType::Utf8, true),
478 Field::new("tag2", ArrowDataType::Utf8, true),
479 ]));
480 let batch2 = RecordBatch::try_new(
481 schema2.clone(),
482 vec![
483 Arc::new(TimestampMillisecondArray::from(vec![2000])),
484 Arc::new(arrow::array::Float64Array::from(vec![2.0])),
485 Arc::new(StringArray::from(vec!["v1"])),
486 Arc::new(StringArray::from(vec!["v2"])),
487 ],
488 )
489 .unwrap();
490
491 let name_to_ids = HashMap::from([("tag1".to_string(), 1), ("tag2".to_string(), 2)]);
492 let partition_columns = HashSet::new();
493
494 let batch3 = RecordBatch::try_new(
496 schema1.clone(),
497 vec![
498 Arc::new(TimestampMillisecondArray::from(vec![2000])),
499 Arc::new(arrow::array::Float64Array::from(vec![2.0])),
500 Arc::new(StringArray::from(vec!["v1"])),
501 ],
502 )
503 .unwrap();
504
505 let (tag_columns2, indices2) =
508 columns_taxonomy(&batch2.schema(), "table", &name_to_ids, &partition_columns).unwrap();
509 let modified2 = modify_batch_sparse(batch2, 123, &tag_columns2, &indices2).unwrap();
510
511 let (tag_columns3, indices3) =
512 columns_taxonomy(&batch3.schema(), "table", &name_to_ids, &partition_columns).unwrap();
513 let modified3 = modify_batch_sparse(batch3, 123, &tag_columns3, &indices3).unwrap();
514
515 let pk2 = modified2
516 .column(0)
517 .as_any()
518 .downcast_ref::<BinaryArray>()
519 .unwrap();
520 let pk3 = modified3
521 .column(0)
522 .as_any()
523 .downcast_ref::<BinaryArray>()
524 .unwrap();
525
526 assert_ne!(
528 pk2.value(0),
529 pk3.value(0),
530 "PK should be different because batch2 has tag2!"
531 );
532 }
533
534 #[test]
535 fn test_transform_logical_batches_to_physical_success() {
536 let batch = mock_aligned_tag_batch("tag1", "v1", 1000, 1.0);
537
538 let table_batches = vec![TableBatch {
539 table_name: "t1".to_string(),
540 table_id: 1,
541 batches: vec![batch],
542 row_count: 1,
543 }];
544
545 let name_to_ids = HashMap::from([("tag1".to_string(), 1)]);
546 let partition_columns = HashSet::new();
547 let modified =
548 transform_logical_batches_to_physical(&table_batches, &name_to_ids, &partition_columns)
549 .unwrap();
550
551 assert_eq!(1, modified.len());
552 assert_eq!(3, modified[0].num_columns());
553 assert_eq!("__primary_key", modified[0].schema().field(0).name());
554 assert_eq!("greptime_timestamp", modified[0].schema().field(1).name());
555 assert_eq!("greptime_value", modified[0].schema().field(2).name());
556 }
557
558 #[test]
559 fn test_transform_logical_batches_to_physical_taxonomy_failure() {
560 let batch = mock_aligned_tag_batch("tag1", "v1", 1000, 1.0);
561
562 let table_batches = vec![TableBatch {
563 table_name: "t1".to_string(),
564 table_id: 1,
565 batches: vec![batch],
566 row_count: 1,
567 }];
568
569 let name_to_ids = HashMap::new();
571 let partition_columns = HashSet::new();
572 let err =
573 transform_logical_batches_to_physical(&table_batches, &name_to_ids, &partition_columns)
574 .unwrap_err();
575
576 assert!(
577 err.to_string()
578 .contains("not found in physical table column IDs")
579 );
580 }
581
582 #[test]
583 fn test_transform_logical_batches_to_physical_multiple_batches() {
584 let batch1 = mock_aligned_tag_batch("tag1", "v1", 1000, 1.0);
585 let batch2 = mock_aligned_tag_batch("tag2", "v2", 2000, 2.0);
586
587 let table_batches = vec![
588 TableBatch {
589 table_name: "t1".to_string(),
590 table_id: 1,
591 batches: vec![batch1],
592 row_count: 1,
593 },
594 TableBatch {
595 table_name: "t2".to_string(),
596 table_id: 2,
597 batches: vec![batch2],
598 row_count: 1,
599 },
600 ];
601
602 let name_to_ids = HashMap::from([("tag1".to_string(), 1), ("tag2".to_string(), 2)]);
603 let partition_columns = HashSet::new();
604 let modified =
605 transform_logical_batches_to_physical(&table_batches, &name_to_ids, &partition_columns)
606 .unwrap();
607
608 assert_eq!(2, modified.len());
609
610 let err = concat_modified_batches(&modified, &table_batches[..1]).unwrap_err();
611 assert!(
612 matches!(&err, Error::Internal { err_msg }
613 if err_msg == "Logical table ids do not match combined rows"),
614 "{err}"
615 );
616 }
617
618 #[test]
619 fn test_transform_logical_batches_to_physical_mixed_success_failure() {
620 let batch1 = mock_aligned_tag_batch("tag1", "v1", 1000, 1.0);
621 let batch2 = mock_aligned_tag_batch("tag2", "v2", 2000, 2.0);
622
623 let table_batches = vec![
624 TableBatch {
625 table_name: "t1".to_string(),
626 table_id: 1,
627 batches: vec![batch1],
628 row_count: 1,
629 },
630 TableBatch {
631 table_name: "t2".to_string(),
632 table_id: 2,
633 batches: vec![batch2],
634 row_count: 1,
635 },
636 ];
637
638 let name_to_ids = HashMap::from([("tag2".to_string(), 2)]);
640 let partition_columns = HashSet::new();
641 let err =
642 transform_logical_batches_to_physical(&table_batches, &name_to_ids, &partition_columns)
643 .unwrap_err();
644
645 assert!(err.to_string().contains("tag1"));
646 }
647}