feat(frontend): add TTL-based PromQL range cache (#10798)

* feat(frontend): add TTL-based PromQL range cache

Signed-off-by: discord9 <discord9@163.com>

* feat(frontend): add rollup cache reset endpoint

Signed-off-by: discord9 <discord9@163.com>

* feat(frontend): honor nocache for rollup cache

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): key rollup cache by table id and invalidate on DDL

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): set transitional rollup cache bounds

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): trim rollup cache to ttl and reset

Remove the reset token and all DDL/heartbeat invalidation so the
transitional cache has one freshness rule (ttl) and one manual escape
(reset). Charge variable-sized keys, honor POST-form nocache, fail on
schema changes instead of falling back, and drop duplicate TTL/dead
checks.

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): drop stale invalidation wording

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): bound rollup cache key and weight

Share one QueryIdentity across a plan's chunk keys, refuse chunks whose
weight does not fit a u32, and reject ttl values longer than moka accepts.
Clarify schema-mismatch and wall-clock tail docs.

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): regenerate config.md for rollup_cache tail

config/config.md was hand-updated and kept the previous wording of the
rollup_cache.tail comment. Run make config-docs so it matches the example
TOMLs, which is what CI checks.

Signed-off-by: discord9 <discord9@163.com>

* test(integration): expect rollup_cache in the /config snapshot

test_config_api compares the whole TOML the /config endpoint returns with a
hardcoded expectation. The rollup cache adds a [rollup_cache] section, so
append it with the values the frontend defaults serialize to.

Signed-off-by: discord9 <discord9@163.com>

* refactor(frontend): rename rollup cache to promql_rollup_cache

Rename the config key, the options and config types, the cache itself,
the instance accessors, the reset endpoint and the session hint so the
name says what is cached. query_cache becomes promql_query_cache for the
same reason: it holds PromQL range-query chunks only.

Signed-off-by: discord9 <discord9@163.com>

* feat(frontend): log the promql rollup cache config when enabled

Signed-off-by: discord9 <discord9@163.com>

* feat(frontend): size the promql rollup cache from system memory by default

Derive max_bytes from total memory like the OTLP trace aux cache
(1/128, floor 32MiB, cap 8GiB) instead of a fixed 256MiB, so a small
frontend does not give up a quarter of its memory and a large host gets
a useful budget. An explicit max_bytes still wins.

Signed-off-by: discord9 <discord9@163.com>

* refactor(frontend): move the promql rollup cache wiring out of instance.rs

Signed-off-by: discord9 <discord9@163.com>

* refactor(query): expose plan_is_native from the native planner

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): key promql rollup cache chunks on the output schema

The metric engine auto-alters a logical table when a new label arrives,
which keeps the table id but changes the schema. Keying on the id alone
let one request meet an old-schema hit with a new-schema fill and fail
until the ttl. The output schema of the built plan is now a key
dimension, so a schema change misses; a disagreement left after that is
a race with an ALTER, and the request bypasses to its original plan
instead of failing.

Signed-off-by: discord9 <discord9@163.com>

* perf(frontend): execute consecutive promql rollup cache misses as one window

A cold request executed every missed chunk as its own subwindow, each
re-reading the range its first point folds. Consecutive misses now run
as one window and the rows are split back into chunks before insert.

Signed-off-by: discord9 <discord9@163.com>

* perf(frontend): size promql rollup cache chunks in steps and drop empty-chunk guards

A fixed-time chunk holds chunk/step points and degrades to one point at
a large step: a 7d panel at a 10m step became 1008 single-point chunks
that all had to be looked up and merged even when warm. A chunk is now
at least MIN_CHUNK_STEPS points wide, so the chunk count tracks points
rather than range (7d at 10m: 50 chunks).

plan_chunks never emits an empty chunk, so the guards in lookup and
insert, the EmptyChunk bypass, Lookup::Bypass and Insert::Bypassed are
gone along with the two tests that built an empty key by hand.

Also applies the reviewer's doc suggestions and dedupes the tests that
asserted one behavior at three layers.

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): regenerate config.md for promql_rollup_cache

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): copy split promql rollup cache chunks before storing them

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): store empty promql rollup cache chunks as complete answers

Signed-off-by: discord9 <discord9@163.com>

* refactor(frontend): key the promql rollup cache on the arrow schema directly

Signed-off-by: discord9 <discord9@163.com>

* fix(frontend): only bypass the promql rollup cache for a set nocache hint

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): record that rollup cache annotations belong to the read

Signed-off-by: discord9 <discord9@163.com>

* perf(frontend): read contiguous direct spans as one window

Signed-off-by: discord9 <discord9@163.com>

* docs(frontend): fix stale rollup cache comments and pin lookback_ms

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-12-02 12:05:25 +00:00
committed by GitHub
parent d5ad08c1e3
commit 76209d6179
21 changed files with 4507 additions and 34 deletions
Generated
+1
View File
@@ -5738,6 +5738,7 @@ dependencies = [
"partition",
"pipeline",
"prometheus 0.14.0",
"promql",
"promql-parser",
"prost 0.14.1",
"query",
+12
View File
@@ -287,6 +287,12 @@
| `event_recorder.event_types` | Array | All | Event types to record. Current available event types: `create_database`,<br/>`alter_database`, `drop_database`, `create_flow`, `drop_flow`,<br/>`create_table`, `create_logical_tables`, `alter_table`, `alter_logical_tables`,<br/>`drop_table`, `undrop_table`, `purge_dropped_table`, `truncate_table`,<br/>`create_view`, `drop_view`, `admin_function`, `reconcile_catalog`,<br/>`reconcile_database`, `reconcile_table`, `reconcile_logical_tables`.<br/>When omitted, all current and future event types are recorded.<br/>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.<br/>When enabled, heap profiling will be activated if the `MALLOC_CONF` environment variable<br/>is set to "prof:true,prof_active:false". The official image adds this env variable.<br/>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.<br/>Defaults to 1/128 of the host or pod memory limit, with a minimum of 32MiB and a maximum of 8GiB.<br/>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<br/>aligns it down to a whole number of the query's steps, floored at 20 steps: any step is<br/>cacheable, the chunk of one step is one fixed length, and a coarse step is never cut into<br/>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.<br/>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<br/>the source, so this age is the cache's whole freshness rule: a write reaches a served chunk<br/>within it, and a late write can stay invisible for that long.<br/>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`.<br/>When omitted, all current and future event types are recorded.<br/>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.<br/>Defaults to 1/128 of the host or pod memory limit, with a minimum of 32MiB and a maximum of 8GiB.<br/>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<br/>aligns it down to a whole number of the query's steps, floored at 20 steps: any step is<br/>cacheable, the chunk of one step is one fixed length, and a coarse step is never cut into<br/>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.<br/>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<br/>the source, so this age is the cache's whole freshness rule: a write reaches a served chunk<br/>within it, and a late write can stay invisible for that long.<br/>Default is `30m`, which bounds how long a cached chunk is served, and therefore how stale a served answer may be. |
### Metasrv
+23
View File
@@ -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"
+23
View File
@@ -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"
+1
View File
@@ -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
+8
View File
@@ -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,
+5 -1
View File
@@ -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<String>,
}
@@ -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![],
}
}
+602 -29
View File
@@ -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<RequestLimiter>,
otlp_resource_info: bool,
suspend: Arc<AtomicBool>,
/// 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<Arc<PromqlRollupCache>>,
}
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<PromqlRollupCache>> {
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<AtomicBool> {
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<Statement> {
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<SendableRecordBatchStream, BoxedError> {
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<RecordBatches> {
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<crate::promql_query_cache::PromqlRollupCache> {
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<Arc<crate::promql_query_cache::PromqlRollupCache>>,
) -> TestResult<Instance> {
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<Option<RecordBatches>> {
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<RecordBatches> {
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<TableRef>,
procedure_executor: ProcedureExecutorRef,
) -> TestResult<Instance> {
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<catalog::memory::MemoryCatalogManager>,
target_table: TableRef,
plugins: Plugins,
metric_names_table: Option<TableRef>,
procedure_executor: ProcedureExecutorRef,
promql_rollup_cache: Option<Arc<crate::promql_query_cache::PromqlRollupCache>>,
) -> TestResult<Instance> {
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(
+38 -1
View File
@@ -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<Arc<PromqlRollupCache>>,
}
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<PromqlRollupCache>) -> 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,
})
}
}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -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;
File diff suppressed because it is too large Load Diff
+145
View File
@@ -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::<RouterConfigurator>() {
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<crate::promql_query_cache::PromqlRollupCache>,
) {
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::<UserProviderRef>(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
+2
View File
@@ -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;
@@ -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>) -> 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, ConfigError> {
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));
}
}
+3 -1
View File
@@ -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;
+15
View File
@@ -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<Item = &'a LogicalPlan>) -> bool {
let mut table = None;
+84 -1
View File
@@ -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<String>,
timeout: Option<String>,
db: Option<String>,
nocache: Option<String>,
}
#[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<Vec<Vec<Matcher>>>,
queries: Mutex<Vec<String>>,
ordered_outputs: Mutex<Vec<bool>>,
/// Whether each executed query asked the rollup cache to stay out of it.
nocache: Mutex<Vec<bool>>,
}
#[async_trait::async_trait]
@@ -2756,12 +2769,16 @@ mod tests {
async fn do_query_parsed(
&self,
query: ParsedPromQuery,
_: QueryContextRef,
query_ctx: QueryContextRef,
) -> Result<Output> {
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,
+2
View File
@@ -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,
+6 -1
View File
@@ -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<String>,
}
@@ -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()
}
+7
View File
@@ -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 =",