Skip to content

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

fix(personhog): harden MergePersons payload handling and retry contract (#82270)

Nick Best00190e9730a8
diff --git a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts
index 6315f577054f..99201587fa4e 100644
--- a/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts
+++ b/nodejs/src/common/generated/personhog/personhog/identity/v1/identity_pb.ts
@@ -455,9 +455,13 @@ export type MergePersonsRequest = Message<'personhog.identity.v1.MergePersonsReq
/**
* Caller-generated operation id (UUID string), typically the executing
- * event's uuid. A retried call carrying the same op_id returns the
- * recorded outcome of the original run instead of merging again, so
- * callers must reuse the op_id across retries.
+ * event's uuid. Callers must reuse the op_id across retries: when the
+ * original run merged distinct persons (ran the durable saga), a retry
+ * returns the recorded outcome instead of merging again. Calls that
+ * settle entirely inline (no-ops, attaches, skips) write no durable
+ * record; their retries re-execute against the current state and
+ * return an equivalent settlement — an attached source, for example,
+ * re-answers NOOP_SAME_PERSON.
*
* @generated from field: string op_id = 6;
*/
@@ -583,8 +587,7 @@ export enum MergeSourceOutcome {
/**
* The source distinct id had no person, so it was attached to the
- * survivor with a plain mapping insert. Reserved for the personless-free
- * world; nothing returns it yet (unresolved sources are ERROR for now).
+ * survivor with a plain mapping insert.
*
* @generated from enum value: MERGE_SOURCE_OUTCOME_ATTACHED = 3;
*/
@@ -592,7 +595,8 @@ export enum MergeSourceOutcome {
/**
* The source distinct id is on the illegal-id list ('anonymous',
- * 'undefined', ...). Never merged.
+ * 'undefined', ...) or exceeds the 400-character storage limit, so it
+ * can never resolve to a person. Never merged.
*
* @generated from enum value: MERGE_SOURCE_OUTCOME_SKIPPED_ILLEGAL = 4;
*/
@@ -622,9 +626,7 @@ export enum MergeSourceOutcome {
SKIPPED_MOVE_LIMIT = 7,
/**
- * The pair could not be handled; details in server logs. Currently also
- * the outcome for sources that resolve to no person (unresolved-source
- * attach is not implemented yet).
+ * The pair could not be handled; details in server logs.
*
* @generated from enum value: MERGE_SOURCE_OUTCOME_ERROR = 8;
*/
@@ -654,8 +656,13 @@ export const MergeSourceOutcomeSchema: GenEnum<MergeSourceOutcome> =
*
* MergePersons semantics: the RPC drives the merge to completion before
* responding. Most merges settle inline (same-person, illegal source); only
- * distinct-person pairs run the durable lifecycle saga. Retries with the same
- * op_id return the recorded outcome.
+ * distinct-person pairs run the durable lifecycle saga. Retries with the
+ * same op_id return the recorded outcome when a saga ran, and an
+ * equivalent re-execution when the call settled inline (see the op_id
+ * field). A definitive refusal is FAILED_PRECONDITION carrying an
+ * x-semantic-refusal reason slug to branch on — "op_id_reused" means the
+ * op_id belongs to a different request. A bare UNAVAILABLE is transient;
+ * retry with the same op_id.
*
* @generated from service personhog.identity.v1.PersonHogIdentity
*/
@@ -706,8 +713,9 @@ export const PersonHogIdentity: GenService<{
* inline, distinct-person pairs run the durable merge saga (fence the
* sources, fold their sealed documents into the target, repoint distinct
* ids, tombstone the sources, produce death documents). An unresolved
- * TARGET refuses the call FAILED_PRECONDITION; an illegal target
- * distinct id refuses it INVALID_ARGUMENT before any durable work.
+ * TARGET is established first: attached to the first eligible source's
+ * person, or born fresh. An illegal target distinct id refuses the call
+ * INVALID_ARGUMENT before any durable work.
*
* @generated from rpc personhog.identity.v1.PersonHogIdentity.MergePersons
*/
diff --git a/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts b/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts
index 387a19890417..b15742aa9f47 100644
--- a/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts
+++ b/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts
@@ -1174,11 +1174,12 @@ export type ReleaseFenceRequest = Message<'personhog.types.v1.ReleaseFenceReques
/**
* The person's creation time as sealed at fence time, in epoch
- * seconds — the unit Person.created_at carries end to end (the leader
- * loads `timestamp()`, the writer binds via `epoch_secs_to_datetime`).
- * The death document carries it verbatim — a cold leader has nothing
- * to re-derive it from, and the writer projects it onto the tombstone
- * row. Required when outcome = COMMITTED.
+ * milliseconds — the unit Person.created_at carries end to end (the
+ * leader loads `timestamp_millis()`, the writer binds via
+ * `epoch_ms_to_datetime`). The death document carries it verbatim — a
+ * cold leader has nothing to re-derive it from, and the writer
+ * projects it onto the tombstone row. Required when outcome =
+ * COMMITTED.
*
* @generated from field: int64 created_at = 7;
*/
diff --git a/proto/personhog/identity/v1/identity.proto b/proto/personhog/identity/v1/identity.proto
index fb4388bc0aa5..ee341127220b 100644
--- a/proto/personhog/identity/v1/identity.proto
+++ b/proto/personhog/identity/v1/identity.proto
@@ -135,9 +135,13 @@ message MergePersonsRequest {
bytes event_set = 4;
bytes event_set_once = 5;
// Caller-generated operation id (UUID string), typically the executing
- // event's uuid. A retried call carrying the same op_id returns the
- // recorded outcome of the original run instead of merging again, so
- // callers must reuse the op_id across retries.
+ // event's uuid. Callers must reuse the op_id across retries: when the
+ // original run merged distinct persons (ran the durable saga), a retry
+ // returns the recorded outcome instead of merging again. Calls that
+ // settle entirely inline (no-ops, attaches, skips) write no durable
+ // record; their retries re-execute against the current state and
+ // return an equivalent settlement — an attached source, for example,
+ // re-answers NOOP_SAME_PERSON.
string op_id = 6;
// $merge_dangerously legally merges already-identified sources;
// $identify does not. Off by default.
@@ -159,11 +163,11 @@ enum MergeSourceOutcome {
// The source distinct id already resolves to the survivor. Nothing to do.
MERGE_SOURCE_OUTCOME_NOOP_SAME_PERSON = 2;
// The source distinct id had no person, so it was attached to the
- // survivor with a plain mapping insert. Reserved for the personless-free
- // world; nothing returns it yet (unresolved sources are ERROR for now).
+ // survivor with a plain mapping insert.
MERGE_SOURCE_OUTCOME_ATTACHED = 3;
// The source distinct id is on the illegal-id list ('anonymous',
- // 'undefined', ...). Never merged.
+ // 'undefined', ...) or exceeds the 400-character storage limit, so it
+ // can never resolve to a person. Never merged.
MERGE_SOURCE_OUTCOME_SKIPPED_ILLEGAL = 4;
// The source person is already identified and the request did not set
// allow_identified_sources.
@@ -173,9 +177,7 @@ enum MergeSourceOutcome {
MERGE_SOURCE_OUTCOME_SKIPPED_CONFLICT = 6;
// The source person has more distinct ids than the request's move_limit.
MERGE_SOURCE_OUTCOME_SKIPPED_MOVE_LIMIT = 7;
- // The pair could not be handled; details in server logs. Currently also
- // the outcome for sources that resolve to no person (unresolved-source
- // attach is not implemented yet).
+ // The pair could not be handled; details in server logs.
MERGE_SOURCE_OUTCOME_ERROR = 8;
}
@@ -211,8 +213,13 @@ message MergePersonsResponse {
//
// MergePersons semantics: the RPC drives the merge to completion before
// responding. Most merges settle inline (same-person, illegal source); only
-// distinct-person pairs run the durable lifecycle saga. Retries with the same
-// op_id return the recorded outcome.
+// distinct-person pairs run the durable lifecycle saga. Retries with the
+// same op_id return the recorded outcome when a saga ran, and an
+// equivalent re-execution when the call settled inline (see the op_id
+// field). A definitive refusal is FAILED_PRECONDITION carrying an
+// x-semantic-refusal reason slug to branch on — "op_id_reused" means the
+// op_id belongs to a different request. A bare UNAVAILABLE is transient;
+// retry with the same op_id.
service PersonHogIdentity {
rpc GetOrCreatePersonByDistinctId(GetOrCreatePersonByDistinctIdRequest) returns (GetOrCreatePersonByDistinctIdResponse);
rpc GetOrCreatePersonsByDistinctIds(GetOrCreatePersonsByDistinctIdsRequest) returns (GetOrCreatePersonsByDistinctIdsResponse);
@@ -229,7 +236,8 @@ service PersonHogIdentity {
// inline, distinct-person pairs run the durable merge saga (fence the
// sources, fold their sealed documents into the target, repoint distinct
// ids, tombstone the sources, produce death documents). An unresolved
- // TARGET refuses the call FAILED_PRECONDITION; an illegal target
- // distinct id refuses it INVALID_ARGUMENT before any durable work.
+ // TARGET is established first: attached to the first eligible source's
+ // person, or born fresh. An illegal target distinct id refuses the call
+ // INVALID_ARGUMENT before any durable work.
rpc MergePersons(MergePersonsRequest) returns (MergePersonsResponse);
}
diff --git a/proto/personhog/types/v1/person.proto b/proto/personhog/types/v1/person.proto
index 19fde29a7e9a..a7386ff93fcb 100644
--- a/proto/personhog/types/v1/person.proto
+++ b/proto/personhog/types/v1/person.proto
@@ -338,11 +338,12 @@ message ReleaseFenceRequest {
// from it.
optional int64 sealed_version = 6;
// The person's creation time as sealed at fence time, in epoch
- // seconds — the unit Person.created_at carries end to end (the leader
- // loads `timestamp()`, the writer binds via `epoch_secs_to_datetime`).
- // The death document carries it verbatim — a cold leader has nothing
- // to re-derive it from, and the writer projects it onto the tombstone
- // row. Required when outcome = COMMITTED.
+ // milliseconds — the unit Person.created_at carries end to end (the
+ // leader loads `timestamp_millis()`, the writer binds via
+ // `epoch_ms_to_datetime`). The death document carries it verbatim — a
+ // cold leader has nothing to re-derive it from, and the writer
+ // projects it onto the tombstone row. Required when outcome =
+ // COMMITTED.
int64 created_at = 7;
}
diff --git a/rust/personhog-common/src/properties.rs b/rust/personhog-common/src/properties.rs
index d31c1be0d388..b0dde2f6d72a 100644
--- a/rust/personhog-common/src/properties.rs
+++ b/rust/personhog-common/src/properties.rs
@@ -123,7 +123,10 @@ impl SanitizeStats {
}
/// Rewrite the merged state so that it both applies to Postgres jsonb and
-/// round-trips back out of it, at any depth:
+/// round-trips back out of it *unchanged* — a sanitized value compares
+/// equal to its own jsonb round-trip, which idempotency guards (frozen
+/// request rows, no-op detection against cached state) rely on. At any
+/// depth:
///
/// * `\u{0000}` (NUL) becomes `\u{FFFD}` in every string — keys and
/// values — mirroring the Node.js pipeline's `sanitizeJsonbValue`;
@@ -133,6 +136,11 @@ impl SanitizeStats {
/// * Floats beyond ±[`MAX_JSONB_SAFE_MAGNITUDE`] are clamped to it, so
/// Postgres's expanded numeric rendering stays parseable on the way
/// back (see the constant's doc).
+/// * Floats holding an exact integer become JSON integers: jsonb renders
+/// numerics in plain decimal, so `1e17` comes back as
+/// `100000000000000000`, which serde_json parses as an integer — never
+/// equal to the float that went in. Converting up front makes the
+/// stored form and the sanitized form the same value.
pub fn sanitize_for_jsonb(value: &mut Value) -> SanitizeStats {
let mut stats = SanitizeStats::default();
sanitize_value(value, &mut stats);
@@ -150,11 +158,15 @@ fn sanitize_value(value: &mut Value, stats: &mut SanitizeStats) {
Value::Number(n) => {
// Only floats can exceed the safe magnitude: i64/u64 top out
// around 1.8e19.
- if let Some(f) = n.as_f64() {
- if n.is_f64() && f.abs() > MAX_JSONB_SAFE_MAGNITUDE {
- let clamped = MAX_JSONB_SAFE_MAGNITUDE.copysign(f);
- *value = Value::from(clamped);
- stats.clamped_numbers += 1;
+ if n.is_f64() {
+ if let Some(f) = n.as_f64() {
+ if f.abs() > MAX_JSONB_SAFE_MAGNITUDE {
+ let clamped = MAX_JSONB_SAFE_MAGNITUDE.copysign(f);
+ *value = Value::from(clamped);
+ stats.clamped_numbers += 1;
+ } else if let Some(int) = integral_float_as_int(f) {
+ *value = int;
+ }
}
}
}
@@ -186,6 +198,30 @@ fn sanitize_value(value: &mut Value, stats: &mut SanitizeStats) {
}
}
+/// The integer a float canonicalizes to when its value is one, i.e. when
+/// Postgres would hand the number back as an integer literal. Positive
+/// values take the u64 path because that is what serde_json's parser
+/// yields for a positive integer literal.
+fn integral_float_as_int(f: f64) -> Option<Value> {
+ if f.fract() != 0.0 {
+ return None;
+ }
+ if f >= 0.0 {
+ // `as u64` saturates: exactly 2^64 aliases to u64::MAX, whose own
+ // f64 round-trip is 2^64 again — the equality check would convert
+ // to the wrong integer. u64::MAX itself is not representable as
+ // f64, so excluding the saturation point loses nothing.
+ let u = f as u64;
+ (u != u64::MAX && u as f64 == f).then(|| Value::from(u))
+ } else {
+ // No aliasing on this side: i64::MIN (-2^63) is exactly
+ // representable, and anything below it saturates to i64::MIN,
+ // whose round-trip then fails the equality check.
+ let i = f as i64;
+ (i as f64 == f).then(|| Value::from(i))
+ }
+}
+
/// Rewrite number tokens that serde_json refuses so the document parses,
/// mimicking `JSON.parse`'s rounding. Postgres renders jsonb numerics in
/// expanded decimal (never e-notation), and serde_json rejects expansions
@@ -639,6 +675,44 @@ mod tests {
assert_eq!(value["int"], u64::MAX);
}
+ #[test]
+ fn sanitize_canonicalizes_integral_floats_to_postgres_integers() {
+ let mut value = serde_json::json!({
+ "exp": 1e17,
+ "neg": -3e3,
+ "whole": 2.0,
+ "neg_zero": -0.0,
+ "two_63": 9.223372036854776e18,
+ "i64_min": -9.223372036854776e18,
+ "frac": 0.5,
+ });
+ let stats = sanitize_for_jsonb(&mut value);
+ assert!(
+ !stats.changed(),
+ "value-preserving rewrites are not changes"
+ );
+ assert_eq!(value["exp"], 100_000_000_000_000_000u64);
+ assert_eq!(value["neg"], -3000);
+ assert_eq!(value["whole"], 2);
+ assert_eq!(value["neg_zero"], 0);
+ assert_eq!(value["two_63"], 9_223_372_036_854_775_808u64);
+ assert_eq!(value["i64_min"], i64::MIN);
+ assert!(value["frac"].is_f64());
+ }
+
+ #[test]
+ fn sanitize_keeps_integral_floats_that_no_integer_can_hold() {
+ // 2^64 saturates the u64 cast; 1e30 is integral but far beyond it.
+ // Both already round-trip through jsonb as themselves (serde_json
+ // re-parses their expansions as the same f64), so they stay floats.
+ let mut value = serde_json::json!([1.8446744073709552e19, 1e30]);
+ sanitize_for_jsonb(&mut value);
+ assert!(value[0].is_f64());
+ assert_eq!(value[0], 1.8446744073709552e19);
+ assert!(value[1].is_f64());
+ assert_eq!(value[1], 1e30);
+ }
+
#[test]
fn sanitize_leaves_clean_values_untouched() {
let mut value = serde_json::json!({"a": "b", "n": [1, 2.5, "x"]});
diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rs
index 747b825d537a..447650022bbc 100644
--- a/rust/personhog-identity/src/lifecycle/delete.rs
+++ b/rust/personhog-identity/src/lifecycle/delete.rs
@@ -361,7 +361,7 @@ async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaE
/// external effect and a same-op re-fence is a re-seal returning fresh
/// state, so the fan-out is safe to repeat; the sealed values and the step
/// CAS commit together afterwards. The sealed jsonb records `created_at`
-/// (epoch seconds, as the leader seals it) alongside `version`; its
+/// (epoch milliseconds, as the leader seals it) alongside `version`; its
/// presence is what marks a victim as fenced when the release runs.
///
/// A victim the leader reports NOT_FOUND vanished between the claim
diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rs
index a562b5f25e2c..705873eccfab 100644
--- a/rust/personhog-identity/src/lifecycle/engine.rs
+++ b/rust/personhog-identity/src/lifecycle/engine.rs
@@ -114,7 +114,12 @@ impl From<SagaError> for Status {
fn from(err: SagaError) -> Status {
match err {
SagaError::Db(e) => Status::internal(format!("database error: {e}")),
- SagaError::RequestMismatch(msg) => Status::failed_precondition(msg),
+ // A definitive refusal (the op_id belongs to a different
+ // request), marked so callers branch on the reason instead of
+ // the message and retry layers never loop on it.
+ SagaError::RequestMismatch(msg) => {
+ personhog_common::grpc::semantic_refusal(msg, "op_id_reused")
+ }
SagaError::Busy => Status::unavailable(
"another instance is driving this operation; retry with the same op_id",
),
@@ -225,7 +230,7 @@ impl Engine {
team_id: i64,
request: &Value,
) -> Result<OpRow, SagaError> {
- sqlx::query!(
+ let inserted = sqlx::query!(
r#"
INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request)
VALUES ($1, $2, $3, $4, $5)
@@ -238,12 +243,23 @@ impl Engine {
request,
)
.execute(&self.pool)
- .await?;
+ .await?
+ .rows_affected()
+ > 0;
let row = self.load(op_id).await?.ok_or_else(|| {
SagaError::CorruptState(format!("op {op_id} vanished right after create-or-attach"))
})?;
- if row.op_type != driver.op_type() || row.team_id != team_id || row.request != *request {
+ // Only a genuine attach is verified: the reloaded copy of our own
+ // insert has been through jsonb normalization (number rewriting,
+ // key ordering), so comparing it against the caller's request
+ // would reject a first call whose request isn't normalization-
+ // stable — and its retries with it, forever.
+ if !inserted
+ && (row.op_type != driver.op_type()
+ || row.team_id != team_id
+ || row.request != *request)
+ {
return Err(SagaError::RequestMismatch(format!(
"op {op_id} already exists with a different request"
)));
diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rs
index acdeca0cd779..13e651c0e329 100644
--- a/rust/personhog-identity/src/lifecycle/merge.rs
+++ b/rust/personhog-identity/src/lifecycle/merge.rs
@@ -232,7 +232,7 @@ struct ClaimRecord {
/// 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 seconds today).
+/// in the unit `Person.created_at` carries (epoch milliseconds).
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SealedSnapshot {
version: i64,
@@ -309,6 +309,18 @@ impl MergeOpExecutor {
.execute(&self.driver, op_id, team_id, frozen)
.await
.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"
+ ));
+ }
if matches!(err, SagaError::Db(_) | SagaError::CorruptState(_)) {
tracing::error!(op_id = %op_id, error = %err, "MergePersons failed");
}
diff --git a/rust/personhog-identity/src/lifecycle/validation.rs b/rust/personhog-identity/src/lifecycle/validation.rs
index c474070b93dc..b1293b678cc6 100644
--- a/rust/personhog-identity/src/lifecycle/validation.rs
+++ b/rust/personhog-identity/src/lifecycle/validation.rs
@@ -16,6 +16,17 @@ pub const MAX_MERGE_BATCH_SIZE: usize = 250;
const MAX_DISTINCT_ID_LENGTH: usize = 400;
+/// Longer than the `posthog_persondistinctid.distinct_id` column admits.
+/// The limit counts characters, not bytes — `varchar(400)` counts
+/// characters, and capture emits multibyte ids whose UTF-8 length passes
+/// 400 bytes well inside its own 200-character cap. An oversized id can
+/// never exist in storage, so it can never resolve and must never be
+/// attached; as a merge SOURCE it settles per-source (skipped_illegal)
+/// rather than failing the batch.
+pub fn is_distinct_id_oversized(id: &str) -> bool {
+ id.chars().count() > MAX_DISTINCT_ID_LENGTH
+}
+
// Mirrors ingestion's isDistinctIdIllegal (nodejs/src/common/persons/
// person-utils.ts): generic ids that stem from a bug or mistake must never
// drive a merge. Some are illegal in any casing, others only exactly as
@@ -103,7 +114,7 @@ pub fn validate_merge_persons(request: &MergePersonsRequest) -> Result<(Uuid, i6
"team_id must be a positive 32-bit integer",
));
}
- if request.target_distinct_id.len() > MAX_DISTINCT_ID_LENGTH {
+ if is_distinct_id_oversized(&request.target_distinct_id) {
return Err(Status::invalid_argument(format!(
"target_distinct_id exceeds {MAX_DISTINCT_ID_LENGTH} characters"
)));
@@ -113,6 +124,14 @@ pub fn validate_merge_persons(request: &MergePersonsRequest) -> Result<(Uuid, i6
"target_distinct_id is an illegal distinct id",
));
}
+ // Postgres cannot store NUL in text: an unresolved NUL target would
+ // reach the establish path and fail person creation with an internal
+ // error on every attempt.
+ if request.target_distinct_id.contains('\u{0000}') {
+ return Err(Status::invalid_argument(
+ "target_distinct_id must not contain NUL",
+ ));
+ }
if request.sources.is_empty() {
return Err(Status::invalid_argument("sources must not be empty"));
}
@@ -124,10 +143,14 @@ pub fn validate_merge_persons(request: &MergePersonsRequest) -> Result<(Uuid, i6
}
let mut seen = HashSet::with_capacity(request.sources.len());
for source in &request.sources {
- if source.source_distinct_id.len() > MAX_DISTINCT_ID_LENGTH {
- return Err(Status::invalid_argument(format!(
- "a source distinct id exceeds {MAX_DISTINCT_ID_LENGTH} characters"
- )));
+ // NUL is a whole-request reject where oversized ids are a
+ // per-source outcome: Postgres cannot store NUL in text at all,
+ // so the frozen op row — which must record every requested
+ // source for retries — would be unwritable jsonb.
+ if source.source_distinct_id.contains('\u{0000}') {
+ return Err(Status::invalid_argument(
+ "source distinct ids must not contain NUL",
+ ));
}
if !seen.insert(source.source_distinct_id.as_str()) {
return Err(Status::invalid_argument(format!(
diff --git a/rust/personhog-identity/src/service/merge.rs b/rust/personhog-identity/src/service/merge.rs
index ca09532f9ea6..15132dead98d 100644
--- a/rust/personhog-identity/src/service/merge.rs
+++ b/rust/personhog-identity/src/service/merge.rs
@@ -9,6 +9,7 @@ use std::collections::HashMap;
use std::sync::Arc;
use chrono::{DateTime, Utc};
+use personhog_common::properties::sanitize_for_jsonb;
use serde_json::Value;
use tonic::Status;
@@ -24,7 +25,9 @@ use crate::lifecycle::merge::{
OP_TYPE_MERGE, OUTCOME_ERROR, OUTCOME_MERGED, OUTCOME_NOOP_SAME_PERSON,
OUTCOME_SKIPPED_ALREADY_IDENTIFIED, OUTCOME_SKIPPED_CONFLICT, OUTCOME_SKIPPED_MOVE_LIMIT,
};
-use crate::lifecycle::validation::{is_distinct_id_illegal, validate_merge_persons};
+use crate::lifecycle::validation::{
+ is_distinct_id_illegal, is_distinct_id_oversized, validate_merge_persons,
+};
use crate::storage::{AttachOutcome, IdentityStorage, Person, PersonStub, StubOutcome};
/// Handler-decided outcomes that never reach the saga.
@@ -32,6 +35,9 @@ const OUTCOME_SKIPPED_ILLEGAL: &str = "skipped_illegal";
const OUTCOME_ATTACHED: &str = "attached";
const MERGE_SOURCES_PER_CALL: &str = "personhog_identity_merge_sources_per_call";
+const PAYLOAD_NUL_SANITIZED_TOTAL: &str = "personhog_identity_merge_payload_nul_sanitized_total";
+const PAYLOAD_NUMBERS_CLAMPED_TOTAL: &str =
+ "personhog_identity_merge_payload_numbers_clamped_total";
/// The full MergePersons flow, owned by the identity side of the crate.
pub struct MergeEntrance {
@@ -62,8 +68,25 @@ impl MergeEntrance {
) -> Result<MergePersonsResponse, Status> {
let (op_id, move_limit) = validate_merge_persons(&request)?;
common_metrics::histogram(MERGE_SOURCES_PER_CALL, &[], request.sources.len() as f64);
- let event_set = parse_json_map(&request.event_set, "event_set")?;
- let event_set_once = parse_json_map(&request.event_set_once, "event_set_once")?;
+ let mut event_set = parse_json_map(&request.event_set, "event_set")?;
+ let mut event_set_once = parse_json_map(&request.event_set_once, "event_set_once")?;
+ // The frozen op row and the retry comparisons live in jsonb
+ // round-trip space: what Postgres hands back must equal what was
+ // written, or the freeze insert fails outright (NUL) and every
+ // retry is rejected as a different request (rewritten numbers).
+ // sanitize_for_jsonb is that canonical form — the leader applies
+ // the same one when the properties land, so nothing downstream
+ // sees a value the sync plane didn't.
+ let mut stats = sanitize_for_jsonb(&mut event_set);
+ let once_stats = sanitize_for_jsonb(&mut event_set_once);
+ stats.nul_strings += once_stats.nul_strings;
+ stats.clamped_numbers += once_stats.clamped_numbers;
+ if stats.nul_strings > 0 {
+ common_metrics::inc(PAYLOAD_NUL_SANITIZED_TOTAL, &[], stats.nul_strings);
+ }
+ if stats.clamped_numbers > 0 {
+ common_metrics::inc(PAYLOAD_NUMBERS_CLAMPED_TOTAL, &[], stats.clamped_numbers);
+ }
let original = merge_original(&request, &event_set, &event_set_once);
// Attach-first: classification below is time-dependent (a retry
@@ -72,16 +95,17 @@ impl MergeEntrance {
// compared on the ORIGINAL call and driven with its own frozen
// request — never re-classified. Two racing FIRST calls can still
// classify divergently and the insert loser then sees the engine's
- // full-request mismatch; that surfaces as FAILED_PRECONDITION once
- // and self-heals — the next retry attaches here.
+ // full-request mismatch; that surfaces as retryable UNAVAILABLE
+ // (see MergeOpExecutor::execute) and the retry attaches here.
if let Some(row) = self.ops.find(op_id).await? {
if row.op_type != OP_TYPE_MERGE
|| row.team_id != request.team_id
|| row.request.get("original") != Some(&original)
{
- return Err(Status::failed_precondition(format!(
- "op_id {op_id} was already used for a different request"
- )));
+ return Err(personhog_common::grpc::semantic_refusal(
+ format!("op_id {op_id} was already used for a different request"),
+ "op_id_reused",
+ ));
}
let frozen = row.request.clone();
let row = self.ops.execute(op_id, row.team_id, &frozen).await?;
@@ -118,7 +142,10 @@ impl MergeEntrance {
let mut saga_sources: Vec<MergeSourceEntry> = Vec::new();
for source in &request.sources {
let did = &source.source_distinct_id;
- if is_distinct_id_illegal(did) {
+ // Oversized ids share the illegal settlement: they cannot
+ // exist in the varchar(400) column, so they can never resolve
+ // — and attaching one would fail the insert.
+ if is_distinct_id_illegal(did) || is_distinct_id_oversized(did) {
inline_results.insert(did.clone(), OUTCOME_SKIPPED_ILLEGAL.to_string());
continue;
}
@@ -443,15 +470,15 @@ fn merge_original(
event_set: &Value,
event_set_once: &Value,
) -> Value {
+ // event_uuid is deliberately absent: the proto documents it as
+ // advisory data the merge never reads, so a retry that regenerated
+ // its event uuids must still match the recorded request.
serde_json::json!({
"target_distinct_id": request.target_distinct_id,
"sources": request
.sources
.iter()
- .map(|s| serde_json::json!({
- "distinct_id": s.source_distinct_id,
- "event_uuid": s.event_uuid,
- }))
+ .map(|s| &s.source_distinct_id)
.collect::<Vec<_>>(),
"event_set": event_set,
"event_set_once": event_set_once,
@@ -528,6 +555,9 @@ fn merge_response(
))
})?
.unwrap_or_default();
+ // Loud on a misshapen frozen shape, like inline_results above: a
+ // silent empty here would answer OK with no results for a corrupt
+ // row.
let original_sources: Vec<String> = row
.request
.get("original")
@@ -536,11 +566,13 @@ fn merge_response(
.map(|sources| {
sources
.iter()
- .filter_map(|s| s.get("distinct_id").and_then(|d| d.as_str()))
+ .filter_map(|s| s.as_str())
.map(str::to_string)
.collect()
})
- .unwrap_or_default();
+ .ok_or_else(|| {
+ Status::internal(format!("op {} original sources are malformed", row.op_id))
+ })?;
let results = original_sources
.iter()
diff --git a/rust/personhog-identity/src/service/validation.rs b/rust/personhog-identity/src/service/validation.rs
index 2c7f608472a3..3d7d2342fae6 100644
--- a/rust/personhog-identity/src/service/validation.rs
+++ b/rust/personhog-identity/src/service/validation.rs
@@ -7,8 +7,11 @@ use personhog_proto::personhog::identity::v1::GetOrCreatePersonEntry;
pub struct RequestLimits {
/// Maximum entries per batch RPC.
pub max_batch_size: usize,
- /// Maximum accepted distinct_id length in bytes. Must not exceed the
- /// posthog_persondistinctid.distinct_id column limit (varchar(400)).
+ /// Maximum accepted distinct_id length in characters — the unit
+ /// varchar(400) counts. Counting bytes here rejected legally captured
+ /// multibyte ids (capture caps at 200 characters, which can pass 400
+ /// bytes). Must not exceed the posthog_persondistinctid.distinct_id
+ /// column limit (varchar(400)).
pub max_distinct_id_length: usize,
/// Maximum extra distinct ids per entry.
pub max_extra_distinct_ids: usize,
@@ -73,12 +76,18 @@ fn validate_distinct_id(limits: &RequestLimits, distinct_id: &str) -> Result<(),
if distinct_id.is_empty() {
return Err(Status::invalid_argument("distinct_id must not be empty"));
}
- if distinct_id.len() > limits.max_distinct_id_length {
+ if distinct_id.chars().count() > limits.max_distinct_id_length {
return Err(Status::invalid_argument(format!(
- "distinct_id exceeds {} bytes",
+ "distinct_id exceeds {} characters",
limits.max_distinct_id_length
)));
}
+ // Postgres cannot store NUL in text, so this id could never be
+ // created — reject it instead of surfacing the insert failure as an
+ // internal error.
+ if distinct_id.contains('\u{0000}') {
+ return Err(Status::invalid_argument("distinct_id must not contain NUL"));
+ }
Ok(())
}
diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
index 73d056b1dfdb..4f7a103d0158 100644
--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
@@ -185,6 +185,26 @@ async fn an_op_id_reused_with_a_different_request_is_rejected() {
ctx.cleanup().await.expect("cleanup");
}
+#[tokio::test]
+async fn a_first_call_is_not_compared_against_its_own_normalized_insert() {
+ let ctx = TestContext::new().await;
+ let engine = ctx.engine();
+ let driver = DummyDriver::new();
+ let op_id = Uuid::now_v7();
+
+ // Postgres renders 1e17 back as an integer, so the reloaded row never
+ // equals this request value-for-value. The call that won the insert
+ // owns the row by construction and must not verify against its own
+ // jsonb-normalized copy.
+ let row = engine
+ .execute(&driver, op_id, ctx.team_id, &json!({"count": 1e17}))
+ .await
+ .expect("the inserting call is never a request mismatch");
+ assert_eq!(row.step, STEP_COMPLETED);
+
+ ctx.cleanup().await.expect("cleanup");
+}
+
#[tokio::test]
async fn resume_picks_up_an_op_from_its_saved_step() {
let ctx = TestContext::new().await;
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index 5b7f18d98b73..fde2a9631605 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -1799,6 +1799,47 @@ async fn an_op_id_reused_with_a_different_request_is_rejected() {
.await
.expect_err("a different request must not attach");
assert_eq!(status.code(), Code::FailedPrecondition);
+ assert_eq!(
+ personhog_common::grpc::semantic_refusal_reason(&status),
+ Some("op_id_reused"),
+ "callers branch on the refusal reason, not the message"
+ );
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
+
+#[tokio::test]
+async fn a_create_race_loser_answers_retryable_unavailable() {
+ let h = MergeHarness::new().await;
+ let executor = MergeOpExecutor::new(
+ Arc::new(h.ctx.engine()),
+ MergeDriver::new(h.leader.clone(), h.ctx.tables.clone()),
+ );
+ let op_id = Uuid::now_v7();
+
+ // Drive a first frozen request to terminal: its target resolves to
+ // nothing, so the claim aborts the op in a single step.
+ let mut frozen_a =
+ serde_json::to_value(merge_request("race-target", &["race-source"])).unwrap();
+ frozen_a["original"] = json!({"call": "a"});
+ frozen_a["inline_results"] = json!({});
+ executor
+ .execute(op_id, h.ctx.team_id, &frozen_a)
+ .await
+ .expect("first request drives to terminal");
+
+ // The entrance reaches this create path only after its attach-first
+ // check found no op row, so a mismatch here is the insert-race
+ // window: it must answer retryable UNAVAILABLE (the retry attaches
+ // fine), not the terminal FAILED_PRECONDITION neither client stack
+ // retries.
+ let mut frozen_b = frozen_a.clone();
+ frozen_b["original"] = json!({"call": "b"});
+ let status = executor
+ .execute(op_id, h.ctx.team_id, &frozen_b)
+ .await
+ .expect_err("a mismatched frozen request must not attach");
+ assert_eq!(status.code(), Code::Unavailable);
h.ctx.cleanup().await.expect("cleanup");
}
@@ -1871,6 +1912,21 @@ async fn invalid_merge_requests_are_rejected_before_any_work() {
},
Code::InvalidArgument,
),
+ (
+ "oversized target",
+ rpc_request(team_id, &"x".repeat(401), &["s"], op),
+ Code::InvalidArgument,
+ ),
+ (
+ "NUL target",
+ rpc_request(team_id, "nul\u{0000}target", &["s"], op),
+ Code::InvalidArgument,
+ ),
+ (
+ "NUL source",
+ rpc_request(team_id, "t", &["nul\u{0000}source"], op),
+ Code::InvalidArgument,
+ ),
];
for (label, request, expected) in cases {
let status = service