diff --git a/.github/scripts/query-regression-run.py b/.github/scripts/query-regression-run.py index 9b3ae9e2af7..ec74d508429 100644 --- a/.github/scripts/query-regression-run.py +++ b/.github/scripts/query-regression-run.py @@ -48,6 +48,10 @@ DEFAULT_CASES = [ HEAVY_CASES = [ "tests/perf/query_cases/prom_remote_write_7913/case.toml", + # The rollup cache case compares a candidate-only frontend feature against + # an uncached base, so it is a feature measurement rather than a routine + # scan-path gate: run it on demand, not on every PR. + "tests/perf/query_cases/prom_rollup_cache_warm_range/case.toml", # High-cardinality direct-SST cases exceed the default query-regression # runner's resources (the self-hosted runner is repeatedly lost during the # run). Keep them in the heavy set so they only run on demand. @@ -449,6 +453,7 @@ def run_remote_case( render = [ str(runner), "render-remote-config", "--case", str(case_path), "--fixture-generator", str(fixture_generator), + "--target", target.name, "--output", str(target.frontend_config), ] render_status = subprocess.run(render, check=False).returncode diff --git a/src/cmd/src/bin/query_perf_fixture/case.rs b/src/cmd/src/bin/query_perf_fixture/case.rs index 271c3928e35..ccb9a8e636d 100644 --- a/src/cmd/src/bin/query_perf_fixture/case.rs +++ b/src/cmd/src/bin/query_perf_fixture/case.rs @@ -161,6 +161,11 @@ pub(super) struct PromStoreConfig { pub(super) worker_channel_capacity: u64, #[serde(default = "default_max_inflight_requests")] pub(super) max_inflight_requests: u64, + /// Rollup cache rendered only into the candidate frontend configuration. The + /// base renders no `[promql_rollup_cache]` table at all, so a case that sets + /// this compares an uncached base against a cached candidate. + #[serde(default)] + pub(super) candidate_promql_rollup_cache: Option, } impl Default for PromStoreConfig { @@ -171,10 +176,30 @@ impl Default for PromStoreConfig { max_concurrent_flushes: default_max_concurrent_flushes(), worker_channel_capacity: default_worker_channel_capacity(), max_inflight_requests: default_max_inflight_requests(), + candidate_promql_rollup_cache: None, } } } +/// The frontend `[promql_rollup_cache]` section, as the strings the frontend +/// parses itself. +/// +/// `max_bytes` is a `ReadableSize` (`256MB`) and the three durations are +/// `humantime` (`5m`, `10m`, `1h`), so a case can express any value the frontend +/// accepts without this schema re-implementing its parsers. An unset field is not +/// rendered, so the frontend default applies. +#[derive(Debug, Deserialize, Serialize)] +pub(super) struct PromqlRollupCacheConfig { + #[serde(default)] + pub(super) max_bytes: Option, + #[serde(default)] + pub(super) chunk: Option, + #[serde(default)] + pub(super) tail: Option, + #[serde(default)] + pub(super) ttl: Option, +} + pub(super) fn default_pending_rows_flush_interval() -> String { "1s".to_string() } @@ -443,6 +468,8 @@ pub(super) fn default_parallelism() -> u64 { #[cfg(test)] mod tests { + use serde_json::json; + use super::*; #[test] @@ -496,6 +523,66 @@ candidate_setup_sql = ["CREATE TABLE candidate_table", "ALTER TABLE candidate_ta ] ); } + + fn plan_cache_json(case: &CaseFile) -> serde_json::Value { + let json = serde_json::to_value(case).unwrap(); + json["scenario"]["remote_write"]["prom_store"]["candidate_promql_rollup_cache"].clone() + } + + #[test] + fn rollup_cache_plan_json_carries_the_fields_the_case_sets() { + let case: CaseFile = toml::from_str( + r#" +[scenario] +kind = "prom_remote_write_then_query" + +[scenario.remote_write] +metric = "metric" +"#, + ) + .unwrap(); + assert_eq!(serde_json::Value::Null, plan_cache_json(&case)); + + let case: CaseFile = toml::from_str( + r#" +[scenario] +kind = "prom_remote_write_then_query" + +[scenario.remote_write] +metric = "metric" + +[scenario.remote_write.prom_store.candidate_promql_rollup_cache] +max_bytes = "256MB" +chunk = "1m" +tail = "0s" +ttl = "1h" +"#, + ) + .unwrap(); + assert_eq!( + json!({"max_bytes": "256MB", "chunk": "1m", "tail": "0s", "ttl": "1h"}), + plan_cache_json(&case) + ); + + let case: CaseFile = toml::from_str( + r#" +[scenario] +kind = "prom_remote_write_then_query" + +[scenario.remote_write] +metric = "metric" + +[scenario.remote_write.prom_store.candidate_promql_rollup_cache] +tail = "0s" +ttl = "1h" +"#, + ) + .unwrap(); + assert_eq!( + json!({"max_bytes": null, "chunk": null, "tail": "0s", "ttl": "1h"}), + plan_cache_json(&case) + ); + } } impl Scenario { diff --git a/src/cmd/src/bin/query_regression_runner/measure.rs b/src/cmd/src/bin/query_regression_runner/measure.rs index d350c1a4556..92edeefad59 100644 --- a/src/cmd/src/bin/query_regression_runner/measure.rs +++ b/src/cmd/src/bin/query_regression_runner/measure.rs @@ -574,6 +574,11 @@ pub(super) fn round_ties_even(value: f64) -> isize { } } +/// The threshold that requires the candidate to be faster: the share of the base +/// median latency it has to save. A feature case sets it so a feature that did not +/// take effect fails instead of passing with base-equal latency. +const MIN_CANDIDATE_LATENCY_SPEEDUP_PCT: &str = "min_candidate_latency_speedup_pct"; + fn enforce_thresholds( queries: &[Query], base: &QueryResult, @@ -617,10 +622,36 @@ fn enforce_thresholds( }; results.push(result); } - for key in thresholds - .keys() - .filter(|key| *key != "max_candidate_latency_regression_pct") + if let Some(limit) = thresholds + .get(MIN_CANDIDATE_LATENCY_SPEEDUP_PCT) + .filter(|value| !value.is_null()) + .map(value_as_f64) + .transpose()? { + let result = match base_measurement { + None => { + json!({"query": candidate_measurement.name, "threshold": MIN_CANDIDATE_LATENCY_SPEEDUP_PCT, "status": "failed", "reason": "missing base measurement"}) + } + Some(base) if matches!(base.latency_ms_median, None | Some(0.0)) => { + json!({"query": candidate_measurement.name, "threshold": MIN_CANDIDATE_LATENCY_SPEEDUP_PCT, "status": "failed", "reason": "base median latency is missing or zero", "base_latency_ms_median": base.latency_ms_median}) + } + Some(_) if candidate_measurement.latency_ms_median.is_none() => { + json!({"query": candidate_measurement.name, "threshold": MIN_CANDIDATE_LATENCY_SPEEDUP_PCT, "status": "failed", "reason": "missing candidate measurement"}) + } + Some(base) => { + let actual = (base.latency_ms_median.unwrap() + - candidate_measurement.latency_ms_median.unwrap()) + / base.latency_ms_median.unwrap() + * 100.0; + json!({"query": candidate_measurement.name, "threshold": MIN_CANDIDATE_LATENCY_SPEEDUP_PCT, "status": if actual >= limit { "passed" } else { "failed" }, "actual_pct": actual, "limit_pct": limit}) + } + }; + results.push(result); + } + for key in thresholds.keys().filter(|key| { + *key != "max_candidate_latency_regression_pct" + && *key != MIN_CANDIDATE_LATENCY_SPEEDUP_PCT + }) { results.push(json!({"query": candidate_measurement.name, "threshold": key, "status": "failed", "reason": "unsupported threshold"})); } } @@ -1032,4 +1063,70 @@ mod tests { assert!(excerpt.ends_with('…')); assert_eq!(plan_excerpt("short"), "short"); } + + fn speedup_query(limit: f64) -> Query { + Query { + name: Some("q".to_string()), + kind: Some("prom_http".to_string()), + query: "q".to_string(), + start: None, + end: None, + step: None, + warmup: 0, + iterations: 3, + thresholds: Map::from_iter([( + MIN_CANDIDATE_LATENCY_SPEEDUP_PCT.to_string(), + json!(limit), + )]), + require_native: false, + } + } + + fn measured_result(median: f64) -> QueryResult { + QueryResult { + validation: vec![], + validation_errors: vec![], + measurements: vec![Measurement { + name: Some("q".to_string()), + kind: Some("prom_http".to_string()), + iterations: 3, + samples: vec![], + latency_ms_median: Some(median), + latency_ms_p95: Some(median), + status: "ok".to_string(), + }], + status: "ok".to_string(), + } + } + + #[test] + fn speedup_threshold_requires_a_faster_candidate() { + let base = measured_result(200.0); + let candidate = measured_result(20.0); + let results = enforce_thresholds(&[speedup_query(50.0)], &base, &candidate).unwrap(); + assert_eq!(1, results.len()); + assert_eq!("passed", results[0]["status"]); + assert_eq!(results[0]["actual_pct"], json!(90.0)); + + // The same case with the cache silently ineffective. + let candidate = measured_result(200.0); + let results = enforce_thresholds(&[speedup_query(50.0)], &base, &candidate).unwrap(); + assert_eq!("failed", results[0]["status"]); + assert_eq!(results[0]["actual_pct"], json!(0.0)); + assert_eq!(results[0]["limit_pct"], json!(50.0)); + } + + #[test] + fn speedup_threshold_fails_without_a_base_measurement() { + let base = QueryResult { + validation: vec![], + validation_errors: vec![], + measurements: vec![], + status: "ok".to_string(), + }; + let results = + enforce_thresholds(&[speedup_query(50.0)], &base, &measured_result(20.0)).unwrap(); + assert_eq!("failed", results[0]["status"]); + assert_eq!("missing base measurement", results[0]["reason"]); + } } diff --git a/src/cmd/src/bin/query_regression_runner/mod.rs b/src/cmd/src/bin/query_regression_runner/mod.rs index 9ed903f5e07..5661d2b2b80 100644 --- a/src/cmd/src/bin/query_regression_runner/mod.rs +++ b/src/cmd/src/bin/query_regression_runner/mod.rs @@ -15,7 +15,7 @@ use std::error::Error; use std::path::PathBuf; -use clap::{Parser, Subcommand}; +use clap::{Parser, Subcommand, ValueEnum}; mod direct; mod materialize; @@ -97,10 +97,23 @@ struct RenderRemoteConfigArgs { case: PathBuf, #[arg(long, value_name = "PATH")] fixture_generator: PathBuf, + /// Which target's frontend configuration to render: only the candidate side + /// gets the case's `candidate_promql_rollup_cache`. The default is the base + /// side, because a candidate rendered without its cache fails its thresholds + /// loudly while the opposite mistake passes quietly. + #[arg(long, value_enum, default_value_t = RemoteTarget::Base)] + target: RemoteTarget, #[arg(long, value_name = "PATH")] output: PathBuf, } +/// The cluster a rendered frontend configuration belongs to. +#[derive(Clone, Copy, Debug, ValueEnum)] +enum RemoteTarget { + Base, + Candidate, +} + #[derive(Debug, Parser)] struct PrepareRemoteArgs { #[arg(long, value_name = "PATH")] diff --git a/src/cmd/src/bin/query_regression_runner/model.rs b/src/cmd/src/bin/query_regression_runner/model.rs index 92da663aec4..1c976c4f755 100644 --- a/src/cmd/src/bin/query_regression_runner/model.rs +++ b/src/cmd/src/bin/query_regression_runner/model.rs @@ -133,6 +133,19 @@ pub(super) struct PromStore { pub(super) max_concurrent_flushes: u64, pub(super) worker_channel_capacity: u64, pub(super) max_inflight_requests: u64, + /// Rollup cache rendered into the candidate frontend configuration only. + #[serde(default)] + pub(super) candidate_promql_rollup_cache: Option, +} + +/// The frontend `[promql_rollup_cache]` section as the strings the frontend +/// parses. An unset bound is not rendered, so the frontend default applies. +#[derive(Clone, Debug, Deserialize)] +pub(super) struct PromqlRollupCache { + pub(super) max_bytes: Option, + pub(super) chunk: Option, + pub(super) tail: Option, + pub(super) ttl: Option, } #[derive(Clone, Debug, Deserialize)] diff --git a/src/cmd/src/bin/query_regression_runner/remote/ingest.rs b/src/cmd/src/bin/query_regression_runner/remote/ingest.rs index 271e27fac42..aa255dcf903 100644 --- a/src/cmd/src/bin/query_regression_runner/remote/ingest.rs +++ b/src/cmd/src/bin/query_regression_runner/remote/ingest.rs @@ -20,28 +20,63 @@ use std::time::{Duration, Instant}; use reqwest::Client; use serde_json::{Value, json}; -use crate::query_regression_runner::model::{PromStore, RemoteWrite}; +use crate::query_regression_runner::model::{PromStore, PromqlRollupCache, RemoteWrite}; use crate::query_regression_runner::plan::normalized_remote_write; use crate::query_regression_runner::sql::{ extract_count_value, http_post_sql, sql_ident, sql_string, value_f64, value_u64, }; -use crate::query_regression_runner::{PrepareRemoteArgs, RenderRemoteConfigArgs, Result}; +use crate::query_regression_runner::{ + PrepareRemoteArgs, RemoteTarget, RenderRemoteConfigArgs, Result, +}; pub(super) async fn run_render_remote_config(args: RenderRemoteConfigArgs) -> Result<()> { let (_, remote) = normalized_remote_write(&args.fixture_generator, &args.case)?; - fs::write(args.output, frontend_prom_config(&remote.prom_store)?)?; + fs::write( + args.output, + frontend_prom_config(&remote.prom_store, args.target)?, + )?; Ok(()) } -fn frontend_prom_config(prom: &PromStore) -> Result { - Ok(format!( +/// Renders the frontend configuration of one target. +/// +/// `[prom_store]` is identical for both targets, because both ingest the same +/// case. The base render writes no `[promql_rollup_cache]` table at all, so it +/// keeps the frontend default (disabled) and a case that sets +/// `candidate_promql_rollup_cache` compares an uncached base against a cached +/// candidate. +fn frontend_prom_config(prom: &PromStore, target: RemoteTarget) -> Result { + let mut text = format!( "[prom_store]\nenable = true\nwith_metric_engine = true\npending_rows_flush_interval = {}\nmax_batch_rows = {}\nmax_concurrent_flushes = {}\nworker_channel_capacity = {}\nmax_inflight_requests = {}\n", serde_json::to_string(&prom.pending_rows_flush_interval)?, prom.max_batch_rows, prom.max_concurrent_flushes, prom.worker_channel_capacity, prom.max_inflight_requests, - )) + ); + if let (RemoteTarget::Candidate, Some(cache)) = (target, &prom.candidate_promql_rollup_cache) { + text.push_str(&render_promql_rollup_cache(cache)?); + } + Ok(text) +} + +/// Renders the `[promql_rollup_cache]` table with the units the frontend parses. +/// +/// Only the bounds the case sets are written, so every other value stays the +/// frontend's own default. Naming the table is what enables the cache. +fn render_promql_rollup_cache(cache: &PromqlRollupCache) -> Result { + let mut text = String::from("\n[promql_rollup_cache]\nenable = true\n"); + for (key, value) in [ + ("max_bytes", &cache.max_bytes), + ("chunk", &cache.chunk), + ("tail", &cache.tail), + ("ttl", &cache.ttl), + ] { + if let Some(value) = value { + text.push_str(&format!("{key} = {}\n", serde_json::to_string(value)?)); + } + } + Ok(text) } pub(super) async fn run_prepare_remote(args: PrepareRemoteArgs) -> Result<()> { @@ -467,6 +502,74 @@ mod tests { use super::*; use crate::query_regression_runner::model::{PromStore, RemoteValue}; + fn prom_store(candidate_promql_rollup_cache: Option) -> PromStore { + PromStore { + pending_rows_flush_interval: "1s".to_string(), + max_batch_rows: 100_000, + max_concurrent_flushes: 256, + worker_channel_capacity: 65_536, + max_inflight_requests: 3_000, + candidate_promql_rollup_cache, + } + } + + #[test] + fn renders_prom_store_alone_when_no_rollup_cache_is_configured() { + let config = frontend_prom_config(&prom_store(None), RemoteTarget::Base).unwrap(); + assert_eq!( + "[prom_store]\nenable = true\nwith_metric_engine = true\n\ + pending_rows_flush_interval = \"1s\"\nmax_batch_rows = 100000\n\ + max_concurrent_flushes = 256\nworker_channel_capacity = 65536\n\ + max_inflight_requests = 3000\n", + config + ); + assert_eq!( + config, + frontend_prom_config(&prom_store(None), RemoteTarget::Candidate).unwrap() + ); + } + + #[test] + fn the_runner_reads_the_fixture_rollup_cache_json_without_defaults() { + // The plan JSON the query_perf_fixture test pins, read as the runner does. + let cache: PromqlRollupCache = + serde_json::from_str(r#"{"max_bytes":"256MB","chunk":"5m","tail":"0s","ttl":"1h"}"#) + .unwrap(); + assert_eq!(Some("256MB"), cache.max_bytes.as_deref()); + assert_eq!(Some("5m"), cache.chunk.as_deref()); + assert_eq!(Some("0s"), cache.tail.as_deref()); + assert_eq!(Some("1h"), cache.ttl.as_deref()); + + let cache: PromqlRollupCache = + serde_json::from_str(r#"{"max_bytes":null,"chunk":null,"tail":"0s","ttl":"1h"}"#) + .unwrap(); + assert_eq!(None, cache.max_bytes); + assert_eq!(None, cache.chunk); + assert_eq!( + Some("0s"), + cache.tail.as_deref(), + "not the frontend default" + ); + assert_eq!(Some("1h"), cache.ttl.as_deref()); + } + + #[test] + fn the_candidate_render_writes_only_the_bounds_the_case_sets() { + let store = prom_store(Some( + serde_json::from_str(r#"{"max_bytes":null,"chunk":null,"tail":"0s","ttl":"1h"}"#) + .unwrap(), + )); + let base = frontend_prom_config(&store, RemoteTarget::Base).unwrap(); + assert!(!base.contains("[promql_rollup_cache]")); + + let candidate = frontend_prom_config(&store, RemoteTarget::Candidate).unwrap(); + assert!( + candidate + .ends_with("\n[promql_rollup_cache]\nenable = true\ntail = \"0s\"\nttl = \"1h\"\n"), + "{candidate}" + ); + } + async fn read_http_request(stream: &mut TcpStream) -> Vec { let mut request = Vec::new(); let mut chunk = [0; 1024]; @@ -588,6 +691,7 @@ mod tests { max_concurrent_flushes: 1, worker_channel_capacity: 1, max_inflight_requests: 1, + candidate_promql_rollup_cache: None, }, value: RemoteValue { pattern: "linear".to_string(), diff --git a/tests-integration/src/standalone.rs b/tests-integration/src/standalone.rs index 9a6c5030f8e..b1dcafea463 100644 --- a/tests-integration/src/standalone.rs +++ b/tests-integration/src/standalone.rs @@ -51,7 +51,9 @@ use frontend::frontend::Frontend; use frontend::instance::Instance; use frontend::instance::builder::FrontendBuilder; use frontend::server::Services; -use frontend::service_config::{BatcherOptions, PendingRowsBatcherOptions}; +use frontend::service_config::{ + BatcherOptions, PendingRowsBatcherOptions, PromqlRollupCacheOptions, +}; use meta_srv::metasrv::{FLOW_ID_SEQ, TABLE_ID_SEQ}; use servers::grpc::GrpcOptions; use standalone::options::StandaloneOptions; @@ -102,6 +104,7 @@ pub struct GreptimeDbStandaloneBuilder { mito_config: Option, query_options: query::options::QueryOptions, pipeline_options: pipeline::PipelineOptions, + promql_rollup_cache: Option, } impl GreptimeDbStandaloneBuilder { @@ -127,9 +130,18 @@ impl GreptimeDbStandaloneBuilder { mito_config: None, query_options: query::options::QueryOptions::default(), pipeline_options: pipeline::PipelineOptions::default(), + promql_rollup_cache: None, } } + /// Installs the frontend rollup cache with these options; it is disabled + /// unless this is called. + #[must_use] + pub fn with_promql_rollup_cache(mut self, options: PromqlRollupCacheOptions) -> Self { + self.promql_rollup_cache = Some(options); + self + } + /// Overrides query options for this standalone test instance. #[must_use] pub fn with_query_options(mut self, options: query::options::QueryOptions) -> Self { @@ -451,6 +463,7 @@ impl GreptimeDbStandaloneBuilder { .auto_create_physical_table_timestamp_unit .unwrap_or(common_time::timestamp::TimeUnit::Millisecond), pipeline: self.pipeline_options.clone(), + promql_rollup_cache: self.promql_rollup_cache.clone().unwrap_or_default(), max_in_flight_write_bytes: self.max_in_flight_write_bytes, pending_rows_batcher: PendingRowsBatcherOptions { logical_table: self.logical_batcher.clone(), diff --git a/tests-integration/src/tests/instance_test.rs b/tests-integration/src/tests/instance_test.rs index fe9e39758c7..8041c54e7ad 100644 --- a/tests-integration/src/tests/instance_test.rs +++ b/tests-integration/src/tests/instance_test.rs @@ -14,6 +14,7 @@ use std::env; use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use client::{DEFAULT_SCHEMA_NAME, OutputData}; use common_catalog::consts::{DEFAULT_CATALOG_NAME, METRICS_EXEMPLARS_TABLE}; @@ -28,6 +29,7 @@ use datatypes::arrow::array::{ }; use frontend::error::Error; use frontend::instance::Instance; +use frontend::service_config::PromqlRollupCacheOptions; use operator::error::Error as OperatorError; use query::datafusion::QUERY_PARALLELISM_HINT; use query::options::QUERY_ENABLE_REMOTE_DYNAMIC_FILTER_PUSHDOWN; @@ -38,12 +40,240 @@ use servers::query_handler::sql::SqlQueryHandler; use session::context::{QueryContext, QueryContextRef}; use crate::tests::test_util::{ - MockInstance, both_instances_cases, both_instances_cases_with_custom_storages, + MockInstance, PromRangeQuery, both_instances_cases, both_instances_cases_with_custom_storages, check_unordered_output_stream, create_local_file_test_dir, distributed, - distributed_with_multiple_object_stores, find_testing_resource, prepare_path, standalone, - standalone_instance_case, standalone_with_multiple_object_stores, + distributed_with_multiple_object_stores, find_testing_resource, prepare_path, + prometheus_http_app, promql_range_points, rollup_cache_options, standalone, + standalone_instance_case, standalone_with_multiple_object_stores, standalone_with_rollup_cache, + standalone_with_rollup_cache_options, }; +/// One point per minute from 20 to 65 minutes past the epoch, in milliseconds. +/// +/// The window starts on a chunk bound because chunk bounds are canonical: a chunk +/// is twenty steps, so its bounds are multiples of twenty minutes and a window +/// that does not start on one holds no whole chunk. +fn cache_ts_ms() -> Vec { + (20..=65).map(|minute| minute * 60_000).collect() +} + +/// The answer of a cache test's range query: every point reads `default`, except +/// the points named in `overrides`, which are `(minute, value)`. +fn cache_answer(default: f64, overrides: &[(i64, f64)]) -> Vec<(i64, f64)> { + cache_ts_ms() + .into_iter() + .map(|ts| { + let value = overrides + .iter() + .find(|(minute, _)| ts == minute * 60_000) + .map(|(_, value)| *value) + .unwrap_or(default); + (ts, value) + }) + .collect() +} + +/// A tail that lands inside the fixed data window: the tail is measured from the +/// wall clock and the data is in 1970, so a recorded duration would leave every +/// point cacheable. "From now back to 43:30 past the epoch" puts the cutoff between +/// the 43rd and the 44th minute. +fn cache_tail_ending_at_4330() -> Duration { + const CUTOFF_MS: u128 = 2_610_000; + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("the test clock is past the epoch") + .as_millis(); + Duration::from_millis(u64::try_from(now_ms - CUTOFF_MS).expect("the test clock is past 1970")) +} + +fn cache_options_with_tail(tail: Duration) -> PromqlRollupCacheOptions { + PromqlRollupCacheOptions { + tail, + ..rollup_cache_options() + } +} + +async fn create_cache_table(frontend: &Arc, table: &str) { + execute_sql( + frontend, + &format!( + "CREATE TABLE {table} (host STRING PRIMARY KEY, ts TIMESTAMP(3) TIME INDEX, val DOUBLE)" + ), + ) + .await; + let rows = cache_ts_ms() + .into_iter() + .map(|ts| format!("('a', {ts}, 1.0)")) + .collect::>() + .join(", "); + execute_sql( + frontend, + &format!("INSERT INTO {table} (host, ts, val) VALUES {rows}"), + ) + .await; +} + +async fn write_cache_point(frontend: &Arc, table: &str, minute: i64, value: f64) { + execute_sql( + frontend, + &format!( + "INSERT INTO {table} (host, ts, val) VALUES ('a', {}, {value})", + minute * 60_000 + ), + ) + .await; +} + +async fn stored_cache_point(frontend: &Arc, table: &str, minute: i64) -> String { + let output = execute_sql( + frontend, + &format!("SELECT val FROM {table} WHERE ts = {}", minute * 60_000), + ) + .await; + output.data.pretty_print().await +} + +/// The range a cache test queries: every point from 20 to 65 minutes, folding one +/// minute of lookback each. +fn cache_range_query(query: &str) -> PromRangeQuery<'_> { + PromRangeQuery::new(query, "1200", "3900", "60", "60") +} + +/// A repeated range is served from memory, except the part inside the tail: the +/// 20..39 minute points are one whole chunk, 40..43 the partial chunk that is never +/// keyed as a whole one, and 44..65 the tail. +/// +/// A row written after the fill separates the two paths: the tail re-reads storage +/// and reports it, the cached chunk keeps answering what it read. +#[tokio::test] +async fn test_rollup_cache_ttl_hit_and_tail_bypass() { + let instance = + standalone_with_rollup_cache_options(cache_options_with_tail(cache_tail_ending_at_4330())) + .await; + let frontend = instance.frontend(); + create_cache_table(&frontend, "cache_hit").await; + let cache = frontend + .promql_rollup_cache() + .expect("the test instance installs the cache") + .clone(); + let app = prometheus_http_app(&frontend); + let query = cache_range_query("sum(cache_hit)"); + + let cold = promql_range_points(&app, &query).await; + assert_eq!(cache_answer(1.0, &[]), cold, "one point per minute"); + assert_eq!(0, cache.hit_count(), "a cold request serves nothing"); + assert_eq!( + 1, + cache.entry_count(), + "the request filled the one whole chunk before the tail" + ); + + // The same range again: the whole chunk is served from memory, and the spans + // outside it (the 40..43 minute edge and the 44..65 minute tail) are executed. + let warm = promql_range_points(&app, &query).await; + assert_eq!(cache_answer(1.0, &[]), warm); + assert_eq!(1, cache.hit_count(), "the repeat hit the one chunk"); + assert_eq!(1, cache.entry_count(), "a hit stores nothing new"); + + // Two rows move: one inside the cached chunk, one inside the tail. + write_cache_point(&frontend, "cache_hit", 30, 2.5).await; + write_cache_point(&frontend, "cache_hit", 44, 2.5).await; + assert!( + stored_cache_point(&frontend, "cache_hit", 30) + .await + .contains("2.5"), + "the write reached storage" + ); + + let after_write = promql_range_points(&app, &query).await; + assert_eq!( + cache_answer(1.0, &[(44, 2.5)]), + after_write, + "the tail re-read storage, the cached chunk answered what it read" + ); + assert_eq!( + 2, + cache.hit_count(), + "the second repeat hit the chunk again" + ); + assert_eq!(1, cache.entry_count(), "the tail filled nothing"); +} + +/// The internal reset drops every entry, so the next request reads storage again; +/// `nocache=1` reads storage without touching the cache, which the request after it +/// shows by still answering from the entry the reset's request filled. +#[tokio::test] +async fn test_rollup_cache_reset_and_nocache() { + let instance = standalone_with_rollup_cache().await; + let frontend = instance.frontend(); + create_cache_table(&frontend, "cache_reset").await; + let cache = frontend + .promql_rollup_cache() + .expect("the test instance installs the cache") + .clone(); + let app = prometheus_http_app(&frontend); + let query = cache_range_query("sum(cache_reset)"); + + // Two whole chunks cover 20..59 minutes, and the 60th minute starts a third + // one the request does not fill, so 60..65 are read directly. + let chunks = 2; + let cold = promql_range_points(&app, &query).await; + assert_eq!(cache_answer(1.0, &[]), cold, "one point per minute"); + assert_eq!(0, cache.hit_count(), "a cold request serves nothing"); + assert_eq!(chunks, cache.entry_count(), "and fills both chunks"); + + let warm = promql_range_points(&app, &query).await; + assert_eq!(cache_answer(1.0, &[]), warm); + assert_eq!( + chunks, + cache.hit_count(), + "the repeat is served from both chunks" + ); + assert_eq!(chunks, cache.entry_count(), "a hit stores nothing new"); + + // Move a row of the cached chunk, so a request that reads storage can be told + // apart from one that answers from memory. + write_cache_point(&frontend, "cache_reset", 30, 2.5).await; + + frontend.clear_promql_rollup_cache(); + assert_eq!(0, cache.entry_count(), "the reset drops every entry"); + let refilled = promql_range_points(&app, &query).await; + assert_eq!( + cache_answer(1.0, &[(30, 2.5)]), + refilled, + "the request after the reset reports what storage holds now" + ); + assert_eq!( + chunks, + cache.hit_count(), + "that request served nothing from memory" + ); + assert_eq!(chunks, cache.entry_count(), "and filled the chunks again"); + + write_cache_point(&frontend, "cache_reset", 30, 3.5).await; + let bypassed = + promql_range_points(&app, &cache_range_query("sum(cache_reset)").without_cache()).await; + assert_eq!( + cache_answer(1.0, &[(30, 3.5)]), + bypassed, + "nocache=1 reads storage instead of the entry" + ); + assert_eq!(chunks, cache.hit_count(), "nocache=1 hit neither chunk"); + assert_eq!(chunks, cache.entry_count(), "and left both chunks in place"); + + let served = promql_range_points(&app, &query).await; + assert_eq!( + cache_answer(1.0, &[(30, 2.5)]), + served, + "the entry outlived the bypassing request" + ); + assert_eq!( + 2 * chunks, + cache.hit_count(), + "the request after it hit both chunks" + ); +} + #[apply(both_instances_cases)] async fn test_sparse_primary_key_schema_validation(instance: Arc) { let instance = instance.frontend(); diff --git a/tests-integration/src/tests/test_util.rs b/tests-integration/src/tests/test_util.rs index 9a0ec6bfd59..b8ce783889d 100644 --- a/tests-integration/src/tests/test_util.rs +++ b/tests-integration/src/tests/test_util.rs @@ -15,9 +15,12 @@ use std::collections::HashMap; use std::env; use std::sync::Arc; +use std::time::Duration; use async_trait::async_trait; +use axum::Router; use client::OutputData; +use common_base::readable_size::ReadableSize; use common_meta::DatanodeId; use common_meta::kv_backend::KvBackendRef; use common_meta::range_stream::{DEFAULT_PAGE_SIZE, PaginationStream}; @@ -34,11 +37,13 @@ use common_wal::config::kafka::{DatanodeKafkaConfig, MetasrvKafkaConfig}; use common_wal::config::{DatanodeWalConfig, MetasrvWalConfig}; use datanode::datanode::Datanode; use frontend::instance::Instance; +use frontend::service_config::PromqlRollupCacheOptions; use futures::TryStreamExt; use meta_srv::metasrv::Metasrv; use rstest_reuse::{self, template}; use servers::query_handler::sql::SqlQueryHandler; use session::context::{QueryContext, QueryContextRef}; +use tower::ServiceExt; use crate::cluster::{GreptimeDbCluster, GreptimeDbClusterBuilder}; use crate::standalone::{GreptimeDbStandalone, GreptimeDbStandaloneBuilder}; @@ -230,6 +235,144 @@ pub(crate) async fn standalone() -> Arc { Arc::new(instance) } +/// Twenty-minute chunks at the tests' one-minute step, a ten-minute tail older +/// than every fixed test point, and an hour-long ttl so a filled chunk outlives +/// the test. +pub(crate) fn rollup_cache_options() -> PromqlRollupCacheOptions { + PromqlRollupCacheOptions { + enable: true, + max_bytes: ReadableSize::mb(256), + chunk: Duration::from_secs(1_200), + tail: Duration::from_secs(600), + ttl: Duration::from_secs(3_600), + } +} + +pub(crate) async fn standalone_with_rollup_cache() -> Arc { + standalone_with_rollup_cache_options(rollup_cache_options()).await +} + +pub(crate) async fn standalone_with_rollup_cache_options( + options: PromqlRollupCacheOptions, +) -> Arc { + let test_name = uuid::Uuid::new_v4().to_string(); + let instance = GreptimeDbStandaloneBuilder::new(&test_name) + .with_promql_rollup_cache(options) + .build() + .await; + Arc::new(instance) +} + +/// The HTTP application of `frontend`, with its result order marked irrelevant +/// ([`servers::http::prometheus::range_query`] runs the statement as unordered), +/// which is the path the rollup cache serves. A direct +/// `PrometheusHandler::do_query` builds an ordered statement and never reaches the +/// cache. +pub(crate) fn prometheus_http_app(frontend: &Arc) -> Router { + let server = crate::test_util::build_test_prom_server(frontend.clone(), false, None).build(); + server.build(server.make_app()).unwrap() +} + +/// The parameters of one Prometheus HTTP range query. +pub(crate) struct PromRangeQuery<'a> { + pub(crate) query: &'a str, + pub(crate) start: &'a str, + pub(crate) end: &'a str, + pub(crate) step: &'a str, + /// The lookback each point folds, stated explicitly because a chunk depends on + /// the input history its first point reaches back to. + pub(crate) lookback: &'a str, + /// Ask the range endpoint to skip the rollup cache (`nocache=1`). + pub(crate) nocache: bool, +} + +impl<'a> PromRangeQuery<'a> { + pub(crate) fn new( + query: &'a str, + start: &'a str, + end: &'a str, + step: &'a str, + lookback: &'a str, + ) -> Self { + Self { + query, + start, + end, + step, + lookback, + nocache: false, + } + } + + /// The same query with `nocache=1`, which the range endpoint turns into the + /// query context's "do not use the rollup cache" hint. + pub(crate) fn without_cache(mut self) -> Self { + self.nocache = true; + self + } +} + +/// The `(timestamp_ms, value)` points of the PromQL range answer of `app`, read +/// out of the JSON a Prometheus client sees. +pub(crate) async fn promql_range_points( + app: &Router, + request: &PromRangeQuery<'_>, +) -> Vec<(i64, f64)> { + let mut uri = format!( + "/v1/prometheus/api/v1/query_range?query={}&start={}&end={}&step={}&lookback={}", + request.query, request.start, request.end, request.step, request.lookback + ); + if request.nocache { + uri.push_str("&nocache=1"); + } + let http_request = axum::http::Request::builder() + .method("GET") + .uri(uri) + // The handler reads its parameters from the query string or from a form body, + // and its form extractor requires the header even when the body is empty. + .header("content-type", "application/x-www-form-urlencoded") + .body(axum::body::Body::empty()) + .unwrap(); + let response = app.clone().oneshot(http_request).await.unwrap(); + let status = response.status(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let body: serde_json::Value = serde_json::from_slice(&body).unwrap_or_else(|_| { + panic!( + "the range answer is not JSON: {}", + String::from_utf8_lossy(&body) + ) + }); + assert!( + status.is_success(), + "the range query failed: {status} {body}" + ); + assert_eq!("success", body["status"], "{body}"); + let series = body["data"]["result"] + .as_array() + .unwrap_or_else(|| panic!("the range answer holds a result: {body}")); + assert_eq!(1, series.len(), "one series answers the range: {body}"); + let values = series[0]["values"] + .as_array() + .unwrap_or_else(|| panic!("the series holds its samples: {body}")); + values + .iter() + .map(|sample| { + let timestamp = sample[0] + .as_f64() + .unwrap_or_else(|| panic!("a sample timestamp is a number: {body}")); + let value = sample[1] + .as_str() + .unwrap_or_else(|| panic!("a sample value is a string: {body}")) + .parse::() + .unwrap_or_else(|_| panic!("a sample value is a float: {body}")); + // The API reports seconds since the epoch; the query states milliseconds. + ((timestamp * 1000.0).round() as i64, value) + }) + .collect() +} + pub(crate) async fn distributed() -> Arc { let test_name = uuid::Uuid::new_v4().to_string(); let instance = create_distributed_instance(&test_name).await; diff --git a/tests/perf/README.md b/tests/perf/README.md index ed83c5c9446..a626e0173b5 100644 --- a/tests/perf/README.md +++ b/tests/perf/README.md @@ -79,6 +79,10 @@ pending_rows_flush_interval = "1s" max_batch_rows = 100000 ``` +A case that measures the frontend rollup cache can add +`[scenario.remote_write.prom_store.candidate_promql_rollup_cache]`; see +[Frontend rollup cache configuration](#frontend-rollup-cache-configuration). + Cases can optionally add `[scenario.remote_write.value]` to control the generated sample values without changing label cardinality or the runner lifecycle: @@ -193,6 +197,38 @@ before trusting the query measurements. Use `--fixture-generator /path/to/query_perf_fixture` to provide the Rust helper to the outer driver. +### Frontend rollup cache configuration + +A remote-write case can render the frontend `[promql_rollup_cache]` section +(`src/frontend/src/promql_query_cache.rs`) into the candidate's config only, so one +case compares an uncached base against a cached candidate: + +```toml +[scenario.remote_write.prom_store.candidate_promql_rollup_cache] +tail = "0s" +ttl = "1h" +``` + +Every field is optional and only the ones a case sets are rendered, so the +frontend owns every default. Values are the strings the frontend parses itself: +`max_bytes` is a `ReadableSize` (`256MB`), and `chunk`, `tail`, and `ttl` are +`humantime` durations (`5m`, `0s`, `1h`). Rendering the table enables the cache; +the base render writes no table at all, which leaves the frontend default +(disabled). `query_regression_runner render-remote-config --target base|candidate` +picks the side and defaults to `base`. + +The cache serves only PromQL range queries whose expression is in the +`selector`/`rate`/`sum` allowlist (`src/query/src/promql/window.rs`) and whose +points are all older than `now - tail`. `chunk` is a target rather than the length +used: planning aligns it down to a whole number of the step and floors it at 20 +steps. The cache is read-through and bounded by `ttl` alone — nothing probes the +source — so a case that wants warm measured iterations writes historical data, +keeps the measured range out of the tail, and lets the first `warmup` repetition +fill. A bare top-level selector is in the allowlist but bypasses the cache +(`windowed_expr_is_bare_selector`), and so is any query that does not go through +`kind = "prom_http"`: that endpoint marks the output unordered, which is the path +the cache serves. + Large manual remote-write cases can set `sample_chunk_size` to split ingestion by time. For each chunk, `prepare-remote` invokes `query_perf_fixture prom-remote-write` with the same series cardinality but a shorter `--samples-per-series` and an advanced @@ -247,6 +283,29 @@ The routine default set also includes Mito prefilter all-match path, a mixed integer/float filter, and integer and float selective controls over a 262144-row direct SST fixture. +### Rollup cache case + +`tests/perf/query_cases/prom_rollup_cache_warm_range/case.toml` measures the +frontend rollup cache serving warm historical PromQL ranges against an uncached +base. The header of that file states the chunk geometry and what each query is +there for; [Query repetitions and latency thresholds](#query-repetitions-and-latency-thresholds) +covers how `warmup` fills the cache and how a speedup gate fails a no-op cache. + +The case is in the `heavy` group rather than the routine `all` set: it measures a +candidate-only feature instead of gating a routine scan path, so it runs on demand +with `--cases heavy`, or on its own when given its path. + +```bash +uv run --no-project python .github/scripts/query-regression-run.py \ + --cases heavy \ + --base-bin "$BASE_GREPTIME" --candidate-bin "$CANDIDATE_GREPTIME" \ + --fixture-generator "$FIXTURE_GENERATOR" --runner "$RUNNER" \ + --work-dir "$WORK_DIR" +``` + +The base build may predate the `[promql_rollup_cache]` option: the base render +never emits it, so such a build only ever sees keys it can parse. + ## OTLP trace load scenario `scenario.kind = "otlp_trace_load"` runs a bounded native `otelgen` process @@ -357,6 +416,29 @@ seed = 12345 The outer driver currently supports `direct_readable_sst`, `prom_remote_write_then_query`, and `otlp_trace_load`. +### Query repetitions and latency thresholds + +Each `[[scenario.queries]]` entry runs its `warmup` repetitions, then its +`iterations` measured repetitions, against each target. `warmup` is where a +read-through cache such as the rollup cache fills: the first repetition executes +and stores, the rest hit, and the measured repetitions then measure the cached +path. There is no separate settle or refresh step to wait for. + +Two latency thresholds are supported, both on the candidate median: + +- `max_candidate_latency_regression_pct` (default gate): fails when the candidate + median is more than this percentage slower than the base median. `25` allows + 25%. +- `min_candidate_latency_speedup_pct` (feature gate): fails when the candidate + does not save at least this percentage of the base median. `50` requires the + candidate to be at least twice as fast. Use it for cases whose whole point is + that a candidate-only feature is in effect, so that a silently inert feature + (option ignored, expression outside a feature's allowlist, cache entry aged + out) fails instead of passing with base-equal latency. + +Any other key in a query's `thresholds` table fails the case as an unsupported +threshold rather than being ignored. + ## Native PromQL route enforcement The native fused-series PromQL route is off by default @@ -439,12 +521,12 @@ stops only both datanodes, writes File-object-store destination TOMLs, invokes `measure` (with one frontend restart retry). `materialize` uses OpenDAL and only replaces the fixture's exact region prefix in each target data home. -For `prom_remote_write_then_query`, it renders a target frontend configuration -with `render-remote-config`, starts both clusters, runs `prepare-remote` and -`measure`, stops both datanodes, then runs `finalize-remote`. Finalization owns -storage inspection and read-bench against the quiescent data homes. Both paths -write `query-regression-report.json` in the case work directory and always clean -up the remaining components. +For `prom_remote_write_then_query`, it renders one frontend configuration per +target with `render-remote-config --target `, starts both clusters, runs +`prepare-remote` and `measure`, stops both datanodes, then runs +`finalize-remote`. Finalization owns storage inspection and read-bench against +the quiescent data homes. Both paths write `query-regression-report.json` in the +case work directory and always clean up the remaining components. For local orchestration after building the three binaries, invoke the outer driver directly: diff --git a/tests/perf/query_cases/prom_rollup_cache_warm_range/case.toml b/tests/perf/query_cases/prom_rollup_cache_warm_range/case.toml new file mode 100644 index 00000000000..afba33f14a2 --- /dev/null +++ b/tests/perf/query_cases/prom_rollup_cache_warm_range/case.toml @@ -0,0 +1,121 @@ +# Frontend rollup cache: warm historical range against an uncached base. +# +# - A chunk is at least 20 query steps and its bounds are canonical multiples, so +# this 6h range at a 5m step plans three 100-minute chunks: 60 of its 73 points +# are cacheable and 13 are read directly (02:00-02:55 plus 08:00). +# - The tail is measured from the wall clock and this data is from 2024, so +# `tail = "0s"` puts every point on the cacheable side. +# - The cache is candidate-only: the base renders no `[promql_rollup_cache]` table +# at all and runs the frontend default (disabled), so this compares an uncached +# base against a cached candidate. +# - `min_candidate_latency_speedup_pct` on the two cached shapes is what catches a +# cache that silently did not take effect: such a candidate measures base-equal +# latency and fails instead of passing quietly. + +[case] +name = "prom_rollup_cache_warm_range" +description = "Frontend rollup cache serving warm historical PromQL ranges against an uncached base" + +[scenario] +kind = "prom_remote_write_then_query" + +[scenario.remote_write] +database = "public" +metric = "prom_rollup_cache_warm_range" +physical_table = "greptime_physical_table" +series_count = 2048 +samples_per_series = 720 +sample_chunk_size = 240 +flush_every_sample_chunks = 1 +start_unix_millis = 1_704_067_200_000 # 2024-01-01T00:00:00Z +step_millis = 60_000 +chunk_series_count = 256 +timeout_seconds = 600 +visibility_timeout_seconds = 300 + +# `linear` is a per-series monotonic counter, so `rate(...)` folds a realistic +# increasing signal. +[scenario.remote_write.value] +pattern = "linear" +base = 0.0 +step = 0.125 + +[scenario.remote_write.prom_store] +pending_rows_flush_interval = "1s" +max_batch_rows = 100000 + +# Candidate only: the base renders no `[promql_rollup_cache]` table at all, so it +# runs the frontend default (disabled). Unset bounds are not rendered either, so +# `chunk` stays the frontend default of 5m (100 minutes at this step, after +# planning) and `max_bytes` is stated because a measurement wants a budget it +# chose. `tail = "0s"` keeps the 2024 data inside the cacheable range, and +# `ttl = "1h"` outlives the run, so a chunk the first warmup repetition filled is +# still served by the measured ones. +[scenario.remote_write.prom_store.candidate_promql_rollup_cache] +max_bytes = "256MB" +tail = "0s" +ttl = "1h" + +# Control: a bare top-level selector bypasses the cache +# (`windowed_expr_is_bare_selector`), because serving 2048 series x 73 points from +# a cached payload measured slower than scanning them. Both targets run the same +# path, so it guards against a cache that slowed the selector down. +[[scenario.queries]] +name = "prom_range_selector_6h_5m_bypass_control" +kind = "prom_http" +query = "prom_rollup_cache_warm_range{host=~\"host.*\"}" +start = "1704074400" # 2024-01-01T02:00:00Z +end = "1704096000" # 2024-01-01T08:00:00Z +step = "5m" +warmup = 3 +iterations = 7 + +[scenario.queries.thresholds] +max_candidate_latency_regression_pct = 25 + +# `rate(...)` folds 5m of input per output point, so the uncached base reads far +# more rows than it returns while the cached candidate returns the same payload. +# The Prometheus JSON response and the merged rows are the floor either way. +# Measured 18.5% once, so the gate sits at 10%: well under that measurement, but +# still out of reach for a candidate whose cache did not take effect. +[[scenario.queries]] +name = "prom_range_rate_5m_6h_5m" +kind = "prom_http" +query = "rate(prom_rollup_cache_warm_range{host=~\"host.*\"}[5m])" +start = "1704074400" +end = "1704096000" +step = "5m" +warmup = 3 +iterations = 7 + +[scenario.queries.thresholds] +min_candidate_latency_speedup_pct = 10 + +# `sum` is the one admitted aggregate; grouping by `host` folds 2048 series into +# 1024 groups, so the base keeps its full input read while the cached candidate +# returns the folded payload. Measured 58% once, so the gate stays at 25%. +[[scenario.queries]] +name = "prom_range_sum_rate_by_host_6h_5m" +kind = "prom_http" +query = "sum by (host) (rate(prom_rollup_cache_warm_range{host=~\"host.*\"}[5m]))" +start = "1704074400" +end = "1704096000" +step = "5m" +warmup = 3 +iterations = 7 + +[scenario.queries.thresholds] +min_candidate_latency_speedup_pct = 25 + +# Control: `TQL` never consults the rollup cache, so both targets run the same +# storage path, where an ordinary scan regression shows up. The gate is 50% rather +# than 25% only because that path is noisy on a shared runner. +[[scenario.queries]] +name = "tql_rate_5m_1h_uncached_control" +kind = "tql" +query = "TQL ANALYZE VERBOSE (1704074400, 1704078000, '1m') rate(prom_rollup_cache_warm_range{host=~'host.*'}[5m])" +warmup = 1 +iterations = 5 + +[scenario.queries.thresholds] +max_candidate_latency_regression_pct = 50 diff --git a/tests/perf/test_query_regression_case_selection.py b/tests/perf/test_query_regression_case_selection.py index 3991e5e03fb..edcbd7a275c 100644 --- a/tests/perf/test_query_regression_case_selection.py +++ b/tests/perf/test_query_regression_case_selection.py @@ -56,6 +56,7 @@ class QueryRegressionCaseSelectionTest(unittest.TestCase): runner.split_cases(["heavy"]), [ "tests/perf/query_cases/prom_remote_write_7913/case.toml", + "tests/perf/query_cases/prom_rollup_cache_warm_range/case.toml", "tests/perf/query_cases/promql_constant_tag_concat_ms_10k/case.toml", "tests/perf/query_cases/promql_constant_tag_concat_ms_100k/case.toml", "tests/perf/query_cases/many_short_series/case.toml",