Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(propdefs): correct the channel gauges and write-latency buckets (#77942)

Eli Reisman45970ec8754d
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 33086b1758da..1c21f58c4c29 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9256,7 +9256,6 @@ dependencies = [
"rstest",
"serde",
"serde_json",
- "serve-metrics",
"sqlx",
"thiserror 2.0.18",
"tokio",
diff --git a/rust/property-defs-rs/Cargo.toml b/rust/property-defs-rs/Cargo.toml
index a50e8045e713..3767cdcf671c 100644
--- a/rust/property-defs-rs/Cargo.toml
+++ b/rust/property-defs-rs/Cargo.toml
@@ -15,7 +15,6 @@ sqlx = { workspace = true }
futures = { workspace = true }
lifecycle = { path = "../common/lifecycle" }
axum = { workspace = true }
-serve-metrics = { path = "../common/serve_metrics" }
metrics = { workspace = true }
chrono = { workspace = true }
quick_cache = { workspace = true }
diff --git a/rust/property-defs-rs/src/lib.rs b/rust/property-defs-rs/src/lib.rs
index defc72e5e465..30b7b0249f3d 100644
--- a/rust/property-defs-rs/src/lib.rs
+++ b/rust/property-defs-rs/src/lib.rs
@@ -28,6 +28,7 @@ pub mod batch_ingestion;
pub mod config;
pub mod group_type_resolver;
pub mod measuring_channel;
+pub mod metrics_buckets;
pub mod metrics_consts;
pub mod types;
pub mod update_cache;
diff --git a/rust/property-defs-rs/src/main.rs b/rust/property-defs-rs/src/main.rs
index 3bac3f42d7a7..869a6e0d4557 100644
--- a/rust/property-defs-rs/src/main.rs
+++ b/rust/property-defs-rs/src/main.rs
@@ -8,13 +8,14 @@ use property_defs_rs::{
app_context::AppContext,
config::Config,
measuring_channel::measuring_channel,
- metrics_consts::CHANNEL_CAPACITY,
+ metrics_buckets::bucket_overrides,
+ metrics_consts::{CHANNEL_CAPACITY, CHANNEL_CAPACITY_TOTAL},
types::MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS,
update_cache::Cache,
update_consumer_loop, update_producer_loop,
};
-use serve_metrics::setup_metrics_routes;
+use common_metrics::setup_metrics_routes_with_overrides;
use sqlx::postgres::PgPoolOptions;
use tokio::net::TcpListener;
use tracing::level_filters::LevelFilter;
@@ -133,13 +134,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
drop(producer_handle);
- // Publish the tx capacity metric every 10 seconds
+ // Publish the tx capacity metrics every 10 seconds. Both are needed to read occupancy:
+ // `capacity()` is remaining slots, `max_capacity()` is the channel size.
tokio::spawn({
let tx = tx.clone();
async move {
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
metrics::gauge!(CHANNEL_CAPACITY).set(tx.capacity() as f64);
+ metrics::gauge!(CHANNEL_CAPACITY_TOTAL).set(tx.max_capacity() as f64);
}
}
});
@@ -178,7 +181,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}),
);
let app = apply_routes(app, context);
- let app = setup_metrics_routes(app);
+ let app = setup_metrics_routes_with_overrides(app, &bucket_overrides());
let bind = format!("{}:{}", config.host, config.port);
info!(address = %bind, "HTTP server starting");
diff --git a/rust/property-defs-rs/src/measuring_channel.rs b/rust/property-defs-rs/src/measuring_channel.rs
index ad182fe3c38a..3cb5ac426234 100644
--- a/rust/property-defs-rs/src/measuring_channel.rs
+++ b/rust/property-defs-rs/src/measuring_channel.rs
@@ -37,18 +37,24 @@ pub fn measuring_channel<T>(capacity: usize) -> (MeasuringSender<T>, MeasuringRe
}
impl<T> MeasuringSender<T> {
+ // Both senders count the message *before* handing it to the channel. Counting afterwards
+ // leaves a window where the receiver has already dequeued the item and decremented, so the
+ // subtraction runs first and wraps the unsigned counter to usize::MAX, where the gauge then
+ // sits forever. On failure the item never entered the channel, so take the count back.
pub fn try_send(&self, item: T) -> Result<(), TrySendError<T>> {
+ self.in_flight.fetch_add(1, Ordering::Relaxed);
let res = self.sender.try_send(item);
- if res.is_ok() {
- self.in_flight.fetch_add(1, Ordering::Relaxed);
+ if res.is_err() {
+ self.in_flight.fetch_sub(1, Ordering::Relaxed);
}
res
}
pub async fn send(&self, item: T) -> Result<(), SendError<T>> {
+ self.in_flight.fetch_add(1, Ordering::Relaxed);
let res = self.sender.send(item).await;
- if res.is_ok() {
- self.in_flight.fetch_add(1, Ordering::Relaxed);
+ if res.is_err() {
+ self.in_flight.fetch_sub(1, Ordering::Relaxed);
}
res
}
@@ -57,10 +63,17 @@ impl<T> MeasuringSender<T> {
self.in_flight.load(Ordering::Relaxed)
}
+ /// Slots still free. Note this is *remaining* capacity, not the channel's size; pair it with
+ /// `max_capacity` to express occupancy.
pub fn capacity(&self) -> usize {
self.sender.capacity()
}
+ /// The channel's total size, which is fixed at construction.
+ pub fn max_capacity(&self) -> usize {
+ self.sender.max_capacity()
+ }
+
pub fn inner(&self) -> &Sender<T> {
&self.sender
}
diff --git a/rust/property-defs-rs/src/metrics_buckets.rs b/rust/property-defs-rs/src/metrics_buckets.rs
new file mode 100644
index 000000000000..1ff3f699ac5f
--- /dev/null
+++ b/rust/property-defs-rs/src/metrics_buckets.rs
@@ -0,0 +1,59 @@
+//! Histogram bucket overrides for `property-defs-rs`.
+//!
+//! `common-metrics`' default ladder is millisecond-shaped and tops out at 10s, which suits the
+//! per-chunk write timings. It does not suit `prop_defs_batch_acquire_time_ms`, which measures how
+//! long the consumer waits for a batch to fill and is therefore bounded by `max_issue_period`
+//! (500s in production), not by any database operation. Left on the default ladder its whole
+//! distribution lands in the overflow bucket and no quantile over it is meaningful.
+//!
+//! Wired in at startup via `common_metrics::setup_metrics_routes_with_overrides`.
+//!
+//! One unit trap to know about: `http_requests_duration_seconds`, recorded by the
+//! `common_metrics` axum middleware, observes seconds while the default ladder is
+//! millisecond-shaped, so every sub-second request collapses into the first bucket. That is
+//! harmless while this service's HTTP surface is only `/metrics` and the probes, but if a real
+//! API endpoint ever ships here it needs a seconds-shaped override in this list.
+
+use common_metrics::Matcher;
+
+use crate::metrics_consts::{
+ BATCH_ACQUIRE_TIME, V2_EVENT_DEFS_BATCH_WRITE_TIME, V2_EVENT_PROPS_BATCH_WRITE_TIME,
+ V2_PROP_DEFS_BATCH_WRITE_TIME,
+};
+
+// Batch-acquire spans "the channel already had a full batch waiting" to "we sat here until
+// max_issue_period expired", so the ladder has to cover sub-millisecond through the 500s
+// production timeout. Coarse at the top: past a minute the only question is which order of
+// magnitude.
+const BATCH_ACQUIRE_BUCKETS_MS: &[f64] = &[
+ 1.0, 10.0, 100.0, 500.0, 1_000.0, 5_000.0, 10_000.0, 30_000.0, 60_000.0, 120_000.0, 300_000.0,
+ 600_000.0,
+];
+
+// Per-chunk write times run in the hundreds of milliseconds normally. The 30s ceiling leaves room
+// for a stalled Postgres plus this path's three retries and their backoff, which the default 10s
+// ceiling would swallow.
+const BATCH_WRITE_BUCKETS_MS: &[f64] = &[
+ 1.0, 5.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1_000.0, 2_000.0, 5_000.0, 10_000.0, 30_000.0,
+];
+
+pub fn bucket_overrides() -> Vec<(Matcher, &'static [f64])> {
+ vec![
+ (
+ Matcher::Full(BATCH_ACQUIRE_TIME.to_string()),
+ BATCH_ACQUIRE_BUCKETS_MS,
+ ),
+ (
+ Matcher::Full(V2_EVENT_DEFS_BATCH_WRITE_TIME.to_string()),
+ BATCH_WRITE_BUCKETS_MS,
+ ),
+ (
+ Matcher::Full(V2_EVENT_PROPS_BATCH_WRITE_TIME.to_string()),
+ BATCH_WRITE_BUCKETS_MS,
+ ),
+ (
+ Matcher::Full(V2_PROP_DEFS_BATCH_WRITE_TIME.to_string()),
+ BATCH_WRITE_BUCKETS_MS,
+ ),
+ ]
+}
diff --git a/rust/property-defs-rs/src/metrics_consts.rs b/rust/property-defs-rs/src/metrics_consts.rs
index 249cd0d0d7aa..58e4d916976a 100644
--- a/rust/property-defs-rs/src/metrics_consts.rs
+++ b/rust/property-defs-rs/src/metrics_consts.rs
@@ -20,17 +20,17 @@ pub const UPDATE_PRODUCER_OFFSET: &str = "prop_defs_update_producer_offset";
pub const GROUP_TYPE_CACHE: &str = "prop_defs_group_type_cache";
pub const RECV_DEQUEUED: &str = "prop_defs_recv_dequeued";
pub const COMPACTED_UPDATES: &str = "prop_defs_compaction_dropped_updates";
-pub const UPDATE_TRANSACTION_TIME: &str = "prop_defs_update_transaction_time_ms";
-pub const GROUP_TYPE_RESOLVE_TIME: &str = "prop_defs_group_type_resolve_time_ms";
pub const UPDATES_SKIPPED: &str = "prop_defs_skipped_updates";
pub const UPDATES_DROPPED: &str = "prop_defs_dropped_updates";
pub const SKIPPED_DUE_TO_TEAM_FILTER: &str = "prop_defs_skipped_due_to_team_filter";
pub const ISSUE_FAILED: &str = "prop_defs_issue_failed";
pub const CHUNK_SIZE: &str = "prop_defs_chunk_size";
pub const DUPLICATES_IN_BATCH: &str = "prop_defs_duplicates_in_batch";
-pub const SINGLE_UPDATE_ISSUE_TIME: &str = "prop_defs_single_update_issue_time_ms";
pub const CHANNEL_MESSAGES_IN_FLIGHT: &str = "prop_defs_channel_messages_in_flight";
+// Remaining free slots, not the channel size. CHANNEL_CAPACITY_TOTAL carries the size, so
+// occupancy is 1 - (capacity / capacity_total).
pub const CHANNEL_CAPACITY: &str = "prop_defs_channel_capacity";
+pub const CHANNEL_CAPACITY_TOTAL: &str = "prop_defs_channel_capacity_total";
pub const ISOLATED_PROPDEFS_DB_SELECTED: &str = "isolated_propdefs_db_selected";
diff --git a/rust/property-defs-rs/tests/measuring_channel.rs b/rust/property-defs-rs/tests/measuring_channel.rs
new file mode 100644
index 000000000000..639d7d95cf66
--- /dev/null
+++ b/rust/property-defs-rs/tests/measuring_channel.rs
@@ -0,0 +1,64 @@
+use property_defs_rs::measuring_channel::measuring_channel;
+
+// The in-flight counter is unsigned, so a decrement landing before its matching increment wraps it
+// to usize::MAX, where the gauge then stays for the life of the process. That is what the
+// production gauge was doing.
+//
+// This is a stress test, not a deterministic one: the window only exists across threads, so it
+// takes a real multi-threaded interleaving to hit. Measured over 12 runs each way it catches the
+// old ordering 11 times and never fails against the current one. It is a few milliseconds, so the
+// occasional miss is worth having it in the suite. It cannot false-fail: the bound below is a hard
+// ceiling on a correct implementation, not a timing guess.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn test_in_flight_count_never_underflows_under_interleaved_send_and_recv() {
+ const CAPACITY: usize = 8;
+ const ROUNDS: usize = 2_000;
+
+ let (tx, mut rx) = measuring_channel::<u64>(CAPACITY);
+
+ let sender = tokio::spawn({
+ let tx = tx.clone();
+ async move {
+ for i in 0..ROUNDS as u64 {
+ tx.send(i).await.expect("receiver alive");
+ }
+ }
+ });
+
+ for _ in 0..ROUNDS {
+ rx.recv().await.expect("sender alive");
+ // A message is counted from submission, so the queued messages plus the one sender
+ // currently blocked inside send() is the true ceiling. What this is really watching for is
+ // a wrapped counter, which lands near usize::MAX and is nowhere near this bound.
+ let in_flight = rx.get_inflight_messages_count();
+ assert!(
+ in_flight <= CAPACITY + 1,
+ "in-flight count {in_flight} is above the ceiling, so the counter wrapped"
+ );
+ }
+
+ sender.await.expect("sender panicked");
+ assert_eq!(
+ rx.get_inflight_messages_count(),
+ 0,
+ "every sent message was received, so the counter must be back to zero"
+ );
+}
+
+// A send that fails never reaches the channel, so it must not leave a phantom message counted.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn test_failed_send_does_not_leak_an_in_flight_count() {
+ let (tx, rx) = measuring_channel::<u64>(1);
+
+ tx.try_send(1).expect("first send fits");
+ assert!(tx.try_send(2).is_err(), "channel should be full");
+ assert_eq!(tx.get_inflight_messages_count(), 1);
+
+ drop(rx);
+ assert!(tx.send(3).await.is_err(), "receiver is gone");
+ assert_eq!(
+ tx.get_inflight_messages_count(),
+ 1,
+ "a send to a closed channel must not be counted"
+ );
+}