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.

feat(capture): split already-disabled GRL counter by over_budget (#101921)

Eli Reisman4765acefa049
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 2fb44596c8a1..3f93b6d812b4 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -508,6 +508,7 @@ async fn process_events_inner(
let mut limited_distinct_ids: HashSet<&str> = HashSet::new();
let mut limited_event_count: u64 = 0;
let mut already_disabled_event_count: u64 = 0;
+ let mut already_disabled_over_budget_count: u64 = 0;
for event in events.iter_mut() {
let cache_key =
GlobalRateLimitKey::TokenDistinctId(&context.token, &event.event.distinct_id)
@@ -522,6 +523,9 @@ async fn process_events_inner(
// so stamp nothing and keep it out of the customer-facing tallies.
if event.metadata.skip_person_processing {
already_disabled_event_count += 1;
+ if limited {
+ already_disabled_over_budget_count += 1;
+ }
continue;
}
@@ -559,10 +563,23 @@ async fn process_events_inner(
);
}
- if already_disabled_event_count > 0 {
- // Charged against the limiter but not re-stamped.
- counter!("capture_global_rate_limiter_already_disabled")
- .increment(already_disabled_event_count);
+ // Enforcement alerting needs the over_budget arm; keep both arms emitted.
+ if already_disabled_over_budget_count > 0 {
+ counter!(
+ "capture_global_rate_limiter_already_disabled",
+ "over_budget" => "true",
+ )
+ .increment(already_disabled_over_budget_count);
+ }
+
+ let already_disabled_under_budget_count =
+ already_disabled_event_count - already_disabled_over_budget_count;
+ if already_disabled_under_budget_count > 0 {
+ counter!(
+ "capture_global_rate_limiter_already_disabled",
+ "over_budget" => "false",
+ )
+ .increment(already_disabled_under_budget_count);
}
if limited_event_count > 0 {
@@ -2890,13 +2907,36 @@ mod tests {
assert!(collector.emitted().is_empty());
}
+ /// Counter value for the already-disabled GRL metric at the given `over_budget` label.
+ fn already_disabled_count(
+ snapshotter: &metrics_util::debugging::Snapshotter,
+ over_budget: &str,
+ ) -> Option<u64> {
+ use metrics_util::debugging::DebugValue;
+
+ snapshotter
+ .snapshot()
+ .into_vec()
+ .into_iter()
+ .find_map(|(key, _, _, value)| {
+ if key.key().name() != "capture_global_rate_limiter_already_disabled" {
+ return None;
+ }
+ let labels: std::collections::HashMap<&str, &str> =
+ key.key().labels().map(|l| (l.key(), l.value())).collect();
+ if labels.get("over_budget") != Some(&over_budget) {
+ return None;
+ }
+ match value {
+ DebugValue::Counter(v) => Some(v),
+ _ => None,
+ }
+ })
+ }
+
#[tokio::test]
async fn global_rate_limit_is_skipped_when_person_processing_was_already_off() {
- // An ops restriction already took person processing away, so the limiter
- // is not consulted: it has nothing left to take, and the call would cost a
- // Redis round trip per event. The event keeps its lane and its partition
- // key, so the limiter's overflow reroute does not apply either. A hot key
- // under a restriction is left to the burst limiter downstream.
+ // Still charged so the key's fleet count stays right, but nothing is stamped.
let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
.unwrap()
.with_timezone(&Utc);
@@ -2911,6 +2951,10 @@ mod tests {
let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&["test_token:test_user"]));
let collector = Arc::new(CollectingEmitter::new());
+ let recorder = metrics_util::debugging::DebuggingRecorder::new();
+ let snapshotter = recorder.snapshotter();
+ let _metrics_guard = metrics::set_default_local_recorder(&recorder);
+
let service =
EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));
let mut manager = RestrictionManager::new();
@@ -2945,8 +2989,73 @@ mod tests {
assert!(captured[0].metadata.skip_person_processing);
assert_eq!(
captured[0].metadata.overflow_reason, None,
- "the limiter is skipped, so it does not reroute the key to overflow"
+ "an already-disabled event is not rerouted to overflow"
+ );
+ assert_eq!(
+ already_disabled_count(&snapshotter, "true"),
+ Some(1),
+ "an over-budget event with person processing already off belongs in the over_budget arm"
+ );
+ assert_eq!(
+ already_disabled_count(&snapshotter, "false"),
+ None,
+ "nothing under budget was already disabled in this batch"
+ );
+ }
+
+ #[tokio::test]
+ async fn already_disabled_under_budget_is_counted_separately() {
+ // Under budget: must not enter the enforcement identity.
+ let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00Z")
+ .unwrap()
+ .with_timezone(&Utc);
+ let context = create_test_context(now, None);
+ let events = vec![create_test_event(
+ Some("2023-01-01T11:00:00Z".to_string()),
+ None,
+ None,
+ )];
+
+ let sink = MockSink::new();
+ let global_limiter = Arc::new(GlobalRateLimiter::mock_limiting(&[]));
+
+ let recorder = metrics_util::debugging::DebuggingRecorder::new();
+ let snapshotter = recorder.snapshotter();
+ let _metrics_guard = metrics::set_default_local_recorder(&recorder);
+
+ let service =
+ EventRestrictionService::new(vec![Pipeline::Analytics], Duration::from_secs(300));
+ let mut manager = RestrictionManager::new();
+ manager.insert_restrictions(
+ Pipeline::Analytics,
+ "test_token",
+ vec![Restriction {
+ restriction_type: RestrictionType::SkipPersonProcessing,
+ scope: RestrictionScope::AllEvents,
+ args: None,
+ }],
+ );
+ service.update(manager).await;
+
+ run_pipeline(
+ Arc::new(OutputRegistry::single(sink.clone())),
+ events,
+ &context,
+ PipelineOptions {
+ restriction_service: Some(service),
+ global_rate_limiter: Some(global_limiter),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ already_disabled_count(&snapshotter, "false"),
+ Some(1),
+ "an under-budget event with person processing already off belongs in the other arm"
);
+ assert_eq!(already_disabled_count(&snapshotter, "true"), None);
}
#[tokio::test]
diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rs
index 6aa8ed2c7d12..16df3a279cf6 100644
--- a/rust/capture/src/v1/analytics/process.rs
+++ b/rust/capture/src/v1/analytics/process.rs
@@ -1013,15 +1013,15 @@ async fn apply_ai_byte_limits(
}
}
-/// Per-batch tally of how the shared global rate limiter classified each
-/// evaluated event. All three fields count events (not distinct_ids) and all
-/// three charge the limiter, so `allowed + limited + already_disabled` equals
-/// the non-Drop events reaching this stage.
+/// Per-batch tally from the shared global rate limiter. Counts events, not
+/// distinct_ids: `allowed + limited + already_disabled` covers every non-Drop event.
#[derive(Debug, Default, PartialEq, Eq)]
struct TokenDistinctIdTally {
allowed: u64,
limited: u64,
already_disabled: u64,
+ /// Subset of `already_disabled`; keep it out of the sum above.
+ already_disabled_over_budget: u64,
}
async fn apply_token_distinct_id_limits(
@@ -1034,6 +1034,7 @@ async fn apply_token_distinct_id_limits(
let mut limited_event_count: u64 = 0;
let mut allowed_count: u64 = 0;
let mut already_disabled_count: u64 = 0;
+ let mut already_disabled_over_budget_count: u64 = 0;
for event in events.iter_mut() {
if event.result != EventResult::Ok {
@@ -1052,6 +1053,9 @@ async fn apply_token_distinct_id_limits(
// person processing, so it still gets its warning stamped below.
if event.force_disable_person_processing {
already_disabled_count += 1;
+ if limited {
+ already_disabled_over_budget_count += 1;
+ }
continue;
}
@@ -1085,13 +1089,26 @@ async fn apply_token_distinct_id_limits(
.increment(allowed_count);
}
- if already_disabled_count > 0 {
+ if already_disabled_over_budget_count > 0 {
metrics::counter!(
CAPTURE_V1_RATE_LIMITER,
"limiter" => "token_distinct_id",
"outcome" => "already_disabled",
+ "over_budget" => "true",
)
- .increment(already_disabled_count);
+ .increment(already_disabled_over_budget_count);
+ }
+
+ let already_disabled_under_budget_count =
+ already_disabled_count - already_disabled_over_budget_count;
+ if already_disabled_under_budget_count > 0 {
+ metrics::counter!(
+ CAPTURE_V1_RATE_LIMITER,
+ "limiter" => "token_distinct_id",
+ "outcome" => "already_disabled",
+ "over_budget" => "false",
+ )
+ .increment(already_disabled_under_budget_count);
}
if limited_event_count > 0 {
@@ -1130,6 +1147,7 @@ async fn apply_token_distinct_id_limits(
allowed: allowed_count,
limited: limited_event_count,
already_disabled: already_disabled_count,
+ already_disabled_over_budget: already_disabled_over_budget_count,
}
}
@@ -2849,7 +2867,7 @@ mod tests {
events[0].force_disable_person_processing = true;
events[0].details = Some(DETAIL_PERSON_PROCESSING_DISABLED);
- apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;
+ let tally = apply_token_distinct_id_limits(&limiter, &ctx, None, &mut events).await;
assert!(
calls
@@ -2858,6 +2876,15 @@ mod tests {
.contains(&"phc_tok:user-1".to_string()),
"already-disabled event must still charge the key's fleet count"
);
+ assert_eq!(
+ tally,
+ TokenDistinctIdTally {
+ allowed: 1,
+ limited: 0,
+ already_disabled: 1,
+ already_disabled_over_budget: 1,
+ }
+ );
// Its stamping is untouched: result stays Ok, no overflow reroute.
let flagged = find_by_did(&events, "user-1");
assert_eq!(flagged.result, EventResult::Ok);
@@ -2906,6 +2933,7 @@ mod tests {
allowed: 1,
limited: 0,
already_disabled: 1,
+ already_disabled_over_budget: 0,
}
);
// Invariant: the three tally fields account for exactly the charged
@@ -2941,6 +2969,7 @@ mod tests {
allowed: 1,
limited: 4,
already_disabled: 0,
+ already_disabled_over_budget: 0,
}
);
}