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.

44.4 KB
Raw Blame
use std::{sync::Arc, time::Duration};

use chrono::{DateTime, Utc};
use common_database::error_class;
use futures::stream::{FuturesUnordered, StreamExt};
use sqlx::PgPool;
use tokio::task::JoinHandle;
use tracing::{error, info, warn};
use uuid::Uuid;

use crate::{
    config::Config,
    metrics_consts::{
        ISSUE_FAILED, V2_BATCH_ROWS_DROPPED_FK, V2_EVENT_DEFS_BATCH_ATTEMPT,
        V2_EVENT_DEFS_BATCH_CACHE_TIME, V2_EVENT_DEFS_BATCH_ROWS_AFFECTED,
        V2_EVENT_DEFS_BATCH_SIZE, V2_EVENT_DEFS_BATCH_WRITE_TIME, V2_EVENT_DEFS_CACHE_REMOVED,
        V2_EVENT_PROPS_BATCH_ATTEMPT, V2_EVENT_PROPS_BATCH_CACHE_TIME,
        V2_EVENT_PROPS_BATCH_ROWS_AFFECTED, V2_EVENT_PROPS_BATCH_SIZE,
        V2_EVENT_PROPS_BATCH_WRITE_TIME, V2_EVENT_PROPS_CACHE_REMOVED, V2_PROP_DEFS_BATCH_ATTEMPT,
        V2_PROP_DEFS_BATCH_CACHE_TIME, V2_PROP_DEFS_BATCH_ROWS_AFFECTED, V2_PROP_DEFS_BATCH_SIZE,
        V2_PROP_DEFS_BATCH_WRITE_TIME, V2_PROP_DEFS_CACHE_REMOVED, V2_PROP_DEFS_DROPPED_UNCACHED,
    },
    types::{
        EventDefinition, EventProperty, GroupType, PropertyDefinition, PropertyParentType, Update,
    },
    update_cache::Cache,
};

const V2_BATCH_MAX_RETRY_ATTEMPTS: u64 = 3;
const V2_BATCH_RETRY_DELAY_MS: u64 = 50;
// How many distinct FK-violating tenants a single batch write will strip-and-rewrite
// around before falling back to the normal retry path. Bounds the failed-INSERT loop
// when a batch is riddled with rows for deleted teams/projects.
const V2_BATCH_MAX_FK_STRIPS: u64 = 3;

// Retains only the elements of `v` whose index holds `true` in `mask`.
fn retain_by_mask<T>(v: &mut Vec<T>, mask: &[bool]) {
    let mut idx = 0;
    v.retain(|_| {
        let keep = mask[idx];
        idx += 1;
        keep
    });
}

/// Extracts the offending column/value from a Postgres foreign-key violation
/// (SQLSTATE 23503) error detail, e.g.
/// `Key (team_id)=(522607) is not present in table "posthog_team".`
/// Returns None for any other error, or when the detail isn't a single integer
/// key (composite keys, unexpected formats) — callers then use the normal
/// retry path, so parsing can only ever narrow behavior, never break it.
fn fk_violation_key(e: &sqlx::Error) -> Option<(String, i64)> {
    let sqlx::Error::Database(db) = e else {
        return None;
    };
    if db.code().as_deref() != Some("23503") {
        return None;
    }
    let pg = db.try_downcast_ref::<sqlx::postgres::PgDatabaseError>()?;
    let rest = pg.detail()?.strip_prefix("Key (")?;
    let (column, rest) = rest.split_once(")=(")?;
    let (value, _) = rest.split_once(')')?;
    Some((column.to_string(), value.parse().ok()?))
}

// Derived hash since these are keyed on all fields in the DB
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EventPropertiesBatch {
    batch_size: usize,
    pub team_ids: Vec<i32>,
    pub project_ids: Vec<i64>,
    pub event_names: Vec<String>,
    pub property_names: Vec<String>,

    pub cached: Vec<Update>,
}

impl EventPropertiesBatch {
    pub fn new(batch_size: usize) -> Self {
        Self {
            batch_size,
            team_ids: Vec::with_capacity(batch_size),
            project_ids: Vec::with_capacity(batch_size),
            event_names: Vec::with_capacity(batch_size),
            property_names: Vec::with_capacity(batch_size),
            cached: Vec::with_capacity(batch_size),
        }
    }

    pub fn append(&mut self, ep: EventProperty) {
        self.team_ids.push(ep.team_id);
        self.project_ids.push(ep.project_id);
        self.event_names.push(ep.event.clone());
        self.property_names.push(ep.property.clone());

        self.cached.push(Update::EventProperty(ep));
    }

    pub fn len(&self) -> usize {
        self.team_ids.len()
    }

    pub fn should_flush_batch(&self) -> bool {
        self.len() >= self.batch_size
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn uncache_batch(&self, cache: &Arc<Cache>) {
        let timer = common_metrics::timing_guard(V2_EVENT_PROPS_BATCH_CACHE_TIME, &[]);

        for update in &self.cached {
            cache.remove(update);
            metrics::counter!(V2_EVENT_PROPS_CACHE_REMOVED).increment(1);
        }

        timer.fin();
    }

    // Strips rows referencing a missing FK target (deleted team/project); returns how many
    // were removed. Their `cached` entries are removed too, so a later uncache_batch can't
    // evict them from the shared dedup cache: staying cached is what stops the dead
    // tenant's events from re-issuing the same failing write.
    // Keeps only the rows whose mask entry is true; returns how many were dropped.
    pub fn retain_rows(&mut self, keep: &[bool]) -> usize {
        let removed = keep.iter().filter(|k| !**k).count();
        if removed == 0 {
            return 0;
        }
        retain_by_mask(&mut self.team_ids, keep);
        retain_by_mask(&mut self.project_ids, keep);
        retain_by_mask(&mut self.event_names, keep);
        retain_by_mask(&mut self.property_names, keep);
        retain_by_mask(&mut self.cached, keep);
        removed
    }

    pub fn remove_rows_for_fk(&mut self, column: &str, value: i64) -> usize {
        let keep: Vec<bool> = match column {
            "team_id" => self
                .team_ids
                .iter()
                .map(|id| i64::from(*id) != value)
                .collect(),
            "project_id" => self.project_ids.iter().map(|id| *id != value).collect(),
            _ => return 0,
        };
        let removed = keep.iter().filter(|k| !**k).count();
        if removed == 0 {
            return 0;
        }
        retain_by_mask(&mut self.team_ids, &keep);
        retain_by_mask(&mut self.project_ids, &keep);
        retain_by_mask(&mut self.event_names, &keep);
        retain_by_mask(&mut self.property_names, &keep);
        retain_by_mask(&mut self.cached, &keep);
        removed
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EventDefinitionsBatch {
    batch_size: usize,
    pub ids: Vec<Uuid>,
    pub names: Vec<String>,
    pub team_ids: Vec<i32>,
    pub project_ids: Vec<i64>,

    pub cached: Vec<Update>,
}

impl EventDefinitionsBatch {
    pub fn new(batch_size: usize) -> Self {
        Self {
            batch_size,
            ids: Vec::with_capacity(batch_size),
            names: Vec::with_capacity(batch_size),
            team_ids: Vec::with_capacity(batch_size),
            project_ids: Vec::with_capacity(batch_size),
            cached: Vec::with_capacity(batch_size),
        }
    }

    pub fn append(&mut self, ed: EventDefinition) {
        self.ids.push(Uuid::now_v7());
        self.names.push(ed.name.clone());
        self.team_ids.push(ed.team_id);
        self.project_ids.push(ed.project_id);

        self.cached.push(Update::Event(ed));
    }

    pub fn len(&self) -> usize {
        self.ids.len()
    }

    pub fn should_flush_batch(&self) -> bool {
        self.len() >= self.batch_size
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn uncache_batch(&self, cache: &Arc<Cache>) {
        let timer = common_metrics::timing_guard(V2_EVENT_DEFS_BATCH_CACHE_TIME, &[]);

        for update in &self.cached {
            cache.remove(update);
            metrics::counter!(V2_EVENT_DEFS_CACHE_REMOVED).increment(1);
        }

        timer.fin();
    }

    // See EventPropertiesBatch::remove_rows_for_fk.
    pub fn remove_rows_for_fk(&mut self, column: &str, value: i64) -> usize {
        let keep: Vec<bool> = match column {
            "team_id" => self
                .team_ids
                .iter()
                .map(|id| i64::from(*id) != value)
                .collect(),
            "project_id" => self.project_ids.iter().map(|id| *id != value).collect(),
            _ => return 0,
        };
        let removed = keep.iter().filter(|k| !**k).count();
        if removed == 0 {
            return 0;
        }
        retain_by_mask(&mut self.ids, &keep);
        retain_by_mask(&mut self.names, &keep);
        retain_by_mask(&mut self.team_ids, &keep);
        retain_by_mask(&mut self.project_ids, &keep);
        retain_by_mask(&mut self.cached, &keep);
        removed
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PropertyDefinitionsBatch {
    batch_size: usize,
    pub ids: Vec<Uuid>,
    pub team_ids: Vec<i32>,
    pub project_ids: Vec<i64>,
    pub names: Vec<String>,
    pub are_numerical: Vec<bool>,
    pub event_types: Vec<i16>,
    pub property_types: Vec<Option<String>>,
    pub group_type_indices: Vec<Option<i16>>,
    // note: I left off deprecated fields we null out on writes
    pub cached: Vec<Update>,
    // Group propdefs dropped for an unresolved group_type_index. They're never written, but
    // the producer already inserted them (as Unresolved) into the shared dedup cache, so we
    // evict them post-batch to avoid poisoning the cache against a later resolvable retry.
    pub dropped_unresolved: Vec<Update>,
}

impl PropertyDefinitionsBatch {
    pub fn new(batch_size: usize) -> Self {
        Self {
            batch_size,
            ids: Vec::with_capacity(batch_size),
            team_ids: Vec::with_capacity(batch_size),
            project_ids: Vec::with_capacity(batch_size),
            names: Vec::with_capacity(batch_size),
            are_numerical: Vec::with_capacity(batch_size),
            property_types: Vec::with_capacity(batch_size),
            event_types: Vec::with_capacity(batch_size),
            group_type_indices: Vec::with_capacity(batch_size),
            cached: Vec::with_capacity(batch_size),
            dropped_unresolved: Vec::new(),
        }
    }

    pub fn append(&mut self, pd: PropertyDefinition) {
        let group_type_index = match &pd.group_type_index {
            Some(GroupType::Resolved(_, i)) => Some(*i as i16),
            Some(GroupType::Unresolved(group_name)) => {
                warn!(
                    "Group type {} not resolved for property definition {} for team {}, skipping update",
                    group_name, pd.name, pd.team_id
                );
                None
            }
            _ => {
                // We don't have a group type, so we don't have a group type index
                None
            }
        };

        if group_type_index.is_none() && matches!(pd.event_type, PropertyParentType::Group) {
            // Some teams/users wildly misuse group-types, and if we fail to issue an update
            // during the transaction (which we do if we don't have a group-type index for a
            // group property), the entire transaction is aborted, so instead we just warn
            // loudly about this (above, and at resolve time), and drop the update.
            //
            // Record it so we can evict the producer's (Unresolved) shared-cache entry after
            // the batch: without this, a transient resolution miss (new group type not yet
            // visible to personhog) permanently blocks the def from ever persisting.
            self.dropped_unresolved.push(Update::Property(pd));
            return;
        }

        let property_type: Option<String> = pd.property_type.clone().map(|pvt| pvt.to_string());

        self.ids.push(Uuid::now_v7());
        self.team_ids.push(pd.team_id);
        self.project_ids.push(pd.project_id);
        self.names.push(pd.name.clone());
        self.are_numerical.push(pd.is_numerical);
        self.property_types.push(property_type);
        self.event_types.push(pd.event_type as i16);
        self.group_type_indices.push(group_type_index);

        self.cached.push(Update::Property(pd));
    }

    pub fn len(&self) -> usize {
        self.ids.len()
    }

    pub fn should_flush_batch(&self) -> bool {
        self.len() >= self.batch_size
    }

    pub fn is_empty(&self) -> bool {
        // Dropped-unresolved entries carry no write, but they still need a flush so their
        // shared-cache entries get evicted, so a batch with only drops is not "empty".
        self.len() == 0 && self.dropped_unresolved.is_empty()
    }

    // Evict the shared-cache entries for group propdefs we dropped for an unresolved
    // group_type_index. The producer inserted them as Unresolved and the resolver preserves
    // that form on a miss, so these keys match the originals directly (no revert needed).
    pub fn uncache_dropped(&self, cache: &Arc<Cache>) {
        for update in &self.dropped_unresolved {
            cache.remove(update);
            metrics::counter!(V2_PROP_DEFS_DROPPED_UNCACHED).increment(1);
        }
    }

    pub fn uncache_batch(&self, cache: &Arc<Cache>) {
        let timer = common_metrics::timing_guard(V2_PROP_DEFS_BATCH_CACHE_TIME, &[]);

        for update in &self.cached {
            // The shared dedup cache stores group property entries with
            // Unresolved group types (inserted by the producer before
            // resolution). By the time we get here the batch entries have been
            // resolved, so we must revert to Unresolved to match the cache key.
            let cache_key = match update {
                Update::Property(pd) if pd.group_type_index.is_some() => {
                    let mut reverted = pd.clone();
                    reverted.group_type_index =
                        reverted.group_type_index.map(|gt| gt.as_unresolved());
                    Update::Property(reverted)
                }
                other => other.clone(),
            };
            cache.remove(&cache_key);
            metrics::counter!(V2_PROP_DEFS_CACHE_REMOVED).increment(1);
        }

        timer.fin();
    }

    // See EventPropertiesBatch::remove_rows_for_fk. `dropped_unresolved` is untouched:
    // those entries were never part of the write.
    pub fn remove_rows_for_fk(&mut self, column: &str, value: i64) -> usize {
        let keep: Vec<bool> = match column {
            "team_id" => self
                .team_ids
                .iter()
                .map(|id| i64::from(*id) != value)
                .collect(),
            "project_id" => self.project_ids.iter().map(|id| *id != value).collect(),
            _ => return 0,
        };
        let removed = keep.iter().filter(|k| !**k).count();
        if removed == 0 {
            return 0;
        }
        self.retain_rows(&keep);
        removed
    }

    // Keeps only the rows whose mask entry is true; returns how many were dropped.
    pub fn retain_rows(&mut self, keep: &[bool]) -> usize {
        let removed = keep.iter().filter(|k| !**k).count();
        if removed == 0 {
            return 0;
        }
        retain_by_mask(&mut self.ids, keep);
        retain_by_mask(&mut self.team_ids, keep);
        retain_by_mask(&mut self.project_ids, keep);
        retain_by_mask(&mut self.names, keep);
        retain_by_mask(&mut self.are_numerical, keep);
        retain_by_mask(&mut self.event_types, keep);
        retain_by_mask(&mut self.property_types, keep);
        retain_by_mask(&mut self.group_type_indices, keep);
        retain_by_mask(&mut self.cached, keep);
        removed
    }
}

// HACK: making this public so the test suite file can live under "../tests/" dir
pub async fn process_batch(
    config: &Config,
    cache: Arc<Cache>,
    pool: &PgPool,
    read_pool: Option<PgPool>,
    batch: Vec<Update>,
    handle: &lifecycle::Handle,
) {
    let read_budget = std::time::Duration::from_millis(config.read_before_write_timeout_ms);
    // prep reshaped, isolated data batch bufffers and async join handles
    let mut event_defs = EventDefinitionsBatch::new(config.write_batch_size);
    let mut event_props = EventPropertiesBatch::new(config.write_batch_size);
    let mut prop_defs = PropertyDefinitionsBatch::new(config.write_batch_size);
    let mut handles: Vec<JoinHandle<Result<(), sqlx::Error>>> = vec![];

    // loop over Update batch, grouping by record type into single-target-table
    // batches for async write attempts with retries
    for update in batch {
        match update {
            Update::Event(ed) => {
                event_defs.append(ed);
                if event_defs.should_flush_batch() {
                    let pool = pool.clone();
                    let cache = cache.clone();
                    let outbound = event_defs;
                    event_defs = EventDefinitionsBatch::new(config.write_batch_size);
                    handles.push(tokio::spawn(async move {
                        write_event_definitions_batch(cache, outbound, &pool).await
                    }));
                }
            }
            Update::EventProperty(ep) => {
                event_props.append(ep);
                if event_props.should_flush_batch() {
                    let pool = pool.clone();
                    let cache = cache.clone();
                    let mut outbound = event_props;
                    event_props = EventPropertiesBatch::new(config.write_batch_size);
                    let read_pool = read_pool.clone();
                    handles.push(tokio::spawn(async move {
                        if let Some(rp) = &read_pool {
                            crate::read_filter::filter_event_properties(
                                rp,
                                &mut outbound,
                                read_budget,
                            )
                            .await;
                        }
                        if outbound.is_empty() {
                            return Ok(());
                        }
                        write_event_properties_batch(cache, outbound, &pool).await
                    }));
                }
            }
            Update::Property(pd) => {
                prop_defs.append(pd);
                if prop_defs.should_flush_batch() {
                    let pool = pool.clone();
                    let cache = cache.clone();
                    let mut outbound = prop_defs;
                    prop_defs = PropertyDefinitionsBatch::new(config.write_batch_size);
                    let read_pool = read_pool.clone();
                    handles.push(tokio::spawn(async move {
                        if let Some(rp) = &read_pool {
                            crate::read_filter::filter_property_definitions(
                                rp,
                                &cache,
                                &mut outbound,
                                read_budget,
                            )
                            .await;
                        }
                        if outbound.is_empty() {
                            return Ok(());
                        }
                        write_property_definitions_batch(cache, outbound, &pool).await
                    }));
                }
            }
        }
    }

    // ensure partial batches are flushed to Postgres too
    if !event_defs.is_empty() {
        let pool = pool.clone();
        let cache = cache.clone();
        handles.push(tokio::spawn(async move {
            write_event_definitions_batch(cache, event_defs, &pool).await
        }));
    }
    if !prop_defs.is_empty() {
        let pool = pool.clone();
        let cache = cache.clone();
        let read_pool = read_pool.clone();
        handles.push(tokio::spawn(async move {
            let mut prop_defs = prop_defs;
            if let Some(rp) = &read_pool {
                crate::read_filter::filter_property_definitions(
                    rp,
                    &cache,
                    &mut prop_defs,
                    read_budget,
                )
                .await;
            }
            if prop_defs.is_empty() {
                return Ok(());
            }
            write_property_definitions_batch(cache, prop_defs, &pool).await
        }));
    }
    if !event_props.is_empty() {
        let pool = pool.clone();
        let cache = cache.clone();
        let read_pool = read_pool.clone();
        handles.push(tokio::spawn(async move {
            let mut event_props = event_props;
            if let Some(rp) = &read_pool {
                crate::read_filter::filter_event_properties(rp, &mut event_props, read_budget)
                    .await;
            }
            if event_props.is_empty() {
                return Ok(());
            }
            write_event_properties_batch(cache, event_props, &pool).await
        }));
    }

    // Drain the chunk writes as they complete, beating the consumer heartbeat on each
    // completion. Heartbeats track real progress: a long batch of slow-but-advancing
    // writes no longer trips the lifecycle stall detector, while a wedged consumer
    // (no chunk completing within the liveness deadline) still does.
    let mut in_flight: FuturesUnordered<_> = handles.into_iter().collect();
    while let Some(result) = in_flight.next().await {
        handle.report_healthy();
        match result {
            Ok(batch_result) => match batch_result {
                Ok(_) => continue,
                // fanned-out write attempts are instrumented locally w/more detail, so we
                // only publish the global error metric here. `class` separates a failover
                // (`read_only`) from routine deadlocks and timeouts; `reason` stays as-is
                // because hand-managed Grafana panels select on `reason="failed"`.
                Err(e) => {
                    metrics::counter!(
                        ISSUE_FAILED,
                        &[("reason", "failed"), ("class", error_class(&e))]
                    )
                    .increment(1);
                }
            },
            Err(join_err) => {
                warn!("Batch query JoinError: {:?}", join_err);
            }
        }
    }
}

async fn write_event_properties_batch(
    cache: Arc<Cache>,
    mut batch: EventPropertiesBatch,
    pool: &PgPool,
) -> Result<(), sqlx::Error> {
    let total_time = common_metrics::timing_guard(V2_EVENT_PROPS_BATCH_WRITE_TIME, &[]);
    let mut tries = 1;
    let mut fk_strips: u64 = 0;

    loop {
        let result = sqlx::query(
            r#"
            INSERT INTO posthog_eventproperty (event, property, team_id, project_id)
                (SELECT * FROM UNNEST(
                    $1::text[],
                    $2::text[],
                    $3::int[],
                    $4::bigint[])) ON CONFLICT DO NOTHING"#,
        )
        .bind(&batch.event_names)
        .bind(&batch.property_names)
        .bind(&batch.team_ids)
        .bind(&batch.project_ids)
        .execute(pool)
        .await;

        match result {
            Err(e) => {
                // Rows referencing a deleted team/project can never be written; strip them
                // (they stay cached, suppressing future re-issues) and rewrite the survivors.
                // Unparseable FK errors, no matching rows, or an exhausted strip budget all
                // fall through to the normal retry path below, so parsing can only ever
                // narrow behavior, never change it.
                if fk_strips < V2_BATCH_MAX_FK_STRIPS {
                    if let Some((column, value)) = fk_violation_key(&e) {
                        let removed = batch.remove_rows_for_fk(&column, value);
                        if removed > 0 {
                            fk_strips += 1;
                            metrics::counter!(
                                V2_EVENT_PROPS_BATCH_ATTEMPT,
                                &[("result", "dropped_fk")]
                            )
                            .increment(1);
                            metrics::counter!(V2_BATCH_ROWS_DROPPED_FK, &[("table", "eventprops")])
                                .increment(removed as u64);
                            warn!(
                                "Dropped {removed} event property rows referencing missing {column}={value}"
                            );
                            if batch.is_empty() {
                                metrics::counter!(
                                    V2_EVENT_PROPS_BATCH_ATTEMPT,
                                    &[("result", "emptied_fk")]
                                )
                                .increment(1);
                                total_time.fin();
                                return Ok(());
                            }
                            continue;
                        }
                    }
                }

                if tries == V2_BATCH_MAX_RETRY_ATTEMPTS {
                    metrics::counter!(V2_EVENT_PROPS_BATCH_ATTEMPT, &[("result", "failed")])
                        .increment(1);
                    total_time.fin();
                    error!(
                        "Batch write to posthog_eventproperty exhausted retries: {:?}",
                        &e
                    );

                    // following the old strategy - if the batch write fails,
                    // remove all entries from cache so they get another shot
                    // at persisting on future event submissions
                    batch.uncache_batch(&cache);

                    return Err(e);
                }

                metrics::counter!(V2_EVENT_PROPS_BATCH_ATTEMPT, &[("result", "retry")])
                    .increment(1);
                let jitter = rand::random::<u64>() % 50;
                let delay: u64 = tries * V2_BATCH_RETRY_DELAY_MS + jitter;
                tokio::time::sleep(Duration::from_millis(delay)).await;
                tries += 1;
            }

            Ok(pgq_result) => {
                let count = pgq_result.rows_affected();
                total_time.fin();

                metrics::counter!(V2_EVENT_PROPS_BATCH_ATTEMPT, &[("result", "success")])
                    .increment(1);
                metrics::counter!(V2_EVENT_PROPS_BATCH_SIZE).increment(batch.len() as u64);
                metrics::counter!(V2_EVENT_PROPS_BATCH_ROWS_AFFECTED).increment(count);
                info!(
                    "Event properties batch of size {} written successfully with {} rows changed",
                    batch.len(),
                    count
                );

                return Ok(());
            }
        }
    }
}

async fn write_property_definitions_batch(
    cache: Arc<Cache>,
    mut batch: PropertyDefinitionsBatch,
    pool: &PgPool,
) -> Result<(), sqlx::Error> {
    let mut tries: u64 = 1;
    let mut fk_strips: u64 = 0;

    // A batch may contain only dropped-unresolved entries (nothing to write). Skip the empty
    // INSERT but still evict those poisoned shared-cache entries so they can be retried.
    // Not `is_empty()`: that intentionally returns false when only drops are present (they
    // still need a flush to evict); here we specifically mean "no writable rows".
    #[allow(clippy::len_zero)]
    if batch.len() == 0 {
        batch.uncache_dropped(&cache);
        metrics::counter!(V2_PROP_DEFS_BATCH_ATTEMPT, &[("result", "noop")]).increment(1);
        return Ok(());
    }

    // Started only once there are rows to write. Opening it above the early return would record a
    // near-zero sample for a batch that issues no SQL at all, which drags down a histogram whose
    // whole purpose is characterizing Postgres write latency.
    let total_time = common_metrics::timing_guard(V2_PROP_DEFS_BATCH_WRITE_TIME, &[]);

    loop {
        // what if we just ditch properties without a property_type set? why update on conflict at all?
        //
        // SELECT DISTINCT ON collapses rows that share the ON CONFLICT key before they reach the
        // insert, so a property name repeated within one batch (e.g. `brand` seen as None then
        // Numeric) can't make Postgres raise "ON CONFLICT DO UPDATE command cannot affect row a
        // second time" (SQLSTATE 21000) and roll back the whole batch. The ORDER BY
        // must lead with the DISTINCT ON keys; the trailing keys make the surviving row deterministic
        // and pick the most useful one to write - a non-null property_type (then is_numerical),
        // mirroring the DO UPDATE that only fills a NULL property_type.
        //
        // The DO UPDATE guard checks both sides of the conflict on purpose. Testing only the
        // stored row means an already-known untyped property still fires the UPDATE, writing
        // property_type NULL over NULL and is_numerical false over false: a new tuple version
        // carrying no new information, plus index maintenance, on by far the most common path
        // through this statement. Requiring EXCLUDED.property_type to be non-null keeps only
        // the writes that actually resolve a type. is_numerical needs no separate check because
        // it is derived from property_type (see `into_updates` in types.rs), so an incoming NULL
        // type always carries is_numerical false and can never be the new information.
        let result = sqlx::query(r#"
            INSERT INTO posthog_propertydefinition (id, name, type, group_type_index, is_numerical, team_id, project_id, property_type)
                SELECT DISTINCT ON (COALESCE(project_id, team_id::bigint), name, type, COALESCE(group_type_index, -1))
                    id, name, type, group_type_index, is_numerical, team_id, project_id, property_type
                FROM UNNEST(
                    $1::uuid[],
                    $2::varchar[],
                    $3::smallint[],
                    $4::smallint[],
                    $5::boolean[],
                    $6::int[],
                    $7::bigint[],
                    $8::varchar[])
                    AS t(id, name, type, group_type_index, is_numerical, team_id, project_id, property_type)
                ORDER BY
                    COALESCE(project_id, team_id::bigint), name, type, COALESCE(group_type_index, -1),
                    (property_type IS NOT NULL) DESC, is_numerical DESC
                ON CONFLICT (
                    COALESCE(project_id, team_id::bigint), name, type,
                    COALESCE(group_type_index, -1))
                DO UPDATE SET
                    property_type=EXCLUDED.property_type,
                    is_numerical=EXCLUDED.is_numerical
                WHERE posthog_propertydefinition.property_type IS NULL
                    AND EXCLUDED.property_type IS NOT NULL"#,
            )
            .bind(&batch.ids)
            .bind(&batch.names)
            .bind(&batch.event_types)
            .bind(&batch.group_type_indices)
            .bind(&batch.are_numerical)
            .bind(&batch.team_ids)
            .bind(&batch.project_ids)
            .bind(&batch.property_types)
            .execute(pool).await;

        match result {
            Err(e) => {
                // Rows referencing a deleted team/project can never be written; strip them
                // (they stay cached, suppressing future re-issues) and rewrite the survivors.
                // Unparseable FK errors, no matching rows, or an exhausted strip budget all
                // fall through to the normal retry path below, so parsing can only ever
                // narrow behavior, never change it.
                if fk_strips < V2_BATCH_MAX_FK_STRIPS {
                    if let Some((column, value)) = fk_violation_key(&e) {
                        let removed = batch.remove_rows_for_fk(&column, value);
                        if removed > 0 {
                            fk_strips += 1;
                            metrics::counter!(
                                V2_PROP_DEFS_BATCH_ATTEMPT,
                                &[("result", "dropped_fk")]
                            )
                            .increment(1);
                            metrics::counter!(V2_BATCH_ROWS_DROPPED_FK, &[("table", "propdefs")])
                                .increment(removed as u64);
                            warn!(
                                "Dropped {removed} property definition rows referencing missing {column}={value}"
                            );
                            // Not `is_empty()`: that returns false when only dropped-unresolved
                            // entries remain, and here we mean "no writable rows left".
                            #[allow(clippy::len_zero)]
                            if batch.len() == 0 {
                                metrics::counter!(
                                    V2_PROP_DEFS_BATCH_ATTEMPT,
                                    &[("result", "emptied_fk")]
                                )
                                .increment(1);
                                total_time.fin();
                                batch.uncache_dropped(&cache);
                                return Ok(());
                            }
                            continue;
                        }
                    }
                }

                if tries == V2_BATCH_MAX_RETRY_ATTEMPTS {
                    metrics::counter!(V2_PROP_DEFS_BATCH_ATTEMPT, &[("result", "failed")])
                        .increment(1);
                    total_time.fin();
                    error!(
                        "Batch write to posthog_propertydefinition exhausted retries: {:?}",
                        &e
                    );

                    // following the old strategy - if the batch write fails,
                    // remove all entries from cache so they get another shot
                    // at persisting on future event submissions
                    batch.uncache_batch(&cache);
                    batch.uncache_dropped(&cache);

                    return Err(e);
                }

                metrics::counter!(V2_PROP_DEFS_BATCH_ATTEMPT, &[("result", "retry")]).increment(1);
                let jitter = rand::random::<u64>() % 50;
                let delay: u64 = tries * V2_BATCH_RETRY_DELAY_MS + jitter;
                tokio::time::sleep(Duration::from_millis(delay)).await;
                tries += 1;
            }

            Ok(pgq_result) => {
                let count = pgq_result.rows_affected();
                total_time.fin();

                metrics::counter!(V2_PROP_DEFS_BATCH_ATTEMPT, &[("result", "success")])
                    .increment(1);
                metrics::counter!(V2_PROP_DEFS_BATCH_SIZE).increment(batch.len() as u64);
                metrics::counter!(V2_PROP_DEFS_BATCH_ROWS_AFFECTED).increment(count);
                info!(
                    "Property definitions batch of size {} written successfully with {} rows changed",
                    batch.len(),
                    count
                );

                // Dropped group propdefs were never written; evict their (Unresolved) shared-cache
                // entries so a later, now-resolvable $groupidentify is not filtered out.
                batch.uncache_dropped(&cache);

                return Ok(());
            }
        }
    }
}

async fn write_event_definitions_batch(
    cache: Arc<Cache>,
    mut batch: EventDefinitionsBatch,
    pool: &PgPool,
) -> Result<(), sqlx::Error> {
    let total_time = common_metrics::timing_guard(V2_EVENT_DEFS_BATCH_WRITE_TIME, &[]);
    let mut tries: u64 = 1;
    let mut fk_strips: u64 = 0;

    loop {
        // The floored last_seen_at on EventDefinition is a dedup-cache key, not the value we
        // store. Generate a fresh timestamp per attempt so the value shown in the UI is accurate,
        // and so a retry cannot replay a stale one and trip PG 21000 (constraint violation)
        // without a transaction wrapper to roll it back.
        let mut per_attempt_last_seen_ats: Vec<DateTime<Utc>> = Vec::with_capacity(batch.len());
        let per_attempt_ts = Utc::now();
        for _ in 0..batch.len() {
            per_attempt_last_seen_ats.push(per_attempt_ts);
        }

        // TODO: see if we can eliminate last_seen_at from being exposed in the UI,
        // then convert this stmt to ON CONFLICT DO NOTHING
        //
        // SELECT DISTINCT ON collapses rows that share the ON CONFLICT key before they reach the
        // insert, so an event name repeated within one batch can't make Postgres raise "ON CONFLICT
        // DO UPDATE command cannot affect row a second time" (SQLSTATE 21000) and roll back the whole
        // batch. last_seen_at is bound to a single per-attempt timestamp for every
        // row above, so the ORDER BY tiebreak is a no-op today, but keeps the survivor deterministic.
        let result = sqlx::query(
            r#"
            INSERT INTO posthog_eventdefinition (id, name, team_id, project_id, last_seen_at, created_at)
                SELECT DISTINCT ON (COALESCE(project_id, team_id::bigint), name)
                    id, name, team_id, project_id, last_seen_at, created_at
                FROM UNNEST (
                    $1::uuid[],
                    $2::varchar[],
                    $3::int[],
                    $4::bigint[],
                    $5::timestamptz[],
                    $5::timestamptz[])
                    AS t(id, name, team_id, project_id, last_seen_at, created_at)
                ORDER BY COALESCE(project_id, team_id::bigint), name, last_seen_at DESC
                ON CONFLICT (coalesce(project_id, team_id::bigint), name) DO UPDATE
                    SET last_seen_at=EXCLUDED.last_seen_at,
                        created_at=COALESCE(posthog_eventdefinition.created_at, EXCLUDED.created_at)
                    WHERE posthog_eventdefinition.last_seen_at IS NULL OR posthog_eventdefinition.last_seen_at < EXCLUDED.last_seen_at"#,
        )
        .bind(&batch.ids)
        .bind(&batch.names)
        .bind(&batch.team_ids)
        .bind(&batch.project_ids)
        .bind(per_attempt_last_seen_ats)
        .execute(pool)
        .await;

        match result {
            Err(e) => {
                // Rows referencing a deleted team/project can never be written; strip them
                // (they stay cached, suppressing future re-issues) and rewrite the survivors.
                // Unparseable FK errors, no matching rows, or an exhausted strip budget all
                // fall through to the normal retry path below, so parsing can only ever
                // narrow behavior, never change it.
                if fk_strips < V2_BATCH_MAX_FK_STRIPS {
                    if let Some((column, value)) = fk_violation_key(&e) {
                        let removed = batch.remove_rows_for_fk(&column, value);
                        if removed > 0 {
                            fk_strips += 1;
                            metrics::counter!(
                                V2_EVENT_DEFS_BATCH_ATTEMPT,
                                &[("result", "dropped_fk")]
                            )
                            .increment(1);
                            metrics::counter!(V2_BATCH_ROWS_DROPPED_FK, &[("table", "eventdefs")])
                                .increment(removed as u64);
                            warn!(
                                "Dropped {removed} event definition rows referencing missing {column}={value}"
                            );
                            if batch.is_empty() {
                                metrics::counter!(
                                    V2_EVENT_DEFS_BATCH_ATTEMPT,
                                    &[("result", "emptied_fk")]
                                )
                                .increment(1);
                                total_time.fin();
                                return Ok(());
                            }
                            continue;
                        }
                    }
                }

                if tries == V2_BATCH_MAX_RETRY_ATTEMPTS {
                    metrics::counter!(V2_EVENT_DEFS_BATCH_ATTEMPT, &[("result", "failed")])
                        .increment(1);
                    total_time.fin();
                    error!(
                        "Batch write to posthog_eventdefinition exhausted retries: {:?}",
                        &e
                    );

                    // following the old strategy - if the batch write fails,
                    // remove all entries from cache so they get another shot
                    // at persisting on future event submissions
                    batch.uncache_batch(&cache);

                    return Err(e);
                }

                metrics::counter!(V2_EVENT_DEFS_BATCH_ATTEMPT, &[("result", "retry")]).increment(1);
                let jitter = rand::random::<u64>() % 50;
                let delay: u64 = tries * V2_BATCH_RETRY_DELAY_MS + jitter;
                tokio::time::sleep(Duration::from_millis(delay)).await;
                tries += 1;
            }
            Ok(pgq_result) => {
                let count = pgq_result.rows_affected();
                total_time.fin();

                metrics::counter!(V2_EVENT_DEFS_BATCH_ATTEMPT, &[("result", "success")])
                    .increment(1);
                metrics::counter!(V2_EVENT_DEFS_BATCH_SIZE).increment(batch.len() as u64);
                metrics::counter!(V2_EVENT_DEFS_BATCH_ROWS_AFFECTED).increment(count);
                info!(
                    "Event definitions batch of size {} written successfully with {} rows changed",
                    batch.len(),
                    count
                );

                return Ok(());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{GroupType, PropertyDefinition, PropertyParentType};

    fn group_pd(team_id: i32, group_name: &str, prop: &str) -> PropertyDefinition {
        PropertyDefinition {
            team_id,
            project_id: team_id as i64,
            name: prop.to_string(),
            is_numerical: false,
            property_type: None,
            event_type: PropertyParentType::Group,
            group_type_index: Some(GroupType::Unresolved(group_name.to_string())),
        }
    }

    #[test]
    fn unresolved_group_pd_is_dropped_and_recorded_for_eviction() {
        let mut batch = PropertyDefinitionsBatch::new(100);
        batch.append(group_pd(1, "org", "seats"));

        // Nothing to write (the CHECK constraint forbids a NULL group_type_index)...
        assert_eq!(batch.len(), 0);
        assert!(batch.cached.is_empty());
        // ...but it's recorded so its shared-cache entry gets evicted, and a drop-only batch
        // must still flush.
        assert_eq!(batch.dropped_unresolved.len(), 1);
        assert!(!batch.is_empty());
    }

    #[test]
    fn uncache_dropped_evicts_the_producer_inserted_key() {
        let cache = Arc::new(Cache::new(10, 10, 10));
        let pd = group_pd(1, "org", "seats");

        // The producer inserts the Unresolved form before resolution runs.
        cache.insert(Update::Property(pd.clone()));
        assert!(cache.contains_key(&Update::Property(pd.clone())));

        let mut batch = PropertyDefinitionsBatch::new(100);
        batch.append(pd.clone());
        batch.uncache_dropped(&cache);

        // The poisoned entry is gone, so a later resolvable $groupidentify won't be filtered.
        assert!(!cache.contains_key(&Update::Property(pd)));
    }

    #[test]
    fn resolved_group_pd_is_written_not_dropped() {
        let mut batch = PropertyDefinitionsBatch::new(100);
        let mut pd = group_pd(1, "org", "seats");
        pd.group_type_index = Some(GroupType::Resolved("org".to_string(), 2));
        batch.append(pd);

        assert_eq!(batch.len(), 1);
        assert!(batch.dropped_unresolved.is_empty());
        assert_eq!(batch.group_type_indices, vec![Some(2)]);
    }

    fn event_prop(team_id: i32, prop: &str) -> EventProperty {
        EventProperty {
            team_id,
            project_id: team_id as i64,
            event: "$pageview".to_string(),
            property: prop.to_string(),
        }
    }

    // UNNEST pads mismatched input arrays with NULLs instead of erroring, so a desync
    // between the parallel vecs would corrupt writes silently. Guard that a strip keeps
    // every vec (including `cached`) aligned, across both FK columns.
    #[test]
    fn remove_rows_for_fk_keeps_parallel_vecs_aligned() {
        for column in ["team_id", "project_id"] {
            let mut batch = EventPropertiesBatch::new(100);
            batch.append(event_prop(1, "a"));
            batch.append(event_prop(999, "b"));
            batch.append(event_prop(1, "c"));
            batch.append(event_prop(999, "d"));

            assert_eq!(batch.remove_rows_for_fk(column, 999), 2);
            assert_eq!(batch.len(), 2);
            assert_eq!(batch.team_ids, vec![1, 1]);
            assert_eq!(batch.project_ids, vec![1, 1]);
            assert_eq!(batch.property_names, vec!["a", "c"]);
            assert_eq!(batch.event_names.len(), 2);
            assert_eq!(batch.cached.len(), 2);
        }
    }

    #[test]
    fn remove_rows_for_fk_ignores_unknown_columns_and_missing_values() {
        let mut batch = EventPropertiesBatch::new(100);
        batch.append(event_prop(1, "a"));

        // an FK column we don't carry (e.g. a composite or exotic constraint) strips nothing
        assert_eq!(batch.remove_rows_for_fk("organization_id", 1), 0);
        // and neither does a value no row references
        assert_eq!(batch.remove_rows_for_fk("team_id", 42), 0);
        assert_eq!(batch.len(), 1);
    }
}