diff --git a/.github/workflows/mvp-ci.yml b/.github/workflows/mvp-ci.yml index 560dadb0e..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 -- --check + run: cargo fmt --all -- --check - name: Check workspace env: 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..5f78c885b 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -6,17 +6,14 @@ 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). 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 @@ -30,15 +27,17 @@ 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" +# 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/engine.rs b/crates/data-plane/src/engine.rs index ea6fbb5bf..113137131 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -33,28 +33,28 @@ 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::{ + PublishedStore, QueryTimeResults, RawData, RawSample, RawShards, RunStore, SeriesPartition, + 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; /// How the views of a closed refresh window are built /// (docs/design/parallel-precompute.md). The `data_plane` binary defaults @@ -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.rs b/crates/data-plane/src/metrics_endpoint.rs similarity index 50% rename from crates/data-plane/src/metrics.rs rename to crates/data-plane/src/metrics_endpoint.rs index e5e646ecf..0af0e7b17 100644 --- a/crates/data-plane/src/metrics.rs +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -1,394 +1,34 @@ -//! 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. +//! `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::collections::BTreeMap; use std::fmt::Write; -use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; -use std::time::Instant; +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; -use crate::store::QueryTimeResults; - -/// CPU time this thread has used, in nanoseconds. -pub fn thread_cpu_ns() -> u64 { - let mut time = libc::timespec { - tv_sec: 0, - tv_nsec: 0, - }; - // SAFETY: `time` is a valid timespec to write. - let status = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut time) }; - if status != 0 { - return 0; - } - time.tv_sec as u64 * 1_000_000_000 + time.tv_nsec as u64 -} - -/// The start of one measured phase on the current thread. -pub struct Timer { - cpu_ns: u64, - wall: Instant, -} - -impl Timer { - pub fn start() -> Self { - Self { - cpu_ns: thread_cpu_ns(), - wall: Instant::now(), - } - } -} - -/// How often a phase ran and the thread CPU and wall time it took. -#[derive(Default)] -pub struct PhaseStats { - runs: AtomicU64, - cpu_ns: AtomicU64, - wall_ns: AtomicU64, -} - -impl PhaseStats { - /// Records one run started at `timer`, ending now on the same thread; - /// returns its wall time in seconds. - pub fn record(&self, timer: Timer) -> f64 { - let wall = timer.wall.elapsed(); - self.runs.fetch_add(1, Ordering::Relaxed); - self.cpu_ns.fetch_add( - thread_cpu_ns().saturating_sub(timer.cpu_ns), - Ordering::Relaxed, - ); - self.wall_ns - .fetch_add(wall.as_nanos() as u64, Ordering::Relaxed); - wall.as_secs_f64() - } - - fn render(&self, out: &mut String, labels: &str) { - let seconds = |ns: &AtomicU64| ns.load(Ordering::Relaxed) as f64 / 1e9; - let _ = writeln!( - out, - "asap_phase_runs_total{{{labels}}} {}", - self.runs.load(Ordering::Relaxed) - ); - let _ = writeln!( - out, - "asap_phase_cpu_seconds_total{{{labels}}} {}", - seconds(&self.cpu_ns) - ); - let _ = writeln!( - out, - "asap_phase_wall_seconds_total{{{labels}}} {}", - seconds(&self.wall_ns) - ); - } -} - -/// Upper bounds of the query latency histogram's buckets, in seconds. -const LATENCY_BUCKETS_S: [f64; 10] = [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 1.0, 5.0]; - -/// A histogram of query latencies. -#[derive(Default)] -pub struct Latency { - /// Observations at or below each bucket's bound (not cumulative). - buckets: [AtomicU64; LATENCY_BUCKETS_S.len()], - count: AtomicU64, - sum_ns: AtomicU64, -} - -impl Latency { - pub fn observe(&self, seconds: f64) { - if let Some(bucket) = LATENCY_BUCKETS_S.iter().position(|b| seconds <= *b) { - self.buckets[bucket].fetch_add(1, Ordering::Relaxed); - } - self.count.fetch_add(1, Ordering::Relaxed); - self.sum_ns - .fetch_add((seconds * 1e9) as u64, Ordering::Relaxed); - } - - 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); - let _ = writeln!(out, "{name}_bucket{{{labels},le=\"{bound}\"}} {cumulative}"); - } - let count = self.count.load(Ordering::Relaxed); - let _ = writeln!(out, "{name}_bucket{{{labels},le=\"+Inf\"}} {count}"); - let _ = writeln!( - out, - "{name}_sum{{{labels}}} {}", - self.sum_ns.load(Ordering::Relaxed) as f64 / 1e9 - ); - let _ = writeln!(out, "{name}_count{{{labels}}} {count}"); - } -} - -/// One refresh group's windows on their way through the precompute task -/// pool. -#[derive(Default)] -pub struct WindowLatency { - /// Windows committed (refreshed, already stored or failed). - pub windows: AtomicU64, - /// From the window closing to its computation starting: the backlog, - /// waiting for the windows it reads and for a free worker. - pub queue_wait_ns: AtomicU64, - /// From its computation ending to its commit: waiting for the group's - /// earlier windows. - pub commit_wait_ns: AtomicU64, - /// From the window's end (event time) to its commit (wall clock). - pub ready_ms: AtomicU64, - pub ready_max_ms: AtomicU64, - /// The runs a window is split into, by series (1: one run). - pub parts: AtomicU64, -} - -impl WindowLatency { - pub fn record( - &self, - queue_wait: std::time::Duration, - commit_wait: std::time::Duration, - ready_ms: i64, - ) { - self.windows.fetch_add(1, Ordering::Relaxed); - self.queue_wait_ns - .fetch_add(queue_wait.as_nanos() as u64, Ordering::Relaxed); - self.commit_wait_ns - .fetch_add(commit_wait.as_nanos() as u64, Ordering::Relaxed); - self.ready_ms.fetch_add(ready_ms as u64, Ordering::Relaxed); - self.ready_max_ms - .fetch_max(ready_ms as u64, Ordering::Relaxed); - } -} - -/// One planned query's measurements. -#[derive(Default)] -pub struct QueryMetrics { - /// The query run of an instant query, on its worker thread. - pub run: PhaseStats, - /// From an instant request reaching the engine to its answer, queueing - /// for a worker included. - pub latency: Latency, - /// The query run of one step of a range query. - pub range_step_run: PhaseStats, - /// From a range request reaching the data plane to its answer. - pub range_latency: Latency, - /// Steps of the range requests answered. - pub range_steps: AtomicU64, - /// Of those, the steps the result cache answered. - pub range_steps_cached: AtomicU64, -} - -/// Push precompute's measurements, by refresh group and ingest shard. -pub struct PushMetrics { - /// Folding one morsel into a group's open windows on a shard. - pub push: Vec>, - /// Sealing a window of a group on a shard. - pub seal: Vec>, - /// Combining a window's partials, by group. - pub combine: Vec, - /// Committing pushed windows. - pub commit: PhaseStats, - /// Bytes of open-window state, by group and shard. - pub state_bytes: Vec>, - /// Open instances by shard. - pub open_instances: Vec, - /// By shard: some group has more than one window open there. - pub older_window_open: Vec, - /// From the newest committed window's end to its commit. - pub commit_lag_ms: AtomicI64, -} - -impl PushMetrics { - pub fn new(groups: usize, shards: usize) -> Self { - let grid = || { - (0..groups) - .map(|_| (0..shards).map(|_| PhaseStats::default()).collect()) - .collect() - }; - Self { - push: grid(), - seal: grid(), - combine: (0..groups).map(|_| PhaseStats::default()).collect(), - commit: PhaseStats::default(), - state_bytes: (0..groups) - .map(|_| (0..shards).map(|_| AtomicU64::new(0)).collect()) - .collect(), - open_instances: (0..shards).map(|_| AtomicU64::new(0)).collect(), - older_window_open: (0..shards).map(|_| AtomicBool::new(false)).collect(), - commit_lag_ms: AtomicI64::new(0), - } - } - - /// Open-window state over every group and shard. - pub fn total_state_bytes(&self) -> u64 { - self.state_bytes - .iter() - .flatten() - .map(|b| b.load(Ordering::Relaxed)) - .sum() - } - - fn render(&self, out: &mut String) { - for (group, shards) in self.push.iter().enumerate() { - for (shard, stats) in shards.iter().enumerate() { - stats.render( - out, - &format!("phase=\"precompute_push\",group=\"{group}\",shard=\"{shard}\""), - ); - } - } - for (group, shards) in self.seal.iter().enumerate() { - for (shard, stats) in shards.iter().enumerate() { - stats.render( - out, - &format!("phase=\"precompute_seal\",group=\"{group}\",shard=\"{shard}\""), - ); - } - } - for (group, stats) in self.combine.iter().enumerate() { - stats.render( - out, - &format!("phase=\"precompute_combine\",group=\"{group}\""), - ); - } - self.commit.render(out, "phase=\"precompute_commit\""); - } - - 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() { - let _ = writeln!( - out, - "asap_precompute_state_bytes{{group=\"{group}\",shard=\"{shard}\"}} {}", - bytes.load(Ordering::Relaxed) - ); - } - } - let _ = writeln!(out, "# HELP asap_precompute_open_instances Open push windows per shard.\n# TYPE asap_precompute_open_instances gauge"); - for (shard, open) in self.open_instances.iter().enumerate() { - let _ = writeln!( - out, - "asap_precompute_open_instances{{shard=\"{shard}\"}} {}", - open.load(Ordering::Relaxed) - ); - } - let _ = writeln!( - out, - "# HELP asap_window_commit_lag_seconds From the newest committed window's end to its commit.\n# TYPE asap_window_commit_lag_seconds gauge\nasap_window_commit_lag_seconds {}", - self.commit_lag_ms.load(Ordering::Relaxed) as f64 / 1e3 - ); - } -} - -/// Every measurement the engine's threads record. -pub struct Metrics { - /// Push precompute's measurements (push mode only). - pub push: Option, - /// Remote Write decode and series interning, on the HTTP threads. - pub remote_write_decode: PhaseStats, - /// Storing one ingest command's samples on the ingest thread: routing, - /// appending, closing windows, compacting and evicting panes. - pub append: PhaseStats, - /// Each refresh group's ingestion runs, with its labels. - pub precompute: Vec<(String, PhaseStats)>, - /// Each refresh group's waits around its ingestion runs. - pub precompute_windows: Vec, - /// Wall time the precompute threads spent computing windows. - pub precompute_busy_ns: AtomicU64, - /// Threads computing windows (`--precompute-threads`). - pub precompute_threads: AtomicU64, - /// Each planned query's runs, by query text. - pub queries: BTreeMap, - /// The watermark, `i64::MIN` before the first. - pub watermark_ms: AtomicI64, - pub raw_data_bytes: AtomicU64, - pub raw_data_samples: AtomicU64, - pub raw_data_panes: AtomicU64, - pub view_bytes: AtomicU64, - /// Bytes written to the view files. - pub view_persisted_bytes: AtomicU64, - /// Time spent syncing the view files. - pub view_sync_ns: AtomicU64, - /// View windows not written to the files (a sketch state, or an error). - pub view_windows_not_persisted: AtomicU64, - /// View windows loaded from the files at startup. - pub view_windows_loaded: AtomicU64, - /// Time the precompute thread waited for room in the persist backlog. - pub view_persist_over_bound: AtomicU64, - /// Bytes of the view files (segments) held. - 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 { - /// Measurements for refresh groups described by `groups` (window width - /// and view ids) and the planned `queries`. - pub fn new(groups: &[(i64, Vec)], queries: &[String]) -> Self { - Self { - push: None, - remote_write_decode: PhaseStats::default(), - append: PhaseStats::default(), - precompute: groups - .iter() - .enumerate() - .map(|(index, (width_ms, views))| { - let labels = format!( - "phase=\"precompute\",group=\"{index}\",window_ms=\"{width_ms}\",views=\"{}\"", - views.join(",") - ); - (labels, PhaseStats::default()) - }) - .collect(), - precompute_windows: groups.iter().map(|_| WindowLatency::default()).collect(), - precompute_busy_ns: AtomicU64::new(0), - precompute_threads: AtomicU64::new(1), - queries: queries - .iter() - .map(|query| (query.trim().to_string(), QueryMetrics::default())) - .collect(), - watermark_ms: AtomicI64::new(i64::MIN), - raw_data_bytes: AtomicU64::new(0), - raw_data_samples: AtomicU64::new(0), - raw_data_panes: AtomicU64::new(0), - view_bytes: AtomicU64::new(0), - view_persisted_bytes: AtomicU64::new(0), - view_sync_ns: AtomicU64::new(0), - view_windows_not_persisted: AtomicU64::new(0), - view_windows_loaded: AtomicU64::new(0), - 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(), - } - } - - /// The query's measurements, if it is planned. - pub fn query(&self, query: &str) -> Option<&QueryMetrics> { - self.queries.get(query.trim()) - } -} /// 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, pub persist_backlog: u64, pub persist_backlog_bytes: u64, pub now_ms: i64, - pub query_time_results: &'a QueryTimeResults, + 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 { +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}"); @@ -416,7 +56,7 @@ pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { .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() { + if let Some(tier) = gauges.view_tier { tier.decode.render(&mut out, "phase=\"view_decode\""); } for (labels, stats) in &metrics.precompute { @@ -578,7 +218,7 @@ pub fn render(metrics: &Metrics, gauges: &Gauges) -> String { "Bytes of materialized view rows held.", load(&metrics.view_bytes), ); - if let Some(tier) = metrics.view_tier.get() { + if let Some(tier) = gauges.view_tier { let cache = tier.cache.stats(); for (name, help, value) in [ ( @@ -812,7 +452,7 @@ pub 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", @@ -844,67 +484,20 @@ 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()?) -} - -/// 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 { - // SAFETY: sysconf has no preconditions. - let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }.max(1) as f64; - let mut by_name = BTreeMap::new(); - for task in std::fs::read_dir("/proc/self/task").into_iter().flatten() { - let Ok(task) = task else { continue }; - let path = task.path(); - let (Ok(comm), Ok(stat)) = ( - std::fs::read_to_string(path.join("comm")), - std::fs::read_to_string(path.join("stat")), - ) else { - continue; - }; - // After the parenthesized name: utime and stime are fields 14 and 15. - let Some(fields) = stat.rfind(')').map(|end| &stat[end + 2..]) else { - continue; - }; - let fields: Vec<&str> = fields.split(' ').collect(); - let (Some(Ok(user)), Some(Ok(system))) = ( - fields.get(11).map(|f| f.parse::()), - fields.get(12).map(|f| f.parse::()), - ) else { - continue; - }; - let name = comm.trim().trim_end_matches(|c: char| c.is_ascii_digit()); - *by_name.entry(name.to_string()).or_insert(0.0) += (user + system) / ticks; - } - by_name -} - #[cfg(test)] mod tests { + use internal_metrics::Timer; + use super::*; - /// A phase records the thread CPU it burns, and the text format names - /// each phase and query. + /// 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()], ); - 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.append.record(Timer::start()); metrics.query("sum(x) ").unwrap().latency.observe(0.003); let text = render( &metrics, @@ -917,6 +510,7 @@ mod tests { now_ms: 0, query_time_results: &QueryTimeResults::new(0, 0), result_cache: None, + view_tier: None, }, ); assert!( 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..a2ca1e6f4 100644 --- a/crates/data-plane/tests/view_tiering.rs +++ b/crates/data-plane/tests/view_tiering.rs @@ -2,9 +2,9 @@ //! 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 -//! keeps every window in memory (the control). +//! 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 new file mode 100644 index 000000000..abaa112f6 --- /dev/null +++ b/crates/internal-metrics/src/lib.rs @@ -0,0 +1,432 @@ +//! 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; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; +use std::time::Instant; + +/// CPU time this thread has used, in nanoseconds. +pub fn thread_cpu_ns() -> u64 { + let mut time = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: `time` is a valid timespec to write. + let status = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut time) }; + if status != 0 { + return 0; + } + time.tv_sec as u64 * 1_000_000_000 + time.tv_nsec as u64 +} + +/// The start of one measured phase on the current thread. +pub struct Timer { + cpu_ns: u64, + wall: Instant, +} + +impl Timer { + pub fn start() -> Self { + Self { + cpu_ns: thread_cpu_ns(), + wall: Instant::now(), + } + } +} + +/// How often a phase ran and the thread CPU and wall time it took. +#[derive(Default)] +pub struct PhaseStats { + runs: AtomicU64, + cpu_ns: AtomicU64, + wall_ns: AtomicU64, +} + +impl PhaseStats { + /// Records one run started at `timer`, ending now on the same thread; + /// returns its wall time in seconds. + pub fn record(&self, timer: Timer) -> f64 { + let wall = timer.wall.elapsed(); + self.runs.fetch_add(1, Ordering::Relaxed); + self.cpu_ns.fetch_add( + thread_cpu_ns().saturating_sub(timer.cpu_ns), + Ordering::Relaxed, + ); + self.wall_ns + .fetch_add(wall.as_nanos() as u64, Ordering::Relaxed); + wall.as_secs_f64() + } + + /// 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, + "asap_phase_runs_total{{{labels}}} {}", + self.runs.load(Ordering::Relaxed) + ); + let _ = writeln!( + out, + "asap_phase_cpu_seconds_total{{{labels}}} {}", + seconds(&self.cpu_ns) + ); + let _ = writeln!( + out, + "asap_phase_wall_seconds_total{{{labels}}} {}", + seconds(&self.wall_ns) + ); + } +} + +/// Upper bounds of the query latency histogram's buckets, in seconds. +const LATENCY_BUCKETS_S: [f64; 10] = [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 1.0, 5.0]; + +/// A histogram of query latencies. +#[derive(Default)] +pub struct Latency { + /// Observations at or below each bucket's bound (not cumulative). + buckets: [AtomicU64; LATENCY_BUCKETS_S.len()], + count: AtomicU64, + sum_ns: AtomicU64, +} + +impl Latency { + pub fn observe(&self, seconds: f64) { + if let Some(bucket) = LATENCY_BUCKETS_S.iter().position(|b| seconds <= *b) { + self.buckets[bucket].fetch_add(1, Ordering::Relaxed); + } + self.count.fetch_add(1, Ordering::Relaxed); + self.sum_ns + .fetch_add((seconds * 1e9) as u64, Ordering::Relaxed); + } + + /// 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); + let _ = writeln!(out, "{name}_bucket{{{labels},le=\"{bound}\"}} {cumulative}"); + } + let count = self.count.load(Ordering::Relaxed); + let _ = writeln!(out, "{name}_bucket{{{labels},le=\"+Inf\"}} {count}"); + let _ = writeln!( + out, + "{name}_sum{{{labels}}} {}", + self.sum_ns.load(Ordering::Relaxed) as f64 / 1e9 + ); + let _ = writeln!(out, "{name}_count{{{labels}}} {count}"); + } +} + +/// One refresh group's windows on their way through the precompute task +/// pool. +#[derive(Default)] +pub struct WindowLatency { + /// Windows committed (refreshed, already stored or failed). + pub windows: AtomicU64, + /// From the window closing to its computation starting: the backlog, + /// waiting for the windows it reads and for a free worker. + pub queue_wait_ns: AtomicU64, + /// From its computation ending to its commit: waiting for the group's + /// earlier windows. + pub commit_wait_ns: AtomicU64, + /// From the window's end (event time) to its commit (wall clock). + pub ready_ms: AtomicU64, + pub ready_max_ms: AtomicU64, + /// The runs a window is split into, by series (1: one run). + pub parts: AtomicU64, +} + +impl WindowLatency { + pub fn record( + &self, + queue_wait: std::time::Duration, + commit_wait: std::time::Duration, + ready_ms: i64, + ) { + self.windows.fetch_add(1, Ordering::Relaxed); + self.queue_wait_ns + .fetch_add(queue_wait.as_nanos() as u64, Ordering::Relaxed); + self.commit_wait_ns + .fetch_add(commit_wait.as_nanos() as u64, Ordering::Relaxed); + self.ready_ms.fetch_add(ready_ms as u64, Ordering::Relaxed); + self.ready_max_ms + .fetch_max(ready_ms as u64, Ordering::Relaxed); + } +} + +/// One planned query's measurements. +#[derive(Default)] +pub struct QueryMetrics { + /// The query run of an instant query, on its worker thread. + pub run: PhaseStats, + /// From an instant request reaching the engine to its answer, queueing + /// for a worker included. + pub latency: Latency, + /// The query run of one step of a range query. + pub range_step_run: PhaseStats, + /// From a range request reaching the data plane to its answer. + pub range_latency: Latency, + /// Steps of the range requests answered. + pub range_steps: AtomicU64, + /// Of those, the steps the result cache answered. + pub range_steps_cached: AtomicU64, +} + +/// Push precompute's measurements, by refresh group and ingest shard. +pub struct PushMetrics { + /// Folding one morsel into a group's open windows on a shard. + pub push: Vec>, + /// Sealing a window of a group on a shard. + pub seal: Vec>, + /// Combining a window's partials, by group. + pub combine: Vec, + /// Committing pushed windows. + pub commit: PhaseStats, + /// Bytes of open-window state, by group and shard. + pub state_bytes: Vec>, + /// Open instances by shard. + pub open_instances: Vec, + /// By shard: some group has more than one window open there. + pub older_window_open: Vec, + /// From the newest committed window's end to its commit. + pub commit_lag_ms: AtomicI64, +} + +impl PushMetrics { + pub fn new(groups: usize, shards: usize) -> Self { + let grid = || { + (0..groups) + .map(|_| (0..shards).map(|_| PhaseStats::default()).collect()) + .collect() + }; + Self { + push: grid(), + seal: grid(), + combine: (0..groups).map(|_| PhaseStats::default()).collect(), + commit: PhaseStats::default(), + state_bytes: (0..groups) + .map(|_| (0..shards).map(|_| AtomicU64::new(0)).collect()) + .collect(), + open_instances: (0..shards).map(|_| AtomicU64::new(0)).collect(), + older_window_open: (0..shards).map(|_| AtomicBool::new(false)).collect(), + commit_lag_ms: AtomicI64::new(0), + } + } + + /// Open-window state over every group and shard. + pub fn total_state_bytes(&self) -> u64 { + self.state_bytes + .iter() + .flatten() + .map(|b| b.load(Ordering::Relaxed)) + .sum() + } + + /// 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( + out, + &format!("phase=\"precompute_push\",group=\"{group}\",shard=\"{shard}\""), + ); + } + } + for (group, shards) in self.seal.iter().enumerate() { + for (shard, stats) in shards.iter().enumerate() { + stats.render( + out, + &format!("phase=\"precompute_seal\",group=\"{group}\",shard=\"{shard}\""), + ); + } + } + for (group, stats) in self.combine.iter().enumerate() { + stats.render( + out, + &format!("phase=\"precompute_combine\",group=\"{group}\""), + ); + } + self.commit.render(out, "phase=\"precompute_commit\""); + } + + /// 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() { + let _ = writeln!( + out, + "asap_precompute_state_bytes{{group=\"{group}\",shard=\"{shard}\"}} {}", + bytes.load(Ordering::Relaxed) + ); + } + } + let _ = writeln!(out, "# HELP asap_precompute_open_instances Open push windows per shard.\n# TYPE asap_precompute_open_instances gauge"); + for (shard, open) in self.open_instances.iter().enumerate() { + let _ = writeln!( + out, + "asap_precompute_open_instances{{shard=\"{shard}\"}} {}", + open.load(Ordering::Relaxed) + ); + } + let _ = writeln!( + out, + "# HELP asap_window_commit_lag_seconds From the newest committed window's end to its commit.\n# TYPE asap_window_commit_lag_seconds gauge\nasap_window_commit_lag_seconds {}", + self.commit_lag_ms.load(Ordering::Relaxed) as f64 / 1e3 + ); + } +} + +/// Every measurement the engine's threads record. +pub struct Metrics { + /// Push precompute's measurements (push mode only). + pub push: Option, + /// Remote Write decode and series interning, on the HTTP threads. + pub remote_write_decode: PhaseStats, + /// Storing one ingest command's samples on the ingest thread: routing, + /// appending, closing windows, compacting and evicting panes. + pub append: PhaseStats, + /// Each refresh group's ingestion runs, with its labels. + pub precompute: Vec<(String, PhaseStats)>, + /// Each refresh group's waits around its ingestion runs. + pub precompute_windows: Vec, + /// Wall time the precompute threads spent computing windows. + pub precompute_busy_ns: AtomicU64, + /// Threads computing windows (`--precompute-threads`). + pub precompute_threads: AtomicU64, + /// Each planned query's runs, by query text. + pub queries: BTreeMap, + /// The watermark, `i64::MIN` before the first. + pub watermark_ms: AtomicI64, + pub raw_data_bytes: AtomicU64, + pub raw_data_samples: AtomicU64, + pub raw_data_panes: AtomicU64, + pub view_bytes: AtomicU64, + /// Bytes written to the view files. + pub view_persisted_bytes: AtomicU64, + /// Time spent syncing the view files. + pub view_sync_ns: AtomicU64, + /// View windows not written to the files (a sketch state, or an error). + pub view_windows_not_persisted: AtomicU64, + /// View windows loaded from the files at startup. + pub view_windows_loaded: AtomicU64, + /// Time the precompute thread waited for room in the persist backlog. + pub view_persist_over_bound: AtomicU64, + /// Bytes of the view files (segments) held. + pub view_file_bytes: AtomicU64, + /// View segments whose pages were advised cold. + pub view_segments_marked_cold: AtomicU64, +} + +impl Metrics { + /// Measurements for refresh groups described by `groups` (window width + /// and view ids) and the planned `queries`. + pub fn new(groups: &[(i64, Vec)], queries: &[String]) -> Self { + Self { + push: None, + remote_write_decode: PhaseStats::default(), + append: PhaseStats::default(), + precompute: groups + .iter() + .enumerate() + .map(|(index, (width_ms, views))| { + let labels = format!( + "phase=\"precompute\",group=\"{index}\",window_ms=\"{width_ms}\",views=\"{}\"", + views.join(",") + ); + (labels, PhaseStats::default()) + }) + .collect(), + precompute_windows: groups.iter().map(|_| WindowLatency::default()).collect(), + precompute_busy_ns: AtomicU64::new(0), + precompute_threads: AtomicU64::new(1), + queries: queries + .iter() + .map(|query| (query.trim().to_string(), QueryMetrics::default())) + .collect(), + watermark_ms: AtomicI64::new(i64::MIN), + raw_data_bytes: AtomicU64::new(0), + raw_data_samples: AtomicU64::new(0), + raw_data_panes: AtomicU64::new(0), + view_bytes: AtomicU64::new(0), + view_persisted_bytes: AtomicU64::new(0), + view_sync_ns: AtomicU64::new(0), + view_windows_not_persisted: AtomicU64::new(0), + view_windows_loaded: AtomicU64::new(0), + view_persist_over_bound: AtomicU64::new(0), + view_file_bytes: AtomicU64::new(0), + view_segments_marked_cold: AtomicU64::new(0), + } + } + + /// The query's measurements, if it is planned. + pub fn query(&self, query: &str) -> Option<&QueryMetrics> { + self.queries.get(query.trim()) + } +} + +/// 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 { + // SAFETY: sysconf has no preconditions. + let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }.max(1) as f64; + let mut by_name = BTreeMap::new(); + for task in std::fs::read_dir("/proc/self/task").into_iter().flatten() { + let Ok(task) = task else { continue }; + let path = task.path(); + let (Ok(comm), Ok(stat)) = ( + std::fs::read_to_string(path.join("comm")), + std::fs::read_to_string(path.join("stat")), + ) else { + continue; + }; + // After the parenthesized name: utime and stime are fields 14 and 15. + let Some(fields) = stat.rfind(')').map(|end| &stat[end + 2..]) else { + continue; + }; + let fields: Vec<&str> = fields.split(' ').collect(); + let (Some(Ok(user)), Some(Ok(system))) = ( + fields.get(11).map(|f| f.parse::()), + fields.get(12).map(|f| f.parse::()), + ) else { + continue; + }; + let name = comm.trim().trim_end_matches(|c: char| c.is_ascii_digit()); + *by_name.entry(name.to_string()).or_insert(0.0) += (user + system) / ticks; + } + by_name +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A phase records the thread CPU it burns. + #[test] + 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); + 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/data-plane/src/memory_budget.rs b/crates/storage/src/memory_budget.rs similarity index 87% rename from crates/data-plane/src/memory_budget.rs rename to crates/storage/src/memory_budget.rs index 3c1b274bb..d9dba1319 100644 --- a/crates/data-plane/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/data-plane/src/persist.rs b/crates/storage/src/persist.rs similarity index 99% rename from crates/data-plane/src/persist.rs rename to crates/storage/src/persist.rs index aa4f286d2..9ea8cee93 100644 --- a/crates/data-plane/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 { @@ -536,7 +537,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/data-plane/src/segment.rs b/crates/storage/src/segment.rs similarity index 99% rename from crates/data-plane/src/segment.rs rename to crates/storage/src/segment.rs index 44682f5d8..13d34a4e5 100644 --- a/crates/data-plane/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/data-plane/src/series_ids.rs b/crates/storage/src/series_ids.rs similarity index 98% rename from crates/data-plane/src/series_ids.rs rename to crates/storage/src/series_ids.rs index ab7c0ae84..af3e76fb0 100644 --- a/crates/data-plane/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/data-plane/src/state_codec.rs b/crates/storage/src/state_codec.rs similarity index 98% rename from crates/data-plane/src/state_codec.rs rename to crates/storage/src/state_codec.rs index c84dc241d..147170fdc 100644 --- a/crates/data-plane/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/data-plane/src/store.rs b/crates/storage/src/store.rs similarity index 99% rename from crates/data-plane/src/store.rs rename to crates/storage/src/store.rs index 3b1099524..4ed237f08 100644 --- a/crates/data-plane/src/store.rs +++ b/crates/storage/src/store.rs @@ -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. @@ -1434,7 +1445,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/data-plane/src/window_cache.rs b/crates/storage/src/window_cache.rs similarity index 99% rename from crates/data-plane/src/window_cache.rs rename to crates/storage/src/window_cache.rs index 90c1abb2e..945c2202f 100644 --- a/crates/data-plane/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; }; diff --git a/crates/data-plane/tests/series_ids.rs b/crates/storage/tests/series_ids.rs similarity index 97% rename from crates/data-plane/tests/series_ids.rs rename to crates/storage/tests/series_ids.rs index 247408e99..27231c65e 100644 --- a/crates/data-plane/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/data-plane/tests/view_cache_charge.rs b/crates/storage/tests/view_cache_charge.rs similarity index 98% rename from crates/data-plane/tests/view_cache_charge.rs rename to crates/storage/tests/view_cache_charge.rs index 556815a38..6c457e6b7 100644 --- a/crates/data-plane/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;