feat(mito2): expose columnar preparation and reader stage metrics (#10132)

* perf(mito2): merge columnar samples with identity-only keys

Signed-off-by: evenyag <realevenyag@gmail.com>

* perf(mito2): instrument columnar sample read stages

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito2): clarify reader timing and focus merge regression coverage

Signed-off-by: evenyag <realevenyag@gmail.com>

* perf(mito2): measure columnar discovery preparation stages

Signed-off-by: evenyag <realevenyag@gmail.com>

* perf(mito2): expose series discovery reader costs

Signed-off-by: evenyag <realevenyag@gmail.com>

* test(mito2): cover first-field null recovery in identity merge

Signed-off-by: evenyag <realevenyag@gmail.com>

* perf(mito2): aggregate preparation counters once per batch

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): retain stage timing on failed and cancelled reads

Signed-off-by: evenyag <realevenyag@gmail.com>

---------

Signed-off-by: evenyag <realevenyag@gmail.com>
This commit is contained in:
Yingwen
2026-11-06 15:56:42 +08:00
committed by GitHub
parent 23afa9697e
commit 758986e12d
3 changed files with 181 additions and 12 deletions
+59 -1
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::time::Duration;
use std::time::{Duration, Instant};
use lazy_static::lazy_static;
use prometheus::*;
@@ -679,6 +679,13 @@ impl StagerNotifier for StagerMetrics {
/// Stream-local counters avoid contended metric updates for every tiny sample block.
/// Stage durations sum elapsed work within a stream, not CPU time or query wall latency.
/// Stages ending in `_wall` include awaits; concurrent streams can overlap.
/// Preparation components partition the work inside `columnar_prepare_wall`; reader
/// stages (`columnar_series_*`) are nested within preparation's discovery stage.
/// `columnar_prepare_acquire_wall` is per caller and includes waiting for shared
/// preparation, so overlapping caller times must not be summed as execution time.
/// Series decode includes decompression and integrity validation; materialization
/// includes dictionary expansion into projected Arrow arrays. Counters are aggregated
/// per stream/preparation, never labeled by query, file, column name, or series ID.
#[derive(Default)]
pub(crate) struct ColumnarReadMetrics {
pub(crate) counts: std::collections::BTreeMap<&'static str, u64>,
@@ -686,7 +693,27 @@ pub(crate) struct ColumnarReadMetrics {
elapsed: std::collections::BTreeMap<&'static str, Duration>,
}
/// Records a stage's elapsed time even when an awaited operation fails or is cancelled.
/// The borrowed accumulator outlives this guard and flushes once with its owner.
pub(crate) struct ColumnarStageTimer<'a> {
elapsed: &'a mut Duration,
started: Instant,
}
impl Drop for ColumnarStageTimer<'_> {
fn drop(&mut self) {
*self.elapsed += self.started.elapsed();
}
}
impl ColumnarReadMetrics {
pub(crate) fn timer(&mut self, stage: &'static str) -> ColumnarStageTimer<'_> {
ColumnarStageTimer {
elapsed: self.elapsed.entry(stage).or_default(),
started: Instant::now(),
}
}
pub(crate) fn add_elapsed(&mut self, stage: &'static str, elapsed: Duration) {
*self.elapsed.entry(stage).or_default() += elapsed;
}
@@ -711,3 +738,34 @@ impl Drop for ColumnarReadMetrics {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn stage_timer_retains_failed_and_cancelled_waits() {
let mut metrics = ColumnarReadMetrics::default();
let result = async {
let mut timer = metrics.timer("columnar_series_fetch_wall");
// Backdate the clock to keep the lifetime test deterministic without sleeping.
timer.started -= Duration::from_secs(1);
std::future::ready(Err::<(), ()>(())).await?;
Ok::<(), ()>(())
}
.await;
assert!(result.is_err());
let failed = metrics.elapsed["columnar_series_fetch_wall"];
assert!(failed >= Duration::from_secs(1));
let mut wait = Box::pin(async {
let mut timer = metrics.timer("columnar_series_fetch_wall");
timer.started -= Duration::from_secs(1);
std::future::pending::<()>().await;
});
assert!(futures::poll!(&mut wait).is_pending());
drop(wait);
// Dropping the suspended future must add to, rather than replace, earlier work.
assert!(metrics.elapsed["columnar_series_fetch_wall"] >= failed + Duration::from_secs(1));
}
}
+71 -1
View File
@@ -20,6 +20,7 @@ mod tests;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::ops::Range;
use std::sync::Arc;
use std::time::Instant;
use api::v1::SemanticType;
use common_error::ext::BoxedError;
@@ -87,6 +88,11 @@ impl Preparation {
raw: RawScanPreparation,
metrics: PartitionMetrics,
) -> std::result::Result<Arc<dyn PreparedSeriesSource>, BoxedError> {
// Per caller, including time awaiting another partition's shared preparation.
// This overlaps prepare_wall and must not be added to its component timings.
let acquire_timer = crate::metrics::READ_STAGE_ELAPSED
.with_label_values(&["columnar_prepare_acquire_wall"])
.start_timer();
let expected = labels.clone();
let result = self
.source
@@ -97,6 +103,7 @@ impl Preparation {
.map_err(Arc::new)
})
.await;
drop(acquire_timer);
let source = result.as_ref().map_err(|error| {
BoxedError::new(crate::error::ScanSeriesSnafu.into_error(error.clone()))
})?;
@@ -302,6 +309,9 @@ impl ColumnarPreparedSource {
let _prepare_timer = crate::metrics::READ_STAGE_ELAPSED
.with_label_values(&["columnar_prepare_wall"])
.start_timer();
let mut preparation_metrics = crate::metrics::ColumnarReadMetrics::default();
preparation_metrics.counts.insert("prepare_executions", 1);
let started = Instant::now();
let input = &context.input;
let metadata = input.region_metadata();
let index = input
@@ -314,6 +324,8 @@ impl ColumnarPreparedSource {
"columnar series coverage changed after series preparation",
));
};
preparation_metrics.add_elapsed("columnar_prepare_coverage", started.elapsed());
let timer = preparation_metrics.timer("columnar_prepare_samples_open_wall");
let cache = input
.cache_strategy
.columnar_metadata(index.cache_namespace);
@@ -330,16 +342,26 @@ impl ColumnarPreparedSource {
format::validate_sample_schema(&reader.schema(), metadata)?;
samples.push(Arc::new(reader));
}
drop(timer);
preparation_metrics
.counts
.insert("prepare_sample_readers", samples.len() as u64);
preparation_metrics
.counts
.insert("prepare_series_indexes", indexes.len() as u64);
let reservation =
MemoryConsumer::new("ColumnarPreparedSource").register(&input.scan_memory_pool);
let mut candidates = BTreeMap::<MetricSeriesId, Candidate>::new();
for id in indexes {
let timer = preparation_metrics.timer("columnar_prepare_series_open_wall");
let reader = crate::series_index::columnar::reader::ColumnarReader::open_cached(
index.store.clone(),
index.version.series_indexes[&id].clone(),
cache.clone(),
)
.await?;
drop(timer);
let started = Instant::now();
let schema = reader.schema();
format::validate_series_schema(&schema, metadata)?;
let mut tags = schema
@@ -378,12 +400,34 @@ impl ColumnarPreparedSource {
}
}
}
preparation_metrics.add_elapsed("columnar_prepare_compile", started.elapsed());
let mut batches = reader.read(request)?;
while let Some(mut batch) = batches.try_next().await? {
loop {
let timer = preparation_metrics.timer("columnar_prepare_discovery_wall");
let batch = batches.try_next().await?;
drop(timer);
let Some(mut batch) = batch else {
break;
};
*preparation_metrics
.counts
.entry("prepare_discovered_rows")
.or_default() += batch.num_rows() as u64;
*preparation_metrics
.counts
.entry("prepare_discovery_batches")
.or_default() += 1;
let started = Instant::now();
for filter in &filters {
batch = common_recordbatch::filter::batch_filter(&batch, filter)
.map_err(|e| invalid(e.to_string()))?;
}
preparation_metrics.add_elapsed("columnar_prepare_residual", started.elapsed());
*preparation_metrics
.counts
.entry("prepare_selected_rows")
.or_default() += batch.num_rows() as u64;
let started = Instant::now();
let table = batch
.column_by_name(DATA_SCHEMA_TABLE_ID_COLUMN_NAME)
.ok_or_else(|| invalid("missing table ID column"))?
@@ -408,6 +452,9 @@ impl ColumnarPreparedSource {
Ok((*id, strings))
})
.collect::<Result<Vec<_>>>()?;
let mut encoded_key_bytes = 0_u64;
let mut tag_values = 0_u64;
let mut duplicate_rows = 0_u64;
for row in 0..batch.num_rows() {
let id = MetricSeriesId {
table_id: table.value(row),
@@ -437,7 +484,9 @@ impl ColumnarPreparedSource {
&mut key,
)
.map_err(|e| invalid(e.to_string()))?;
encoded_key_bytes += key.len() as u64;
if let Some(previous) = candidates.get(&id) {
duplicate_rows += 1;
if previous.key.as_slice() != key.as_slice() {
return Err(invalid(
"conflicting labels for the same table ID and TSID",
@@ -447,6 +496,7 @@ impl ColumnarPreparedSource {
}
// Duplicate identities still undergo a full key comparison before
// allocating another owned tag map.
tag_values += tag_arrays.len() as u64;
let mut values = HashMap::with_capacity(tag_arrays.len());
for (column_id, strings) in &tag_arrays {
values.insert(
@@ -474,12 +524,32 @@ impl ColumnarPreparedSource {
},
);
}
*preparation_metrics
.bytes
.entry("prepare_encoded_keys")
.or_default() += encoded_key_bytes;
*preparation_metrics
.counts
.entry("prepare_tag_values")
.or_default() += tag_values;
*preparation_metrics
.counts
.entry("prepare_duplicate_rows")
.or_default() += duplicate_rows;
preparation_metrics.add_elapsed("columnar_prepare_candidates", started.elapsed());
}
}
let started = Instant::now();
preparation_metrics
.counts
.insert("prepare_unique_series", candidates.len() as u64);
let mut candidates: Vec<_> = candidates.into_values().collect();
candidates.sort_unstable_by(|a, b| a.key.as_slice().cmp(b.key.as_slice()));
preparation_metrics.add_elapsed("columnar_prepare_sort", started.elapsed());
let started = Instant::now();
let mut raw = raw;
let sample_schema = sample_merge_schema(&context, &mut raw)?;
preparation_metrics.add_elapsed("columnar_prepare_schema", started.elapsed());
Ok(Self {
context,
labels,
+51 -10
View File
@@ -16,6 +16,7 @@
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Instant;
use common_recordbatch::filter::SimpleFilterEvaluator;
use datatypes::arrow::array::{ArrayRef, StringArray, UInt32Array, UInt64Array};
@@ -28,6 +29,7 @@ use snafu::ResultExt;
use crate::cache::columnar::{self as metadata_cache, MetadataCache};
use crate::error::{NewRecordBatchSnafu, OpenDalSnafu, RecordBatchSnafu, Result, SerdeJsonSnafu};
use crate::metrics::ColumnarReadMetrics;
use crate::series_index::artifact::ArtifactFormat;
use crate::series_index::columnar::codec::{self, Dictionary};
use crate::series_index::columnar::metadata::{self, Block, Column, Page, PageReference, Trailer};
@@ -226,8 +228,11 @@ impl FormatReader for ColumnarReader {
Ok(Box::pin(async_stream::try_stream! {
// Retained across every yield, even after the reader object is dropped.
let _handle = handle;
let mut metrics = ColumnarReadMetrics::default();
for part in &manifest.files {
if !matches_range(part.first, part.last, &request) { continue; }
*metrics.counts.entry("series_parts").or_default() += 1;
let timer = metrics.timer("columnar_series_metadata_wall");
let path = manifest.part_path(part.part_id);
let size = part.file_size;
let trailer = metadata_cache::load(cache.as_ref(), format!("{path}/{size}/framing"), |_| std::mem::size_of::<Trailer>(), async {
@@ -244,6 +249,7 @@ impl FormatReader for ColumnarReader {
}).await?;
require(trailer.root.first == part.first && trailer.root.last == part.last, "series part/root bounds mismatch")?;
let root = load_metadata_page(cache.as_ref(), &store, (&path, size), &trailer.root, trailer.depth, trailer.payload_end, &names).await?;
drop(timer);
let (mut active, children) = match root.as_ref() {
Page::Leaf(_) => (Some(root.clone()), Vec::new()),
Page::Internal(children) => (None, children.clone()),
@@ -255,18 +261,31 @@ impl FormatReader for ColumnarReader {
let page = if let Some(page) = active.take() { page } else {
let Some(child) = child_iter.next() else { break; };
if !matches_range(child.first, child.last, &request) { continue; }
load_metadata_page(cache.as_ref(), &store, (&path, size), &child, 1, trailer.payload_end, &names).await?
let timer = metrics.timer("columnar_series_metadata_wall");
let page = load_metadata_page(cache.as_ref(), &store, (&path, size), &child, 1, trailer.payload_end, &names).await?;
drop(timer);
page
};
let blocks = match page.as_ref() { Page::Leaf(blocks) => blocks, Page::Internal(_) => Err(unsupported("internal child in depth-two series index"))? };
for block in blocks {
*metrics.counts.entry("series_blocks_considered").or_default() += 1;
observed_rows = observed_rows.checked_add(u64::from(block.rows)).ok_or_else(|| invalid("series part row count overflow"))?;
for column in &block.columns {
column.payload.validate(previous_payload_end, trailer.payload_end, false)?;
previous_payload_end = column.payload.end()?;
}
if !matches_range(block.first_id(), block.last_id(), &request) || !matches_statistics(block, &request.filters) { continue; }
if let Some(mut output) = read_block(&store, &path, block, &request, projected.clone()).await? {
while let Some(batch) = output.next_batch()? { yield batch; }
*metrics.counts.entry("series_blocks_read").or_default() += 1;
*metrics.counts.entry("series_rows_examined").or_default() += u64::from(block.rows);
if let Some(mut output) = read_block(&store, &path, block, &request, projected.clone(), &mut metrics).await? {
loop {
let started = Instant::now();
let batch = output.next_batch()?;
metrics.add_elapsed("columnar_series_materialize", started.elapsed());
let Some(batch) = batch else { break; };
*metrics.counts.entry("series_rows_output").or_default() += batch.num_rows() as u64;
yield batch;
}
}
}
}
@@ -433,6 +452,7 @@ async fn load_column_chunk(
path: &str,
column: &Column,
block: &Block,
metrics: &mut ColumnarReadMetrics,
) -> Result<Decoded> {
let integer = column.name == TSID_COLUMN || column.name == ROW_COUNT_COLUMN;
let expected = if integer {
@@ -446,12 +466,17 @@ async fn load_column_chunk(
column.payload.encoding, column.name
)));
}
let timer = metrics.timer("columnar_series_fetch_wall");
let bytes = read_range(store, path, column.payload.offset, column.payload.end()?).await?;
drop(timer);
*metrics.counts.entry("series_column_reads").or_default() += 1;
*metrics.bytes.entry("series_payload_fetched").or_default() += bytes.len() as u64;
let started = Instant::now();
let rows = block.rows as usize;
let first = block.first;
let last = block.last;
let bytes = column.payload.unpack(&bytes)?;
if integer {
let result = if integer {
let values = codec::decode_integers(&bytes, rows)?;
if column.name == TSID_COLUMN {
require(
@@ -486,15 +511,23 @@ async fn load_column_chunk(
"series dictionary bounds mismatch",
)?;
Ok(Decoded::Strings(dictionary))
}
};
metrics.add_elapsed("columnar_series_decode", started.elapsed());
result
}
async fn get_column(store: &ObjectStore, path: &str, block: &Block, name: &str) -> Result<Decoded> {
async fn get_column(
store: &ObjectStore,
path: &str,
block: &Block,
name: &str,
metrics: &mut ColumnarReadMetrics,
) -> Result<Decoded> {
if name == TABLE_ID_COLUMN {
return Ok(Decoded::Table(block.table_id, block.rows as usize));
}
match block.columns.iter().find(|c| c.name == name) {
Some(column) => load_column_chunk(store, path, column, block).await,
Some(column) => load_column_chunk(store, path, column, block, metrics).await,
None => Ok(Decoded::Null(block.rows as usize)),
}
}
@@ -505,11 +538,12 @@ async fn read_block(
block: &Block,
request: &SeriesReadRequest,
schema: SchemaRef,
metrics: &mut ColumnarReadMetrics,
) -> Result<Option<ProjectedBlock>> {
let mut decoded = HashMap::new();
let mut selected: Vec<_> = (0..block.rows as usize).collect();
if let Some(ids) = &request.ids {
let column = get_column(store, path, block, TSID_COLUMN).await?;
let column = get_column(store, path, block, TSID_COLUMN, metrics).await?;
if let Decoded::Integers(values) = &column {
selected.retain(|&i| {
ids.contains(&MetricSeriesId {
@@ -526,15 +560,18 @@ async fn read_block(
}
let name = filter.column_name();
if !decoded.contains_key(name) {
*metrics.counts.entry("series_filter_columns").or_default() += 1;
decoded.insert(
name.to_owned(),
Arc::new(get_column(store, path, block, name).await?),
Arc::new(get_column(store, path, block, name, metrics).await?),
);
}
let started = Instant::now();
decoded
.get(name)
.ok_or_else(|| invalid("missing decoded filter column"))?
.filter(filter, &mut selected)?;
metrics.add_elapsed("columnar_series_filter", started.elapsed());
}
if selected.is_empty() {
return Ok(None);
@@ -542,9 +579,13 @@ async fn read_block(
let mut columns = Vec::with_capacity(request.projection.len());
for name in &request.projection {
if !decoded.contains_key(name) {
*metrics
.counts
.entry("series_projection_columns")
.or_default() += 1;
decoded.insert(
name.clone(),
Arc::new(get_column(store, path, block, name).await?),
Arc::new(get_column(store, path, block, name, metrics).await?),
);
}
columns.push(