diff --git a/Cargo.lock b/Cargo.lock index 8fcec39a0ca..2b5ad408991 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5738,6 +5738,7 @@ dependencies = [ "partition", "pipeline", "prometheus 0.14.0", + "promql", "promql-parser", "prost 0.14.1", "query", diff --git a/config/config.md b/config/config.md index c0abf27ee3c..12fde8ffd68 100644 --- a/config/config.md +++ b/config/config.md @@ -287,6 +287,12 @@ | `event_recorder.event_types` | Array | All | Event types to record. Current available event types: `create_database`,
`alter_database`, `drop_database`, `create_flow`, `drop_flow`,
`create_table`, `create_logical_tables`, `alter_table`, `alter_logical_tables`,
`drop_table`, `undrop_table`, `purge_dropped_table`, `truncate_table`,
`create_view`, `drop_view`, `admin_function`, `reconcile_catalog`,
`reconcile_database`, `reconcile_table`, `reconcile_logical_tables`.
When omitted, all current and future event types are recorded.
Set to an empty array to disable event recording. | | `memory` | -- | -- | The memory options. | | `memory.enable_heap_profiling` | Bool | `true` | Whether to enable heap profiling activation during startup.
When enabled, heap profiling will be activated if the `MALLOC_CONF` environment variable
is set to "prof:true,prof_active:false". The official image adds this env variable.
Default is true. | +| `promql_rollup_cache` | -- | -- | The frontend-local cache of PromQL range-query chunks. It is disabled by default; enabling it does not change instant queries or expressions outside the window allowlist. | +| `promql_rollup_cache.enable` | Bool | `false` | Whether range queries may be served from the cache. | +| `promql_rollup_cache.max_bytes` | String | Auto | The total memory budget for cached chunks and their annotations.
Defaults to 1/128 of the host or pod memory limit, with a minimum of 32MiB and a maximum of 8GiB.
Uses 32MiB if memory detection is unavailable. | +| `promql_rollup_cache.chunk` | String | `5m` | The target chunk duration. It is global while the step belongs to the query, so planning
aligns it down to a whole number of the query's steps, floored at 20 steps: any step is
cacheable, the chunk of one step is one fixed length, and a coarse step is never cut into
one-point chunks. | +| `promql_rollup_cache.tail` | String | `5m` | Output points this close to wall-clock now may still be receiving data, so they are executed directly and never cached.
Default is `5m`: the cutoff is wall-clock relative, so points at or after `now - 5m` are read from storage directly, wherever the query window ends. | +| `promql_rollup_cache.ttl` | String | `30m` | How long a cached chunk is served, counted from the read that produced it. Nothing probes
the source, so this age is the cache's whole freshness rule: a write reaches a served chunk
within it, and a late write can stay invisible for that long.
Default is `30m`, which bounds how long a cached chunk is served, and therefore how stale a served answer may be. | ## Distributed Mode @@ -454,6 +460,12 @@ | `event_recorder` | -- | -- | Configuration options for the event recorder. | | `event_recorder.ttl` | String | `90d` | TTL for the events table that will be used to store the events. Default is `90d`. | | `event_recorder.event_types` | Array | All | Event types to record. Current available event type: `admin_function`.
When omitted, all current and future event types are recorded.
Set to an empty array to disable event recording. | +| `promql_rollup_cache` | -- | -- | The frontend-local cache of PromQL range-query chunks. It is disabled by default; enabling it does not change instant queries or expressions outside the window allowlist. | +| `promql_rollup_cache.enable` | Bool | `false` | Whether range queries may be served from the cache. | +| `promql_rollup_cache.max_bytes` | String | Auto | The total memory budget for cached chunks and their annotations.
Defaults to 1/128 of the host or pod memory limit, with a minimum of 32MiB and a maximum of 8GiB.
Uses 32MiB if memory detection is unavailable. | +| `promql_rollup_cache.chunk` | String | `5m` | The target chunk duration. It is global while the step belongs to the query, so planning
aligns it down to a whole number of the query's steps, floored at 20 steps: any step is
cacheable, the chunk of one step is one fixed length, and a coarse step is never cut into
one-point chunks. | +| `promql_rollup_cache.tail` | String | `5m` | Output points this close to wall-clock now may still be receiving data, so they are executed directly and never cached.
Default is `5m`: the cutoff is wall-clock relative, so points at or after `now - 5m` are read from storage directly, wherever the query window ends. | +| `promql_rollup_cache.ttl` | String | `30m` | How long a cached chunk is served, counted from the read that produced it. Nothing probes
the source, so this age is the cache's whole freshness rule: a write reaches a served chunk
within it, and a late write can stay invisible for that long.
Default is `30m`, which bounds how long a cached chunk is served, and therefore how stale a served answer may be. | ### Metasrv diff --git a/config/frontend.example.toml b/config/frontend.example.toml index a2a751e99b2..9e158a16d16 100644 --- a/config/frontend.example.toml +++ b/config/frontend.example.toml @@ -580,3 +580,26 @@ ttl = "90d" ## Set to an empty array to disable event recording. ## @toml2docs:none-default="All" #+ event_types = ["admin_function"] + +## The frontend-local cache of PromQL range-query chunks. It is disabled by default; enabling it does not change instant queries or expressions outside the window allowlist. +[promql_rollup_cache] +## Whether range queries may be served from the cache. +enable = false +## The total memory budget for cached chunks and their annotations. +## Defaults to 1/128 of the host or pod memory limit, with a minimum of 32MiB and a maximum of 8GiB. +## Uses 32MiB if memory detection is unavailable. +## @toml2docs:none-default="Auto" +#+ max_bytes = "256MiB" +## The target chunk duration. It is global while the step belongs to the query, so planning +## aligns it down to a whole number of the query's steps, floored at 20 steps: any step is +## cacheable, the chunk of one step is one fixed length, and a coarse step is never cut into +## one-point chunks. +chunk = "5m" +## Output points this close to wall-clock now may still be receiving data, so they are executed directly and never cached. +## Default is `5m`: the cutoff is wall-clock relative, so points at or after `now - 5m` are read from storage directly, wherever the query window ends. +tail = "5m" +## How long a cached chunk is served, counted from the read that produced it. Nothing probes +## the source, so this age is the cache's whole freshness rule: a write reaches a served chunk +## within it, and a late write can stay invisible for that long. +## Default is `30m`, which bounds how long a cached chunk is served, and therefore how stale a served answer may be. +ttl = "30m" diff --git a/config/standalone.example.toml b/config/standalone.example.toml index ba0e8b2d031..b3847b8fd0a 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -1226,3 +1226,26 @@ ttl = "90d" ## is set to "prof:true,prof_active:false". The official image adds this env variable. ## Default is true. enable_heap_profiling = true + +## The frontend-local cache of PromQL range-query chunks. It is disabled by default; enabling it does not change instant queries or expressions outside the window allowlist. +[promql_rollup_cache] +## Whether range queries may be served from the cache. +enable = false +## The total memory budget for cached chunks and their annotations. +## Defaults to 1/128 of the host or pod memory limit, with a minimum of 32MiB and a maximum of 8GiB. +## Uses 32MiB if memory detection is unavailable. +## @toml2docs:none-default="Auto" +#+ max_bytes = "256MiB" +## The target chunk duration. It is global while the step belongs to the query, so planning +## aligns it down to a whole number of the query's steps, floored at 20 steps: any step is +## cacheable, the chunk of one step is one fixed length, and a coarse step is never cut into +## one-point chunks. +chunk = "5m" +## Output points this close to wall-clock now may still be receiving data, so they are executed directly and never cached. +## Default is `5m`: the cutoff is wall-clock relative, so points at or after `now - 5m` are read from storage directly, wherever the query window ends. +tail = "5m" +## How long a cached chunk is served, counted from the read that produced it. Nothing probes +## the source, so this age is the cache's whole freshness rule: a write reaches a served chunk +## within it, and a late write can stay invisible for that long. +## Default is `30m`, which bounds how long a cached chunk is served, and therefore how stale a served answer may be. +ttl = "30m" diff --git a/src/frontend/Cargo.toml b/src/frontend/Cargo.toml index c8cdb454496..fcacf2c7fcf 100644 --- a/src/frontend/Cargo.toml +++ b/src/frontend/Cargo.toml @@ -65,6 +65,7 @@ otel-arrow-rust.workspace = true partition.workspace = true pipeline.workspace = true prometheus.workspace = true +promql.workspace = true promql-parser.workspace = true prost.workspace = true query.workspace = true diff --git a/src/frontend/src/error.rs b/src/frontend/src/error.rs index 923e6879f35..bfad651c494 100644 --- a/src/frontend/src/error.rs +++ b/src/frontend/src/error.rs @@ -337,6 +337,13 @@ pub enum Error { location: Location, }, + #[snafu(display("Invalid rollup cache config: {reason}"))] + InvalidPromqlRollupCacheConfig { + reason: String, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Invalid tls config"))] InvalidTlsConfig { #[snafu(source)] @@ -407,6 +414,7 @@ impl ErrorExt for Error { | Error::ColumnNoneDefaultValue { .. } | Error::IncompleteGrpcRequest { .. } | Error::InvalidTlsConfig { .. } + | Error::InvalidPromqlRollupCacheConfig { .. } | Error::InvalidWriteRetryConfig { .. } => StatusCode::InvalidArguments, Error::NotSupported { .. } => StatusCode::Unsupported, diff --git a/src/frontend/src/frontend.rs b/src/frontend/src/frontend.rs index af8b63c7b0d..78afd040a94 100644 --- a/src/frontend/src/frontend.rs +++ b/src/frontend/src/frontend.rs @@ -39,7 +39,8 @@ use crate::heartbeat::HeartbeatTask; use crate::instance::Instance; use crate::service_config::{ InfluxdbOptions, JaegerOptions, MysqlOptions, OpentsdbOptions, OtlpOptions, - PendingRowsBatcherOptions, PostgresOptions, PromStoreOptions, WriteRetryOptions, + PendingRowsBatcherOptions, PostgresOptions, PromStoreOptions, PromqlRollupCacheOptions, + WriteRetryOptions, }; /// Configures frontend protocols, query execution, and distributed write retries. @@ -104,6 +105,8 @@ pub struct FrontendOptions { pub pipeline: PipelineOptions, /// The event recorder options. pub event_recorder: EventRecorderOptions, + /// The frontend-local cache of PromQL range-query chunks. + pub promql_rollup_cache: PromqlRollupCacheOptions, /// Environment variable keys to read and report in heartbeat messages. pub heartbeat_env_vars: Vec, } @@ -140,6 +143,7 @@ impl Default for FrontendOptions { memory: MemoryOptions::default(), pipeline: PipelineOptions::default(), event_recorder: EventRecorderOptions::default(), + promql_rollup_cache: PromqlRollupCacheOptions::default(), heartbeat_env_vars: vec![], } } diff --git a/src/frontend/src/instance.rs b/src/frontend/src/instance.rs index 9d10591fba1..4aa73f35d73 100644 --- a/src/frontend/src/instance.rs +++ b/src/frontend/src/instance.rs @@ -29,6 +29,7 @@ mod opentsdb; mod otlp; pub mod prom_store; mod promql; +mod promql_rollup_cache; mod region_query; mod schema_selection; @@ -59,7 +60,7 @@ use common_meta::cache_invalidator::CacheInvalidatorRef; use common_meta::key::TableMetadataManagerRef; use common_meta::node_manager::NodeManagerRef; use common_meta::procedure_executor::ProcedureExecutorRef; -use common_query::Output; +use common_query::{Output, OutputMeta}; use common_recordbatch::RecordBatchStreamWrapper; use common_recordbatch::error::StreamTimeoutSnafu; use common_telemetry::logging::SlowQueryOptions; @@ -76,6 +77,7 @@ use operator::statement::{StatementExecutor, StatementExecutorRef}; use partition::manager::PartitionRuleManagerRef; use pipeline::pipeline_operator::PipelineOperator; use prometheus::HistogramTimer; +// The absolute path names the `promql` crate, not this module's `promql` submodule. use promql_parser::label::{METRIC_NAME, MatchOp, Matcher}; use promql_parser::util::{ExprVisitor, walk_expr}; use query::QueryEngineRef; @@ -84,7 +86,7 @@ use query::parser::{PromQuery, QueryStatement}; use query::query_engine::DescribeResult; use query::query_engine::options::{QueryOptions, validate_catalog_and_schema}; use servers::batcher::logical_table::LogicalTablePendingRowsBatcher; -use servers::error::{self as server_error, AuthSnafu, ExecuteQuerySnafu, UnexpectedResultSnafu}; +use servers::error::{self as server_error, AuthSnafu, ExecuteQuerySnafu}; use servers::interceptor::{ PromQueryInterceptor, PromQueryInterceptorRef, SqlQueryInterceptor, SqlQueryInterceptorRef, }; @@ -116,6 +118,7 @@ use crate::error::{ ExternalSnafu, InvalidSqlSnafu, ParseSqlSnafu, PermissionSnafu, PlanStatementSnafu, Result, SqlExecInterceptedSnafu, StatementTimeoutSnafu, TableOperationSnafu, }; +use crate::promql_query_cache::PromqlRollupCache; use crate::service_config::InfluxdbMergeMode; use crate::stream_wrapper::CancellableStreamWrapper; @@ -159,6 +162,13 @@ pub struct Instance { trace_aux_limiter: Option, otlp_resource_info: bool, suspend: Arc, + /// The frontend-local rollup cache of PromQL range queries, when one is + /// installed. + /// + /// Disabled by default. [`crate::frontend::FrontendOptions::promql_rollup_cache`] + /// installs it; a request that misses fills it itself, so nothing else has to run + /// for it to serve. + promql_rollup_cache: Option>, } impl Instance { @@ -237,6 +247,22 @@ impl Instance { self.statement_executor.procedure_executor() } + /// The rollup cache a range query may be served from, when one is installed. + pub fn promql_rollup_cache(&self) -> Option<&Arc> { + self.promql_rollup_cache.as_ref() + } + + /// Empties this frontend's local rollup cache. + /// + /// The cache is process-local. This does not affect other frontends, source + /// data, or in-flight queries; those either finish with their own plan or + /// refill the cache on their next read. + pub fn clear_promql_rollup_cache(&self) { + if let Some(cache) = self.promql_rollup_cache.as_ref() { + cache.clear(); + } + } + pub fn suspend_state(&self) -> Arc { self.suspend.clone() } @@ -1996,9 +2022,10 @@ impl PrometheusHandler for Instance { let requires_output_ordering = query.requires_output_ordering(); let (query, stmt) = query.into_parts(); - let QueryStatement::Promql(eval_stmt, _) = &stmt else { + let QueryStatement::Promql(eval_stmt, alias) = &stmt else { unreachable!("query is parsed from promql"); }; + let cached_alias = alias.clone(); let plan = self .statement_executor @@ -2015,16 +2042,10 @@ impl PrometheusHandler for Instance { interceptor.pre_execute(&query, &eval_stmt.expr, Some(&plan), query_ctx.clone())?; - // Take the EvalStmt from the original QueryStatement and use it to create the CatalogQueryStatement. - let query_statement = if let QueryStatement::Promql(eval_stmt, alias) = stmt { - CatalogQueryStatement::Promql(eval_stmt, alias) - } else { - // It should not happen since the query is already parsed successfully. - return UnexpectedResultSnafu { - reason: "The query should always be promql.".to_string(), - } - .fail(); - }; + // Take the EvalStmt from the original QueryStatement and use it to create the + // CatalogQueryStatement. It is copied rather than moved, because the statement + // passed the `let else` above and the range path may still read it below. + let query_statement = CatalogQueryStatement::Promql(eval_stmt.clone(), alias.clone()); let raw_query = query_statement.to_string(); let slow_query_timer = self.slow_query_options.enable.then(|| { @@ -2047,16 +2068,42 @@ impl PrometheusHandler for Instance { slow_query_timer, ); - let query_fut = self.statement_executor.exec_plan(plan, query_ctx.clone()); + // A range query over a whole evaluation grid is the one shape the rollup cache + // serves. It is consulted after authorization, after `pre_execute`, and under the + // same process-list ticket, so a cached answer passes exactly the checks an + // executed one does; anything the cache declines keeps the original plan below. + let cached = self + .cached_range_output( + &query, + eval_stmt, + cached_alias, + requires_output_ordering, + &plan, + &query_ctx, + ticket.cancellation_handle.clone(), + ) + .await?; - let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) - .await - .map_err(|_| servers::error::CancelledSnafu.build())? - .map_err(BoxedError::new) - .context(ExecuteQuerySnafu)?; - let output = map_query_output(output) - .map_err(BoxedError::new) - .context(ExecuteQuerySnafu)?; + let output = match cached { + Some(rows) => Output { + data: OutputData::RecordBatches(rows), + // Every row was read into memory above, so the merged answer carries no + // stretches of one plan to point at. + meta: OutputMeta::default(), + }, + None => { + let query_fut = self.statement_executor.exec_plan(plan, query_ctx.clone()); + + let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) + .await + .map_err(|_| servers::error::CancelledSnafu.build())? + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu)?; + map_query_output(output) + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu)? + } + }; let Output { meta, data } = output; let data = match data { OutputData::Stream(stream) => { @@ -2506,6 +2553,7 @@ mod tests { }; use catalog::process_manager::{ProcessManager, QueryStatement, SlowQueryTimer}; use common_base::Plugins; + use common_base::cancellation::CancellationHandle; use common_catalog::consts::DEFAULT_PRIVATE_SCHEMA_NAME; use common_error::ext::{BoxedError, ErrorExt, PlainError}; use common_error::status_code::StatusCode; @@ -2522,7 +2570,7 @@ mod tests { use common_query::prelude::greptime_value; use common_query::{Output, OutputMeta}; use common_recordbatch::{ - OrderOption, RecordBatch, RecordBatchStream, SendableRecordBatchStream, + OrderOption, RecordBatch, RecordBatchStream, RecordBatches, SendableRecordBatchStream, }; use common_telemetry::logging::SlowQueriesRecordType; use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef}; @@ -2536,6 +2584,7 @@ mod tests { VectorRef, }; use log_query::LogQuery; + use promql_parser::parser::EvalStmt; use prost::Message; use query::query_engine::options::QueryOptions; use servers::query_handler::{ @@ -2552,7 +2601,7 @@ mod tests { use store_api::storage::ScanRequest; use strfmt::Format; use table::metadata::{ - FilterPushDownType, TableInfo, TableInfoBuilder, TableMetaBuilder, TableType, + FilterPushDownType, TableId, TableInfo, TableInfoBuilder, TableMetaBuilder, TableType, }; use table::table_name::TableName; use table::test_util::{EmptyTable, MemTable}; @@ -2564,6 +2613,9 @@ mod tests { use crate::instance::builder::FrontendBuilder; use crate::instance::*; + /// The id the `cpu` metric table of [`metric_instance`] is registered under. + const CPU_TABLE_ID: TableId = 1024; + fn parse_test_sql(sql: &str) -> Vec { parse_stmt(sql, &GreptimeDbDialect {}).unwrap() } @@ -3411,6 +3463,504 @@ mod tests { Ok(EmptyTable::from_table_info(&table_info)) } + /// A metric table of one series whose rows are exactly `rows`. + /// + /// A PromQL range query reads a table through its time index and its value + /// columns, which a table's metadata names, so the fixture states both: the + /// `ts` column is the time index and `cpu` is the single value column. Every + /// scan sees the same rows, which is what makes a cached answer and an executed + /// one comparable. + fn test_metric_table_with_rows(rows: Vec<(i64, f64)>) -> TableRef { + let schema = Arc::new(GtSchema::new(vec![ + ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ) + .with_time_index(true), + ColumnSchema::new("cpu", ConcreteDataType::float64_datatype(), false), + ])); + let (timestamps, values): (Vec<_>, Vec<_>) = rows.into_iter().unzip(); + let recordbatch = RecordBatch::new( + schema.clone(), + vec![ + Arc::new(TimestampMillisecondVector::from_vec(timestamps)) as VectorRef, + Arc::new(Float64Vector::from_vec(values)) as VectorRef, + ], + ) + .unwrap(); + let table_meta = TableMetaBuilder::empty() + .schema(schema) + // No tag columns: the fixture is one series. + .primary_key_indices(vec![]) + .value_indices(vec![1]) + .next_column_id(1024) + .build() + .unwrap(); + let table_info = TableInfoBuilder::new("cpu", table_meta) + .table_id(1024) + .catalog_name("greptime") + .schema_name("public") + .build() + .unwrap(); + Arc::new(Table::new( + Arc::new(table_info), + FilterPushDownType::Unsupported, + Arc::new(StaticRowsDataSource { recordbatch }), + )) + } + + /// A data source that answers every scan with the same rows. + struct StaticRowsDataSource { + recordbatch: RecordBatch, + } + + impl StaticRowsDataSource { + /// The fixture has no storage error of its own, so a failure to lay its one + /// batch out is reported as the test bug it is. + fn boxed(error: impl std::fmt::Display) -> BoxedError { + BoxedError::new(PlainError::new(error.to_string(), StatusCode::Unexpected)) + } + } + + impl DataSource for StaticRowsDataSource { + fn get_stream( + &self, + request: ScanRequest, + ) -> std::result::Result { + let projected = match request.projection.as_deref() { + Some(indices) => self + .recordbatch + .df_record_batch() + .project(indices) + .map_err(Self::boxed)?, + None => self.recordbatch.df_record_batch().clone(), + }; + let schema = Arc::new(GtSchema::try_from(projected.schema()).map_err(Self::boxed)?); + let recordbatch = RecordBatch::from_df_record_batch(schema.clone(), projected); + Ok(RecordBatches::try_new(schema, vec![recordbatch]) + .map_err(Self::boxed)? + .as_stream()) + } + } + + /// Runs one PromQL request and returns the rows it answered with, in order. + async fn promql_rows( + instance: &Instance, + query: &PromQuery, + ctx: QueryContextRef, + ) -> TestResult { + let output = PrometheusHandler::do_query(instance, query, ctx) + .await + .with_context(|_| ExecutePromqlSnafu { + query: query.query.clone(), + }) + .with_context(|_| ExecuteSqlSnafu { + sql: query.query.clone(), + })?; + match output.data { + OutputData::RecordBatches(rows) => Ok(rows), + OutputData::Stream(stream) => RecordBatches::try_collect(stream) + .await + .context(CollectRecordbatchSnafu) + .with_context(|_| ExecuteSqlSnafu { + sql: query.query.clone(), + }), + OutputData::AffectedRows(_) => unreachable!("a PromQL query returns rows"), + } + } + + /// The rows of a result, in order, as one printed table. + /// + /// The spans of a chunked request read into several batches while a request that + /// executed its whole plan reads into one, so comparing batch by batch would + /// compare layouts rather than rows; one table prints the rows either way. + fn printed(rows: &RecordBatches) -> String { + rows.pretty_print().unwrap() + } + + /// How many rows a result holds. + /// + /// A test that compares two answers states with it that the answer they agree on is + /// not empty, which two empty answers would satisfy vacuously. + fn row_count(rows: &RecordBatches) -> usize { + rows.iter().map(|batch| batch.num_rows()).sum() + } + + /// A range cache configured with a five-minute chunk target, with no tail, so a + /// request over whole chunks is cacheable in a test that runs at wall-clock time. + /// + /// The target is below the twenty-step floor of a one-minute query, so the chunk + /// these tests plan with is twenty minutes wide, not five. + fn test_promql_rollup_cache() -> Arc { + let config = crate::promql_query_cache::PromqlRollupCacheConfig::new( + 1 << 20, + Duration::ZERO, + Duration::from_secs(300), + Duration::from_secs(3_600), + ) + .unwrap(); + Arc::new(crate::promql_query_cache::PromqlRollupCache::new(config)) + } + + /// One-minute steps from 10:00, with a gap between minutes 12 and 19: a + /// lookback of one minute leaves the points inside the gap without a sample. + fn metric_rows() -> Vec<(i64, f64)> { + const HEAD_MS: i64 = 36_000_000; + (0..60i64) + .filter(|minute| !(13..19).contains(minute)) + .map(|minute| (HEAD_MS + minute * 60_000, minute as f64)) + .collect() + } + + /// The range query `expr` asks for: 10:00 to 10:59, one-minute steps, a + /// one-minute lookback. + fn metric_range_query(expr: &str) -> PromQuery { + PromQuery { + query: expr.to_string(), + start: "36000".to_string(), + end: "39540".to_string(), + step: "60".to_string(), + lookback: "60".to_string(), + alias: None, + } + } + + /// An instance over [`test_metric_table_with_rows`], with `cache` installed + /// when one is given. + async fn metric_instance( + promql_rollup_cache: Option>, + ) -> TestResult { + let catalog_manager = catalog::memory::MemoryCatalogManager::new_with_table( + test_metric_table_with_rows(metric_rows()), + ); + test_instance_with_catalog_manager_and_cache( + catalog_manager, + test_table(1025, "target")?, + Plugins::default(), + None, + Arc::new(NoopProcedureExecutor), + promql_rollup_cache, + ) + .await + } + + #[test] + fn range_query_identity_uses_source_from_the_statement_across_sliding_windows() { + let mut query = metric_range_query("sum(rate(cpu[5m]))"); + let stmt = EvalStmt { + expr: promql_parser::parser::parse(&query.query).unwrap(), + start: std::time::UNIX_EPOCH + Duration::from_secs(36_000), + end: std::time::UNIX_EPOCH + Duration::from_secs(37_740), + interval: Duration::from_secs(60), + lookback_delta: Duration::from_secs(60), + }; + let context = test_query_ctx(1); + let plan = LogicalPlanBuilder::empty(false).build().unwrap(); + let first = + Instance::range_query_identity(&query, &stmt, None, &plan, &context, CPU_TABLE_ID) + .expect("the expression names one admitted table"); + assert_eq!(first.source_table, "cpu"); + assert_eq!(first.table_id, CPU_TABLE_ID); + + query.start = "36300".to_string(); + query.end = "38040".to_string(); + let mut sliding = stmt.clone(); + sliding.start += Duration::from_secs(300); + sliding.end += Duration::from_secs(300); + let second = + Instance::range_query_identity(&query, &sliding, None, &plan, &context, CPU_TABLE_ID) + .expect("the sliding expression names the same table"); + assert_eq!(first, second); + assert_eq!(second.source_table, "cpu"); + + // The statement expression, not the original query text, is authoritative. + sliding.expr = promql_parser::parser::parse("sum(rate(memory[5m]))").unwrap(); + let other = + Instance::range_query_identity(&query, &sliding, None, &plan, &context, CPU_TABLE_ID) + .expect("the statement names a table"); + assert_eq!(other.source_table, "memory"); + assert_ne!(first, other); + } + + #[test] + fn range_query_identity_bypasses_when_the_source_is_unknown() { + let context = test_query_ctx(1); + let plan = LogicalPlanBuilder::empty(false).build().unwrap(); + for text in ["cpu + memory", "avg(cpu)", "{host=\"a\"}"] { + let query = metric_range_query(text); + let stmt = EvalStmt { + expr: promql_parser::parser::parse(text).unwrap(), + start: std::time::UNIX_EPOCH, + end: std::time::UNIX_EPOCH + Duration::from_secs(300), + interval: Duration::from_secs(60), + lookback_delta: Duration::from_secs(60), + }; + assert!( + Instance::range_query_identity(&query, &stmt, None, &plan, &context, CPU_TABLE_ID) + .is_none(), + "{text}" + ); + } + } + + #[tokio::test] + async fn promql_rollup_cache_is_disabled_by_default() -> TestResult<()> { + let instance = metric_instance(None).await?; + + assert!(instance.promql_rollup_cache().is_none()); + + Ok(()) + } + + /// Runs the cached range path of `instance` the way a Prometheus range request + /// reaches it: the statement is planned exactly as the original path plans it, and + /// that plan is what the cache is consulted with. + /// + /// Answers the rows the cache served, or `None` when it declined and the original + /// plan has to run. The ordering flag is the one the HTTP and gRPC Prometheus + /// handlers mark: a request that demands execution order keeps its own plan. + async fn run_cached_range( + instance: &Instance, + query: &PromQuery, + ctx: QueryContextRef, + requires_output_ordering: bool, + ) -> TestResult> { + let parsed = ParsedPromQuery::parse(query.clone(), &ctx) + .expect("the test query is a parsable PromQL statement"); + let (query, statement) = parsed.into_parts(); + let query::parser::QueryStatement::Promql(eval_stmt, alias) = &statement else { + unreachable!("a PromQL query parses into a PromQL statement"); + }; + let plan = instance + .statement_executor() + .plan(&statement, ctx.clone()) + .await + .expect("the test statement plans"); + instance + .cached_range_output( + &query, + eval_stmt, + alias.clone(), + requires_output_ordering, + &plan, + &ctx, + Arc::new(CancellationHandle::default()), + ) + .await + .context(ExecutePromqlSnafu { + query: query.query.clone(), + }) + .with_context(|_| ExecuteSqlSnafu { + sql: query.query.clone(), + }) + } + + /// [`run_cached_range`] on a request the cache must serve. + async fn cached_rows(instance: &Instance, query: &PromQuery) -> TestResult { + Ok(run_cached_range(instance, query, test_query_ctx(1), false) + .await? + .expect("the cache served the request")) + } + + #[tokio::test] + async fn a_range_query_fills_the_cache_and_the_next_one_is_served() -> TestResult<()> { + let cached = metric_instance(Some(test_promql_rollup_cache())).await?; + let cache = cached.promql_rollup_cache().unwrap().clone(); + let plain = metric_instance(None).await?; + // A `rate` rather than a bare selector, which bypasses the cache before it is + // ever consulted. + let query = metric_range_query("rate(cpu[5m])"); + + let cold = cached_rows(&cached, &query).await?; + assert_eq!( + 3, + cache.entry_count(), + "sixty one-minute points are three twenty-step chunks" + ); + assert_eq!(0, cache.hit_count(), "the first request filled every chunk"); + let warm = cached_rows(&cached, &query).await?; + let uncached = promql_rows(&plain, &query, test_query_ctx(3)).await?; + + // The gap is in the answer: the points inside it have no pair of samples the + // `rate` can fold, so the range query holds fewer rows than the sixty grid + // points it evaluates, and more than none. + let rows = row_count(&cold); + assert!( + rows > 0 && rows < 60, + "the gap leaves points unanswered: {rows}" + ); + assert_eq!(printed(&uncached), printed(&cold)); + assert_eq!(printed(&uncached), printed(&warm)); + assert_eq!(3, cache.hit_count(), "the warm request served every chunk"); + Ok(()) + } + + #[tokio::test] + async fn every_bypass_reason_keeps_the_original_plan() -> TestResult<()> { + let cached = metric_instance(Some(test_promql_rollup_cache())).await?; + let cache = cached.promql_rollup_cache().unwrap().clone(); + let plain = metric_instance(None).await?; + let cacheable = metric_range_query("rate(cpu[5m])"); + + // One row per reason a range request keeps its own plan. `nocache` is the client's + // request and the rest are what the request carries, so each row states the flag + // and the context it needs and nothing else. + let nocache = QueryContextBuilder::default() + .set_extension( + session::hints::PROMQL_ROLLUP_CACHE_NOCACHE.to_string(), + "true".to_string(), + ) + .build(); + let mut instant = cacheable.clone(); + instant.start = "36300".to_string(); + instant.end = instant.start.clone(); + let snapshot = QueryContext::with_db_name(None); + snapshot.set_snapshot(1, 42); + let sst_bounded = QueryContextBuilder::default() + .sst_min_sequences(Arc::new(std::sync::RwLock::new(HashMap::from([(1, 90)])))) + .build(); + let flow = QueryContextBuilder::default() + .set_extension("flow.incremental_start".to_string(), "1".to_string()) + .build(); + + for (reason, query, ctx, ordering) in [ + ("nocache", &cacheable, Arc::new(nocache), false), + ("instant query", &instant, test_query_ctx(1), false), + ("output ordering", &cacheable, test_query_ctx(1), true), + ("snapshot", &cacheable, Arc::new(snapshot), false), + ("SST bound", &cacheable, Arc::new(sst_bounded), false), + ("flow bound", &cacheable, Arc::new(flow), false), + ] { + assert!( + run_cached_range(&cached, query, ctx.clone(), ordering) + .await? + .is_none(), + "{reason}: the cache must decline" + ); + // The request still answers what the ordinary path answers, and it fills + // nothing on the way. + let answer = promql_rows(&cached, query, ctx.clone()).await?; + let uncached = promql_rows(&plain, query, ctx).await?; + assert!( + row_count(&answer) > 0, + "{reason}: the answers compared are not empty" + ); + assert_eq!(printed(&uncached), printed(&answer), "{reason}"); + assert_eq!(0, cache.entry_count(), "{reason}: nothing may be filled"); + assert_eq!(0, cache.hit_count(), "{reason}: nothing may be served"); + } + Ok(()) + } + + #[tokio::test] + async fn a_schema_override_range_query_bypasses_the_promql_rollup_cache() -> TestResult<()> { + let cached = metric_instance(Some(test_promql_rollup_cache())).await?; + let cache = cached.promql_rollup_cache().unwrap().clone(); + let plain = metric_instance(None).await?; + + // `__schema__` makes the planner read another schema, and the cache key only + // names the current one. The expression is a `rate` around a named selector, so + // what bypasses is the override leaving the window allowlist rather than the + // bare-selector heuristic. + let overridden = metric_range_query(r#"rate(cpu{__schema__="public"}[5m])"#); + let answer = promql_rows(&cached, &overridden, test_query_ctx(1)).await?; + let uncached = promql_rows(&plain, &overridden, test_query_ctx(2)).await?; + assert!(row_count(&answer) > 0, "the answers compared are not empty"); + assert_eq!(printed(&uncached), printed(&answer)); + assert!( + run_cached_range(&cached, &overridden, test_query_ctx(3), false) + .await? + .is_none(), + "a schema override is never planned into chunks" + ); + assert_eq!(0, cache.entry_count(), "schema override fills nothing"); + Ok(()) + } + + #[tokio::test] + async fn a_bare_selector_range_query_bypasses_the_promql_rollup_cache() -> TestResult<()> { + // A bare selector is scan- and serialize-dominated, so a chunk served from memory + // costs a copy and a merge of the cached payload (and the fill pays for both) on + // top of a read that was already cheap: the cached path measured ~23% slower in a + // local benchmark on a 2048-series selector. Such a request therefore keeps its + // original plan and fills nothing. Parentheses only group, so they do not make a + // selector cacheable again. + let cached = metric_instance(Some(test_promql_rollup_cache())).await?; + let cache = cached.promql_rollup_cache().unwrap().clone(); + let plain = metric_instance(None).await?; + + for expr in ["cpu", "((cpu))"] { + let query = metric_range_query(expr); + let cold = promql_rows(&cached, &query, test_query_ctx(1)).await?; + let repeated = promql_rows(&cached, &query, test_query_ctx(2)).await?; + let uncached = promql_rows(&plain, &query, test_query_ctx(3)).await?; + + assert_eq!(printed(&uncached), printed(&cold), "{expr}"); + assert_eq!(printed(&uncached), printed(&repeated), "{expr}"); + assert!( + row_count(&cold) > 0, + "{expr}: the answers compared are not empty" + ); + assert!( + run_cached_range(&cached, &query, test_query_ctx(4), false) + .await? + .is_none(), + "{expr}: a bare selector keeps its own plan" + ); + } + assert_eq!(0, cache.entry_count(), "a bare selector fills nothing"); + assert_eq!(0, cache.hit_count(), "a bare selector is never served"); + + Ok(()) + } + + #[tokio::test] + async fn the_annotations_of_a_merged_answer_are_replayed_once() { + // The response path reads the collector the request opened, so everything the + // chunked execution recorded has to be replayed into it — once, however many + // spans recorded the same message. + let query_ctx = Arc::new(QueryContext::with("greptime", "public")); + let annotations = crate::promql_query_cache::CachedAnnotations::new( + vec![ + "b-warning".to_string(), + "a-warning".to_string(), + "a-warning".to_string(), + ], + vec!["an-info".to_string()], + ); + + // The response path holds the collector across the call, which is what keeps + // the registry entry alive for the replay to write into. + let collector = common_query::promql_annotations::promql_annotation_collector( + query_ctx.remote_query_id().unwrap(), + ); + Instance::record_annotations(&query_ctx, &annotations); + Instance::record_annotations(&query_ctx, &annotations); + + let (mut warnings, mut infos) = (Vec::new(), Vec::new()); + collector.append_to(&mut warnings, &mut infos); + assert_eq!( + vec!["a-warning".to_string(), "b-warning".to_string()], + warnings + ); + assert_eq!(vec!["an-info".to_string()], infos); + + // The replay is per request: another request's collector is untouched, and a + // request with nothing to report writes nothing. + let other = Arc::new(QueryContext::with("greptime", "public")); + let other_collector = common_query::promql_annotations::promql_annotation_collector( + other.remote_query_id().unwrap(), + ); + Instance::record_annotations( + &other, + &crate::promql_query_cache::CachedAnnotations::default(), + ); + let (mut other_warnings, mut other_infos) = (Vec::new(), Vec::new()); + other_collector.append_to(&mut other_warnings, &mut other_infos); + assert!(other_warnings.is_empty() && other_infos.is_empty()); + } + fn test_metric_names_table() -> TableRef { let schema = Arc::new(GtSchema::new(vec![ ColumnSchema::new("table_catalog", ConcreteDataType::string_datatype(), false), @@ -3749,6 +4299,27 @@ mod tests { plugins: Plugins, metric_names_table: Option, procedure_executor: ProcedureExecutorRef, + ) -> TestResult { + test_instance_with_catalog_manager_and_cache( + catalog_manager, + target_table, + plugins, + metric_names_table, + procedure_executor, + None, + ) + .await + } + + /// [`test_instance_with_catalog_manager`] with the rollup cache the PromQL range + /// path serves from, when a test installs one. + async fn test_instance_with_catalog_manager_and_cache( + catalog_manager: Arc, + target_table: TableRef, + plugins: Plugins, + metric_names_table: Option, + procedure_executor: ProcedureExecutorRef, + promql_rollup_cache: Option>, ) -> TestResult { let kv_backend = Arc::new(MemoryKvBackend::new()); let process_manager = Arc::new(ProcessManager::new("test-frontend".to_string(), None)); @@ -3786,7 +4357,7 @@ mod tests { let cache_registry = test_cache_registry(kv_backend.clone())?; - FrontendBuilder::new( + let builder = FrontendBuilder::new( FrontendOptions::default(), kv_backend, cache_registry, @@ -3795,10 +4366,12 @@ mod tests { procedure_executor, process_manager, ) - .with_plugin(plugins) - .try_build() - .await - .context(BuildFrontendSnafu) + .with_plugin(plugins); + let builder = match promql_rollup_cache { + Some(cache) => builder.with_promql_rollup_cache(cache), + None => builder, + }; + builder.try_build().await.context(BuildFrontendSnafu) } async fn execute_one_sql( diff --git a/src/frontend/src/instance/builder.rs b/src/frontend/src/instance/builder.rs index 5ae71b173f8..3753fa7c301 100644 --- a/src/frontend/src/instance/builder.rs +++ b/src/frontend/src/instance/builder.rs @@ -33,6 +33,7 @@ use common_meta::key::flow::FlowMetadataManager; use common_meta::kv_backend::KvBackendRef; use common_meta::node_manager::NodeManagerRef; use common_meta::procedure_executor::ProcedureExecutorRef; +use common_telemetry::info; use operator::batcher::PendingRowsBatcher; use operator::delete::Deleter; use operator::flow::FlowServiceOperator; @@ -57,13 +58,16 @@ use servers::batcher::{BatchingProtocol, pending_rows_batch_sync_enabled}; use servers::request_memory_limiter::ServerMemoryLimiter; use snafu::{OptionExt, ResultExt}; -use crate::error::{self, DataFusionSnafu, ExternalSnafu, Result}; +use crate::error::{ + self, DataFusionSnafu, ExternalSnafu, InvalidPromqlRollupCacheConfigSnafu, Result, +}; use crate::events::EventHandlerImpl; use crate::frontend::FrontendOptions; use crate::instance::Instance; use crate::instance::entity_graph::EntityGraphProviderImpl; use crate::instance::otlp::TraceAuxCache; use crate::instance::region_query::FrontendRegionQueryHandler; +use crate::promql_query_cache::PromqlRollupCache; use crate::service_config::BatcherOptions; /// The frontend [`Instance`] builder. @@ -78,6 +82,7 @@ pub struct FrontendBuilder { procedure_executor: ProcedureExecutorRef, process_manager: ProcessManagerRef, local_file_access: LocalFileAccess, + promql_rollup_cache: Option>, } impl FrontendBuilder { @@ -105,9 +110,19 @@ impl FrontendBuilder { procedure_executor, process_manager, local_file_access: LocalFileAccess::Disabled, + promql_rollup_cache: None, } } + /// Installs the frontend-local rollup cache of PromQL range queries. + /// + /// [`crate::frontend::FrontendOptions::promql_rollup_cache`] builds one when it is enabled; + /// this seam is for an embedder that already holds one, which today is a test. + pub fn with_promql_rollup_cache(mut self, promql_rollup_cache: Arc) -> Self { + self.promql_rollup_cache = Some(promql_rollup_cache); + self + } + #[cfg(test)] pub(crate) fn new_test( options: &FrontendOptions, @@ -433,6 +448,27 @@ impl FrontendBuilder { None }; + let promql_rollup_cache = match self.promql_rollup_cache { + Some(cache) => Some(cache), + None if self.options.promql_rollup_cache.enable => { + let config = self.options.promql_rollup_cache.config().map_err(|error| { + InvalidPromqlRollupCacheConfigSnafu { + reason: error.to_string(), + } + .build() + })?; + info!( + max_bytes = config.max_bytes(), + chunk = ?config.chunk(), + tail = ?config.tail(), + ttl = ?config.ttl(), + "PromQL rollup cache enabled" + ); + Some(Arc::new(PromqlRollupCache::new(config))) + } + None => None, + }; + Ok(Instance { server_memory_limiter, logical_batcher: Default::default(), @@ -458,6 +494,7 @@ impl FrontendBuilder { trace_aux_limiter, otlp_resource_info: self.options.otlp.experimental_enable_resource_info, suspend: Arc::new(AtomicBool::new(false)), + promql_rollup_cache, }) } } diff --git a/src/frontend/src/instance/promql_rollup_cache.rs b/src/frontend/src/instance/promql_rollup_cache.rs new file mode 100644 index 00000000000..79d4132b82d --- /dev/null +++ b/src/frontend/src/instance/promql_rollup_cache.rs @@ -0,0 +1,1666 @@ +// 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. + +//! Cache-aware execution of one PromQL range query. +//! +//! [`PromqlRollupCache::plan`] splits the statement into canonical chunks and direct +//! spans. A hit serves the stored rows; a miss executes the chunk's subwindow +//! ([`windowed_eval_stmt`]), reads it to the end, and inserts it; a direct span (the +//! partial chunks at either edge and the tail) is executed and never inserted. There +//! is no single-flight: concurrent misses on one chunk each execute it. +//! +//! Annotations are recorded per window read, not per chunk: a run of consecutive misses +//! is one read, so every chunk of the run carries that read's warnings and infos +//! ([`CachedAnnotations`]). A hit replays the messages of the read behind it, which may +//! mention points outside the chunk it serves. +//! +//! [`windowed_eval_stmt`]: query::promql::window::windowed_eval_stmt + +use std::sync::Arc; +use std::time::SystemTime; + +use async_trait::async_trait; +use client::OutputData; +use common_base::cancellation::{CancellableFuture, CancellationHandle}; +use common_error::ext::BoxedError; +use common_query::promql_annotations::{PromqlAnnotationCollector, promql_annotation_collector}; +use common_recordbatch::{RecordBatch, RecordBatches}; +use common_time::timestamp::TimeUnit; +use datafusion::logical_expr::LogicalPlan; +use datatypes::arrow::datatypes::DataType as ArrowDataType; +use datatypes::schema::{Schema, SchemaRef}; +use promql_parser::parser::EvalStmt; +use query::parser::{PromQuery, QueryStatement}; +use query::promql::planner::plan_is_native; +use query::promql::window::{WindowGrid, windowed_eval_stmt, windowed_source_table}; +use servers::error::{self as server_error, ExecuteQuerySnafu, UnexpectedResultSnafu}; +use session::context::{QueryContextRef, REMOTE_QUERY_ID_EXTENSION_KEY, generate_remote_query_id}; +use snafu::ResultExt; +use table::metadata::TableId; + +use crate::instance::{Instance, map_query_output}; +use crate::promql_query_cache::{ + CachedAnnotations, ChunkPlan, DirectSpan, Lookup, PlanSchema, PromqlRollupCache, QueryIdentity, + QueryRoute, TimeChunk, TimeChunkKey, +}; + +impl Instance { + /// Serves a PromQL range query from the rollup cache, or returns `None` to run the + /// original plan. Every bypass below is decided before any span executes. + #[allow(clippy::too_many_arguments)] + pub(crate) async fn cached_range_output( + &self, + query: &PromQuery, + eval_stmt: &EvalStmt, + alias: Option, + requires_output_ordering: bool, + plan: &LogicalPlan, + query_ctx: &QueryContextRef, + cancellation_handle: Arc, + ) -> server_error::Result> { + let Some(cache) = self.promql_rollup_cache.as_ref() else { + return Ok(None); + }; + if rollup_cache_bypassed(query_ctx) { + return Ok(None); + } + // An instant query is one point, and the cache keys whole chunks of a grid. + if eval_stmt.start == eval_stmt.end { + return Ok(None); + } + // The cached path concatenates the spans of one request in time order, so it + // answers an unordered result only. A request that demands ordered rows keeps + // its own plan, which is the only one that knows the global ordering. + if requires_output_ordering { + return Ok(None); + } + // A snapshot or Flow incremental bound changes which rows a read may see. + // The cache key does not encode either bound, so such a request must never + // hit or fill the ordinary entries. + if !query_ctx.snapshots().is_empty() + || !query_ctx.sst_min_sequences().is_empty() + || query_ctx + .extensions() + .keys() + .any(|key| key.starts_with("flow.")) + { + return Ok(None); + } + // Checked before the identity, so a bare selector never fills and never hits. + if Self::windowed_expr_is_bare_selector(&eval_stmt.expr) { + return Ok(None); + } + // The identity keys the request on the id the source table name resolves to + // now, not on the name alone: a table created again under a dropped table's + // name is another table, and its chunks must not answer this one's requests. + let Some(table_id) = self + .promql_rollup_source_table_id(eval_stmt, query_ctx) + .await + else { + return Ok(None); + }; + let Some(identity) = + Self::range_query_identity(query, eval_stmt, alias.clone(), plan, query_ctx, table_id) + else { + return Ok(None); + }; + let executor = StatementWindowExecutor { + instance: self, + query_ctx: query_ctx.clone(), + alias, + cancellation_handle, + }; + match execute_range(&executor, cache, identity, eval_stmt, SystemTime::now()).await? { + RangeOutcome::Merged { rows, annotations } => { + Self::record_annotations(query_ctx, &annotations); + Ok(Some(rows)) + } + RangeOutcome::Bypassed => Ok(None), + } + } + + /// Reports the merged answer's warnings and infos the way the request's response + /// reads them. + /// + /// The HTTP and gRPC front-ends open a collector for the request before calling + /// in and report it afterwards, so replaying here is what makes a message of a + /// chunk served from memory (or of a window read under its own collector) show + /// up in the response. The collector deduplicates, so replaying the same message + /// twice reports it once. A request without a collector has nobody to report to + /// and is left alone. + pub(crate) fn record_annotations(query_ctx: &QueryContextRef, annotations: &CachedAnnotations) { + if annotations.is_empty() { + return; + } + let Some(query_id) = query_ctx.remote_query_id() else { + return; + }; + let collector = promql_annotation_collector(query_id); + for warning in annotations.warnings() { + collector.record_warning(warning.clone()); + } + for info in annotations.infos() { + collector.record_info(info.clone()); + } + } + + /// Whether `expr` is a bare top-level selector, however it is parenthesised. + /// + /// Such a statement would be served by the cache, but it would be slower that way: a + /// selector over many series is dominated by the scan and by serializing the rows, so a + /// chunk served from memory trades that for a copy and a merge of the cached payload + /// (and the fill pays for both), which measured ~23% slower in a local benchmark on a + /// 2048-series selector. The window shapes the cache does help — `sum(rate(x[5m]))` + /// and `rate(x[5m])` — separate the scan from the answer enough for the reuse to win, + /// and keep the cached path. + /// + /// The bypass is a cache decision only: the statement is as valid as any other + /// windowable one and runs its original plan, it just does not use the cache. + fn windowed_expr_is_bare_selector(expr: &promql_parser::parser::Expr) -> bool { + use promql_parser::parser::Expr; + + match expr { + Expr::Paren(paren) => Self::windowed_expr_is_bare_selector(&paren.expr), + Expr::VectorSelector(_) => true, + _ => false, + } + } + + /// The id of the table the statement's named source resolves to. + /// + /// The identity keys chunks on it, so it is read from the catalog rather than + /// taken from the name: a table dropped and created again under the same name has + /// another id, and that is what tells its chunks apart from the old ones. + /// + /// [`None`] when the expression names no admitted table or the name resolves to + /// nothing this context can read: a request whose table cannot be identified keeps + /// its original plan, since its chunks could not be told apart from another + /// table's either. + async fn promql_rollup_source_table_id( + &self, + eval_stmt: &EvalStmt, + query_ctx: &QueryContextRef, + ) -> Option { + let source_table = windowed_source_table(&eval_stmt.expr).ok()?; + self.catalog_manager + .table_id( + query_ctx.current_catalog(), + &query_ctx.current_schema(), + source_table, + Some(query_ctx.as_ref()), + ) + .await + .ok()? + } + + /// The reusable half of this request, or [`None`] when the expression has no + /// admitted source table or a dimension does not fit the identity's integer fields, + /// because a narrowed value would key the same span under a different grid. + /// + /// `table_id` is the id [`Instance::promql_rollup_source_table_id`] resolved the + /// statement's source table to; the caller resolves it, because the name alone + /// does not identify the table. + pub(crate) fn range_query_identity( + query: &PromQuery, + eval_stmt: &EvalStmt, + alias: Option, + plan: &LogicalPlan, + query_ctx: &QueryContextRef, + table_id: TableId, + ) -> Option { + Some(QueryIdentity { + tenant: query_ctx.current_user().username().to_string(), + catalog: query_ctx.current_catalog().to_string(), + schema: query_ctx.current_schema(), + query: query.query.clone(), + source_table: windowed_source_table(&eval_stmt.expr).ok()?.to_string(), + table_id, + step_ms: i64::try_from(eval_stmt.interval.as_millis()).ok()?, + lookback_ms: i64::try_from(eval_stmt.lookback_delta.as_millis()).ok()?, + route: plan_route(plan), + output_schema: PlanSchema::of(plan.schema().as_arrow()), + alias, + read_preference: Some(query_ctx.read_preference().to_string()), + }) + } +} + +/// Whether the request asked for this one query to skip the cache. +/// +/// The hint is a flag, so a bare (empty) value means "set" as much as the spellings of +/// true do: `true`, any case of it, and `1`. A value of `false` or `0` leaves the cache +/// on; the hint channel can carry those, while the Prometheus HTTP parameter parsing only +/// ever stores `true`. +fn rollup_cache_bypassed(query_ctx: &QueryContextRef) -> bool { + query_ctx + .extension(session::hints::PROMQL_ROLLUP_CACHE_NOCACHE) + .is_some_and(|value| value.is_empty() || value == "1" || value.eq_ignore_ascii_case("true")) +} + +/// The planner that evaluated `plan`, which every cache key records. +/// +/// Both routes evaluate the same expression on the same grid but build different +/// plans and different row layouts, so a chunk of one must never answer the other. +fn plan_route(plan: &LogicalPlan) -> QueryRoute { + if plan_is_native(plan) { + QueryRoute::Native + } else { + QueryRoute::Legacy + } +} + +/// Executes the subwindows of one range query through the statement executor. +/// +/// A subwindow is planned and executed exactly as the request itself would be, so +/// route selection, planning, and execution behave the same; the request's +/// cancellation handle covers every window, and the caller's interceptors and +/// process-list entry stay around the whole call. +struct StatementWindowExecutor<'a> { + instance: &'a Instance, + query_ctx: QueryContextRef, + alias: Option, + cancellation_handle: Arc, +} + +impl StatementWindowExecutor<'_> { + /// The context the window is planned and executed under, and the collector its + /// annotations land in. + /// + /// The request's collector is shared by every span of the request, so a reading + /// of it cannot say which chunk recorded which message. A window therefore runs + /// under a remote query id of its own: the planner looks the collector up by that + /// id, so what the window records is attributable to it, and the caller replays + /// it into the request's collector afterwards. Every window gets one, whether or + /// not the request opened a collector, so a chunk filled by a request that + /// reports nothing still carries what its read recorded for the requests that do. + /// + /// The context is a copy of the request's: extensions are not shared by a clone, so + /// the window's id stays its own. The snapshot and SST-bound maps *are* shared, and + /// are empty here because a request that carries either bypasses the cache before + /// this point. + fn window_context(&self) -> (QueryContextRef, Option) { + let query_id = generate_remote_query_id(); + let collector = promql_annotation_collector(&query_id); + let mut query_ctx = (*self.query_ctx).clone(); + query_ctx.set_extension(REMOTE_QUERY_ID_EXTENSION_KEY, query_id); + (Arc::new(query_ctx), Some(collector)) + } +} + +#[async_trait] +impl WindowExecutor for StatementWindowExecutor<'_> { + async fn execute_window(&self, eval_stmt: EvalStmt) -> server_error::Result { + let (query_ctx, collector) = self.window_context(); + let statement = QueryStatement::Promql(eval_stmt, self.alias.clone()); + let plan = self + .instance + .statement_executor + .plan(&statement, query_ctx.clone()) + .await + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu)?; + // The cached path answers an unordered result only, and its spans are + // concatenated in time order, which the sort would only undo. + let plan = crate::instance::promql::remove_output_sort(plan); + let output = CancellableFuture::new( + self.instance.statement_executor.exec_plan(plan, query_ctx), + self.cancellation_handle.clone(), + ) + .await + .map_err(|_| server_error::CancelledSnafu.build())? + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu)?; + let output = map_query_output(output) + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu)?; + let rows = match output.data { + OutputData::RecordBatches(batches) => batches, + OutputData::Stream(stream) => { + // The plan future is cancellable, but consuming its stream is where + // most of a range query's work happens. Keep the collect future under + // the same handle, so cancellation drops the stream and stops the + // read rather than only its planning. + CancellableFuture::new( + RecordBatches::try_collect(stream), + self.cancellation_handle.clone(), + ) + .await + .map_err(|_| server_error::CancelledSnafu.build())? + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu)? + } + OutputData::AffectedRows(_) => { + return Err(UnexpectedResultSnafu { + reason: "a PromQL range query answered with affected rows".to_string(), + } + .build()); + } + }; + let mut warnings = Vec::new(); + let mut infos = Vec::new(); + if let Some(collector) = &collector { + collector.append_to(&mut warnings, &mut infos); + } + Ok(WindowOutput { + rows, + annotations: CachedAnnotations::new(warnings, infos), + }) + } +} + +/// Executes one PromQL evaluation subwindow. +#[async_trait] +pub(crate) trait WindowExecutor: Send + Sync { + /// Executes one PromQL evaluation subwindow and returns its rows fully consumed, so a + /// fill never inserts a result it did not read to the end. + async fn execute_window(&self, stmt: EvalStmt) -> server_error::Result; +} + +/// What one evaluation window produced. +#[derive(Debug)] +pub(crate) struct WindowOutput { + /// Every row the window read. + pub rows: RecordBatches, + /// The PromQL annotations the window's read recorded. + pub annotations: CachedAnnotations, +} + +/// What a cache-aware range execution produced. +#[derive(Debug)] +pub(crate) enum RangeOutcome { + /// The merged answer of every span of the statement. + Merged { + rows: RecordBatches, + /// What the served and executed spans recorded. + annotations: CachedAnnotations, + }, + /// Nothing was executed; the caller runs its original plan. + /// + /// One bypass is found after the first span: spans that disagree on their schema say + /// an ALTER landed under the plan, and the request still runs that plan. + Bypassed, +} + +/// Executes `stmt`, serving its chunks from `cache` and executing only the spans the +/// plan says must be read. `now` places the tail. +pub(crate) async fn execute_range( + executor: &E, + cache: &PromqlRollupCache, + identity: QueryIdentity, + stmt: &EvalStmt, + now: SystemTime, +) -> server_error::Result +where + E: WindowExecutor + ?Sized, +{ + let planned = match cache.plan(identity, stmt, now) { + ChunkPlan::Bypass(_) => return Ok(RangeOutcome::Bypassed), + ChunkPlan::Planned(planned) => planned, + }; + if planned.chunks().is_empty() { + // Everything would be read directly: splitting it would change nothing. + return Ok(RangeOutcome::Bypassed); + } + let grid = WindowGrid::of(stmt).map_err(|error| { + UnexpectedResultSnafu { + reason: format!("the statement planned into chunks has no evaluation grid: {error}"), + } + .build() + })?; + + // A lookup is local, so resolving every span first is what tells the misses that are + // adjacent apart from the hits between them. + let steps = resolve(cache, planned.chunks(), planned.direct()); + let mut merged = MergedRows::default(); + let mut warnings = Vec::new(); + let mut infos = Vec::new(); + let mut next = 0; + while next < steps.len() { + let annotations = match &steps[next] { + Step::Hit { + payload, + annotations, + } => { + let rows = clone_rows(payload)?; + next += 1; + if !merged.push(rows) { + return Ok(RangeOutcome::Bypassed); + } + annotations.clone() + } + Step::Direct(direct) => { + let window = execute_span(executor, stmt, &grid, direct.span()).await?; + next += 1; + if !merged.push(window.rows) { + return Ok(RangeOutcome::Bypassed); + } + Arc::new(window.annotations) + } + Step::Miss(_) => { + // Consecutive misses are one region of the coverage, so one window answers + // all of them: a cold request pays one planning and one scan for the run + // rather than one of each per chunk. + let mut keys = Vec::new(); + while let Some(Step::Miss(key)) = steps.get(next) { + keys.push(*key); + next += 1; + } + let Some(annotations) = + fill_misses(executor, cache, &keys, stmt, &grid, &mut merged).await? + else { + return Ok(RangeOutcome::Bypassed); + }; + annotations + } + }; + warnings.extend(annotations.warnings().iter().cloned()); + infos.extend(annotations.infos().iter().cloned()); + } + merged.finish(CachedAnnotations::new(warnings, infos)) +} + +/// One span of the plan, resolved against the cache before anything is executed. +#[derive(Debug)] +enum Step<'a> { + /// A chunk that is resident: its rows and messages are served as they are. + Hit { + payload: Arc, + annotations: Arc, + }, + /// A chunk that is not resident: it is read and, if the read joins the result, + /// stored. + Miss(&'a TimeChunkKey), + /// A span that must be read and must never be stored. + Direct(&'a DirectSpan), +} + +/// Every span of the plan in time order, each resolved to what serving it takes. +fn resolve<'a>( + cache: &PromqlRollupCache, + chunks: &'a [TimeChunkKey], + direct: &'a [DirectSpan], +) -> Vec> { + ascending_spans(chunks, direct) + .into_iter() + .map(|span| match span { + Span::Chunk(key) => match cache.lookup(key) { + Lookup::Hit { + payload, + annotations, + } => Step::Hit { + payload, + annotations, + }, + Lookup::Miss(_) => Step::Miss(key), + }, + Span::Direct(direct) => Step::Direct(direct), + }) + .collect() +} + +/// Reads the consecutive chunks of `keys` as one window, stores what each of them read, +/// and adds their rows to `merged`. +/// +/// The chunks of `keys` are adjacent, so one execution covers them all and the rows it +/// returned are split back into the chunks they belong to: a chunk is the unit a lookup +/// serves, so it is also the unit a fill stores. A chunk the window answered no row for is +/// stored too, as the empty answer it is: the window was read to the end, so its emptiness +/// is complete and re-reading it would repeat a read that already said so. Answers [`None`] +/// when the rows do not join the result, in which case nothing was stored. +/// +/// Annotations belong to the read, not to the chunk: one window answered the whole run, so +/// every chunk of it stores the same [`CachedAnnotations`] and a hit of any one of them +/// replays what that read said, including messages about points outside the chunk served. +async fn fill_misses( + executor: &E, + cache: &PromqlRollupCache, + keys: &[&TimeChunkKey], + stmt: &EvalStmt, + grid: &WindowGrid, + merged: &mut MergedRows, +) -> server_error::Result>> +where + E: WindowExecutor + ?Sized, +{ + let chunks = keys.iter().map(|key| key.chunk()).collect::>(); + let window = match (chunks.first(), chunks.last()) { + (Some(first), Some(last)) => { + execute_span( + executor, + stmt, + grid, + TimeChunk::new(first.start_ms(), last.end_ms()), + ) + .await? + } + // `keys` is the run of misses the caller found, so it is never empty. + _ => return Ok(None), + }; + let parts = split_window(window.rows, &chunks)?; + // A chunk's payload is taken before its rows join the merge, which consumes them; it + // is stored only once the whole run joined it, so a schema that changed under the plan + // stores nothing. + let payloads = parts + .iter() + .map(clone_rows) + .collect::>>()?; + for rows in parts { + if !merged.push(rows) { + return Ok(None); + } + } + let annotations = Arc::new(window.annotations); + for (key, payload) in keys.iter().zip(payloads) { + cache.insert(key, Arc::new(payload), annotations.clone()); + } + Ok(Some(annotations)) +} + +/// The rows of one executed window, split into the rows of each chunk of `chunks`. +/// +/// The chunks are consecutive, so a row's timestamp alone says which of them it belongs +/// to and a window cannot produce a point outside them. The window's row order is +/// preserved within every chunk, so merging the chunks in order keeps the whole result's +/// order. A chunk the window produced no row for comes back empty. +fn split_window( + rows: RecordBatches, + chunks: &[TimeChunk], +) -> server_error::Result> { + let schema = rows.schema(); + let mut parts = chunks.iter().map(|_| Vec::new()).collect::>(); + for batch in rows.take() { + if batch.num_rows() == 0 { + continue; + } + let column = timestamp_column(&batch)?; + let mut first = 0; + let mut current = chunk_of(chunks, timestamp_ms(&batch, column, 0)?)?; + for row in 1..batch.num_rows() { + let index = chunk_of(chunks, timestamp_ms(&batch, column, row)?)?; + if index != current { + parts[current].push(slice_batch(&batch, first, row - first)?); + first = row; + current = index; + } + } + parts[current].push(slice_batch(&batch, first, batch.num_rows() - first)?); + } + parts + .into_iter() + .map(|batches| { + let batches = match own_batch(&schema, batches)? { + Some(batch) => vec![batch], + None => Vec::new(), + }; + RecordBatches::try_new(schema.clone(), batches) + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu) + }) + .collect() +} + +/// The rows of one chunk as a batch of its own, or [`None`] when it holds no rows. +/// +/// A slice shares the buffers of the batch it was cut from, and `buffer_memory_size` reports +/// those buffers whole: a chunk cut from a window's batch would be charged the whole batch, +/// and the batch would stay alive as long as any chunk holds a slice of it. Concatenating +/// copies exactly the rows the chunk holds, so its weight is its own size and evicting it +/// frees what it was charged. +fn own_batch( + schema: &SchemaRef, + batches: Vec, +) -> server_error::Result> { + if batches.is_empty() { + return Ok(None); + } + // `concat` answers a lone input with a slice of itself, so the empty batch is what makes + // a chunk cut from a single batch take the copying path. + let empty = RecordBatch::new_empty(schema.clone()); + let owned = datatypes::arrow::compute::concat_batches( + schema.arrow_schema(), + std::iter::once(empty.df_record_batch()) + .chain(batches.iter().map(|batch| batch.df_record_batch())), + ) + .map_err(|error| { + UnexpectedResultSnafu { + reason: format!("a chunk's rows cannot be copied into a batch of their own: {error}"), + } + .build() + })?; + Ok(Some(RecordBatch::from_df_record_batch( + schema.clone(), + owned, + ))) +} + +/// `count` rows of `batch`, starting at `first`. +fn slice_batch( + batch: &RecordBatch, + first: usize, + count: usize, +) -> server_error::Result { + batch + .slice(first, count) + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu) +} + +/// The index of the column a window's rows are timestamped by. +/// +/// The timestamp is the first timestamp-typed column, which is how a PromQL result +/// carries its evaluation grid whatever the column prefix is configured to. +fn timestamp_column(batch: &RecordBatch) -> server_error::Result { + (0..batch.num_columns()) + .find(|index| { + matches!( + batch.column(*index).data_type(), + ArrowDataType::Timestamp(_, _) + ) + }) + .ok_or_else(|| { + UnexpectedResultSnafu { + reason: "a PromQL range result holds no timestamp column".to_string(), + } + .build() + }) +} + +/// The millisecond instant of row `row` in the timestamp `column` of `batch`. +fn timestamp_ms(batch: &RecordBatch, column: usize, row: usize) -> server_error::Result { + let array = batch.column(column); + if array.is_null(row) { + return Err(UnexpectedResultSnafu { + reason: "a PromQL range result holds a row without a timestamp".to_string(), + } + .build()); + } + datatypes::arrow_array::timestamp_array_value(array, row) + .convert_to(TimeUnit::Millisecond) + .map(|timestamp| timestamp.value()) + .ok_or_else(|| { + UnexpectedResultSnafu { + reason: "a row's timestamp does not fit milliseconds".to_string(), + } + .build() + }) +} + +/// The index of the chunk of `chunks` that holds `ms`. +/// +/// The chunks are consecutive and were cut from the statement's grid, so a point outside +/// them is an internal inconsistency rather than a caller error. +fn chunk_of(chunks: &[TimeChunk], ms: i64) -> server_error::Result { + let index = chunks.partition_point(|chunk| chunk.end_ms() <= ms); + match chunks.get(index) { + Some(chunk) if chunk.start_ms() <= ms => Ok(index), + _ => Err(UnexpectedResultSnafu { + reason: format!("a window read the point {ms}, which no chunk of its run covers"), + } + .build()), + } +} + +/// A copy of `rows`, which the cache hands out by shared reference. +/// +/// The batches themselves are reference counted, so a copy shares their buffers; only +/// the list of batches is new, which is what keeps a cached payload immutable while a +/// result of its own is merged with the spans around it. +fn clone_rows(rows: &RecordBatches) -> server_error::Result { + RecordBatches::try_new(rows.schema(), rows.iter().cloned().collect()) + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu) +} + +/// Executes the subwindow covering `span`, which the plan cut from `stmt`'s grid. +async fn execute_span( + executor: &E, + stmt: &EvalStmt, + grid: &WindowGrid, + span: TimeChunk, +) -> server_error::Result +where + E: WindowExecutor + ?Sized, +{ + let first = grid_index(grid, span.start_ms())?; + let last = grid_index(grid, span.end_ms())?; + let window = windowed_eval_stmt(stmt, first, last).map_err(|error| { + UnexpectedResultSnafu { + reason: format!("the planned span {span:?} is not an evaluation window: {error}"), + } + .build() + })?; + executor.execute_window(window).await +} + +/// The index of the grid point at `ms`. +/// +/// Planning only cuts spans on grid points, so a bound that is not one is an +/// internal inconsistency rather than a caller error. +fn grid_index(grid: &WindowGrid, ms: i64) -> server_error::Result { + let offset = i128::from(ms) - i128::from(grid.start_ms()); + let step = i128::from(grid.step_ms()); + if offset < 0 || offset % step != 0 { + return Err(UnexpectedResultSnafu { + reason: format!("{ms} is not a point of the evaluation grid"), + } + .build()); + } + usize::try_from(offset / step).map_err(|error| { + UnexpectedResultSnafu { + reason: format!("the evaluation grid index of {ms} overflows: {error}"), + } + .build() + }) +} + +/// One span of the statement, in the order the result must hold its rows. +#[derive(Debug, Clone, Copy)] +enum Span<'a> { + /// A cacheable chunk: served from memory or filled. + Chunk(&'a TimeChunkKey), + /// A span that must be read and must not be cached. + Direct(&'a DirectSpan), +} + +/// The chunks and direct spans of a plan, interleaved in increasing time. +fn ascending_spans<'a>(chunks: &'a [TimeChunkKey], direct: &'a [DirectSpan]) -> Vec> { + let mut spans = Vec::with_capacity(chunks.len() + direct.len()); + let (mut next_chunk, mut next_direct) = (0, 0); + while next_chunk < chunks.len() || next_direct < direct.len() { + let take_chunk = match (chunks.get(next_chunk), direct.get(next_direct)) { + (Some(chunk), Some(span)) => chunk.chunk().start_ms() <= span.span().start_ms(), + (Some(_), None) => true, + (None, Some(_)) => false, + (None, None) => break, + }; + if take_chunk { + spans.push(Span::Chunk(&chunks[next_chunk])); + next_chunk += 1; + } else { + spans.push(Span::Direct(&direct[next_direct])); + next_direct += 1; + } + } + spans +} + +/// The rows of every span of one statement, concatenated under one schema. +#[derive(Default)] +struct MergedRows { + schema: Option, + rows: Vec, +} + +impl MergedRows { + /// Appends one span's rows, reporting whether they joined the result. + /// + /// A span whose schema differs from the result's cannot be concatenated with the + /// spans around it, so the caller fails the request instead of reporting an answer + /// no plan produced. + fn push(&mut self, rows: RecordBatches) -> bool { + let schema = rows.schema(); + match &self.schema { + Some(expected) if expected.arrow_schema() != schema.arrow_schema() => return false, + Some(_) => {} + None => self.schema = Some(schema), + } + self.rows.extend(rows.take()); + true + } + + /// The merged result: the spans' rows in time order, or the schema alone when + /// every span was empty, together with everything the spans recorded. + fn finish(self, annotations: CachedAnnotations) -> server_error::Result { + let schema = self.schema.unwrap_or_else(|| Arc::new(Schema::new(vec![]))); + let rows = RecordBatches::try_new(schema, self.rows) + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu)?; + Ok(RangeOutcome::Merged { rows, annotations }) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::{Duration, UNIX_EPOCH}; + + use common_recordbatch::RecordBatch; + use datatypes::prelude::ConcreteDataType; + use datatypes::schema::{ColumnSchema, Schema}; + use datatypes::vectors::{Int64Vector, StringVector, TimestampMillisecondVector, VectorRef}; + use promql_parser::parser::parse; + + use datatypes::arrow::array::Int64Array; + use datatypes::arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema}; + + use super::*; + use crate::promql_query_cache::{PromqlRollupCacheConfig, QueryRoute}; + + /// One minute, the step every test statement evaluates on. + const STEP_MS: i64 = 60_000; + /// The fewest steps one chunk holds, and the width every test plans with. + const CHUNK_STEPS: usize = 20; + /// The twenty-step chunk the tests plan with. + const CHUNK_MS: i64 = CHUNK_STEPS as i64 * STEP_MS; + /// The five-minute chunk target the tests configure: shorter than the floor, so the + /// floor decides the width. + const CHUNK_TARGET: Duration = Duration::from_secs(300); + /// A five-minute-aligned instant, standing in for 10:00. + const HEAD_MS: i64 = 36_000_000; + /// The ttl every test configures. + const TTL: Duration = Duration::from_secs(3_600); + /// The id the table every test reads resolves to. + const CPU_TABLE_ID: u32 = 1024; + + fn at(ms: i64) -> SystemTime { + UNIX_EPOCH + Duration::from_millis(ms.unsigned_abs()) + } + + /// The millisecond instant `time` names. + fn millis(time: SystemTime) -> i64 { + query::promql::label_values::signed_millis_since_epoch(time).unwrap() + } + + /// A statement from `start_ms` over `points` grid points, stepping `step_ms`. + fn range_stmt(expr: &str, start_ms: i64, points: u64, step_ms: i64) -> EvalStmt { + EvalStmt { + expr: parse(expr).expect("the expression parses"), + start: at(start_ms), + end: at(start_ms + (points as i64 - 1) * step_ms), + interval: Duration::from_millis(step_ms.unsigned_abs()), + lookback_delta: Duration::from_secs(300), + } + } + + /// The output schema [`rows_of`] answers under. + fn plan_schema() -> PlanSchema { + PlanSchema::of(&ArrowSchema::new(vec![Field::new( + "point", + ArrowDataType::Int64, + false, + )])) + } + + fn identity(query: &str) -> QueryIdentity { + QueryIdentity { + tenant: "greptime".to_string(), + catalog: "greptime".to_string(), + schema: "public".to_string(), + query: query.to_string(), + // Every test query reads cpu; a test that wants another series set states + // it in the query text. + source_table: "cpu".to_string(), + table_id: CPU_TABLE_ID, + step_ms: STEP_MS, + lookback_ms: 300_000, + route: QueryRoute::Legacy, + output_schema: plan_schema(), + alias: None, + read_preference: None, + } + } + + /// A cache whose tail is empty, so every point of a historical statement is + /// cacheable, and whose chunk is five steps of a one-minute grid. + fn test_cache() -> PromqlRollupCache { + let config = PromqlRollupCacheConfig::new(1 << 20, Duration::ZERO, CHUNK_TARGET, TTL) + .expect("the test configuration is valid"); + PromqlRollupCache::new(config) + } + + /// The points of `stmt`'s evaluation grid, in order. + fn grid_points(stmt: &EvalStmt) -> Vec { + let grid = WindowGrid::of(stmt).expect("a window is on a grid"); + (0..grid.points()) + .map(|index| grid.point_ms(index).expect("the point fits")) + .collect() + } + + /// One row per point of `points`, stamped with the point and holding it as an integer + /// as well. + fn rows_at(points: &[i64]) -> RecordBatches { + let schema = Arc::new(Schema::new(vec![ + ColumnSchema::new( + "greptime_timestamp", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + ColumnSchema::new("point", ConcreteDataType::int64_datatype(), false), + ])); + let columns: Vec = vec![ + Arc::new(TimestampMillisecondVector::from_vec(points.to_vec())), + Arc::new(Int64Vector::from_vec(points.to_vec())), + ]; + RecordBatches::try_new( + schema.clone(), + vec![RecordBatch::new(schema, columns).unwrap()], + ) + .unwrap() + } + + /// One row per grid point of `stmt`. + fn rows_of(stmt: &EvalStmt) -> RecordBatches { + rows_at(&grid_points(stmt)) + } + + /// One row per grid point of `stmt`, under the schema another table version produces: + /// the same two columns and one the ALTER added. + fn rows_with_another_schema(stmt: &EvalStmt) -> RecordBatches { + let points = grid_points(stmt); + let schema = Arc::new(Schema::new(vec![ + ColumnSchema::new( + "greptime_timestamp", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + ColumnSchema::new("point", ConcreteDataType::int64_datatype(), false), + ColumnSchema::new("extra", ConcreteDataType::int64_datatype(), false), + ])); + let columns: Vec = vec![ + Arc::new(TimestampMillisecondVector::from_vec(points.clone())), + Arc::new(Int64Vector::from_vec(points.clone())), + Arc::new(Int64Vector::from_vec(points)), + ]; + RecordBatches::try_new( + schema.clone(), + vec![RecordBatch::new(schema, columns).unwrap()], + ) + .unwrap() + } + + /// The length of the label [`wide_rows`] writes into every row. + const WIDE_LABEL_BYTES: usize = 256; + + /// One row per grid point of `stmt` in one batch, under a label column wide enough + /// that a chunk's share of the batch dwarfs what an entry's key and overhead add. + fn wide_rows(stmt: &EvalStmt) -> RecordBatches { + let points = grid_points(stmt); + let labels = vec!["x".repeat(WIDE_LABEL_BYTES); points.len()]; + let schema = Arc::new(Schema::new(vec![ + ColumnSchema::new( + "greptime_timestamp", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + ColumnSchema::new("label", ConcreteDataType::string_datatype(), false), + ])); + let columns: Vec = vec![ + Arc::new(TimestampMillisecondVector::from_vec(points)), + Arc::new(StringVector::from(labels)), + ]; + RecordBatches::try_new( + schema.clone(), + vec![RecordBatch::new(schema, columns).unwrap()], + ) + .unwrap() + } + + /// Every point a result holds, in row order. + fn points(result: &RecordBatches) -> Vec { + let mut points = Vec::new(); + for batch in result.iter() { + let column = batch + .column_by_name("point") + .expect("the result holds the point column") + .as_any() + .downcast_ref::() + .expect("the point column is an integer column"); + points.extend(column.values().iter().copied()); + } + points + } + + /// An executor that records the windows it was asked to plan and execute. + #[derive(Default)] + struct RecordingExecutor { + windows: Mutex>, + /// The zero-based call at which the executor fails, when one is set. + fail_at: Option, + /// The warning every window the executor runs records. + warns: Option, + } + + impl RecordingExecutor { + fn failing_at(call: usize) -> Self { + Self { + fail_at: Some(call), + ..Default::default() + } + } + + /// An executor whose every window records `warning`, as a range function + /// over a mixed float/native-histogram window does. + fn warning(warning: &str) -> Self { + Self { + warns: Some(warning.to_string()), + ..Default::default() + } + } + + /// The windows executed so far, as `(start_ms, end_ms)` pairs. + fn windows(&self) -> Vec<(i64, i64)> { + self.windows.lock().unwrap().clone() + } + } + + #[async_trait] + impl WindowExecutor for RecordingExecutor { + async fn execute_window(&self, stmt: EvalStmt) -> server_error::Result { + let call = { + let mut windows = self.windows.lock().unwrap(); + windows.push((millis(stmt.start), millis(stmt.end))); + windows.len() - 1 + }; + if self.fail_at == Some(call) { + return Err(UnexpectedResultSnafu { + reason: format!("the executor was asked to fail on call {call}"), + } + .build()); + } + let annotations = match &self.warns { + Some(warning) => CachedAnnotations::new(vec![warning.clone()], vec![]), + None => CachedAnnotations::default(), + }; + Ok(WindowOutput { + rows: rows_of(&stmt), + annotations, + }) + } + } + + /// An executor that fails the test if it is asked to execute anything: a warm + /// chunk must never reach it. + struct ForbiddenExecutor; + + #[async_trait] + impl WindowExecutor for ForbiddenExecutor { + async fn execute_window(&self, stmt: EvalStmt) -> server_error::Result { + panic!( + "a warm chunk was planned and executed: [{}, {}]", + millis(stmt.start), + millis(stmt.end) + ); + } + } + + /// An executor that answers every window with the one wide batch of [`wide_rows`], + /// so a chunk is always a slice of a batch larger than itself. + struct WideBatchExecutor; + + #[async_trait] + impl WindowExecutor for WideBatchExecutor { + async fn execute_window(&self, stmt: EvalStmt) -> server_error::Result { + Ok(WindowOutput { + rows: wide_rows(&stmt), + annotations: CachedAnnotations::default(), + }) + } + } + + /// An executor that answers every point of its window but no row for the points of the + /// second of the three chunks the tests' statements cover. + struct EmptyMiddleChunkExecutor; + + #[async_trait] + impl WindowExecutor for EmptyMiddleChunkExecutor { + async fn execute_window(&self, stmt: EvalStmt) -> server_error::Result { + let points = grid_points(&stmt) + .into_iter() + .filter(|ms| !(HEAD_MS + CHUNK_MS..HEAD_MS + 2 * CHUNK_MS).contains(ms)) + .collect::>(); + Ok(WindowOutput { + rows: rows_at(&points), + annotations: CachedAnnotations::default(), + }) + } + } + + /// An executor that answers its later windows under another schema, as a table + /// altered under a running statement does. + #[derive(Default)] + struct SchemaChangingExecutor { + windows: AtomicUsize, + } + + #[async_trait] + impl WindowExecutor for SchemaChangingExecutor { + async fn execute_window(&self, stmt: EvalStmt) -> server_error::Result { + let rows = if self.windows.fetch_add(1, Ordering::AcqRel) == 0 { + rows_of(&stmt) + } else { + rows_with_another_schema(&stmt) + }; + Ok(WindowOutput { + rows, + annotations: CachedAnnotations::default(), + }) + } + } + + async fn run( + executor: &E, + cache: &PromqlRollupCache, + stmt: &EvalStmt, + query: &str, + ) -> server_error::Result { + // The wall clock is the real one and the tail is empty, so every point of a + // historical statement is cacheable, and an entry is younger than the ttl + // unless a test says otherwise. + execute_range(executor, cache, identity(query), stmt, SystemTime::now()).await + } + + fn merged(outcome: RangeOutcome) -> RecordBatches { + match outcome { + RangeOutcome::Merged { rows, .. } => rows, + RangeOutcome::Bypassed => panic!("the statement was expected to be chunked"), + } + } + + fn recorded(outcome: &RangeOutcome) -> CachedAnnotations { + match outcome { + RangeOutcome::Merged { annotations, .. } => annotations.clone(), + RangeOutcome::Bypassed => panic!("the statement was expected to be chunked"), + } + } + + #[tokio::test] + async fn a_cold_plan_reads_every_consecutive_miss_as_one_window() { + let cache = test_cache(); + // Sixty points are exactly three twenty-step chunks: no partial chunk at either + // end, so the cold request is all misses. + let stmt = range_stmt("cpu", HEAD_MS, 60, STEP_MS); + let cold = RecordingExecutor::default(); + + let cold_rows = merged(run(&cold, &cache, &stmt, "cpu").await.unwrap()); + + assert_eq!( + vec![(HEAD_MS, HEAD_MS + 3 * CHUNK_MS - STEP_MS)], + cold.windows(), + "the three missed chunks are executed as one window" + ); + assert_eq!(3, cache.entry_count(), "each chunk is stored on its own"); + assert_eq!( + 0, + cache.hit_count(), + "nothing was served, so the request was cold" + ); + + // The warm request executes nothing at all: every chunk it asked for is resident. + let warm = RecordingExecutor::default(); + let warm_rows = merged(run(&warm, &cache, &stmt, "cpu").await.unwrap()); + assert!( + warm.windows().is_empty(), + "a warm request executes no window: {:?}", + warm.windows() + ); + assert_eq!(3, cache.hit_count(), "all three chunks were served"); + assert_eq!(points(&cold_rows), points(&warm_rows)); + } + + #[tokio::test] + async fn a_hit_reuses_the_payload_of_the_chunk_it_serves() { + let cache = test_cache(); + let stmt = range_stmt("cpu", HEAD_MS, 40, STEP_MS); + let cold = RecordingExecutor::default(); + let cold_rows = merged(run(&cold, &cache, &stmt, "cpu").await.unwrap()); + + // The same request one chunk later shares the second chunk only, which is + // what a sliding dashboard does. + let sliding = range_stmt("cpu", HEAD_MS + CHUNK_MS, 40, STEP_MS); + let sliding_executor = RecordingExecutor::default(); + let slid = merged( + run(&sliding_executor, &cache, &sliding, "cpu") + .await + .unwrap(), + ); + + assert_eq!( + vec![(HEAD_MS + 2 * CHUNK_MS, HEAD_MS + 3 * CHUNK_MS - STEP_MS)], + sliding_executor.windows(), + "only the chunk that was not cached reaches the executor" + ); + let expected = (0..40) + .map(|index| HEAD_MS + index * STEP_MS) + .collect::>(); + assert_eq!(expected, points(&cold_rows)); + assert_eq!( + expected + .iter() + .cloned() + .skip(CHUNK_STEPS) + .chain((40..60).map(|index| HEAD_MS + index * STEP_MS)) + .collect::>(), + points(&slid) + ); + assert_eq!(1, cache.hit_count(), "one chunk was served"); + assert_eq!(3, cache.entry_count(), "the third chunk was filled"); + } + + #[tokio::test] + async fn a_split_chunk_is_charged_for_its_own_rows_not_the_window_batch() { + let cache = test_cache(); + // Forty points are two whole chunks, and the window answers both out of one + // batch: every chunk is a slice of the same buffers. + let stmt = range_stmt("cpu", HEAD_MS, 40, STEP_MS); + let window_bytes = u64::try_from( + wide_rows(&stmt) + .iter() + .map(|batch| batch.buffer_memory_size()) + .sum::(), + ) + .unwrap(); + + merged(run(&WideBatchExecutor, &cache, &stmt, "cpu").await.unwrap()); + + assert_eq!(2, cache.entry_count()); + assert!( + cache.byte_count() < 2 * window_bytes, + "a chunk is charged its own rows, not the batch it was cut from: {} bytes \ + charged for one {window_bytes}-byte window", + cache.byte_count() + ); + } + + #[tokio::test] + async fn a_direct_span_is_executed_but_not_inserted() { + let cache = test_cache(); + // Forty-two points: two whole chunks and a two-point edge that may not be + // keyed as a chunk. + let stmt = range_stmt("cpu", HEAD_MS, 42, STEP_MS); + let executor = RecordingExecutor::default(); + + let rows = merged(run(&executor, &cache, &stmt, "cpu").await.unwrap()); + + assert_eq!( + vec![ + (HEAD_MS, HEAD_MS + 2 * CHUNK_MS - STEP_MS), + (HEAD_MS + 2 * CHUNK_MS, HEAD_MS + 2 * CHUNK_MS + STEP_MS), + ], + executor.windows(), + "the two missed chunks are one window and the edge span another" + ); + assert_eq!(2, cache.entry_count(), "the edge span is not an entry"); + // The merged rows are in time order and hold every point once. + assert_eq!( + (0..42) + .map(|index| HEAD_MS + index * STEP_MS) + .collect::>(), + points(&rows) + ); + } + + #[tokio::test] + async fn the_tail_is_executed_directly_on_every_request() { + let cache = test_cache(); + let stmt = range_stmt("cpu", HEAD_MS, 40, STEP_MS); + // The wall clock sits on a chunk boundary inside the coverage, so the last + // points are in the tail and may not be cached however often they are asked + // for. Forty points are two chunks; the tail starts where the second one does, so + // only the first is cacheable. + let now = at(HEAD_MS + CHUNK_MS); + let expected = (0..40) + .map(|index| HEAD_MS + index * STEP_MS) + .collect::>(); + let mut readings = Vec::new(); + for _ in 0..2 { + let executor = RecordingExecutor::default(); + let rows = merged( + execute_range(&executor, &cache, identity("cpu"), &stmt, now) + .await + .unwrap(), + ); + assert_eq!(expected, points(&rows)); + readings.push(executor.windows()); + } + assert_eq!( + vec![ + vec![ + (HEAD_MS, HEAD_MS + CHUNK_MS - STEP_MS), + (HEAD_MS + CHUNK_MS, HEAD_MS + 39 * STEP_MS), + ], + // The second request is served the chunk and reads only the tail. + vec![(HEAD_MS + CHUNK_MS, HEAD_MS + 39 * STEP_MS)], + ], + readings, + "the cacheable chunk is read once and the tail on every request" + ); + // The first chunk was filled once and served the second time; the tail is + // never an entry. + assert_eq!(1, cache.entry_count()); + assert_eq!(1, cache.hit_count()); + } + + #[tokio::test] + async fn contiguous_direct_spans_are_read_as_one_window() { + let cache = test_cache(); + // Forty points are two whole chunks, and the cutoff sits five points into the + // second one: its edge and its tail are contiguous, so they are one span and one + // read rather than two that meet. + let stmt = range_stmt("cpu", HEAD_MS, 40, STEP_MS); + let now = at(HEAD_MS + CHUNK_MS + 5 * STEP_MS); + let ChunkPlan::Planned(planned) = cache.plan(identity("cpu"), &stmt, now) else { + panic!("the statement is planned into chunks"); + }; + assert_eq!( + vec![TimeChunk::new(HEAD_MS + CHUNK_MS, HEAD_MS + 40 * STEP_MS)], + planned + .direct() + .iter() + .map(|span| span.span()) + .collect::>(), + "the edge and the tail of the last region are one span" + ); + + let executor = RecordingExecutor::default(); + merged( + execute_range(&executor, &cache, identity("cpu"), &stmt, now) + .await + .unwrap(), + ); + assert_eq!( + vec![ + (HEAD_MS, HEAD_MS + CHUNK_MS - STEP_MS), + (HEAD_MS + CHUNK_MS, HEAD_MS + 39 * STEP_MS), + ], + executor.windows(), + "one window for the chunk and one for the whole direct span" + ); + } + + #[tokio::test] + async fn a_failed_fill_publishes_no_rows_and_inserts_no_partial_chunk() { + let cache = test_cache(); + let stmt = range_stmt("cpu", HEAD_MS, 40, STEP_MS); + // The first span fails, so nothing was consumed and nothing may be offered + // as a result or as an entry. + let failing = RecordingExecutor::failing_at(0); + assert!(run(&failing, &cache, &stmt, "cpu").await.is_err()); + assert_eq!(0, cache.entry_count()); + + // Forty-two points are the two chunks and a two-point edge, so the edge is a window + // of its own: failing it leaves the answer an error rather than the first window, + // and the chunks that were read to the end stay as the complete entries they are. + let cache = test_cache(); + let edged = range_stmt("cpu", HEAD_MS, 42, STEP_MS); + let failing = RecordingExecutor::failing_at(1); + assert!(run(&failing, &cache, &edged, "cpu").await.is_err()); + assert_eq!(2, cache.entry_count()); + } + + #[tokio::test] + async fn a_schema_change_between_two_spans_bypasses_the_cache() { + let cache = test_cache(); + // Forty-two points: two whole chunks and a two-point edge, so the chunks and the + // edge are two windows and the ALTER can land between them. + let stmt = range_stmt("cpu", HEAD_MS, 42, STEP_MS); + // The second window is read after the table's schema changed, so its rows cannot + // be concatenated with the first's: the request runs its original plan instead of + // answering with a merge no plan produced. + let executor = SchemaChangingExecutor::default(); + assert!( + matches!( + run(&executor, &cache, &stmt, "cpu").await.unwrap(), + RangeOutcome::Bypassed + ), + "a span of another schema bypasses the cache instead of merging" + ); + } + + #[tokio::test] + async fn a_statement_outside_the_allowlist_bypasses_the_cache() { + let cache = test_cache(); + // `avg` is not the one aggregate the window allowlist admits. + let stmt = range_stmt("avg(cpu)", HEAD_MS, 10, STEP_MS); + + assert!(matches!( + run(&ForbiddenExecutor, &cache, &stmt, "avg(cpu)") + .await + .unwrap(), + RangeOutcome::Bypassed + )); + assert_eq!(0, cache.entry_count()); + } + + #[tokio::test] + async fn a_coverage_without_a_cacheable_chunk_bypasses_the_cache() { + let cache = test_cache(); + // Nineteen points are shorter than one chunk, so every point is an edge span. + let stmt = range_stmt("cpu", HEAD_MS, 19, STEP_MS); + + assert!(matches!( + run(&ForbiddenExecutor, &cache, &stmt, "cpu").await.unwrap(), + RangeOutcome::Bypassed + )); + assert_eq!(0, cache.entry_count()); + } + + #[tokio::test] + async fn a_request_of_another_identity_is_not_served() { + let cache = test_cache(); + let stmt = range_stmt("cpu", HEAD_MS, 40, STEP_MS); + merged( + run(&RecordingExecutor::default(), &cache, &stmt, "cpu") + .await + .unwrap(), + ); + assert_eq!(2, cache.entry_count()); + + // The same series set on another step keys its chunks as spans of another + // grid, so the chunks of this one cannot answer it. + let stepped = range_stmt("cpu", HEAD_MS, 40, 2 * STEP_MS); + let mut stepped_identity = identity("cpu"); + stepped_identity.step_ms = 2 * STEP_MS; + let executor = RecordingExecutor::default(); + merged( + execute_range( + &executor, + &cache, + stepped_identity, + &stepped, + SystemTime::now(), + ) + .await + .unwrap(), + ); + assert!(!executor.windows().is_empty(), "the other grid was read"); + assert_eq!(0, cache.hit_count(), "nothing was served across grids"); + + // A query that selects other series is another identity as well. + let other = range_stmt("cpu{code=\"500\"}", HEAD_MS, 40, STEP_MS); + let executor = RecordingExecutor::default(); + merged( + run(&executor, &cache, &other, "cpu{code=\"500\"}") + .await + .unwrap(), + ); + assert_eq!( + 1, + executor.windows().len(), + "the other series were read once" + ); + assert_eq!(0, cache.hit_count()); + } + + #[tokio::test] + async fn a_hit_reports_the_annotations_of_the_read_it_serves() { + let cache = test_cache(); + let stmt = range_stmt("cpu", HEAD_MS, 40, STEP_MS); + let cold = + RecordingExecutor::warning("encountered a mix of float and native histogram samples"); + + // The fill records the warning; the request that filled reports it once. + let filled = run(&cold, &cache, &stmt, "cpu").await.unwrap(); + assert_eq!( + vec!["encountered a mix of float and native histogram samples".to_string()], + recorded(&filled).warnings() + ); + + // The warm request executes nothing and still reports the warning of the + // read it is served, exactly once. + let warm = run(&ForbiddenExecutor, &cache, &stmt, "cpu").await.unwrap(); + assert_eq!( + vec!["encountered a mix of float and native histogram samples".to_string()], + recorded(&warm).warnings() + ); + assert!(recorded(&warm).infos().is_empty()); + assert_eq!(points(&merged(filled)), points(&merged(warm))); + } + + #[tokio::test] + async fn a_chunk_hit_replays_the_annotations_of_the_read_that_filled_it() { + let cache = test_cache(); + // Forty points are one run of two missed chunks, so one read filled both and + // recorded its warning once. + let stmt = range_stmt("cpu", HEAD_MS, 40, STEP_MS); + let cold = + RecordingExecutor::warning("encountered a mix of float and native histogram samples"); + merged(run(&cold, &cache, &stmt, "cpu").await.unwrap()); + assert_eq!(2, cache.entry_count()); + + // A request for the second chunk alone is served that chunk, and with it the + // messages of the read that filled the run it belonged to: annotations belong to + // the read, which covered points of both chunks. + let second = range_stmt("cpu", HEAD_MS + CHUNK_MS, CHUNK_STEPS as u64, STEP_MS); + let warm = run(&ForbiddenExecutor, &cache, &second, "cpu") + .await + .unwrap(); + assert_eq!( + vec!["encountered a mix of float and native histogram samples".to_string()], + recorded(&warm).warnings(), + "the chunk replays the read that filled it, not its own attribution" + ); + assert_eq!(1, cache.hit_count()); + } + + #[tokio::test] + async fn a_direct_span_records_annotations_without_being_inserted() { + let cache = test_cache(); + // Forty-two points: two whole chunks and a two-point edge that may not be keyed + // as a chunk. + let stmt = range_stmt("cpu", HEAD_MS, 42, STEP_MS); + let executor = RecordingExecutor::warning("the edge span warned"); + + let cold = run(&executor, &cache, &stmt, "cpu").await.unwrap(); + assert_eq!(2, cache.entry_count(), "the edge span is not an entry"); + assert_eq!( + vec!["the edge span warned".to_string()], + recorded(&cold).warnings(), + "the three spans recorded one message between them" + ); + + // The warm request reads only the edge span again, and still reports the + // message once rather than once per span. + let warm = run( + &RecordingExecutor::warning("the edge span warned"), + &cache, + &stmt, + "cpu", + ) + .await + .unwrap(); + assert_eq!( + vec!["the edge span warned".to_string()], + recorded(&warm).warnings() + ); + } + + #[tokio::test] + async fn an_empty_chunk_is_stored_as_the_complete_answer_it_is() { + let cache = test_cache(); + // Sixty points are three whole chunks, and the read answers nothing for the middle + // one: it was still read to the end, so its emptiness is the answer. + let stmt = range_stmt("cpu", HEAD_MS, 60, STEP_MS); + let expected = (0..60) + .map(|index| HEAD_MS + index * STEP_MS) + .filter(|ms| !(HEAD_MS + CHUNK_MS..HEAD_MS + 2 * CHUNK_MS).contains(ms)) + .collect::>(); + + let cold = merged( + run(&EmptyMiddleChunkExecutor, &cache, &stmt, "cpu") + .await + .unwrap(), + ); + assert_eq!(expected, points(&cold)); + assert_eq!( + 3, + cache.entry_count(), + "the chunk that read no rows is an entry too" + ); + + // The warm request executes nothing at all, the empty chunk included. + let warm = merged(run(&ForbiddenExecutor, &cache, &stmt, "cpu").await.unwrap()); + assert_eq!(expected, points(&warm)); + assert_eq!(3, cache.hit_count(), "all three chunks were served"); + + // A request that is the empty chunk alone is answered from the entry, under the + // schema of the read rather than as a batch without columns. + let empty = range_stmt("cpu", HEAD_MS + CHUNK_MS, CHUNK_STEPS as u64, STEP_MS); + let rows = merged( + run(&ForbiddenExecutor, &cache, &empty, "cpu") + .await + .unwrap(), + ); + assert!(points(&rows).is_empty()); + assert_eq!( + rows_of(&empty).schema().arrow_schema(), + rows.schema().arrow_schema(), + "an empty chunk answers with the schema of the read behind it" + ); + } + + #[test] + fn a_nocache_hint_of_false_leaves_the_cache_on() { + let ctx = |value: &str| { + Arc::new( + session::context::QueryContextBuilder::default() + .set_extension( + session::hints::PROMQL_ROLLUP_CACHE_NOCACHE.to_string(), + value.to_string(), + ) + .build(), + ) + }; + // The hint channel carries whatever the client sent, so only a value that says + // "set" may bypass. + for value in ["false", "0", "False"] { + assert!( + !rollup_cache_bypassed(&ctx(value)), + "{value:?} must leave the cache on" + ); + } + for value in ["true", "TRUE", "1", ""] { + assert!(rollup_cache_bypassed(&ctx(value)), "{value:?} must bypass"); + } + assert!( + !rollup_cache_bypassed(&Arc::new( + session::context::QueryContextBuilder::default().build() + )), + "a request without the hint does not bypass" + ); + } + + #[tokio::test] + async fn a_chunk_without_annotations_stays_empty_across_hits() { + let cache = test_cache(); + let stmt = range_stmt("cpu", HEAD_MS, 40, STEP_MS); + let filled = run(&RecordingExecutor::default(), &cache, &stmt, "cpu") + .await + .unwrap(); + assert!(recorded(&filled).is_empty()); + + let warm = run(&ForbiddenExecutor, &cache, &stmt, "cpu").await.unwrap(); + assert!(recorded(&warm).is_empty()); + } +} diff --git a/src/frontend/src/lib.rs b/src/frontend/src/lib.rs index 7c68e445242..334f72f1803 100644 --- a/src/frontend/src/lib.rs +++ b/src/frontend/src/lib.rs @@ -20,6 +20,7 @@ pub mod frontend; pub mod heartbeat; pub mod instance; pub(crate) mod metrics; +pub(crate) mod promql_query_cache; pub mod server; pub mod service_config; mod stream_wrapper; diff --git a/src/frontend/src/promql_query_cache.rs b/src/frontend/src/promql_query_cache.rs new file mode 100644 index 00000000000..49e4f661b8a --- /dev/null +++ b/src/frontend/src/promql_query_cache.rs @@ -0,0 +1,1693 @@ +// 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. + +//! Frontend-local, read-through cache of PromQL range-query chunks. +//! +//! A key is the request's [`QueryIdentity`] plus a [`TimeChunk`] aligned to absolute +//! time: with grid phase `p` and chunk length `c` (the configured `chunk` rounded down +//! to whole steps, at least 20), chunk `k` is `[p + k*c, p + (k+1)*c)`, so a sliding +//! window keeps its interior chunks. Only whole chunks older than `now - tail` are +//! cached; the partial edges and the tail are [`DirectSpan`]s. +//! +//! Freshness is the entry's age alone: an entry is served until `ttl`, so a late or +//! backfilled row inside a cached chunk stays invisible for up to `ttl`. Entries are +//! weighted by payload, annotation and key bytes against `max_bytes`. + +use std::collections::HashMap; +use std::fmt; +use std::sync::Arc; +#[cfg(any(test, feature = "testing"))] +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, SystemTime}; + +use common_recordbatch::RecordBatches; +use datatypes::arrow::datatypes::{Schema as ArrowSchema, SchemaRef as ArrowSchemaRef}; +use moka::sync::Cache; +use promql_parser::parser::EvalStmt; +use query::promql::label_values::signed_millis_since_epoch; +use query::promql::window::{WindowError, WindowGrid, is_windowable}; +use table::metadata::TableId; + +/// The placeholder a [`QueryIdentity`] prints instead of its query text. +const REDACTED_QUERY: &str = ""; + +/// What every entry is charged beyond the bytes of its key and its payload. +/// +/// The entry itself and the map's own bookkeeping are heap-allocated too; without a +/// fixed charge an empty result would weigh almost nothing and the cache could hold +/// unbounded entries. +const ENTRY_OVERHEAD_BYTES: u64 = 256; + +/// The planner that evaluated a PromQL query. +/// +/// Both routes evaluate the same expression on the same grid but build different +/// plans, so a result produced by one is not reused for the other. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum QueryRoute { + /// The legacy `query::promql::planner` route. + Legacy, + /// The native `query::promql::native_compile` route. + Native, +} + +/// The output schema of the plan a request was cut from, as a key compares it. +/// +/// The schema is a key dimension because a table can change its schema while keeping its +/// id: the metric engine alters a table in place when a new label appears, so a chunk +/// filled before the ALTER and one read after it hold different rows under the same +/// `table_id`, and a hit of the first must never be merged with a fill of the second. +/// +/// The arrow schema is the comparison itself: `Field` and `Schema` compare and hash the +/// same name, type, nullability and metadata, and both sort a metadata map's keys before +/// reading them, so the order one of them happens to iterate in cannot split a single +/// schema into two keys. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct PlanSchema(ArrowSchemaRef); + +impl PlanSchema { + /// The schema `schema` describes. + pub fn of(schema: &ArrowSchema) -> Self { + Self(Arc::new(schema.clone())) + } + + /// The heap bytes an entry is charged for the schema it is keyed by. + /// + /// The fields' names and metadata are what a schema holds, and [`FIELD_BYTES`] stands + /// in for the field, its name's allocation, and the schema's own vectors, which are not + /// measured one by one. + fn bytes(&self) -> u64 { + let schema = &self.0; + schema + .fields() + .iter() + .map(|field| { + FIELD_BYTES + .saturating_add(text_bytes(field.name())) + .saturating_add(metadata_bytes(field.metadata())) + }) + .fold(metadata_bytes(schema.metadata()), u64::saturating_add) + } +} + +/// What one field of a key's schema is charged beyond the bytes of its text. +const FIELD_BYTES: u64 = 64; + +/// The bytes a metadata map's keys and values hold. +fn metadata_bytes(metadata: &HashMap) -> u64 { + metadata + .iter() + .map(|(key, value)| text_bytes(key).saturating_add(text_bytes(value))) + .fold(0, u64::saturating_add) +} + +/// The bytes a text holds. +fn text_bytes(text: &str) -> u64 { + u64::try_from(text.len()).unwrap_or(u64::MAX) +} + +/// Every dimension two requests must agree on before one may reuse the other's +/// chunks. +/// +/// This is the reusable half of a request: it carries no window, so two requests +/// that ask for overlapping windows of the same query produce the same identity +/// and can share every canonical chunk they have in common. A missing dimension +/// would let one request answer another's points, which is why the list is +/// exhaustive rather than minimal. +/// +/// The query text and source table are redacted in [`fmt::Debug`], since a query +/// name and its selectors can carry tenant data; the alias and the read preference +/// are not query text and are printed. +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct QueryIdentity { + /// The tenant the query runs as. + pub tenant: String, + /// The catalog the query reads. + pub catalog: String, + /// The schema (database) the query reads. + pub schema: String, + /// The query text exactly as the caller wrote it. + pub query: String, + /// The expression's named source table, without catalog or schema. + pub source_table: String, + /// The id of the table [`QueryIdentity::source_table`] resolved to. + /// + /// A name alone does not identify the data: a table dropped and created again + /// under the same name is a different table with different rows, so a chunk + /// keyed on the name would answer one table's points from another's rows. + pub table_id: TableId, + /// The evaluation step, in milliseconds. + /// + /// A chunk keyed on one grid must never be served to another, so the step is a + /// key dimension: two requests that evaluate on different grids are two + /// identities. The caller reads it from the statement it evaluates, which is what + /// makes a mismatch impossible rather than something planning has to reject. + pub step_ms: i64, + /// The lookback delta planning applies, in milliseconds. + /// + /// Nothing in today's window allowlist reads `lookback_delta`: only subqueries do, and + /// no subquery is windowable, so this dimension currently separates no two requests + /// and must stay anyway. The day the allowlist admits an expression that reads the + /// delta — `deriv`, `predict_linear`, `holt_winters`, a subquery — two requests over + /// one chunk with different deltas answer different points, and a key without it would + /// serve one request's points to the other. Widening the allowlist has to keep this + /// field; removing it is not a cleanup, it is a correctness bug waiting for that day. + pub lookback_ms: i64, + /// The planner that evaluated the query. + pub route: QueryRoute, + /// The output schema of the plan that was cut into chunks. + /// + /// Two requests over one table can carry the same `table_id` and still answer + /// differently shaped rows, because an ALTER changes the schema in place. The + /// dimension is what keeps the chunks of one shape from answering the other, and it + /// is the plan's own output schema, so a request cannot declare a shape it does not + /// produce. + pub output_schema: PlanSchema, + /// The optional output alias of a PromQL statement + /// (`QueryStatement::Promql(_, alias)`). + /// + /// The alias renames the result's columns without changing the expression, so + /// two requests that differ only in it must not share entries. + pub alias: Option, + /// The read preference the request ran under, as + /// `QueryContext::read_preference()` spells it. + /// + /// It can change which replica serves the query, so it is part of the identity + /// even while every session accepts the same preference. `None` means the + /// caller has not threaded one through; the cache never substitutes a default. + pub read_preference: Option, +} + +impl fmt::Debug for QueryIdentity { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("QueryIdentity") + .field("tenant", &self.tenant) + .field("catalog", &self.catalog) + .field("schema", &self.schema) + .field("query", &REDACTED_QUERY) + .field("source_table", &REDACTED_QUERY) + .field("table_id", &self.table_id) + .field("step_ms", &self.step_ms) + .field("lookback_ms", &self.lookback_ms) + .field("route", &self.route) + .field("output_schema", &self.output_schema) + .field("alias", &self.alias) + .field("read_preference", &self.read_preference) + .finish() + } +} + +/// The coverage one request asked for, in milliseconds. +/// +/// It is deliberately not part of any key: it says which points a plan must cover +/// exactly once, not which results are interchangeable. `end_ms` is the last +/// requested grid point, so the coverage is inclusive there and half-open in the +/// plans this module returns. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct QuerySpan { + start_ms: i64, + end_ms: i64, +} + +impl QuerySpan { + /// The coverage `[start_ms, end_ms]`. + pub fn new(start_ms: i64, end_ms: i64) -> Self { + Self { start_ms, end_ms } + } + + /// The first requested grid point. + #[cfg(test)] + pub fn start_ms(&self) -> i64 { + self.start_ms + } + + /// The last requested grid point. + #[cfg(test)] + pub fn end_ms(&self) -> i64 { + self.end_ms + } +} + +/// A half-open `[start, end)` span of output grid points, in milliseconds. +/// +/// Both bounds lie on the evaluation grid of the statement the span was planned +/// from: `start` is a grid point, and `end` is either the next grid point past the +/// last point the span holds or the instant one step past the statement's last +/// point. Spans are never rounded to wall-clock buckets. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct TimeChunk { + start_ms: i64, + end_ms: i64, +} + +impl TimeChunk { + /// A half-open `[start_ms, end_ms)` span. + pub fn new(start_ms: i64, end_ms: i64) -> Self { + Self { start_ms, end_ms } + } + + /// The first millisecond of the span. + pub fn start_ms(&self) -> i64 { + self.start_ms + } + + /// The millisecond just past the span. + pub fn end_ms(&self) -> i64 { + self.end_ms + } +} + +/// Why a span must be executed without the cache. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DirectReason { + /// A partial chunk at one end of the request, or the gaps around the cacheable + /// chunks. Its points are cacheable in principle but this request does not + /// cover a whole canonical chunk there. + Edge, + /// Points at or after `now - tail`, which may still be receiving data. + Tail, +} + +/// A span the caller must execute directly, and why. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DirectSpan { + span: TimeChunk, + reason: DirectReason, +} + +impl DirectSpan { + /// The span to execute without the cache. + pub fn span(&self) -> TimeChunk { + self.span + } + + /// Why the span is not cacheable. + #[cfg(test)] + pub fn reason(&self) -> DirectReason { + self.reason + } +} + +/// The cache key of one materialized chunk. +/// +/// The identity is shared rather than copied: one request plans many chunks of the +/// same identity, and a long query text would otherwise be duplicated once per key. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct TimeChunkKey { + identity: Arc, + chunk: TimeChunk, +} + +impl TimeChunkKey { + /// The key of the canonical `chunk` of `identity`. + pub fn new(identity: QueryIdentity, chunk: TimeChunk) -> Self { + Self::from_shared(Arc::new(identity), chunk) + } + + /// The key of `chunk` of an identity the caller already shares. + fn from_shared(identity: Arc, chunk: TimeChunk) -> Self { + Self { identity, chunk } + } + + /// The canonical span the chunk covers. + pub fn chunk(&self) -> TimeChunk { + self.chunk + } + + /// How many keys share this key's identity allocation, this one included. + #[cfg(test)] + pub fn identity_share_count(&self) -> usize { + Arc::strong_count(&self.identity) + } + + /// The heap bytes the key's identity holds, which is what an entry is charged for + /// it. + /// + /// Every dimension that is text is a heap allocation, and the query text is the + /// caller's own string: a long selector costs as much to key as to hold. One + /// request shares its identity between all of its keys, so this charges that text + /// once per entry and over-states what an entry adds — an upper bound, which is + /// what a budget wants. The two integers are covered by the per-entry overhead. + fn bytes(&self) -> u64 { + let identity = &self.identity; + [ + Some(&identity.tenant), + Some(&identity.catalog), + Some(&identity.schema), + Some(&identity.query), + Some(&identity.source_table), + identity.alias.as_ref(), + identity.read_preference.as_ref(), + ] + .into_iter() + .flatten() + .map(|text| u64::try_from(text.len()).unwrap_or(u64::MAX)) + .sum::() + .saturating_add(identity.output_schema.bytes()) + } +} + +/// Why a statement or a chunk must not be cached. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BypassReason { + /// The expression is outside the windowable allowlist + /// ([`query::promql::window::is_windowable`]). + NotWindowable, + /// The statement's span or its step cannot be planned into chunks. + InvalidSpan, + /// The grid arithmetic, or a chunk bound, cannot be represented. + Overflow, +} + +impl fmt::Display for BypassReason { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NotWindowable => f.write_str("the expression is not windowable"), + Self::InvalidSpan => f.write_str("the statement cannot be split into chunks"), + Self::Overflow => f.write_str("a chunk bound overflows the time grid"), + } + } +} + +impl std::error::Error for BypassReason {} + +impl From for BypassReason { + fn from(error: WindowError) -> Self { + match error { + WindowError::NotEligible => Self::NotWindowable, + WindowError::InvalidSpan => Self::InvalidSpan, + WindowError::Overflow => Self::Overflow, + } + } +} + +/// The cacheable chunks and the direct spans of one statement. +/// +/// The chunks and the direct spans partition the requested coverage exactly once +/// each, in increasing order of time: the direct spans are disjoint, and together +/// with the chunks they leave neither a gap nor an overlap. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChunkSpans { + span: QuerySpan, + chunks: Vec, + direct: Vec, + tail: Option, +} + +impl ChunkSpans { + /// The coverage, chunks, direct spans, and tail. + pub fn into_parts( + self, + ) -> ( + QuerySpan, + Vec, + Vec, + Option, + ) { + (self.span, self.chunks, self.direct, self.tail) + } +} + +/// Plans the cacheable chunks and the direct spans of `stmt` as of `now`. +/// +/// The rule, in one place: +/// +/// - chunk bounds are canonical: the configured `chunk` is a target that is +/// aligned down to a whole number of the statement's steps, floored at +/// [`MIN_CHUNK_STEPS`], so with phase `p = start_ms.rem_euclid(step_ms)` and the +/// aligned chunk length `c` a bound is `p + k * c`; +/// - a chunk is cacheable only when every one of its points is requested and every +/// one of them is older than `now - tail`; +/// - everything else — the partial chunks at either end and the whole tail — is +/// returned as [`DirectSpan`]s, because a partial chunk must never be keyed as a +/// full one. +/// +/// Chunking selects output points only: the evaluator still has to read the input +/// history each point folds. +pub fn plan_chunks( + stmt: &EvalStmt, + tail: Duration, + chunk: Duration, + now: SystemTime, +) -> Result { + if !is_windowable(&stmt.expr) { + return Err(BypassReason::NotWindowable); + } + let grid = WindowGrid::of(stmt)?; + let chunk_in_steps = chunk_steps(chunk, grid.step_ms())?; + // The aligned chunk, not the configured target: `chunk_in_steps` whole steps. + let chunk_ms = i64::try_from(chunk_in_steps) + .ok() + .and_then(|steps| steps.checked_mul(grid.step_ms())) + .ok_or(BypassReason::Overflow)?; + let now_ms = signed_millis_since_epoch(now).map_err(|_| BypassReason::Overflow)?; + let tail_ms = i64::try_from(tail.as_millis()).unwrap_or(i64::MAX); + let cutoff_ms = now_ms.saturating_sub(tail_ms); + + let points = grid.points(); + let span = QuerySpan::new(grid.start_ms(), grid.last_ms()); + // The first requested point that must be read directly because of the tail. + let tail_start = first_index_at_or_after(&grid, cutoff_ms)?; + + // The first canonical chunk bound at or after the coverage starts. + let first_chunk = first_canonical_chunk(&grid, chunk_ms)?; + // Chunks may only cover points before the tail cutoff. + let cacheable_end = points.min(tail_start); + + let mut chunks = Vec::new(); + let mut next = first_chunk; + while next.saturating_add(chunk_in_steps) <= cacheable_end { + let start_ms = grid.point_ms(next)?; + let end_ms = grid.point_ms(next + chunk_in_steps)?; + chunks.push(TimeChunk::new(start_ms, end_ms)); + next += chunk_in_steps; + } + + // What is left over: before the first chunk, and after the last one. With no + // cacheable chunk both ends collapse into one region covering the whole + // request. + let head_end = if chunks.is_empty() { 0 } else { first_chunk }; + let tail_from = if chunks.is_empty() { 0 } else { next }; + let mut direct = Vec::new(); + let head_tail = push_direct_region(&grid, &mut direct, 0, head_end, tail_start)?; + let last_tail = push_direct_region(&grid, &mut direct, tail_from, points, tail_start)?; + // Merging folds a region's tail part into the edge span before it, and the merged span + // keeps the edge reason, so the tail is the one the region reported instead of the one + // a scan of reasons would find. + let tail = head_tail.or(last_tail); + + Ok(ChunkSpans { + span, + chunks, + direct, + tail, + }) +} + +/// The fewest steps one chunk holds. +/// +/// A chunk of a fixed duration degrades to a single point at a coarse step: seven days at +/// ten-minute steps is a thousand points, so a five-minute target would key one chunk per +/// point and pay the cache's per-entry cost a thousand times for no reuse. Sizing the +/// chunk in steps instead makes the chunk count track the points a query asks for rather +/// than the range it spans. +const MIN_CHUNK_STEPS: u64 = 20; + +/// The configured target chunk as a whole number of steps of `step_ms`. +/// +/// The target is global while the step belongs to the query, so it is rounded *down* to a +/// whole number of steps and floored at [`MIN_CHUNK_STEPS`], and the result is the chunk +/// planning uses. Every step therefore plans: no query bypasses merely because the target +/// is not a multiple of its step, and none is cut into one-point chunks merely because its +/// step is coarse. For one step the result is one fixed length, so the canonical bounds of +/// a sliding window do not move. +/// +/// Only an arithmetic that cannot be represented fails, with +/// [`BypassReason::Overflow`]; `step_ms` is positive by construction +/// ([`WindowGrid`] rejects anything else). +fn chunk_steps(chunk: Duration, step_ms: i64) -> Result { + let chunk_ms = i64::try_from(chunk.as_millis()).map_err(|_| BypassReason::Overflow)?; + let steps = (i128::from(chunk_ms) / i128::from(step_ms)).max(i128::from(MIN_CHUNK_STEPS)); + u64::try_from(steps).map_err(|_| BypassReason::Overflow) +} + +/// `value / divisor` rounded towards positive infinity, for a positive `divisor`. +/// +/// The signed `div_ceil` is not stable yet, and the bounds below may lie before the +/// epoch, where truncating division would round the wrong way. +fn div_ceil(value: i128, divisor: i128) -> i128 { + let quotient = value.div_euclid(divisor); + if value.rem_euclid(divisor) == 0 { + quotient + } else { + quotient + 1 + } +} + +/// The first grid index whose point is at or after `ms`, clamped to the grid. +fn first_index_at_or_after(grid: &WindowGrid, ms: i64) -> Result { + let delta = i128::from(ms) - i128::from(grid.start_ms()); + let index = div_ceil(delta, i128::from(grid.step_ms())); + let index = index.clamp(0, i128::from(grid.points())); + u64::try_from(index).map_err(|_| BypassReason::Overflow) +} + +/// The grid index of the first canonical chunk bound at or after the grid starts. +/// +/// Canonical bounds are `phase + k * chunk`, with the phase read from the grid, so +/// this is the smallest such bound that is not before the grid's first point. +fn first_canonical_chunk(grid: &WindowGrid, chunk_ms: i64) -> Result { + let phase = i128::from(grid.phase_ms()); + let chunk = i128::from(chunk_ms); + let start = i128::from(grid.start_ms()); + let bound = div_ceil(start - phase, chunk) * chunk + phase; + let index = (bound - start) / i128::from(grid.step_ms()); + u64::try_from(index).map_err(|_| BypassReason::Overflow) +} + +/// Appends the direct spans that the grid indexes `[from, to)` split into at +/// `tail_start`, answering the tail part it covers. +fn push_direct_region( + grid: &WindowGrid, + direct: &mut Vec, + from: u64, + to: u64, + tail_start: u64, +) -> Result, BypassReason> { + let tail_from = from.max(tail_start).min(to); + push_direct_span(grid, direct, from, tail_from, DirectReason::Edge)?; + if tail_from >= to { + return Ok(None); + } + push_direct_span(grid, direct, tail_from, to, DirectReason::Tail)?; + Ok(Some(TimeChunk::new( + grid.point_ms(tail_from)?, + grid.point_ms(to)?, + ))) +} + +/// Appends one direct span, merging it into the previous one when they are contiguous. +/// +/// A merged span keeps the reason of its first part, so a span that an edge and a tail +/// part both cover reads as the edge it starts with: both are read the same way. +fn push_direct_span( + grid: &WindowGrid, + direct: &mut Vec, + from: u64, + to: u64, + reason: DirectReason, +) -> Result<(), BypassReason> { + if from >= to { + return Ok(()); + } + let start_ms = grid.point_ms(from)?; + let end_ms = grid.point_ms(to)?; + if let Some(last) = direct.last_mut() + && last.span.end_ms() == start_ms + { + last.span = TimeChunk::new(last.span.start_ms(), end_ms); + return Ok(()); + } + direct.push(DirectSpan { + span: TimeChunk::new(start_ms, end_ms), + reason, + }); + Ok(()) +} + +/// Why a lookup misses. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MissReason { + /// No entry holds this chunk. + /// + /// An entry that reached [`PromqlRollupCacheConfig::ttl`] is such an absence: moka + /// drops it on its own clock, and the cache keeps no second one to report the + /// expiry separately. + NotFound, +} + +/// The outcome of one [`PromqlRollupCache::lookup`]. +#[derive(Debug, PartialEq)] +pub enum Lookup { + /// The whole materialized chunk. + Hit { + /// The complete result of the chunk. + payload: Arc, + /// The warnings and infos the read behind `payload` recorded. + annotations: Arc, + }, + /// The chunk cannot be served; execute storage and fill it. + Miss(MissReason), +} + +/// The outcome of one [`PromqlRollupCache::insert`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Insert { + /// The payload became the entry of the chunk. + Stored, + /// The chunk weighs more than a cache weight can express, so it is not stored. + /// + /// A weight is a `u32`, and clamping such a chunk to the largest one would charge + /// it a few bytes while it holds gigabytes. The read that produced it is served as + /// usual; only the entry is refused. + TooLarge, +} + +/// Why a [`PromqlRollupCacheConfig`] is unusable. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConfigError { + /// The cache must be allowed some bytes. + Bytes, + /// A chunk must cover at least one millisecond. + Chunk, + /// An entry must live at least one millisecond, and no longer than the longest ttl + /// moka accepts ([`MAX_TTL`]). + Ttl, +} + +impl fmt::Display for ConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Bytes => f.write_str("the cache byte budget must be positive"), + Self::Chunk => f.write_str("the chunk duration must be positive"), + Self::Ttl => f.write_str("the ttl must be positive and no longer than 365000 days"), + } + } +} + +impl std::error::Error for ConfigError {} + +/// The longest ttl a moka builder accepts: 365,000 days, a little under 1,000 years. +/// +/// moka panics on a longer `time_to_live`, so a configuration is rejected here rather +/// than by starting the cache. +pub const MAX_TTL: Duration = Duration::from_secs(365_000 * 86_400); + +/// The bounds a [`PromqlRollupCache`] enforces. +/// +/// `tail` is a [`Duration`], so it is non-negative by construction and needs no +/// check; `max_bytes`, `chunk`, and `ttl` all have to be positive, and `ttl` also has +/// to fit what moka's builder accepts ([`MAX_TTL`]). +/// +/// `chunk` cannot be resolved into a chunk length here, because the length is the +/// target aligned down to the query's steps and the step belongs to the query, not +/// the cache: planning aligns it, so the cache never bypasses a query merely because +/// the target is not a multiple of its step. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PromqlRollupCacheConfig { + max_bytes: u64, + tail: Duration, + chunk: Duration, + ttl: Duration, +} + +impl PromqlRollupCacheConfig { + /// The validated configuration of a cache. + pub fn new( + max_bytes: u64, + tail: Duration, + chunk: Duration, + ttl: Duration, + ) -> Result { + if max_bytes == 0 { + return Err(ConfigError::Bytes); + } + if chunk.is_zero() { + return Err(ConfigError::Chunk); + } + if ttl.is_zero() || ttl > MAX_TTL { + return Err(ConfigError::Ttl); + } + Ok(Self { + max_bytes, + tail, + chunk, + ttl, + }) + } + + /// The bytes resident entries may occupy before eviction. + pub fn max_bytes(&self) -> u64 { + self.max_bytes + } + + /// How close to the wall clock output points stop being cacheable. + pub fn tail(&self) -> Duration { + self.tail + } + + /// The target span of the grid one chunk covers. + /// + /// It is a target, not the length used: planning aligns it down to a whole + /// number of the statement's steps, at least one, so a query at a coarser step + /// than this target gets one step per chunk. + pub fn chunk(&self) -> Duration { + self.chunk + } + + /// How long an entry is served, counted from the instant it was filled. + pub fn ttl(&self) -> Duration { + self.ttl + } +} + +/// A statement planned into the chunk keys a lookup uses, plus what to read +/// directly. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlannedChunks { + span: QuerySpan, + chunks: Vec, + direct: Vec, + tail: Option, +} + +impl PlannedChunks { + /// The coverage every span below partitions. + #[cfg(test)] + pub fn span(&self) -> QuerySpan { + self.span + } + + /// The cacheable chunks of the statement, in time order. + pub fn chunks(&self) -> &[TimeChunkKey] { + &self.chunks + } + + /// The spans to execute without the cache, in time order. + pub fn direct(&self) -> &[DirectSpan] { + &self.direct + } + + /// The part of the coverage at or after `now - tail`. + #[cfg(test)] + pub fn tail(&self) -> Option { + self.tail + } +} + +/// The result of planning a statement against a cache. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ChunkPlan { + /// The statement must not use the cache at all. + Bypass(BypassReason), + /// The statement's cacheable chunks and the spans to read directly. + Planned(PlannedChunks), +} + +/// The PromQL annotations (warnings and infos) one chunk's read recorded. +/// +/// A hit serves the rows of a read that already happened, so it cannot re-run the +/// code that observed what the read saw. Recording those observations beside the +/// rows lets a served chunk report the same warnings and infos a fresh read of it +/// reported, instead of dropping them because the evaluation was skipped. +/// +/// Both lists are sorted and deduplicated, exactly as the collector a request +/// reports from keeps them, so replaying them cannot duplicate a message. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CachedAnnotations { + warnings: Vec, + infos: Vec, +} + +impl CachedAnnotations { + /// The annotations of one read, sorted and deduplicated. + pub fn new(mut warnings: Vec, mut infos: Vec) -> Self { + warnings.sort(); + warnings.dedup(); + infos.sort(); + infos.dedup(); + Self { warnings, infos } + } + + /// The warnings the read recorded, in order. + pub fn warnings(&self) -> &[String] { + &self.warnings + } + + /// The infos the read recorded, in order. + pub fn infos(&self) -> &[String] { + &self.infos + } + + /// Whether the read recorded nothing. + pub fn is_empty(&self) -> bool { + self.warnings.is_empty() && self.infos.is_empty() + } + + /// The heap bytes these messages hold, which is what an entry is charged for + /// them. + /// + /// The text is the whole cost: the two lists and their pointers are covered by + /// the per-entry overhead every entry pays. + fn bytes(&self) -> u64 { + self.warnings + .iter() + .chain(self.infos.iter()) + .map(|message| u64::try_from(message.len()).unwrap_or(u64::MAX)) + .sum() + } +} + +/// One cached chunk: the complete materialized result and the read that made it. +#[derive(Debug, Clone)] +struct Entry { + payload: Arc, + /// What the read that produced `payload` recorded, served with it. + annotations: Arc, + /// The bytes this entry is charged: its key, its payload, its annotations, and a + /// fixed overhead. + weight: u32, +} + +impl Entry { + /// The bytes one entry is charged, or [`None`] when they do not fit a cache weight. + /// + /// The key and the annotations count: a chunk whose read recorded a long message, + /// or one reached by a long selector, costs more to keep than the same rows under + /// a short key and no message, so eviction stays within the budget the + /// configuration names. + fn weigh( + key: &TimeChunkKey, + payload: &RecordBatches, + annotations: &CachedAnnotations, + ) -> Option { + let data: usize = payload + .iter() + .map(|batch| batch.buffer_memory_size()) + .sum::(); + let bytes = u64::try_from(data) + .unwrap_or(u64::MAX) + .saturating_add(key.bytes()) + .saturating_add(annotations.bytes()) + .saturating_add(ENTRY_OVERHEAD_BYTES); + cache_weight(bytes) + } +} + +/// `bytes` as a cache weight, or [`None`] when it is larger than a weight can express. +/// +/// Clamping instead would charge a multi-gigabyte chunk a few bytes and let it stay +/// resident however small the budget is. +fn cache_weight(bytes: u64) -> Option { + u32::try_from(bytes).ok() +} + +/// A bounded, frontend-local, read-through cache of whole PromQL chunks. +/// +/// The cache is read-through: [`PromqlRollupCache::lookup`] answers from memory or says +/// why it cannot, and the caller executes storage and calls [`PromqlRollupCache::insert`]. +/// Entries leave for three reasons only — they reach +/// [`PromqlRollupCacheConfig::ttl`], moka evicts them once the byte budget is spent, or the +/// reset endpoint empties the cache ([`PromqlRollupCache::clear`]) — so nothing on the +/// request path has to observe the source at all. The cache is a bounded-staleness +/// one: `ttl` is the whole freshness rule, and the reset is its escape hatch. +pub struct PromqlRollupCache { + config: PromqlRollupCacheConfig, + entries: Cache, + /// How many lookups were answered from an existing entry. + #[cfg(any(test, feature = "testing"))] + hits: AtomicU64, +} + +impl PromqlRollupCache { + /// A cache bounded by `config`. + pub fn new(config: PromqlRollupCacheConfig) -> Self { + let entries = Cache::builder() + .max_capacity(config.max_bytes()) + .time_to_live(config.ttl()) + .weigher(|_key: &TimeChunkKey, entry: &Entry| entry.weight) + .build(); + Self { + config, + entries, + #[cfg(any(test, feature = "testing"))] + hits: AtomicU64::new(0), + } + } + + /// The configuration this cache enforces. + pub fn config(&self) -> &PromqlRollupCacheConfig { + &self.config + } + + /// How many entries the cache holds once pending maintenance has run. + #[cfg(any(test, feature = "testing"))] + pub fn entry_count(&self) -> u64 { + self.entries.run_pending_tasks(); + self.entries.entry_count() + } + + /// The bytes the resident entries are charged once pending maintenance has run. + #[cfg(any(test, feature = "testing"))] + pub fn byte_count(&self) -> u64 { + self.entries.run_pending_tasks(); + self.entries.weighted_size() + } + + /// How many lookups this cache has answered from an existing entry. + /// + /// Only a served entry advances it: a miss and a fill never do. + #[cfg(any(test, feature = "testing"))] + pub fn hit_count(&self) -> u64 { + self.hits.load(Ordering::SeqCst) + } + + /// Empties the cache, dropping every entry of every request. + /// + /// This is the local reset behind `POST /debug/reset_promql_rollup_cache`; it does not + /// touch source data or other frontends. + pub fn clear(&self) { + self.entries.invalidate_all(); + self.entries.run_pending_tasks(); + } + + /// Plans `stmt` of `identity` into chunk keys and direct spans as of `now`. + /// + /// The returned direct spans are the caller's to send to storage; their points + /// are never cached. + pub fn plan(&self, identity: QueryIdentity, stmt: &EvalStmt, now: SystemTime) -> ChunkPlan { + match plan_chunks(stmt, self.config.tail(), self.config.chunk(), now) { + Err(reason) => ChunkPlan::Bypass(reason), + Ok(spans) => { + let (span, chunks, direct, tail) = spans.into_parts(); + // One allocation for every key of this request: a year of five-minute + // chunks is a hundred thousand keys, and none of them may copy the query. + let identity = Arc::new(identity); + let chunks = chunks + .into_iter() + .map(|chunk| TimeChunkKey::from_shared(identity.clone(), chunk)) + .collect(); + ChunkPlan::Planned(PlannedChunks { + span, + chunks, + direct, + tail, + }) + } + } + } + + /// Tries to serve `key` from memory. + /// + /// An entry that reached [`PromqlRollupCacheConfig::ttl`] is simply absent: moka owns + /// that clock. + pub fn lookup(&self, key: &TimeChunkKey) -> Lookup { + let Some(entry) = self.entries.get(key) else { + return Lookup::Miss(MissReason::NotFound); + }; + // The entry is served: nothing else in this cache counts as a hit. + #[cfg(any(test, feature = "testing"))] + self.hits.fetch_add(1, Ordering::SeqCst); + Lookup::Hit { + payload: entry.payload, + annotations: entry.annotations, + } + } + + /// Stores what a read of `key` produced. + /// + /// The chunk is stored as it is: the cache has no notion of a read being + /// un-publishable, so the caller's insert is the whole decision. The one exception is + /// a chunk that would weigh more than a cache weight can express + /// ([`Insert::TooLarge`]), because charging it anything less would let it outlive the + /// budget. + pub fn insert( + &self, + key: &TimeChunkKey, + payload: Arc, + annotations: Arc, + ) -> Insert { + let Some(weight) = Entry::weigh(key, &payload, &annotations) else { + return Insert::TooLarge; + }; + let entry = Entry { + weight, + payload, + annotations, + }; + self.entries.insert(key.clone(), entry); + Insert::Stored + } +} + +#[cfg(test)] +mod tests { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + use std::time::UNIX_EPOCH; + + use datatypes::arrow::datatypes::{DataType as ArrowDataType, Field}; + use promql_parser::parser::parse; + + use super::*; + + /// The hash a schema keys an entry by. + fn hash_of(schema: &PlanSchema) -> u64 { + let mut hasher = DefaultHasher::new(); + schema.hash(&mut hasher); + hasher.finish() + } + + /// One minute, the step every clock-aligned test uses. + const STEP_MS: i64 = 60_000; + /// The fewest steps a chunk of a one-minute grid may hold. + const CHUNK_STEPS: i64 = MIN_CHUNK_STEPS as i64; + /// The twenty-step chunk every clock-aligned test plans with. + const CHUNK_MS: i64 = CHUNK_STEPS * STEP_MS; + /// The chunk target every test configures: coarser than one step, so the floor is + /// what decides the width. + const CHUNK_TARGET: Duration = Duration::from_secs(300); + /// The same target as the chunk the aligned length comes out at. + const CHUNK: Duration = Duration::from_millis(CHUNK_MS as u64); + /// A five-minute-aligned instant, standing in for 10:00. + const HEAD_MS: i64 = 36_000_000; + /// A wall clock far enough past every test window that no point is in its tail. + const LATER_MS: i64 = HEAD_MS + 24 * 3_600_000; + /// The ttl every test configures. + const TTL: Duration = Duration::from_secs(3_600); + /// The id the table every test names resolves to. + const TABLE_ID: TableId = 1024; + /// The id a table created under a name another table was dropped from gets. + const RECREATED_TABLE_ID: TableId = 2048; + + fn at(ms: i64) -> SystemTime { + let duration = Duration::from_millis(ms.unsigned_abs()); + if ms >= 0 { + UNIX_EPOCH + duration + } else { + UNIX_EPOCH - duration + } + } + + /// A statement from `start_ms` to `end_ms` (inclusive), stepping `step_ms`. + fn stmt_between(expr: &str, start_ms: i64, end_ms: i64, step_ms: i64) -> EvalStmt { + EvalStmt { + expr: parse(expr).expect("the expression parses"), + start: at(start_ms), + end: at(end_ms), + interval: Duration::from_millis(step_ms.unsigned_abs()), + lookback_delta: Duration::from_secs(300), + } + } + + /// A statement of `points` points from `start_ms`. + fn stmt_from(expr: &str, start_ms: i64, points: u64, step_ms: i64) -> EvalStmt { + let end_ms = start_ms + (points as i64 - 1) * step_ms; + stmt_between(expr, start_ms, end_ms, step_ms) + } + + /// The output schema every test's plan produces. + fn output_schema() -> PlanSchema { + PlanSchema::of(&ArrowSchema::new(vec![Field::new( + "greptime_value", + ArrowDataType::Float64, + true, + )])) + } + + fn identity() -> QueryIdentity { + QueryIdentity { + tenant: "greptime".to_string(), + catalog: "greptime".to_string(), + schema: "public".to_string(), + query: "rate(http_requests_total[5m])".to_string(), + source_table: "http_requests_total".to_string(), + table_id: TABLE_ID, + step_ms: STEP_MS, + lookback_ms: 300_000, + route: QueryRoute::Legacy, + output_schema: output_schema(), + alias: None, + read_preference: None, + } + } + + /// The key of chunk `index` after [`HEAD_MS`], so `-1` ends where the first starts. + fn chunk_key_at(index: i64) -> TimeChunkKey { + let start = HEAD_MS + index * CHUNK_MS; + TimeChunkKey::new(identity(), TimeChunk::new(start, start + CHUNK_MS)) + } + + fn payload() -> Arc { + Arc::new(RecordBatches::empty()) + } + + fn config() -> PromqlRollupCacheConfig { + config_targeting(CHUNK_TARGET) + } + + /// The test configuration with `chunk` as its target chunk duration. + fn config_targeting(chunk: Duration) -> PromqlRollupCacheConfig { + PromqlRollupCacheConfig::new(1 << 20, Duration::ZERO, chunk, TTL) + .expect("the test configuration is valid") + } + + fn cache() -> PromqlRollupCache { + PromqlRollupCache::new(config()) + } + + /// A cache whose target chunk is `chunk`, everything else as [`config`] has it. + fn cache_targeting(chunk: Duration) -> PromqlRollupCache { + PromqlRollupCache::new(config_targeting(chunk)) + } + + fn planned( + cache: &PromqlRollupCache, + stmt: &EvalStmt, + now: SystemTime, + ) -> ( + QuerySpan, + Vec, + Vec, + Option, + ) { + planned_for(identity(), cache, stmt, now) + } + + #[allow(clippy::type_complexity)] + fn planned_for( + identity: QueryIdentity, + cache: &PromqlRollupCache, + stmt: &EvalStmt, + now: SystemTime, + ) -> ( + QuerySpan, + Vec, + Vec, + Option, + ) { + match cache.plan(identity, stmt, now) { + ChunkPlan::Planned(planned) => ( + planned.span(), + planned.chunks().iter().map(|key| key.chunk()).collect(), + planned.direct().to_vec(), + planned.tail(), + ), + ChunkPlan::Bypass(reason) => panic!("the statement should plan: {reason}"), + } + } + + /// Every span a plan returns, in time order, must partition the coverage exactly + /// once. + fn assert_partition(span: QuerySpan, chunks: &[TimeChunk], direct: &[DirectSpan]) { + let mut spans: Vec = chunks + .iter() + .copied() + .chain(direct.iter().map(|span| span.span())) + .collect(); + spans.sort_by_key(|span| span.start_ms()); + assert_eq!( + spans.first().map(|span| span.start_ms()), + Some(span.start_ms()) + ); + let mut previous_end = span.start_ms(); + for chunk in &spans { + assert_eq!( + chunk.start_ms(), + previous_end, + "gap or overlap at {chunk:?}" + ); + assert!(chunk.start_ms() < chunk.end_ms(), "empty span {chunk:?}"); + previous_end = chunk.end_ms(); + } + assert!( + previous_end > span.end_ms(), + "the last span must reach past the last point of {span:?}" + ); + } + + #[test] + fn a_sliding_window_reuses_every_interior_chunk() { + let cache = cache(); + // Forty points one minute apart cover two whole chunks of twenty steps each. + let first = stmt_from("rate(http_requests_total[5m])", HEAD_MS, 40, STEP_MS); + let (_, chunks, direct, _) = planned(&cache, &first, at(LATER_MS)); + assert_eq!( + chunks, + vec![ + TimeChunk::new(HEAD_MS, HEAD_MS + CHUNK_MS), + TimeChunk::new(HEAD_MS + CHUNK_MS, HEAD_MS + 2 * CHUNK_MS), + ] + ); + assert!(direct.is_empty()); + + // Sliding the window by one chunk keeps both chunks and moves the coverage. + let second = stmt_from( + "rate(http_requests_total[5m])", + HEAD_MS + CHUNK_MS, + 40, + STEP_MS, + ); + let (_, chunks, _, _) = planned(&cache, &second, at(LATER_MS)); + assert_eq!( + chunks, + vec![ + TimeChunk::new(HEAD_MS + CHUNK_MS, HEAD_MS + 2 * CHUNK_MS), + TimeChunk::new(HEAD_MS + 2 * CHUNK_MS, HEAD_MS + 3 * CHUNK_MS), + ] + ); + } + + #[test] + fn a_plan_keys_every_one_of_its_chunks_with_one_identity() { + let cache = cache(); + // Two chunks stand in for the hundred thousand a year of twenty-step ones would + // make: one allocation is the whole claim. + let stmt = stmt_from("rate(http_requests_total[5m])", HEAD_MS, 40, STEP_MS); + let ChunkPlan::Planned(planned) = cache.plan(identity(), &stmt, at(LATER_MS)) else { + panic!("the statement should plan"); + }; + let chunks = planned.chunks(); + assert_eq!(chunks.len(), 2); + // `plan` drops the reference it made the keys with, so one count per key is a + // single shared allocation; a copy per key would count one for each. + assert!( + chunks + .iter() + .all(|key| key.identity_share_count() == chunks.len()), + "every key of a plan must share one identity allocation" + ); + } + + #[test] + fn the_tail_is_measured_from_now_not_from_the_query_end() { + let cache = cache(); + let stmt = stmt_from("rate(http_requests_total[5m])", HEAD_MS, 40, STEP_MS); + // A wall clock inside the statement's own coverage puts the last points in the + // tail even though the query asks for them. + let now_ms = HEAD_MS + CHUNK_MS; + let (span, chunks, direct, tail) = planned(&cache, &stmt, at(now_ms)); + assert_partition(span, &chunks, &direct); + assert_eq!(chunks.len(), 1); + assert!(tail.is_some_and(|tail| tail.end_ms() > now_ms)); + assert!( + direct + .iter() + .any(|span| span.reason() == DirectReason::Tail), + "the points at or after the cutoff are direct: {direct:?}" + ); + } + + #[test] + fn a_step_without_whole_milliseconds_is_not_plannable() { + // The step is a key dimension rather than something planning cross-checks, + // because the identity is built from the statement it keys. A step that has no + // whole millisecond is the one case the two could disagree on, and the grid + // refuses it before a key is made. + let cache = cache(); + let mut stmt = stmt_from("rate(http_requests_total[5m])", HEAD_MS, 10, STEP_MS); + stmt.interval = Duration::from_micros(500); + assert_eq!( + cache.plan(identity(), &stmt, at(LATER_MS)), + ChunkPlan::Bypass(BypassReason::InvalidSpan) + ); + } + + #[test] + fn a_target_chunk_is_aligned_down_to_whole_steps() { + // 90 seconds against a 60-second step is one step, not one and a half: the query + // plans instead of bypassing, and every chunk is the twenty-step floor. + let cache = cache_targeting(Duration::from_secs(90)); + let stmt = stmt_from("rate(http_requests_total[5m])", HEAD_MS, 40, STEP_MS); + let (span, chunks, direct, _) = planned(&cache, &stmt, at(LATER_MS)); + assert_partition(span, &chunks, &direct); + assert!(direct.is_empty()); + assert_eq!(2, chunks.len()); + assert!( + chunks + .iter() + .all(|chunk| chunk.end_ms() - chunk.start_ms() == CHUNK_MS), + "every chunk is the floor: {chunks:?}" + ); + assert_eq!( + chunks.first(), + Some(&TimeChunk::new(HEAD_MS, HEAD_MS + CHUNK_MS)) + ); + + // A sliding window therefore keeps the same canonical bounds: one step later, + // the interior chunks are the very same spans. + let slid = stmt_from( + "rate(http_requests_total[5m])", + HEAD_MS + STEP_MS, + 40, + STEP_MS, + ); + let (_, slid_chunks, _, _) = planned(&cache, &slid, at(LATER_MS)); + assert_eq!(&chunks[1..], &slid_chunks[..chunks.len() - 1]); + + // A 5m target against a 2m step is above the floor: twenty steps of two minutes + // make 40m chunks. + let two_min = 2 * STEP_MS; + let cache = cache_targeting(CHUNK_TARGET); + let stmt = stmt_from("rate(http_requests_total[5m])", HEAD_MS, 40, two_min); + let (span, chunks, direct, _) = planned_for( + QueryIdentity { + step_ms: two_min, + ..identity() + }, + &cache, + &stmt, + at(LATER_MS), + ); + assert_partition(span, &chunks, &direct); + assert!(direct.is_empty()); + assert_eq!( + chunks, + vec![ + TimeChunk::new(HEAD_MS, HEAD_MS + CHUNK_STEPS * two_min), + TimeChunk::new( + HEAD_MS + CHUNK_STEPS * two_min, + HEAD_MS + 2 * CHUNK_STEPS * two_min + ), + ] + ); + } + + #[test] + fn a_chunk_is_at_least_the_minimum_steps_wide() { + // A five-minute target against a ten-minute step cannot hold even one step, so + // the floor decides the width rather than the target. + assert_eq!( + Ok(MIN_CHUNK_STEPS), + chunk_steps(Duration::from_secs(300), 600_000) + ); + // Fifteen seconds divide the same target into exactly the floor: the floor does + // not change a chunk it agrees with. + assert_eq!( + Ok(MIN_CHUNK_STEPS), + chunk_steps(Duration::from_secs(300), 15_000) + ); + // Above the floor, the target is still aligned down to whole steps. + assert_eq!(Ok(30), chunk_steps(Duration::from_secs(300), 10_000)); + } + + #[test] + fn a_coarse_step_chunks_by_points_not_by_range() { + // Seven days at ten-minute steps is a thousand and eight points. One chunk per + // point would key all of them separately; twenty steps per chunk leaves fifty + // chunks and an eight-point remainder. + let cache = cache_targeting(CHUNK_TARGET); + let ten_min = 600_000; + let stmt = stmt_between( + "rate(http_requests_total[5m])", + HEAD_MS, + HEAD_MS + 1007 * ten_min, + ten_min, + ); + let (span, chunks, direct, _) = planned_for( + QueryIdentity { + step_ms: ten_min, + ..identity() + }, + &cache, + &stmt, + at(HEAD_MS + 8 * 24 * 3_600_000), + ); + assert_partition(span, &chunks, &direct); + assert_eq!(50, chunks.len()); + assert!( + chunks + .iter() + .all(|chunk| chunk.end_ms() - chunk.start_ms() == MIN_CHUNK_STEPS as i64 * ten_min), + "every chunk is the floor: {chunks:?}" + ); + // The points that did not fill a whole chunk are read directly. + assert_eq!( + 8, + direct + .iter() + .map(|span| (span.span().end_ms() - span.span().start_ms()) / ten_min) + .sum::() + ); + } + + #[test] + fn a_small_step_keeps_its_chunking() { + // Fifteen-second steps divide the five-minute target into exactly twenty steps, + // so six hours is still the seventy-two chunks it was before the floor. + let cache = cache_targeting(CHUNK_TARGET); + let stmt = stmt_between( + "rate(http_requests_total[5m])", + HEAD_MS, + HEAD_MS + 1440 * 15_000, + 15_000, + ); + let (span, chunks, direct, _) = planned_for( + QueryIdentity { + step_ms: 15_000, + ..identity() + }, + &cache, + &stmt, + at(LATER_MS), + ); + assert_partition(span, &chunks, &direct); + assert_eq!(72, chunks.len()); + assert!( + chunks + .iter() + .all(|chunk| chunk.end_ms() - chunk.start_ms() == 300_000), + "every chunk is the five-minute target: {chunks:?}" + ); + } + + #[test] + fn a_target_coarser_than_the_step_chunks_the_minimum_steps() { + // A 1m target against a 2m step cannot hold even one step, so planning keeps the + // floor rather than an empty or one-point chunk. + let two_min = 2 * STEP_MS; + let cache = cache_targeting(Duration::from_secs(60)); + let stmt = stmt_from("rate(http_requests_total[5m])", HEAD_MS, 20, two_min); + let (span, chunks, direct, _) = planned_for( + QueryIdentity { + step_ms: two_min, + ..identity() + }, + &cache, + &stmt, + at(LATER_MS), + ); + assert_partition(span, &chunks, &direct); + assert!(direct.is_empty()); + assert_eq!( + chunks, + vec![TimeChunk::new(HEAD_MS, HEAD_MS + CHUNK_STEPS * two_min)] + ); + } + + #[test] + fn a_non_windowable_expression_bypasses_the_cache() { + let cache = cache(); + let stmt = stmt_from("http_requests_total + 1", HEAD_MS, 10, STEP_MS); + assert_eq!( + cache.plan(identity(), &stmt, at(LATER_MS)), + ChunkPlan::Bypass(BypassReason::NotWindowable) + ); + } + + #[test] + fn an_identity_prints_its_context_but_never_its_query_text() { + let printed = format!("{:?}", identity()); + assert!(printed.contains("greptime")); + assert!(printed.contains("public")); + assert!(!printed.contains("http_requests_total")); + assert!(printed.contains(REDACTED_QUERY)); + assert!( + printed.contains(&TABLE_ID.to_string()), + "the table id is part of the key, so it is printed: {printed}" + ); + } + + #[test] + fn a_chunk_is_never_served_to_another_table_of_the_same_name() { + let cache = cache(); + let key = chunk_key_at(0); + assert_eq!( + cache.insert(&key, payload(), Arc::default()), + Insert::Stored + ); + + // Dropping the table and creating it again under the same name leaves the + // request otherwise identical and changes only the id the name resolves to. + let recreated = TimeChunkKey::new( + QueryIdentity { + table_id: RECREATED_TABLE_ID, + ..identity() + }, + key.chunk(), + ); + assert_eq!(cache.lookup(&recreated), Lookup::Miss(MissReason::NotFound)); + assert_eq!( + cache.entry_count(), + 1, + "the chunk of the table that still exists is untouched" + ); + } + + #[test] + fn a_chunk_of_another_output_schema_is_another_entry() { + let cache = cache(); + let key = chunk_key_at(0); + assert_eq!( + cache.insert(&key, payload(), Arc::default()), + Insert::Stored + ); + + // The metric engine alters a table in place when a new label appears: the name, + // the id it resolves to, and every other dimension stay the same, and only the + // shape of the rows changes, so a chunk of the table before the ALTER must not + // answer the request after it. + let altered = TimeChunkKey::new( + QueryIdentity { + output_schema: PlanSchema::of(&ArrowSchema::new(vec![ + Field::new("greptime_value", ArrowDataType::Float64, true), + Field::new("host", ArrowDataType::Utf8, true), + ])), + ..identity() + }, + key.chunk(), + ); + assert_eq!(cache.lookup(&altered), Lookup::Miss(MissReason::NotFound)); + // ... while the shape that filled it is served. + assert!(matches!(cache.lookup(&key), Lookup::Hit { .. })); + assert_eq!(cache.entry_count(), 1); + } + + #[test] + fn a_schemas_metadata_order_does_not_split_its_identity() { + // The same metadata inserted in another order is one schema: arrow's `Eq` and + // `Hash` both read a metadata map's keys sorted, so neither the order the map + // iterates in nor the order it was built in can key one shape twice. + let schema = |entries: [(&str, &str); 2]| { + let metadata = entries + .into_iter() + .map(|(key, value)| (key.to_string(), value.to_string())) + .collect::>(); + PlanSchema::of(&ArrowSchema::new(vec![ + Field::new("greptime_value", ArrowDataType::Float64, true).with_metadata(metadata), + ])) + }; + let first = schema([("unit", "seconds"), ("kind", "gauge")]); + let second = schema([("kind", "gauge"), ("unit", "seconds")]); + assert_eq!(first, second); + assert_eq!(hash_of(&first), hash_of(&second)); + } + + #[test] + fn a_missed_chunk_is_filled_and_then_hit() { + let cache = cache(); + let key = chunk_key_at(0); + assert_eq!(cache.lookup(&key), Lookup::Miss(MissReason::NotFound)); + assert_eq!( + cache.insert(&key, payload(), Arc::default()), + Insert::Stored + ); + assert!(matches!(cache.lookup(&key), Lookup::Hit { .. })); + assert_eq!(cache.hit_count(), 1); + assert_eq!(cache.entry_count(), 1); + } + + #[tokio::test] + async fn an_entry_older_than_the_ttl_never_serves() { + // A ttl short enough to wait out: the age moka counts is the cache's whole + // freshness rule, so an entry leaves by reaching it and for no other reason. + let config = + PromqlRollupCacheConfig::new(1 << 20, Duration::ZERO, CHUNK, Duration::from_millis(50)) + .expect("the test configuration is valid"); + let cache = PromqlRollupCache::new(config); + let key = chunk_key_at(0); + assert_eq!( + cache.insert(&key, payload(), Arc::default()), + Insert::Stored + ); + assert!(matches!(cache.lookup(&key), Lookup::Hit { .. })); + + tokio::time::sleep(Duration::from_millis(200)).await; + + // Past the ttl nothing is served, even though nothing else happened: the age + // alone decides. + assert_eq!(cache.lookup(&key), Lookup::Miss(MissReason::NotFound)); + } + + #[test] + fn the_byte_budget_bounds_the_entries() { + // An empty result costs its key and the fixed overhead, so a budget of two of + // them holds two. + let per_entry = u64::from( + Entry::weigh(&chunk_key_at(0), &payload(), &CachedAnnotations::default()) + .expect("the test entry fits a weight"), + ); + let tiny = PromqlRollupCacheConfig::new(per_entry * 2, Duration::ZERO, CHUNK, TTL) + .expect("the test configuration is valid"); + let cache = PromqlRollupCache::new(tiny); + for index in 0..6 { + let key = chunk_key_at(index); + cache.insert(&key, payload(), Arc::default()); + } + assert_eq!(cache.entry_count(), 2); + } + + #[test] + fn a_long_key_is_charged_to_the_entry_that_holds_it() { + // An empty result holds no payload bytes, so its key is what it costs: a long + // selector returning nothing must not be charged like a short one. + let short = chunk_key_at(0); + let selector = format!( + "rate(http_requests_total{{code=\"{}\"}}[5m])", + "5".repeat(200) + ); + let long = TimeChunkKey::new( + QueryIdentity { + query: selector.clone(), + ..identity() + }, + short.chunk(), + ); + let empty = payload(); + let annotations = CachedAnnotations::default(); + + let short_weight = u64::from( + Entry::weigh(&short, &empty, &annotations).expect("the short key fits a weight"), + ); + let long_weight = u64::from( + Entry::weigh(&long, &empty, &annotations).expect("the long key fits a weight"), + ); + assert_eq!(short_weight, ENTRY_OVERHEAD_BYTES + short.bytes()); + assert_eq!( + long_weight - short_weight, + u64::try_from(selector.len() - identity().query.len()).unwrap(), + "the entry is charged every byte the key's text holds" + ); + } + + #[test] + fn a_chunk_too_large_for_a_weight_is_never_stored() { + // A weight is a `u32`: a chunk that does not fit one must be refused rather than + // clamped, which would charge it a few bytes and let it stay resident. + assert_eq!(Some(42), cache_weight(42)); + assert_eq!(Some(u32::MAX), cache_weight(u64::from(u32::MAX))); + assert_eq!(None, cache_weight(u64::from(u32::MAX) + 1)); + assert_eq!(None, cache_weight(u64::MAX)); + } + + #[test] + fn configuration_validation_rejects_disabled_bounds() { + assert_eq!( + PromqlRollupCacheConfig::new(0, Duration::ZERO, CHUNK, TTL), + Err(ConfigError::Bytes) + ); + assert_eq!( + PromqlRollupCacheConfig::new(1 << 20, Duration::ZERO, Duration::ZERO, TTL), + Err(ConfigError::Chunk) + ); + assert_eq!( + PromqlRollupCacheConfig::new(1 << 20, Duration::ZERO, CHUNK, Duration::ZERO), + Err(ConfigError::Ttl) + ); + // A zero tail is a valid configuration: it caches every point the query asks + // for, which is what a test that runs at wall-clock time wants. + assert!(PromqlRollupCacheConfig::new(1 << 20, Duration::ZERO, CHUNK, TTL).is_ok()); + // The longest ttl moka accepts is valid, and a millisecond more is not: a longer + // one would panic the builder instead of failing here. + assert!(PromqlRollupCacheConfig::new(1 << 20, Duration::ZERO, CHUNK, MAX_TTL).is_ok()); + assert_eq!( + PromqlRollupCacheConfig::new( + 1 << 20, + Duration::ZERO, + CHUNK, + MAX_TTL + Duration::from_millis(1) + ), + Err(ConfigError::Ttl) + ); + } +} diff --git a/src/frontend/src/server.rs b/src/frontend/src/server.rs index 56219164f9c..442ec89b9d9 100644 --- a/src/frontend/src/server.rs +++ b/src/frontend/src/server.rs @@ -17,9 +17,12 @@ use std::sync::Arc; use std::time::Duration; use auth::UserProviderRef; +use axum::Router; use axum::extract::{Request, State}; +use axum::http::StatusCode; use axum::middleware::Next; use axum::response::IntoResponse; +use axum::routing::post; use common_base::Plugins; use common_config::Configurable; use common_telemetry::{info, warn}; @@ -158,6 +161,27 @@ where builder = builder.with_dashboard_handler(self.instance.clone()); + if self.instance.promql_rollup_cache().is_some() { + // Registered under `/debug` so the existing `check_http_auth` layer requires + // the request's credentials exactly as it does for `/debug/log_level`: that + // layer only demands them for the `/v1` and `/debug` namespaces, so a route + // anywhere else would be served unauthenticated. It is operational-route auth + // (any authenticated user, and every caller when no user provider is set), not + // an admin boundary. + let instance = self.instance.clone(); + let reset = Router::new().route( + "/debug/reset_promql_rollup_cache", + post(move || { + let instance = instance.clone(); + async move { + instance.clear_promql_rollup_cache(); + StatusCode::NO_CONTENT + } + }), + ); + builder = builder.with_extra_router(reset); + } + if let Some(configurator) = self.plugins.get::() { info!("Adding extra router from plugins"); builder = builder.with_extra_router(configurator.router()); @@ -1048,6 +1072,127 @@ mod tests { ); } + /// One frontend whose rollup cache holds exactly one chunk, with an HTTP listener + /// that authenticates `greptime:greptime` when `secured` is set. + async fn reset_endpoint_services( + secured: bool, + ) -> ( + ServerHandlers, + std::net::SocketAddr, + Arc, + ) { + use common_recordbatch::RecordBatches; + use datatypes::arrow::datatypes::Schema as ArrowSchema; + + use crate::promql_query_cache::{ + Insert, PlanSchema, QueryIdentity, QueryRoute, TimeChunk, TimeChunkKey, + }; + + let options = FrontendOptions { + http: HttpOptions { + addr: "127.0.0.1:0".to_string(), + ..Default::default() + }, + grpc: GrpcOptions::default().with_bind_addr("127.0.0.1:0"), + mysql: crate::service_config::MysqlOptions { + enable: false, + ..Default::default() + }, + postgres: crate::service_config::PostgresOptions { + enable: false, + ..Default::default() + }, + promql_rollup_cache: crate::service_config::PromqlRollupCacheOptions { + enable: true, + ..Default::default() + }, + ..Default::default() + }; + let meta_client = Arc::new( + MetaClientBuilder::new(0, Role::Frontend) + .enable_procedure() + .build(), + ); + let instance = Arc::new( + FrontendBuilder::new_test(&options, meta_client) + .try_build() + .await + .unwrap(), + ); + let cache = instance + .promql_rollup_cache() + .expect("enabling the cache installs one") + .clone(); + let key = TimeChunkKey::new( + QueryIdentity { + tenant: "greptime".to_string(), + catalog: "greptime".to_string(), + schema: "public".to_string(), + query: "rate(cpu[5m])".to_string(), + source_table: "cpu".to_string(), + table_id: 1024, + step_ms: 60_000, + lookback_ms: 300_000, + route: QueryRoute::Legacy, + output_schema: PlanSchema::of(&ArrowSchema::empty()), + alias: None, + read_preference: None, + }, + TimeChunk::new(0, 300_000), + ); + assert_eq!( + Insert::Stored, + cache.insert(&key, Arc::new(RecordBatches::empty()), Arc::default()) + ); + assert_eq!(1, cache.entry_count()); + + let plugins = Plugins::default(); + if secured { + let provider = + static_user_provider_from_option("static_user_provider:cmd:greptime=greptime") + .unwrap(); + plugins.insert::(Arc::new(provider)); + } + let mut services = Services::new(options, instance, plugins).build().unwrap(); + services.start_all().await.unwrap(); + let addr = services.addr(servers::http::HTTP_SERVER).unwrap(); + (services, addr, cache) + } + + #[tokio::test] + async fn test_promql_rollup_cache_reset_endpoint_is_authenticated_like_the_debug_routes() { + // With a user provider configured, the reset is behind the same `check_http_auth` + // layer as `/debug/log_level`: an unauthenticated request is rejected and its + // credentials are what the layer checks. + let (mut services, addr, cache) = reset_endpoint_services(true).await; + let client = reqwest::Client::new(); + let url = format!("http://{addr}/debug/reset_promql_rollup_cache"); + let rejected = client.post(&url).send().await.unwrap(); + assert_eq!(reqwest::StatusCode::UNAUTHORIZED, rejected.status()); + assert_eq!(1, cache.entry_count(), "a rejected request resets nothing"); + let accepted = client + .post(&url) + .basic_auth("greptime", Some("greptime")) + .send() + .await + .unwrap(); + assert_eq!(reqwest::StatusCode::NO_CONTENT, accepted.status()); + assert_eq!(0, cache.entry_count(), "the endpoint emptied the cache"); + services.shutdown_all().await.unwrap(); + + // Without one, the layer is the pass-through every `/debug` route has: the reset + // is operational-route auth, not an admin boundary. + let (mut services, addr, cache) = reset_endpoint_services(false).await; + let response = client + .post(format!("http://{addr}/debug/reset_promql_rollup_cache")) + .send() + .await + .unwrap(); + services.shutdown_all().await.unwrap(); + assert_eq!(reqwest::StatusCode::NO_CONTENT, response.status()); + assert_eq!(0, cache.entry_count()); + } + #[tokio::test] async fn test_services_builder_health_check_is_reachable() { // Arrange diff --git a/src/frontend/src/service_config.rs b/src/frontend/src/service_config.rs index 535ae9b655b..cd44befe2e5 100644 --- a/src/frontend/src/service_config.rs +++ b/src/frontend/src/service_config.rs @@ -20,6 +20,7 @@ pub mod otlp; pub mod pending_rows_batcher; pub mod postgres; pub mod prom_store; +pub mod promql_rollup_cache; pub use influxdb::{InfluxdbMergeMode, InfluxdbOptions}; pub use jaeger::JaegerOptions; @@ -30,3 +31,4 @@ pub use otlp::OtlpOptions; pub use pending_rows_batcher::{BatcherOptions, PendingRowsBatcherOptions}; pub use postgres::PostgresOptions; pub use prom_store::PromStoreOptions; +pub use promql_rollup_cache::PromqlRollupCacheOptions; diff --git a/src/frontend/src/service_config/promql_rollup_cache.rs b/src/frontend/src/service_config/promql_rollup_cache.rs new file mode 100644 index 00000000000..e43f9992851 --- /dev/null +++ b/src/frontend/src/service_config/promql_rollup_cache.rs @@ -0,0 +1,170 @@ +// 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::time::Duration; + +use common_base::readable_size::ReadableSize; +use common_stat::get_total_memory_readable; +use serde::{Deserialize, Serialize}; + +use crate::promql_query_cache::{ConfigError, PromqlRollupCacheConfig}; + +/// The fraction of the host or pod memory limit the cache may hold by default. +const MEMORY_FRACTION: u64 = 128; + +/// The smallest default budget, and the budget a host whose memory cannot be detected +/// gets. +const MIN_DEFAULT_BYTES: ReadableSize = ReadableSize::mb(32); + +/// The largest default budget, so a host with a lot of memory does not hand one +/// process-local query cache a share of it that nothing else can use. +const MAX_DEFAULT_BYTES: ReadableSize = ReadableSize::gb(8); + +/// Controls the frontend-local cache of PromQL range-query chunks. +/// +/// The cache is disabled by default. When enabled, a range query whose expression is +/// in the window allowlist is cut into canonical chunks, and a chunk a request has +/// read is reused until it reaches `ttl`. +/// +/// The defaults are the transitional, VM-style bounds of that opt-in cache: output +/// points within 5 minutes (`tail`) of wall-clock now bypass the cache, and a cached +/// chunk can be served for at most 30 minutes (`ttl`) from the read that produced it. +/// +/// Nothing probes the source: a chunk is served without the frontend asking whether +/// the data behind it moved, and `ttl` is the whole freshness rule. The cache is +/// therefore a bounded-staleness one — a write reaches a served chunk within `ttl`, +/// and a late write can stay invisible for that long — which is the trade it makes +/// for never reading the source on the request path. It does not detect late or +/// backfill writes: no automatic late/backfill invalidation, no per-write or +/// cross-frontend broadcast, and no epoch are added, so an entry leaves by aging out +/// or through the manual reset endpoint (`POST /debug/reset_promql_rollup_cache`), +/// which is served whenever the cache is enabled, behind the same HTTP auth as the +/// other `/debug` operational routes. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(default)] +pub struct PromqlRollupCacheOptions { + /// Whether range queries may be served from the cache. + pub enable: bool, + /// The total memory budget for cached chunks and their annotations. + /// + /// It defaults to 1/128 of the host or pod memory limit, at least 32MiB and at + /// most 8GiB, and to 32MiB when memory detection is unavailable. An explicit size + /// (`max_bytes = "1GiB"`) is used as it is. + pub max_bytes: ReadableSize, + /// The target chunk duration. It is global while the step belongs to the query, + /// so planning aligns it down to a whole number of the query's steps, at least + /// one: any step is cacheable, and the actual chunk stays fixed for that step. + #[serde(with = "humantime_serde")] + pub chunk: Duration, + /// Output points this close to wall-clock now may still be receiving data, + /// so they are executed directly and never cached. The default is 5 minutes: + /// that recent window is always read from storage and never enters the cache. + #[serde(with = "humantime_serde")] + pub tail: Duration, + /// How long a cached chunk is served, counted from the read that produced it. + /// The default is 30 minutes, which bounds how long a cached chunk can be served. + /// + /// It is the cache's whole freshness rule: no probe decides that a chunk is still + /// current, so this age alone bounds how stale a served answer may be. An entry + /// reaching it is dropped, and the next request for that chunk reads storage. + #[serde(with = "humantime_serde")] + pub ttl: Duration, +} + +impl Default for PromqlRollupCacheOptions { + fn default() -> Self { + Self { + enable: false, + max_bytes: default_max_bytes(get_total_memory_readable()), + chunk: Duration::from_secs(300), + tail: Duration::from_secs(300), + ttl: Duration::from_secs(1_800), + } + } +} + +/// The budget a host with `memory` usable bytes gets when none is configured. +fn default_max_bytes(memory: Option) -> ReadableSize { + memory + .map(|size| size / MEMORY_FRACTION) + .unwrap_or_default() + .max(MIN_DEFAULT_BYTES) + .min(MAX_DEFAULT_BYTES) +} + +impl PromqlRollupCacheOptions { + /// Validates the options and builds the cache configuration. + pub fn config(&self) -> Result { + PromqlRollupCacheConfig::new(self.max_bytes.0, self.tail, self.chunk, self.ttl) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_budget_follows_the_detected_memory() { + for (memory, expected) in [ + // Nothing detected, and a host too small for the fraction to reach the + // floor, both get the floor. + (None, ReadableSize::mb(32)), + (Some(ReadableSize(0)), ReadableSize::mb(32)), + (Some(ReadableSize::gb(1)), ReadableSize::mb(32)), + (Some(ReadableSize::gb(8)), ReadableSize::mb(64)), + (Some(ReadableSize::gb(32)), ReadableSize::mb(256)), + (Some(ReadableSize::gb(64)), ReadableSize::mb(512)), + // The cap holds however much memory the host reports. + (Some(ReadableSize::gb(1024)), ReadableSize::gb(8)), + ] { + assert_eq!(default_max_bytes(memory), expected, "memory: {memory:?}"); + } + } + + #[test] + fn an_explicit_budget_replaces_the_derived_one() { + let options: PromqlRollupCacheOptions = toml::from_str("max_bytes = \"1GiB\"").unwrap(); + assert_eq!(ReadableSize::gb(1), options.max_bytes); + assert_eq!(ReadableSize::gb(1).0, options.config().unwrap().max_bytes()); + + // An unset budget is the derived one, so a configuration that only enables the + // cache states nothing about memory and still gets a budget. + let options: PromqlRollupCacheOptions = toml::from_str("enable = true").unwrap(); + assert_eq!( + default_max_bytes(get_total_memory_readable()), + options.max_bytes + ); + } + + #[test] + fn zero_bounds_are_rejected() { + let options = PromqlRollupCacheOptions { + max_bytes: ReadableSize(0), + ..Default::default() + }; + assert_eq!(options.config(), Err(ConfigError::Bytes)); + + let options = PromqlRollupCacheOptions { + chunk: Duration::ZERO, + ..Default::default() + }; + assert_eq!(options.config(), Err(ConfigError::Chunk)); + + let options = PromqlRollupCacheOptions { + ttl: Duration::ZERO, + ..Default::default() + }; + assert_eq!(options.config(), Err(ConfigError::Ttl)); + } +} diff --git a/src/query/src/promql/planner.rs b/src/query/src/promql/planner.rs index b07990cbbc6..26911343ba6 100644 --- a/src/query/src/promql/planner.rs +++ b/src/query/src/promql/planner.rs @@ -17,7 +17,9 @@ mod function_plans; mod island; mod matching_filters; pub(crate) mod native; -pub use native::{NATIVE_PROMQL_EXTENSION_KEY, discovers_metric_name, native_promql_resolved}; +pub use native::{ + NATIVE_PROMQL_EXTENSION_KEY, discovers_metric_name, native_promql_resolved, plan_is_native, +}; mod set_operator; diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 1c443009e9f..a89c5b66882 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -2523,6 +2523,21 @@ fn split_exports_histogram_state(partial: &NativeTree) -> bool { } } +/// Whether `plan` was built by the native fused-series route. +/// +/// The native route is the one that builds a [`FusedSeries`] node; the legacy route never +/// does, so the absence of one is what makes a plan the legacy one. Both routes evaluate +/// the same expression on the same grid, so the plan itself is what tells them apart. +pub fn plan_is_native(plan: &LogicalPlan) -> bool { + if let LogicalPlan::Extension(extension) = plan { + let name = extension.node.name(); + if name == FusedSeries::name() || name == RawSeriesSource::name() { + return true; + } + } + plan.inputs().into_iter().any(plan_is_native) +} + /// Whether every plan is a scan of the same table, ignoring filters, projections and bounds. pub(crate) fn same_table_scans<'a>(plans: impl IntoIterator) -> bool { let mut table = None; diff --git a/src/servers/src/http/prometheus.rs b/src/servers/src/http/prometheus.rs index 1b8faa1e543..6611fa1e7aa 100644 --- a/src/servers/src/http/prometheus.rs +++ b/src/servers/src/http/prometheus.rs @@ -61,6 +61,7 @@ use serde::de::{self, MapAccess, Visitor}; use serde::{Deserialize, Serialize}; use serde_json::Value; use session::context::{Channel, QueryContext, QueryContextRef}; +use session::hints::PROMQL_ROLLUP_CACHE_NOCACHE; use snafu::{Location, OptionExt, ResultExt, ensure}; use store_api::metric_engine_consts::{ DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, LOGICAL_TABLE_METADATA_KEY, @@ -605,6 +606,7 @@ pub struct RangeQuery { lookback: Option, timeout: Option, db: Option, + nocache: Option, } #[axum_macros::debug_handler] @@ -631,6 +633,15 @@ pub async fn range_query( alias: None, }; + if params + .nocache + .or(form_params.nocache) + .as_deref() + .is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true")) + { + query_ctx.set_extension(PROMQL_ROLLUP_CACHE_NOCACHE, "true"); + } + // update catalog and schema in query context if necessary if let Err(error) = select_database( &mut query_ctx, @@ -2729,6 +2740,8 @@ mod tests { label_lookups: Mutex>>, queries: Mutex>, ordered_outputs: Mutex>, + /// Whether each executed query asked the rollup cache to stay out of it. + nocache: Mutex>, } #[async_trait::async_trait] @@ -2756,12 +2769,16 @@ mod tests { async fn do_query_parsed( &self, query: ParsedPromQuery, - _: QueryContextRef, + query_ctx: QueryContextRef, ) -> Result { self.ordered_outputs .lock() .unwrap() .push(query.requires_output_ordering()); + self.nocache + .lock() + .unwrap() + .push(query_ctx.extension(PROMQL_ROLLUP_CACHE_NOCACHE).is_some()); self.queries .lock() .unwrap() @@ -2943,6 +2960,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }); let app = axum::Router::new() .route( @@ -3027,6 +3045,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }); let ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME); if !explicit { @@ -3051,6 +3070,61 @@ mod tests { } } + #[tokio::test] + async fn range_query_honors_nocache_from_the_url_and_from_the_post_form() { + let handler = Arc::new(TestPrometheusHandler { + catalog_manager: MemoryCatalogManager::new(), + deny_operation: false, + denied_table: None, + metric_names: Vec::new(), + label_metric_names: Vec::new(), + label_lookups: Mutex::new(Vec::new()), + queries: Mutex::new(Vec::new()), + ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), + }); + let state: PrometheusHandlerRef = handler.clone(); + + // A client that fills the whole request as a form puts the flag in the body, + // which is where every other field of such a request already comes from. + for (url_nocache, form_nocache, expected) in [ + (None, Some("1"), true), + (None, Some("true"), true), + (None, None, false), + (Some("1"), None, true), + (Some("true"), None, true), + // The URL wins over the body, exactly as it does for the other fields. + (Some("0"), Some("1"), false), + ] { + range_query( + None, + State(state.clone()), + Query(RangeQuery { + nocache: url_nocache.map(str::to_string), + ..Default::default() + }), + Extension(QueryContext::with( + DEFAULT_CATALOG_NAME, + DEFAULT_SCHEMA_NAME, + )), + Form(RangeQuery { + query: Some("sort(vector(1))".to_string()), + start: Some("0".to_string()), + end: Some("1".to_string()), + step: Some("1s".to_string()), + nocache: form_nocache.map(str::to_string), + ..Default::default() + }), + ) + .await; + let recorded = *handler.nocache.lock().unwrap().last().unwrap(); + assert_eq!( + expected, recorded, + "url {url_nocache:?} against form {form_nocache:?}" + ); + } + } + #[tokio::test] async fn range_query_does_not_require_execution_output_ordering() { let handler = Arc::new(TestPrometheusHandler { @@ -3062,6 +3136,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }); let state: PrometheusHandlerRef = handler.clone(); instant_query( @@ -3119,6 +3194,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }); let response = range_query( None, @@ -3159,6 +3235,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }); let query_ctx = QueryContext::with("promql_timer_test", "parse_error"); let db = query_ctx.get_db_string(); @@ -3211,6 +3288,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }) } @@ -3363,6 +3441,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }) } @@ -3505,6 +3584,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }); let state: PrometheusHandlerRef = handler.clone(); let query_ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME); @@ -4225,6 +4305,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }); let ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME); let response = labels_query( @@ -4744,6 +4825,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), })), Query(MetadataQuery::default()), Extension(query_ctx.clone()), @@ -4760,6 +4842,7 @@ mod tests { label_lookups: Mutex::new(Vec::new()), queries: Mutex::new(Vec::new()), ordered_outputs: Mutex::new(Vec::new()), + nocache: Mutex::new(Vec::new()), }); let response = metadata_query( None, diff --git a/src/session/src/hints.rs b/src/session/src/hints.rs index 3ed4fd8dc2e..aecad7e4bf5 100644 --- a/src/session/src/hints.rs +++ b/src/session/src/hints.rs @@ -27,6 +27,8 @@ pub const LIVE_ANALYZE_METRICS_EXTENSION_KEY: &str = "query.live_analyze_metrics pub const INSERT_SKIP_WAL_HINT: &str = "insert_skip_wal"; pub const READ_PREFERENCE_HINT: &str = "read_preference"; +/// Extension key marking a query as not cacheable by the rollup cache. +pub const PROMQL_ROLLUP_CACHE_NOCACHE: &str = "internal.promql_rollup_cache_nocache"; pub const READ_PREFERENCE_EXTENSION_KEY: &str = "query.read_preference"; pub const RESERVED_EXTENSION_KEYS: [&str; 5] = [ REMOTE_QUERY_ID_EXTENSION_KEY, diff --git a/src/standalone/src/options.rs b/src/standalone/src/options.rs index a0d622fc907..76a40863cf2 100644 --- a/src/standalone/src/options.rs +++ b/src/standalone/src/options.rs @@ -29,7 +29,8 @@ use flow::FlowConfig; use frontend::frontend::FrontendOptions; use frontend::service_config::{ InfluxdbOptions, JaegerOptions, MysqlOptions, OpentsdbOptions, OtlpOptions, - PendingRowsBatcherOptions, PostgresOptions, PromStoreOptions, WriteRetryOptions, + PendingRowsBatcherOptions, PostgresOptions, PromStoreOptions, PromqlRollupCacheOptions, + WriteRetryOptions, }; use mito2::config::MitoConfig; use pipeline::PipelineOptions; @@ -106,6 +107,8 @@ pub struct StandaloneOptions { pub pipeline: PipelineOptions, /// The event recorder options. pub event_recorder: EventRecorderOptions, + /// The frontend-local cache of PromQL range-query chunks. + pub promql_rollup_cache: PromqlRollupCacheOptions, /// Environment variable keys to read and report in heartbeat messages. pub heartbeat_env_vars: Vec, } @@ -151,6 +154,7 @@ impl Default for StandaloneOptions { memory: MemoryOptions::default(), pipeline: PipelineOptions::default(), event_recorder: EventRecorderOptions::default(), + promql_rollup_cache: PromqlRollupCacheOptions::default(), heartbeat_env_vars: vec![], } } @@ -215,6 +219,7 @@ impl StandaloneOptions { slow_query: cloned_opts.slow_query, pipeline: cloned_opts.pipeline, event_recorder: cloned_opts.event_recorder, + promql_rollup_cache: cloned_opts.promql_rollup_cache, heartbeat_env_vars: cloned_opts.heartbeat_env_vars.clone(), ..Default::default() } diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index 17dccb7e905..b8c49316ec8 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -5199,6 +5199,12 @@ ignore_errors = false [event_recorder] ttl = "2months 29days 2h 52m 48s" + +[promql_rollup_cache] +enable = false +chunk = "5m" +tail = "5m" +ttl = "30m" "#, ) .trim() @@ -5221,6 +5227,7 @@ fn drop_lines_with_inconsistent_results(input: String) -> String { "cache_path =", "cache_capacity =", "trace_aux_cache_size =", + "max_bytes =", "memory_pool_size =", "sas_token =", "scope =",