diff --git a/crates/core/src/metrics/collector.rs b/crates/core/src/metrics/collector.rs index 52fb30af7..9de8d1225 100755 --- a/crates/core/src/metrics/collector.rs +++ b/crates/core/src/metrics/collector.rs @@ -9,6 +9,7 @@ use std::sync::{Mutex, RwLock}; use std::time::{Duration, Instant, SystemTime}; use super::accumulator::Accumulator; +use super::segments::SegmentStore; use super::types::{LatencySegments, MetricName, TimeWindow}; /// Returns `None` for `AllTime` (no cutoff), or `Some(cutoff)` for bounded windows. @@ -41,32 +42,22 @@ pub(super) struct MetricKey { /// metrics endpoint). Individual `record_*` calls take a write lock briefly. pub struct MetricsCollector { pub(super) data: RwLock>, - /// Per-operation latency segment breakdowns for the console deep-dive. - pub(super) segments: RwLock>, + /// Per-account, per-operation latency segment sums for the console + /// deep-dive, bucketed by time so memory is bounded by the number of + /// accounts and operations. + pub(super) segments: RwLock, /// Serializes drains, so each one takes and keeps points in record order. /// `record` and `prune` never take it. pub(super) drain_lock: Mutex<()>, } -/// A single latency segment data point with metadata. -#[derive(Debug, Clone)] -pub(super) struct SegmentPoint { - pub(super) operation: String, - /// The account of the request, which `query_segments` filters on. - pub(super) account_id: String, - #[allow(dead_code)] // TODO(cleanup): used when console adds table-scoped latency breakdown - pub(super) table_name: Option, - pub(super) segments: LatencySegments, - pub(super) timestamp: Instant, -} - impl MetricsCollector { /// Create a new empty collector. #[must_use] pub fn new() -> Self { Self { data: RwLock::new(HashMap::new()), - segments: RwLock::new(Vec::with_capacity(256)), + segments: RwLock::new(SegmentStore::new(Instant::now())), drain_lock: Mutex::new(()), } } @@ -113,29 +104,49 @@ impl MetricsCollector { } /// Record per-segment latency breakdown for a request. - pub fn record_segments( + /// + /// The breakdown is summed into the current time buckets of the account's + /// operation, so the memory held is bounded by the ring lengths, whatever + /// the request count. The account is a dimension because `query_segments` + /// filters on it. The table is not: a per-table breakdown would multiply + /// the bound by the table count, and the console reads per-operation + /// averages. + pub fn record_segments(&self, account_id: &str, operation: &str, segments: &LatencySegments) { + self.record_segments_with(account_id, operation, segments, Instant::now); + } + + /// `record_segments` with the clock it reads. The clock is read under the + /// lock, as in `query_segments`, so a stored record is never ahead of a + /// query that follows it; otherwise a writer that crosses a bucket + /// boundary between its clock read and its lock could drop the oldest + /// in-window bucket before a reader with an earlier clock reads it. + pub(super) fn record_segments_with( &self, account_id: &str, operation: &str, - table_name: Option<&str>, - segments: LatencySegments, + segments: &LatencySegments, + clock: impl FnOnce() -> Instant, ) { - let point = SegmentPoint { - operation: operation.to_owned(), - account_id: account_id.to_owned(), - table_name: table_name.map(ToOwned::to_owned), - segments, - timestamp: Instant::now(), - }; - let Ok(mut vec) = self.segments.write() else { + let Ok(mut store) = self.segments.write() else { return; }; - vec.push(point); + store.record(account_id, operation, segments, clock()); } /// Prune data points older than 1 day. + /// + /// Segment buckets leave their ring as time advances; the prune drops the + /// rings of an account's operation once its newest bucket is older than a + /// day, so an account that stopped sending requests, or was deleted, frees + /// its segment buckets after a day. pub fn prune(&self) { - let now = Instant::now(); + self.prune_at(Instant::now()); + } + + /// `prune` at the clock `now`, which may be read before the locks: a + /// point or a segment recorded in between is newer than `now`, so the + /// prune keeps it. + pub(super) fn prune_at(&self, now: Instant) { let cutoff = now.checked_sub(Duration::from_secs(86400)).unwrap_or(now); let Ok(mut map) = self.data.write() else { return; @@ -145,9 +156,8 @@ impl MetricsCollector { } map.retain(|_, acc| !acc.is_empty()); drop(map); - // Prune segment points too. - if let Ok(mut segs) = self.segments.write() { - segs.retain(|p| p.timestamp >= cutoff); + if let Ok(mut store) = self.segments.write() { + store.prune(now); } } } diff --git a/crates/core/src/metrics/collector_query.rs b/crates/core/src/metrics/collector_query.rs index 373d49fc7..52be2428d 100755 --- a/crates/core/src/metrics/collector_query.rs +++ b/crates/core/src/metrics/collector_query.rs @@ -10,15 +10,12 @@ use std::collections::hash_map::Entry; use std::time::{Duration, Instant, SystemTime}; use super::accumulator::{Accumulator, DataPoint}; -use super::collector::{MetricKey, MetricsCollector, window_cutoff}; +use super::collector::{MetricKey, MetricsCollector}; use super::types::{ Dimension, FlushBucket, MetricName, MetricSnapshot, MetricsQuery, OperationSegments, Percentiles, TimeWindow, }; -/// Accumulator for per-operation segment sums: (auth, authz, throttle, dispatch, response, total, count). -type SegmentAccum = (f64, f64, f64, f64, f64, f64, u64); - impl MetricsCollector { /// Query metrics and return snapshots. /// @@ -152,61 +149,34 @@ impl MetricsCollector { /// Query average latency segments for the console deep-dive. /// - /// Returns per-operation averages over the given time window, of the - /// requests of `account_id` only when it is given (an empty string is no - /// filter). + /// Returns per-operation averages over the given time window, sorted by + /// operation name, of the requests of `account_id` only when it is given + /// (an empty string is no filter); without it, every account's requests + /// are summed per operation. `LastMinute` and `Last5Minutes` read + /// 1-second buckets, the longer windows read 1-minute buckets: a window of + /// `W` seconds covers at least the last `W` seconds and at most the last + /// `W` plus one bucket width. `AllTime` is the whole 24-hour ring. #[must_use] pub fn query_segments( &self, window: TimeWindow, account_id: Option<&str>, ) -> Vec { - let account_id = account_id.filter(|a| !a.is_empty()); - let now = Instant::now(); - let cutoff = window_cutoff(window, now); - let Ok(vec) = self.segments.read() else { + self.query_segments_with(window, account_id, Instant::now) + } + + /// `query_segments` with the clock it reads, under the lock, paired with + /// `record_segments`. + pub(super) fn query_segments_with( + &self, + window: TimeWindow, + account_id: Option<&str>, + clock: impl FnOnce() -> Instant, + ) -> Vec { + let Ok(store) = self.segments.read() else { return Vec::new(); }; - let mut by_op: HashMap = HashMap::new(); - for p in vec.iter() { - if let Some(c) = cutoff - && p.timestamp < c - { - continue; - } - if account_id.is_some_and(|a| a != p.account_id) { - continue; - } - let e = by_op.entry(p.operation.clone()).or_default(); - e.0 += p.segments.auth_us; - e.1 += p.segments.authz_us; - e.2 += p.segments.throttle_us; - e.3 += p.segments.dispatch_us; - e.4 += p.segments.response_us; - e.5 += p.segments.total_us; - e.6 += 1; - } - by_op - .into_iter() - .map( - |(op, (auth, authz, throttle, dispatch, response, total, count))| { - #[allow(clippy::cast_precision_loss)] - let c = count as f64; - OperationSegments { - operation: op, - count, - avg: super::types::LatencySegments { - auth_us: auth / c, - authz_us: authz / c, - throttle_us: throttle / c, - dispatch_us: dispatch / c, - response_us: response / c, - total_us: total / c, - }, - } - }, - ) - .collect() + store.query(window, account_id, clock()) } } diff --git a/crates/core/src/metrics/collector_tests.rs b/crates/core/src/metrics/collector_tests.rs index 0075cbaff..174b9864a 100755 --- a/crates/core/src/metrics/collector_tests.rs +++ b/crates/core/src/metrics/collector_tests.rs @@ -162,8 +162,7 @@ fn record_and_query_segments() { c.record_segments( ACCOUNT, "GetItem", - Some("T"), - LatencySegments { + &LatencySegments { auth_us: 100.0, authz_us: 200.0, throttle_us: 50.0, @@ -175,8 +174,7 @@ fn record_and_query_segments() { c.record_segments( ACCOUNT, "GetItem", - Some("T"), - LatencySegments { + &LatencySegments { auth_us: 200.0, authz_us: 300.0, throttle_us: 50.0, @@ -198,15 +196,18 @@ fn record_and_query_segments() { } #[test] -fn prune_removes_old_segments() { +fn prune_keeps_recent_segments_and_drops_them_a_day_later() { use crate::metrics::types::LatencySegments; + use std::time::Duration; let c = MetricsCollector::new(); + let Ok(epoch) = c.segments.read().map(|s| s.epoch()) else { + panic!("segments lock poisoned"); + }; c.record_segments( ACCOUNT, "PutItem", - None, - LatencySegments { + &LatencySegments { auth_us: 10.0, authz_us: 20.0, throttle_us: 5.0, @@ -221,6 +222,54 @@ fn prune_removes_old_segments() { let segs = c.query_segments(TimeWindow::AllTime, None); assert_eq!(segs.len(), 1); assert_eq!(segs[0].count, 1); + + // A day later the bucket has left the ring without any prune call. + let later = epoch + Duration::from_mins(1441); + assert!( + c.query_segments_with(TimeWindow::AllTime, None, || later) + .is_empty() + ); + assert!( + c.query_segments_with(TimeWindow::LastDay, None, || later) + .is_empty() + ); + // The buckets are still held until the collector's prune runs at that + // time; then the account's rings and the account are gone. + let held = |c: &MetricsCollector| c.segments.read().map_or(usize::MAX, |s| s.buckets().0); + assert_eq!(held(&c), 2); + c.prune_at(later); + assert_eq!(held(&c), 0); +} + +/// `record_segments` and `query_segments` read the clock under the lock: a +/// clock that runs while the lock is free fails these checks. +#[test] +fn segment_record_and_query_read_the_clock_under_the_lock() { + use crate::metrics::types::LatencySegments; + use std::sync::TryLockError; + use std::time::Instant; + + let c = MetricsCollector::new(); + let point = LatencySegments { + total_us: 10.0, + ..LatencySegments::default() + }; + c.record_segments_with(ACCOUNT, "GetItem", &point, || { + assert!( + matches!(c.segments.try_read(), Err(TryLockError::WouldBlock)), + "record read the clock before taking the write lock" + ); + Instant::now() + }); + let out = c.query_segments_with(TimeWindow::AllTime, None, || { + assert!( + matches!(c.segments.try_write(), Err(TryLockError::WouldBlock)), + "query read the clock before taking the read lock" + ); + Instant::now() + }); + assert_eq!(out.len(), 1); + assert_eq!(out[0].count, 1); } #[test] @@ -231,8 +280,7 @@ fn segments_multiple_operations() { c.record_segments( ACCOUNT, "GetItem", - Some("T"), - LatencySegments { + &LatencySegments { auth_us: 100.0, authz_us: 200.0, throttle_us: 50.0, @@ -244,8 +292,7 @@ fn segments_multiple_operations() { c.record_segments( ACCOUNT, "PutItem", - Some("T"), - LatencySegments { + &LatencySegments { auth_us: 120.0, authz_us: 220.0, throttle_us: 60.0, @@ -486,9 +533,9 @@ fn segments_are_filtered_by_account() { total_us: 10.0, ..LatencySegments::default() }; - c.record_segments(ACCOUNT, "GetItem", Some("T"), point.clone()); - c.record_segments("222222222222", "Scan", Some("T"), point.clone()); - c.record_segments("222222222222", "GetItem", Some("T"), point); + c.record_segments(ACCOUNT, "GetItem", &point); + c.record_segments("222222222222", "Scan", &point); + c.record_segments("222222222222", "GetItem", &point); let ops = |account: Option<&str>| { let mut ops: Vec<(String, u64)> = c diff --git a/crates/core/src/metrics/mod.rs b/crates/core/src/metrics/mod.rs index 9a680fd0d..d20eb205e 100755 --- a/crates/core/src/metrics/mod.rs +++ b/crates/core/src/metrics/mod.rs @@ -6,7 +6,10 @@ //! Collects `DynamoDB`-style `CloudWatch` metrics per table, per operation, and //! per GSI. Metrics are accumulated in memory using an `RwLock`-protected map //! of per-key accumulators. A background task prunes data points older than -//! 1 day every 5 minutes. +//! 1 day every 5 minutes. Per-account, per-operation latency segments are +//! summed into fixed time buckets at record time (see `segments`), so they +//! hold a bounded amount of memory; the same task drops the buckets of an +//! account that has sent no request for a day. //! //! REQ-OBS-005: Metrics endpoint. @@ -14,6 +17,7 @@ mod accumulator; mod collector; mod collector_query; mod collector_record; +mod segments; mod types; pub use collector::MetricsCollector; diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs new file mode 100644 index 000000000..8be3cfc71 --- /dev/null +++ b/crates/core/src/metrics/segments.rs @@ -0,0 +1,348 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Bounded storage for the per-operation latency segment breakdown. +//! +//! The console shows, per operation, the request count and the mean of each +//! latency segment over a time window. Those are sums, so a request does not +//! need to be stored: it is added into a time bucket at record time. Each +//! operation of each account owns two rings of buckets, one of 1-second +//! buckets covering the last 5 minutes and one of 1-minute buckets covering +//! the last 24 hours. A bucket holds the count and six running sums, 64 bytes. +//! A ring holds only the buckets of the slots that had a request, in slot +//! order, and a record drops the buckets that have left the ring's window, so +//! a ring never holds more than `FINE_SLOTS` or `COARSE_SLOTS` buckets and +//! its allocation grows by doubling up to that length and no further. The +//! allocation does not shrink: a pair keeps the largest one it reached until +//! the prune drops its rings. The memory per process is therefore at most +//! `accounts * operations * (FINE_SLOTS + COARSE_SLOTS) * 64` bytes of +//! buckets. A pair holds that many buckets only with a request in every +//! second of the last five minutes and every minute of the last day; a pair +//! with one request a day holds two buckets. The server only records +//! operations that pass `is_known_operation`, which caps `operations` at the +//! size of the dispatch table, and only for a request that reached dispatch. +//! `accounts` is the number of accounts that sent a request in the last 1,440 +//! to about 1,446 minutes. The collector's prune runs every five minutes. It +//! drops the rings of an account's operation once its newest bucket has left +//! the coarse ring's window, and the account once it holds no operation. +//! +//! The account is a key because `/metrics` filters the segments by account. +//! A query without the filter sums every account's buckets per operation. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::time::Instant; + +use super::types::{LatencySegments, OperationSegments, TimeWindow}; + +/// Width of a fine bucket, in seconds. Serves `LastMinute` and `Last5Minutes`. +pub(super) const FINE_WIDTH_SECS: u64 = 1; +/// Fine buckets per operation: the 300 s of `Last5Minutes` plus the bucket +/// that contains the window cutoff. +pub(super) const FINE_SLOTS: usize = 301; +/// Width of a coarse bucket, in seconds. Serves `LastHour`, `LastDay`, `AllTime`. +pub(super) const COARSE_WIDTH_SECS: u64 = 60; +/// Coarse buckets per operation: the 1440 minutes of `LastDay` plus the bucket +/// that contains the window cutoff. +pub(super) const COARSE_SLOTS: usize = 1441; + +/// Buckets held per operation of one account, the constant in the memory +/// bound. +#[cfg(test)] +pub(super) const BUCKETS_PER_OPERATION: usize = FINE_SLOTS + COARSE_SLOTS; + +/// One time bucket: the slot it currently holds, the request count and the +/// sum of each segment over those requests. +#[derive(Debug, Clone, Copy, Default)] +struct Bucket { + slot: u64, + count: u64, + auth_us: f64, + authz_us: f64, + throttle_us: f64, + dispatch_us: f64, + response_us: f64, + total_us: f64, +} + +impl Bucket { + /// A bucket at `slot` that holds one request. + fn new(slot: u64, s: &LatencySegments) -> Self { + Self { + slot, + count: 1, + auth_us: s.auth_us, + authz_us: s.authz_us, + throttle_us: s.throttle_us, + dispatch_us: s.dispatch_us, + response_us: s.response_us, + total_us: s.total_us, + } + } + + fn add_bucket(&mut self, b: &Bucket) { + self.count += b.count; + self.auth_us += b.auth_us; + self.authz_us += b.authz_us; + self.throttle_us += b.throttle_us; + self.dispatch_us += b.dispatch_us; + self.response_us += b.response_us; + self.total_us += b.total_us; + } +} + +/// A ring of buckets. Slot `k` covers elapsed seconds +/// `[k * width, (k + 1) * width)`. Only the slots that had a request have a +/// bucket, in slot order with the newest at the back, and never more than +/// `len` of them: a record at slot `k` drops the buckets of slots before +/// `k + 1 - len` first. +#[derive(Debug)] +struct Ring { + width_secs: u64, + /// Most buckets held, and the capacity the deque grows to and no further. + len: usize, + buckets: VecDeque, +} + +impl Ring { + fn new(width_secs: u64, len: usize) -> Self { + Self { + width_secs, + len, + buckets: VecDeque::new(), + } + } + + fn slots(&self) -> u64 { + self.len as u64 + } + + /// Adds one request observed `elapsed_secs` after the epoch. + fn record(&mut self, elapsed_secs: u64, segments: &LatencySegments) { + let slot = elapsed_secs / self.width_secs; + if let Some(newest) = self.buckets.back_mut() + && newest.slot >= slot + { + // The same slot, or a record behind the newest one, which the + // clock read under the lock rules out: counted in the newest. + newest.add_bucket(&Bucket::new(slot, segments)); + return; + } + let first_kept = (slot + 1).saturating_sub(self.slots()); + while self.buckets.front().is_some_and(|b| b.slot < first_kept) { + self.buckets.pop_front(); + } + if self.buckets.len() == self.buckets.capacity() { + // Double the capacity, up to the ring length: after the pops at + // most `len - 1` buckets are held, so `len - held` is at least 1. + let held = self.buckets.len(); + self.buckets.reserve_exact(held.max(1).min(self.len - held)); + } + self.buckets.push_back(Bucket::new(slot, segments)); + } + + /// Sums every bucket whose slot is at or after `first_slot` into `acc`. + /// The buckets are in slot order, so this reads only the window's slots. + fn sum_from(&self, first_slot: u64, acc: &mut Bucket) { + let start = self.buckets.partition_point(|b| b.slot < first_slot); + for b in self.buckets.range(start..) { + acc.add_bucket(b); + } + } + + /// First slot included in a query made `elapsed_secs` after the epoch for + /// a window of `window_secs`, or for the whole ring when `None`. + fn first_slot(&self, elapsed_secs: u64, window_secs: Option) -> u64 { + match window_secs { + Some(w) => elapsed_secs.saturating_sub(w) / self.width_secs, + None => (elapsed_secs / self.width_secs).saturating_sub(self.slots() - 1), + } + } +} + +/// The two rings of one operation. +#[derive(Debug)] +struct OperationRings { + fine: Ring, + coarse: Ring, +} + +impl OperationRings { + fn new() -> Self { + Self { + fine: Ring::new(FINE_WIDTH_SECS, FINE_SLOTS), + coarse: Ring::new(COARSE_WIDTH_SECS, COARSE_SLOTS), + } + } + + fn record(&mut self, elapsed_secs: u64, segments: &LatencySegments) { + self.fine.record(elapsed_secs, segments); + self.coarse.record(elapsed_secs, segments); + } +} + +/// Which ring a window reads, and the window length in seconds (`None` for +/// the whole ring). +fn ring_for(window: TimeWindow) -> (bool, Option) { + match window { + TimeWindow::LastMinute => (true, Some(60)), + TimeWindow::Last5Minutes => (true, Some(300)), + TimeWindow::LastHour => (false, Some(3600)), + TimeWindow::LastDay => (false, Some(86400)), + TimeWindow::AllTime => (false, None), + } +} + +/// Per-account, per-operation segment buckets. Lives behind the collector's +/// lock. +#[derive(Debug)] +pub(super) struct SegmentStore { + /// Time zero for slot arithmetic. + epoch: Instant, + /// The rings of each operation, under the account that sent the request. + /// Two maps rather than one keyed by the pair, so a record probes with + /// the borrowed names and allocates no key after the first request of an + /// account's operation. + by_account: HashMap>, +} + +impl SegmentStore { + pub(super) fn new(epoch: Instant) -> Self { + Self { + epoch, + by_account: HashMap::new(), + } + } + + #[cfg(test)] + pub(super) fn epoch(&self) -> Instant { + self.epoch + } + + fn elapsed_secs(&self, now: Instant) -> u64 { + now.saturating_duration_since(self.epoch).as_secs() + } + + /// Adds one request of `account_id`. Steady state is two hash lookups and + /// two bucket updates. The allocations are the keys of a pair's first + /// request and the growth of its rings, which doubles up to the ring + /// length and stops there. + pub(super) fn record( + &mut self, + account_id: &str, + operation: &str, + segments: &LatencySegments, + now: Instant, + ) { + let elapsed = self.elapsed_secs(now); + if let Some(rings) = self + .by_account + .get_mut(account_id) + .and_then(|operations| operations.get_mut(operation)) + { + rings.record(elapsed, segments); + return; + } + self.by_account + .entry(account_id.to_owned()) + .or_default() + .entry(operation.to_owned()) + .or_insert_with(OperationRings::new) + .record(elapsed, segments); + } + + /// Per-operation count and mean segments over `window`, sorted by + /// operation name: the requests of `account_id` when it is given and not + /// empty (an empty account is no filter, as in the stores), every + /// account's requests summed per operation when it is not. Operations + /// with no request in the window are omitted. + /// + /// A window of `W` seconds read from a ring of `b`-second buckets covers + /// at least the last `W` seconds and at most the last `W + b` seconds. + pub(super) fn query( + &self, + window: TimeWindow, + account_id: Option<&str>, + now: Instant, + ) -> Vec { + let account_id = account_id.filter(|a| !a.is_empty()); + let elapsed = self.elapsed_secs(now); + let (fine, window_secs) = ring_for(window); + let mut by_operation: BTreeMap<&str, Bucket> = BTreeMap::new(); + // One account's rings when filtered, every account's when not. + let one = account_id.and_then(|a| self.by_account.get(a)); + let all = account_id.is_none().then(|| self.by_account.values()); + for operations in one.into_iter().chain(all.into_iter().flatten()) { + for (operation, rings) in operations { + let ring = if fine { &rings.fine } else { &rings.coarse }; + let acc = by_operation.entry(operation).or_default(); + ring.sum_from(ring.first_slot(elapsed, window_secs), acc); + } + } + by_operation + .into_iter() + .filter(|(_, acc)| acc.count > 0) + .map(|(operation, acc)| { + #[allow(clippy::cast_precision_loss)] + let c = acc.count as f64; + OperationSegments { + operation: operation.to_owned(), + count: acc.count, + avg: LatencySegments { + auth_us: acc.auth_us / c, + authz_us: acc.authz_us / c, + throttle_us: acc.throttle_us / c, + dispatch_us: acc.dispatch_us / c, + response_us: acc.response_us / c, + total_us: acc.total_us / c, + }, + } + }) + .collect() + } + + /// Drops the rings of each account's operation whose newest coarse bucket + /// has left the whole-ring window at `now`, then each account left with + /// no operation. The fine ring's windows lie inside the coarse ring's, so + /// no query answer changes; an account that has sent no request for the + /// length of the coarse ring releases its memory to the allocator. The + /// check is one comparison per pair. + pub(super) fn prune(&mut self, now: Instant) { + let elapsed = self.elapsed_secs(now); + self.by_account.retain(|_, operations| { + operations.retain(|_, rings| { + let ring = &rings.coarse; + let first = ring.first_slot(elapsed, None); + ring.buckets.back().is_some_and(|b| b.slot >= first) + }); + !operations.is_empty() + }); + } + + /// Buckets held, the quantity the memory bound is stated in, and buckets + /// allocated, held or spare. The bucket memory is the second number times + /// [`Self::bucket_size`]. + #[cfg(test)] + pub(super) fn buckets(&self) -> (usize, usize) { + self.by_account + .values() + .flat_map(HashMap::values) + .flat_map(|r| [&r.fine.buckets, &r.coarse.buckets]) + .fold((0, 0), |(held, allocated), b| { + (held + b.len(), allocated + b.capacity()) + }) + } + + /// Size in bytes of one bucket, for stating the bound in bytes. + #[cfg(test)] + pub(super) const fn bucket_size() -> usize { + std::mem::size_of::() + } +} + +#[cfg(test)] +#[path = "segments_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "segments_bound_tests.rs"] +mod bound_tests; diff --git a/crates/core/src/metrics/segments_bound_tests.rs b/crates/core/src/metrics/segments_bound_tests.rs new file mode 100644 index 000000000..683726ed8 --- /dev/null +++ b/crates/core/src/metrics/segments_bound_tests.rs @@ -0,0 +1,237 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Tests for the memory bound and the prune of [`SegmentStore`]. + +use std::time::{Duration, Instant}; + +use super::tests::{ACCOUNTS, OPS, at, count_of, segs}; +use super::*; + +#[test] +fn bucket_is_64_bytes() { + assert_eq!(SegmentStore::bucket_size(), 64); + assert_eq!(BUCKETS_PER_OPERATION, 1742); +} + +/// Five million requests over three simulated days across three accounts and +/// five operations fill the rings and allocate nothing more. +#[test] +fn boundedness_five_million_records() { + let epoch = Instant::now(); + let mut store = SegmentStore::new(epoch); + let total: u64 = 5_000_000; + // 52 ms apart: 260 000 s, three days, so every ring laps many times. + // 3 and 5 are coprime, so every account records every operation, every + // second and every minute. + for i in 0..total { + let now = epoch + Duration::from_millis(i * 52); + #[allow(clippy::cast_possible_truncation)] + let account = ACCOUNTS[(i % 3) as usize]; + #[allow(clippy::cast_possible_truncation)] + let op = OPS[(i % 5) as usize]; + store.record(account, op, &segs(1.0), now); + } + let bound = ACCOUNTS.len() * OPS.len() * BUCKETS_PER_OPERATION; + let (held, allocated) = store.buckets(); + assert!(held <= bound, "bucket count {held} exceeds bound {bound}"); + assert!(allocated * SegmentStore::bucket_size() <= bound * 64); + // Every slot of every ring had a request, so the bound is reached + // exactly, held and allocated. + assert_eq!(held, bound); + assert_eq!(allocated, bound); + // The whole-ring query still answers, with at most 1441 minutes of data. + let now = epoch + Duration::from_millis(total * 52); + let out = store.query(TimeWindow::AllTime, None, now); + let in_day: u64 = out.iter().map(|o| o.count).sum(); + assert!(in_day > 0 && in_day <= 86_460_000 / 52 + OPS.len() as u64); +} + +/// A bucket whose slot has left the ring is dropped by the next record, and a +/// bucket that is still in the ring but outside the window is excluded by the +/// window filter. `AllTime` is the whole 24-hour ring. +#[test] +fn ring_lap_and_stale_slots() { + let epoch = Instant::now(); + let mut store = SegmentStore::new(epoch); + store.record(ACCOUNTS[0], "Scan", &segs(1.0), at(epoch, 0)); + // One day minus a second later minute 0 is still inside the ring. + assert_eq!( + count_of( + &store.query(TimeWindow::AllTime, None, at(epoch, 86_459)), + "Scan" + ), + 1 + ); + assert_eq!( + count_of( + &store.query(TimeWindow::LastDay, None, at(epoch, 86_459)), + "Scan" + ), + 1 + ); + // At 1441 minutes the ring has moved past minute 0 without a record. + assert!( + store + .query(TimeWindow::AllTime, None, at(epoch, 86_460)) + .is_empty() + ); + assert!( + store + .query(TimeWindow::LastDay, None, at(epoch, 86_460)) + .is_empty() + ); + assert_eq!(store.buckets().0, 2); + // A record one full ring later drops minute 0 and second 0. + store.record(ACCOUNTS[0], "Scan", &segs(5.0), at(epoch, 1441 * 60)); + let out = store.query(TimeWindow::AllTime, None, at(epoch, 1441 * 60)); + assert_eq!(count_of(&out, "Scan"), 1); + assert!((out[0].avg.auth_us - 5.0).abs() < f64::EPSILON); + assert_eq!(store.buckets().0, 2); +} + +/// The prune drops the rings of an account's operation once its newest coarse +/// bucket has left the whole-ring window, and the account once it holds no +/// operation. An account whose last request is still in the window keeps its +/// rings and the data in them. +#[test] +fn prune_drops_idle_accounts_and_keeps_active_ones() { + let epoch = Instant::now(); + let mut store = SegmentStore::new(epoch); + store.record(ACCOUNTS[0], "GetItem", &segs(1.0), at(epoch, 0)); + store.record(ACCOUNTS[0], "Scan", &segs(1.0), at(epoch, 0)); + store.record(ACCOUNTS[1], "GetItem", &segs(1.0), at(epoch, 0)); + store.record(ACCOUNTS[1], "GetItem", &segs(1.0), at(epoch, 60)); + // Two buckets per pair with one request, two per ring for the pair with + // requests in two seconds and two minutes. + assert_eq!(store.buckets().0, 2 + 2 + 4); + + // At 1440 minutes, minute 0 is the oldest slot of the ring: nothing goes. + store.prune(at(epoch, 1440 * 60)); + assert_eq!(store.by_account.len(), 2); + assert_eq!(store.buckets().0, 8); + assert_eq!( + count_of( + &store.query(TimeWindow::AllTime, None, at(epoch, 1440 * 60)), + "Scan" + ), + 1 + ); + + // One minute later minute 0 has left the ring. The first account's two + // operations have no newer bucket, so their rings go and the account with + // them. The second account's GetItem ring has minute 1 and stays. + store.prune(at(epoch, 1441 * 60)); + assert_eq!(store.by_account.len(), 1); + assert_eq!(store.buckets().0, 4); + assert!( + store + .query(TimeWindow::AllTime, Some(ACCOUNTS[0]), at(epoch, 1441 * 60)) + .is_empty() + ); + assert_eq!( + count_of( + &store.query(TimeWindow::AllTime, Some(ACCOUNTS[1]), at(epoch, 1441 * 60)), + "GetItem" + ), + 1 + ); + // The dropped account's next request allocates its rings again. + store.record(ACCOUNTS[0], "Scan", &segs(2.0), at(epoch, 1441 * 60)); + assert_eq!(store.by_account.len(), 2); + assert_eq!(store.buckets().0, 6); +} + +/// A memory case: label, accounts, operations, request times in seconds (the +/// same for every pair), then the buckets held and the buckets allocated +/// expected per pair. +type MemoryCase<'a> = (&'a str, usize, usize, &'a [u64], usize, usize); + +/// Buckets exist only for the seconds and minutes that had a request, and a +/// ring's allocation doubles up to its length and stops. +#[test] +fn bucket_memory_follows_the_requests_up_to_the_ring_length() { + const DAY: u64 = COARSE_SLOTS as u64 * COARSE_WIDTH_SECS; + let many: Vec = (0..1000) + .map(|i| format!("{:012}", 100_000_000_000u64 + i)) + .collect(); + let every_second: Vec = (0..2 * DAY).collect(); + let cases: [MemoryCase; 6] = [ + // One request a day holds one bucket per ring. + ( + "1,000 accounts x 40 operations, one request", + 1000, + 40, + &[0], + 2, + 2, + ), + // Six seconds of one minute: six fine buckets in a capacity of 8, one coarse. + ("six consecutive seconds", 1, 1, &[0, 1, 2, 3, 4, 5], 7, 9), + // A request a ring later drops all six fine buckets. The fine deque + // keeps its capacity of 8. + ( + "six seconds, then one request a ring later", + 1, + 1, + &[0, 1, 2, 3, 4, 5, DAY], + 2, + 9, + ), + // Five requests an hour apart: each drops the fine bucket before it; + // five coarse buckets in a capacity of 8. + ( + "five requests an hour apart", + 1, + 1, + &[0, 3600, 7200, 10_800, 14_400], + 6, + 9, + ), + // Two days of a request every second fill both rings exactly. + ( + "a request every second for two days", + 1, + 1, + &every_second, + BUCKETS_PER_OPERATION, + BUCKETS_PER_OPERATION, + ), + // A request a day later than the first drops the first's buckets. + ("two requests a ring apart", 1, 1, &[0, DAY], 2, 2), + ]; + for (label, accounts, operations, times, buckets, capacity) in cases { + let epoch = Instant::now(); + let mut store = SegmentStore::new(epoch); + let ops: Vec = (0..operations) + .map(|i| format!("Operation{i:02}")) + .collect(); + for account in &many[..accounts] { + for op in &ops { + for &t in times { + store.record(account, op, &segs(1.0), at(epoch, t)); + } + } + } + let pairs = accounts * operations; + let (held, allocated) = store.buckets(); + assert_eq!(held, pairs * buckets, "{label}: buckets"); + assert_eq!(allocated, pairs * capacity, "{label}: capacity"); + assert!( + allocated <= pairs * BUCKETS_PER_OPERATION, + "{label}: capacity over the ring length" + ); + // Every request is still in the whole-ring window. + let now = at(epoch, times[times.len() - 1]); + let total: u64 = store + .query(TimeWindow::AllTime, None, now) + .iter() + .map(|o| o.count) + .sum(); + let in_ring = times + .iter() + .filter(|&&t| t / 60 + COARSE_SLOTS as u64 > now.duration_since(epoch).as_secs() / 60) + .count(); + assert_eq!(total, (pairs * in_ring) as u64, "{label}: count"); + } +} diff --git a/crates/core/src/metrics/segments_tests.rs b/crates/core/src/metrics/segments_tests.rs new file mode 100644 index 000000000..28ee6a747 --- /dev/null +++ b/crates/core/src/metrics/segments_tests.rs @@ -0,0 +1,400 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Window and reference tests for [`SegmentStore`]; the bound and prune tests +//! are in `segments_bound_tests.rs`. + +use std::time::{Duration, Instant}; + +use super::*; + +pub(super) const OPS: [&str; 5] = ["GetItem", "PutItem", "Query", "Scan", "UpdateItem"]; +pub(super) const ACCOUNTS: [&str; 3] = ["111111111111", "222222222222", "333333333333"]; + +pub(super) fn segs(v: f64) -> LatencySegments { + LatencySegments { + auth_us: v, + authz_us: 2.0 * v, + throttle_us: 0.5 * v, + dispatch_us: 4.0 * v, + response_us: 0.25 * v, + total_us: 7.75 * v, + } +} + +/// Deterministic xorshift64* generator, so the random workload needs no crate. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} + +pub(super) fn at(epoch: Instant, secs: u64) -> Instant { + epoch + Duration::from_secs(secs) +} + +pub(super) fn count_of(out: &[OperationSegments], op: &str) -> u64 { + out.iter() + .find(|o| o.operation == op) + .map_or(0, |o| o.count) +} + +/// Naive reference: for a window of `w` seconds read from `b`-second buckets, +/// the store returns every point whose bucket starts at or after the bucket +/// that contains `now - w`. That set contains the exact last `w` seconds and +/// is contained in the exact last `w + b` seconds. Without an account filter +/// the reference is every account's points; with one, that account's points. +/// A point is `(account index, operation index, ms after the epoch, segments)`. +#[test] +fn random_workload_matches_naive_reference() { + let epoch = Instant::now(); + let mut store = SegmentStore::new(epoch); + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + let mut points: Vec<(usize, usize, u64, LatencySegments)> = Vec::new(); + let mut t_ms: u64 = 0; + // 300 000 points, 0 to 40 ms apart: about 6 000 s, so the hour and the + // minute windows both cut inside the data. + for _ in 0..300_000 { + t_ms += rng.below(41); + #[allow(clippy::cast_possible_truncation)] + let account = rng.below(ACCOUNTS.len() as u64) as usize; + #[allow(clippy::cast_possible_truncation)] + let op = rng.below(OPS.len() as u64) as usize; + #[allow(clippy::cast_precision_loss)] + let v = rng.below(10_000) as f64 / 7.0; + let s = segs(v); + store.record( + ACCOUNTS[account], + OPS[op], + &s, + epoch + Duration::from_millis(t_ms), + ); + points.push((account, op, t_ms, s)); + } + let windows = [ + (TimeWindow::LastMinute, 60, 1), + (TimeWindow::Last5Minutes, 300, 1), + (TimeWindow::LastHour, 3600, 60), + (TimeWindow::LastDay, 86400, 60), + ]; + let filters = [None, Some(0), Some(1), Some(2)]; + for now_ms in [t_ms, t_ms + 500, t_ms + 59_500, t_ms + 61_000] { + let now = epoch + Duration::from_millis(now_ms); + let now_secs = now_ms / 1000; + for (window, w, b) in windows { + let first_slot = now_secs.saturating_sub(w) / b; + for filter in filters { + let out = store.query(window, filter.map(|a| ACCOUNTS[a]), now); + assert_matches_reference(&out, &points, filter, (window, w, b), now_ms, first_slot); + } + } + } +} + +/// Checks `out`, the store's answer for the window `(window, w, b)` at +/// `now_ms`, against the points of the account at index `filter` in +/// `ACCOUNTS` (every account when `None`) summed by hand: the count is exact, +/// the means agree to 1e-9, and the count lies between the exact `w` and +/// `w + b` second windows. The label names the index, not the account id. +fn assert_matches_reference( + out: &[OperationSegments], + points: &[(usize, usize, u64, LatencySegments)], + filter: Option, + (window, w, b): (TimeWindow, u64, u64), + now_ms: u64, + first_slot: u64, +) { + for (i, op) in OPS.iter().enumerate() { + let label = format!( + "{op} {window:?} at {now_ms} ms, filter {}", + filter.map_or_else(|| "none".to_owned(), |a| format!("index {a}")) + ); + let mut count = 0u64; + let mut sum = LatencySegments::default(); + let mut exact_w = 0u64; + let mut exact_w_plus_b = 0u64; + for (p_account, p_op, p_ms, s) in points { + if *p_op != i || filter.is_some_and(|a| *p_account != a) { + continue; + } + if *p_ms + w * 1000 >= now_ms { + exact_w += 1; + } + if *p_ms + (w + b) * 1000 >= now_ms { + exact_w_plus_b += 1; + } + if (*p_ms / 1000) / b >= first_slot { + count += 1; + sum.auth_us += s.auth_us; + sum.authz_us += s.authz_us; + sum.throttle_us += s.throttle_us; + sum.dispatch_us += s.dispatch_us; + sum.response_us += s.response_us; + sum.total_us += s.total_us; + } + } + let got = out.iter().find(|o| &o.operation == op); + if count == 0 { + assert!(got.is_none(), "{label}: expected absent"); + continue; + } + let got = got.unwrap_or_else(|| panic!("{label}: missing")); + assert_eq!(got.count, count, "{label}: count"); + assert!( + exact_w <= count && count <= exact_w_plus_b, + "{label}: {exact_w} <= {count} <= {exact_w_plus_b}" + ); + #[allow(clippy::cast_precision_loss)] + let c = count as f64; + let close = |a: f64, b: f64| ((a - b) / b).abs() < 1e-9; + assert!(close(got.avg.auth_us, sum.auth_us / c), "{label}: auth"); + assert!(close(got.avg.authz_us, sum.authz_us / c), "{label}: authz"); + assert!( + close(got.avg.throttle_us, sum.throttle_us / c), + "{label}: throttle" + ); + assert!( + close(got.avg.dispatch_us, sum.dispatch_us / c), + "{label}: dispatch" + ); + assert!( + close(got.avg.response_us, sum.response_us / c), + "{label}: response" + ); + assert!(close(got.avg.total_us, sum.total_us / c), "{label}: total"); + } +} + +/// `LastHour` reads 1-minute buckets: points 0 s and 59 s after the epoch +/// share a bucket, and that bucket is included until the hour window's +/// cutoff leaves the minute it starts in. +#[test] +fn window_filter_at_minute_boundary() { + let epoch = Instant::now(); + let mut store = SegmentStore::new(epoch); + for t in [0, 59, 60] { + store.record(ACCOUNTS[0], "GetItem", &segs(1.0), at(epoch, t)); + } + // The fine ring cuts at the second: 119 s keeps 59 s and 60 s, 120 s drops 59 s. + assert_eq!( + count_of( + &store.query(TimeWindow::LastMinute, None, at(epoch, 119)), + "GetItem" + ), + 2 + ); + assert_eq!( + count_of( + &store.query(TimeWindow::LastMinute, None, at(epoch, 120)), + "GetItem" + ), + 1 + ); + // 3659 s: cutoff 59 s lies in minute 0, so minute 0 is included. + store.record(ACCOUNTS[0], "GetItem", &segs(1.0), at(epoch, 3659)); + assert_eq!( + count_of( + &store.query(TimeWindow::LastHour, None, at(epoch, 3659)), + "GetItem" + ), + 4 + ); + // An exact filter would have returned 3 here (59, 60, 3659). + // 3660 s: cutoff 60 s starts minute 1, so minute 0 is excluded. + assert_eq!( + count_of( + &store.query(TimeWindow::LastHour, None, at(epoch, 3660)), + "GetItem" + ), + 2 + ); +} + +/// `LastMinute` and `Last5Minutes` read 1-second buckets, so they are at most +/// one second wider than the exact window. +#[test] +fn fine_windows_cut_at_the_second() { + let epoch = Instant::now(); + let mut store = SegmentStore::new(epoch); + for t in [0, 1, 2, 300, 301] { + store.record(ACCOUNTS[0], "Query", &segs(1.0), at(epoch, t)); + } + // 301 s: cutoff 1 s, buckets 1, 2, 300, 301. + assert_eq!( + count_of( + &store.query(TimeWindow::Last5Minutes, None, at(epoch, 301)), + "Query" + ), + 4 + ); + // 302 s: cutoff 2 s. + assert_eq!( + count_of( + &store.query(TimeWindow::Last5Minutes, None, at(epoch, 302)), + "Query" + ), + 3 + ); + // 361 s: cutoff 301 s for the minute window. + assert_eq!( + count_of( + &store.query(TimeWindow::LastMinute, None, at(epoch, 361)), + "Query" + ), + 1 + ); + assert_eq!( + count_of( + &store.query(TimeWindow::LastMinute, None, at(epoch, 362)), + "Query" + ), + 0 + ); + assert!( + store + .query(TimeWindow::LastMinute, None, at(epoch, 362)) + .is_empty() + ); +} + +/// One request every second for three laps of the coarse ring, queried at +/// every ring and window boundary and every 977 s in between. The expected +/// count and mean have a closed form (an arithmetic series over the included +/// seconds) that does not go through the ring, so a coarse ring that loses or +/// leaks a bucket after its first lap fails here. +#[test] +fn continuous_load_three_coarse_laps_exact_count_and_mean() { + // (window, W seconds, bucket width b, ring length) + const WINDOWS: [(TimeWindow, u64, u64, u64); 5] = [ + ( + TimeWindow::LastMinute, + 60, + FINE_WIDTH_SECS, + FINE_SLOTS as u64, + ), + ( + TimeWindow::Last5Minutes, + 300, + FINE_WIDTH_SECS, + FINE_SLOTS as u64, + ), + ( + TimeWindow::LastHour, + 3600, + COARSE_WIDTH_SECS, + COARSE_SLOTS as u64, + ), + ( + TimeWindow::LastDay, + 86_400, + COARSE_WIDTH_SECS, + COARSE_SLOTS as u64, + ), + ( + TimeWindow::AllTime, + 86_400, + COARSE_WIDTH_SECS, + COARSE_SLOTS as u64, + ), + ]; + let epoch = Instant::now(); + let mut store = SegmentStore::new(epoch); + let end: u64 = 3 * COARSE_SLOTS as u64 * COARSE_WIDTH_SECS + 123; + let mut query_times: Vec = (0..=end).step_by(977).collect(); + for (_, w, b, len) in WINDOWS { + query_times.extend([ + w - 1, + w, + w + 1, + w + b - 1, + w + b, + len * b - 1, + len * b, + len * b + 1, + 2 * len * b, + 2 * len * b + b - 1, + end, + ]); + } + query_times.sort_unstable(); + query_times.dedup(); + let mut next = 0usize; + let mut checks = 0u64; + for t in 0..=end { + #[allow(clippy::cast_precision_loss)] + let v = t as f64; + store.record( + ACCOUNTS[0], + "Scan", + &LatencySegments { + auth_us: v, + authz_us: 0.0, + throttle_us: 1.0, + dispatch_us: 0.0, + response_us: 0.0, + total_us: v, + }, + at(epoch, t), + ); + if next >= query_times.len() || query_times[next] != t { + continue; + } + next += 1; + for (window, w, b, _) in WINDOWS { + // First included second: the start of the bucket holding t - W. + let first = t.saturating_sub(w) / b * b; + let want_count = t - first + 1; + let want_sum = (first + t) * want_count / 2; + let out = store.query(window, None, at(epoch, t)); + let Some(o) = out.iter().find(|o| o.operation == "Scan") else { + panic!("{window:?} t={t}: Scan absent"); + }; + assert_eq!(o.count, want_count, "{window:?} t={t} count"); + #[allow(clippy::cast_precision_loss)] + let mean = want_sum as f64 / want_count as f64; + assert!( + (o.avg.auth_us - mean).abs() <= mean * 1e-12, + "{window:?} t={t} mean got {} want {mean}", + o.avg.auth_us + ); + assert!( + (o.avg.throttle_us - 1.0).abs() < 1e-12, + "{window:?} t={t} throttle" + ); + checks += 1; + } + } + assert!(checks > 1000, "only {checks} checks ran"); +} + +#[test] +fn operations_sorted_and_zero_count_absent() { + let epoch = Instant::now(); + let mut store = SegmentStore::new(epoch); + store.record(ACCOUNTS[0], "Scan", &segs(1.0), at(epoch, 10)); + store.record(ACCOUNTS[0], "GetItem", &segs(1.0), at(epoch, 10)); + store.record(ACCOUNTS[0], "PutItem", &segs(1.0), at(epoch, 1000)); + let out = store.query(TimeWindow::LastMinute, None, at(epoch, 1000)); + let names: Vec<&str> = out.iter().map(|o| o.operation.as_str()).collect(); + assert_eq!(names, ["PutItem"]); + let out = store.query(TimeWindow::AllTime, None, at(epoch, 1000)); + let names: Vec<&str> = out.iter().map(|o| o.operation.as_str()).collect(); + assert_eq!(names, ["GetItem", "PutItem", "Scan"]); + // An account that sent nothing has no buckets to read. + assert!( + store + .query(TimeWindow::AllTime, Some(ACCOUNTS[1]), at(epoch, 1000)) + .is_empty() + ); +} diff --git a/crates/server/src/console/pages/metrics_pages_tests.rs b/crates/server/src/console/pages/metrics_pages_tests.rs index 09324da15..fa89def6e 100644 --- a/crates/server/src/console/pages/metrics_pages_tests.rs +++ b/crates/server/src/console/pages/metrics_pages_tests.rs @@ -98,8 +98,7 @@ fn collector() -> Arc { collector.record_segments( TABLES[0].0, "GetItem", - Some(TABLES[0].1), - LatencySegments { + &LatencySegments { dispatch_us: 500.0, total_us: 500.0, ..LatencySegments::default() diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 6033494d6..343c81357 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -404,8 +404,7 @@ pub(crate) async fn handle_request( state.metrics.record_segments( &ctx.account_id, &operation, - metric_table.as_deref(), - extenddb_core::metrics::LatencySegments { + &extenddb_core::metrics::LatencySegments { auth_us, authz_us, throttle_us, diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index 46cd8c524..d52daf1c7 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -346,6 +346,38 @@ ExtendDB's own `AccountId` dimension. (omitted in the in-memory fallback path). - `segments` (`Vec`): per-operation latency breakdown (auth / authz / throttle / dispatch / response in microseconds), in-memory only. + Requests are summed at record time into fixed time buckets per account and + operation (1-second buckets for the last 5 minutes, 1-minute buckets for the + last 24 hours), so a window covers at least its length and at most one bucket + width more, and the memory per account and operation is bounded whatever the + request count. `LastMinute` + and `Last5Minutes` read the 1-second buckets; `LastHour` and `LastDay` read + the 1-minute buckets; `AllTime` returns the whole 24-hour ring. With the + `account_id` filter the breakdown reads that account's buckets; without it, + every account's buckets are summed per operation. The table is not a + dimension of this breakdown. Operations with no request in the window are + omitted; results are sorted by operation name. + Each account's operation holds a 64-byte bucket per second of the last five + minutes and per minute of the last day with a request. That is at most 301 + one-second and 1,441 one-minute buckets, 111,488 bytes. So the breakdown + holds at most `accounts x operations x 111,488` bytes of buckets, plus the + keys and map entries. A pair with one request a day holds two buckets. With + its keys and map entries it takes 286 to 429 bytes when its account sends 3 + to 40 operations. The cost steps up each time the account's map of + operations grows. It is 475 bytes with 2 operations. It is 810 bytes when its + account sends only that operation (release build, counting allocator, 1,000 + accounts, 24 November 2026). A ring's allocation + does not shrink: a pair keeps the largest allocation it reached until a day + passes with no request for it. With the 40 operations the server dispatches, + an account that sends every operation every second holds about 4.46 MB + (4.25 MiB). An account that sends each operation once a day holds about + 14 KB. `accounts` counts the accounts that sent a request in the + last day. The metrics prune runs every five minutes. It drops the buckets of + an account's operation once its newest bucket left the 24-hour ring, 1,440 to + about 1,446 minutes after that request. It drops the account once it holds no + operation. The segments are recorded only for requests that reach dispatch. A + request refused by authentication, authorization, throttling or the + point-in-time recovery check adds none. - `source`: `"database"` when served from the persistent `MetricsStore`, `"memory"` when served from the in-process `MetricsCollector` fallback. diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index ab3b307fe..99fc9afde 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -388,6 +388,17 @@ Catalog upgrades change the schema; behavior changes alter how the running serve interprets existing data or configuration. Review these before upgrading a live deployment, even when no catalog migration is required. +### v1.1.0: latency `segments` are summed into time buckets + +**What changed** (#398). The latency `segments` that `/metrics` and the console's `/console/metrics-data` return come from time buckets per account and operation. 1.0.0 kept one record per request for 24 hours. Each operation's count and means are still exact over the requests that the window covers. Four things change: + +- A window of `W` seconds returns at least the last `W` seconds and at most one bucket width more: up to 1 second more for `LastMinute` and `Last5Minutes`, and up to 60 seconds more for `LastHour` and `LastDay`. 1.0.0 cut each window exactly `W` seconds before the query. +- `AllTime` returns the same as `LastDay`. 1.0.0 returned every record it held, 24 hours to 24 hours and 5 minutes of requests. +- The operations are sorted by name. 1.0.0 returned them in no fixed order. +- The segment memory is bounded: at most 111,488 bytes of buckets for each operation of each account that sent it in the last day, about 4.46 MB for an account that sends all 40 operations every second. 1.0.0 kept about 250 bytes for each request that reached dispatch in the last 24 hours, so the sizing rule in the deployment guide's [Process Memory](11-deployment-guide.md#process-memory) section stops applying after the upgrade. + +No catalog migration or configuration change is required. + ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM` **What changed.** The Cassandra backend runs its reads and writes at `LOCAL_QUORUM`. 0.1.15 ran many of them at `ONE`, the driver's default, in each area: items (the reads of GetItem, Query and Scan among them), transactions, TTL, streams, the catalog, IAM and `init`. A read with `ConsistentRead` `false` also runs at `LOCAL_QUORUM`. A lightweight transaction runs Paxos at `LOCAL_SERIAL` and commits at `LOCAL_QUORUM`. 0.1.15 ran many of its lightweight transactions at those levels already, and others, among them the admin user creation and most IAM writes, at the driver's defaults, `SERIAL` and `ONE`. Batches ran at `LOCAL_QUORUM` before and still do. No setting changes these levels (#945). diff --git a/docs/manuals/11-deployment-guide.md b/docs/manuals/11-deployment-guide.md index d11e9a79f..cbaf593e5 100755 --- a/docs/manuals/11-deployment-guide.md +++ b/docs/manuals/11-deployment-guide.md @@ -381,6 +381,70 @@ FROM pg_stat_statements WHERE usename = 'extenddb' ORDER BY mean_exec_time DESC LIMIT 10; ``` +### Process Memory + +The memory the metrics hold does not grow with the number of requests served. +Counter metrics are held for at most two minutes before they are flushed to the +catalog. So the memory they occupy scales with the request rate and not with +uptime. A GetItem adds five or seven 40-byte points (seven when it returns an +item), held for 60 to 120 seconds. +Per-operation latency segments are summed into time buckets per account and +operation. A bucket is 64 bytes and covers one second of the last five minutes +or one minute of the last day. A bucket exists only for a second or minute in +which the account sent that operation. An operation the account sends every +second holds the most buckets, 1,742, which is 111,488 bytes (109 KiB). An +operation the account sends once a day holds two buckets. With its keys and +map entries that is 286 to 429 bytes when the account sends 3 to 40 +operations. The cost steps up each time the account's map of operations grows. +It is 475 bytes with 2 operations, and 810 bytes when the account sends only +that operation. These figures come from a release build with a counting +allocator and 1,000 accounts, on 24 November 2026. With the 40 +operations the server dispatches, an account that sends every operation every +second holds about 4.46 MB (4.25 MiB) of buckets. An account that sends each +operation once a day holds about 14 KB. The memory of an operation's buckets +does not shrink when the account sends it less often. The operation keeps the +largest allocation it reached, up to 111,488 bytes, until a day passes with no +request for it. Then the five-minute metrics prune drops its buckets, and it +drops the account once the account holds no operation. That happens 1,440 to +about 1,446 minutes after the last request. The buckets return to the +allocator. The process's resident size can +stay at the high-water mark the allocator reached. So the segments grow with +the number of accounts that sent a request in the last day. They also grow with +the seconds and minutes in which each of those accounts was active. Below one +request a second per operation, they grow with the request rate. Above it, and +with the table count or uptime, they do not grow. With +`throttling_enabled = true` the throttle manager keeps a read and a write token +bucket for each distinct value of the first attribute in the `Key` or `Item` +of a GetItem, PutItem, UpdateItem or DeleteItem. That attribute comes first in +name order, or in the request's order on a build with the MongoDB backend. So +it can be the sort key. It never drops a bucket. Resident memory then grows +with the number of distinct values those requests carry. + +Every release through 1.0.0 kept one latency segment record per request that +reaches dispatch in memory for 24 hours. So does any later release before the +one that carries this change. The upgrade manual's +[v1.1.0 entry](07-upgrade-manual.md#v110-latency-segments-are-summed-into-time-buckets) +lists what the change does to the `segments` that `/metrics` returns. A record +takes about 190 bytes through 0.1.14, and about +250 from 0.1.15 on, which also stores the account id. On those releases resident +memory grows for the first 24 hours. It then holds at the level set by the +busiest 24-hour window the process saw, and it does not come down short of a +restart. To run one of those releases until you upgrade, size the memory limit +as + +``` +limit >= baseline + bytes_per_request * requests_per_24h * 1.3 +``` + +where `bytes_per_request` is 190 through 0.1.14 and 250 from 0.1.15 on. The +factor 1.3 is a modelled allowance for allocator overhead, not a measured +figure. At 274 requests per second, 23.7 million requests per day, the rule +gives about 5.5 GiB plus baseline on 0.1.14. On 1.0.0 it gives about 7.2 GiB +plus baseline. Or restart the process before the limit is reached. +Stop with SIGTERM or `extenddb stop` so the last partial minute of counter +metrics is flushed. Only the in-memory latency segments are lost on restart; +counter metrics are in the catalog. + --- ## License diff --git a/docs/todo-index.md b/docs/todo-index.md index 428c744a1..2fa05d98b 100755 --- a/docs/todo-index.md +++ b/docs/todo-index.md @@ -13,7 +13,6 @@ Regenerated: v0.1.6 (BR-7085) - `crates/storage/src/lib.rs:592` — Unreachable method; engine handler returns before reaching it. - `crates/storage-postgres/src/backup_engine.rs:640` — Unreachable method; engine handler returns before reaching it. -- `crates/core/src/metrics/collector.rs:124` — `#[allow(dead_code)]` on field used when console adds table-scoped latency breakdown. ## TODO (issue-tracked)