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(cymbal): attribute postgres writes (#90778)

Hugues Pouillot3b9854e24c44
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index b0650423190e..f631f3da7611 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3374,6 +3374,7 @@ dependencies = [
"httpmock",
"insta",
"metrics",
+ "metrics-util",
"mockall",
"moka",
"personhog-common",
diff --git a/rust/cymbal/Cargo.toml b/rust/cymbal/Cargo.toml
index 98f3ecf29d9c..53c31277ee59 100644
--- a/rust/cymbal/Cargo.toml
+++ b/rust/cymbal/Cargo.toml
@@ -69,6 +69,7 @@ tower.workspace = true
# For decompressing the committed native ELF test fixture
zstd = "0.13"
testcontainers = { workspace = true }
+metrics-util = { workspace = true }
[lints]
workspace = true
diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rs
index 9ffffa6c1675..5dc385a0287f 100644
--- a/rust/cymbal/src/core/metric_consts.rs
+++ b/rust/cymbal/src/core/metric_consts.rs
@@ -13,6 +13,10 @@ pub const SYMBOL_SET_DB_FETCHES: &str = "cymbal_symbol_set_db_fetches";
pub const SYMBOL_SET_DB_HITS: &str = "cymbal_symbol_set_db_hits";
pub const SYMBOL_SET_DB_MISSES: &str = "cymbal_symbol_set_db_misses";
pub const SYMBOL_SET_SAVED: &str = "cymbal_symbol_set_saved";
+// Purpose and outcome labels are fixed enums in `write_attribution` so these
+// counters can be safely grouped in Grafana and reconciled with Postgres table stats.
+pub const POSTGRES_WRITE_ATTEMPTS: &str = "cymbal_postgres_write_attempts";
+pub const POSTGRES_ROWS_AFFECTED: &str = "cymbal_postgres_rows_affected";
pub const SAVED_SYMBOL_SET_LOADED: &str = "cymbal_saved_symbol_set_loaded";
pub const SAVED_SYMBOL_SET_ERROR_RETURNED: &str = "cymbal_saved_symbol_set_error_returned";
pub const SYMBOL_SET_NEGATIVE_CACHE_HIT: &str = "cymbal_symbol_set_negative_cache_hit";
diff --git a/rust/cymbal/src/core/mod.rs b/rust/cymbal/src/core/mod.rs
index bf1a4a7ccdd9..5b935312b36f 100644
--- a/rust/cymbal/src/core/mod.rs
+++ b/rust/cymbal/src/core/mod.rs
@@ -13,3 +13,4 @@ pub mod sanitize;
pub mod shutdown;
pub mod symbolication;
pub mod types;
+pub(crate) mod write_attribution;
diff --git a/rust/cymbal/src/core/symbolication/symbol/local.rs b/rust/cymbal/src/core/symbolication/symbol/local.rs
index 225eb507e52a..b538c849a162 100644
--- a/rust/cymbal/src/core/symbolication/symbol/local.rs
+++ b/rust/cymbal/src/core/symbolication/symbol/local.rs
@@ -15,6 +15,7 @@ use sqlx::PgPool;
use crate::{
core::config::ResolverConfig,
+ core::write_attribution::{record_frame_write, FrameWriteOutcome},
error::{JsResolveErr, ProguardError, ResolveError, UnhandledError},
frames::{releases::ReleaseRecord, Frame, RawFrame},
langs::native::DebugImage,
@@ -23,7 +24,9 @@ use crate::{
RELEASE_ID_CACHE_HITS, RELEASE_ID_CACHE_MISSES, SUSPICIOUS_FRAMES_DETECTED,
},
symbolication::resolve::Resolve,
- symbolication::symbol::records::{ErrorTrackingStackFrame, FrameResultTtlPolicy},
+ symbolication::symbol::records::{
+ classify_frame_snapshot, ErrorTrackingStackFrame, FrameResultTtlPolicy,
+ },
symbolication::symbol::SymbolResolver,
symbolication::symbol_store::{
chunk_id::OrChunkId,
@@ -156,11 +159,11 @@ impl LocalSymbolResolver {
raw_id: RawFrameId,
debug_images: &[DebugImage],
) -> Result<Vec<ErrorTrackingStackFrame>, UnhandledError> {
- let loaded =
- ErrorTrackingStackFrame::load_all(&self.pool, &raw_id, self.ttl_policy).await?;
- if !loaded.is_empty() {
+ let stored =
+ ErrorTrackingStackFrame::load_snapshot(&self.pool, &raw_id, self.ttl_policy).await?;
+ if stored.fresh {
metrics::counter!(FRAME_DB_HITS).increment(1);
- return Ok(loaded);
+ return Ok(stored.records);
}
metrics::counter!(FRAME_DB_MISSES).increment(1);
@@ -186,9 +189,8 @@ impl LocalSymbolResolver {
None
};
- let mut records = Vec::new();
+ let mut records = Vec::with_capacity(resolved.len());
for r_frame in &resolved {
- // Save back to the DB
let record = ErrorTrackingStackFrame::new(
r_frame.frame_id.clone(),
set.as_ref().map(|s| s.id),
@@ -196,14 +198,25 @@ impl LocalSymbolResolver {
r_frame.resolved,
r_frame.context.clone(),
);
- record.save(&self.pool).await?;
+ records.push(record);
+ }
+
+ let write_outcome = classify_frame_snapshot(&stored.records, &records);
+ for record in &records {
+ let rows_affected = match record.save(&self.pool).await {
+ Ok(rows_affected) => rows_affected,
+ Err(error) => {
+ record_frame_write(FrameWriteOutcome::Error, 0);
+ return Err(error);
+ }
+ };
+ record_frame_write(write_outcome, rows_affected);
+
+ let r_frame = &record.contents;
if r_frame.suspicious {
metrics::counter!(SUSPICIOUS_FRAMES_DETECTED, "frame_type" => "resolved")
.increment(1);
}
-
- // And gather up for the cache
- records.push(record);
}
Ok(records)
}
diff --git a/rust/cymbal/src/core/symbolication/symbol/records.rs b/rust/cymbal/src/core/symbolication/symbol/records.rs
index 815fb0f9b2f9..75563cacd28c 100644
--- a/rust/cymbal/src/core/symbolication/symbol/records.rs
+++ b/rust/cymbal/src/core/symbolication/symbol/records.rs
@@ -5,6 +5,7 @@ use serde_json::Value;
use sqlx::Executor;
use uuid::Uuid;
+use crate::core::write_attribution::FrameWriteOutcome;
use crate::error::UnhandledError;
use crate::frames::{Context, Frame};
@@ -81,6 +82,35 @@ pub struct ErrorTrackingStackFrame {
pub context: Option<Context>,
}
+#[derive(Debug)]
+pub(crate) struct StoredFrameSnapshot {
+ pub records: Vec<ErrorTrackingStackFrame>,
+ pub fresh: bool,
+}
+
+pub(crate) fn classify_frame_snapshot(
+ existing: &[ErrorTrackingStackFrame],
+ current: &[ErrorTrackingStackFrame],
+) -> FrameWriteOutcome {
+ if existing.is_empty() {
+ return FrameWriteOutcome::Insert;
+ }
+
+ if existing.len() == current.len()
+ && existing.iter().zip(current).all(|(existing, current)| {
+ existing.id == current.id
+ && existing.symbol_set_id == current.symbol_set_id
+ && existing.contents == current.contents
+ && existing.resolved == current.resolved
+ && existing.context == current.context
+ })
+ {
+ FrameWriteOutcome::Unchanged
+ } else {
+ FrameWriteOutcome::Changed
+ }
+}
+
impl ErrorTrackingStackFrame {
pub fn new(
id: FrameId,
@@ -99,7 +129,7 @@ impl ErrorTrackingStackFrame {
}
}
- pub async fn save<'c, E>(&self, e: E) -> Result<(), UnhandledError>
+ pub async fn save<'c, E>(&self, e: E) -> Result<u64, UnhandledError>
where
E: Executor<'c, Database = sqlx::Postgres>,
{
@@ -108,7 +138,7 @@ impl ErrorTrackingStackFrame {
} else {
None
};
- sqlx::query!(
+ let result = sqlx::query!(
r#"
INSERT INTO posthog_errortrackingstackframe (raw_id, part, team_id, created_at, symbol_set_id, contents, resolved, id, context)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
@@ -128,8 +158,10 @@ impl ErrorTrackingStackFrame {
self.resolved,
Uuid::now_v7(),
context,
- ).execute(e).await?;
- Ok(())
+ )
+ .execute(e)
+ .await?;
+ Ok(result.rows_affected())
}
pub async fn load_all<'c, E>(
@@ -137,6 +169,22 @@ impl ErrorTrackingStackFrame {
id: &RawFrameId,
ttl_policy: FrameResultTtlPolicy,
) -> Result<Vec<Self>, UnhandledError>
+ where
+ E: Executor<'c, Database = sqlx::Postgres>,
+ {
+ let snapshot = Self::load_snapshot(e, id, ttl_policy).await?;
+ if snapshot.fresh {
+ Ok(snapshot.records)
+ } else {
+ Ok(Vec::new())
+ }
+ }
+
+ pub(crate) async fn load_snapshot<'c, E>(
+ e: E,
+ id: &RawFrameId,
+ ttl_policy: FrameResultTtlPolicy,
+ ) -> Result<StoredFrameSnapshot, UnhandledError>
where
E: Executor<'c, Database = sqlx::Postgres>,
{
@@ -164,17 +212,10 @@ impl ErrorTrackingStackFrame {
.fetch_all(e)
.await?;
- if res.is_empty() {
- return Ok(Vec::new());
- }
-
- let mut results = Vec::new();
let result_ttl = ttl_policy.ttl_for_resolved_status(id, res.iter().all(|f| f.resolved));
- if res.iter().any(|f| f.created_at < Utc::now() - result_ttl) {
- // If any resultant frame is too old, we should recalculate all of them
- return Ok(Vec::new());
- }
+ let fresh = !res.is_empty() && res.iter().all(|f| f.created_at >= Utc::now() - result_ttl);
+ let mut results = Vec::new();
for found in res {
// Frame ID's lose team_id when they're serialized, so we fix that up here when loading them
let frame_id = FrameId::new(found.raw_id, found.team_id, found.part);
@@ -204,7 +245,10 @@ impl ErrorTrackingStackFrame {
})
}
- Ok(results)
+ Ok(StoredFrameSnapshot {
+ records: results,
+ fresh,
+ })
}
}
@@ -262,6 +306,77 @@ mod tests {
assert_eq!(parts, (0..8).collect::<Vec<i32>>());
}
+ #[test]
+ fn durable_snapshot_classification_covers_every_persisted_field() {
+ use crate::core::write_attribution::FrameWriteOutcome;
+
+ let id = FrameId::new("raw-frame-id".to_string(), 1, 0);
+ let frame = frame_with_part(id.clone(), 0);
+ let existing = ErrorTrackingStackFrame::new(id, None, frame, true, None);
+ let current = existing.clone();
+
+ assert_eq!(
+ classify_frame_snapshot(&[], std::slice::from_ref(&current)),
+ FrameWriteOutcome::Insert
+ );
+ assert_eq!(
+ classify_frame_snapshot(
+ std::slice::from_ref(&existing),
+ std::slice::from_ref(&current),
+ ),
+ FrameWriteOutcome::Unchanged
+ );
+
+ let mut changed_created_at = current.clone();
+ changed_created_at.created_at += Duration::hours(1);
+ assert_eq!(
+ classify_frame_snapshot(
+ std::slice::from_ref(&existing),
+ std::slice::from_ref(&changed_created_at),
+ ),
+ FrameWriteOutcome::Unchanged,
+ "created_at is an observation timestamp, not durable content"
+ );
+
+ let mut variants = Vec::new();
+
+ let mut changed_contents = current.clone();
+ changed_contents.contents.mangled_name = "different".to_string();
+ variants.push(("contents", changed_contents));
+
+ let mut changed_context = current.clone();
+ changed_context.context = Some(Context {
+ before: Vec::new(),
+ line: crate::frames::ContextLine {
+ number: 1,
+ line: "changed".to_string(),
+ },
+ after: Vec::new(),
+ });
+ variants.push(("context", changed_context));
+
+ let mut changed_resolved = current.clone();
+ changed_resolved.resolved = false;
+ variants.push(("resolved", changed_resolved));
+
+ let mut changed_symbol_set = current.clone();
+ changed_symbol_set.symbol_set_id = Some(Uuid::now_v7());
+ variants.push(("symbol_set_id", changed_symbol_set));
+
+ let mut changed_part = current;
+ changed_part.id.part = 1;
+ changed_part.contents.frame_id.part = 1;
+ variants.push(("ordered parts", changed_part));
+
+ for (field, changed) in variants {
+ assert_eq!(
+ classify_frame_snapshot(std::slice::from_ref(&existing), &[changed]),
+ FrameWriteOutcome::Changed,
+ "{field}"
+ );
+ }
+ }
+
#[test]
fn ttl_policy_applies_expected_ttl_with_deterministic_jitter() {
for (name, resolved_ttl, unresolved_ttl, all_resolved, min_ttl, max_ttl) in [
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/saving.rs b/rust/cymbal/src/core/symbolication/symbol_store/saving.rs
index 0a58c31f6596..195f386b14a8 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/saving.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/saving.rs
@@ -12,6 +12,9 @@ use uuid::Uuid;
use crate::{
core::analytics::{capture_symbol_set_deleted, capture_symbol_set_saved},
+ core::write_attribution::{
+ record_symbol_set_write, PostgresMutation, SymbolSetWriteOutcome, SymbolSetWritePurpose,
+ },
error::{FrameError, ResolveError, UnhandledError},
metric_consts::{
FRAME_RESOLUTION_RESULTS_DELETED, SAVED_SYMBOL_SET_ERROR_RETURNED, SAVED_SYMBOL_SET_LOADED,
@@ -178,14 +181,33 @@ impl<F> Saving<F> {
}
// We just saved new data for this symbol set, which invalidates all our previous stack frame resolution results,
// so delete them
- let deleted: u64 = sqlx::query_scalar!(
+ let deleted_result = sqlx::query_scalar!(
r#"WITH deleted AS (DELETE FROM posthog_errortrackingstackframe WHERE symbol_set_id = $1 RETURNING *) SELECT count(*) from deleted"#,
record.id // The call to save() above ensures that this id is correct
)
.fetch_one(&self.pool)
- .await.expect("Got at least one row back").map_or(0, |v| {
- v.max(0) as u64
- });
+ .await;
+ if deleted_result.is_err() {
+ record_symbol_set_write(
+ SymbolSetWritePurpose::Invalidation,
+ SymbolSetWriteOutcome::Error,
+ PostgresMutation::Delete,
+ 0,
+ );
+ }
+ let deleted: u64 = deleted_result
+ .expect("Got at least one row back")
+ .map_or(0, |v| v.max(0) as u64);
+ record_symbol_set_write(
+ SymbolSetWritePurpose::Invalidation,
+ if deleted > 0 {
+ SymbolSetWriteOutcome::Written
+ } else {
+ SymbolSetWriteOutcome::Skipped
+ },
+ PostgresMutation::Delete,
+ deleted,
+ );
debug!(
team_id,
@@ -490,18 +512,48 @@ impl SymbolSetRecord {
.map(|l| Utc::now() - l < Duration::hours(12))
.unwrap_or_default()
{
+ record_symbol_set_write(
+ SymbolSetWritePurpose::LastUsed,
+ SymbolSetWriteOutcome::Skipped,
+ PostgresMutation::Update,
+ 0,
+ );
return Ok(());
}
let now = Utc::now();
- sqlx::query!(
+ let result = sqlx::query!(
r#"UPDATE posthog_errortrackingsymbolset SET last_used = $2 WHERE id = $1"#,
self.id,
now
)
.execute(e)
- .await?;
+ .await;
+
+ let rows_affected = match result {
+ Ok(result) => result.rows_affected(),
+ Err(error) => {
+ record_symbol_set_write(
+ SymbolSetWritePurpose::LastUsed,
+ SymbolSetWriteOutcome::Error,
+ PostgresMutation::Update,
+ 0,
+ );
+ return Err(error.into());
+ }
+ };
+
+ record_symbol_set_write(
+ SymbolSetWritePurpose::LastUsed,
+ if rows_affected > 0 {
+ SymbolSetWriteOutcome::Written
+ } else {
+ SymbolSetWriteOutcome::Skipped
+ },
+ PostgresMutation::Update,
+ rows_affected,
+ );
self.last_used = Some(now);
@@ -565,14 +617,40 @@ impl SymbolSetRecord {
.bind(&self.content_hash)
.bind(self.last_used)
.fetch_optional(e)
- .await?;
+ .await;
+
+ let id = match id {
+ Ok(id) => id,
+ Err(error) => {
+ record_symbol_set_write(
+ SymbolSetWritePurpose::Data,
+ SymbolSetWriteOutcome::Error,
+ PostgresMutation::Upsert,
+ 0,
+ );
+ return Err(error.into());
+ }
+ };
if let Some(id) = id {
self.id = id;
metrics::counter!(SYMBOL_SET_SAVED).increment(1);
+ record_symbol_set_write(
+ SymbolSetWritePurpose::Data,
+ SymbolSetWriteOutcome::Written,
+ PostgresMutation::Upsert,
+ 1,
+ );
return Ok(true);
}
+ record_symbol_set_write(
+ SymbolSetWritePurpose::Data,
+ SymbolSetWriteOutcome::Skipped,
+ PostgresMutation::Upsert,
+ 0,
+ );
+
Ok(false)
}
@@ -586,7 +664,7 @@ impl SymbolSetRecord {
E: sqlx::Executor<'c, Database = sqlx::Postgres>,
{
let truncated_ref = truncate_ref(&self.set_ref);
- if let Some(id) = sqlx::query_scalar::<_, Uuid>(
+ let id = sqlx::query_scalar::<_, Uuid>(
r#"
INSERT INTO posthog_errortrackingsymbolset (id, team_id, ref, storage_ptr, failure_reason, created_at, content_hash, last_used)
VALUES ($1, $2, $3, NULL, $4, $5, NULL, $6)
@@ -603,13 +681,40 @@ impl SymbolSetRecord {
.bind(self.created_at)
.bind(self.last_used)
.fetch_optional(e)
- .await?
- {
+ .await;
+
+ let id = match id {
+ Ok(id) => id,
+ Err(error) => {
+ record_symbol_set_write(
+ SymbolSetWritePurpose::AutomaticFailure,
+ SymbolSetWriteOutcome::Error,
+ PostgresMutation::Upsert,
+ 0,
+ );
+ return Err(error.into());
+ }
+ };
+
+ if let Some(id) = id {
self.id = id;
metrics::counter!(SYMBOL_SET_SAVED).increment(1);
+ record_symbol_set_write(
+ SymbolSetWritePurpose::AutomaticFailure,
+ SymbolSetWriteOutcome::Written,
+ PostgresMutation::Upsert,
+ 1,
+ );
return Ok(true);
}
+ record_symbol_set_write(
+ SymbolSetWritePurpose::AutomaticFailure,
+ SymbolSetWriteOutcome::Skipped,
+ PostgresMutation::Upsert,
+ 0,
+ );
+
Ok(false)
}
@@ -617,7 +722,7 @@ impl SymbolSetRecord {
where
E: sqlx::Executor<'c, Database = sqlx::Postgres>,
{
- let _ignored = sqlx::query!(
+ let result = sqlx::query!(
r#"
DELETE FROM posthog_errortrackingsymbolset WHERE id = $1
"#,
@@ -626,6 +731,28 @@ impl SymbolSetRecord {
.execute(e)
.await; // We don't really care if this fails, since it's a robustness thing anyway
+ match result {
+ Ok(result) => {
+ let rows_affected = result.rows_affected();
+ record_symbol_set_write(
+ SymbolSetWritePurpose::Cleanup,
+ if rows_affected > 0 {
+ SymbolSetWriteOutcome::Written
+ } else {
+ SymbolSetWriteOutcome::Skipped
+ },
+ PostgresMutation::Delete,
+ rows_affected,
+ );
+ }
+ Err(_) => record_symbol_set_write(
+ SymbolSetWritePurpose::Cleanup,
+ SymbolSetWriteOutcome::Error,
+ PostgresMutation::Delete,
+ 0,
+ ),
+ }
+
capture_symbol_set_deleted(self.team_id, &self.set_ref, self.storage_ptr.as_deref());
Ok(())
diff --git a/rust/cymbal/src/core/write_attribution.rs b/rust/cymbal/src/core/write_attribution.rs
new file mode 100644
index 000000000000..ca96c1083450
--- /dev/null
+++ b/rust/cymbal/src/core/write_attribution.rs
@@ -0,0 +1,266 @@
+use crate::metric_consts::{POSTGRES_ROWS_AFFECTED, POSTGRES_WRITE_ATTEMPTS};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum FrameWriteOutcome {
+ Insert,
+ Changed,
+ Unchanged,
+ Error,
+}
+
+impl FrameWriteOutcome {
+ const fn as_str(self) -> &'static str {
+ match self {
+ Self::Insert => "insert",
+ Self::Changed => "changed",
+ Self::Unchanged => "unchanged",
+ Self::Error => "error",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum SymbolSetWritePurpose {
+ Data,
+ AutomaticFailure,
+ LastUsed,
+ Invalidation,
+ Cleanup,
+}
+
+impl SymbolSetWritePurpose {
+ const fn as_str(self) -> &'static str {
+ match self {
+ Self::Data => "symbol_data",
+ Self::AutomaticFailure => "automatic_failure",
+ Self::LastUsed => "last_used",
+ Self::Invalidation => "invalidation",
+ Self::Cleanup => "cleanup",
+ }
+ }
+
+ const fn table(self) -> &'static str {
+ match self {
+ Self::Invalidation => "stack_frame",
+ Self::Data | Self::AutomaticFailure | Self::LastUsed | Self::Cleanup => "symbol_set",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum SymbolSetWriteOutcome {
+ Written,
+ Skipped,
+ Error,
+}
+
+impl SymbolSetWriteOutcome {
+ const fn as_str(self) -> &'static str {
+ match self {
+ Self::Written => "written",
+ Self::Skipped => "skipped",
+ Self::Error => "error",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum PostgresMutation {
+ Upsert,
+ Update,
+ Delete,
+}
+
+impl PostgresMutation {
+ const fn as_str(self) -> &'static str {
+ match self {
+ Self::Upsert => "upsert",
+ Self::Update => "update",
+ Self::Delete => "delete",
+ }
+ }
+}
+
+pub(crate) fn record_frame_write(outcome: FrameWriteOutcome, rows_affected: u64) {
+ metrics::counter!(
+ POSTGRES_WRITE_ATTEMPTS,
+ "table" => "stack_frame",
+ "purpose" => "frame_snapshot",
+ "outcome" => outcome.as_str(),
+ )
+ .increment(1);
+
+ record_rows_affected(
+ "stack_frame",
+ "frame_snapshot",
+ PostgresMutation::Upsert,
+ rows_affected,
+ );
+}
+
+pub(crate) fn record_symbol_set_write(
+ purpose: SymbolSetWritePurpose,
+ outcome: SymbolSetWriteOutcome,
+ mutation: PostgresMutation,
+ rows_affected: u64,
+) {
+ metrics::counter!(
+ POSTGRES_WRITE_ATTEMPTS,
+ "table" => purpose.table(),
+ "purpose" => purpose.as_str(),
+ "outcome" => outcome.as_str(),
+ )
+ .increment(1);
+
+ record_rows_affected(purpose.table(), purpose.as_str(), mutation, rows_affected);
+}
+
+fn record_rows_affected(
+ table: &'static str,
+ purpose: &'static str,
+ mutation: PostgresMutation,
+ rows_affected: u64,
+) {
+ if rows_affected == 0 {
+ return;
+ }
+
+ metrics::counter!(
+ POSTGRES_ROWS_AFFECTED,
+ "table" => table,
+ "purpose" => purpose,
+ "mutation" => mutation.as_str(),
+ )
+ .increment(rows_affected);
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashSet;
+
+ use metrics_util::debugging::DebuggingRecorder;
+
+ use super::{
+ record_frame_write, record_symbol_set_write, FrameWriteOutcome, PostgresMutation,
+ SymbolSetWriteOutcome, SymbolSetWritePurpose,
+ };
+ use crate::metric_consts::{POSTGRES_ROWS_AFFECTED, POSTGRES_WRITE_ATTEMPTS};
+
+ #[test]
+ fn write_attribution_uses_only_bounded_labels() {
+ let recorder = DebuggingRecorder::new();
+
+ metrics::with_local_recorder(&recorder, || {
+ for outcome in [
+ FrameWriteOutcome::Insert,
+ FrameWriteOutcome::Changed,
+ FrameWriteOutcome::Unchanged,
+ FrameWriteOutcome::Error,
+ ] {
+ record_frame_write(outcome, u64::from(outcome != FrameWriteOutcome::Error));
+ }
+
+ for purpose in [
+ SymbolSetWritePurpose::Data,
+ SymbolSetWritePurpose::AutomaticFailure,
+ SymbolSetWritePurpose::LastUsed,
+ SymbolSetWritePurpose::Invalidation,
+ SymbolSetWritePurpose::Cleanup,
+ ] {
+ for outcome in [
+ SymbolSetWriteOutcome::Written,
+ SymbolSetWriteOutcome::Skipped,
+ SymbolSetWriteOutcome::Error,
+ ] {
+ let mutation =
+ match purpose {
+ SymbolSetWritePurpose::Data
+ | SymbolSetWritePurpose::AutomaticFailure => PostgresMutation::Upsert,
+ SymbolSetWritePurpose::LastUsed => PostgresMutation::Update,
+ SymbolSetWritePurpose::Invalidation
+ | SymbolSetWritePurpose::Cleanup => PostgresMutation::Delete,
+ };
+ record_symbol_set_write(
+ purpose,
+ outcome,
+ mutation,
+ u64::from(outcome == SymbolSetWriteOutcome::Written),
+ );
+ }
+ }
+ });
+
+ let snapshot = recorder.snapshotter().snapshot().into_vec();
+ let attempts = snapshot
+ .iter()
+ .filter(|(key, _, _, _)| key.key().name() == POSTGRES_WRITE_ATTEMPTS)
+ .collect::<Vec<_>>();
+ let rows = snapshot
+ .iter()
+ .filter(|(key, _, _, _)| key.key().name() == POSTGRES_ROWS_AFFECTED)
+ .collect::<Vec<_>>();
+
+ assert_eq!(attempts.len(), 19);
+ assert_eq!(rows.len(), 6);
+
+ let allowed_label_keys = HashSet::from(["table", "purpose", "outcome"]);
+ let allowed_tables = HashSet::from(["stack_frame", "symbol_set"]);
+ let allowed_purposes = HashSet::from([
+ "frame_snapshot",
+ "symbol_data",
+ "automatic_failure",
+ "last_used",
+ "invalidation",
+ "cleanup",
+ ]);
+ let allowed_outcomes = HashSet::from([
+ "insert",
+ "changed",
+ "unchanged",
+ "written",
+ "skipped",
+ "error",
+ ]);
+
+ for (key, _, _, _) in attempts {
+ let labels = key
+ .key()
+ .labels()
+ .map(|label| (label.key(), label.value()))
+ .collect::<Vec<_>>();
+ assert!(labels
+ .iter()
+ .all(|(key, _)| allowed_label_keys.contains(key)));
+ assert!(labels
+ .iter()
+ .any(|(key, value)| *key == "table" && allowed_tables.contains(value)));
+ assert!(labels
+ .iter()
+ .any(|(key, value)| *key == "purpose" && allowed_purposes.contains(value)));
+ assert!(labels
+ .iter()
+ .any(|(key, value)| *key == "outcome" && allowed_outcomes.contains(value)));
+ }
+
+ let allowed_row_label_keys = HashSet::from(["table", "purpose", "mutation"]);
+ let allowed_mutations = HashSet::from(["upsert", "update", "delete"]);
+ let mut observed_mutations = HashSet::new();
+ for (key, _, _, _) in rows {
+ let labels = key
+ .key()
+ .labels()
+ .map(|label| (label.key(), label.value()))
+ .collect::<Vec<_>>();
+ assert!(labels
+ .iter()
+ .all(|(key, _)| allowed_row_label_keys.contains(key)));
+ let mutation = labels
+ .iter()
+ .find_map(|(key, value)| (*key == "mutation").then_some(*value))
+ .expect("rows metric has a mutation label");
+ assert!(allowed_mutations.contains(mutation));
+ observed_mutations.insert(mutation);
+ }
+ assert_eq!(observed_mutations, allowed_mutations);
+ }
+}