From e1a2945a22b61fee325c4d92cb976752624c4fd4 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 07:57:13 +0000 Subject: [PATCH 1/5] refactor: move the internal-metrics and storage files out of data-plane git mv only, so the history follows each file; the next commit makes the crates build. --- crates/{data-plane/src/metrics.rs => internal-metrics/src/lib.rs} | 0 crates/{data-plane => storage}/src/memory_budget.rs | 0 crates/{data-plane => storage}/src/persist.rs | 0 crates/{data-plane => storage}/src/segment.rs | 0 crates/{data-plane => storage}/src/series_ids.rs | 0 crates/{data-plane => storage}/src/state_codec.rs | 0 crates/{data-plane => storage}/src/store.rs | 0 crates/{data-plane => storage}/src/window_cache.rs | 0 crates/{data-plane => storage}/tests/series_ids.rs | 0 crates/{data-plane => storage}/tests/view_cache_charge.rs | 0 10 files changed, 0 insertions(+), 0 deletions(-) rename crates/{data-plane/src/metrics.rs => internal-metrics/src/lib.rs} (100%) rename crates/{data-plane => storage}/src/memory_budget.rs (100%) rename crates/{data-plane => storage}/src/persist.rs (100%) rename crates/{data-plane => storage}/src/segment.rs (100%) rename crates/{data-plane => storage}/src/series_ids.rs (100%) rename crates/{data-plane => storage}/src/state_codec.rs (100%) rename crates/{data-plane => storage}/src/store.rs (100%) rename crates/{data-plane => storage}/src/window_cache.rs (100%) rename crates/{data-plane => storage}/tests/series_ids.rs (100%) rename crates/{data-plane => storage}/tests/view_cache_charge.rs (100%) diff --git a/crates/data-plane/src/metrics.rs b/crates/internal-metrics/src/lib.rs similarity index 100% rename from crates/data-plane/src/metrics.rs rename to crates/internal-metrics/src/lib.rs diff --git a/crates/data-plane/src/memory_budget.rs b/crates/storage/src/memory_budget.rs similarity index 100% rename from crates/data-plane/src/memory_budget.rs rename to crates/storage/src/memory_budget.rs diff --git a/crates/data-plane/src/persist.rs b/crates/storage/src/persist.rs similarity index 100% rename from crates/data-plane/src/persist.rs rename to crates/storage/src/persist.rs diff --git a/crates/data-plane/src/segment.rs b/crates/storage/src/segment.rs similarity index 100% rename from crates/data-plane/src/segment.rs rename to crates/storage/src/segment.rs diff --git a/crates/data-plane/src/series_ids.rs b/crates/storage/src/series_ids.rs similarity index 100% rename from crates/data-plane/src/series_ids.rs rename to crates/storage/src/series_ids.rs diff --git a/crates/data-plane/src/state_codec.rs b/crates/storage/src/state_codec.rs similarity index 100% rename from crates/data-plane/src/state_codec.rs rename to crates/storage/src/state_codec.rs diff --git a/crates/data-plane/src/store.rs b/crates/storage/src/store.rs similarity index 100% rename from crates/data-plane/src/store.rs rename to crates/storage/src/store.rs diff --git a/crates/data-plane/src/window_cache.rs b/crates/storage/src/window_cache.rs similarity index 100% rename from crates/data-plane/src/window_cache.rs rename to crates/storage/src/window_cache.rs diff --git a/crates/data-plane/tests/series_ids.rs b/crates/storage/tests/series_ids.rs similarity index 100% rename from crates/data-plane/tests/series_ids.rs rename to crates/storage/tests/series_ids.rs diff --git a/crates/data-plane/tests/view_cache_charge.rs b/crates/storage/tests/view_cache_charge.rs similarity index 100% rename from crates/data-plane/tests/view_cache_charge.rs rename to crates/storage/tests/view_cache_charge.rs From 50722b469c3653ef4434c26662e9aadfbd356d93 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 07:57:26 +0000 Subject: [PATCH 2/5] refactor: split internal-metrics and storage crates out of data-plane Step 3 of docs/design/repo-layout.md. `internal_metrics` holds the measurement types (phase timers, latency histograms, the engine's `Metrics`); `storage` holds the raw and view stores, the window cache, the memory budget, segments, persistence, state codecs and the series interner, and the view-cache monitor thread's body from engine.rs. `data_plane` depends on both; `storage` depends on `internal_metrics` and `asap-executor`, never on `data_plane`. The `/metrics` renderer and its `Gauges` stay in data-plane (`metrics_endpoint.rs`) because they read ingestion, query and store state. The view tier moves from `Metrics` to `Gauges`. `millis` and `window_end` move to `storage::store`, the lower crate that uses them. The persist-N threads stay in engine.rs until step 5. --- Cargo.lock | 31 +- Cargo.toml | 9 +- README.md | 2 + benchmarks/micro/ingest_bench.rs | 2 +- benchmarks/micro/range_bench.rs | 2 +- benchmarks/micro/rw_corpus_bench.rs | 4 +- benchmarks/micro/tier_bench.rs | 2 +- benchmarks/micro/view_read_bench.rs | 2 +- crates/data-plane/Cargo.toml | 8 +- crates/data-plane/src/engine.rs | 68 +-- crates/data-plane/src/ingestion.rs | 20 +- crates/data-plane/src/lib.rs | 13 +- crates/data-plane/src/main.rs | 2 +- crates/data-plane/src/metrics_endpoint.rs | 536 ++++++++++++++++++ crates/data-plane/src/push.rs | 7 +- crates/data-plane/src/query.rs | 21 +- crates/data-plane/src/remote_write.rs | 7 +- .../tests/remote_write_reference.rs | 8 +- crates/data-plane/tests/view_tiering.rs | 4 +- crates/internal-metrics/Cargo.toml | 7 + crates/internal-metrics/src/lib.rs | 536 +----------------- crates/storage/Cargo.toml | 21 + crates/storage/src/lib.rs | 12 + crates/storage/src/persist.rs | 2 +- crates/storage/src/store.rs | 46 +- crates/storage/tests/series_ids.rs | 2 +- crates/storage/tests/view_cache_charge.rs | 6 +- 27 files changed, 737 insertions(+), 643 deletions(-) create mode 100644 crates/data-plane/src/metrics_endpoint.rs create mode 100644 crates/internal-metrics/Cargo.toml create mode 100644 crates/storage/Cargo.toml create mode 100644 crates/storage/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index fec6adc54..5dc5ff4b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -962,22 +962,21 @@ dependencies = [ "futures", "hashbrown 0.15.5", "http-body-util", + "internal_metrics", "libc", "prost", "reqwest", - "rmp-serde", "ryu", "serde", - "serde_bytes", "serde_json", "snap", + "storage", "thiserror 1.0.69", "tikv-jemallocator", "tokio", "tower", "tracing", "tracing-subscriber", - "zstd", ] [[package]] @@ -2175,6 +2174,13 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "internal_metrics" +version = "0.1.0" +dependencies = [ + "libc", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -3450,6 +3456,25 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "storage" +version = "0.1.0" +dependencies = [ + "ahash", + "asap-executor", + "asap_sketchlib", + "clap", + "futures", + "internal_metrics", + "libc", + "rmp-serde", + "serde", + "serde_bytes", + "serde_json", + "tracing", + "zstd", +] + [[package]] name = "strsim" version = "0.11.1" diff --git a/Cargo.toml b/Cargo.toml index 4efa1e2a7..5cd886380 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,11 @@ [workspace] resolver = "2" -members = ["crates/control-plane", "crates/data-plane"] +members = [ + "crates/control-plane", + "crates/data-plane", + "crates/internal-metrics", + "crates/storage", +] [workspace.package] edition = "2021" @@ -30,6 +35,8 @@ tokio = { version = "1.0", features = ["full"] } axum = "0.7" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } control_plane = { path = "crates/control-plane" } +internal_metrics = { path = "crates/internal-metrics" } +storage = { path = "crates/storage" } # asap_sketchlib#271's head, ahead of the Planner's pin (389530c): DDSketch # view merges in place, with width-specialized loops (a 1 h quantile over diff --git a/README.md b/README.md index 19638aab6..83aa2df23 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,8 @@ not stored) with a Prometheus `execution` error (422, |---|---| | `crates/control-plane/` | package `control_plane`: workload → `asap-planner` → plan file | | `crates/data-plane/` | package `data_plane`: the data plane and its binary | +| `crates/storage/` | package `storage`: raw samples and views in memory, the view cache, segments and persistence | +| `crates/internal-metrics/` | package `internal_metrics`: the backend's measurements of itself, exported on `/metrics` | | `benchmarks/` | the backend alone: `micro/` benchmarks (examples of `data_plane`) and `scripts/` | | `eval/` | comparisons with other systems and the live demo; see [eval/README.md](eval/README.md) | | `deployment/monitoring/` | Prometheus, exporters and Grafana for the demo and the comparisons | diff --git a/benchmarks/micro/ingest_bench.rs b/benchmarks/micro/ingest_bench.rs index 21554600a..18f07e66e 100644 --- a/benchmarks/micro/ingest_bench.rs +++ b/benchmarks/micro/ingest_bench.rs @@ -44,9 +44,9 @@ use axum::http::{Request, StatusCode}; use control_plane::{plan_workload, DeploymentInputs}; use data_plane::engine::{EngineOptions, PrecomputeMode}; use data_plane::ingestion::IngestionOptions; -use data_plane::metrics::thread_cpu_seconds; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; +use internal_metrics::thread_cpu_seconds; use tower::ServiceExt; #[tokio::main(flavor = "multi_thread")] diff --git a/benchmarks/micro/range_bench.rs b/benchmarks/micro/range_bench.rs index 251b7e682..d8bb74da7 100644 --- a/benchmarks/micro/range_bench.rs +++ b/benchmarks/micro/range_bench.rs @@ -26,10 +26,10 @@ use axum::Router; use control_plane::{plan_workload, DeploymentInputs}; use data_plane::engine::EngineOptions; use data_plane::ingestion::IngestionOptions; -use data_plane::metrics::thread_cpu_seconds; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane, EXECUTION_HEADER}; use http_body_util::BodyExt; +use internal_metrics::thread_cpu_seconds; use tower::ServiceExt; const STEP_MS: i64 = 15_000; diff --git a/benchmarks/micro/rw_corpus_bench.rs b/benchmarks/micro/rw_corpus_bench.rs index b0a805f08..e101470b7 100644 --- a/benchmarks/micro/rw_corpus_bench.rs +++ b/benchmarks/micro/rw_corpus_bench.rs @@ -29,9 +29,9 @@ static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; use std::sync::mpsc; use std::time::Instant; -use data_plane::metrics::thread_cpu_ns; use data_plane::remote_write::{decode_samples, Limits}; -use data_plane::store::RawSample; +use internal_metrics::thread_cpu_ns; +use storage::store::RawSample; fn main() { let args: Vec = std::env::args().collect(); diff --git a/benchmarks/micro/tier_bench.rs b/benchmarks/micro/tier_bench.rs index 9411bc978..c5711a45d 100644 --- a/benchmarks/micro/tier_bench.rs +++ b/benchmarks/micro/tier_bench.rs @@ -39,10 +39,10 @@ use axum::Router; use control_plane::{plan_workload, DeploymentInputs}; use data_plane::engine::EngineOptions; use data_plane::ingestion::IngestionOptions; -use data_plane::persist::ViewRead; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; +use storage::persist::ViewRead; use tower::ServiceExt; const WINDOW_MS: i64 = 15_000; diff --git a/benchmarks/micro/view_read_bench.rs b/benchmarks/micro/view_read_bench.rs index bdea03ee0..498be9441 100644 --- a/benchmarks/micro/view_read_bench.rs +++ b/benchmarks/micro/view_read_bench.rs @@ -23,7 +23,7 @@ use asap_executor::summary_kernels::exact::ExactAccumulator; use asap_executor::summary_kernels::{DDSketchAccumulator, DatasketchesKLLAccumulator}; use asap_executor::values::{Batch, Value}; use asap_executor::AggregateCore; -use data_plane::persist::{ViewFiles, ViewRead}; +use storage::persist::{ViewFiles, ViewRead}; fn main() { let args: Vec = std::env::args().collect(); diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index b2ef11327..603b15fbb 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -6,10 +6,8 @@ edition.workspace = true [dependencies] asap-planner.workspace = true asap-executor.workspace = true -asap_sketchlib.workspace = true -serde_bytes = "0.11" -# Each view fragment is compressed (segment.rs). -zstd = "0.13" +internal_metrics.workspace = true +storage.workspace = true ahash = "0.8" # The per-thread series cache of the Remote Write decoder (a table of # indices hashed by the keys they point to). @@ -30,13 +28,13 @@ tokio.workspace = true axum.workspace = true reqwest.workspace = true prost = "0.13" -rmp-serde = "1" snap = "1.1" futures = "0.3" form_urlencoded = "1" [dev-dependencies] control_plane.workspace = true +asap_sketchlib.workspace = true tower = { version = "0.5", features = ["util"] } http-body-util = "0.1" diff --git a/crates/data-plane/src/engine.rs b/crates/data-plane/src/engine.rs index ea6fbb5bf..988e2affc 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -35,24 +35,24 @@ use std::time::Instant; use asap_executor::runtime::Limits; use asap_planner::InstallablePlan; - +use internal_metrics::{Metrics, PushMetrics, Timer}; +use storage::persist::{plan_hash, ViewFiles, ViewRead}; +use storage::store::SeriesPartition; +use storage::store::{ + serve_view_cache, PublishedStore, QueryTimeResults, RawData, RawSample, RawShards, RunStore, + ViewStore, ViewTier, WindowSlot, +}; +use storage::window_cache::WindowCache; use tokio::sync::oneshot; use crate::ingestion::{ ClosedWindow, Computed, Ingestion, IngestionOptions, IngestionStats, Precompute, RefreshTaskGraph, Refreshed, Routing, }; -use crate::metrics::{Gauges, Metrics, PushMetrics, Timer}; -use crate::persist::{plan_hash, ViewFiles, ViewRead}; +use crate::metrics_endpoint::Gauges; use crate::push::{Partial, PushGroup, PushShard}; use crate::query::{QueryEngine, Snapshot, Unanswered}; use crate::result_cache::{Answer, ResultCache}; -use crate::store::SeriesPartition; -use crate::store::{ - PublishedStore, QueryTimeResults, RawData, RawSample, RawShards, RunStore, ViewStore, ViewTier, - WindowSlot, -}; -use crate::window_cache::WindowCache; use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::values::Batch; @@ -145,7 +145,7 @@ pub struct EngineOptions { /// recently used are dropped first. pub result_cache_max_bytes: usize, /// Where the materialized views are persisted and loaded from at - /// startup ([`crate::persist`]); `None`: kept in memory only. + /// startup ([`storage::persist`]); `None`: kept in memory only. pub view_dir: Option, /// How often the view files are synced to disk: a refreshed window is /// durable within this long. 0 syncs after every window. @@ -223,7 +223,7 @@ impl Default for EngineOptions { view_sync_interval_ms: 5_000, view_cache_max_bytes: None, view_cache_idle_ms: None, - view_segment_ms: crate::persist::DEFAULT_SEGMENT_MS, + view_segment_ms: storage::persist::DEFAULT_SEGMENT_MS, view_read: ViewRead::Mmap, cold_decode_delay_ms: 0, unpersistable_views: Vec::new(), @@ -385,6 +385,8 @@ struct Shared { /// keep a refresh from finishing. precompute_gate: Mutex<()>, metrics: Metrics, + /// The views' cold tier, when they are persisted. + view_tier: Option>, } /// Marks the engine stopped when its thread exits, panics included. @@ -466,9 +468,6 @@ impl EngineHandle { .map(|(width_ms, views)| (width_ms, views.iter().map(ToString::to_string).collect())) .collect(); let mut metrics = Metrics::new(&groups, &query_texts); - if let Some(tier) = &tier { - let _ = metrics.view_tier.set(tier.clone()); - } if options.precompute_mode == PrecomputeMode::Push { metrics.push = Some(PushMetrics::new(groups.len(), shard_count)); } @@ -504,6 +503,7 @@ impl EngineHandle { published: PublishedStore::new(Arc::new(raw_shards.clone())), precompute_gate: Mutex::new(()), metrics, + view_tier: tier.clone(), }); let (commands, command_receiver) = channel(); let (jobs, job_receiver) = sync_channel(options.max_precompute_backlog.max(1)); @@ -771,7 +771,7 @@ impl EngineHandle { } /// The query-time partition of the view store. - pub fn query_time_results(&self) -> &QueryTimeResults { + pub fn query_time_results(&self) -> &QueryTimeResults { self.query.query_time_results() } @@ -783,7 +783,7 @@ impl EngineHandle { /// The engine's measurements and counters in the Prometheus text /// format. pub fn render_metrics(&self) -> String { - crate::metrics::render( + crate::metrics_endpoint::render( &self.shared.metrics, &Gauges { stats: self.stats(), @@ -798,6 +798,7 @@ impl EngineHandle { now_ms: crate::ingestion::wall_clock_ms(), query_time_results: self.query.query_time_results(), result_cache: self.query.result_cache(), + view_tier: self.shared.view_tier.as_deref(), }, ) } @@ -1002,7 +1003,7 @@ fn install( "materialized views" ); let results = QueryTimeResults::new( - crate::ingestion::millis(options.query_time_results_retention_ms), + storage::store::millis(options.query_time_results_retention_ms), options.query_time_results_max_bytes, ); let query = QueryEngine::new( @@ -2440,15 +2441,15 @@ fn serve_persist( /// with its budget (the option, else from the cgroup's `memory.max`, else /// none) and idle time. fn view_tier(options: &EngineOptions) -> ViewTier { - let cgroup = crate::memory_budget::own_cgroup() - .and_then(|dir| crate::memory_budget::read_cgroup(&dir).ok()); + let cgroup = storage::memory_budget::own_cgroup() + .and_then(|dir| storage::memory_budget::read_cgroup(&dir).ok()); let other_pools = (options.result_cache_max_bytes + options.query_time_results_max_bytes) as u64 + options.max_persist_backlog_bytes; let budget = options.view_cache_max_bytes.or_else(|| { - cgroup - .as_ref() - .and_then(|cgroup| crate::memory_budget::default_view_cache_budget(cgroup, other_pools)) + cgroup.as_ref().and_then(|cgroup| { + storage::memory_budget::default_view_cache_budget(cgroup, other_pools) + }) }); let idle_ms = options .view_cache_idle_ms @@ -2464,27 +2465,6 @@ fn view_tier(options: &EngineOptions) -> ViewTier { ) } -/// The view cache's monitor: once a second, drops idle windows and, under -/// a cgroup memory limit, lowers the cache's target while anonymous memory -/// runs higher than its budget assumed. -fn serve_view_cache(tier: Arc, budget: Option, running: Arc) { - let cgroup = crate::memory_budget::own_cgroup(); - while running.load(Ordering::SeqCst) { - std::thread::sleep(std::time::Duration::from_secs(1)); - tier.cache.evict_idle(std::time::Instant::now()); - if let Some(memory) = cgroup - .as_ref() - .and_then(|dir| crate::memory_budget::read_cgroup(dir).ok()) - { - let cached = tier.cache.stats().bytes; - tier.cache - .set_target_bytes(crate::memory_budget::monitored_target( - budget, &memory, cached, - )); - } - } -} - #[cfg(test)] mod tests { use super::*; @@ -2697,7 +2677,7 @@ mod tests { let widths: Vec = ingestion.group_windows().iter().map(|w| w.0).collect(); assert_eq!(widths, [60_000, 10_000]); ingestion.set_push_groups(vec![true, false]); - let series = crate::series_ids::intern_pairs(&[("__name__", "m_engine_push_late")]); + let series = storage::series_ids::intern_pairs(&[("__name__", "m_engine_push_late")]); ingestion.observe(&[(series.metric.clone(), 1_000)]); ingestion.advance_newest_sample(Some(25_000)); ingestion.advance_clock(25_000); diff --git a/crates/data-plane/src/ingestion.rs b/crates/data-plane/src/ingestion.rs index 8602df6fa..783afc437 100644 --- a/crates/data-plane/src/ingestion.rs +++ b/crates/data-plane/src/ingestion.rs @@ -41,9 +41,11 @@ use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalA use asap_executor::runtime::{Limits, RunContext, Scope}; use asap_executor::values::{Batch, SchemaRef}; use futures::executor::block_on; +use storage::store::{ + millis, window_end, RawData, RawSample, RawShards, RunStore, SeriesPartition, ViewStore, +}; use crate::prometheus::MAX_TIME_MS; -use crate::store::{RawData, RawSample, RawShards, RunStore, SeriesPartition, ViewStore}; /// How ingestion treats sample times. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -338,7 +340,7 @@ impl Ingestion { } let ingestion = Self { groups: clocks, - scanned_metrics: Arc::new(crate::store::scanned_metrics(&dag.nodes)), + scanned_metrics: Arc::new(storage::store::scanned_metrics(&dag.nodes)), pane_width_ms, query_time_lookback_ms, options, @@ -1223,7 +1225,7 @@ impl<'a> DagIndex<'a> { read_views: &BTreeSet, ) -> BTreeSet { let stop: HashSet = read_views.iter().copied().collect(); - crate::store::scanned_metrics(self.below(views, &stop).iter().map(|id| self.nodes[id])) + storage::store::scanned_metrics(self.below(views, &stop).iter().map(|id| self.nodes[id])) } } @@ -1250,21 +1252,9 @@ fn gcd(a: i64, b: i64) -> i64 { } } -/// A duration option in milliseconds as a time offset, saturating. -pub(crate) fn millis(value: u64) -> i64 { - i64::try_from(value).unwrap_or(i64::MAX) -} - /// Milliseconds since the Unix epoch. pub fn wall_clock_ms() -> i64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)) } - -/// End of the tumbling window of width `width_ms` (on multiples of it) -/// that holds `timestamp_ms`. Windows are `(end - width_ms, end]`, like -/// PromQL ranges: a sample at a boundary belongs to the window it ends. -pub fn window_end(timestamp_ms: i64, width_ms: i64) -> i64 { - -((-timestamp_ms).div_euclid(width_ms)) * width_ms -} diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index 5d7167674..a2fc42183 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -16,20 +16,13 @@ pub mod engine; pub mod ingestion; -pub mod memory_budget; -pub mod metrics; -pub mod persist; +mod metrics_endpoint; pub mod prometheus; pub mod push; pub mod query; pub mod raw_forward; pub mod remote_write; pub mod result_cache; -pub mod segment; -pub mod series_ids; -mod state_codec; -pub mod store; -pub mod window_cache; use std::sync::atomic::Ordering; use std::sync::Arc; @@ -179,7 +172,7 @@ async fn proxy( } async fn write(State(state): State>, body: Bytes) -> Response { - let timer = metrics::Timer::start(); + let timer = internal_metrics::Timer::start(); match remote_write::decode_samples(&body, &state.limits) { Ok(samples) => { state.engine.metrics().remote_write_decode.record(timer); @@ -306,7 +299,7 @@ async fn status(State(state): State>) -> Response { /// The data plane's measurements in the Prometheus text format: per-phase /// thread CPU and wall time, query latency, counters, backlogs, watermark -/// lag, bytes held and each thread's CPU time ([`metrics`]). +/// lag, bytes held and each thread's CPU time ([`metrics_endpoint`]). async fn metrics(State(state): State>) -> Response { let mut text = state.engine.render_metrics(); if let Some(forwarder) = &state.raw_forward { diff --git a/crates/data-plane/src/main.rs b/crates/data-plane/src/main.rs index f330e1ecf..43359a450 100644 --- a/crates/data-plane/src/main.rs +++ b/crates/data-plane/src/main.rs @@ -21,8 +21,8 @@ static malloc_conf: &[u8] = b"background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0,narenas:8\0"; use data_plane::engine::{EngineOptions, PrecomputeMode}; use data_plane::ingestion::IngestionOptions; -use data_plane::persist::ViewRead; use data_plane::{router, DataPlane, DEFAULT_FORWARD_TIMEOUT}; +use storage::persist::ViewRead; /// Serve Remote Write ingestion and the Prometheus query API for a plan. #[derive(Parser)] diff --git a/crates/data-plane/src/metrics_endpoint.rs b/crates/data-plane/src/metrics_endpoint.rs new file mode 100644 index 000000000..1502233f8 --- /dev/null +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -0,0 +1,536 @@ +//! `GET /metrics`: the engine's measurements ([`internal_metrics::Metrics`]) +//! and the gauges it reads from the stores, the ingestion counters and the +//! result cache, in the Prometheus text format. + +use std::fmt::Write; +use std::sync::atomic::{AtomicU64, Ordering}; + +use internal_metrics::{thread_cpu_seconds, Metrics, QueryMetrics, WindowLatency}; +use storage::store::{QueryTimeResults, ViewTier}; + +use crate::ingestion::IngestionStats; +use crate::query::Unanswered; +use crate::result_cache::ResultCache; + +/// What `/metrics` reports beside [`Metrics`]. +pub struct Gauges<'a> { + pub stats: IngestionStats, + pub samples_queued: u64, + pub precompute_backlog: u64, + pub persist_backlog: u64, + pub persist_backlog_bytes: u64, + pub now_ms: i64, + pub query_time_results: &'a QueryTimeResults, + /// `None` when the result cache is off. + pub result_cache: Option<&'a ResultCache>, + /// The views' cold tier, when they are persisted. + pub view_tier: Option<&'a ViewTier>, +} + +/// `metrics` and `gauges` in the Prometheus text format. +pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { + let mut out = String::new(); + let family = |out: &mut String, name: &str, kind: &str, help: &str| { + let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {kind}"); + }; + + family( + &mut out, + "asap_phase_runs_total", + "counter", + "Runs of each measured phase.", + ); + family( + &mut out, + "asap_phase_cpu_seconds_total", + "counter", + "Thread CPU time of each measured phase.", + ); + family( + &mut out, + "asap_phase_wall_seconds_total", + "counter", + "Wall time of each measured phase.", + ); + metrics + .remote_write_decode + .render(&mut out, "phase=\"remote_write_decode\""); + metrics.append.render(&mut out, "phase=\"append\""); + if let Some(tier) = gauges.view_tier { + tier.decode.render(&mut out, "phase=\"view_decode\""); + } + for (labels, stats) in &metrics.precompute { + stats.render(&mut out, labels); + } + if let Some(push) = &metrics.push { + push.render(&mut out); + } + for (query, query_metrics) in &metrics.queries { + let labels = format!("phase=\"query\",query=\"{}\"", escape(query)); + query_metrics.run.render(&mut out, &labels); + let labels = format!("phase=\"query_range_step\",query=\"{}\"", escape(query)); + query_metrics.range_step_run.render(&mut out, &labels); + } + + family( + &mut out, + "asap_query_latency_seconds", + "histogram", + "Planned instant query latency in the engine, queueing for a worker included.", + ); + for (query, query_metrics) in &metrics.queries { + let labels = format!("query=\"{}\"", escape(query)); + query_metrics + .latency + .render(&mut out, "asap_query_latency_seconds", &labels); + } + family( + &mut out, + "asap_range_query_latency_seconds", + "histogram", + "Planned range query latency, every step included.", + ); + for (query, query_metrics) in &metrics.queries { + let labels = format!("query=\"{}\"", escape(query)); + query_metrics + .range_latency + .render(&mut out, "asap_range_query_latency_seconds", &labels); + } + for (name, help, count) in [ + ( + "asap_range_query_steps_total", + "Steps of the planned range requests answered.", + (|m: &QueryMetrics| &m.range_steps) as fn(&QueryMetrics) -> &AtomicU64, + ), + ( + "asap_range_query_steps_cached_total", + "Steps of the planned range requests the result cache answered.", + |m: &QueryMetrics| &m.range_steps_cached, + ), + ] { + family(&mut out, name, "counter", help); + for (query, query_metrics) in &metrics.queries { + let _ = writeln!( + out, + "{name}{{query=\"{}\"}} {}", + escape(query), + count(query_metrics).load(Ordering::Relaxed) + ); + } + } + + family( + &mut out, + "asap_samples_total", + "counter", + "Samples by what ingestion did with them.", + ); + let stats = gauges.stats; + for (outcome, count) in [ + ("accepted", stats.samples_accepted), + ("dropped_late", stats.samples_dropped_late), + ("dropped_future", stats.samples_dropped_future), + ("unrouted", stats.samples_unrouted), + ("late_for_views", stats.samples_late_for_views), + ] { + let _ = writeln!(out, "asap_samples_total{{outcome=\"{outcome}\"}} {count}"); + } + if let Some(push) = &metrics.push { + push.render_gauges(&mut out); + } + family( + &mut out, + "asap_windows_total", + "counter", + "Refresh windows by outcome.", + ); + for (outcome, count) in [ + ("refreshed", stats.windows_refreshed), + ("failed", stats.windows_failed), + ("skipped_first", stats.windows_skipped_first), + ("skipped_expired", stats.windows_skipped_expired), + ("already_stored", stats.windows_already_stored), + ] { + let _ = writeln!(out, "asap_windows_total{{outcome=\"{outcome}\"}} {count}"); + } + + let gauge = |out: &mut String, name: &str, help: &str, value: f64| { + let _ = writeln!( + out, + "# HELP {name} {help}\n# TYPE {name} gauge\n{name} {value}" + ); + }; + gauge( + &mut out, + "asap_samples_queued", + "Samples queued for the ingest shards.", + gauges.samples_queued as f64, + ); + gauge( + &mut out, + "asap_precompute_backlog_windows", + "Refresh windows closed and not yet refreshed.", + gauges.precompute_backlog as f64, + ); + gauge( + &mut out, + "asap_persist_backlog_windows", + "Refreshed windows not yet written to the view files.", + gauges.persist_backlog as f64, + ); + gauge( + &mut out, + "asap_persist_backlog_bytes", + "Bytes of refreshed windows queued for the persist threads.", + gauges.persist_backlog_bytes as f64, + ); + let watermark_ms = metrics.watermark_ms.load(Ordering::Relaxed); + if watermark_ms != i64::MIN { + gauge( + &mut out, + "asap_watermark_lag_seconds", + "Wall clock minus the watermark.", + (gauges.now_ms - watermark_ms) as f64 / 1e3, + ); + } + let load = |value: &AtomicU64| value.load(Ordering::Relaxed) as f64; + gauge( + &mut out, + "asap_raw_data_bytes", + "Bytes of raw samples held.", + load(&metrics.raw_data_bytes), + ); + gauge( + &mut out, + "asap_raw_data_samples", + "Raw samples held.", + load(&metrics.raw_data_samples), + ); + gauge( + &mut out, + "asap_raw_data_panes", + "Raw-data panes held, over every metric.", + load(&metrics.raw_data_panes), + ); + gauge( + &mut out, + "asap_view_bytes", + "Bytes of materialized view rows held.", + load(&metrics.view_bytes), + ); + if let Some(tier) = gauges.view_tier { + let cache = tier.cache.stats(); + for (name, help, value) in [ + ( + "asap_view_cache_bytes", + "Bytes of decoded view windows in the window cache.", + cache.bytes as f64, + ), + ( + "asap_view_cache_entries", + "View windows in the window cache.", + cache.entries as f64, + ), + ( + "asap_view_pending_bytes", + "Bytes of view windows committed and not yet written to the view files.", + load(&tier.pending_bytes), + ), + ( + "asap_view_pinned_bytes", + "Bytes of view windows that cannot be written, kept in memory.", + load(&tier.pinned_bytes), + ), + ( + "asap_view_file_bytes", + "Bytes of the view files (segments) held.", + load(&metrics.view_file_bytes), + ), + ] { + gauge(&mut out, name, help, value); + } + for (name, help, value) in [ + ( + "asap_view_cache_hits_total", + "View window reads the window cache answered.", + cache.hits, + ), + ( + "asap_view_cache_misses_total", + "View window reads the window cache did not answer.", + cache.misses, + ), + ( + "asap_view_cache_evictions_total", + "View windows evicted from the window cache.", + cache.evictions, + ), + ( + "asap_view_cold_reads_total", + "View windows decoded from the view files.", + load(&tier.cold_reads) as u64, + ), + ( + "asap_view_cold_read_bytes_total", + "Bytes of the view files decoded.", + load(&tier.cold_read_bytes) as u64, + ), + ] { + family(&mut out, name, "counter", help); + let _ = writeln!(out, "{name} {value}"); + } + } + for (name, help, value) in [ + ( + "asap_view_persisted_bytes_total", + "Bytes written to the view files.", + load(&metrics.view_persisted_bytes), + ), + ( + "asap_view_sync_seconds_total", + "Time spent syncing the view files.", + load(&metrics.view_sync_ns) / 1e9, + ), + ( + "asap_view_windows_not_persisted_total", + "View windows not written to the view files (a sketch state, or an error).", + load(&metrics.view_windows_not_persisted), + ), + ( + "asap_view_segments_marked_cold_total", + "View segments whose pages were advised cold (MADV_COLD, POSIX_FADV_DONTNEED) once a newer sealed segment of their refresh group existed.", + load(&metrics.view_segments_marked_cold), + ), + ( + "asap_view_persist_over_bound_total", + "Windows queued for the view files while the queue held more than --max-persist-backlog-bytes (the data plane does not wait for its disk).", + load(&metrics.view_persist_over_bound), + ), + ( + "asap_view_windows_loaded_total", + "View windows loaded from the view files at startup.", + load(&metrics.view_windows_loaded), + ), + ] { + family(&mut out, name, "counter", help); + let _ = writeln!(out, "{name} {value}"); + } + let seconds = |ns: &AtomicU64| ns.load(Ordering::Relaxed) as f64 / 1e9; + for (name, help, value) in [ + ( + "asap_precompute_windows_total", + "Refresh windows committed, by refresh group.", + (|w: &WindowLatency| w.windows.load(Ordering::Relaxed) as f64) + as fn(&WindowLatency) -> f64, + ), + ( + "asap_precompute_queue_wait_seconds_total", + "Time from a window closing to its computation starting, by refresh group.", + |w| w.queue_wait_ns.load(Ordering::Relaxed) as f64 / 1e9, + ), + ( + "asap_precompute_commit_wait_seconds_total", + "Time from a window computed to its commit, waiting for the group's earlier windows.", + |w| w.commit_wait_ns.load(Ordering::Relaxed) as f64 / 1e9, + ), + ( + "asap_window_ready_seconds_total", + "Time from a window's end (event time) to its commit (wall clock), by refresh group.", + |w| w.ready_ms.load(Ordering::Relaxed) as f64 / 1e3, + ), + ] { + family(&mut out, name, "counter", help); + for (group, windows) in metrics.precompute_windows.iter().enumerate() { + let _ = writeln!(out, "{name}{{group=\"{group}\"}} {}", value(windows)); + } + } + family( + &mut out, + "asap_window_ready_seconds_max", + "gauge", + "The longest time from a window's end to its commit, by refresh group.", + ); + for (group, windows) in metrics.precompute_windows.iter().enumerate() { + let _ = writeln!( + out, + "asap_window_ready_seconds_max{{group=\"{group}\"}} {}", + windows.ready_max_ms.load(Ordering::Relaxed) as f64 / 1e3 + ); + } + family( + &mut out, + "asap_precompute_window_parts", + "gauge", + "The runs a refresh group's window is split into, by series; 1 when some node combines series.", + ); + for (group, windows) in metrics.precompute_windows.iter().enumerate() { + let _ = writeln!( + out, + "asap_precompute_window_parts{{group=\"{group}\"}} {}", + windows.parts.load(Ordering::Relaxed) + ); + } + family( + &mut out, + "asap_precompute_busy_seconds_total", + "counter", + "Wall time the precompute threads spent computing windows; divided by asap_precompute_threads, the task pool's utilisation.", + ); + let _ = writeln!( + out, + "asap_precompute_busy_seconds_total {}", + seconds(&metrics.precompute_busy_ns) + ); + gauge( + &mut out, + "asap_precompute_threads", + "Threads computing refresh windows.", + load(&metrics.precompute_threads), + ); + let results = gauges.query_time_results; + gauge( + &mut out, + "asap_query_time_result_bytes", + "Bytes of query-time OneEvaluation results held.", + results.bytes() as f64, + ); + gauge( + &mut out, + "asap_query_time_results", + "Query-time OneEvaluation results held, computed or being computed.", + results.len() as f64, + ); + family( + &mut out, + "asap_query_time_result_computes_total", + "counter", + "Query-time OneEvaluation results computed (misses).", + ); + let _ = writeln!( + out, + "asap_query_time_result_computes_total {}", + results.computes() + ); + family( + &mut out, + "asap_query_time_result_hits_total", + "counter", + "Reads of a query-time OneEvaluation result already computed.", + ); + let _ = writeln!(out, "asap_query_time_result_hits_total {}", results.hits()); + if let Some(cache) = gauges.result_cache { + gauge( + &mut out, + "asap_result_cache_bytes", + "Bytes of final query answers the result cache keeps (estimated).", + cache.bytes() as f64, + ); + gauge( + &mut out, + "asap_result_cache_entries", + "Final query answers the result cache keeps, by query and evaluation time.", + cache.len() as f64, + ); + for (name, help, value) in [ + ( + "asap_result_cache_hits_total", + "Result cache lookups that found the answer.", + cache.hits(), + ), + ( + "asap_result_cache_misses_total", + "Result cache lookups that found no answer.", + cache.misses(), + ), + ( + "asap_result_cache_evictions_total", + "Answers the result cache dropped by age or by bytes.", + cache.evictions(), + ), + ] { + family(&mut out, name, "counter", help); + let _ = writeln!(out, "{name} {value}"); + } + } + if let Some(rss) = resident_bytes() { + gauge( + &mut out, + "process_resident_memory_bytes", + "Resident memory of the process.", + rss as f64, + ); + } + + family( + &mut out, + "asap_thread_cpu_seconds_total", + "counter", + "CPU time of the live threads, by name (trailing digits removed).", + ); + for (thread, seconds) in thread_cpu_seconds() { + let _ = writeln!( + out, + "asap_thread_cpu_seconds_total{{thread=\"{}\"}} {seconds}", + escape(&thread) + ); + } + out +} + +/// `text` as a label value. +fn escape(text: &str) -> String { + text.replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('\n', "\\n") +} + +/// Resident set size, from `/proc/self/statm`. +fn resident_bytes() -> Option { + let statm = std::fs::read_to_string("/proc/self/statm").ok()?; + let pages: u64 = statm.split(' ').nth(1)?.parse().ok()?; + // SAFETY: sysconf has no preconditions. + let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + Some(pages * u64::try_from(page_size).ok()?) +} + +#[cfg(test)] +mod tests { + use internal_metrics::Timer; + + use super::*; + + /// The text format names each phase and query. + #[test] + fn records_and_renders_phases() { + let metrics = Metrics::new( + &[(10_000, vec!["3".into(), "5".into()])], + &["sum(x)".to_string()], + ); + metrics.append.record(Timer::start()); + metrics.query("sum(x) ").unwrap().latency.observe(0.003); + let text = render( + &metrics, + &Gauges { + stats: IngestionStats::default(), + samples_queued: 0, + precompute_backlog: 2, + persist_backlog: 0, + persist_backlog_bytes: 0, + now_ms: 0, + query_time_results: &QueryTimeResults::new(0, 0), + result_cache: None, + view_tier: None, + }, + ); + assert!( + text.contains("asap_phase_runs_total{phase=\"append\"} 1"), + "{text}" + ); + assert!(text.contains( + "asap_phase_cpu_seconds_total{phase=\"precompute\",group=\"0\",window_ms=\"10000\",views=\"3,5\"} 0" + )); + assert!(text.contains("asap_query_latency_seconds_bucket{query=\"sum(x)\",le=\"0.005\"} 1")); + assert!(text.contains("asap_precompute_backlog_windows 2")); + assert!(text.contains("asap_thread_cpu_seconds_total{thread=")); + } +} diff --git a/crates/data-plane/src/push.rs b/crates/data-plane/src/push.rs index 03b0381eb..1eb6a3544 100644 --- a/crates/data-plane/src/push.rs +++ b/crates/data-plane/src/push.rs @@ -47,9 +47,10 @@ use futures::executor::LocalPool; use futures::task::LocalSpawnExt; use futures::StreamExt; -use crate::ingestion::{window_end, ClosedWindow, Computed, Precompute}; -use crate::metrics::{Metrics, Timer}; -use crate::store::{RawData, RawSample}; +use internal_metrics::{Metrics, Timer}; +use storage::store::{window_end, RawData, RawSample}; + +use crate::ingestion::{ClosedWindow, Computed, Precompute}; /// The samples of one Remote Write request routed to a shard, and their /// batches converted once per metric and slot schema: every `Scan` of diff --git a/crates/data-plane/src/query.rs b/crates/data-plane/src/query.rs index 744c1dfd1..924673b3f 100644 --- a/crates/data-plane/src/query.rs +++ b/crates/data-plane/src/query.rs @@ -33,9 +33,9 @@ use asap_executor::values::{Batch, Value}; use asap_planner::InstallablePlan; use futures::executor::block_on; use futures::StreamExt; +use storage::store::{PublishedStore, QueryTimeResults, RawReads, RawShards, RunStore, ViewStore}; use crate::result_cache::{Answer, ResultCache}; -use crate::store::{PublishedStore, QueryTimeResults, RawReads, RawShards, RunStore, ViewStore}; /// One series of an instant-query result. #[derive(Debug, Clone, PartialEq)] @@ -78,7 +78,7 @@ pub struct QueryEngine { runs: BTreeMap, /// The shared nodes: their outputs live in `results`. shared: BTreeSet, - results: QueryTimeResults, + results: QueryTimeResults, limits: Limits, /// The query roots whose runs read raw data through a `Scan` (rather /// than only materialized views). @@ -98,7 +98,7 @@ impl QueryEngine { plan: &InstallablePlan, views: &[MaterializedView], limits: Limits, - results: QueryTimeResults, + results: QueryTimeResults, share_one_evaluation: bool, result_cache: Option, ) -> anyhow::Result { @@ -174,7 +174,7 @@ impl QueryEngine { } /// The query-time partition of the view store. - pub fn query_time_results(&self) -> &QueryTimeResults { + pub fn query_time_results(&self) -> &QueryTimeResults { &self.results } @@ -315,7 +315,7 @@ impl Snapshot { /// Every stored view's rows: per view, each window's `(start, end]` /// and batches, oldest first (for comparing two engines' views). #[doc(hidden)] - pub fn view_rows(&self) -> crate::store::ViewRowsByView { + pub fn view_rows(&self) -> storage::store::ViewRowsByView { self.views.rows() } } @@ -443,7 +443,7 @@ fn query_time_slot(node: PhysicalASAPNodeId) -> anyhow::Result /// The batches of `compiled`'s one root in a query run at `time_ms`. fn run_compiled( compiled: &CompiledPhysicalDAG, - store: std::sync::Arc, + store: std::sync::Arc, time_ms: i64, limits: &Limits, ) -> Result, asap_executor::Error> { @@ -542,7 +542,7 @@ fn result_samples(schema: &Schema, batches: &[Batch]) -> Result { // An input series' identity is interned; parse only a // series the query built. - match crate::series_ids::by_identity(text) { + match storage::series_ids::by_identity(text) { Some(series) => match own.as_mut() { Some(own) => own.extend( series @@ -552,9 +552,10 @@ fn result_samples(schema: &Schema, batches: &[Batch]) -> Result shared = Some(series.labels().clone()), }, None => { - let identity = crate::series_ids::result_labels(text).map_err(|e| { - Unanswered::Execution(format!("series identity: {e}")) - })?; + let identity = + storage::series_ids::result_labels(text).map_err(|e| { + Unanswered::Execution(format!("series identity: {e}")) + })?; match own.as_mut() { Some(own) => own.extend( identity diff --git a/crates/data-plane/src/remote_write.rs b/crates/data-plane/src/remote_write.rs index d3a385ca4..4dc3dfcf0 100644 --- a/crates/data-plane/src/remote_write.rs +++ b/crates/data-plane/src/remote_write.rs @@ -1,9 +1,8 @@ //! Prometheus Remote Write v1 decoding and validation. use prost::Message; - -use crate::series_ids::Series; -use crate::store::RawSample; +use storage::series_ids::Series; +use storage::store::RawSample; #[derive(Clone, PartialEq, Message)] pub struct WriteRequest { @@ -404,7 +403,7 @@ fn parse_labels(key: &[u8]) -> Result<&'static Series, RemoteWriteError> { if !names.contains(&"__name__") { return Err(RemoteWriteError::MissingMetricName); } - Ok(crate::series_ids::intern_pairs(&pairs)) + Ok(storage::series_ids::intern_pairs(&pairs)) } /// One protobuf field value. diff --git a/crates/data-plane/tests/remote_write_reference.rs b/crates/data-plane/tests/remote_write_reference.rs index 0d9d5f745..1315f7292 100644 --- a/crates/data-plane/tests/remote_write_reference.rs +++ b/crates/data-plane/tests/remote_write_reference.rs @@ -14,8 +14,8 @@ use data_plane::remote_write::{decode_samples, Limits, RemoteWriteError}; /// interned `&'static Series`. mod reference { use data_plane::remote_write::{Limits, RemoteWriteError}; - use data_plane::series_ids::Series; - use data_plane::store::RawSample; + use storage::series_ids::Series; + use storage::store::RawSample; fn decompress(body: &[u8], limits: &Limits) -> Result, RemoteWriteError> { if body.len() > limits.max_compressed_bytes { @@ -187,7 +187,7 @@ mod reference { if !names.contains(&"__name__") { return Err(RemoteWriteError::MissingMetricName); } - Ok(data_plane::series_ids::intern_pairs(&pairs)) + Ok(storage::series_ids::intern_pairs(&pairs)) } /// One protobuf field value. @@ -281,7 +281,7 @@ mod reference { /// Each decoded sample as (series id, time, value bits), or the error. type Decoded = Result, RemoteWriteError>; -fn decoded(samples: Result, RemoteWriteError>) -> Decoded { +fn decoded(samples: Result, RemoteWriteError>) -> Decoded { samples.map(|samples| { samples .iter() diff --git a/crates/data-plane/tests/view_tiering.rs b/crates/data-plane/tests/view_tiering.rs index 5cdfb138f..14100d18d 100644 --- a/crates/data-plane/tests/view_tiering.rs +++ b/crates/data-plane/tests/view_tiering.rs @@ -2,8 +2,8 @@ //! windows in a bounded cache, the rest read cold from the view files. //! Tests V7–V12, V16 and V17 of the design's test plan, end to end through //! the HTTP API; the parity test V1 is in `planner_executor_parity.rs` and -//! the unit tests are next to the code (`persist.rs`, `window_cache.rs`, -//! `memory_budget.rs`). Each compares a tiered data plane with one that +//! the unit tests are next to the code (`crates/storage`: `persist.rs`, +//! `window_cache.rs`, `memory_budget.rs`). Each compares a tiered data plane with one that //! keeps every window in memory (the control). mod common; diff --git a/crates/internal-metrics/Cargo.toml b/crates/internal-metrics/Cargo.toml new file mode 100644 index 000000000..5cb095570 --- /dev/null +++ b/crates/internal-metrics/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "internal_metrics" +version.workspace = true +edition.workspace = true + +[dependencies] +libc = "0.2" diff --git a/crates/internal-metrics/src/lib.rs b/crates/internal-metrics/src/lib.rs index e5e646ecf..bbc90d51b 100644 --- a/crates/internal-metrics/src/lib.rs +++ b/crates/internal-metrics/src/lib.rs @@ -10,10 +10,6 @@ use std::fmt::Write; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; use std::time::Instant; -use crate::ingestion::IngestionStats; -use crate::result_cache::ResultCache; -use crate::store::QueryTimeResults; - /// CPU time this thread has used, in nanoseconds. pub fn thread_cpu_ns() -> u64 { let mut time = libc::timespec { @@ -66,7 +62,8 @@ impl PhaseStats { wall.as_secs_f64() } - fn render(&self, out: &mut String, labels: &str) { + /// Its runs, CPU and wall time in the Prometheus text format. + pub fn render(&self, out: &mut String, labels: &str) { let seconds = |ns: &AtomicU64| ns.load(Ordering::Relaxed) as f64 / 1e9; let _ = writeln!( out, @@ -108,7 +105,8 @@ impl Latency { .fetch_add((seconds * 1e9) as u64, Ordering::Relaxed); } - fn render(&self, out: &mut String, name: &str, labels: &str) { + /// The histogram `name` in the Prometheus text format. + pub fn render(&self, out: &mut String, name: &str, labels: &str) { let mut cumulative = 0; for (bound, bucket) in LATENCY_BUCKETS_S.iter().zip(&self.buckets) { cumulative += bucket.load(Ordering::Relaxed); @@ -230,7 +228,8 @@ impl PushMetrics { .sum() } - fn render(&self, out: &mut String) { + /// Its phases in the Prometheus text format. + pub fn render(&self, out: &mut String) { for (group, shards) in self.push.iter().enumerate() { for (shard, stats) in shards.iter().enumerate() { stats.render( @@ -256,7 +255,8 @@ impl PushMetrics { self.commit.render(out, "phase=\"precompute_commit\""); } - fn render_gauges(&self, out: &mut String) { + /// Its gauges in the Prometheus text format. + pub fn render_gauges(&self, out: &mut String) { let _ = writeln!(out, "# HELP asap_precompute_state_bytes Bytes of open push-window state.\n# TYPE asap_precompute_state_bytes gauge"); for (group, shards) in self.state_bytes.iter().enumerate() { for (shard, bytes) in shards.iter().enumerate() { @@ -322,8 +322,6 @@ pub struct Metrics { pub view_file_bytes: AtomicU64, /// View segments whose pages were advised cold. pub view_segments_marked_cold: AtomicU64, - /// The views' cold tier, when they are persisted. - pub view_tier: std::sync::OnceLock>, } impl Metrics { @@ -364,7 +362,6 @@ impl Metrics { view_persist_over_bound: AtomicU64::new(0), view_file_bytes: AtomicU64::new(0), view_segments_marked_cold: AtomicU64::new(0), - view_tier: std::sync::OnceLock::new(), } } @@ -374,485 +371,6 @@ impl Metrics { } } -/// What `/metrics` reports beside [`Metrics`]. -pub struct Gauges<'a> { - pub stats: IngestionStats, - pub samples_queued: u64, - pub precompute_backlog: u64, - pub persist_backlog: u64, - pub persist_backlog_bytes: u64, - pub now_ms: i64, - pub query_time_results: &'a QueryTimeResults, - /// `None` when the result cache is off. - pub result_cache: Option<&'a ResultCache>, -} - -/// `metrics` and `gauges` in the Prometheus text format. -pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { - let mut out = String::new(); - let family = |out: &mut String, name: &str, kind: &str, help: &str| { - let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {kind}"); - }; - - family( - &mut out, - "asap_phase_runs_total", - "counter", - "Runs of each measured phase.", - ); - family( - &mut out, - "asap_phase_cpu_seconds_total", - "counter", - "Thread CPU time of each measured phase.", - ); - family( - &mut out, - "asap_phase_wall_seconds_total", - "counter", - "Wall time of each measured phase.", - ); - metrics - .remote_write_decode - .render(&mut out, "phase=\"remote_write_decode\""); - metrics.append.render(&mut out, "phase=\"append\""); - if let Some(tier) = metrics.view_tier.get() { - tier.decode.render(&mut out, "phase=\"view_decode\""); - } - for (labels, stats) in &metrics.precompute { - stats.render(&mut out, labels); - } - if let Some(push) = &metrics.push { - push.render(&mut out); - } - for (query, query_metrics) in &metrics.queries { - let labels = format!("phase=\"query\",query=\"{}\"", escape(query)); - query_metrics.run.render(&mut out, &labels); - let labels = format!("phase=\"query_range_step\",query=\"{}\"", escape(query)); - query_metrics.range_step_run.render(&mut out, &labels); - } - - family( - &mut out, - "asap_query_latency_seconds", - "histogram", - "Planned instant query latency in the engine, queueing for a worker included.", - ); - for (query, query_metrics) in &metrics.queries { - let labels = format!("query=\"{}\"", escape(query)); - query_metrics - .latency - .render(&mut out, "asap_query_latency_seconds", &labels); - } - family( - &mut out, - "asap_range_query_latency_seconds", - "histogram", - "Planned range query latency, every step included.", - ); - for (query, query_metrics) in &metrics.queries { - let labels = format!("query=\"{}\"", escape(query)); - query_metrics - .range_latency - .render(&mut out, "asap_range_query_latency_seconds", &labels); - } - for (name, help, count) in [ - ( - "asap_range_query_steps_total", - "Steps of the planned range requests answered.", - (|m: &QueryMetrics| &m.range_steps) as fn(&QueryMetrics) -> &AtomicU64, - ), - ( - "asap_range_query_steps_cached_total", - "Steps of the planned range requests the result cache answered.", - |m: &QueryMetrics| &m.range_steps_cached, - ), - ] { - family(&mut out, name, "counter", help); - for (query, query_metrics) in &metrics.queries { - let _ = writeln!( - out, - "{name}{{query=\"{}\"}} {}", - escape(query), - count(query_metrics).load(Ordering::Relaxed) - ); - } - } - - family( - &mut out, - "asap_samples_total", - "counter", - "Samples by what ingestion did with them.", - ); - let stats = gauges.stats; - for (outcome, count) in [ - ("accepted", stats.samples_accepted), - ("dropped_late", stats.samples_dropped_late), - ("dropped_future", stats.samples_dropped_future), - ("unrouted", stats.samples_unrouted), - ("late_for_views", stats.samples_late_for_views), - ] { - let _ = writeln!(out, "asap_samples_total{{outcome=\"{outcome}\"}} {count}"); - } - if let Some(push) = &metrics.push { - push.render_gauges(&mut out); - } - family( - &mut out, - "asap_windows_total", - "counter", - "Refresh windows by outcome.", - ); - for (outcome, count) in [ - ("refreshed", stats.windows_refreshed), - ("failed", stats.windows_failed), - ("skipped_first", stats.windows_skipped_first), - ("skipped_expired", stats.windows_skipped_expired), - ("already_stored", stats.windows_already_stored), - ] { - let _ = writeln!(out, "asap_windows_total{{outcome=\"{outcome}\"}} {count}"); - } - - let gauge = |out: &mut String, name: &str, help: &str, value: f64| { - let _ = writeln!( - out, - "# HELP {name} {help}\n# TYPE {name} gauge\n{name} {value}" - ); - }; - gauge( - &mut out, - "asap_samples_queued", - "Samples queued for the ingest shards.", - gauges.samples_queued as f64, - ); - gauge( - &mut out, - "asap_precompute_backlog_windows", - "Refresh windows closed and not yet refreshed.", - gauges.precompute_backlog as f64, - ); - gauge( - &mut out, - "asap_persist_backlog_windows", - "Refreshed windows not yet written to the view files.", - gauges.persist_backlog as f64, - ); - gauge( - &mut out, - "asap_persist_backlog_bytes", - "Bytes of refreshed windows queued for the persist threads.", - gauges.persist_backlog_bytes as f64, - ); - let watermark_ms = metrics.watermark_ms.load(Ordering::Relaxed); - if watermark_ms != i64::MIN { - gauge( - &mut out, - "asap_watermark_lag_seconds", - "Wall clock minus the watermark.", - (gauges.now_ms - watermark_ms) as f64 / 1e3, - ); - } - let load = |value: &AtomicU64| value.load(Ordering::Relaxed) as f64; - gauge( - &mut out, - "asap_raw_data_bytes", - "Bytes of raw samples held.", - load(&metrics.raw_data_bytes), - ); - gauge( - &mut out, - "asap_raw_data_samples", - "Raw samples held.", - load(&metrics.raw_data_samples), - ); - gauge( - &mut out, - "asap_raw_data_panes", - "Raw-data panes held, over every metric.", - load(&metrics.raw_data_panes), - ); - gauge( - &mut out, - "asap_view_bytes", - "Bytes of materialized view rows held.", - load(&metrics.view_bytes), - ); - if let Some(tier) = metrics.view_tier.get() { - let cache = tier.cache.stats(); - for (name, help, value) in [ - ( - "asap_view_cache_bytes", - "Bytes of decoded view windows in the window cache.", - cache.bytes as f64, - ), - ( - "asap_view_cache_entries", - "View windows in the window cache.", - cache.entries as f64, - ), - ( - "asap_view_pending_bytes", - "Bytes of view windows committed and not yet written to the view files.", - load(&tier.pending_bytes), - ), - ( - "asap_view_pinned_bytes", - "Bytes of view windows that cannot be written, kept in memory.", - load(&tier.pinned_bytes), - ), - ( - "asap_view_file_bytes", - "Bytes of the view files (segments) held.", - load(&metrics.view_file_bytes), - ), - ] { - gauge(&mut out, name, help, value); - } - for (name, help, value) in [ - ( - "asap_view_cache_hits_total", - "View window reads the window cache answered.", - cache.hits, - ), - ( - "asap_view_cache_misses_total", - "View window reads the window cache did not answer.", - cache.misses, - ), - ( - "asap_view_cache_evictions_total", - "View windows evicted from the window cache.", - cache.evictions, - ), - ( - "asap_view_cold_reads_total", - "View windows decoded from the view files.", - load(&tier.cold_reads) as u64, - ), - ( - "asap_view_cold_read_bytes_total", - "Bytes of the view files decoded.", - load(&tier.cold_read_bytes) as u64, - ), - ] { - family(&mut out, name, "counter", help); - let _ = writeln!(out, "{name} {value}"); - } - } - for (name, help, value) in [ - ( - "asap_view_persisted_bytes_total", - "Bytes written to the view files.", - load(&metrics.view_persisted_bytes), - ), - ( - "asap_view_sync_seconds_total", - "Time spent syncing the view files.", - load(&metrics.view_sync_ns) / 1e9, - ), - ( - "asap_view_windows_not_persisted_total", - "View windows not written to the view files (a sketch state, or an error).", - load(&metrics.view_windows_not_persisted), - ), - ( - "asap_view_segments_marked_cold_total", - "View segments whose pages were advised cold (MADV_COLD, POSIX_FADV_DONTNEED) once a newer sealed segment of their refresh group existed.", - load(&metrics.view_segments_marked_cold), - ), - ( - "asap_view_persist_over_bound_total", - "Windows queued for the view files while the queue held more than --max-persist-backlog-bytes (the data plane does not wait for its disk).", - load(&metrics.view_persist_over_bound), - ), - ( - "asap_view_windows_loaded_total", - "View windows loaded from the view files at startup.", - load(&metrics.view_windows_loaded), - ), - ] { - family(&mut out, name, "counter", help); - let _ = writeln!(out, "{name} {value}"); - } - let seconds = |ns: &AtomicU64| ns.load(Ordering::Relaxed) as f64 / 1e9; - for (name, help, value) in [ - ( - "asap_precompute_windows_total", - "Refresh windows committed, by refresh group.", - (|w: &WindowLatency| w.windows.load(Ordering::Relaxed) as f64) - as fn(&WindowLatency) -> f64, - ), - ( - "asap_precompute_queue_wait_seconds_total", - "Time from a window closing to its computation starting, by refresh group.", - |w| w.queue_wait_ns.load(Ordering::Relaxed) as f64 / 1e9, - ), - ( - "asap_precompute_commit_wait_seconds_total", - "Time from a window computed to its commit, waiting for the group's earlier windows.", - |w| w.commit_wait_ns.load(Ordering::Relaxed) as f64 / 1e9, - ), - ( - "asap_window_ready_seconds_total", - "Time from a window's end (event time) to its commit (wall clock), by refresh group.", - |w| w.ready_ms.load(Ordering::Relaxed) as f64 / 1e3, - ), - ] { - family(&mut out, name, "counter", help); - for (group, windows) in metrics.precompute_windows.iter().enumerate() { - let _ = writeln!(out, "{name}{{group=\"{group}\"}} {}", value(windows)); - } - } - family( - &mut out, - "asap_window_ready_seconds_max", - "gauge", - "The longest time from a window's end to its commit, by refresh group.", - ); - for (group, windows) in metrics.precompute_windows.iter().enumerate() { - let _ = writeln!( - out, - "asap_window_ready_seconds_max{{group=\"{group}\"}} {}", - windows.ready_max_ms.load(Ordering::Relaxed) as f64 / 1e3 - ); - } - family( - &mut out, - "asap_precompute_window_parts", - "gauge", - "The runs a refresh group's window is split into, by series; 1 when some node combines series.", - ); - for (group, windows) in metrics.precompute_windows.iter().enumerate() { - let _ = writeln!( - out, - "asap_precompute_window_parts{{group=\"{group}\"}} {}", - windows.parts.load(Ordering::Relaxed) - ); - } - family( - &mut out, - "asap_precompute_busy_seconds_total", - "counter", - "Wall time the precompute threads spent computing windows; divided by asap_precompute_threads, the task pool's utilisation.", - ); - let _ = writeln!( - out, - "asap_precompute_busy_seconds_total {}", - seconds(&metrics.precompute_busy_ns) - ); - gauge( - &mut out, - "asap_precompute_threads", - "Threads computing refresh windows.", - load(&metrics.precompute_threads), - ); - let results = gauges.query_time_results; - gauge( - &mut out, - "asap_query_time_result_bytes", - "Bytes of query-time OneEvaluation results held.", - results.bytes() as f64, - ); - gauge( - &mut out, - "asap_query_time_results", - "Query-time OneEvaluation results held, computed or being computed.", - results.len() as f64, - ); - family( - &mut out, - "asap_query_time_result_computes_total", - "counter", - "Query-time OneEvaluation results computed (misses).", - ); - let _ = writeln!( - out, - "asap_query_time_result_computes_total {}", - results.computes() - ); - family( - &mut out, - "asap_query_time_result_hits_total", - "counter", - "Reads of a query-time OneEvaluation result already computed.", - ); - let _ = writeln!(out, "asap_query_time_result_hits_total {}", results.hits()); - if let Some(cache) = gauges.result_cache { - gauge( - &mut out, - "asap_result_cache_bytes", - "Bytes of final query answers the result cache keeps (estimated).", - cache.bytes() as f64, - ); - gauge( - &mut out, - "asap_result_cache_entries", - "Final query answers the result cache keeps, by query and evaluation time.", - cache.len() as f64, - ); - for (name, help, value) in [ - ( - "asap_result_cache_hits_total", - "Result cache lookups that found the answer.", - cache.hits(), - ), - ( - "asap_result_cache_misses_total", - "Result cache lookups that found no answer.", - cache.misses(), - ), - ( - "asap_result_cache_evictions_total", - "Answers the result cache dropped by age or by bytes.", - cache.evictions(), - ), - ] { - family(&mut out, name, "counter", help); - let _ = writeln!(out, "{name} {value}"); - } - } - if let Some(rss) = resident_bytes() { - gauge( - &mut out, - "process_resident_memory_bytes", - "Resident memory of the process.", - rss as f64, - ); - } - - family( - &mut out, - "asap_thread_cpu_seconds_total", - "counter", - "CPU time of the live threads, by name (trailing digits removed).", - ); - for (thread, seconds) in thread_cpu_seconds() { - let _ = writeln!( - out, - "asap_thread_cpu_seconds_total{{thread=\"{}\"}} {seconds}", - escape(&thread) - ); - } - out -} - -/// `text` as a label value. -fn escape(text: &str) -> String { - text.replace('\\', "\\\\") - .replace('"', "\\\"") - .replace('\n', "\\n") -} - -/// Resident set size, from `/proc/self/statm`. -fn resident_bytes() -> Option { - let statm = std::fs::read_to_string("/proc/self/statm").ok()?; - let pages: u64 = statm.split(' ').nth(1)?.parse().ok()?; - // SAFETY: sysconf has no preconditions. - let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; - Some(pages * u64::try_from(page_size).ok()?) -} - /// CPU seconds of each live thread, summed by name with trailing digits /// removed (`query-0`, `query-1`, … are `query-`). pub fn thread_cpu_seconds() -> BTreeMap { @@ -889,45 +407,17 @@ pub fn thread_cpu_seconds() -> BTreeMap { mod tests { use super::*; - /// A phase records the thread CPU it burns, and the text format names - /// each phase and query. + /// A phase records the thread CPU it burns. #[test] - fn records_and_renders_phases() { - let metrics = Metrics::new( - &[(10_000, vec!["3".into(), "5".into()])], - &["sum(x)".to_string()], - ); + fn a_phase_records_its_thread_cpu() { + let stats = PhaseStats::default(); let timer = Timer::start(); let mut x = 0u64; for i in 0..5_000_000u64 { x = x.wrapping_add(i * i); } std::hint::black_box(x); - metrics.append.record(timer); - assert!(metrics.append.cpu_ns.load(Ordering::Relaxed) > 0); - metrics.query("sum(x) ").unwrap().latency.observe(0.003); - let text = render( - &metrics, - &Gauges { - stats: IngestionStats::default(), - samples_queued: 0, - precompute_backlog: 2, - persist_backlog: 0, - persist_backlog_bytes: 0, - now_ms: 0, - query_time_results: &QueryTimeResults::new(0, 0), - result_cache: None, - }, - ); - assert!( - text.contains("asap_phase_runs_total{phase=\"append\"} 1"), - "{text}" - ); - assert!(text.contains( - "asap_phase_cpu_seconds_total{phase=\"precompute\",group=\"0\",window_ms=\"10000\",views=\"3,5\"} 0" - )); - assert!(text.contains("asap_query_latency_seconds_bucket{query=\"sum(x)\",le=\"0.005\"} 1")); - assert!(text.contains("asap_precompute_backlog_windows 2")); - assert!(text.contains("asap_thread_cpu_seconds_total{thread=")); + stats.record(timer); + assert!(stats.cpu_ns.load(Ordering::Relaxed) > 0); } } diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml new file mode 100644 index 000000000..87abdbe66 --- /dev/null +++ b/crates/storage/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "storage" +version.workspace = true +edition.workspace = true + +[dependencies] +internal_metrics.workspace = true +asap-executor.workspace = true +asap_sketchlib.workspace = true +serde_bytes = "0.11" +# Each view fragment is compressed (segment.rs). +zstd = "0.13" +ahash = "0.8" +libc = "0.2" +serde.workspace = true +serde_json.workspace = true +tracing.workspace = true +# `ViewRead` is a command-line value of the data plane (`--view-read`). +clap.workspace = true +rmp-serde = "1" +futures = "0.3" diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs new file mode 100644 index 000000000..f4c3e9772 --- /dev/null +++ b/crates/storage/src/lib.rs @@ -0,0 +1,12 @@ +//! The data plane's stores: the raw samples the plan's `Scan`s read and the +//! materialized views its precompute writes ([`store`]), the views' window +//! cache and memory budget, their on-disk segments and persistence, the +//! state codecs, and the process-wide series interner. + +pub mod memory_budget; +pub mod persist; +pub mod segment; +pub mod series_ids; +mod state_codec; +pub mod store; +pub mod window_cache; diff --git a/crates/storage/src/persist.rs b/crates/storage/src/persist.rs index aa4f286d2..332cea05c 100644 --- a/crates/storage/src/persist.rs +++ b/crates/storage/src/persist.rs @@ -536,7 +536,7 @@ impl ViewFiles { &mut self, groups: &[Vec<(MaterializedView, SchemaRef)>], ) -> std::io::Result { - let millis = |view: &MaterializedView| crate::ingestion::millis(view.retention_ms()); + let millis = |view: &MaterializedView| crate::store::millis(view.retention_ms()); for (view, _) in groups.iter().flatten() { self.view_retention_ms.insert(view.node_id, millis(view)); } diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 3b1099524..0afea77a5 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -31,7 +31,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::ops::Bound; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, RwLock}; use asap_executor::arrow::array::{ @@ -48,9 +48,8 @@ use asap_executor::sources::{DataStore, MaterializedViewRequest, RawDataRequest} use asap_executor::values::{Batch, BatchColumn, SchemaRef}; use asap_executor::Error; use futures::{stream, StreamExt}; +use internal_metrics::{PhaseStats, Timer}; -use crate::ingestion::window_end; -use crate::metrics::{PhaseStats, Timer}; use crate::persist::{ViewRead, WindowLocation}; use crate::series_ids::Series; use crate::window_cache::{WindowCache, WindowKey}; @@ -355,7 +354,7 @@ impl RawData { /// when `None`) as batches of `request`'s schema: one per chunk of the /// panes overlapping the range, the open pane's included. A chunk read /// whole is converted once per `reads` and shared by its later reads. - pub(crate) fn read( + pub fn read( &self, metric: &str, request: &RawDataRequest, @@ -433,7 +432,7 @@ impl SeriesPartition { /// One run's part of the series and the stored chunks it has cut to that /// part, so the run's scans filter each chunk (and build its series /// identities) once, as a whole run reads each chunk's cached ones. -pub(crate) struct PartitionReads { +pub struct PartitionReads { partition: SeriesPartition, /// By chunk address; each entry holds the chunk, so its address is not /// reused while it is kept. @@ -685,7 +684,19 @@ pub type ViewRowsByView = BTreeMap i64 { - newest_end.saturating_sub(crate::ingestion::millis(view.retention_ms())) + newest_end.saturating_sub(millis(view.retention_ms())) +} + +/// A duration option in milliseconds as a time offset, saturating. +pub fn millis(value: u64) -> i64 { + i64::try_from(value).unwrap_or(i64::MAX) +} + +/// End of the tumbling window of width `width_ms` (on multiples of it) +/// that holds `timestamp_ms`. Windows are `(end - width_ms, end]`, like +/// PromQL ranges: a sample at a boundary belongs to the window it ends. +pub fn window_end(timestamp_ms: i64, width_ms: i64) -> i64 { + -((-timestamp_ms).div_euclid(width_ms)) * width_ms } /// Rows stored for one view: one entry per appended window, oldest first. @@ -740,6 +751,27 @@ impl ViewTier { } } +/// The view cache's monitor: once a second, drops idle windows and, under +/// a cgroup memory limit, lowers the cache's target while anonymous memory +/// runs higher than its budget assumed. +pub fn serve_view_cache(tier: Arc, budget: Option, running: Arc) { + let cgroup = crate::memory_budget::own_cgroup(); + while running.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_secs(1)); + tier.cache.evict_idle(std::time::Instant::now()); + if let Some(memory) = cgroup + .as_ref() + .and_then(|dir| crate::memory_budget::read_cgroup(dir).ok()) + { + let cached = tier.cache.stats().bytes; + tier.cache + .set_target_bytes(crate::memory_budget::monitored_target( + budget, &memory, cached, + )); + } + } +} + /// Where a committed window's rows are. enum SlotState { /// Committed, not yet written to a file: in memory. @@ -1434,7 +1466,7 @@ type QueryTimeEntry = Arc<(Mutex>, Condvar)>; /// one at a later time is computed by each run that needs it. A result is /// kept while `T` is within `retention_ms` of the watermark, and the /// oldest are dropped while more than `max_bytes` are held. -pub struct QueryTimeResults { +pub struct QueryTimeResults { entries: Mutex>>, retention_ms: i64, max_bytes: usize, diff --git a/crates/storage/tests/series_ids.rs b/crates/storage/tests/series_ids.rs index 247408e99..27231c65e 100644 --- a/crates/storage/tests/series_ids.rs +++ b/crates/storage/tests/series_ids.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; -use data_plane::series_ids::intern_pairs; +use storage::series_ids::intern_pairs; fn labels(pairs: &[(&str, &str)]) -> BTreeMap { pairs diff --git a/crates/storage/tests/view_cache_charge.rs b/crates/storage/tests/view_cache_charge.rs index 556815a38..6c457e6b7 100644 --- a/crates/storage/tests/view_cache_charge.rs +++ b/crates/storage/tests/view_cache_charge.rs @@ -15,9 +15,9 @@ use std::time::Duration; use asap_executor::planner::ir::schema::{DataType, Field, Schema, PROMQL_SERIES_IDENTITY}; use asap_executor::planner::plan::materialized_view::MaterializedView; use asap_executor::values::{Batch, Value}; -use data_plane::persist::{ViewFiles, ViewRead}; -use data_plane::store::{ViewStore, ViewTier}; -use data_plane::window_cache::{WindowCache, WindowKey}; +use storage::persist::{ViewFiles, ViewRead}; +use storage::store::{ViewStore, ViewTier}; +use storage::window_cache::{WindowCache, WindowKey}; /// Counts the bytes allocated now. struct Counting; From e1d04fb112c0fe03dcc5e966c31ec26f822f9926 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 07:57:39 +0000 Subject: [PATCH 3/5] ci: format-check the internal_metrics and storage packages --- .github/workflows/mvp-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/mvp-ci.yml b/.github/workflows/mvp-ci.yml index 560dadb0e..3c8caaea0 100644 --- a/.github/workflows/mvp-ci.yml +++ b/.github/workflows/mvp-ci.yml @@ -53,7 +53,7 @@ jobs: - name: Check workspace formatting working-directory: ASAPQuery-backend - run: cargo fmt -p control_plane -p data_plane -- --check + run: cargo fmt -p control_plane -p data_plane -p internal_metrics -p storage -- --check - name: Check workspace env: From c67346f6041e5b30ca75ea612d8d264928686248 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 08:06:38 +0000 Subject: [PATCH 4/5] refactor: review fixes for the storage and internal-metrics split serve_view_cache sits in memory_budget next to what it calls, so monitored_target is private; Gauges and render are pub(crate); the internal_metrics crate doc says what it holds now. --- crates/data-plane/src/engine.rs | 8 +++---- crates/data-plane/src/metrics_endpoint.rs | 6 +++--- crates/data-plane/tests/view_tiering.rs | 4 ++-- crates/internal-metrics/src/lib.rs | 12 +++++------ crates/storage/src/memory_budget.rs | 26 ++++++++++++++++++----- crates/storage/src/store.rs | 23 +------------------- 6 files changed, 37 insertions(+), 42 deletions(-) diff --git a/crates/data-plane/src/engine.rs b/crates/data-plane/src/engine.rs index 988e2affc..113137131 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -33,13 +33,15 @@ use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock}; use std::time::Instant; +use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::runtime::Limits; +use asap_executor::values::Batch; use asap_planner::InstallablePlan; use internal_metrics::{Metrics, PushMetrics, Timer}; +use storage::memory_budget::serve_view_cache; use storage::persist::{plan_hash, ViewFiles, ViewRead}; -use storage::store::SeriesPartition; use storage::store::{ - serve_view_cache, PublishedStore, QueryTimeResults, RawData, RawSample, RawShards, RunStore, + PublishedStore, QueryTimeResults, RawData, RawSample, RawShards, RunStore, SeriesPartition, ViewStore, ViewTier, WindowSlot, }; use storage::window_cache::WindowCache; @@ -53,8 +55,6 @@ use crate::metrics_endpoint::Gauges; use crate::push::{Partial, PushGroup, PushShard}; use crate::query::{QueryEngine, Snapshot, Unanswered}; use crate::result_cache::{Answer, ResultCache}; -use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; -use asap_executor::values::Batch; /// How the views of a closed refresh window are built /// (docs/design/parallel-precompute.md). The `data_plane` binary defaults diff --git a/crates/data-plane/src/metrics_endpoint.rs b/crates/data-plane/src/metrics_endpoint.rs index 1502233f8..7978c713d 100644 --- a/crates/data-plane/src/metrics_endpoint.rs +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -13,7 +13,7 @@ use crate::query::Unanswered; use crate::result_cache::ResultCache; /// What `/metrics` reports beside [`Metrics`]. -pub struct Gauges<'a> { +pub(crate) struct Gauges<'a> { pub stats: IngestionStats, pub samples_queued: u64, pub precompute_backlog: u64, @@ -28,7 +28,7 @@ pub struct Gauges<'a> { } /// `metrics` and `gauges` in the Prometheus text format. -pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { +pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { let mut out = String::new(); let family = |out: &mut String, name: &str, kind: &str, help: &str| { let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {kind}"); @@ -501,7 +501,7 @@ mod tests { /// The text format names each phase and query. #[test] - fn records_and_renders_phases() { + fn renders_phases_and_queries() { let metrics = Metrics::new( &[(10_000, vec!["3".into(), "5".into()])], &["sum(x)".to_string()], diff --git a/crates/data-plane/tests/view_tiering.rs b/crates/data-plane/tests/view_tiering.rs index 14100d18d..a2ca1e6f4 100644 --- a/crates/data-plane/tests/view_tiering.rs +++ b/crates/data-plane/tests/view_tiering.rs @@ -3,8 +3,8 @@ //! Tests V7–V12, V16 and V17 of the design's test plan, end to end through //! the HTTP API; the parity test V1 is in `planner_executor_parity.rs` and //! the unit tests are next to the code (`crates/storage`: `persist.rs`, -//! `window_cache.rs`, `memory_budget.rs`). Each compares a tiered data plane with one that -//! keeps every window in memory (the control). +//! `window_cache.rs`, `memory_budget.rs`). Each compares a tiered data +//! plane with one that keeps every window in memory (the control). mod common; diff --git a/crates/internal-metrics/src/lib.rs b/crates/internal-metrics/src/lib.rs index bbc90d51b..85ec3a1e0 100644 --- a/crates/internal-metrics/src/lib.rs +++ b/crates/internal-metrics/src/lib.rs @@ -1,9 +1,9 @@ -//! The data plane's own measurements, for profiling and benchmarks, -//! exported on `GET /metrics` in the Prometheus text format: thread CPU -//! time and wall time of each phase (Remote Write decode, append, -//! precompute per refresh group, query run per query text), query -//! latency, sample and window counters, backlogs, watermark lag, bytes -//! held, and each thread's CPU time by name. +//! The data plane's own measurements, for profiling and benchmarks: thread +//! CPU time and wall time of each phase (Remote Write decode, append, +//! precompute per refresh group, query run per query text), query latency, +//! the watermark, bytes held, and each thread's CPU time by name. The data +//! plane renders them, with the stores' and the engine's gauges, on +//! `GET /metrics` in the Prometheus text format. use std::collections::BTreeMap; use std::fmt::Write; diff --git a/crates/storage/src/memory_budget.rs b/crates/storage/src/memory_budget.rs index 3c1b274bb..d9dba1319 100644 --- a/crates/storage/src/memory_budget.rs +++ b/crates/storage/src/memory_budget.rs @@ -8,6 +8,10 @@ //! as headroom for page cache of the segments being written and read. use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use crate::store::ViewTier; /// What a cgroup v2 directory reports about memory. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] @@ -85,11 +89,7 @@ pub fn default_view_cache_budget(cgroup: &CgroupMemory, other_pools_bytes: u64) /// The cache's target for the next second: `budget` while anonymous /// memory stays within `memory.max` less the headroom; otherwise the /// cached bytes less the excess (at least zero). -pub fn monitored_target( - budget: Option, - cgroup: &CgroupMemory, - cached_bytes: u64, -) -> Option { +fn monitored_target(budget: Option, cgroup: &CgroupMemory, cached_bytes: u64) -> Option { let Some(max) = cgroup.max_bytes else { return budget; }; @@ -101,6 +101,22 @@ pub fn monitored_target( Some(budget.map_or(lowered, |budget| budget.min(lowered))) } +/// The view cache's monitor: once a second, drops idle windows and, under +/// a cgroup memory limit, lowers the cache's target while anonymous memory +/// runs higher than its budget assumed. +pub fn serve_view_cache(tier: Arc, budget: Option, running: Arc) { + let cgroup = own_cgroup(); + while running.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_secs(1)); + tier.cache.evict_idle(std::time::Instant::now()); + if let Some(memory) = cgroup.as_ref().and_then(|dir| read_cgroup(dir).ok()) { + let cached = tier.cache.stats().bytes; + tier.cache + .set_target_bytes(monitored_target(budget, &memory, cached)); + } + } +} + #[cfg(test)] mod tests { //! Test V14 of docs/design/tiered-view-storage.md. diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 0afea77a5..4ed237f08 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -31,7 +31,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::ops::Bound; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, RwLock}; use asap_executor::arrow::array::{ @@ -751,27 +751,6 @@ impl ViewTier { } } -/// The view cache's monitor: once a second, drops idle windows and, under -/// a cgroup memory limit, lowers the cache's target while anonymous memory -/// runs higher than its budget assumed. -pub fn serve_view_cache(tier: Arc, budget: Option, running: Arc) { - let cgroup = crate::memory_budget::own_cgroup(); - while running.load(Ordering::SeqCst) { - std::thread::sleep(std::time::Duration::from_secs(1)); - tier.cache.evict_idle(std::time::Instant::now()); - if let Some(memory) = cgroup - .as_ref() - .and_then(|dir| crate::memory_budget::read_cgroup(dir).ok()) - { - let cached = tier.cache.stats().bytes; - tier.cache - .set_target_bytes(crate::memory_budget::monitored_target( - budget, &memory, cached, - )); - } - } -} - /// Where a committed window's rows are. enum SlotState { /// Committed, not yet written to a file: in memory. From f93e5e73ea9832c9f5eca4be8517b1576197bf76 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 22:29:43 +0000 Subject: [PATCH 5/5] refactor: whole-stack review fixes for the storage and internal-metrics split - CI checks formatting with cargo fmt --all, so a new crate is checked too (the README and pre-commit already run it). - The /proc resident-memory reader moves to internal-metrics, next to the other /proc readers; libc is only a dev-dependency of data-plane (the benchmarks' posix_fadvise). - storage items used only inside storage are pub(crate): the segment format version and Segment's seal/end/forget helpers, the persisted view index, the state and text-key codecs, labels_of_identity, the window cache's get_or_load and evict_idle. --- .github/workflows/mvp-ci.yml | 2 +- crates/data-plane/Cargo.toml | 3 ++- crates/data-plane/src/metrics_endpoint.rs | 11 +---------- crates/internal-metrics/src/lib.rs | 9 +++++++++ crates/storage/src/persist.rs | 5 +++-- crates/storage/src/segment.rs | 8 ++++---- crates/storage/src/series_ids.rs | 2 +- crates/storage/src/state_codec.rs | 18 +++++++++++------- crates/storage/src/window_cache.rs | 4 ++-- 9 files changed, 34 insertions(+), 28 deletions(-) diff --git a/.github/workflows/mvp-ci.yml b/.github/workflows/mvp-ci.yml index 3c8caaea0..867994814 100644 --- a/.github/workflows/mvp-ci.yml +++ b/.github/workflows/mvp-ci.yml @@ -53,7 +53,7 @@ jobs: - name: Check workspace formatting working-directory: ASAPQuery-backend - run: cargo fmt -p control_plane -p data_plane -p internal_metrics -p storage -- --check + run: cargo fmt --all -- --check - name: Check workspace env: diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index 603b15fbb..5f78c885b 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -14,7 +14,6 @@ ahash = "0.8" hashbrown = "0.15" # Shortest round-trip float digits for range responses (prometheus.rs). ryu = "1" -libc = "0.2" # The data plane's allocator (main.rs): many small per-request allocations. tikv-jemallocator = "0.6" serde.workspace = true @@ -37,6 +36,8 @@ control_plane.workspace = true asap_sketchlib.workspace = true tower = { version = "0.5", features = ["util"] } http-body-util = "0.1" +# posix_fadvise in the tier and view-read benchmarks (cold reads). +libc = "0.2" # The micro benchmarks live in benchmarks/micro/ and build as examples of this # crate (`cargo run --release -p data_plane --example `). diff --git a/crates/data-plane/src/metrics_endpoint.rs b/crates/data-plane/src/metrics_endpoint.rs index 7978c713d..0af0e7b17 100644 --- a/crates/data-plane/src/metrics_endpoint.rs +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -452,7 +452,7 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { let _ = writeln!(out, "{name} {value}"); } } - if let Some(rss) = resident_bytes() { + if let Some(rss) = internal_metrics::resident_bytes() { gauge( &mut out, "process_resident_memory_bytes", @@ -484,15 +484,6 @@ fn escape(text: &str) -> String { .replace('\n', "\\n") } -/// Resident set size, from `/proc/self/statm`. -fn resident_bytes() -> Option { - let statm = std::fs::read_to_string("/proc/self/statm").ok()?; - let pages: u64 = statm.split(' ').nth(1)?.parse().ok()?; - // SAFETY: sysconf has no preconditions. - let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; - Some(pages * u64::try_from(page_size).ok()?) -} - #[cfg(test)] mod tests { use internal_metrics::Timer; diff --git a/crates/internal-metrics/src/lib.rs b/crates/internal-metrics/src/lib.rs index 85ec3a1e0..abaa112f6 100644 --- a/crates/internal-metrics/src/lib.rs +++ b/crates/internal-metrics/src/lib.rs @@ -371,6 +371,15 @@ impl Metrics { } } +/// The process's resident set size, from `/proc/self/statm`. +pub fn resident_bytes() -> Option { + let statm = std::fs::read_to_string("/proc/self/statm").ok()?; + let pages: u64 = statm.split(' ').nth(1)?.parse().ok()?; + // SAFETY: sysconf has no preconditions. + let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + Some(pages * u64::try_from(page_size).ok()?) +} + /// CPU seconds of each live thread, summed by name with trailing digits /// removed (`query-0`, `query-1`, … are `query-`). pub fn thread_cpu_seconds() -> BTreeMap { diff --git a/crates/storage/src/persist.rs b/crates/storage/src/persist.rs index 332cea05c..9ea8cee93 100644 --- a/crates/storage/src/persist.rs +++ b/crates/storage/src/persist.rs @@ -58,8 +58,9 @@ use asap_sketchlib::{ }; use serde::{Deserialize, Serialize}; +pub(crate) use crate::segment::FORMAT_VERSION; use crate::segment::{encode_fragment, RecordHead, Segment, SegmentHeader, SegmentTexts}; -pub use crate::segment::{ViewRead, WindowLocation, FORMAT_VERSION}; +pub use crate::segment::{ViewRead, WindowLocation}; /// The kernels whose sketch state is stored as ASAPv1 bytes, with what /// rebuilding one needs beyond the bytes. @@ -123,7 +124,7 @@ pub struct Written { /// The windows indexed at startup, by view: each window's range and /// location, oldest first. -pub type ViewIndex = BTreeMap>; +pub(crate) type ViewIndex = BTreeMap>; /// The segment being appended to, with its texts by text. struct ActiveSegment { diff --git a/crates/storage/src/segment.rs b/crates/storage/src/segment.rs index 44682f5d8..13d34a4e5 100644 --- a/crates/storage/src/segment.rs +++ b/crates/storage/src/segment.rs @@ -50,7 +50,7 @@ use crate::state_codec::{ }; /// The view file format version these segments are. -pub const FORMAT_VERSION: u32 = 4; +pub(crate) const FORMAT_VERSION: u32 = 4; /// Frame kinds. const HEADER_FRAME: u32 = 0; @@ -398,12 +398,12 @@ impl Segment { self.len() == 0 } - pub fn is_sealed(&self) -> bool { + pub(crate) fn is_sealed(&self) -> bool { self.sealed.load(Ordering::SeqCst) } /// The newest window end of its records. - pub fn max_end_ms(&self) -> i64 { + pub(crate) fn max_end_ms(&self) -> i64 { self.max_end_ms.load(Ordering::SeqCst) } @@ -841,7 +841,7 @@ impl SegmentTexts<'_> { } /// Drops the new texts after the first `mark` (a fragment left out). - pub fn forget_after(&mut self, mark: usize) { + pub(crate) fn forget_after(&mut self, mark: usize) { for text in self.new.drain(mark..) { self.new_index.remove(&text); } diff --git a/crates/storage/src/series_ids.rs b/crates/storage/src/series_ids.rs index ab7c0ae84..af3e76fb0 100644 --- a/crates/storage/src/series_ids.rs +++ b/crates/storage/src/series_ids.rs @@ -201,7 +201,7 @@ pub fn result_labels(identity: &str) -> Result { /// The labels of the series whose identity text is `identity`: an /// interned series' own (no parse), else parsed once ([`result_labels`]); /// `None` when `identity` is not a label set's JSON. -pub fn labels_of_identity(identity: &str) -> Option>> { +pub(crate) fn labels_of_identity(identity: &str) -> Option>> { match by_identity(identity) { Some(series) => Some(series.labels().clone()), None => result_labels(identity).ok(), diff --git a/crates/storage/src/state_codec.rs b/crates/storage/src/state_codec.rs index c84dc241d..147170fdc 100644 --- a/crates/storage/src/state_codec.rs +++ b/crates/storage/src/state_codec.rs @@ -27,7 +27,7 @@ /// The state families with a compact form, as the mapped layout names /// them: which fixed-size exact record, or which sketch. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CompactKind { +pub(crate) enum CompactKind { DDSketch, /// Exact sum: `sum`, `compensation` (f64), `seen` (0 or 1). Sum, @@ -45,7 +45,7 @@ pub enum CompactKind { impl CompactKind { /// Its code in a fragment's column descriptor. - pub fn code(self) -> u32 { + pub(crate) fn code(self) -> u32 { match self { Self::DDSketch => 1, Self::Sum => 2, @@ -56,7 +56,7 @@ impl CompactKind { } } - pub fn from_code(code: u32) -> Option { + pub(crate) fn from_code(code: u32) -> Option { Some(match code { 1 => Self::DDSketch, 2 => Self::Sum, @@ -592,7 +592,7 @@ const RAW: u8 = 0xff; /// `kind`) in compact form; `None` when the column has no compact form /// (its sketches differ in index mapping or admission rate, or a state is /// not of `kind`'s layout). -pub fn encode_states( +pub(crate) fn encode_states( kind: CompactKind, states: impl Iterator>, ) -> Option> { @@ -720,7 +720,11 @@ fn put_record( /// layout: the states back to back in 8-byte words (each state starting on /// a word), and their byte offsets (`rows + 1`). `None` when the bytes are /// damaged. -pub fn decode_states(kind: CompactKind, bytes: &[u8], rows: usize) -> Option<(Vec, Vec)> { +pub(crate) fn decode_states( + kind: CompactKind, + bytes: &[u8], + rows: usize, +) -> Option<(Vec, Vec)> { let mut reader = StreamReader::new(bytes)?; // Every row takes at least a byte: `rows` past that is damage, and must // not size an allocation. @@ -844,7 +848,7 @@ fn record( /// A column of text keys in compact form: each a signed varint delta from /// the previous row's. -pub fn encode_text_keys(keys: impl ExactSizeIterator) -> Vec { +pub(crate) fn encode_text_keys(keys: impl ExactSizeIterator) -> Vec { let mut out = Vec::with_capacity(keys.len()); let mut previous = 0i64; for key in keys { @@ -855,7 +859,7 @@ pub fn encode_text_keys(keys: impl ExactSizeIterator) -> Vec { } /// `rows` text keys from their compact form. -pub fn decode_text_keys(bytes: &[u8], rows: usize) -> Option> { +pub(crate) fn decode_text_keys(bytes: &[u8], rows: usize) -> Option> { if rows > bytes.len() { return None; } diff --git a/crates/storage/src/window_cache.rs b/crates/storage/src/window_cache.rs index 90c1abb2e..945c2202f 100644 --- a/crates/storage/src/window_cache.rs +++ b/crates/storage/src/window_cache.rs @@ -194,7 +194,7 @@ impl WindowCache { /// `key`'s batches: cached, or decoded by `load` (its batches and /// bytes) and inserted. Concurrent callers for one key run `load` once /// and share its result or error; an error is not kept. - pub fn get_or_load( + pub(crate) fn get_or_load( &self, key: WindowKey, now: Instant, @@ -251,7 +251,7 @@ impl WindowCache { } /// Drops the entries not read since `now - idle`. - pub fn evict_idle(&self, now: Instant) { + pub(crate) fn evict_idle(&self, now: Instant) { let Some(idle) = self.idle else { return; };