Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
8d4208e
fix(metrics): sum latency segments into fixed time buckets instead of…
LeeroyHannigan Oct 13, 2026
b9555b3
Merge branch 'main' into fix/bounded-latency-segments
LeeroyHannigan Oct 13, 2026
99c3e89
Merge origin/main into fix/bounded-latency-segments
LeeroyHannigan Nov 14, 2026
6fe3bda
test(metrics): check the segment store's account key
LeeroyHannigan Nov 14, 2026
48768ee
docs(metrics): state the latency segment bound per account
LeeroyHannigan Nov 14, 2026
a43ef7e
fix(metrics): drop the segment rings of an account idle for a day
LeeroyHannigan Nov 14, 2026
b276bd5
refactor(metrics): apply the empty account rule in the segment store
LeeroyHannigan Nov 14, 2026
e9567da
test(metrics): name the accounts in the bound test's comment
LeeroyHannigan Nov 14, 2026
9b6bff1
test(metrics): trim the segment store tests
LeeroyHannigan Nov 14, 2026
0c3a1d0
test(metrics): label the segment reference check with the filter index
LeeroyHannigan Nov 14, 2026
2e5e047
fix(metrics): hold only the segment buckets that had a request
LeeroyHannigan Nov 20, 2026
03bae35
docs(metrics): state the segment memory per bucket held and the relea…
LeeroyHannigan Nov 20, 2026
0019e59
test(metrics): query through the clock seam in the collector tests
LeeroyHannigan Nov 20, 2026
b6d0196
test(metrics): move the segment bound and prune tests to their own file
LeeroyHannigan Nov 20, 2026
11bfdbe
docs(metrics): give the segment memory per release and count the keys…
LeeroyHannigan Nov 20, 2026
8412d67
refactor(metrics): compare the newest bucket in the prune itself
LeeroyHannigan Nov 20, 2026
5532d07
Merge origin/main into fix/bounded-latency-segments
LeeroyHannigan Nov 23, 2026
737a515
test(metrics): pin the drop of every stale bucket in a record
LeeroyHannigan Nov 23, 2026
9c57cba
refactor(metrics): add a request to a bucket through add_bucket
LeeroyHannigan Nov 23, 2026
da45615
test(metrics): drop the ignored timing comparison of the old push
LeeroyHannigan Nov 23, 2026
17f47a2
test(metrics): count held and allocated buckets in one helper
LeeroyHannigan Nov 23, 2026
2e5a5f6
docs(metrics): state the prune lag and the kept allocation in comments
LeeroyHannigan Nov 23, 2026
7967ac7
docs(metrics): give the pair memory per account shape and an upgrade …
LeeroyHannigan Nov 23, 2026
5c4f613
test(metrics): clear the two pedantic lints in the segment prune test
LeeroyHannigan Nov 23, 2026
637cefd
docs(metrics): give the measured cost range of a pair and the throttl…
LeeroyHannigan Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 41 additions & 31 deletions crates/core/src/metrics/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -41,32 +42,22 @@ pub(super) struct MetricKey {
/// metrics endpoint). Individual `record_*` calls take a write lock briefly.
pub struct MetricsCollector {
pub(super) data: RwLock<HashMap<MetricKey, Accumulator>>,
/// Per-operation latency segment breakdowns for the console deep-dive.
pub(super) segments: RwLock<Vec<SegmentPoint>>,
/// Per-account, per-operation latency segment sums for the console
/// deep-dive, bucketed by time so memory is bounded by the number of
/// accounts and operations.
pub(super) segments: RwLock<SegmentStore>,
/// Serializes drains, so each one takes and keeps points in record order.
/// `record` and `prune` never take it.
pub(super) drain_lock: Mutex<()>,
}

/// A single latency segment data point with metadata.
#[derive(Debug, Clone)]
pub(super) struct SegmentPoint {
pub(super) operation: String,
/// The account of the request, which `query_segments` filters on.
pub(super) account_id: String,
#[allow(dead_code)] // TODO(cleanup): used when console adds table-scoped latency breakdown
pub(super) table_name: Option<String>,
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(()),
}
}
Expand Down Expand Up @@ -113,29 +104,49 @@ impl MetricsCollector {
}

/// Record per-segment latency breakdown for a request.
pub fn record_segments(
///
/// The breakdown is summed into the current time buckets of the account's
/// operation, so the memory held is bounded by the ring lengths, whatever
/// the request count. The account is a dimension because `query_segments`
/// filters on it. The table is not: a per-table breakdown would multiply
/// the bound by the table count, and the console reads per-operation
/// averages.
pub fn record_segments(&self, account_id: &str, operation: &str, segments: &LatencySegments) {
self.record_segments_with(account_id, operation, segments, Instant::now);
}

/// `record_segments` with the clock it reads. The clock is read under the
/// lock, as in `query_segments`, so a stored record is never ahead of a
/// query that follows it; otherwise a writer that crosses a bucket
/// boundary between its clock read and its lock could drop the oldest
/// in-window bucket before a reader with an earlier clock reads it.
pub(super) fn record_segments_with(
&self,
account_id: &str,
operation: &str,
table_name: Option<&str>,
segments: LatencySegments,
segments: &LatencySegments,
clock: impl FnOnce() -> Instant,
) {
let point = SegmentPoint {
operation: operation.to_owned(),
account_id: account_id.to_owned(),
table_name: table_name.map(ToOwned::to_owned),
segments,
timestamp: Instant::now(),
};
let Ok(mut vec) = self.segments.write() else {
let Ok(mut store) = self.segments.write() else {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading the clock before the lock here, or before the read lock in query_segments, leaves every test passing. The comment's property rests on the lock placement alone. A clock seam on the record path would let a test hold it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced for both paths. 2e5e047 moves the clock behind record_segments_with and query_segments_with, and the production paths pass Instant::now. segment_record_and_query_read_the_clock_under_the_lock passes a clock that asserts try_read and try_write on the segments lock return WouldBlock. A clock read before either lock fails it.

return;
};
vec.push(point);
store.record(account_id, operation, segments, clock());
}

/// Prune data points older than 1 day.
///
/// Segment buckets leave their ring as time advances; the prune drops the
/// rings of an account's operation once its newest bucket is older than a
/// day, so an account that stopped sending requests, or was deleted, frees
/// its segment buckets after a day.
pub fn prune(&self) {
let now = Instant::now();
self.prune_at(Instant::now());
}

/// `prune` at the clock `now`, which may be read before the locks: a
/// point or a segment recorded in between is newer than `now`, so the
/// prune keeps it.
pub(super) fn prune_at(&self, now: Instant) {
let cutoff = now.checked_sub(Duration::from_secs(86400)).unwrap_or(now);
let Ok(mut map) = self.data.write() else {
return;
Expand All @@ -145,9 +156,8 @@ impl MetricsCollector {
}
map.retain(|_, acc| !acc.is_empty());
drop(map);
// Prune segment points too.
if let Ok(mut segs) = self.segments.write() {
segs.retain(|p| p.timestamp >= cutoff);
if let Ok(mut store) = self.segments.write() {
store.prune(now);
}
}
}
Expand Down
72 changes: 21 additions & 51 deletions crates/core/src/metrics/collector_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -152,61 +149,34 @@ impl MetricsCollector {

/// Query average latency segments for the console deep-dive.
///
/// Returns per-operation averages over the given time window, of the
/// requests of `account_id` only when it is given (an empty string is no
/// filter).
/// Returns per-operation averages over the given time window, sorted by
/// operation name, of the requests of `account_id` only when it is given
/// (an empty string is no filter); without it, every account's requests
/// are summed per operation. `LastMinute` and `Last5Minutes` read
/// 1-second buckets, the longer windows read 1-minute buckets: a window of
/// `W` seconds covers at least the last `W` seconds and at most the last
/// `W` plus one bucket width. `AllTime` is the whole 24-hour ring.
#[must_use]
pub fn query_segments(
&self,
window: TimeWindow,
account_id: Option<&str>,
) -> Vec<OperationSegments> {
let account_id = account_id.filter(|a| !a.is_empty());
let now = Instant::now();
let cutoff = window_cutoff(window, now);
let Ok(vec) = self.segments.read() else {
self.query_segments_with(window, account_id, Instant::now)
}

/// `query_segments` with the clock it reads, under the lock, paired with
/// `record_segments`.
pub(super) fn query_segments_with(
&self,
window: TimeWindow,
account_id: Option<&str>,
clock: impl FnOnce() -> Instant,
) -> Vec<OperationSegments> {
let Ok(store) = self.segments.read() else {
return Vec::new();
};
let mut by_op: HashMap<String, SegmentAccum> = HashMap::new();
for p in vec.iter() {
if let Some(c) = cutoff
&& p.timestamp < c
{
continue;
}
if account_id.is_some_and(|a| a != p.account_id) {
continue;
}
let e = by_op.entry(p.operation.clone()).or_default();
e.0 += p.segments.auth_us;
e.1 += p.segments.authz_us;
e.2 += p.segments.throttle_us;
e.3 += p.segments.dispatch_us;
e.4 += p.segments.response_us;
e.5 += p.segments.total_us;
e.6 += 1;
}
by_op
.into_iter()
.map(
|(op, (auth, authz, throttle, dispatch, response, total, count))| {
#[allow(clippy::cast_precision_loss)]
let c = count as f64;
OperationSegments {
operation: op,
count,
avg: super::types::LatencySegments {
auth_us: auth / c,
authz_us: authz / c,
throttle_us: throttle / c,
dispatch_us: dispatch / c,
response_us: response / c,
total_us: total / c,
},
}
},
)
.collect()
store.query(window, account_id, clock())
}
}

Expand Down
75 changes: 61 additions & 14 deletions crates/core/src/metrics/collector_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,7 @@ fn record_and_query_segments() {
c.record_segments(
ACCOUNT,
"GetItem",
Some("T"),
LatencySegments {
&LatencySegments {
auth_us: 100.0,
authz_us: 200.0,
throttle_us: 50.0,
Expand All @@ -175,8 +174,7 @@ fn record_and_query_segments() {
c.record_segments(
ACCOUNT,
"GetItem",
Some("T"),
LatencySegments {
&LatencySegments {
auth_us: 200.0,
authz_us: 300.0,
throttle_us: 50.0,
Expand All @@ -198,15 +196,18 @@ fn record_and_query_segments() {
}

#[test]
fn prune_removes_old_segments() {
fn prune_keeps_recent_segments_and_drops_them_a_day_later() {
use crate::metrics::types::LatencySegments;
use std::time::Duration;

let c = MetricsCollector::new();
let Ok(epoch) = c.segments.read().map(|s| s.epoch()) else {
panic!("segments lock poisoned");
};
c.record_segments(
ACCOUNT,
"PutItem",
None,
LatencySegments {
&LatencySegments {
auth_us: 10.0,
authz_us: 20.0,
throttle_us: 5.0,
Expand All @@ -221,6 +222,54 @@ fn prune_removes_old_segments() {
let segs = c.query_segments(TimeWindow::AllTime, None);
assert_eq!(segs.len(), 1);
assert_eq!(segs[0].count, 1);

// A day later the bucket has left the ring without any prune call.
let later = epoch + Duration::from_mins(1441);
assert!(
c.query_segments_with(TimeWindow::AllTime, None, || later)
.is_empty()
);
assert!(
c.query_segments_with(TimeWindow::LastDay, None, || later)
.is_empty()
);
// The buckets are still held until the collector's prune runs at that
// time; then the account's rings and the account are gone.
let held = |c: &MetricsCollector| c.segments.read().map_or(usize::MAX, |s| s.buckets().0);
assert_eq!(held(&c), 2);
c.prune_at(later);
assert_eq!(held(&c), 0);
}

/// `record_segments` and `query_segments` read the clock under the lock: a
/// clock that runs while the lock is free fails these checks.
#[test]
fn segment_record_and_query_read_the_clock_under_the_lock() {
use crate::metrics::types::LatencySegments;
use std::sync::TryLockError;
use std::time::Instant;

let c = MetricsCollector::new();
let point = LatencySegments {
total_us: 10.0,
..LatencySegments::default()
};
c.record_segments_with(ACCOUNT, "GetItem", &point, || {
assert!(
matches!(c.segments.try_read(), Err(TryLockError::WouldBlock)),
"record read the clock before taking the write lock"
);
Instant::now()
});
let out = c.query_segments_with(TimeWindow::AllTime, None, || {
assert!(
matches!(c.segments.try_write(), Err(TryLockError::WouldBlock)),
"query read the clock before taking the read lock"
);
Instant::now()
});
assert_eq!(out.len(), 1);
assert_eq!(out[0].count, 1);
}

#[test]
Expand All @@ -231,8 +280,7 @@ fn segments_multiple_operations() {
c.record_segments(
ACCOUNT,
"GetItem",
Some("T"),
LatencySegments {
&LatencySegments {
auth_us: 100.0,
authz_us: 200.0,
throttle_us: 50.0,
Expand All @@ -244,8 +292,7 @@ fn segments_multiple_operations() {
c.record_segments(
ACCOUNT,
"PutItem",
Some("T"),
LatencySegments {
&LatencySegments {
auth_us: 120.0,
authz_us: 220.0,
throttle_us: 60.0,
Expand Down Expand Up @@ -486,9 +533,9 @@ fn segments_are_filtered_by_account() {
total_us: 10.0,
..LatencySegments::default()
};
c.record_segments(ACCOUNT, "GetItem", Some("T"), point.clone());
c.record_segments("222222222222", "Scan", Some("T"), point.clone());
c.record_segments("222222222222", "GetItem", Some("T"), point);
c.record_segments(ACCOUNT, "GetItem", &point);
c.record_segments("222222222222", "Scan", &point);
c.record_segments("222222222222", "GetItem", &point);

let ops = |account: Option<&str>| {
let mut ops: Vec<(String, u64)> = c
Expand Down
6 changes: 5 additions & 1 deletion crates/core/src/metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@
//! Collects `DynamoDB`-style `CloudWatch` metrics per table, per operation, and
//! per GSI. Metrics are accumulated in memory using an `RwLock`-protected map
//! of per-key accumulators. A background task prunes data points older than
//! 1 day every 5 minutes.
//! 1 day every 5 minutes. Per-account, per-operation latency segments are
//! summed into fixed time buckets at record time (see `segments`), so they
//! hold a bounded amount of memory; the same task drops the buckets of an
//! account that has sent no request for a day.
//!
//! REQ-OBS-005: Metrics endpoint.

mod accumulator;
mod collector;
mod collector_query;
mod collector_record;
mod segments;
mod types;

pub use collector::MetricsCollector;
Expand Down
Loading
Loading