From 8d4208e2875a7e8516f3becf08a9b83d71a50d4b Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Tue, 13 Oct 2026 14:12:23 +0000 Subject: [PATCH 01/22] fix(metrics): sum latency segments into fixed time buckets instead of keeping one point per request MetricsCollector kept a SegmentPoint (112 bytes plus two heap strings) for every data-plane request for 24 hours. At 274 requests per second that is 23.7 million points a day and about 4.3 GiB of anonymous memory (issue #397); measured here, the 0.1.13 binary grows by 193.5 bytes per GetItem. The console only reads per-operation counts and mean segments over a window, so the points are summed at record time instead. Each operation now owns two fixed rings of 64-byte buckets: 301 one-second buckets serving LastMinute and Last5Minutes, and 1441 one-minute buckets serving LastHour, LastDay and AllTime. A record is one hash lookup and two bucket updates under the write lock; the rings are allocated once per operation. Memory is at most operations * 111,488 bytes, and the server only records the 37 operations in the dispatch table, so under 4 MiB per process. A window of W seconds covers at least the last W seconds and at most W plus one bucket width. The clock is read under the lock on both the record and the query path, so a stored record is never ahead of a query that follows it. prune() no longer touches segments. record_segments(operation, &LatencySegments) no longer takes the table name: a per-table dimension would multiply the bound by the table count, which clients control, and nothing read it. The one caller is updated. Docs: the design doc states the bucket widths and what each window returns; the deployment guide gains a Process Memory subsection with the growth law for releases through 0.1.13; the todo-index entry for the table field is removed. Tests: boundedness over five million synthetic requests, a naive-reference comparison on a random workload, continuous load across three laps of the coarse ring against a closed-form reference, window filters at second and minute boundaries, ring wrap and stale-slot exclusion, and an ignored timing comparison of the old push against the new record. --- crates/core/src/metrics/collector.rs | 53 +-- crates/core/src/metrics/collector_query.rs | 67 +-- crates/core/src/metrics/collector_tests.rs | 26 +- crates/core/src/metrics/mod.rs | 5 +- crates/core/src/metrics/segments.rs | 269 +++++++++++ crates/core/src/metrics/segments_tests.rs | 529 +++++++++++++++++++++ crates/server/src/handler.rs | 3 +- docs/design/06-component-server.md | 8 + docs/manuals/11-deployment-guide.md | 27 ++ docs/todo-index.md | 1 - 10 files changed, 896 insertions(+), 92 deletions(-) create mode 100644 crates/core/src/metrics/segments.rs create mode 100644 crates/core/src/metrics/segments_tests.rs diff --git a/crates/core/src/metrics/collector.rs b/crates/core/src/metrics/collector.rs index 689b900a5..9489d35de 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. @@ -38,30 +39,21 @@ 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-operation latency segment sums for the console deep-dive, bucketed + /// by time so memory is bounded by the number of 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, - #[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(()), } } @@ -318,25 +310,27 @@ impl MetricsCollector { } /// Record per-segment latency breakdown for a request. - pub fn record_segments( - &self, - operation: &str, - table_name: Option<&str>, - segments: LatencySegments, - ) { - let point = SegmentPoint { - operation: operation.to_owned(), - table_name: table_name.map(ToOwned::to_owned), - segments, - timestamp: Instant::now(), - }; - let Ok(mut vec) = self.segments.write() else { + /// + /// The breakdown is summed into the operation's current time buckets, so + /// the memory held does not grow with the request count (issue #397). The + /// table is not a dimension here: a per-table breakdown would multiply the + /// bound by the table count, and the console reads per-operation averages. + pub fn record_segments(&self, operation: &str, segments: &LatencySegments) { + // 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 overwrite the oldest in-window bucket before a reader with an + // earlier clock reads it. + let Ok(mut store) = self.segments.write() else { return; }; - vec.push(point); + store.record(operation, segments, Instant::now()); } /// Prune data points older than 1 day. + /// + /// Segment buckets are overwritten in place as time advances and need no + /// pruning. pub fn prune(&self) { let now = Instant::now(); let cutoff = now.checked_sub(Duration::from_secs(86400)).unwrap_or(now); @@ -347,11 +341,6 @@ impl MetricsCollector { acc.prune(cutoff); } 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); - } } } diff --git a/crates/core/src/metrics/collector_query.rs b/crates/core/src/metrics/collector_query.rs index 7ce9af6ff..0d329890c 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. /// @@ -142,51 +139,31 @@ impl MetricsCollector { /// Query average latency segments for the console deep-dive. /// - /// Returns per-operation averages over the given time window. + /// Returns per-operation averages over the given time window, sorted by + /// operation name. `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) -> Vec { - let now = Instant::now(); - let cutoff = window_cutoff(window, now); - let Ok(vec) = self.segments.read() else { + // Clock read under the lock, paired with `record_segments`. + 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; - } - 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, Instant::now()) + } + + /// `query_segments` with an injected clock, for tests. + #[cfg(test)] + pub(super) fn query_segments_at( + &self, + window: TimeWindow, + now: Instant, + ) -> Vec { + let Ok(store) = self.segments.read() else { + return Vec::new(); + }; + store.query(window, now) } } diff --git a/crates/core/src/metrics/collector_tests.rs b/crates/core/src/metrics/collector_tests.rs index 26a50b7f6..6646314e8 100755 --- a/crates/core/src/metrics/collector_tests.rs +++ b/crates/core/src/metrics/collector_tests.rs @@ -79,8 +79,7 @@ fn record_and_query_segments() { let c = MetricsCollector::new(); c.record_segments( "GetItem", - Some("T"), - LatencySegments { + &LatencySegments { auth_us: 100.0, authz_us: 200.0, throttle_us: 50.0, @@ -91,8 +90,7 @@ fn record_and_query_segments() { ); c.record_segments( "GetItem", - Some("T"), - LatencySegments { + &LatencySegments { auth_us: 200.0, authz_us: 300.0, throttle_us: 50.0, @@ -114,14 +112,17 @@ fn record_and_query_segments() { } #[test] -fn prune_removes_old_segments() { +fn prune_leaves_segments_alone_and_the_ring_ages_them_out() { 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( "PutItem", - None, - LatencySegments { + &LatencySegments { auth_us: 10.0, authz_us: 20.0, throttle_us: 5.0, @@ -136,6 +137,11 @@ fn prune_removes_old_segments() { let segs = c.query_segments(TimeWindow::AllTime); 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_secs(1441 * 60); + assert!(c.query_segments_at(TimeWindow::AllTime, later).is_empty()); + assert!(c.query_segments_at(TimeWindow::LastDay, later).is_empty()); } #[test] @@ -145,8 +151,7 @@ fn segments_multiple_operations() { let c = MetricsCollector::new(); c.record_segments( "GetItem", - Some("T"), - LatencySegments { + &LatencySegments { auth_us: 100.0, authz_us: 200.0, throttle_us: 50.0, @@ -157,8 +162,7 @@ fn segments_multiple_operations() { ); c.record_segments( "PutItem", - Some("T"), - LatencySegments { + &LatencySegments { auth_us: 120.0, authz_us: 220.0, throttle_us: 60.0, diff --git a/crates/core/src/metrics/mod.rs b/crates/core/src/metrics/mod.rs index bf1ff0272..b6050e94a 100755 --- a/crates/core/src/metrics/mod.rs +++ b/crates/core/src/metrics/mod.rs @@ -6,13 +6,16 @@ //! 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-operation latency segments are summed into fixed +//! time buckets at record time (see `segments`), so they hold a bounded amount +//! of memory and need no pruning. //! //! REQ-OBS-005: Metrics endpoint. mod accumulator; mod collector; mod collector_query; +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..a427c69e9 --- /dev/null +++ b/crates/core/src/metrics/segments.rs @@ -0,0 +1,269 @@ +// 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 owns two fixed 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, and is overwritten +//! in place when its ring position comes around again, so the memory per +//! process is at most `operations * (FINE_SLOTS + COARSE_SLOTS) * 64` bytes. +//! The server only records operations that pass `is_known_operation`, which +//! caps `operations` at the size of the dispatch table. +//! +//! Issue #397: one `SegmentPoint` per request grew to about 4.3 GiB in a day at +//! 274 requests per second. + +use std::collections::HashMap; +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, 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 { + fn add(&mut self, s: &LatencySegments) { + self.count += 1; + self.auth_us += s.auth_us; + self.authz_us += s.authz_us; + self.throttle_us += s.throttle_us; + self.dispatch_us += s.dispatch_us; + self.response_us += s.response_us; + self.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 fixed ring of buckets. Slot `k` covers elapsed seconds +/// `[k * width, (k + 1) * width)` and lives at position `k % len`. +#[derive(Debug)] +struct Ring { + width_secs: u64, + buckets: Box<[Bucket]>, +} + +impl Ring { + fn new(width_secs: u64, slots: usize) -> Self { + Self { + width_secs, + buckets: vec![Bucket::default(); slots].into_boxed_slice(), + } + } + + fn slots(&self) -> u64 { + self.buckets.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; + #[allow(clippy::cast_possible_truncation)] // slot % len < len <= usize::MAX + let position = (slot % self.slots()) as usize; + let bucket = &mut self.buckets[position]; + if bucket.slot < slot { + // The position comes around again: drop what the previous lap left. + *bucket = Bucket { + slot, + ..Bucket::default() + }; + } + // `bucket.slot > slot` means this record lags the newest one by a full + // ring, which monotonic time rules out; it is counted where it lands. + bucket.add(segments); + } + + /// Sums every bucket whose slot is at or after `first_slot` into `acc`. + /// Slots left over from an earlier lap are older than `first_slot` for + /// every window this ring serves, so no separate staleness check is needed. + fn sum_from(&self, first_slot: u64, acc: &mut Bucket) { + for b in &self.buckets { + if b.slot >= first_slot && b.count > 0 { + 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-operation segment buckets. Lives behind the collector's lock. +#[derive(Debug)] +pub(super) struct SegmentStore { + /// Time zero for slot arithmetic. + epoch: Instant, + by_operation: HashMap, +} + +impl SegmentStore { + pub(super) fn new(epoch: Instant) -> Self { + Self { + epoch, + by_operation: 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. Steady state is one hash lookup and two bucket + /// updates; the only allocation is the rings of an operation seen for the + /// first time. + pub(super) fn record(&mut self, operation: &str, segments: &LatencySegments, now: Instant) { + let elapsed = self.elapsed_secs(now); + if let Some(rings) = self.by_operation.get_mut(operation) { + rings.record(elapsed, segments); + return; + } + self.by_operation + .entry(operation.to_owned()) + .or_insert_with(OperationRings::new) + .record(elapsed, segments); + } + + /// Per-operation count and mean segments over `window`, sorted by + /// operation name. 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, now: Instant) -> Vec { + let elapsed = self.elapsed_secs(now); + let (fine, window_secs) = ring_for(window); + let mut out: Vec = self + .by_operation + .iter() + .filter_map(|(operation, rings)| { + let ring = if fine { &rings.fine } else { &rings.coarse }; + let mut acc = Bucket::default(); + ring.sum_from(ring.first_slot(elapsed, window_secs), &mut acc); + (acc.count > 0).then(|| { + #[allow(clippy::cast_precision_loss)] + let c = acc.count as f64; + OperationSegments { + operation: operation.clone(), + 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(); + out.sort_by(|a, b| a.operation.cmp(&b.operation)); + out + } + + /// Number of operations with rings allocated. + #[cfg(test)] + pub(super) fn operation_count(&self) -> usize { + self.by_operation.len() + } + + /// Number of buckets allocated, the quantity the memory bound is stated in. + #[cfg(test)] + pub(super) fn bucket_count(&self) -> usize { + self.by_operation + .values() + .map(|r| r.fine.buckets.len() + r.coarse.buckets.len()) + .sum() + } + + /// 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; diff --git a/crates/core/src/metrics/segments_tests.rs b/crates/core/src/metrics/segments_tests.rs new file mode 100644 index 000000000..c56c11db6 --- /dev/null +++ b/crates/core/src/metrics/segments_tests.rs @@ -0,0 +1,529 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Tests for [`SegmentStore`]. + +use std::time::{Duration, Instant}; + +use super::*; + +const OPS: [&str; 5] = ["GetItem", "PutItem", "Query", "Scan", "UpdateItem"]; + +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 + } +} + +fn at(epoch: Instant, secs: u64) -> Instant { + epoch + Duration::from_secs(secs) +} + +fn count_of(out: &[OperationSegments], op: &str) -> u64 { + out.iter() + .find(|o| o.operation == op) + .map_or(0, |o| o.count) +} + +#[test] +fn bucket_is_64_bytes() { + assert_eq!(SegmentStore::bucket_size(), 64); + assert_eq!(BUCKETS_PER_OPERATION, 1742); +} + +/// Issue #397: five million requests over three simulated days across five +/// operations allocate exactly the fixed rings and nothing per request. +#[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. + for i in 0..total { + let now = epoch + Duration::from_millis(i * 52); + #[allow(clippy::cast_possible_truncation)] + let op = OPS[(i % 5) as usize]; + store.record(op, &segs(1.0), now); + } + let bound = OPS.len() * BUCKETS_PER_OPERATION; + assert_eq!(store.operation_count(), OPS.len()); + assert!( + store.bucket_count() <= bound, + "bucket count {} exceeds bound {bound}", + store.bucket_count() + ); + assert!(store.bucket_count() * SegmentStore::bucket_size() <= bound * 64); + // The rings are allocated once per operation, so the bound is also exact. + assert_eq!(store.bucket_count(), 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, 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); +} + +/// 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. +#[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, 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 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(OPS[op], &s, epoch + Duration::from_millis(t_ms)); + points.push((op, t_ms, s)); + } + let windows = [ + (TimeWindow::LastMinute, 60, 1), + (TimeWindow::Last5Minutes, 300, 1), + (TimeWindow::LastHour, 3600, 60), + (TimeWindow::LastDay, 86400, 60), + ]; + 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 out = store.query(window, now); + let first_slot = now_secs.saturating_sub(w) / b; + for (i, op) in OPS.iter().enumerate() { + let mut count = 0u64; + let mut sum = LatencySegments::default(); + let mut exact_w = 0u64; + let mut exact_w_plus_b = 0u64; + for (p_op, p_ms, s) in &points { + if *p_op != i { + 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(), + "{op} {window:?} at {now_ms}: expected absent" + ); + continue; + } + let got = got.unwrap_or_else(|| panic!("{op} {window:?} at {now_ms}: missing")); + assert_eq!(got.count, count, "{op} {window:?} at {now_ms}: count"); + assert!( + exact_w <= count && count <= exact_w_plus_b, + "{op} {window:?} at {now_ms}: {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), + "{op} {window:?} auth" + ); + assert!( + close(got.avg.authz_us, sum.authz_us / c), + "{op} {window:?} authz" + ); + assert!( + close(got.avg.throttle_us, sum.throttle_us / c), + "{op} {window:?} throttle" + ); + assert!( + close(got.avg.dispatch_us, sum.dispatch_us / c), + "{op} {window:?} dispatch" + ); + assert!( + close(got.avg.response_us, sum.response_us / c), + "{op} {window:?} response" + ); + assert!( + close(got.avg.total_us, sum.total_us / c), + "{op} {window:?} 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("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, at(epoch, 119)), + "GetItem" + ), + 2 + ); + assert_eq!( + count_of( + &store.query(TimeWindow::LastMinute, at(epoch, 120)), + "GetItem" + ), + 1 + ); + // 3659 s: cutoff 59 s lies in minute 0, so minute 0 is included. + store.record("GetItem", &segs(1.0), at(epoch, 3659)); + assert_eq!( + count_of( + &store.query(TimeWindow::LastHour, 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, 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("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, at(epoch, 301)), + "Query" + ), + 4 + ); + // 302 s: cutoff 2 s. + assert_eq!( + count_of( + &store.query(TimeWindow::Last5Minutes, at(epoch, 302)), + "Query" + ), + 3 + ); + // 361 s: cutoff 301 s for the minute window. + assert_eq!( + count_of( + &store.query(TimeWindow::LastMinute, at(epoch, 361)), + "Query" + ), + 1 + ); + assert_eq!( + count_of( + &store.query(TimeWindow::LastMinute, at(epoch, 362)), + "Query" + ), + 0 + ); + assert!( + store + .query(TimeWindow::LastMinute, at(epoch, 362)) + .is_empty() + ); +} + +/// A ring position that comes around again is reset for the new slot, and a +/// slot from an earlier lap that was never overwritten 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("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, at(epoch, 86_459)), "Scan"), + 1 + ); + assert_eq!( + count_of(&store.query(TimeWindow::LastDay, at(epoch, 86_459)), "Scan"), + 1 + ); + // At 1441 minutes the ring has moved past minute 0 without overwriting it. + assert!( + store + .query(TimeWindow::AllTime, at(epoch, 86_460)) + .is_empty() + ); + assert!( + store + .query(TimeWindow::LastDay, at(epoch, 86_460)) + .is_empty() + ); + // A record one full lap later lands on position 0 and resets it. + store.record("Scan", &segs(5.0), at(epoch, 1441 * 60)); + let out = store.query(TimeWindow::AllTime, 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.bucket_count(), BUCKETS_PER_OPERATION); +} + +/// 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( + "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, 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("Scan", &segs(1.0), at(epoch, 10)); + store.record("GetItem", &segs(1.0), at(epoch, 10)); + store.record("PutItem", &segs(1.0), at(epoch, 1000)); + let out = store.query(TimeWindow::LastMinute, 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, at(epoch, 1000)); + let names: Vec<&str> = out.iter().map(|o| o.operation.as_str()).collect(); + assert_eq!(names, ["GetItem", "PutItem", "Scan"]); +} + +/// Write-path and read-path cost of the previous one-point-per-request +/// `Vec` against the bucketed store, one million single-threaded calls each. +/// Run with `cargo test -p extenddb-core -- --ignored bench --nocapture`, in +/// debug and in `--release`. +#[test] +#[ignore = "timing, run by hand"] +fn bench_old_push_vs_new_record() { + use std::sync::RwLock; + + #[allow(dead_code)] + struct OldPoint { + operation: String, + table_name: Option, + segments: LatencySegments, + timestamp: Instant, + } + + const N: u64 = 1_000_000; + let profile = if cfg!(debug_assertions) { + "debug" + } else { + "release" + }; + + let old = RwLock::new(Vec::::with_capacity(256)); + let start = Instant::now(); + for i in 0..N { + #[allow(clippy::cast_possible_truncation)] + let op = OPS[(i % 5) as usize]; + let point = OldPoint { + operation: op.to_owned(), + table_name: Some("T".to_owned()), + segments: segs(1.0), + timestamp: Instant::now(), + }; + if let Ok(mut v) = old.write() { + v.push(point); + } + } + let old_ns = start.elapsed().as_nanos() / u128::from(N); + let old_bytes = old + .read() + .map_or(0, |v| v.capacity() * std::mem::size_of::()); + + let new = RwLock::new(SegmentStore::new(Instant::now())); + let start = Instant::now(); + for i in 0..N { + #[allow(clippy::cast_possible_truncation)] + let op = OPS[(i % 5) as usize]; + if let Ok(mut s) = new.write() { + s.record(op, &segs(1.0), Instant::now()); + } + } + let new_ns = start.elapsed().as_nanos() / u128::from(N); + let new_bytes = new + .read() + .map_or(0, |s| s.bucket_count() * SegmentStore::bucket_size()); + + // Read path: the old query_segments loop over every point, versus the store. + let start = Instant::now(); + let mut by_op: std::collections::HashMap = std::collections::HashMap::new(); + if let Ok(v) = old.read() { + for p in v.iter() { + let e = by_op.entry(p.operation.clone()).or_default(); + e.0 += p.segments.total_us; + e.1 += 1; + } + } + let old_query_us = start.elapsed().as_micros(); + let start = Instant::now(); + let out = new + .read() + .map(|s| s.query(TimeWindow::AllTime, Instant::now())) + .unwrap_or_default(); + let new_query_us = start.elapsed().as_micros(); + + println!( + "bench[{profile}] record: old push {old_ns} ns/call, new record {new_ns} ns/call; \ + memory after {N} calls: old {old_bytes} B (Vec capacity, Strings excluded), new {new_bytes} B; \ + query over {N} points: old {old_query_us} us ({} ops), new {new_query_us} us ({} ops)", + by_op.len(), + out.len() + ); +} diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 5a5a5f51c..b17c4acce 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -304,8 +304,7 @@ pub(crate) async fn handle_request( state.metrics.record_request_count(&operation); state.metrics.record_segments( &operation, - table_name.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 37e2529b6..3804c0aa8 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -341,6 +341,14 @@ schema that uses DynamoDB CloudWatch-style metric names and dimensions. (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 per-operation time buckets + (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 memory does not grow with 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. The table is + not a dimension of this breakdown. Operations with no request in the window + are omitted; results are sorted by operation name. - `source`: `"database"` when served from the persistent `MetricsStore`, `"memory"` when served from the in-process `MetricsCollector` fallback. diff --git a/docs/manuals/11-deployment-guide.md b/docs/manuals/11-deployment-guide.md index fb03c271b..a494753a9 100755 --- a/docs/manuals/11-deployment-guide.md +++ b/docs/manuals/11-deployment-guide.md @@ -269,6 +269,33 @@ FROM pg_stat_statements WHERE usename = 'extenddb' ORDER BY mean_exec_time DESC LIMIT 10; ``` +### Process Memory + +The server's resident memory 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 (for example six 40-byte points per GetItem, held for 60 to 120 seconds) +and not with uptime, and per-operation latency segments are summed into fixed +time buckets, at most about 110 KB per operation. + +Releases through 0.1.13 kept one latency segment record per data-plane +request in memory for 24 hours, about 190 bytes per request. On those +releases resident memory grows for the first 24 hours and then holds at the +level set by the busiest 24-hour window the process has seen; 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 + 190 bytes * requests_per_24h * 1.3 +``` + +where 1.3 is a modelled allowance for allocator overhead, not a measured +figure (274 requests per second is 23.7 million requests per day and about +5.5 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 3d9abdb12..a686d6b37 100755 --- a/docs/todo-index.md +++ b/docs/todo-index.md @@ -14,7 +14,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) From 6fe3bda37363708445e976efbfa88d749faa1aa2 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:58:55 +0000 Subject: [PATCH 02/22] test(metrics): check the segment store's account key Main filters the latency segments by account, so the bucket store has two keys: the account, then the operation. The bound test records under three accounts and expects accounts x operations x 1,742 buckets. The random workload test gives each point an account. It checks the answer without a filter against every account's points, and the answer with each account's filter against that account's points. The sort test checks that an account that sent nothing reads empty. --- crates/core/src/metrics/segments_tests.rs | 201 ++++++++++++++-------- 1 file changed, 126 insertions(+), 75 deletions(-) diff --git a/crates/core/src/metrics/segments_tests.rs b/crates/core/src/metrics/segments_tests.rs index e2d0ca0ed..6e3a7b112 100644 --- a/crates/core/src/metrics/segments_tests.rs +++ b/crates/core/src/metrics/segments_tests.rs @@ -9,6 +9,7 @@ use super::*; const OPS: [&str; 5] = ["GetItem", "PutItem", "Query", "Scan", "UpdateItem"]; const ACCOUNT: &str = "111111111111"; +const ACCOUNTS: [&str; 3] = ["111111111111", "222222222222", "333333333333"]; fn segs(v: f64) -> LatencySegments { LatencySegments { @@ -63,21 +64,25 @@ fn boundedness_five_million_records() { 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. 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); + store.record(account, op, &segs(1.0), now); } - let bound = OPS.len() * BUCKETS_PER_OPERATION; - assert_eq!(store.ring_pair_count(), OPS.len()); + let bound = ACCOUNTS.len() * OPS.len() * BUCKETS_PER_OPERATION; + assert_eq!(store.ring_pair_count(), ACCOUNTS.len() * OPS.len()); assert!( store.bucket_count() <= bound, "bucket count {} exceeds bound {bound}", store.bucket_count() ); assert!(store.bucket_count() * SegmentStore::bucket_size() <= bound * 64); - // The rings are allocated once per operation, so the bound is also exact. + // The rings are allocated once per account and operation, so the bound + // is also exact. assert_eq!(store.bucket_count(), bound); // The whole-ring query still answers, with at most 1441 minutes of data. let now = epoch + Duration::from_millis(total * 52); @@ -86,28 +91,51 @@ fn boundedness_five_million_records() { assert!(in_day > 0 && in_day <= 86_460_000 / 52 + OPS.len() as u64); } +/// One request of the random workload: the index of its account, the index +/// of its operation, its time in milliseconds after the epoch and its +/// segments. +struct Point { + account: usize, + op: usize, + t_ms: u64, + segs: LatencySegments, +} + /// 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. +/// 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. #[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, u64, LatencySegments)> = Vec::new(); + let mut points: Vec = 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(ACCOUNT, OPS[op], &s, epoch + Duration::from_millis(t_ms)); - points.push((op, t_ms, s)); + let segs = segs(v); + store.record( + ACCOUNTS[account], + OPS[op], + &segs, + epoch + Duration::from_millis(t_ms), + ); + points.push(Point { + account, + op, + t_ms, + segs, + }); } let windows = [ (TimeWindow::LastMinute, 60, 1), @@ -115,83 +143,100 @@ fn random_workload_matches_naive_reference() { (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 out = store.query(window, None, now); let first_slot = now_secs.saturating_sub(w) / b; - for (i, op) in OPS.iter().enumerate() { - let mut count = 0u64; - let mut sum = LatencySegments::default(); - let mut exact_w = 0u64; - let mut exact_w_plus_b = 0u64; - for (p_op, p_ms, s) in &points { - if *p_op != i { - 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(), - "{op} {window:?} at {now_ms}: expected absent" - ); - continue; - } - let got = got.unwrap_or_else(|| panic!("{op} {window:?} at {now_ms}: missing")); - assert_eq!(got.count, count, "{op} {window:?} at {now_ms}: count"); - assert!( - exact_w <= count && count <= exact_w_plus_b, - "{op} {window:?} at {now_ms}: {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), - "{op} {window:?} auth" - ); - assert!( - close(got.avg.authz_us, sum.authz_us / c), - "{op} {window:?} authz" - ); - assert!( - close(got.avg.throttle_us, sum.throttle_us / c), - "{op} {window:?} throttle" - ); - assert!( - close(got.avg.dispatch_us, sum.dispatch_us / c), - "{op} {window:?} dispatch" - ); - assert!( - close(got.avg.response_us, sum.response_us / c), - "{op} {window:?} response" - ); - assert!( - close(got.avg.total_us, sum.total_us / c), - "{op} {window:?} total" + for account in filters { + let out = store.query(window, account.map(|a| ACCOUNTS[a]), now); + assert_matches_reference( + &out, + &points, + account, + (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 `account` (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. +fn assert_matches_reference( + out: &[OperationSegments], + points: &[Point], + account: 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, account filter {}", + account.map_or("none", |a| ACCOUNTS[a]) + ); + let mut count = 0u64; + let mut sum = LatencySegments::default(); + let mut exact_w = 0u64; + let mut exact_w_plus_b = 0u64; + for p in points { + if p.op != i || account.is_some_and(|a| p.account != a) { + continue; + } + if p.t_ms + w * 1000 >= now_ms { + exact_w += 1; + } + if p.t_ms + (w + b) * 1000 >= now_ms { + exact_w_plus_b += 1; + } + if (p.t_ms / 1000) / b >= first_slot { + count += 1; + sum.auth_us += p.segs.auth_us; + sum.authz_us += p.segs.authz_us; + sum.throttle_us += p.segs.throttle_us; + sum.dispatch_us += p.segs.dispatch_us; + sum.response_us += p.segs.response_us; + sum.total_us += p.segs.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. @@ -449,6 +494,12 @@ fn operations_sorted_and_zero_count_absent() { 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() + ); } /// Write-path and read-path cost of the previous one-point-per-request From 48768ee34ec0ad549b01d89bf19c69e3817d2dfb Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:59:01 +0000 Subject: [PATCH 03/22] docs(metrics): state the latency segment bound per account Main filters the latency segments by account, so the bucket store has two keys, the account and the operation, and its bound is per account. The metrics section of the server design doc and the process memory section of the deployment guide now give the bound. It is accounts x operations x 111,488 bytes. With the 40 operations the server dispatches that is 4,459,520 bytes (4.25 MiB) for each account that sends a request. The bound grows with the accounts that send requests and not with the request rate, the table count or uptime. The metrics module doc names the account key. --- crates/core/src/metrics/mod.rs | 6 +++--- docs/design/06-component-server.md | 21 +++++++++++++++------ docs/manuals/11-deployment-guide.md | 6 +++++- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/crates/core/src/metrics/mod.rs b/crates/core/src/metrics/mod.rs index e5c19e8bd..65abc8bda 100755 --- a/crates/core/src/metrics/mod.rs +++ b/crates/core/src/metrics/mod.rs @@ -6,9 +6,9 @@ //! 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. Per-operation latency segments are summed into fixed -//! time buckets at record time (see `segments`), so they hold a bounded amount -//! of memory and need no pruning. +//! 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 and need no pruning. //! //! REQ-OBS-005: Metrics endpoint. diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index 548747c45..a3ba01a78 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -346,14 +346,23 @@ 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 per-operation time buckets - (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 + 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 memory does not grow with 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. The table is - not a dimension of this breakdown. Operations with no request in the window - are omitted; results are sorted by operation name. + 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 301 one-second and 1,441 one-minute buckets + of 64 bytes, 111,488 bytes, so the breakdown holds at most + `accounts x operations x 111,488` bytes: with the 40 operations the server + dispatches, 4,459,520 bytes (4.25 MiB) per account that has sent a + request. The segments are recorded only for authenticated requests, so + `accounts` is bounded by the accounts in the catalog, which operators + create. - `source`: `"database"` when served from the persistent `MetricsStore`, `"memory"` when served from the in-process `MetricsCollector` fallback. diff --git a/docs/manuals/11-deployment-guide.md b/docs/manuals/11-deployment-guide.md index a269fc96e..fbb0a6bd9 100755 --- a/docs/manuals/11-deployment-guide.md +++ b/docs/manuals/11-deployment-guide.md @@ -366,7 +366,11 @@ 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 (for example six 40-byte points per GetItem, held for 60 to 120 seconds) and not with uptime, and per-operation latency segments are summed into fixed -time buckets, at most about 110 KB per operation. +time buckets per account and operation, at most 111,488 bytes (109 KiB) +per operation an account has sent. With the 40 operations the server +dispatches that is 4,459,520 bytes (4.25 MiB) per account, so the +segments grow with the number of accounts that send requests, which the +operator controls, and not with the request rate, the table count or uptime. Releases through 0.1.13 kept one latency segment record per data-plane request in memory for 24 hours, about 190 bytes per request. On those From a43ef7e2260fc90a4552b507a2d481cc96d73ad4 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:28:29 +0000 Subject: [PATCH 04/22] fix(metrics): drop the segment rings of an account idle for a day The segment store allocated the rings of an account's operation on its first request and kept them until restart. An account that stopped sending requests, or that an operator deleted, held 111,488 bytes per operation for the life of the process. Main's prune dropped such an account's segment points after a day. The metrics prune runs every five minutes. It now drops the rings of an account's operation once the coarse ring's whole-ring window holds no bucket of theirs. It drops the account once it holds no operation. The check reuses the ring's first slot and bucket sum. The fine ring's windows lie inside the coarse ring's, so no query answer changes. The bound in the module doc, the server design doc and the deployment guide counts the accounts that sent a request in the last day. A new store test records under two accounts and prunes at 1440 and 1441 minutes. The idle account goes at 1441 minutes with its two operations. The active account keeps its ring and its data. The idle account's next request allocates its rings again. --- crates/core/src/metrics/collector.rs | 11 ++++- crates/core/src/metrics/collector_tests.rs | 2 +- crates/core/src/metrics/mod.rs | 3 +- crates/core/src/metrics/segments.rs | 28 ++++++++++-- crates/core/src/metrics/segments_tests.rs | 50 ++++++++++++++++++++++ docs/design/06-component-server.md | 10 +++-- docs/manuals/11-deployment-guide.md | 8 ++-- 7 files changed, 98 insertions(+), 14 deletions(-) diff --git a/crates/core/src/metrics/collector.rs b/crates/core/src/metrics/collector.rs index 2d1fe59ae..b5eadfde5 100755 --- a/crates/core/src/metrics/collector.rs +++ b/crates/core/src/metrics/collector.rs @@ -125,8 +125,10 @@ impl MetricsCollector { /// Prune data points older than 1 day. /// - /// Segment buckets are overwritten in place as time advances and need no - /// pruning. + /// Segment buckets inside the window are overwritten in place as time + /// advances; the prune drops the rings of an account's operation once no + /// bucket of the last day remains, so an account that stopped sending + /// requests, or was deleted, holds no segment memory after a day. pub fn prune(&self) { let now = Instant::now(); let cutoff = now.checked_sub(Duration::from_secs(86400)).unwrap_or(now); @@ -137,6 +139,11 @@ impl MetricsCollector { acc.prune(cutoff); } map.retain(|_, acc| !acc.is_empty()); + drop(map); + // Clock read under the lock, as in `record_segments`. + if let Ok(mut store) = self.segments.write() { + store.prune(Instant::now()); + } } } diff --git a/crates/core/src/metrics/collector_tests.rs b/crates/core/src/metrics/collector_tests.rs index 7268ba724..8a20f5858 100755 --- a/crates/core/src/metrics/collector_tests.rs +++ b/crates/core/src/metrics/collector_tests.rs @@ -196,7 +196,7 @@ fn record_and_query_segments() { } #[test] -fn prune_leaves_segments_alone_and_the_ring_ages_them_out() { +fn prune_keeps_recent_segments_and_the_ring_ages_them_out() { use crate::metrics::types::LatencySegments; use std::time::Duration; diff --git a/crates/core/src/metrics/mod.rs b/crates/core/src/metrics/mod.rs index 65abc8bda..d20eb205e 100755 --- a/crates/core/src/metrics/mod.rs +++ b/crates/core/src/metrics/mod.rs @@ -8,7 +8,8 @@ //! of per-key accumulators. A background task prunes data points older than //! 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 and need no pruning. +//! 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. diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs index 4f5eabd8e..ab6071c36 100644 --- a/crates/core/src/metrics/segments.rs +++ b/crates/core/src/metrics/segments.rs @@ -14,8 +14,11 @@ //! `accounts * operations * (FINE_SLOTS + COARSE_SLOTS) * 64` bytes. 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 authenticated, so `accounts` is the number of accounts in the catalog -//! that sent a request, which operators create. +//! that authenticated. `accounts` is the number of accounts that sent a +//! request within the coarse ring's window, the last 1,440 to 1,441 minutes: +//! the collector's prune, every five minutes, drops the rings of an account's +//! operation once that window holds no bucket of theirs, 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. @@ -204,7 +207,8 @@ impl SegmentStore { /// Adds one request of `account_id`. Steady state is two hash lookups and /// two bucket updates; the only allocation is the rings of an account's - /// operation seen for the first time. + /// operation that has none, because it is the first request or because + /// `prune` dropped them. pub(super) fn record( &mut self, account_id: &str, @@ -277,6 +281,24 @@ impl SegmentStore { .collect() } + /// Drops the rings of each account's operation whose coarse ring holds no + /// bucket of 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. + 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 mut in_window = Bucket::default(); + ring.sum_from(ring.first_slot(elapsed, None), &mut in_window); + in_window.count > 0 + }); + !operations.is_empty() + }); + } + /// Number of (account, operation) pairs with rings allocated. #[cfg(test)] pub(super) fn ring_pair_count(&self) -> usize { diff --git a/crates/core/src/metrics/segments_tests.rs b/crates/core/src/metrics/segments_tests.rs index 6e3a7b112..496459be5 100644 --- a/crates/core/src/metrics/segments_tests.rs +++ b/crates/core/src/metrics/segments_tests.rs @@ -371,6 +371,56 @@ fn ring_lap_and_stale_slots() { assert_eq!(store.bucket_count(), BUCKETS_PER_OPERATION); } +/// The prune drops the rings of an account's operation once the coarse ring's +/// whole-ring window holds no bucket of theirs, 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)); + assert_eq!(store.bucket_count(), 3 * BUCKETS_PER_OPERATION); + + // 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.bucket_count(), 3 * BUCKETS_PER_OPERATION); + 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 other 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.bucket_count(), BUCKETS_PER_OPERATION); + 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.bucket_count(), 2 * BUCKETS_PER_OPERATION); +} + /// 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 diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index a3ba01a78..098c53844 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -359,10 +359,12 @@ ExtendDB's own `AccountId` dimension. Each account's operation holds 301 one-second and 1,441 one-minute buckets of 64 bytes, 111,488 bytes, so the breakdown holds at most `accounts x operations x 111,488` bytes: with the 40 operations the server - dispatches, 4,459,520 bytes (4.25 MiB) per account that has sent a - request. The segments are recorded only for authenticated requests, so - `accounts` is bounded by the accounts in the catalog, which operators - create. + dispatches, 4,459,520 bytes (4.25 MiB) per account. `accounts` counts the + accounts that sent a request in the last day (the 24-hour ring, 1,440 to + 1,441 minutes): the metrics prune, every five minutes, drops the buckets of + an account's operation once that window holds none of its requests, and the + account once it holds no operation. The segments are recorded only for + authenticated requests. - `source`: `"database"` when served from the persistent `MetricsStore`, `"memory"` when served from the in-process `MetricsCollector` fallback. diff --git a/docs/manuals/11-deployment-guide.md b/docs/manuals/11-deployment-guide.md index fbb0a6bd9..49d5e4ed6 100755 --- a/docs/manuals/11-deployment-guide.md +++ b/docs/manuals/11-deployment-guide.md @@ -368,9 +368,11 @@ rate (for example six 40-byte points per GetItem, held for 60 to 120 seconds) and not with uptime, and per-operation latency segments are summed into fixed time buckets per account and operation, at most 111,488 bytes (109 KiB) per operation an account has sent. With the 40 operations the server -dispatches that is 4,459,520 bytes (4.25 MiB) per account, so the -segments grow with the number of accounts that send requests, which the -operator controls, and not with the request rate, the table count or uptime. +dispatches that is 4,459,520 bytes (4.25 MiB) per account that sent a +request in the last day: the five-minute metrics prune drops the buckets of +an account that has sent no request for a day. So the segments grow with the +number of accounts that sent a request in the last day, and not with the +request rate, the table count or uptime. Releases through 0.1.13 kept one latency segment record per data-plane request in memory for 24 hours, about 190 bytes per request. On those From b276bd5111648c5a9ed75078491d4773c4bb54cd Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:30:04 +0000 Subject: [PATCH 05/22] refactor(metrics): apply the empty account rule in the segment store query_segments turned an empty account filter into no filter before it read the store, and its test twin query_segments_at did not. The rule now lives in SegmentStore::query, so both readers share one copy and answer alike. --- crates/core/src/metrics/collector_query.rs | 1 - crates/core/src/metrics/segments.rs | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/core/src/metrics/collector_query.rs b/crates/core/src/metrics/collector_query.rs index ec010d54c..4c2428edd 100755 --- a/crates/core/src/metrics/collector_query.rs +++ b/crates/core/src/metrics/collector_query.rs @@ -162,7 +162,6 @@ impl MetricsCollector { window: TimeWindow, account_id: Option<&str>, ) -> Vec { - let account_id = account_id.filter(|a| !a.is_empty()); // Clock read under the lock, paired with `record_segments`. let Ok(store) = self.segments.read() else { return Vec::new(); diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs index ab6071c36..977d5bd05 100644 --- a/crates/core/src/metrics/segments.rs +++ b/crates/core/src/metrics/segments.rs @@ -234,7 +234,8 @@ impl SegmentStore { } /// Per-operation count and mean segments over `window`, sorted by - /// operation name: the requests of `account_id` when it is given, every + /// 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. /// @@ -246,6 +247,7 @@ impl SegmentStore { 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(); From e9567da67094d2e6e55904da561ae5a614c8394f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:30:47 +0000 Subject: [PATCH 06/22] test(metrics): name the accounts in the bound test's comment The bound test records under three accounts and five operations and asserts the bucket count of every pair. Its comment named the operations only. --- crates/core/src/metrics/segments_tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/core/src/metrics/segments_tests.rs b/crates/core/src/metrics/segments_tests.rs index 496459be5..9520feef1 100644 --- a/crates/core/src/metrics/segments_tests.rs +++ b/crates/core/src/metrics/segments_tests.rs @@ -56,8 +56,9 @@ fn bucket_is_64_bytes() { assert_eq!(BUCKETS_PER_OPERATION, 1742); } -/// Issue #397: five million requests over three simulated days across five -/// operations allocate exactly the fixed rings and nothing per request. +/// Issue #397: five million requests over three simulated days across three +/// accounts and five operations allocate exactly the fixed rings and nothing +/// per request. #[test] fn boundedness_five_million_records() { let epoch = Instant::now(); From 9b6bff13cea0b4346293f6e14ef6b3fdf6827d78 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:41:14 +0000 Subject: [PATCH 07/22] test(metrics): trim the segment store tests The bound test asserted the number of ring pairs through a test-only accessor and then asserted the exact bucket count. Each pair holds exactly 1,742 buckets, so the bucket count fixes the pair count. The accessor and its assertion go. The random workload test described a point with a four-field struct. It is a four-tuple again, destructured as the three-tuple was before the account joined it. The single-account constant equalled the first entry of the account list and goes. Every assertion keeps its meaning. --- crates/core/src/metrics/segments.rs | 6 -- crates/core/src/metrics/segments_tests.rs | 70 +++++++++-------------- 2 files changed, 27 insertions(+), 49 deletions(-) diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs index 977d5bd05..536f2659a 100644 --- a/crates/core/src/metrics/segments.rs +++ b/crates/core/src/metrics/segments.rs @@ -301,12 +301,6 @@ impl SegmentStore { }); } - /// Number of (account, operation) pairs with rings allocated. - #[cfg(test)] - pub(super) fn ring_pair_count(&self) -> usize { - self.by_account.values().map(HashMap::len).sum() - } - /// Number of buckets allocated, the quantity the memory bound is stated in. #[cfg(test)] pub(super) fn bucket_count(&self) -> usize { diff --git a/crates/core/src/metrics/segments_tests.rs b/crates/core/src/metrics/segments_tests.rs index 9520feef1..e4aa307fd 100644 --- a/crates/core/src/metrics/segments_tests.rs +++ b/crates/core/src/metrics/segments_tests.rs @@ -8,7 +8,6 @@ use std::time::{Duration, Instant}; use super::*; const OPS: [&str; 5] = ["GetItem", "PutItem", "Query", "Scan", "UpdateItem"]; -const ACCOUNT: &str = "111111111111"; const ACCOUNTS: [&str; 3] = ["111111111111", "222222222222", "333333333333"]; fn segs(v: f64) -> LatencySegments { @@ -75,7 +74,6 @@ fn boundedness_five_million_records() { store.record(account, op, &segs(1.0), now); } let bound = ACCOUNTS.len() * OPS.len() * BUCKETS_PER_OPERATION; - assert_eq!(store.ring_pair_count(), ACCOUNTS.len() * OPS.len()); assert!( store.bucket_count() <= bound, "bucket count {} exceeds bound {bound}", @@ -92,27 +90,18 @@ fn boundedness_five_million_records() { assert!(in_day > 0 && in_day <= 86_460_000 / 52 + OPS.len() as u64); } -/// One request of the random workload: the index of its account, the index -/// of its operation, its time in milliseconds after the epoch and its -/// segments. -struct Point { - account: usize, - op: usize, - t_ms: u64, - segs: LatencySegments, -} - /// 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 = Vec::new(); + 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. @@ -124,19 +113,14 @@ fn random_workload_matches_naive_reference() { 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 segs = segs(v); + let s = segs(v); store.record( ACCOUNTS[account], OPS[op], - &segs, + &s, epoch + Duration::from_millis(t_ms), ); - points.push(Point { - account, - op, - t_ms, - segs, - }); + points.push((account, op, t_ms, s)); } let windows = [ (TimeWindow::LastMinute, 60, 1), @@ -171,7 +155,7 @@ fn random_workload_matches_naive_reference() { /// count lies between the exact `w` and `w + b` second windows. fn assert_matches_reference( out: &[OperationSegments], - points: &[Point], + points: &[(usize, usize, u64, LatencySegments)], account: Option, (window, w, b): (TimeWindow, u64, u64), now_ms: u64, @@ -186,24 +170,24 @@ fn assert_matches_reference( let mut sum = LatencySegments::default(); let mut exact_w = 0u64; let mut exact_w_plus_b = 0u64; - for p in points { - if p.op != i || account.is_some_and(|a| p.account != a) { + for (p_account, p_op, p_ms, s) in points { + if *p_op != i || account.is_some_and(|a| *p_account != a) { continue; } - if p.t_ms + w * 1000 >= now_ms { + if *p_ms + w * 1000 >= now_ms { exact_w += 1; } - if p.t_ms + (w + b) * 1000 >= now_ms { + if *p_ms + (w + b) * 1000 >= now_ms { exact_w_plus_b += 1; } - if (p.t_ms / 1000) / b >= first_slot { + if (*p_ms / 1000) / b >= first_slot { count += 1; - sum.auth_us += p.segs.auth_us; - sum.authz_us += p.segs.authz_us; - sum.throttle_us += p.segs.throttle_us; - sum.dispatch_us += p.segs.dispatch_us; - sum.response_us += p.segs.response_us; - sum.total_us += p.segs.total_us; + 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); @@ -246,7 +230,7 @@ fn window_filter_at_minute_boundary() { let epoch = Instant::now(); let mut store = SegmentStore::new(epoch); for t in [0, 59, 60] { - store.record(ACCOUNT, "GetItem", &segs(1.0), at(epoch, t)); + 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!( @@ -264,7 +248,7 @@ fn window_filter_at_minute_boundary() { 1 ); // 3659 s: cutoff 59 s lies in minute 0, so minute 0 is included. - store.record(ACCOUNT, "GetItem", &segs(1.0), at(epoch, 3659)); + store.record(ACCOUNTS[0], "GetItem", &segs(1.0), at(epoch, 3659)); assert_eq!( count_of( &store.query(TimeWindow::LastHour, None, at(epoch, 3659)), @@ -290,7 +274,7 @@ 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(ACCOUNT, "Query", &segs(1.0), at(epoch, t)); + store.record(ACCOUNTS[0], "Query", &segs(1.0), at(epoch, t)); } // 301 s: cutoff 1 s, buckets 1, 2, 300, 301. assert_eq!( @@ -337,7 +321,7 @@ fn fine_windows_cut_at_the_second() { fn ring_lap_and_stale_slots() { let epoch = Instant::now(); let mut store = SegmentStore::new(epoch); - store.record(ACCOUNT, "Scan", &segs(1.0), at(epoch, 0)); + 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( @@ -365,7 +349,7 @@ fn ring_lap_and_stale_slots() { .is_empty() ); // A record one full lap later lands on position 0 and resets it. - store.record(ACCOUNT, "Scan", &segs(5.0), at(epoch, 1441 * 60)); + 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); @@ -489,7 +473,7 @@ fn continuous_load_three_coarse_laps_exact_count_and_mean() { #[allow(clippy::cast_precision_loss)] let v = t as f64; store.record( - ACCOUNT, + ACCOUNTS[0], "Scan", &LatencySegments { auth_us: v, @@ -536,9 +520,9 @@ fn continuous_load_three_coarse_laps_exact_count_and_mean() { fn operations_sorted_and_zero_count_absent() { let epoch = Instant::now(); let mut store = SegmentStore::new(epoch); - store.record(ACCOUNT, "Scan", &segs(1.0), at(epoch, 10)); - store.record(ACCOUNT, "GetItem", &segs(1.0), at(epoch, 10)); - store.record(ACCOUNT, "PutItem", &segs(1.0), at(epoch, 1000)); + 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"]); @@ -603,7 +587,7 @@ fn bench_old_push_vs_new_record() { #[allow(clippy::cast_possible_truncation)] let op = OPS[(i % 5) as usize]; if let Ok(mut s) = new.write() { - s.record(ACCOUNT, op, &segs(1.0), Instant::now()); + s.record(ACCOUNTS[0], op, &segs(1.0), Instant::now()); } } let new_ns = start.elapsed().as_nanos() / u128::from(N); From 0c3a1d03b2136405d68b5c780b94b26e50f25b86 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:06:04 +0000 Subject: [PATCH 08/22] test(metrics): label the segment reference check with the filter index The reference check in segments_tests.rs put the account id of its filter into the label of every assertion message. Code scanning reads an account id written to a message as cleartext logging of sensitive data, and reported two alerts on the check. The ids are test constants. The label now names the filter's index in ACCOUNTS instead, and the parameter's name is filter. No assertion changes. --- crates/core/src/metrics/segments_tests.rs | 28 +++++++++-------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/crates/core/src/metrics/segments_tests.rs b/crates/core/src/metrics/segments_tests.rs index e4aa307fd..545bfeae5 100644 --- a/crates/core/src/metrics/segments_tests.rs +++ b/crates/core/src/metrics/segments_tests.rs @@ -134,44 +134,38 @@ fn random_workload_matches_naive_reference() { let now_secs = now_ms / 1000; for (window, w, b) in windows { let first_slot = now_secs.saturating_sub(w) / b; - for account in filters { - let out = store.query(window, account.map(|a| ACCOUNTS[a]), now); - assert_matches_reference( - &out, - &points, - account, - (window, w, b), - now_ms, - first_slot, - ); + 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 `account` (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. +/// `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)], - account: Option, + 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, account filter {}", - account.map_or("none", |a| ACCOUNTS[a]) + "{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 || account.is_some_and(|a| *p_account != a) { + if *p_op != i || filter.is_some_and(|a| *p_account != a) { continue; } if *p_ms + w * 1000 >= now_ms { From 2e5e0474ed6d5ad55eeb295b35c713716306a027 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:03:27 +0000 Subject: [PATCH 09/22] fix(metrics): hold only the segment buckets that had a request A ring now holds only the buckets of the slots that had a request, in slot order. A record first drops the buckets outside the ring's window, then adds its own. The deque grows by doubling up to the ring length and no further. So a pair that sends a request every second still holds at most 1,742 buckets, 111,488 bytes. A pair with one request a day holds two buckets. Before this change the first request of an (account, operation) pair allocated both rings in full. On a release build with a counting allocator, 1,000 accounts x 40 operations with one request each held 4,464,933,520 bytes. Main holds 9,922,080 bytes for the same requests. With this change the same store holds 13,605,520 bytes, 340 per pair. On that store the unfiltered Last5Minutes query held the read lock between 76.7 and 80.5 milliseconds. The prune held the write lock between 187.9 and 201.3 milliseconds. Both read every slot of every ring. The query now finds the window's first slot with a binary search and reads from there (5.2 to 12.2 milliseconds). The filtered query looks the account up instead of scanning the map. The prune compares one slot per pair (0.27 to 1.19 milliseconds). The collector's prune is now `prune_at(now)` behind `prune()`. The record and query paths take their clock through `record_segments_with` and `query_segments_with`. Tests can therefore run the production prune at a chosen time and check that the clock runs inside the lock. Before this change, a no-op segment prune and a clock read before the lock both passed every test. --- crates/core/src/metrics/collector.rs | 41 ++++-- crates/core/src/metrics/collector_query.rs | 19 ++- crates/core/src/metrics/collector_tests.rs | 44 ++++++- crates/core/src/metrics/segments.rs | 137 +++++++++++++-------- crates/core/src/metrics/segments_tests.rs | 131 +++++++++++++++++--- 5 files changed, 281 insertions(+), 91 deletions(-) diff --git a/crates/core/src/metrics/collector.rs b/crates/core/src/metrics/collector.rs index b5eadfde5..f76a69605 100755 --- a/crates/core/src/metrics/collector.rs +++ b/crates/core/src/metrics/collector.rs @@ -112,25 +112,41 @@ impl MetricsCollector { /// 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) { - // 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 overwrite the oldest in-window bucket before a reader with an - // earlier clock reads it. + 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, + segments: &LatencySegments, + clock: impl FnOnce() -> Instant, + ) { let Ok(mut store) = self.segments.write() else { return; }; - store.record(account_id, operation, segments, Instant::now()); + store.record(account_id, operation, segments, clock()); } /// Prune data points older than 1 day. /// - /// Segment buckets inside the window are overwritten in place as time - /// advances; the prune drops the rings of an account's operation once no - /// bucket of the last day remains, so an account that stopped sending - /// requests, or was deleted, holds no segment memory after a 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; @@ -140,9 +156,8 @@ impl MetricsCollector { } map.retain(|_, acc| !acc.is_empty()); drop(map); - // Clock read under the lock, as in `record_segments`. if let Ok(mut store) = self.segments.write() { - store.prune(Instant::now()); + store.prune(now); } } } diff --git a/crates/core/src/metrics/collector_query.rs b/crates/core/src/metrics/collector_query.rs index 4c2428edd..dd5083787 100755 --- a/crates/core/src/metrics/collector_query.rs +++ b/crates/core/src/metrics/collector_query.rs @@ -162,11 +162,21 @@ impl MetricsCollector { window: TimeWindow, account_id: Option<&str>, ) -> Vec { - // Clock read under the lock, paired with `record_segments`. + 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(); }; - store.query(window, account_id, Instant::now()) + store.query(window, account_id, clock()) } /// `query_segments` with an injected clock, for tests. @@ -177,10 +187,7 @@ impl MetricsCollector { account_id: Option<&str>, now: Instant, ) -> Vec { - let Ok(store) = self.segments.read() else { - return Vec::new(); - }; - store.query(window, account_id, now) + self.query_segments_with(window, account_id, || now) } } diff --git a/crates/core/src/metrics/collector_tests.rs b/crates/core/src/metrics/collector_tests.rs index 8a20f5858..e70fb637a 100755 --- a/crates/core/src/metrics/collector_tests.rs +++ b/crates/core/src/metrics/collector_tests.rs @@ -196,7 +196,7 @@ fn record_and_query_segments() { } #[test] -fn prune_keeps_recent_segments_and_the_ring_ages_them_out() { +fn prune_keeps_recent_segments_and_drops_them_a_day_later() { use crate::metrics::types::LatencySegments; use std::time::Duration; @@ -233,6 +233,48 @@ fn prune_keeps_recent_segments_and_the_ring_ages_them_out() { c.query_segments_at(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(|s| s.bucket_count()) + .unwrap_or(usize::MAX) + }; + 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] diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs index 536f2659a..3733dba96 100644 --- a/crates/core/src/metrics/segments.rs +++ b/crates/core/src/metrics/segments.rs @@ -6,19 +6,24 @@ //! 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 fixed rings of buckets, one of 1-second +//! 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, -//! and is overwritten in place when its ring position comes around again, so -//! the memory per process is at most -//! `accounts * operations * (FINE_SLOTS + COARSE_SLOTS) * 64` bytes. 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 authenticated. `accounts` is the number of accounts that sent a -//! request within the coarse ring's window, the last 1,440 to 1,441 minutes: -//! the collector's prune, every five minutes, drops the rings of an account's -//! operation once that window holds no bucket of theirs, and the account once -//! it holds no operation. +//! 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 +//! memory per process is therefore at most +//! `accounts * operations * (FINE_SLOTS + COARSE_SLOTS) * 64` bytes of +//! buckets, reached only by a pair 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 within the coarse ring's window, +//! the last 1,440 to 1,441 minutes: the collector's prune, every five minutes, +//! drops the rings of an account's operation once its newest bucket has left +//! that 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. @@ -26,7 +31,7 @@ //! Issue #397: one `SegmentPoint` per request grew to about 4.3 GiB in a day at //! 274 requests per second. -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, VecDeque}; use std::time::Instant; use super::types::{LatencySegments, OperationSegments, TimeWindow}; @@ -83,55 +88,75 @@ impl Bucket { } } -/// A fixed ring of buckets. Slot `k` covers elapsed seconds -/// `[k * width, (k + 1) * width)` and lives at position `k % len`. +/// 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, - buckets: Box<[Bucket]>, + /// Most buckets held, and the capacity the deque grows to and no further. + len: usize, + buckets: VecDeque, } impl Ring { - fn new(width_secs: u64, slots: usize) -> Self { + fn new(width_secs: u64, len: usize) -> Self { Self { width_secs, - buckets: vec![Bucket::default(); slots].into_boxed_slice(), + len, + buckets: VecDeque::new(), } } fn slots(&self) -> u64 { - self.buckets.len() as 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; - #[allow(clippy::cast_possible_truncation)] // slot % len < len <= usize::MAX - let position = (slot % self.slots()) as usize; - let bucket = &mut self.buckets[position]; - if bucket.slot < slot { - // The position comes around again: drop what the previous lap left. - *bucket = Bucket { - slot, - ..Bucket::default() - }; + 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(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)); } - // `bucket.slot > slot` means this record lags the newest one by a full - // ring, which monotonic time rules out; it is counted where it lands. + let mut bucket = Bucket { + slot, + ..Bucket::default() + }; bucket.add(segments); + self.buckets.push_back(bucket); } /// Sums every bucket whose slot is at or after `first_slot` into `acc`. - /// Slots left over from an earlier lap are older than `first_slot` for - /// every window this ring serves, so no separate staleness check is needed. + /// The buckets are in slot order, so this reads only the window's slots. fn sum_from(&self, first_slot: u64, acc: &mut Bucket) { - for b in &self.buckets { - if b.slot >= first_slot && b.count > 0 { - acc.add_bucket(b); - } + let start = self.buckets.partition_point(|b| b.slot < first_slot); + for b in self.buckets.range(start..) { + acc.add_bucket(b); } } + /// Whether the newest bucket is at or after `first_slot`. + fn holds_from(&self, first_slot: u64) -> bool { + self.buckets.back().is_some_and(|b| b.slot >= first_slot) + } + /// 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 { @@ -183,7 +208,7 @@ pub(super) struct SegmentStore { 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 nothing after the first request of an + /// the borrowed names and allocates no key after the first request of an /// account's operation. by_account: HashMap>, } @@ -206,9 +231,9 @@ impl SegmentStore { } /// Adds one request of `account_id`. Steady state is two hash lookups and - /// two bucket updates; the only allocation is the rings of an account's - /// operation that has none, because it is the first request or because - /// `prune` dropped them. + /// 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, @@ -251,10 +276,10 @@ impl SegmentStore { let elapsed = self.elapsed_secs(now); let (fine, window_secs) = ring_for(window); let mut by_operation: BTreeMap<&str, Bucket> = BTreeMap::new(); - for (account, operations) in &self.by_account { - if account_id.is_some_and(|a| a != account) { - continue; - } + // 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(); @@ -283,25 +308,24 @@ impl SegmentStore { .collect() } - /// Drops the rings of each account's operation whose coarse ring holds no - /// bucket of the whole-ring window at `now`, then each account left with + /// 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. + /// 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 mut in_window = Bucket::default(); - ring.sum_from(ring.first_slot(elapsed, None), &mut in_window); - in_window.count > 0 + ring.holds_from(ring.first_slot(elapsed, None)) }); !operations.is_empty() }); } - /// Number of buckets allocated, the quantity the memory bound is stated in. + /// Number of buckets held, the quantity the memory bound is stated in. #[cfg(test)] pub(super) fn bucket_count(&self) -> usize { self.by_account @@ -311,6 +335,17 @@ impl SegmentStore { .sum() } + /// Number of buckets allocated, held or spare: the bucket memory is this + /// times [`Self::bucket_size`]. + #[cfg(test)] + pub(super) fn bucket_capacity(&self) -> usize { + self.by_account + .values() + .flat_map(HashMap::values) + .map(|r| r.fine.buckets.capacity() + r.coarse.buckets.capacity()) + .sum() + } + /// Size in bytes of one bucket, for stating the bound in bytes. #[cfg(test)] pub(super) const fn bucket_size() -> usize { diff --git a/crates/core/src/metrics/segments_tests.rs b/crates/core/src/metrics/segments_tests.rs index 545bfeae5..c1b8aa937 100644 --- a/crates/core/src/metrics/segments_tests.rs +++ b/crates/core/src/metrics/segments_tests.rs @@ -56,15 +56,15 @@ fn bucket_is_64_bytes() { } /// Issue #397: five million requests over three simulated days across three -/// accounts and five operations allocate exactly the fixed rings and nothing -/// per request. +/// 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. + // 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)] @@ -79,10 +79,11 @@ fn boundedness_five_million_records() { "bucket count {} exceeds bound {bound}", store.bucket_count() ); - assert!(store.bucket_count() * SegmentStore::bucket_size() <= bound * 64); - // The rings are allocated once per account and operation, so the bound - // is also exact. + assert!(store.bucket_capacity() * SegmentStore::bucket_size() <= bound * 64); + // Every slot of every ring had a request, so the bound is reached + // exactly, held and allocated. assert_eq!(store.bucket_count(), bound); + assert_eq!(store.bucket_capacity(), 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); @@ -308,8 +309,8 @@ fn fine_windows_cut_at_the_second() { ); } -/// A ring position that comes around again is reset for the new slot, and a -/// slot from an earlier lap that was never overwritten is excluded by the +/// 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() { @@ -331,7 +332,7 @@ fn ring_lap_and_stale_slots() { ), 1 ); - // At 1441 minutes the ring has moved past minute 0 without overwriting it. + // At 1441 minutes the ring has moved past minute 0 without a record. assert!( store .query(TimeWindow::AllTime, None, at(epoch, 86_460)) @@ -342,18 +343,19 @@ fn ring_lap_and_stale_slots() { .query(TimeWindow::LastDay, None, at(epoch, 86_460)) .is_empty() ); - // A record one full lap later lands on position 0 and resets it. + assert_eq!(store.bucket_count(), 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.bucket_count(), BUCKETS_PER_OPERATION); + assert_eq!(store.bucket_count(), 2); } -/// The prune drops the rings of an account's operation once the coarse ring's -/// whole-ring window holds no bucket of theirs, 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. +/// 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(); @@ -362,12 +364,14 @@ fn prune_drops_idle_accounts_and_keeps_active_ones() { 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)); - assert_eq!(store.bucket_count(), 3 * BUCKETS_PER_OPERATION); + // Two buckets per pair with one request, two per ring for the pair with + // requests in two seconds and two minutes. + assert_eq!(store.bucket_count(), 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.bucket_count(), 3 * BUCKETS_PER_OPERATION); + assert_eq!(store.bucket_count(), 8); assert_eq!( count_of( &store.query(TimeWindow::AllTime, None, at(epoch, 1440 * 60)), @@ -377,11 +381,11 @@ fn prune_drops_idle_accounts_and_keeps_active_ones() { ); // One minute later minute 0 has left the ring. The first account's two - // operations have no other bucket, so their rings go and the account with + // 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.bucket_count(), BUCKETS_PER_OPERATION); + assert_eq!(store.bucket_count(), 4); assert!( store .query(TimeWindow::AllTime, Some(ACCOUNTS[0]), at(epoch, 1441 * 60)) @@ -397,7 +401,94 @@ fn prune_drops_idle_accounts_and_keeps_active_ones() { // 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.bucket_count(), 2 * BUCKETS_PER_OPERATION); + assert_eq!(store.bucket_count(), 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; 5] = [ + // 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), + // 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; + assert_eq!(store.bucket_count(), pairs * buckets, "{label}: buckets"); + assert_eq!( + store.bucket_capacity(), + pairs * capacity, + "{label}: capacity" + ); + assert!( + store.bucket_capacity() <= 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"); + } } /// One request every second for three laps of the coarse ring, queried at From 03bae3541a28c0fc7b86334b282ef6a9d2f6d10b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:15:43 +0000 Subject: [PATCH 10/22] docs(metrics): state the segment memory per bucket held and the release range The deployment guide and the design doc gave the memory per (account, operation) pair as a fixed 111,488 bytes. A pair now holds a bucket only for each second and minute with a request, so the texts give 111,488 bytes as the ceiling. A pair with one request a day costs 340 bytes with its keys and map entries (counting allocator), and the texts give that too. The guide said resident memory does not grow with requests. Wrong with `throttling_enabled = true`: the throttle manager keeps a bucket per partition key it saw and never drops one. The first sentence now covers the metrics only, and the throttle growth has a sentence of its own. The guide also said the prune frees an idle account's memory. The buckets return to the allocator. The resident size can stay at its high-water mark. The text now says both. "Releases through 0.1.13" was wrong. v0.1.14, v0.1.15 and v1.0.0 all ship `segments: RwLock>`. The range is now every release through 1.0.0, plus any later one before the release with this change. The design doc said the server records segments only for authenticated requests. A request refused by authorization, throttling or the point-in-time recovery check also returns before the record, and the text now names the dispatch instead. The prune runs every five minutes, so an idle account's buckets go 1,440 to about 1,446 minutes after its last request. The doc gives that range. --- docs/design/06-component-server.md | 23 +++++++------ docs/manuals/11-deployment-guide.md | 50 ++++++++++++++++++----------- 2 files changed, 45 insertions(+), 28 deletions(-) diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index 098c53844..ba984f4ff 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -356,15 +356,20 @@ ExtendDB's own `AccountId` dimension. 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 301 one-second and 1,441 one-minute buckets - of 64 bytes, 111,488 bytes, so the breakdown holds at most - `accounts x operations x 111,488` bytes: with the 40 operations the server - dispatches, 4,459,520 bytes (4.25 MiB) per account. `accounts` counts the - accounts that sent a request in the last day (the 24-hour ring, 1,440 to - 1,441 minutes): the metrics prune, every five minutes, drops the buckets of - an account's operation once that window holds none of its requests, and the - account once it holds no operation. The segments are recorded only for - authenticated requests. + 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 about + 340 bytes per pair for its keys and map entries. 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/11-deployment-guide.md b/docs/manuals/11-deployment-guide.md index 49d5e4ed6..9a18e9643 100755 --- a/docs/manuals/11-deployment-guide.md +++ b/docs/manuals/11-deployment-guide.md @@ -361,25 +361,37 @@ ORDER BY mean_exec_time DESC LIMIT 10; ### Process Memory -The server's resident memory 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 (for example six 40-byte points per GetItem, held for 60 to 120 seconds) -and not with uptime, and per-operation latency segments are summed into fixed -time buckets per account and operation, at most 111,488 bytes (109 KiB) -per operation an account has sent. With the 40 operations the server -dispatches that is 4,459,520 bytes (4.25 MiB) per account that sent a -request in the last day: the five-minute metrics prune drops the buckets of -an account that has sent no request for a day. So the segments grow with the -number of accounts that sent a request in the last day, and not with the -request rate, the table count or uptime. - -Releases through 0.1.13 kept one latency segment record per data-plane -request in memory for 24 hours, about 190 bytes per request. On those -releases resident memory grows for the first 24 hours and then holds at the -level set by the busiest 24-hour window the process has seen; it does not -come down short of a restart. To run one of those releases until you upgrade, -size the memory limit as +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 six 40-byte points, 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, about 340 bytes with +its keys and map entries. 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 five-minute metrics prune drops the buckets of an account that sent no +request for a day. That happens 1,440 to about 1,446 minutes after its 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. They do not +grow with the request rate, the table count or uptime. With +`throttling_enabled = true` the throttle manager keeps a token bucket for every +partition key it saw and never drops one. Resident memory then grows with the +number of distinct partition keys written. + +Every release through 1.0.0 kept one latency segment record per data-plane +request in memory for 24 hours, about 190 bytes per request. So does any later +release before the one that carries this change. 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 + 190 bytes * requests_per_24h * 1.3 From 0019e590aa601b5d38fb6694c098e14e779a0042 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:47:11 +0000 Subject: [PATCH 11/22] test(metrics): query through the clock seam in the collector tests `query_segments_at(window, account, now)` only wrapped `query_segments_with(window, account, || now)`. The two tests that used it now call the seam, and the wrapper is gone. --- crates/core/src/metrics/collector_query.rs | 11 ----------- crates/core/src/metrics/collector_tests.rs | 4 ++-- 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/crates/core/src/metrics/collector_query.rs b/crates/core/src/metrics/collector_query.rs index dd5083787..52be2428d 100755 --- a/crates/core/src/metrics/collector_query.rs +++ b/crates/core/src/metrics/collector_query.rs @@ -178,17 +178,6 @@ impl MetricsCollector { }; store.query(window, account_id, clock()) } - - /// `query_segments` with an injected clock, for tests. - #[cfg(test)] - pub(super) fn query_segments_at( - &self, - window: TimeWindow, - account_id: Option<&str>, - now: Instant, - ) -> Vec { - self.query_segments_with(window, account_id, || now) - } } /// Compute percentiles from a pre-sorted slice of values. diff --git a/crates/core/src/metrics/collector_tests.rs b/crates/core/src/metrics/collector_tests.rs index e70fb637a..7b06d7a66 100755 --- a/crates/core/src/metrics/collector_tests.rs +++ b/crates/core/src/metrics/collector_tests.rs @@ -226,11 +226,11 @@ fn prune_keeps_recent_segments_and_drops_them_a_day_later() { // A day later the bucket has left the ring without any prune call. let later = epoch + Duration::from_secs(1441 * 60); assert!( - c.query_segments_at(TimeWindow::AllTime, None, later) + c.query_segments_with(TimeWindow::AllTime, None, || later) .is_empty() ); assert!( - c.query_segments_at(TimeWindow::LastDay, None, later) + c.query_segments_with(TimeWindow::LastDay, None, || later) .is_empty() ); // The buckets are still held until the collector's prune runs at that From b6d01963cfa495b2fa76c24da1c68241407ac9d1 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:52:45 +0000 Subject: [PATCH 12/22] test(metrics): move the segment bound and prune tests to their own file `segments_tests.rs` was 708 lines long. The bound, prune and memory tests and the timing comparison move unchanged to `segments_bound_tests.rs`, and the five helpers they share with the window tests become `pub(super)`. --- crates/core/src/metrics/segments.rs | 4 + .../core/src/metrics/segments_bound_tests.rs | 318 +++++++++++++++++ crates/core/src/metrics/segments_tests.rs | 322 +----------------- 3 files changed, 329 insertions(+), 315 deletions(-) create mode 100644 crates/core/src/metrics/segments_bound_tests.rs diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs index 3733dba96..a777bec4f 100644 --- a/crates/core/src/metrics/segments.rs +++ b/crates/core/src/metrics/segments.rs @@ -356,3 +356,7 @@ impl SegmentStore { #[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..04b87edf7 --- /dev/null +++ b/crates/core/src/metrics/segments_bound_tests.rs @@ -0,0 +1,318 @@ +// 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); +} + +/// Issue #397: 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; + assert!( + store.bucket_count() <= bound, + "bucket count {} exceeds bound {bound}", + store.bucket_count() + ); + assert!(store.bucket_capacity() * SegmentStore::bucket_size() <= bound * 64); + // Every slot of every ring had a request, so the bound is reached + // exactly, held and allocated. + assert_eq!(store.bucket_count(), bound); + assert_eq!(store.bucket_capacity(), 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.bucket_count(), 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.bucket_count(), 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.bucket_count(), 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.bucket_count(), 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.bucket_count(), 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.bucket_count(), 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; 5] = [ + // 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), + // 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; + assert_eq!(store.bucket_count(), pairs * buckets, "{label}: buckets"); + assert_eq!( + store.bucket_capacity(), + pairs * capacity, + "{label}: capacity" + ); + assert!( + store.bucket_capacity() <= 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"); + } +} + +/// Write-path and read-path cost of the previous one-point-per-request +/// `Vec` against the bucketed store, one million single-threaded calls each. +/// Run with `cargo test -p extenddb-core -- --ignored bench --nocapture`, in +/// debug and in `--release`. +#[test] +#[ignore = "timing, run by hand"] +fn bench_old_push_vs_new_record() { + use std::sync::RwLock; + + #[allow(dead_code)] + struct OldPoint { + operation: String, + table_name: Option, + segments: LatencySegments, + timestamp: Instant, + } + + const N: u64 = 1_000_000; + let profile = if cfg!(debug_assertions) { + "debug" + } else { + "release" + }; + + let old = RwLock::new(Vec::::with_capacity(256)); + let start = Instant::now(); + for i in 0..N { + #[allow(clippy::cast_possible_truncation)] + let op = OPS[(i % 5) as usize]; + let point = OldPoint { + operation: op.to_owned(), + table_name: Some("T".to_owned()), + segments: segs(1.0), + timestamp: Instant::now(), + }; + if let Ok(mut v) = old.write() { + v.push(point); + } + } + let old_ns = start.elapsed().as_nanos() / u128::from(N); + let old_bytes = old + .read() + .map_or(0, |v| v.capacity() * std::mem::size_of::()); + + let new = RwLock::new(SegmentStore::new(Instant::now())); + let start = Instant::now(); + for i in 0..N { + #[allow(clippy::cast_possible_truncation)] + let op = OPS[(i % 5) as usize]; + if let Ok(mut s) = new.write() { + s.record(ACCOUNTS[0], op, &segs(1.0), Instant::now()); + } + } + let new_ns = start.elapsed().as_nanos() / u128::from(N); + let new_bytes = new + .read() + .map_or(0, |s| s.bucket_count() * SegmentStore::bucket_size()); + + // Read path: the old query_segments loop over every point, versus the store. + let start = Instant::now(); + let mut by_op: std::collections::HashMap = std::collections::HashMap::new(); + if let Ok(v) = old.read() { + for p in v.iter() { + let e = by_op.entry(p.operation.clone()).or_default(); + e.0 += p.segments.total_us; + e.1 += 1; + } + } + let old_query_us = start.elapsed().as_micros(); + let start = Instant::now(); + let out = new + .read() + .map(|s| s.query(TimeWindow::AllTime, None, Instant::now())) + .unwrap_or_default(); + let new_query_us = start.elapsed().as_micros(); + + println!( + "bench[{profile}] record: old push {old_ns} ns/call, new record {new_ns} ns/call; \ + memory after {N} calls: old {old_bytes} B (Vec capacity, Strings excluded), new {new_bytes} B; \ + query over {N} points: old {old_query_us} us ({} ops), new {new_query_us} us ({} ops)", + by_op.len(), + out.len() + ); +} diff --git a/crates/core/src/metrics/segments_tests.rs b/crates/core/src/metrics/segments_tests.rs index c1b8aa937..28ee6a747 100644 --- a/crates/core/src/metrics/segments_tests.rs +++ b/crates/core/src/metrics/segments_tests.rs @@ -1,16 +1,17 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! Tests for [`SegmentStore`]. +//! Window and reference tests for [`SegmentStore`]; the bound and prune tests +//! are in `segments_bound_tests.rs`. use std::time::{Duration, Instant}; use super::*; -const OPS: [&str; 5] = ["GetItem", "PutItem", "Query", "Scan", "UpdateItem"]; -const ACCOUNTS: [&str; 3] = ["111111111111", "222222222222", "333333333333"]; +pub(super) const OPS: [&str; 5] = ["GetItem", "PutItem", "Query", "Scan", "UpdateItem"]; +pub(super) const ACCOUNTS: [&str; 3] = ["111111111111", "222222222222", "333333333333"]; -fn segs(v: f64) -> LatencySegments { +pub(super) fn segs(v: f64) -> LatencySegments { LatencySegments { auth_us: v, authz_us: 2.0 * v, @@ -39,58 +40,16 @@ impl Rng { } } -fn at(epoch: Instant, secs: u64) -> Instant { +pub(super) fn at(epoch: Instant, secs: u64) -> Instant { epoch + Duration::from_secs(secs) } -fn count_of(out: &[OperationSegments], op: &str) -> u64 { +pub(super) fn count_of(out: &[OperationSegments], op: &str) -> u64 { out.iter() .find(|o| o.operation == op) .map_or(0, |o| o.count) } -#[test] -fn bucket_is_64_bytes() { - assert_eq!(SegmentStore::bucket_size(), 64); - assert_eq!(BUCKETS_PER_OPERATION, 1742); -} - -/// Issue #397: 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; - assert!( - store.bucket_count() <= bound, - "bucket count {} exceeds bound {bound}", - store.bucket_count() - ); - assert!(store.bucket_capacity() * SegmentStore::bucket_size() <= bound * 64); - // Every slot of every ring had a request, so the bound is reached - // exactly, held and allocated. - assert_eq!(store.bucket_count(), bound); - assert_eq!(store.bucket_capacity(), 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); -} - /// 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 @@ -309,188 +268,6 @@ fn fine_windows_cut_at_the_second() { ); } -/// 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.bucket_count(), 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.bucket_count(), 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.bucket_count(), 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.bucket_count(), 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.bucket_count(), 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.bucket_count(), 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; 5] = [ - // 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), - // 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; - assert_eq!(store.bucket_count(), pairs * buckets, "{label}: buckets"); - assert_eq!( - store.bucket_capacity(), - pairs * capacity, - "{label}: capacity" - ); - assert!( - store.bucket_capacity() <= 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"); - } -} - /// 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 @@ -621,88 +398,3 @@ fn operations_sorted_and_zero_count_absent() { .is_empty() ); } - -/// Write-path and read-path cost of the previous one-point-per-request -/// `Vec` against the bucketed store, one million single-threaded calls each. -/// Run with `cargo test -p extenddb-core -- --ignored bench --nocapture`, in -/// debug and in `--release`. -#[test] -#[ignore = "timing, run by hand"] -fn bench_old_push_vs_new_record() { - use std::sync::RwLock; - - #[allow(dead_code)] - struct OldPoint { - operation: String, - table_name: Option, - segments: LatencySegments, - timestamp: Instant, - } - - const N: u64 = 1_000_000; - let profile = if cfg!(debug_assertions) { - "debug" - } else { - "release" - }; - - let old = RwLock::new(Vec::::with_capacity(256)); - let start = Instant::now(); - for i in 0..N { - #[allow(clippy::cast_possible_truncation)] - let op = OPS[(i % 5) as usize]; - let point = OldPoint { - operation: op.to_owned(), - table_name: Some("T".to_owned()), - segments: segs(1.0), - timestamp: Instant::now(), - }; - if let Ok(mut v) = old.write() { - v.push(point); - } - } - let old_ns = start.elapsed().as_nanos() / u128::from(N); - let old_bytes = old - .read() - .map_or(0, |v| v.capacity() * std::mem::size_of::()); - - let new = RwLock::new(SegmentStore::new(Instant::now())); - let start = Instant::now(); - for i in 0..N { - #[allow(clippy::cast_possible_truncation)] - let op = OPS[(i % 5) as usize]; - if let Ok(mut s) = new.write() { - s.record(ACCOUNTS[0], op, &segs(1.0), Instant::now()); - } - } - let new_ns = start.elapsed().as_nanos() / u128::from(N); - let new_bytes = new - .read() - .map_or(0, |s| s.bucket_count() * SegmentStore::bucket_size()); - - // Read path: the old query_segments loop over every point, versus the store. - let start = Instant::now(); - let mut by_op: std::collections::HashMap = std::collections::HashMap::new(); - if let Ok(v) = old.read() { - for p in v.iter() { - let e = by_op.entry(p.operation.clone()).or_default(); - e.0 += p.segments.total_us; - e.1 += 1; - } - } - let old_query_us = start.elapsed().as_micros(); - let start = Instant::now(); - let out = new - .read() - .map(|s| s.query(TimeWindow::AllTime, None, Instant::now())) - .unwrap_or_default(); - let new_query_us = start.elapsed().as_micros(); - - println!( - "bench[{profile}] record: old push {old_ns} ns/call, new record {new_ns} ns/call; \ - memory after {N} calls: old {old_bytes} B (Vec capacity, Strings excluded), new {new_bytes} B; \ - query over {N} points: old {old_query_us} us ({} ops), new {new_query_us} us ({} ops)", - by_op.len(), - out.len() - ); -} From 11bfdbe1a69e31201b56d93dd88406bbc2d1e67d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:26:01 +0000 Subject: [PATCH 13/22] docs(metrics): give the segment memory per release and count the keys once The deployment guide gave about 190 bytes per request for every release through 1.0.0. That is the 0.1.12 and 0.1.13 figure. 0.1.15 added the account id to each segment record (#955). The harness on the merge-base measured 248 bytes per point and 252 per later request. The guide now gives 190 bytes through 0.1.14 and 250 from 0.1.15 on, and the sizing rule takes the figure of the release that runs. The design doc's 340 bytes per pair for keys and map entries counted the pair's two 64-byte buckets twice. The keys and entries take about 210 bytes. The guide also states that the segments grow with the request rate up to one request a second per operation. It says that the throttle manager keeps a read and a write bucket for each partition key that a GetItem, PutItem, UpdateItem or DeleteItem names. --- docs/design/06-component-server.md | 2 +- docs/manuals/11-deployment-guide.md | 27 ++++++++++++++++----------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index ba984f4ff..26d8562af 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -360,7 +360,7 @@ ExtendDB's own `AccountId` dimension. 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 about - 340 bytes per pair for its keys and map entries. With the 40 operations the + 210 bytes per pair for its keys and map entries. 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 diff --git a/docs/manuals/11-deployment-guide.md b/docs/manuals/11-deployment-guide.md index 9a18e9643..c3881eb00 100755 --- a/docs/manuals/11-deployment-guide.md +++ b/docs/manuals/11-deployment-guide.md @@ -379,27 +379,32 @@ request for a day. That happens 1,440 to about 1,446 minutes after its 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. They do not -grow with the request rate, the table count or uptime. With -`throttling_enabled = true` the throttle manager keeps a token bucket for every -partition key it saw and never drops one. Resident memory then grows with the -number of distinct partition keys written. +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 partition key that a GetItem, PutItem, UpdateItem or DeleteItem +names. It never drops one. Resident memory then grows with the number of +distinct partition keys those requests name. Every release through 1.0.0 kept one latency segment record per data-plane -request in memory for 24 hours, about 190 bytes per request. So does any later -release before the one that carries this change. On those releases resident +request in memory for 24 hours. So does any later release before the one that +carries this change. 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 + 190 bytes * requests_per_24h * 1.3 +limit >= baseline + bytes_per_request * requests_per_24h * 1.3 ``` -where 1.3 is a modelled allowance for allocator overhead, not a measured -figure (274 requests per second is 23.7 million requests per day and about -5.5 GiB plus baseline), or restart the process before the limit is reached. +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. From 8412d676b5f47746290261e6a508857c37950735 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:26:01 +0000 Subject: [PATCH 14/22] refactor(metrics): compare the newest bucket in the prune itself SegmentStore::prune was the only caller of Ring::holds_from, a one-line comparison of the newest bucket's slot with the first slot of the window. The comparison now sits in the prune's retain closure. --- crates/core/src/metrics/segments.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs index a777bec4f..d996acd52 100644 --- a/crates/core/src/metrics/segments.rs +++ b/crates/core/src/metrics/segments.rs @@ -152,11 +152,6 @@ impl Ring { } } - /// Whether the newest bucket is at or after `first_slot`. - fn holds_from(&self, first_slot: u64) -> bool { - self.buckets.back().is_some_and(|b| b.slot >= first_slot) - } - /// 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 { @@ -319,7 +314,8 @@ impl SegmentStore { self.by_account.retain(|_, operations| { operations.retain(|_, rings| { let ring = &rings.coarse; - ring.holds_from(ring.first_slot(elapsed, None)) + let first = ring.first_slot(elapsed, None); + ring.buckets.back().is_some_and(|b| b.slot >= first) }); !operations.is_empty() }); From 737a515a192471525f6884517542f77990dc785c Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:59:41 +0000 Subject: [PATCH 15/22] test(metrics): pin the drop of every stale bucket in a record A record at a new slot pops each bucket outside the ring with a `while` loop. No test counted the buckets after a record with more than one stale bucket to drop. So the loop changed to an `if` passed every metrics test. The new row of `bucket_memory_follows_the_requests_up_to_the_ring_length` records six consecutive seconds, then one request a ring later. That record drops all six fine buckets. The pair holds 2 buckets in a capacity of 9. With the `if`, the fine ring keeps five stale buckets and the row fails with 7 buckets held. --- crates/core/src/metrics/segments_bound_tests.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/core/src/metrics/segments_bound_tests.rs b/crates/core/src/metrics/segments_bound_tests.rs index 04b87edf7..6a67e3f1e 100644 --- a/crates/core/src/metrics/segments_bound_tests.rs +++ b/crates/core/src/metrics/segments_bound_tests.rs @@ -159,7 +159,7 @@ fn bucket_memory_follows_the_requests_up_to_the_ring_length() { .map(|i| format!("{:012}", 100_000_000_000u64 + i)) .collect(); let every_second: Vec = (0..2 * DAY).collect(); - let cases: [MemoryCase; 5] = [ + let cases: [MemoryCase; 6] = [ // One request a day holds one bucket per ring. ( "1,000 accounts x 40 operations, one request", @@ -171,6 +171,16 @@ fn bucket_memory_follows_the_requests_up_to_the_ring_length() { ), // 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. ( From 9c57cba6f693d3405a61e61dd64b01a1db270b32 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:02:03 +0000 Subject: [PATCH 16/22] refactor(metrics): add a request to a bucket through add_bucket `Bucket::add` and `Bucket::add_bucket` held the same sum over the count and the six segment fields. `Bucket::new` now builds a bucket that holds one request. A record adds that bucket to the newest one with `add_bucket`, or pushes it. So only `add_bucket` holds the sum. The metrics tests pass unchanged. --- crates/core/src/metrics/segments.rs | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs index d996acd52..70d6c4f87 100644 --- a/crates/core/src/metrics/segments.rs +++ b/crates/core/src/metrics/segments.rs @@ -67,14 +67,18 @@ struct Bucket { } impl Bucket { - fn add(&mut self, s: &LatencySegments) { - self.count += 1; - self.auth_us += s.auth_us; - self.authz_us += s.authz_us; - self.throttle_us += s.throttle_us; - self.dispatch_us += s.dispatch_us; - self.response_us += s.response_us; - self.total_us += s.total_us; + /// 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) { @@ -122,7 +126,7 @@ impl Ring { { // 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(segments); + newest.add_bucket(&Bucket::new(slot, segments)); return; } let first_kept = (slot + 1).saturating_sub(self.slots()); @@ -135,12 +139,7 @@ impl Ring { let held = self.buckets.len(); self.buckets.reserve_exact(held.max(1).min(self.len - held)); } - let mut bucket = Bucket { - slot, - ..Bucket::default() - }; - bucket.add(segments); - self.buckets.push_back(bucket); + self.buckets.push_back(Bucket::new(slot, segments)); } /// Sums every bucket whose slot is at or after `first_slot` into `acc`. From da4561565a1d86c4e58b91b98076af18c9de4215 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:03:24 +0000 Subject: [PATCH 17/22] test(metrics): drop the ignored timing comparison of the old push `bench_old_push_vs_new_record` ran only by hand and timed a point with two strings. The point on the base had three: 0.1.15 added the account id. The PR body keeps the numbers it gave. The test file loses 85 lines. --- .../core/src/metrics/segments_bound_tests.rs | 85 ------------------- 1 file changed, 85 deletions(-) diff --git a/crates/core/src/metrics/segments_bound_tests.rs b/crates/core/src/metrics/segments_bound_tests.rs index 6a67e3f1e..632ed5de8 100644 --- a/crates/core/src/metrics/segments_bound_tests.rs +++ b/crates/core/src/metrics/segments_bound_tests.rs @@ -241,88 +241,3 @@ fn bucket_memory_follows_the_requests_up_to_the_ring_length() { assert_eq!(total, (pairs * in_ring) as u64, "{label}: count"); } } - -/// Write-path and read-path cost of the previous one-point-per-request -/// `Vec` against the bucketed store, one million single-threaded calls each. -/// Run with `cargo test -p extenddb-core -- --ignored bench --nocapture`, in -/// debug and in `--release`. -#[test] -#[ignore = "timing, run by hand"] -fn bench_old_push_vs_new_record() { - use std::sync::RwLock; - - #[allow(dead_code)] - struct OldPoint { - operation: String, - table_name: Option, - segments: LatencySegments, - timestamp: Instant, - } - - const N: u64 = 1_000_000; - let profile = if cfg!(debug_assertions) { - "debug" - } else { - "release" - }; - - let old = RwLock::new(Vec::::with_capacity(256)); - let start = Instant::now(); - for i in 0..N { - #[allow(clippy::cast_possible_truncation)] - let op = OPS[(i % 5) as usize]; - let point = OldPoint { - operation: op.to_owned(), - table_name: Some("T".to_owned()), - segments: segs(1.0), - timestamp: Instant::now(), - }; - if let Ok(mut v) = old.write() { - v.push(point); - } - } - let old_ns = start.elapsed().as_nanos() / u128::from(N); - let old_bytes = old - .read() - .map_or(0, |v| v.capacity() * std::mem::size_of::()); - - let new = RwLock::new(SegmentStore::new(Instant::now())); - let start = Instant::now(); - for i in 0..N { - #[allow(clippy::cast_possible_truncation)] - let op = OPS[(i % 5) as usize]; - if let Ok(mut s) = new.write() { - s.record(ACCOUNTS[0], op, &segs(1.0), Instant::now()); - } - } - let new_ns = start.elapsed().as_nanos() / u128::from(N); - let new_bytes = new - .read() - .map_or(0, |s| s.bucket_count() * SegmentStore::bucket_size()); - - // Read path: the old query_segments loop over every point, versus the store. - let start = Instant::now(); - let mut by_op: std::collections::HashMap = std::collections::HashMap::new(); - if let Ok(v) = old.read() { - for p in v.iter() { - let e = by_op.entry(p.operation.clone()).or_default(); - e.0 += p.segments.total_us; - e.1 += 1; - } - } - let old_query_us = start.elapsed().as_micros(); - let start = Instant::now(); - let out = new - .read() - .map(|s| s.query(TimeWindow::AllTime, None, Instant::now())) - .unwrap_or_default(); - let new_query_us = start.elapsed().as_micros(); - - println!( - "bench[{profile}] record: old push {old_ns} ns/call, new record {new_ns} ns/call; \ - memory after {N} calls: old {old_bytes} B (Vec capacity, Strings excluded), new {new_bytes} B; \ - query over {N} points: old {old_query_us} us ({} ops), new {new_query_us} us ({} ops)", - by_op.len(), - out.len() - ); -} From 17f47a22a0cf54f6b56d86af4038d1a6d36697dc Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:04:37 +0000 Subject: [PATCH 18/22] test(metrics): count held and allocated buckets in one helper `SegmentStore::bucket_count` and `bucket_capacity` were the same walk over the rings, one summing `len` and one `capacity`. `SegmentStore::buckets` returns both. The tests read it and assert the same numbers as before. --- crates/core/src/metrics/collector_tests.rs | 2 +- crates/core/src/metrics/segments.rs | 23 +++++------- .../core/src/metrics/segments_bound_tests.rs | 36 ++++++++----------- 3 files changed, 24 insertions(+), 37 deletions(-) diff --git a/crates/core/src/metrics/collector_tests.rs b/crates/core/src/metrics/collector_tests.rs index 7b06d7a66..337309572 100755 --- a/crates/core/src/metrics/collector_tests.rs +++ b/crates/core/src/metrics/collector_tests.rs @@ -238,7 +238,7 @@ fn prune_keeps_recent_segments_and_drops_them_a_day_later() { let held = |c: &MetricsCollector| { c.segments .read() - .map(|s| s.bucket_count()) + .map(|s| s.buckets().0) .unwrap_or(usize::MAX) }; assert_eq!(held(&c), 2); diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs index 70d6c4f87..d917effe1 100644 --- a/crates/core/src/metrics/segments.rs +++ b/crates/core/src/metrics/segments.rs @@ -320,25 +320,18 @@ impl SegmentStore { }); } - /// Number of buckets held, the quantity the memory bound is stated in. + /// 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 bucket_count(&self) -> usize { + pub(super) fn buckets(&self) -> (usize, usize) { self.by_account .values() .flat_map(HashMap::values) - .map(|r| r.fine.buckets.len() + r.coarse.buckets.len()) - .sum() - } - - /// Number of buckets allocated, held or spare: the bucket memory is this - /// times [`Self::bucket_size`]. - #[cfg(test)] - pub(super) fn bucket_capacity(&self) -> usize { - self.by_account - .values() - .flat_map(HashMap::values) - .map(|r| r.fine.buckets.capacity() + r.coarse.buckets.capacity()) - .sum() + .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. diff --git a/crates/core/src/metrics/segments_bound_tests.rs b/crates/core/src/metrics/segments_bound_tests.rs index 632ed5de8..b933430b8 100644 --- a/crates/core/src/metrics/segments_bound_tests.rs +++ b/crates/core/src/metrics/segments_bound_tests.rs @@ -33,16 +33,13 @@ fn boundedness_five_million_records() { store.record(account, op, &segs(1.0), now); } let bound = ACCOUNTS.len() * OPS.len() * BUCKETS_PER_OPERATION; - assert!( - store.bucket_count() <= bound, - "bucket count {} exceeds bound {bound}", - store.bucket_count() - ); - assert!(store.bucket_capacity() * SegmentStore::bucket_size() <= bound * 64); + 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!(store.bucket_count(), bound); - assert_eq!(store.bucket_capacity(), bound); + 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); @@ -84,13 +81,13 @@ fn ring_lap_and_stale_slots() { .query(TimeWindow::LastDay, None, at(epoch, 86_460)) .is_empty() ); - assert_eq!(store.bucket_count(), 2); + 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.bucket_count(), 2); + assert_eq!(store.buckets().0, 2); } /// The prune drops the rings of an account's operation once its newest coarse @@ -107,12 +104,12 @@ fn prune_drops_idle_accounts_and_keeps_active_ones() { 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.bucket_count(), 2 + 2 + 4); + 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.bucket_count(), 8); + assert_eq!(store.buckets().0, 8); assert_eq!( count_of( &store.query(TimeWindow::AllTime, None, at(epoch, 1440 * 60)), @@ -126,7 +123,7 @@ fn prune_drops_idle_accounts_and_keeps_active_ones() { // 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.bucket_count(), 4); + assert_eq!(store.buckets().0, 4); assert!( store .query(TimeWindow::AllTime, Some(ACCOUNTS[0]), at(epoch, 1441 * 60)) @@ -142,7 +139,7 @@ fn prune_drops_idle_accounts_and_keeps_active_ones() { // 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.bucket_count(), 6); + assert_eq!(store.buckets().0, 6); } /// A memory case: label, accounts, operations, request times in seconds (the @@ -217,14 +214,11 @@ fn bucket_memory_follows_the_requests_up_to_the_ring_length() { } } let pairs = accounts * operations; - assert_eq!(store.bucket_count(), pairs * buckets, "{label}: buckets"); - assert_eq!( - store.bucket_capacity(), - pairs * capacity, - "{label}: capacity" - ); + let (held, allocated) = store.buckets(); + assert_eq!(held, pairs * buckets, "{label}: buckets"); + assert_eq!(allocated, pairs * capacity, "{label}: capacity"); assert!( - store.bucket_capacity() <= pairs * BUCKETS_PER_OPERATION, + allocated <= pairs * BUCKETS_PER_OPERATION, "{label}: capacity over the ring length" ); // Every request is still in the whole-ring window. From 2e5a5f606fceedd57b2ac03bdb1c41a1e775f62b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:06:23 +0000 Subject: [PATCH 19/22] docs(metrics): state the prune lag and the kept allocation in comments The module doc of `segments.rs` counted the accounts that sent a request in the last 1,440 to 1,441 minutes. The prune runs every five minutes, so an account stays for up to about 1,446 minutes. The doc also said that only a pair with a request in every second and every minute reaches the bound. That holds for the buckets held. A ring's allocation does not shrink, so a pair keeps the largest allocation it reached until the prune drops its rings. The doc now says both. `record_segments` said that the memory does not grow with the request count. It grows up to the ring lengths. The comments also drop the issue number, and with it the reference to `SegmentPoint`, a type the PR removes. --- crates/core/src/metrics/collector.rs | 4 ++-- crates/core/src/metrics/segments.rs | 22 +++++++++---------- .../core/src/metrics/segments_bound_tests.rs | 4 ++-- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/crates/core/src/metrics/collector.rs b/crates/core/src/metrics/collector.rs index f76a69605..9de8d1225 100755 --- a/crates/core/src/metrics/collector.rs +++ b/crates/core/src/metrics/collector.rs @@ -106,8 +106,8 @@ impl MetricsCollector { /// Record per-segment latency breakdown for a request. /// /// The breakdown is summed into the current time buckets of the account's - /// operation, so the memory held does not grow with the request count - /// (issue #397). The account is a dimension because `query_segments` + /// 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. diff --git a/crates/core/src/metrics/segments.rs b/crates/core/src/metrics/segments.rs index d917effe1..8be3cfc71 100644 --- a/crates/core/src/metrics/segments.rs +++ b/crates/core/src/metrics/segments.rs @@ -13,23 +13,21 @@ //! 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 -//! memory per process is therefore at most +//! 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, reached only by a pair 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 within the coarse ring's window, -//! the last 1,440 to 1,441 minutes: the collector's prune, every five minutes, +//! 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 -//! that window, and the account once it holds no operation. +//! 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. -//! -//! Issue #397: one `SegmentPoint` per request grew to about 4.3 GiB in a day at -//! 274 requests per second. use std::collections::{BTreeMap, HashMap, VecDeque}; use std::time::Instant; diff --git a/crates/core/src/metrics/segments_bound_tests.rs b/crates/core/src/metrics/segments_bound_tests.rs index b933430b8..683726ed8 100644 --- a/crates/core/src/metrics/segments_bound_tests.rs +++ b/crates/core/src/metrics/segments_bound_tests.rs @@ -14,8 +14,8 @@ fn bucket_is_64_bytes() { assert_eq!(BUCKETS_PER_OPERATION, 1742); } -/// Issue #397: five million requests over three simulated days across three -/// accounts and five operations fill the rings and allocate nothing more. +/// 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(); From 7967ac727667b2e4ecf2e59e6095ecdc35049791 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:09:54 +0000 Subject: [PATCH 20/22] docs(metrics): give the pair memory per account shape and an upgrade entry The deployment guide and the design doc gave about 340 bytes for a pair with one request a day. That holds when the account sends many operations. An account that sends one operation takes about 810 bytes for it, because its account key and its map of operations serve that one pair. Both docs now give the two figures, measured on a release build with a counting allocator. They also say that a ring's allocation does not shrink. A pair keeps the largest allocation it reached until a day passes with no request for it. The guide said that a GetItem adds six counter points. It adds five, or seven when it returns an item. The guide also said that earlier releases kept a segment record per data-plane request. They kept one per request that reaches dispatch, control-plane requests included. The upgrade manual gains a v1.1.0 entry for the `segments` of `/metrics` and `/console/metrics-data`: the wider windows, `AllTime`, the sort order and the bounded memory. The guide's Process Memory section links to it. --- docs/design/06-component-server.md | 18 ++++++++++------ docs/manuals/07-upgrade-manual.md | 11 ++++++++++ docs/manuals/11-deployment-guide.md | 32 +++++++++++++++++++---------- 3 files changed, 44 insertions(+), 17 deletions(-) diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index 88e4889c9..7b7c16b01 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -349,7 +349,8 @@ ExtendDB's own `AccountId` dimension. 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 memory does not grow with the request count. `LastMinute` + 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, @@ -359,11 +360,16 @@ ExtendDB's own `AccountId` dimension. 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 about - 210 bytes per pair for its keys and map entries. 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 + 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 about 340 bytes when its account sends many + operations, and about 810 bytes when its account sends only that operation + (release build, counting allocator, 23 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 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 09a3fa889..d0b515224 100755 --- a/docs/manuals/11-deployment-guide.md +++ b/docs/manuals/11-deployment-guide.md @@ -386,19 +386,26 @@ ORDER BY mean_exec_time DESC LIMIT 10; 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 six 40-byte points, held for 60 to 120 seconds. +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, about 340 bytes with -its keys and map entries. 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 five-minute metrics prune drops the buckets of an account that sent no -request for a day. That happens 1,440 to about 1,446 minutes after its last -request. The buckets return to the allocator. The process's resident size can +operation the account sends once a day holds two buckets. With its keys and +map entries that is about 340 bytes when the account sends many operations, +and about 810 bytes when the account sends only that operation (measured on a +release build with a counting allocator, 23 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 @@ -409,9 +416,12 @@ bucket for each partition key that a GetItem, PutItem, UpdateItem or DeleteItem names. It never drops one. Resident memory then grows with the number of distinct partition keys those requests name. -Every release through 1.0.0 kept one latency segment record per data-plane -request in memory for 24 hours. So does any later release before the one that -carries this change. A record takes about 190 bytes through 0.1.14, and about +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 From 5c4f613e9cd2c9c18b46e53e439abb1465f8ed10 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:19:40 +0000 Subject: [PATCH 21/22] test(metrics): clear the two pedantic lints in the segment prune test `cargo clippy -W clippy::pedantic` warned on two lines that the PR adds to `prune_keeps_recent_segments_and_drops_them_a_day_later`: 1,441 minutes as `Duration::from_secs(1441 * 60)`, and `map` then `unwrap_or` on the lock result. The test now uses `Duration::from_mins(1441)` and `map_or`. --- crates/core/src/metrics/collector_tests.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/crates/core/src/metrics/collector_tests.rs b/crates/core/src/metrics/collector_tests.rs index 337309572..174b9864a 100755 --- a/crates/core/src/metrics/collector_tests.rs +++ b/crates/core/src/metrics/collector_tests.rs @@ -224,7 +224,7 @@ fn prune_keeps_recent_segments_and_drops_them_a_day_later() { assert_eq!(segs[0].count, 1); // A day later the bucket has left the ring without any prune call. - let later = epoch + Duration::from_secs(1441 * 60); + let later = epoch + Duration::from_mins(1441); assert!( c.query_segments_with(TimeWindow::AllTime, None, || later) .is_empty() @@ -235,12 +235,7 @@ fn prune_keeps_recent_segments_and_drops_them_a_day_later() { ); // 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(|s| s.buckets().0) - .unwrap_or(usize::MAX) - }; + 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); From 637cefdd5331ffd5b921bc5991fb3bf24ab002bf Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:12:07 +0000 Subject: [PATCH 22/22] docs(metrics): give the measured cost range of a pair and the throttle bucket key The deployment guide said the throttle manager keeps a bucket for each partition key that a GetItem, PutItem, UpdateItem or DeleteItem names. extract_partition_value in crates/server/src/throttle_helpers.rs takes the first attribute of Key or Item as the parsed map gives it. That is name order, or the request's order on a build with the MongoDB backend. So the bucket can belong to the sort key value. The sentence now says so. The guide and the server design doc gave about 340 bytes for a pair with one request a day when its account sends many operations. On a release build with a counting allocator and 1,000 accounts, every count from 1 to 40 operations was measured on 24 November 2026. A pair costs 286 to 429 bytes with 3 to 40 operations, 475 bytes with 2, and 810 bytes with 1. The cost steps up each time the account's map of operations grows. Both docs now give the range. --- docs/design/06-component-server.md | 8 +++++--- docs/manuals/11-deployment-guide.md | 16 ++++++++++------ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index 7b7c16b01..d52daf1c7 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -362,9 +362,11 @@ ExtendDB's own `AccountId` dimension. 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 about 340 bytes when its account sends many - operations, and about 810 bytes when its account sends only that operation - (release build, counting allocator, 23 November 2026). A ring's allocation + 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 diff --git a/docs/manuals/11-deployment-guide.md b/docs/manuals/11-deployment-guide.md index d0b515224..cbaf593e5 100755 --- a/docs/manuals/11-deployment-guide.md +++ b/docs/manuals/11-deployment-guide.md @@ -394,9 +394,11 @@ 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 about 340 bytes when the account sends many operations, -and about 810 bytes when the account sends only that operation (measured on a -release build with a counting allocator, 23 November 2026). With the 40 +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 @@ -412,9 +414,11 @@ 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 partition key that a GetItem, PutItem, UpdateItem or DeleteItem -names. It never drops one. Resident memory then grows with the number of -distinct partition keys those requests name. +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