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.

90.0 KB
Raw Blame
//! The merge saga's step handlers.
//!
//! Steps run in order: `started → claimed → sources_sealed →
//! document_folded → flipped → completed`. `aborted` is reachable from
//! every handler up to and including the fold; the flip is the point of
//! no return, after which the op can only complete (or park on a
//! definitive leader refusal).
//!
//! Two rules make every step safe to re-run (the engine's lease is a
//! throttle, not a lock, so any step may execute more than once):
//!
//! - Each step commits its Postgres work in the same transaction as its
//!   step advance, so a lost step CAS rolls the work back with it.
//! - Leader calls (fence, fold, release) cannot roll back with a lost
//!   CAS, so every leader call is convergent under repetition: a re-run
//!   step re-issues the call and lands in the same state.
//!
//! The driver receives a MergePersons call's classified two-person set:
//! source distinct ids that resolved to a live person distinct from the
//! target's. That classification is advisory. The claim step re-resolves
//! everything authoritatively inside its own transaction, because the
//! world can change between the handler and the saga.
//!
//! Durable per-op state beyond the step column lives on the op's
//! `lifecycle_op_person` rows. Source rows use the JSONB columns as the
//! schema intends: `sealed` freezes the fence snapshot, `moved` records
//! the repointed mapping rows for later ClickHouse emission (delete
//! parity). The target row's columns are repurposed as the op's scratch
//! anchor, which is safe because a target is never fenced (`sealed` is
//! otherwise unused) and a target's dids never move (`moved` is
//! otherwise unused): `moved` holds the per-did claim dispositions and
//! `sealed` holds the folded survivor document.

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use common_sqlx_macros::{mirrored_query, mirrored_query_as, mirrored_query_scalar};
use futures::stream::{self, StreamExt};
use personhog_common::persons::{person_uuid, COOKIELESS_SENTINEL_VALUE};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tonic::{Code, Status};
use uuid::Uuid;

use personhog_proto::personhog::types::v1::{
    FencePersonRequest, FoldPersonDocumentRequest, LifecycleOpType, Person, ReleaseFenceRequest,
    ReleaseOutcome, SealedSourceSnapshot,
};

use crate::config::{IdentityTables, OutboxWrites};
use crate::leader::LifecycleLeader;
use crate::lifecycle::detach::DetachedDrives;
use crate::lifecycle::engine::{
    abort_op_in_tx, advance_step_in_tx, complete_op_in_tx, Engine, OpDriver, OpRow, SagaError, Tx,
    STEP_ABORTED, STEP_COMPLETED,
};
use crate::pools::{IdentityPools, Lane};
use crate::warnings::{effective_event_uuid, MergePair, MergeWarnings, MERGE_SAGA};
use personhog_common::query_tag;

// Derived from the shared enum so the op-type string cannot drift from
// the leader's fence records or the lifecycle_op CHECK constraint.
pub const OP_TYPE_MERGE: &str = LifecycleOpType::Merge.as_op_type_str();

/// The merge saga's non-terminal steps, in order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MergeStep {
    Started,
    Claimed,
    SourcesSealed,
    DocumentFolded,
    Flipped,
}

impl MergeStep {
    pub fn as_str(self) -> &'static str {
        match self {
            MergeStep::Started => "started",
            MergeStep::Claimed => "claimed",
            MergeStep::SourcesSealed => "sources_sealed",
            MergeStep::DocumentFolded => "document_folded",
            MergeStep::Flipped => "flipped",
        }
    }

    fn parse(step: &str) -> Option<Self> {
        match step {
            "started" => Some(MergeStep::Started),
            "claimed" => Some(MergeStep::Claimed),
            "sources_sealed" => Some(MergeStep::SourcesSealed),
            "document_folded" => Some(MergeStep::DocumentFolded),
            "flipped" => Some(MergeStep::Flipped),
            _ => None,
        }
    }
}

/// The frozen `lifecycle_op.request` payload for a merge op: the
/// two-person set the handler classified, plus the merge event's
/// property payloads.
/// `sources` order is property precedence (earlier beats later).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeRequest {
    pub target_distinct_id: String,
    pub sources: Vec<MergeSourceEntry>,
    #[serde(default)]
    pub event_set: Value,
    #[serde(default)]
    pub event_set_once: Value,
    /// `$merge_dangerously` legally merges identified sources; `$identify`
    /// does not.
    #[serde(default)]
    pub allow_identified_sources: bool,
    /// Per-source distinct-id count guard. Required: an unlimited merge
    /// would make the flip's repoint an unbounded statement.
    pub move_limit: i64,
    /// The event that asked for this merge, recorded as $creator_event_uuid
    /// on a person this call's establishment births. Skipped when empty so
    /// older frozen rows compare equal.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub creator_event_uuid: String,
    /// Establishment birthed the target, so the fold and the abort delivery
    /// stamp its creating event (a recycled source can complete a born fold).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub target_born: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeSourceEntry {
    pub distinct_id: String,
    /// The `$identify` event that contributed this pair; carried for the
    /// caller's warning correlation, unused by the saga itself.
    #[serde(default)]
    pub event_uuid: String,
}

/// Whether another driver advanced or settled the op past our step.
async fn op_moved_on(
    pools: &IdentityPools,
    tables: &IdentityTables,
    op: &OpRow,
) -> Result<bool, SagaError> {
    let current = mirrored_query_as!(
        OpProgress,
        tables.is_validation(),
        op = "merge_op_moved_on",
        r#"SELECT step, completed_at IS NOT NULL AS "completed!" FROM {lifecycle_op} WHERE op_id = $1"#,
        op.op_id
        => fetch_optional(pools.fast())
    )?;
    Ok(match current {
        // A vanished row was completed and garbage-collected.
        None => true,
        Some(row) => row.completed || row.step != op.step,
    })
}

struct OpProgress {
    step: String,
    completed: bool,
}

struct PersonRef {
    person_id: i64,
    person_uuid: Uuid,
}

struct PersonStatus {
    person_id: i64,
    status: String,
}

/// A sealed source row. `ordinal` and `sealed` are set before any reader
/// selects on `status = sealed`, so a NULL decodes as the corrupt state it is.
struct SealedSource {
    person_id: i64,
    person_uuid: Uuid,
    ordinal: i32,
    sealed: Value,
}

/// The recorded `lifecycle_op.outcome` payload: one entry per requested
/// source distinct id, in request order, plus the survivor document when
/// the merge committed.
#[derive(Debug, Serialize, Deserialize)]
pub struct MergeOutcome {
    pub aborted: bool,
    /// The folded survivor document (id, uuid, properties, created_at,
    /// is_identified, version). Absent when the op aborted.
    pub survivor: Option<Value>,
    pub results: Vec<MergeSourceRecord>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct MergeSourceRecord {
    pub distinct_id: String,
    pub outcome: String,
    /// Defaulted so rows written before the field existed replay as `None`.
    #[serde(default)]
    pub person_id: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub person_uuid: Option<Uuid>,
}

pub const OUTCOME_MERGED: &str = "merged";
pub const OUTCOME_NOOP_SAME_PERSON: &str = "noop_same_person";
pub const OUTCOME_SKIPPED_ALREADY_IDENTIFIED: &str = "skipped_already_identified";
pub const OUTCOME_SKIPPED_CONFLICT: &str = "skipped_conflict";
pub const OUTCOME_SKIPPED_MOVE_LIMIT: &str = "skipped_move_limit";
pub const OUTCOME_SKIPPED_REFUSED: &str = "skipped_refused";

#[derive(Clone, Copy)]
enum AbortOutcome {
    /// Claim contention: another live op held a person. Unsettled.
    Conflict,
    /// A definitive leader refusal: retrying meets the same answer.
    Refused,
}

impl AbortOutcome {
    fn as_str(self) -> &'static str {
        match self {
            AbortOutcome::Conflict => OUTCOME_SKIPPED_CONFLICT,
            AbortOutcome::Refused => OUTCOME_SKIPPED_REFUSED,
        }
    }
}
pub const OUTCOME_ERROR: &str = "error";
/// Handler-decided outcomes that never reach the saga.
pub const OUTCOME_SKIPPED_ILLEGAL: &str = "skipped_illegal";
pub const OUTCOME_ATTACHED: &str = "attached";

/// Per-person row statuses this driver writes. `marked`/`sealed` are the
/// mark-covered set (the partial unique index); everything else releases
/// the mark. `dropped` and `aborted` are merge-specific settlements the
/// schema comment does not list — the column is unconstrained TEXT and the
/// mark index only cares that they are outside `('marked','sealed')`.
const STATUS_MARKED: &str = "marked";
const STATUS_SEALED: &str = "sealed";
const STATUS_DELETED: &str = "deleted";
const STATUS_CLEARED: &str = "cleared";
const STATUS_DROPPED: &str = "dropped";
const STATUS_ABORTED: &str = "aborted";
const STATUS_SKIPPED_CONFLICT: &str = "skipped_conflict";

const ROLE_TARGET: &str = "target";
const ROLE_SOURCE: &str = "source";

const STEPS_TOTAL: &str = "personhog_lifecycle_merge_steps_total";
const OUTCOMES_TOTAL: &str = "personhog_lifecycle_merge_outcomes_total";
/// Pre-flip aborts by refusal slug.
const ABORTS_TOTAL: &str = "personhog_lifecycle_merge_aborts_total";
const TOMBSTONES_ABOVE_SEAL_TOTAL: &str = "personhog_lifecycle_merge_tombstones_above_seal_total";

fn record_transition(from: &str, to: &str) {
    common_metrics::inc(
        STEPS_TOTAL,
        &[
            ("from".to_string(), from.to_string()),
            ("to".to_string(), to.to_string()),
        ],
        1,
    );
}

/// Count settled per-source outcomes. Shared by the saga's terminal record
/// and the entrance's inline settlement, so the counter covers every
/// requested source — not just the ones that entered the saga. `stage` is
/// `inline` or the step the op settled from.
pub(crate) fn record_outcome_count(stage: &'static str, outcome: &str, count: u64) {
    common_metrics::inc(
        OUTCOMES_TOTAL,
        &[
            ("stage".to_string(), stage.to_string()),
            ("outcome".to_string(), outcome.to_string()),
        ],
        count,
    );
}

/// Unsettled (skipped_conflict) verdicts by the check that produced them.
const CONFLICTS_TOTAL: &str = "personhog_identity_merge_conflicts_total";

/// Emit accumulated conflict reasons; called only after the recording
/// transaction commits, so rollbacks and step re-runs never count.
fn record_conflicts(conflicts: Vec<(&'static str, u64)>) {
    for (reason, count) in conflicts {
        record_conflict(reason, count);
    }
}

/// Attribute each conflict verdict, so an unsettled spike reads as live
/// contention, concurrent remaps, or vanished persons.
pub(crate) fn record_conflict(reason: &str, count: u64) {
    if count > 0 {
        common_metrics::inc(
            CONFLICTS_TOTAL,
            &[("reason".to_string(), reason.to_string())],
            count,
        );
    }
}

fn record_outcomes(stage: &'static str, outcome: &Value) {
    let Ok(parsed) = serde_json::from_value::<MergeOutcome>(outcome.clone()) else {
        return;
    };
    for label in [
        OUTCOME_MERGED,
        OUTCOME_NOOP_SAME_PERSON,
        OUTCOME_SKIPPED_ALREADY_IDENTIFIED,
        OUTCOME_SKIPPED_CONFLICT,
        OUTCOME_SKIPPED_MOVE_LIMIT,
        OUTCOME_SKIPPED_REFUSED,
        OUTCOME_ERROR,
    ] {
        let count = parsed.results.iter().filter(|r| r.outcome == label).count();
        if count > 0 {
            record_outcome_count(stage, label, count as u64);
        }
    }
}

/// One requested source did's claim-time decision, persisted in the target
/// row's `moved` column so the terminal outcome can be rebuilt after any
/// crash. `pending_merge` resolves to `merged` (row settled `deleted`) or
/// to the drop reason recorded when the source fell out.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Disposition {
    distinct_id: String,
    /// The person the did resolved to at claim time; absent when it
    /// resolved to nothing.
    person_id: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    person_uuid: Option<Uuid>,
    decision: String,
}

const DECISION_PENDING_MERGE: &str = "pending_merge";

#[derive(Debug, Serialize, Deserialize)]
struct ClaimRecord {
    dispositions: Vec<Disposition>,
}

/// The fence snapshot persisted per source row (`sealed`), and the exact
/// inputs the fold and the committed release replay from. `created_at` is
/// in the unit `Person.created_at` carries (epoch milliseconds).
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SealedSnapshot {
    version: i64,
    created_at: i64,
    is_identified: bool,
    properties: Value,
    // Defaulted so seals written before the field existed still parse.
    #[serde(default)]
    last_seen_at: Option<i64>,
    // The version the flip's source tombstone committed at. Absent until
    // the flip records it; the committed release forwards it so the death
    // document lands at or above it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    tombstone_version: Option<i64>,
}

pub struct MergeDriver {
    leader: Arc<dyn LifecycleLeader>,
    tables: IdentityTables,
    leader_call_concurrency: usize,
    warnings: MergeWarnings,
    outbox_writes: OutboxWrites,
}

impl MergeDriver {
    pub fn new(
        leader: Arc<dyn LifecycleLeader>,
        tables: IdentityTables,
        leader_call_concurrency: usize,
        outbox_writes: OutboxWrites,
    ) -> Self {
        tables.validate().expect("invalid identity table set");
        Self {
            leader,
            tables,
            // Clamped to 1: a zero-width buffered stream never polls.
            leader_call_concurrency: leader_call_concurrency.max(1),
            warnings: MergeWarnings::disabled(),
            outbox_writes,
        }
    }

    pub fn with_warnings(mut self, warnings: MergeWarnings) -> Self {
        self.warnings = warnings;
        self
    }
}

/// The caller's durability decision: every outcome is final under retry
/// except a claim conflict, and only where a retry actually re-runs it
/// (a discarded claim abort, or an inline answer with no op row).
pub(crate) fn outcome_settled(outcome: &str) -> bool {
    outcome != OUTCOME_SKIPPED_CONFLICT
}

/// Borrowed views of the frozen request and recorded outcome, so emitting
/// never clones the row and serde owns the key names.
#[derive(Deserialize)]
struct RequestView<'a> {
    #[serde(borrow)]
    target_distinct_id: &'a str,
    #[serde(borrow, default)]
    creator_event_uuid: &'a str,
    #[serde(borrow)]
    sources: Vec<SourceView<'a>>,
    /// Verdicts the entrance gave before the saga, by distinct id; a row
    /// frozen without an entrance pass has none.
    #[serde(borrow, default)]
    inline_results: HashMap<&'a str, &'a str>,
}

#[derive(Deserialize)]
struct SourceView<'a> {
    #[serde(borrow)]
    distinct_id: &'a str,
    #[serde(borrow, default)]
    event_uuid: &'a str,
}

#[derive(Deserialize)]
struct OutcomeView<'a> {
    #[serde(borrow, default)]
    survivor: Option<SurvivorView<'a>>,
    #[serde(borrow)]
    results: Vec<RecordView<'a>>,
}

#[derive(Deserialize)]
struct SurvivorView<'a> {
    #[serde(borrow, default)]
    uuid: Option<&'a str>,
}

#[derive(Deserialize)]
struct RecordView<'a> {
    #[serde(borrow)]
    distinct_id: &'a str,
    #[serde(borrow)]
    outcome: &'a str,
    #[serde(default)]
    person_id: Option<i64>,
    #[serde(default)]
    person_uuid: Option<Uuid>,
}

fn emit_terminal_warnings(warnings: &MergeWarnings, op: &OpRow, outcome: &Value) {
    if !warnings.is_enabled() {
        return;
    }
    let request = match RequestView::deserialize(&op.request) {
        Ok(request) => request,
        Err(error) => {
            tracing::warn!(op_id = %op.op_id, %error, "merge warnings skipped: frozen request did not parse");
            return;
        }
    };
    let recorded = match OutcomeView::deserialize(outcome) {
        Ok(recorded) => recorded,
        Err(error) => {
            tracing::warn!(op_id = %op.op_id, %error, "merge warnings skipped: recorded outcome did not parse");
            return;
        }
    };
    let event_uuids: HashMap<&str, &str> = request
        .sources
        .iter()
        .map(|source| (source.distinct_id, source.event_uuid))
        .collect();
    let claim_abort = MergeOpExecutor::is_claim_abort_outcome(outcome);
    let survivor_uuid = recorded
        .survivor
        .as_ref()
        .and_then(|survivor| survivor.uuid)
        .and_then(|uuid| Uuid::parse_str(uuid).ok());
    for record in &recorded.results {
        let event_uuid = effective_event_uuid(
            event_uuids.get(record.distinct_id).copied().unwrap_or(""),
            request.creator_event_uuid,
        );
        warnings.emit_verdict(
            op.team_id,
            MERGE_SAGA,
            record.outcome,
            outcome_settled(record.outcome) || !claim_abort,
            &MergePair {
                source_distinct_id: record.distinct_id,
                target_distinct_id: request.target_distinct_id,
                event_uuid,
                source_person_id: record.person_id,
                source_person_uuid: record.person_uuid,
                survivor_uuid,
            },
        );
    }
    // An inline conflict is unsettled at the entrance, so it warned nothing
    // there; this op finishing without a claim abort is what settles it,
    // the same way the response reports it.
    if claim_abort {
        return;
    }
    for (distinct_id, outcome) in &request.inline_results {
        if outcome_settled(outcome) {
            continue;
        }
        warnings.emit_verdict(
            op.team_id,
            MERGE_SAGA,
            outcome,
            true,
            &MergePair {
                source_distinct_id: distinct_id,
                target_distinct_id: request.target_distinct_id,
                event_uuid: request.creator_event_uuid,
                source_person_id: None,
                source_person_uuid: None,
                survivor_uuid,
            },
        );
    }
}

/// Everything the merge entrance may do with merge op rows: probe for an
/// existing op (the attach-first path) and drive a frozen request to its
/// terminal row. Identity work — resolution, classification, inline
/// settlement — lives in [`crate::service::merge`]; this seam keeps the
/// lifecycle side blind to it, and is where a future service split would
/// put the wire.
pub struct MergeOpExecutor {
    engine: Arc<Engine>,
    driver: Arc<MergeDriver>,
    drives: DetachedDrives,
}

impl MergeOpExecutor {
    pub fn new(engine: Arc<Engine>, driver: MergeDriver, drives: DetachedDrives) -> Self {
        Self {
            engine,
            driver: Arc::new(driver),
            drives,
        }
    }

    /// The op row for this id, if one exists.
    // tonic Status is a large Err variant; boxing would diverge from the
    // handler signatures this feeds into.
    #[allow(clippy::result_large_err)]
    pub async fn find(&self, op_id: Uuid) -> Result<Option<OpRow>, Status> {
        self.engine
            .load(op_id)
            .await
            .map_err(|e| Status::internal(format!("database error: {e}")))
    }

    /// Whether this terminal row is a disposable claim abort.
    pub fn is_claim_abort(row: &OpRow) -> bool {
        row.completed_at.is_some()
            && row
                .outcome
                .as_ref()
                .is_some_and(Self::is_claim_abort_outcome)
    }

    pub fn is_claim_abort_outcome(outcome: &Value) -> bool {
        outcome.get("claim_abort").and_then(Value::as_bool) == Some(true)
    }

    /// Delete a claim-aborted op; the flag is re-checked in SQL.
    // See `find` for why result_large_err is allowed.
    #[allow(clippy::result_large_err)]
    pub async fn discard_claim_abort(&self, op_id: Uuid) -> Result<(), Status> {
        let mut tx = self
            .engine
            .pools()
            .begin(Lane::Fast)
            .await
            .map_err(|e| Status::internal(format!("discard begin failed: {e}")))?;
        let tables = self.engine.tables();
        let deleted = mirrored_query!(
            tables.is_validation(),
            op = "merge_discard_claim_abort_op",
            r#"
            DELETE FROM {lifecycle_op}
            WHERE op_id = $1
              AND completed_at IS NOT NULL
              AND (outcome->>'claim_abort')::boolean IS TRUE
            "#,
            op_id
            => execute(&mut *tx)
        )
        .map_err(|e| Status::internal(format!("discard failed: {e}")))?;
        if deleted.rows_affected() > 0 {
            mirrored_query!(
                tables.is_validation(),
                op = "merge_discard_claim_abort_persons",
                "DELETE FROM {lifecycle_op_person} WHERE op_id = $1",
                op_id
                => execute(&mut *tx)
            )
            .map_err(|e| Status::internal(format!("discard marks failed: {e}")))?;
        }
        tx.commit()
            .await
            .map_err(|e| Status::internal(format!("discard commit failed: {e}")))?;
        Ok(())
    }

    /// Drive the op to terminal with the given frozen request (a resumed
    /// row's own request, or a freshly frozen one) and return the row. The
    /// drive outlives a caller that hangs up: see [`DetachedDrives`].
    // See `find` for why result_large_err is allowed.
    #[allow(clippy::result_large_err)]
    pub async fn execute(
        &self,
        op_id: Uuid,
        team_id: i64,
        frozen: &Value,
    ) -> Result<OpRow, Status> {
        let engine = self.engine.clone();
        let driver = self.driver.clone();
        let frozen = frozen.clone();
        let deadline = engine.execute_deadline();
        let terminal = engine.wait_for_lease_lapse(op_id, deadline).await;
        let drive = async move {
            engine
                .execute_by(driver.as_ref(), op_id, team_id, &frozen, deadline)
                .await
                .inspect_err(|err| {
                    if matches!(err, SagaError::Db(_) | SagaError::CorruptState(_)) {
                        tracing::error!(op_id = %op_id, error = %err, "MergePersons failed");
                    }
                })
        };
        let driven = match terminal {
            Ok(true) => drive.await,
            Ok(false) => self.drives.run(drive).await.map_err(|err| {
                tracing::error!(op_id = %op_id, error = %err, "MergePersons drive task died");
                Status::internal(format!("merge op {op_id} drive task died: {err}"))
            })?,
            Err(err) => Err(err),
        };
        driven.map_err(|err| {
            // The entrance only reaches this create path after finding
            // no op row, so an engine-level mismatch means the row
            // appeared in the race window since — a transient loss,
            // not op_id misuse (which the entrance's attach-first
            // comparison answers). Both client stacks treat
            // FAILED_PRECONDITION as terminal, so surfacing the race
            // as one would fail a request whose retry attaches fine.
            if matches!(err, SagaError::RequestMismatch(_)) {
                return Status::unavailable(format!(
                    "another call is initializing op {op_id}; retry with the same op_id"
                ));
            }
            Status::from(err)
        })
    }
}

#[async_trait]
impl OpDriver for MergeDriver {
    fn op_type(&self) -> &'static str {
        OP_TYPE_MERGE
    }

    fn initial_step(&self) -> &'static str {
        MergeStep::Started.as_str()
    }

    async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
        let step = MergeStep::parse(&op.step).ok_or_else(|| {
            SagaError::CorruptState(format!(
                "merge op {} is on unknown step '{}'",
                op.op_id, op.step
            ))
        })?;
        match step {
            MergeStep::Started => self.claim(pools, op).await,
            MergeStep::Claimed => self.seal(pools, op).await,
            MergeStep::SourcesSealed => self.fold(pools, op).await,
            MergeStep::DocumentFolded => flip(pools, &self.tables, op).await,
            MergeStep::Flipped => self.complete(pools, op).await,
        }
    }
}

fn parse_request(op: &OpRow) -> Result<MergeRequest, SagaError> {
    let request: MergeRequest = serde_json::from_value(op.request.clone()).map_err(|e| {
        SagaError::CorruptState(format!(
            "merge op {} has a malformed request: {e}",
            op.op_id
        ))
    })?;
    // A non-positive limit would silently skip every source.
    if request.move_limit < 1 {
        return Err(SagaError::CorruptState(format!(
            "merge op {} has a non-positive move_limit ({})",
            op.op_id, request.move_limit
        )));
    }
    Ok(request)
}

/// A did's resolution on the primary: the live person its live mapping row
/// points at.
struct Resolution {
    person_id: i64,
    person_uuid: Uuid,
    is_identified: bool,
}

/// Post-insert reconciliation of the pending set against the fresh
/// resolve. A pending did that no longer resolves to its claimed person
/// was remapped by a concurrent identify — the flip will not repoint it,
/// so reporting it merged would be a lie; it settles as a retryable
/// conflict even when a sibling did keeps the person claimed. Returns the
/// claimed persons no pending did still reaches (to be dropped).
fn reconcile_pending_claims(
    dispositions: &mut [Disposition],
    claim_persons: &[(i64, Uuid, i32)],
    marked: &[i64],
    fresh: &HashMap<String, Resolution>,
    conflicts: &mut Vec<(&'static str, u64)>,
) -> Vec<i64> {
    for d in dispositions.iter_mut() {
        if d.decision != DECISION_PENDING_MERGE {
            continue;
        }
        let Some(person_id) = d.person_id else {
            continue;
        };
        if !marked.contains(&person_id) {
            continue;
        }
        if fresh
            .get(&d.distinct_id)
            .is_none_or(|r| r.person_id != person_id)
        {
            conflicts.push(("remapped_after_claim", 1));
            d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();
        }
    }
    claim_persons
        .iter()
        .filter(|(person_id, _, _)| {
            marked.contains(person_id)
                && !dispositions.iter().any(|d| {
                    d.decision == DECISION_PENDING_MERGE && d.person_id == Some(*person_id)
                })
        })
        .map(|(person_id, _, _)| *person_id)
        .collect()
}

async fn resolve_dids(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    team_id: i32,
    dids: &[String],
) -> Result<HashMap<String, Resolution>, SagaError> {
    let resolve_sql = format!(
        r#"
        SELECT d.distinct_id, d.person_id, p.uuid, p.is_identified
        FROM {pdi_table} d
        JOIN {person_table} p ON p.team_id = d.team_id AND p.id = d.person_id
        WHERE d.team_id = $1 AND d.distinct_id = ANY($2)
          AND d.is_deleted = false AND p.is_deleted = false
        "#,
        pdi_table = tables.person_distinct_id,
        person_table = tables.person,
    );
    let rows: Vec<(String, i64, Uuid, bool)> =
        sqlx::query_as(&query_tag!("merge_resolve_dids", resolve_sql))
            .bind(team_id)
            .bind(dids)
            .fetch_all(&mut **tx)
            .await?;
    Ok(rows
        .into_iter()
        .map(|(distinct_id, person_id, person_uuid, is_identified)| {
            (
                distinct_id,
                Resolution {
                    person_id,
                    person_uuid,
                    is_identified,
                },
            )
        })
        .collect())
}

impl MergeDriver {
    /// `started → claimed` (or `→ aborted`): re-resolve authoritatively,
    /// classify every source did, and claim the target plus every
    /// still-mergeable source person via the mark index — all in one
    /// transaction. Nothing outside this op's own rows is mutated, so the
    /// abort branch can end the op in the same commit.
    async fn claim(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
        let request = parse_request(op)?;
        let team_id = op.team_id as i32;
        // Conflict reasons emit only after a commit (see record_conflicts).
        let mut conflicts: Vec<(&'static str, u64)> = Vec::new();
        let mut tx = pools.begin(Lane::Heavy).await?;

        // Authoritative resolution: the handler's classification aged while
        // the op row traveled here.
        let mut all_dids: Vec<String> = Vec::with_capacity(request.sources.len() + 1);
        all_dids.push(request.target_distinct_id.clone());
        all_dids.extend(request.sources.iter().map(|s| s.distinct_id.clone()));
        all_dids.sort_unstable();
        all_dids.dedup();
        let resolved = resolve_dids(&mut tx, &self.tables, team_id, &all_dids).await?;

        let Some(target) = resolved.get(&request.target_distinct_id) else {
            // The target person vanished between classification and now. The
            // caller's re-drive (new op) re-classifies; this op has changed
            // nothing.
            let dispositions: Vec<Disposition> = request
                .sources
                .iter()
                .map(|s| Disposition {
                    distinct_id: s.distinct_id.clone(),
                    person_id: None,
                    person_uuid: None,
                    decision: OUTCOME_SKIPPED_CONFLICT.to_string(),
                })
                .collect();
            conflicts.push(("target_vanished", dispositions.len() as u64));
            return abort_in_claim_tx(
                tx,
                &self.tables,
                &self.warnings,
                op,
                dispositions,
                conflicts,
            )
            .await;
        };
        let (target_person_id, target_person_uuid) = (target.person_id, target.person_uuid);

        // Classify each source did; collect the distinct persons to claim.
        // Two dids resolving to one person share a claim (first ordinal
        // wins the row's ordinal; both dids ride its fate).
        let mut dispositions: Vec<Disposition> = Vec::with_capacity(request.sources.len());
        let mut claim_persons: Vec<(i64, Uuid, i32)> = Vec::new();
        for (ordinal, source) in request.sources.iter().enumerate() {
            let Some(resolution) = resolved.get(&source.distinct_id) else {
                // Consumed by another lifecycle op (or never existed): a
                // retryable signal — the caller's re-drive re-classifies it.
                conflicts.push(("source_consumed", 1));
                dispositions.push(Disposition {
                    distinct_id: source.distinct_id.clone(),
                    person_id: None,
                    person_uuid: None,
                    decision: OUTCOME_SKIPPED_CONFLICT.to_string(),
                });
                continue;
            };
            if resolution.person_id == target_person_id {
                dispositions.push(Disposition {
                    distinct_id: source.distinct_id.clone(),
                    person_id: Some(resolution.person_id),
                    person_uuid: Some(resolution.person_uuid),
                    decision: OUTCOME_NOOP_SAME_PERSON.to_string(),
                });
                continue;
            }
            if resolution.is_identified && !request.allow_identified_sources {
                // Cheap Postgres pre-filter; the authoritative re-check runs
                // on the sealed state (Postgres lags the leader, and
                // is_identified only ever flips true, so this can only
                // under-drop, never over-drop).
                dispositions.push(Disposition {
                    distinct_id: source.distinct_id.clone(),
                    person_id: Some(resolution.person_id),
                    person_uuid: Some(resolution.person_uuid),
                    decision: OUTCOME_SKIPPED_ALREADY_IDENTIFIED.to_string(),
                });
                continue;
            }
            if !claim_persons
                .iter()
                .any(|(id, _, _)| *id == resolution.person_id)
            {
                claim_persons.push((resolution.person_id, resolution.person_uuid, ordinal as i32));
            }
            dispositions.push(Disposition {
                distinct_id: source.distinct_id.clone(),
                person_id: Some(resolution.person_id),
                person_uuid: Some(resolution.person_uuid),
                decision: DECISION_PENDING_MERGE.to_string(),
            });
        }

        // The move-limit guard: a source with more distinct ids than the
        // caller's limit is skipped, not chunked; the caller applies its
        // merge-mode policy to the skip. The inner LIMIT stops each
        // candidate's scan at limit+1 rows, so an oversized person cannot
        // blow the statement timeout.
        let candidate_ids: Vec<i64> = claim_persons.iter().map(|(id, _, _)| *id).collect();
        let over_sql = format!(
            r#"
            SELECT c.person_id
            FROM unnest($2::bigint[]) AS c(person_id)
            WHERE (
                SELECT count(*)
                FROM (
                    SELECT 1
                    FROM {pdi_table} d
                    WHERE d.team_id = $1
                      AND d.person_id = c.person_id
                      AND d.is_deleted = false
                    LIMIT $3::bigint + 1
                ) capped
            ) > $3::bigint
            "#,
            pdi_table = self.tables.person_distinct_id,
        );
        let over: Vec<i64> = sqlx::query_scalar(&query_tag!("merge_claim_over_limit", over_sql))
            .bind(team_id)
            .bind(&candidate_ids)
            .bind(request.move_limit)
            .fetch_all(&mut *tx)
            .await?;
        if !over.is_empty() {
            claim_persons.retain(|(id, _, _)| !over.contains(id));
            for d in dispositions.iter_mut() {
                if d.decision == DECISION_PENDING_MERGE
                    && d.person_id.is_some_and(|id| over.contains(&id))
                {
                    d.decision = OUTCOME_SKIPPED_MOVE_LIMIT.to_string();
                }
            }
        }

        // The mark: one sorted insert covering the target and every source
        // person, so concurrent ops touching the same persons take row
        // locks in the same order. Inserting is claiming; a unique
        // violation on the partial mark index IS the conflict.
        let mut rows: Vec<(i64, Uuid, &str, Option<i32>)> = claim_persons
            .iter()
            .map(|(id, uuid, ordinal)| (*id, *uuid, ROLE_SOURCE, Some(*ordinal)))
            .collect();
        rows.push((target_person_id, target_person_uuid, ROLE_TARGET, None));
        rows.sort_unstable_by_key(|(id, _, _, _)| *id);
        let ids: Vec<i64> = rows.iter().map(|r| r.0).collect();
        let uuids: Vec<Uuid> = rows.iter().map(|r| r.1).collect();
        let roles: Vec<String> = rows.iter().map(|r| r.2.to_string()).collect();
        let ordinals: Vec<Option<i32>> = rows.iter().map(|r| r.3).collect();

        let marked: Vec<i64> = mirrored_query_scalar!(
            self.tables.is_validation(),
            op = "merge_claim_mark",
            r#"
            INSERT INTO {lifecycle_op_person}
                (op_id, team_id, person_id, person_uuid, role, ordinal, status, mark_active)
            SELECT $1, $2, u.person_id, u.person_uuid, u.role, u.ordinal, $6, true
            FROM unnest($3::bigint[], $4::uuid[], $5::text[], $7::int[])
                AS u(person_id, person_uuid, role, ordinal)
            ON CONFLICT (team_id, person_id) WHERE mark_active DO NOTHING
            RETURNING person_id
            "#,
            op.op_id,
            team_id,
            &ids,
            &uuids,
            roles.as_slice(),
            STATUS_MARKED,
            ordinals.as_slice() as _
            => fetch_all(&mut *tx)
        )?;

        if !marked.contains(&target_person_id) {
            // Another live op holds the target: abort. Flip whatever this
            // insert claimed back out of the mark set in the same commit —
            // nothing outside our rows has happened.
            unmark(&mut tx, &self.tables, op).await?;
            let mut converted = 0;
            for d in dispositions.iter_mut() {
                if d.decision == DECISION_PENDING_MERGE {
                    d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();
                    converted += 1;
                }
            }
            conflicts.push(("target_marked", converted));
            return abort_in_claim_tx(
                tx,
                &self.tables,
                &self.warnings,
                op,
                dispositions,
                conflicts,
            )
            .await;
        }

        // Sources another live op holds: record the skip (the status keeps
        // the row outside the mark index). ON CONFLICT on the primary key
        // covers a concurrent driver of this same op racing us.
        let conflicted: Vec<(i64, Uuid)> = claim_persons
            .iter()
            .filter(|(id, _, _)| !marked.contains(id))
            .map(|(id, uuid, _)| (*id, *uuid))
            .collect();
        if !conflicted.is_empty() {
            let conflicted_ids: Vec<i64> = conflicted.iter().map(|c| c.0).collect();
            let conflicted_uuids: Vec<Uuid> = conflicted.iter().map(|c| c.1).collect();
            mirrored_query!(
                self.tables.is_validation(),
                op = "merge_claim_record_conflicts",
                r#"
                INSERT INTO {lifecycle_op_person} (op_id, team_id, person_id, person_uuid, role, status)
                SELECT $1, $2, u.person_id, u.person_uuid, $5, $6
                FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)
                ON CONFLICT (op_id, person_id) DO NOTHING
                "#,
                op.op_id,
                team_id,
                &conflicted_ids,
                &conflicted_uuids,
                ROLE_SOURCE,
                STATUS_SKIPPED_CONFLICT
                => execute(&mut *tx)
            )?;
            let mut converted = 0;
            for d in dispositions.iter_mut() {
                if d.decision == DECISION_PENDING_MERGE
                    && d.person_id.is_some_and(|id| conflicted_ids.contains(&id))
                {
                    d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();
                    converted += 1;
                }
            }
            conflicts.push(("source_marked", converted));
        }

        // Post-insert liveness recheck. The resolve above and the insert run
        // in different statement snapshots, so a destroyer that tombstoned a
        // person and settled its mark between them makes our insert succeed
        // on a corpse. One fresh statement re-verifies person liveness and
        // mapping stability; after it, mark + liveness hold in one snapshot
        // and nothing can destroy or re-map a claimed person (the mark
        // blocks every lifecycle op and identity mutation).
        let fresh = resolve_dids(&mut tx, &self.tables, team_id, &all_dids).await?;
        let target_still_live = fresh
            .get(&request.target_distinct_id)
            .is_some_and(|r| r.person_id == target_person_id);
        if !target_still_live {
            unmark(&mut tx, &self.tables, op).await?;
            let mut converted = 0;
            for d in dispositions.iter_mut() {
                if d.decision == DECISION_PENDING_MERGE {
                    d.decision = OUTCOME_SKIPPED_CONFLICT.to_string();
                    converted += 1;
                }
            }
            conflicts.push(("target_vanished", converted));
            return abort_in_claim_tx(
                tx,
                &self.tables,
                &self.warnings,
                op,
                dispositions,
                conflicts,
            )
            .await;
        }
        let dropped = reconcile_pending_claims(
            &mut dispositions,
            &claim_persons,
            &marked,
            &fresh,
            &mut conflicts,
        );
        if !dropped.is_empty() {
            mirrored_query!(
                self.tables.is_validation(),
                op = "merge_claim_drop_pending",
                r#"
                UPDATE {lifecycle_op_person} SET status = $2, mark_active = false
                WHERE op_id = $1 AND person_id = ANY($3) AND status = $4
                "#,
                op.op_id,
                STATUS_DROPPED,
                &dropped,
                STATUS_MARKED
                => execute(&mut *tx)
            )?;
        }

        if !dispositions
            .iter()
            .any(|d| d.decision == DECISION_PENDING_MERGE)
        {
            // Every source fell out: release the target's just-taken mark
            // and end the op. No fences exist yet.
            mirrored_query!(
                self.tables.is_validation(),
                op = "merge_claim_abort_marks",
                r#"
                UPDATE {lifecycle_op_person} SET status = $2, mark_active = false
                WHERE op_id = $1 AND role = $3 AND status = $4
                "#,
                op.op_id,
                STATUS_CLEARED,
                ROLE_TARGET,
                STATUS_MARKED
                => execute(&mut *tx)
            )?;
            return abort_in_claim_tx(
                tx,
                &self.tables,
                &self.warnings,
                op,
                dispositions,
                conflicts,
            )
            .await;
        }

        // Persist the claim record on the target row; the terminal outcome
        // is rebuilt from it after any crash.
        let claim_record = serde_json::to_value(ClaimRecord { dispositions }).map_err(|e| {
            SagaError::CorruptState(format!("failed to serialize claim record: {e}"))
        })?;
        write_claim_record(&mut tx, &self.tables, op, &claim_record).await?;

        if !advance_step_in_tx(
            &mut tx,
            &self.tables,
            op.op_id,
            MergeStep::Started.as_str(),
            MergeStep::Claimed.as_str(),
        )
        .await?
        {
            tx.rollback().await?;
            return Ok(());
        }
        tx.commit().await?;
        record_conflicts(conflicts);
        record_transition(MergeStep::Started.as_str(), MergeStep::Claimed.as_str());
        Ok(())
    }
}

async fn unmark(tx: &mut Tx<'_>, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
    mirrored_query!(
        tables.is_validation(),
        op = "merge_unmark",
        "UPDATE {lifecycle_op_person} SET status = $2, mark_active = false WHERE op_id = $1 AND status = $3",
        op.op_id,
        STATUS_ABORTED,
        STATUS_MARKED
        => execute(&mut **tx)
    )?;
    Ok(())
}

async fn write_claim_record(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    op: &OpRow,
    record: &Value,
) -> Result<(), SagaError> {
    mirrored_query!(
        tables.is_validation(),
        op = "merge_write_claim_record",
        "UPDATE {lifecycle_op_person} SET moved = $2 WHERE op_id = $1 AND role = $3",
        op.op_id,
        record,
        ROLE_TARGET
        => execute(&mut **tx)
    )?;
    Ok(())
}

/// End an op inside the claim transaction: nothing outside this op's own
/// rows has been mutated, so recording the outcome and the terminal step
/// in the same commit is the whole abort.
async fn abort_in_claim_tx(
    mut tx: Tx<'_>,
    tables: &IdentityTables,
    warnings: &MergeWarnings,
    op: &OpRow,
    dispositions: Vec<Disposition>,
    conflicts: Vec<(&'static str, u64)>,
) -> Result<(), SagaError> {
    let mut outcome = outcome_from_dispositions(
        &dispositions,
        Some(AbortOutcome::Conflict),
        None,
        &HashMap::new(),
    )?;
    // The entrance discards flagged rows on the next presentation of the
    // op id, so a plain retry re-runs where a recorded conflict replays.
    outcome["claim_abort"] = Value::Bool(true);
    if !abort_op_in_tx(
        &mut tx,
        tables,
        op.op_id,
        MergeStep::Started.as_str(),
        &outcome,
    )
    .await?
    {
        tx.rollback().await?;
        return Ok(());
    }
    tx.commit().await?;
    record_conflicts(conflicts);
    record_transition(MergeStep::Started.as_str(), STEP_ABORTED);
    record_outcomes(MergeStep::Started.as_str(), &outcome);
    emit_terminal_warnings(warnings, op, &outcome);
    Ok(())
}

impl MergeDriver {
    /// `claimed → sources_sealed` (or `→ aborted`): fence every claimed
    /// source's owning leader and persist the sealed snapshots. The fences
    /// are the step's only external effect and re-fencing with the same
    /// op_id is a re-seal returning identical state (the fence itself
    /// froze the person), so the fan-out is safe to repeat; the snapshots
    /// and the step CAS commit together afterwards.
    ///
    /// Known residual: a stale duplicate driver can re-fence a source the
    /// winner already dropped (its settling TX loses the CAS, but its
    /// fence call does not roll back). No later step releases a dropped
    /// source, so the orphan clears via the leader's ghost-fence healer on
    /// the next rejected write (or a partition handoff) — the same class
    /// the takeover scan can mint, bounded the same way.
    async fn seal(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
        let request = parse_request(op)?;
        let sources = live_sources(pools, &self.tables, op).await?;

        let mut sealed: Vec<(i64, SealedSnapshot)> = Vec::new();
        let mut vanished: Vec<i64> = Vec::new();
        let fence_calls: Vec<_> = sources
            .iter()
            .map(|source| {
                let leader = Arc::clone(&self.leader);
                let request = FencePersonRequest {
                    team_id: op.team_id,
                    person_id: source.person_id,
                    op_id: op.op_id.to_string(),
                    op_type: LifecycleOpType::Merge.into(),
                };
                let person_id = source.person_id;
                async move { (person_id, leader.fence_person(request).await) }
            })
            .collect();
        let fence_results: Vec<_> = stream::iter(fence_calls)
            .buffer_unordered(self.leader_call_concurrency)
            .collect()
            .await;
        for (person_id, result) in fence_results {
            match result {
                Ok(response) => {
                    let person = response.sealed.ok_or_else(|| {
                        SagaError::CorruptState(format!(
                            "fence response for person {person_id} carries no sealed state"
                        ))
                    })?;
                    sealed.push((person_id, snapshot_from_sealed(&person)?));
                }
                Err(status) if status.code() == Code::NotFound => {
                    // Unreachable while the mark holds (the claim recheck
                    // closed the pre-mark race), so a hit here is an
                    // anomaly worth shouting about — but dropping the
                    // source is still the correct settlement: it no longer
                    // exists, and no fence was installed.
                    tracing::error!(
                        op_id = %op.op_id,
                        person_id,
                        "marked merge source vanished before its fence; dropping it"
                    );
                    vanished.push(person_id);
                }
                Err(status) => {
                    // Fenced-by-another-op can only be a ghost fence (a
                    // real foreign op would need a live mark we hold); the
                    // leader's healer clears it on observation. Transient
                    // failures retry the step; a refusal backs the op out.
                    return match SagaError::leader(status) {
                        SagaError::LeaderRefused(status) => {
                            self.abort_refused(pools, op, MergeStep::Claimed, &status)
                                .await
                        }
                        err => Err(err),
                    };
                }
            }
        }

        // The authoritative is_identified check, on the sealed state the
        // fold would consume. An identified source drops out; its fence is
        // released (produce nothing) before its mark settles below.
        let mut identified: Vec<i64> = Vec::new();
        if !request.allow_identified_sources {
            let (keep, drop_identified): (Vec<_>, Vec<_>) = sealed
                .into_iter()
                .partition(|(_, snapshot)| !snapshot.is_identified);
            sealed = keep;
            identified = drop_identified.iter().map(|(id, _)| *id).collect();
            let identified_pairs: Vec<(i64, Uuid)> = sources
                .iter()
                .filter(|s| identified.contains(&s.person_id))
                .map(|s| (s.person_id, s.person_uuid))
                .collect();
            self.release_fences(op, &identified_pairs).await?;
        }

        if sealed.is_empty() {
            // Every source fell out between claim and seal: abort. Fences
            // for remaining marked sources were never installed (vanished)
            // or already released (identified); release again vacuously for
            // crash-resilience, then settle the rows.
            let remaining: Vec<(i64, Uuid)> = sources
                .iter()
                .map(|s| (s.person_id, s.person_uuid))
                .collect();
            self.release_fences(op, &remaining).await?;
            let mut tx = pools.begin(Lane::Heavy).await?;
            settle_drops(&mut tx, &self.tables, op, &vanished, &identified).await?;
            abort_marks(&mut tx, &self.tables, op).await?;
            let outcome =
                build_outcome(&mut tx, &self.tables, op, Some(AbortOutcome::Conflict)).await?;
            if !abort_op_in_tx(
                &mut tx,
                &self.tables,
                op.op_id,
                MergeStep::Claimed.as_str(),
                &outcome,
            )
            .await?
            {
                tx.rollback().await?;
                return Ok(());
            }
            tx.commit().await?;
            record_transition(MergeStep::Claimed.as_str(), STEP_ABORTED);
            record_outcomes(MergeStep::Claimed.as_str(), &outcome);
            emit_terminal_warnings(&self.warnings, op, &outcome);
            return Ok(());
        }

        let mut tx = pools.begin(Lane::Heavy).await?;
        settle_drops(&mut tx, &self.tables, op, &vanished, &identified).await?;
        let sealed_ids: Vec<i64> = sealed.iter().map(|(id, _)| *id).collect();
        let sealed_jsons: Vec<Value> = sealed
            .iter()
            .map(|(_, snapshot)| serde_json::to_value(snapshot))
            .collect::<Result<_, _>>()
            .map_err(|e| SagaError::CorruptState(format!("failed to serialize seal: {e}")))?;
        mirrored_query!(
            self.tables.is_validation(),
            op = "merge_seal",
            r#"
            UPDATE {lifecycle_op_person} lop
            SET status = $4, sealed = u.sealed
            FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, sealed)
            WHERE lop.op_id = $1 AND lop.person_id = u.person_id
              AND lop.mark_active
            "#,
            op.op_id,
            &sealed_ids,
            &sealed_jsons,
            STATUS_SEALED
            => execute(&mut *tx)
        )?;

        if !advance_step_in_tx(
            &mut tx,
            &self.tables,
            op.op_id,
            MergeStep::Claimed.as_str(),
            MergeStep::SourcesSealed.as_str(),
        )
        .await?
        {
            tx.rollback().await?;
            return Ok(());
        }
        tx.commit().await?;
        record_transition(
            MergeStep::Claimed.as_str(),
            MergeStep::SourcesSealed.as_str(),
        );
        Ok(())
    }

    /// Back the op out after a pre-flip refusal. Nothing is destroyed
    /// before the flip, so unwinding is safe; post-flip refusals park.
    async fn abort_refused(
        &self,
        pools: &IdentityPools,
        op: &OpRow,
        from_step: MergeStep,
        status: &Status,
    ) -> Result<(), SagaError> {
        let live = live_sources(pools, &self.tables, op).await?;
        let pairs: Vec<(i64, Uuid)> = live.iter().map(|s| (s.person_id, s.person_uuid)).collect();

        let mut tx = pools.begin(Lane::Heavy).await?;
        abort_marks(&mut tx, &self.tables, op).await?;
        // Fence contention never reaches this abort; it retries at the step.
        let outcome = build_outcome(&mut tx, &self.tables, op, Some(AbortOutcome::Refused)).await?;
        if !abort_op_in_tx(
            &mut tx,
            &self.tables,
            op.op_id,
            from_step.as_str(),
            &outcome,
        )
        .await?
        {
            tx.rollback().await?;
            return Ok(());
        }
        tx.commit().await?;
        // Attribute the abort before the releases: a failed release
        // leaves the op terminal with nothing retrying it.
        tracing::error!(
            op_id = %op.op_id,
            step = %from_step.as_str(),
            reason = %personhog_common::grpc::refusal_reason_label(status),
            message = %status.message(),
            "leader definitively refused a pre-flip merge step; op aborted, releasing its fences"
        );
        record_transition(from_step.as_str(), STEP_ABORTED);
        common_metrics::inc(
            ABORTS_TOTAL,
            &[(
                "reason".to_string(),
                personhog_common::grpc::refusal_reason_label(status).to_string(),
            )],
            1,
        );
        record_outcomes(from_step.as_str(), &outcome);
        emit_terminal_warnings(&self.warnings, op, &outcome);
        // Releases only after the completing CAS proves we still owned the
        // op; ghosts left by a crash here are healed lazily by the leader.
        self.release_fences(op, &pairs).await?;
        Ok(())
    }

    /// Release fences with outcome `aborted` for the given persons,
    /// bounded-concurrently. Releasing a never-fenced person is a no-op at
    /// the leader, so callers pass every candidate rather than tracking
    /// which fences actually installed.
    async fn release_fences(&self, op: &OpRow, persons: &[(i64, Uuid)]) -> Result<(), SagaError> {
        let calls: Vec<_> = persons
            .iter()
            .map(|(person_id, person_uuid)| {
                let leader = Arc::clone(&self.leader);
                let request = ReleaseFenceRequest {
                    team_id: op.team_id,
                    person_id: *person_id,
                    person_uuid: person_uuid.to_string(),
                    op_id: op.op_id.to_string(),
                    outcome: ReleaseOutcome::Aborted.into(),
                    sealed_version: None,
                    created_at: 0,
                    tombstone_version: None,
                };
                async move { leader.release_fence(request).await }
            })
            .collect();
        let results: Vec<_> = stream::iter(calls)
            .buffer_unordered(self.leader_call_concurrency)
            .collect()
            .await;
        for result in results {
            result.map_err(SagaError::leader)?;
        }
        Ok(())
    }
}

fn snapshot_from_sealed(person: &Person) -> Result<SealedSnapshot, SagaError> {
    let properties = if person.properties.is_empty() {
        Value::Object(serde_json::Map::new())
    } else {
        serde_json::from_slice(&person.properties).map_err(|e| {
            SagaError::CorruptState(format!("sealed properties do not parse as JSON: {e}"))
        })?
    };
    Ok(SealedSnapshot {
        version: person.version,
        created_at: person.created_at,
        is_identified: person.is_identified,
        properties,
        last_seen_at: person.last_seen_at,
        tombstone_version: None,
    })
}

async fn live_sources(
    pools: &IdentityPools,
    tables: &IdentityTables,
    op: &OpRow,
) -> Result<Vec<PersonRef>, SagaError> {
    Ok(mirrored_query_as!(
        PersonRef,
        tables.is_validation(),
        op = "merge_live_sources",
        r#"
        SELECT person_id, person_uuid FROM {lifecycle_op_person}
        WHERE op_id = $1 AND role = $2 AND mark_active
        "#,
        op.op_id,
        ROLE_SOURCE
        => fetch_all(pools.fast())
    )?)
}

/// Settle a pre-flip abort's marks: sources `aborted`, target `cleared`.
async fn abort_marks(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    op: &OpRow,
) -> Result<(), SagaError> {
    mirrored_query!(
        tables.is_validation(),
        op = "merge_abort_marks",
        r#"
        UPDATE {lifecycle_op_person} SET status = $2, mark_active = false
        WHERE op_id = $1 AND role = $3 AND mark_active
        "#,
        op.op_id,
        STATUS_ABORTED,
        ROLE_SOURCE
        => execute(&mut **tx)
    )?;
    clear_target_mark(tx, tables, op).await
}

/// Settle sources that dropped out during the seal: `dropped` releases
/// their marks; the claim record's decisions flip to the drop reason.
async fn settle_drops(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    op: &OpRow,
    vanished: &[i64],
    identified: &[i64],
) -> Result<(), SagaError> {
    let all: Vec<i64> = vanished.iter().chain(identified.iter()).copied().collect();
    if all.is_empty() {
        return Ok(());
    }
    mirrored_query!(
        tables.is_validation(),
        op = "merge_settle_drops",
        r#"
        UPDATE {lifecycle_op_person} SET status = $2, mark_active = false
        WHERE op_id = $1 AND person_id = ANY($3) AND mark_active
        "#,
        op.op_id,
        STATUS_DROPPED,
        &all
        => execute(&mut **tx)
    )?;

    let mut record = claim_record(tx, tables, op).await?;
    for disposition in record.dispositions.iter_mut() {
        if disposition.decision != DECISION_PENDING_MERGE {
            continue;
        }
        let Some(person_id) = disposition.person_id else {
            continue;
        };
        if vanished.contains(&person_id) {
            // error-without-merged reads as an abort to the caller's fold
            // guard, so this shape cannot read as executed.
            disposition.decision = OUTCOME_ERROR.to_string();
        } else if identified.contains(&person_id) {
            disposition.decision = OUTCOME_SKIPPED_ALREADY_IDENTIFIED.to_string();
        }
    }
    let updated = serde_json::to_value(&record)
        .map_err(|e| SagaError::CorruptState(format!("failed to serialize claim record: {e}")))?;
    write_claim_record(tx, tables, op, &updated).await
}

impl MergeDriver {
    /// `sources_sealed → document_folded`: one FoldPersonDocument call to
    /// the target's leader with the sealed snapshots in precedence order.
    /// A re-driven fold on unchanged target state changes no content and
    /// only bumps the version, so a crash between the fold and the CAS is
    /// absorbed — up to the accepted re-appliable-merge residual: the
    /// target is never fenced, so a re-fold recomputes over writes that
    /// landed in between (see FoldPersonDocumentRequest.op_id in the
    /// proto). The folded document persists on the target row: the
    /// terminal outcome's survivor, durable without ever re-folding.
    async fn fold(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
        let request = parse_request(op)?;
        let target = target_row(pools, &self.tables, op).await?;
        let sources = sealed_sources(pools, &self.tables, op).await?;

        // The fold verifies each snapshot's identity and orders by the
        // ordinal itself, so the request carries the recorded pair order
        // and the source's real identity fields.
        let mut snapshots: Vec<SealedSourceSnapshot> = Vec::with_capacity(sources.len());
        for source in &sources {
            let snapshot: SealedSnapshot =
                serde_json::from_value(source.sealed.clone()).map_err(|e| {
                    SagaError::CorruptState(format!(
                        "merge op {} source {} has a malformed seal: {e}",
                        op.op_id, source.person_id
                    ))
                })?;
            snapshots.push(SealedSourceSnapshot {
                person: Some(Person {
                    id: source.person_id,
                    team_id: op.team_id,
                    properties: serde_json::to_vec(&snapshot.properties).map_err(|e| {
                        SagaError::CorruptState(format!("failed to serialize seal properties: {e}"))
                    })?,
                    version: snapshot.version,
                    created_at: snapshot.created_at,
                    is_identified: snapshot.is_identified,
                    last_seen_at: snapshot.last_seen_at,
                    ..Default::default()
                }),
                ordinal: source.ordinal,
            });
        }

        // The stub never reached the changelog, so the born stamp rides the
        // fold's $set; the uuid check keeps it off a person the claim
        // resolved after a rival settled the newborn away.
        let mut event_set = request.event_set.clone();
        if request.target_born
            && !request.creator_event_uuid.is_empty()
            && target.person_uuid == person_uuid(op.team_id, &request.target_distinct_id)
        {
            if event_set.is_null() {
                event_set = Value::Object(Default::default());
            }
            let map = event_set.as_object_mut().ok_or_else(|| {
                SagaError::CorruptState(format!("merge op {} event_set is not a map", op.op_id))
            })?;
            map.insert(
                "$creator_event_uuid".to_string(),
                Value::String(request.creator_event_uuid.clone()),
            );
        }
        let response = match self
            .leader
            .fold_person_document(FoldPersonDocumentRequest {
                team_id: op.team_id,
                person_id: target.person_id,
                sealed_snapshots: snapshots,
                event_set: encode_json_map(&event_set)?,
                event_set_once: encode_json_map(&request.event_set_once)?,
                op_id: op.op_id.to_string(),
            })
            .await
        {
            Ok(response) => response,
            Err(status) => {
                return match SagaError::leader(status) {
                    SagaError::LeaderRefused(status) => {
                        // Under a stale claim the advancing driver still
                        // needs the fences, so Busy re-attaches the retry;
                        // under a live claim the pre-flip abort is safe.
                        if personhog_common::grpc::semantic_refusal_reason(&status)
                            == Some("fold-unverified")
                            && op_moved_on(pools, &self.tables, op).await?
                        {
                            tracing::info!(
                                op_id = %op.op_id,
                                "stale drive's fold refusal deferred to the op row; the caller's retry attaches to it"
                            );
                            Err(SagaError::Busy)
                        } else {
                            self.abort_refused(pools, op, MergeStep::SourcesSealed, &status)
                                .await
                        }
                    }
                    err => Err(err),
                };
            }
        };
        let folded = response.person.ok_or_else(|| {
            SagaError::CorruptState(format!(
                "fold response for merge op {} carries no document",
                op.op_id
            ))
        })?;
        let survivor = serde_json::json!({
            "id": folded.id,
            "uuid": folded.uuid,
            "properties": serde_json::from_slice::<Value>(&folded.properties)
                .unwrap_or_else(|_| Value::Object(serde_json::Map::new())),
            "created_at": folded.created_at,
            "last_seen_at": folded.last_seen_at,
            "is_identified": folded.is_identified,
            "version": folded.version,
        });

        let mut tx = pools.begin(Lane::Heavy).await?;
        mirrored_query!(
            self.tables.is_validation(),
            op = "merge_fold_record_target",
            "UPDATE {lifecycle_op_person} SET sealed = $2 WHERE op_id = $1 AND role = $3",
            op.op_id,
            survivor,
            ROLE_TARGET
            => execute(&mut *tx)
        )?;
        if !advance_step_in_tx(
            &mut tx,
            &self.tables,
            op.op_id,
            MergeStep::SourcesSealed.as_str(),
            MergeStep::DocumentFolded.as_str(),
        )
        .await?
        {
            tx.rollback().await?;
            return Ok(());
        }
        tx.commit().await?;
        record_transition(
            MergeStep::SourcesSealed.as_str(),
            MergeStep::DocumentFolded.as_str(),
        );
        Ok(())
    }
}

async fn target_row(
    pools: &IdentityPools,
    tables: &IdentityTables,
    op: &OpRow,
) -> Result<PersonRef, SagaError> {
    Ok(mirrored_query_as!(
        PersonRef,
        tables.is_validation(),
        op = "merge_target_row",
        "SELECT person_id, person_uuid FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
        op.op_id,
        ROLE_TARGET
        => fetch_one(pools.fast())
    )?)
}

async fn sealed_sources(
    pools: &IdentityPools,
    tables: &IdentityTables,
    op: &OpRow,
) -> Result<Vec<SealedSource>, SagaError> {
    Ok(mirrored_query_as!(
        SealedSource,
        tables.is_validation(),
        op = "merge_sealed_sources",
        r#"
        SELECT person_id, person_uuid, ordinal as "ordinal!", sealed as "sealed!"
        FROM {lifecycle_op_person}
        WHERE op_id = $1 AND role = $2 AND status = $3
        ORDER BY ordinal
        "#,
        op.op_id,
        ROLE_SOURCE,
        STATUS_SEALED
        => fetch_all(pools.fast())
    )?)
}

fn encode_json_map(value: &Value) -> Result<Vec<u8>, SagaError> {
    if value.is_null() {
        return Ok(Vec::new());
    }
    serde_json::to_vec(value)
        .map_err(|e| SagaError::CorruptState(format!("failed to serialize event payload: {e}")))
}

/// `document_folded → flipped`: the destroying transaction, all Postgres.
/// Repoint every sealed source's distinct ids to the target (recording the
/// moves per source row in the same commit), move cohort membership and
/// hash-key overrides target-wins, scrub and tombstone the source person
/// rows at their exact death versions, and clear the target's mark. The
/// source marks stay: they are the fences' durable record until release.
async fn flip(pools: &IdentityPools, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
    let team_id = op.team_id as i32;
    let mut tx = pools.begin(Lane::Heavy).await?;

    let target: i64 = mirrored_query_scalar!(
        tables.is_validation(),
        op = "merge_flip_target",
        "SELECT person_id FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
        op.op_id,
        ROLE_TARGET
        => fetch_one(&mut *tx)
    )?;
    let mut sources: Vec<i64> = mirrored_query_scalar!(
        tables.is_validation(),
        op = "merge_flip_sources",
        r#"
        SELECT person_id FROM {lifecycle_op_person}
        WHERE op_id = $1 AND role = $2 AND status = $3
        "#,
        op.op_id,
        ROLE_SOURCE,
        STATUS_SEALED
        => fetch_all(&mut *tx)
    )?;
    sources.sort_unstable();

    // Lock every row up front in id order; the writer's flush does the
    // same, so a deadlock cycle is impossible. Including the target keeps
    // the lock set a superset of any partner's.
    let mut lock_ids = sources.clone();
    lock_ids.push(target);
    lock_ids.sort_unstable();
    let lock_persons_sql = format!(
        "SELECT id FROM {person_table} WHERE team_id = $1 AND id = ANY($2) ORDER BY id FOR NO KEY UPDATE",
        person_table = tables.person,
    );
    sqlx::query(&query_tag!("merge_flip_lock_persons", lock_persons_sql))
        .bind(team_id)
        .bind(&lock_ids)
        .execute(&mut *tx)
        .await?;
    let lock_pdi_sql = format!(
        "SELECT id FROM {pdi_table} WHERE team_id = $1 AND person_id = ANY($2) ORDER BY id FOR UPDATE",
        pdi_table = tables.person_distinct_id,
    );
    sqlx::query(&query_tag!("merge_flip_lock_distinct_ids", lock_pdi_sql))
        .bind(team_id)
        .bind(&sources)
        .execute(&mut *tx)
        .await?;

    let repointed = repoint_distinct_ids(&mut tx, tables, team_id, &sources, target).await?;
    record_moved_mappings(&mut tx, tables, op, &sources, &repointed).await?;
    move_cohort_membership(&mut tx, tables, &sources, target).await?;
    move_hash_key_overrides(&mut tx, tables, team_id, &sources, target).await?;
    let moved_above_seal = tombstone_sealed_sources(&mut tx, tables, op, team_id).await?;
    clear_target_mark(&mut tx, tables, op).await?;

    if !advance_step_in_tx(
        &mut tx,
        tables,
        op.op_id,
        MergeStep::DocumentFolded.as_str(),
        MergeStep::Flipped.as_str(),
    )
    .await?
    {
        tx.rollback().await?;
        return Ok(());
    }
    tx.commit().await?;
    record_transition(
        MergeStep::DocumentFolded.as_str(),
        MergeStep::Flipped.as_str(),
    );
    // Reported after the commit: a driver that loses the step CAS sees the
    // winner's tombstone as a moved row, and its transaction rolls back.
    if !moved_above_seal.is_empty() {
        tracing::warn!(
            op_id = %op.op_id,
            team_id = op.team_id,
            persons = moved_above_seal.len(),
            person_sealed_tombstone = ?moved_above_seal,
            "merge source tombstones landed above sealed + 1; the rows moved after the seal"
        );
        common_metrics::inc(
            TOMBSTONES_ABOVE_SEAL_TOTAL,
            &[],
            moved_above_seal.len() as u64,
        );
    }
    Ok(())
}

/// One distinct-id row repointed by [`repoint_distinct_ids`], keyed by its
/// pre-update owner.
struct RepointedDid {
    old_person_id: i64,
    distinct_id: String,
    version: i64,
}

/// Repoint every sealed source's live distinct ids to the target, bumping
/// each row's version.
async fn repoint_distinct_ids(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    team_id: i32,
    sources: &[i64],
    target: i64,
) -> Result<Vec<RepointedDid>, SagaError> {
    // RETURNING sees the post-update row, so the pre-update owner has to
    // come from a self-join snapshot — without it every returned
    // person_id would be the target.
    let repoint_sql = format!(
        r#"
        UPDATE {pdi_table} pdi
        SET person_id = $3, version = COALESCE(pdi.version, 0) + 1
        FROM {pdi_table} old
        WHERE old.id = pdi.id
          AND pdi.team_id = $1 AND pdi.person_id = ANY($2) AND pdi.is_deleted = false
        RETURNING old.person_id, pdi.distinct_id, pdi.version
        "#,
        pdi_table = tables.person_distinct_id,
    );
    let rows: Vec<(i64, String, i64)> =
        sqlx::query_as(&query_tag!("merge_repoint_distinct_ids", repoint_sql))
            .bind(team_id)
            .bind(sources)
            .bind(target)
            .fetch_all(&mut **tx)
            .await?;
    Ok(rows
        .into_iter()
        .map(|(old_person_id, distinct_id, version)| RepointedDid {
            old_person_id,
            distinct_id,
            version,
        })
        .collect())
}

/// Record the repointed mappings per source in the same commit — what a
/// later ClickHouse emission (or an operator) reads back (delete parity).
async fn record_moved_mappings(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    op: &OpRow,
    sources: &[i64],
    repointed: &[RepointedDid],
) -> Result<(), SagaError> {
    let mut moved_ids: Vec<i64> = Vec::new();
    let mut moved_json: Vec<Value> = Vec::new();
    for source in sources {
        let rows: Vec<Value> = repointed
            .iter()
            .filter(|r| r.old_person_id == *source)
            .map(|r| serde_json::json!({"distinct_id": r.distinct_id, "version": r.version}))
            .collect();
        if !rows.is_empty() {
            moved_ids.push(*source);
            moved_json.push(Value::Array(rows));
        }
    }
    if moved_ids.is_empty() {
        return Ok(());
    }
    mirrored_query!(
        tables.is_validation(),
        op = "merge_record_moved_mappings",
        r#"
        UPDATE {lifecycle_op_person} lop
        SET moved = u.moved
        FROM unnest($2::bigint[], $3::jsonb[]) AS u(person_id, moved)
        WHERE lop.op_id = $1 AND lop.person_id = u.person_id
        "#,
        op.op_id,
        &moved_ids,
        &moved_json
        => execute(&mut **tx)
    )?;
    Ok(())
}

/// Cohort membership moves wholesale. The table has no unique
/// constraint, so a target already in a cohort ends up with duplicate
/// rows — deliberately matching the production merge path, whose
/// recalculation heals the rare duplicate.
async fn move_cohort_membership(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    sources: &[i64],
    target: i64,
) -> Result<(), SagaError> {
    // posthog_cohortpeople has no shadow mirror and no team_id column, so it
    // is only addressable by real posthog_person ids. On any other person
    // table the source ids come from that table's own sequence and would
    // collide with unrelated persons' cohort rows — skip the move entirely.
    if tables.person != "posthog_person" {
        return Ok(());
    }
    sqlx::query!(
        "/* service='personhog-identity', operation='merge_move_cohort_membership' */ UPDATE posthog_cohortpeople SET person_id = $2 WHERE person_id = ANY($1)",
        sources,
        target,
    )
    .execute(&mut **tx)
    .await?;
    Ok(())
}

/// Hash-key overrides move target-wins: the target's existing override
/// for a flag beats any source's. The cookieless sentinel is not a real
/// key. The merge drops a source's sentinel row. A source's real key
/// replaces a sentinel on the target.
async fn move_hash_key_overrides(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    team_id: i32,
    sources: &[i64],
    target: i64,
) -> Result<(), SagaError> {
    // Postgres rejects an ON CONFLICT DO UPDATE statement that changes the
    // same row twice, so DISTINCT ON keeps one row per flag.
    let move_sql = format!(
        r#"
        WITH removed AS (
            DELETE FROM {override_table}
            WHERE team_id = $1 AND person_id = ANY($2)
            RETURNING feature_flag_key, hash_key
        )
        INSERT INTO {override_table} (team_id, person_id, feature_flag_key, hash_key)
        SELECT DISTINCT ON (feature_flag_key) $1, $3, feature_flag_key, hash_key
        FROM removed
        WHERE hash_key <> $4
        ON CONFLICT (team_id, person_id, feature_flag_key) DO UPDATE
            SET hash_key = EXCLUDED.hash_key
            WHERE {override_table}.hash_key = $4
        "#,
        override_table = tables.ff_hash_key_override,
    );
    sqlx::query(&query_tag!("merge_move_hash_key_overrides", move_sql))
        .bind(team_id)
        .bind(sources)
        .bind(target)
        .bind(COOKIELESS_SENTINEL_VALUE)
        .execute(&mut **tx)
        .await?;
    Ok(())
}

/// Scrub and tombstone the sealed source person rows at sealed + 1, the
/// death version the leader derives from the same seal, so a reused key
/// revives above it. The fence stops leader writes only: a writer on the
/// Postgres path can move a source row past its seal before the flip, so
/// the tombstone also clears the row's own version. The committed version
/// joins the seal, and the release carries it to the leader. Returns the
/// rows that moved, as (person_id, sealed_version, tombstone_version).
async fn tombstone_sealed_sources(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    op: &OpRow,
    team_id: i32,
) -> Result<Vec<(i64, i64, i64)>, SagaError> {
    let tombstone_sql = format!(
        r#"
        UPDATE {person_table} p
        SET is_deleted = true,
            properties = '{{}}'::jsonb,
            properties_last_updated_at = '{{}}'::jsonb,
            properties_last_operation = '{{}}'::jsonb,
            version = GREATEST(COALESCE(p.version, 0) + 1, (lop.sealed->>'version')::bigint + 1)
        FROM {lop_table} lop
        WHERE lop.op_id = $1 AND lop.role = $3 AND lop.status = $4
          AND p.team_id = $2 AND p.id = lop.person_id
        RETURNING p.id, p.version, (lop.sealed->>'version')::bigint
        "#,
        person_table = tables.person,
        lop_table = tables.lifecycle_op_person,
    );
    let tombstoned_sources: Vec<(i64, i64, Option<i64>)> =
        sqlx::query_as(&query_tag!("merge_tombstone_sealed_sources", tombstone_sql))
            .bind(op.op_id)
            .bind(team_id)
            .bind(ROLE_SOURCE)
            .bind(STATUS_SEALED)
            .fetch_all(&mut **tx)
            .await?;
    let moved_above_seal: Vec<(i64, i64, i64)> = tombstoned_sources
        .iter()
        .filter_map(|(id, version, sealed)| {
            sealed
                .filter(|sealed| *version > sealed + 1)
                .map(|sealed| (*id, sealed, *version))
        })
        .collect();

    let (tombstoned_ids, tombstone_versions): (Vec<i64>, Vec<i64>) = tombstoned_sources
        .into_iter()
        .map(|(id, version, _)| (id, version))
        .unzip();
    mirrored_query!(
        tables.is_validation(),
        op = "merge_flip_record_tombstone_versions",
        r#"
        UPDATE {lifecycle_op_person} lop
        SET sealed = lop.sealed || jsonb_build_object('tombstone_version', u.version)
        FROM unnest($2::bigint[], $3::bigint[]) AS u(person_id, version)
        WHERE lop.op_id = $1 AND lop.person_id = u.person_id
        "#,
        op.op_id,
        &tombstoned_ids,
        &tombstone_versions
        => execute(&mut **tx)
    )?;
    Ok(moved_above_seal)
}

/// The target's own person row is untouched: the folded document
/// reaches Postgres through the writer's projection (single-writer
/// rule). Only its mark clears — from here the merged person is
/// claimable by other lifecycle ops.
async fn clear_target_mark(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    op: &OpRow,
) -> Result<(), SagaError> {
    mirrored_query!(
        tables.is_validation(),
        op = "merge_clear_target_mark",
        "UPDATE {lifecycle_op_person} SET status = $2, mark_active = false WHERE op_id = $1 AND role = $3",
        op.op_id,
        STATUS_CLEARED,
        ROLE_TARGET
        => execute(&mut **tx)
    )?;
    Ok(())
}

impl MergeDriver {
    /// `flipped → completed`: release every source fence with outcome
    /// committed — the leader verifies the live mark and produces each
    /// death document — then settle the rows and record the outcome. The
    /// order is load-bearing: the mark flip to `deleted` must follow the
    /// release ack, because to the leader a `deleted` mark means "the
    /// death document already exists; absorb the retry". Flipping first
    /// would make the first-ever release absorb and never produce.
    async fn complete(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
        let sources = sealed_sources(pools, &self.tables, op).await?;

        let release_calls: Vec<_> = sources
            .iter()
            .map(|source| {
                let snapshot: Result<SealedSnapshot, _> =
                    serde_json::from_value(source.sealed.clone());
                let leader = Arc::clone(&self.leader);
                let op_id = op.op_id.to_string();
                let team_id = op.team_id;
                let person_id = source.person_id;
                let person_uuid = source.person_uuid.to_string();
                async move {
                    let snapshot = match snapshot {
                        Ok(snapshot) => snapshot,
                        Err(e) => {
                            return (
                                person_id,
                                Err(SagaError::CorruptState(format!(
                                    "merge source {person_id} has a malformed seal: {e}"
                                ))),
                            )
                        }
                    };
                    let result = leader
                        .release_fence(ReleaseFenceRequest {
                            team_id,
                            person_id,
                            person_uuid,
                            op_id,
                            outcome: ReleaseOutcome::Committed.into(),
                            sealed_version: Some(snapshot.version),
                            created_at: snapshot.created_at,
                            tombstone_version: snapshot.tombstone_version,
                        })
                        .await
                        .map(|_| ())
                        .map_err(SagaError::leader);
                    (person_id, result)
                }
            })
            .collect();
        let release_results: Vec<_> = stream::iter(release_calls)
            .buffer_unordered(self.leader_call_concurrency)
            .collect()
            .await;
        for (_, result) in release_results {
            result?;
        }

        let mut tx = pools.begin(Lane::Heavy).await?;
        mirrored_query!(
            self.tables.is_validation(),
            op = "merge_complete",
            r#"
            UPDATE {lifecycle_op_person} SET status = $2, mark_active = false
            WHERE op_id = $1 AND role = $3 AND status = $4
            "#,
            op.op_id,
            STATUS_DELETED,
            ROLE_SOURCE,
            STATUS_SEALED
            => execute(&mut *tx)
        )?;
        let outcome = build_outcome(&mut tx, &self.tables, op, None).await?;
        if !complete_op_in_tx(
            &mut tx,
            &self.tables,
            op.op_id,
            MergeStep::Flipped.as_str(),
            &outcome,
            self.outbox_writes,
        )
        .await?
        {
            tx.rollback().await?;
            return Ok(());
        }
        tx.commit().await?;
        record_transition(MergeStep::Flipped.as_str(), STEP_COMPLETED);
        record_outcomes(MergeStep::Flipped.as_str(), &outcome);
        emit_terminal_warnings(&self.warnings, op, &outcome);
        Ok(())
    }
}

async fn claim_record(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    op: &OpRow,
) -> Result<ClaimRecord, SagaError> {
    let moved = mirrored_query_scalar!(
        tables.is_validation(),
        op = "merge_load_claim_record",
        "SELECT moved FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
        op.op_id,
        ROLE_TARGET
        => fetch_one(&mut **tx)
    )?;
    let moved = moved.ok_or_else(|| {
        SagaError::CorruptState(format!("merge op {} has no claim record", op.op_id))
    })?;
    serde_json::from_value(moved).map_err(|e| {
        SagaError::CorruptState(format!(
            "merge op {} claim record is malformed: {e}",
            op.op_id
        ))
    })
}

/// Build the terminal outcome from the persisted claim record and the
/// settled per-person rows. `pending_merge` decisions resolve through
/// their row's status: `deleted` means the merge committed for that
/// person; anything else on a non-aborted path is an anomaly reported as
/// `error`.
async fn build_outcome(
    tx: &mut Tx<'_>,
    tables: &IdentityTables,
    op: &OpRow,
    abort_outcome: Option<AbortOutcome>,
) -> Result<Value, SagaError> {
    let record = claim_record(tx, tables, op).await?;
    let statuses: HashMap<i64, String> = mirrored_query_as!(
        PersonStatus,
        tables.is_validation(),
        op = "merge_outcome_statuses",
        "SELECT person_id, status FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
        op.op_id,
        ROLE_SOURCE
        => fetch_all(&mut **tx)
    )?
    .into_iter()
    .map(|r| (r.person_id, r.status))
    .collect();

    let survivor = if abort_outcome.is_some() {
        None
    } else {
        mirrored_query_scalar!(
            tables.is_validation(),
            op = "merge_outcome_sealed",
            "SELECT sealed FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
            op.op_id,
            ROLE_TARGET
            => fetch_one(&mut **tx)
        )?
    };

    outcome_from_dispositions(&record.dispositions, abort_outcome, survivor, &statuses)
}

fn outcome_from_dispositions(
    dispositions: &[Disposition],
    abort_outcome: Option<AbortOutcome>,
    survivor: Option<Value>,
    statuses: &HashMap<i64, String>,
) -> Result<Value, SagaError> {
    let results = dispositions
        .iter()
        .map(|d| {
            let outcome = if d.decision == DECISION_PENDING_MERGE {
                let status = d
                    .person_id
                    .and_then(|id| statuses.get(&id))
                    .map(String::as_str);
                match (abort_outcome, status) {
                    (Some(abort), _) => abort.as_str(),
                    (None, Some(STATUS_DELETED)) => OUTCOME_MERGED,
                    (None, _) => OUTCOME_ERROR,
                }
            } else {
                d.decision.as_str()
            };
            MergeSourceRecord {
                distinct_id: d.distinct_id.clone(),
                outcome: outcome.to_string(),
                person_id: d.person_id,
                person_uuid: d.person_uuid,
            }
        })
        .collect();
    serde_json::to_value(MergeOutcome {
        aborted: abort_outcome.is_some(),
        survivor,
        results,
    })
    .map_err(|e| SagaError::CorruptState(format!("failed to serialize merge outcome: {e}")))
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use chrono::Utc;
    use common_ingestion_warnings::test_support::CollectingRowEmitter;
    use common_ingestion_warnings::WarningType;

    use super::*;

    fn terminal_row(request: &MergeRequest, outcome: &Value) -> OpRow {
        OpRow {
            op_id: Uuid::now_v7(),
            op_type: OP_TYPE_MERGE.to_string(),
            team_id: 7,
            step: STEP_ABORTED.to_string(),
            attempt: 1,
            request: serde_json::to_value(request).unwrap(),
            outcome: Some(outcome.clone()),
            created_at: Utc::now(),
            completed_at: Some(Utc::now()),
            lease_live: false,
        }
    }

    #[test]
    fn terminal_warnings_read_the_recorded_shapes() {
        let source_uuid = Uuid::new_v4();
        let survivor_uuid = Uuid::new_v4();
        let request = MergeRequest {
            target_distinct_id: "user-1".to_string(),
            sources: vec![MergeSourceEntry {
                distinct_id: "anon-1".to_string(),
                event_uuid: String::new(),
            }],
            event_set: serde_json::json!({"plan": "pro"}),
            event_set_once: serde_json::json!({}),
            allow_identified_sources: false,
            move_limit: 10,
            creator_event_uuid: "creator".to_string(),
            target_born: false,
        };
        let outcome = serde_json::to_value(MergeOutcome {
            aborted: false,
            survivor: Some(serde_json::json!({"id": 9, "uuid": survivor_uuid})),
            results: vec![MergeSourceRecord {
                distinct_id: "anon-1".to_string(),
                outcome: OUTCOME_SKIPPED_REFUSED.to_string(),
                person_id: Some(42),
                person_uuid: Some(source_uuid),
            }],
        })
        .unwrap();
        let row = terminal_row(&request, &outcome);

        let emitter = Arc::new(CollectingRowEmitter::new());
        emit_terminal_warnings(&MergeWarnings::new(emitter.clone()), &row, &outcome);
        let rows = emitter.rows();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].warning, WarningType::MergeSettledFailure);
        assert_eq!(rows[0].team_id, 7);
        let details = rows[0].details();
        assert_eq!(details["sourcePersonDistinctId"], "anon-1");
        assert_eq!(details["targetPersonDistinctId"], "user-1");
        assert_eq!(
            details["eventUuid"], "creator",
            "empty source event falls back"
        );
        assert_eq!(details["sourcePersonId"], "42");
        assert_eq!(details["otherPersonId"], source_uuid.to_string());
        assert_eq!(details["personId"], survivor_uuid.to_string());
        assert_eq!(details["outcome"], OUTCOME_SKIPPED_REFUSED);
    }

    fn pending(distinct_id: &str, person_id: i64) -> Disposition {
        Disposition {
            distinct_id: distinct_id.to_string(),
            person_id: Some(person_id),
            person_uuid: None,
            decision: DECISION_PENDING_MERGE.to_string(),
        }
    }

    fn resolution(person_id: i64) -> Resolution {
        Resolution {
            person_id,
            person_uuid: Uuid::new_v4(),
            is_identified: false,
        }
    }

    #[test]
    fn a_remapped_did_settles_as_conflict_while_a_sibling_keeps_the_person() {
        let mut dispositions = vec![pending("d1", 7), pending("d2", 7)];
        let claim_persons = vec![(7, Uuid::new_v4(), 0)];
        // d2 was remapped to person 9 between the resolve and the recheck.
        let fresh = HashMap::from([
            ("d1".to_string(), resolution(7)),
            ("d2".to_string(), resolution(9)),
        ]);

        let dropped = reconcile_pending_claims(
            &mut dispositions,
            &claim_persons,
            &[7],
            &fresh,
            &mut Vec::new(),
        );

        assert!(dropped.is_empty(), "person 7 is still reachable via d1");
        assert_eq!(dispositions[0].decision, DECISION_PENDING_MERGE);
        assert_eq!(
            dispositions[1].decision, OUTCOME_SKIPPED_CONFLICT,
            "the remapped did must not later be reported as merged"
        );
    }

    #[test]
    fn a_person_with_no_reachable_did_left_is_dropped() {
        let mut dispositions = vec![pending("d1", 7), pending("d2", 7)];
        let claim_persons = vec![(7, Uuid::new_v4(), 0)];
        let fresh = HashMap::from([
            ("d1".to_string(), resolution(9)),
            ("d2".to_string(), resolution(9)),
        ]);

        let dropped = reconcile_pending_claims(
            &mut dispositions,
            &claim_persons,
            &[7],
            &fresh,
            &mut Vec::new(),
        );

        assert_eq!(dropped, vec![7]);
        for d in &dispositions {
            assert_eq!(d.decision, OUTCOME_SKIPPED_CONFLICT);
        }
    }
}