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): stop lifecycle claims from queueing on the op row (#82199)

José Sequeira5191575fafd1
diff --git a/rust/personhog-identity/.sqlx/query-a32e9eae1d71c4efbded813dc6809b39a1b89b4b1154a611fbb132a6de5cbc23.json b/rust/personhog-identity/.sqlx/query-63cc7113e122f98c5408aa855f10a9cad31fb8a761dbdb8ff449aa84734fd7d2.json
similarity index 50%
rename from rust/personhog-identity/.sqlx/query-a32e9eae1d71c4efbded813dc6809b39a1b89b4b1154a611fbb132a6de5cbc23.json
rename to rust/personhog-identity/.sqlx/query-63cc7113e122f98c5408aa855f10a9cad31fb8a761dbdb8ff449aa84734fd7d2.json
index b212eacdd97e..3d80ed75b619 100644
--- a/rust/personhog-identity/.sqlx/query-a32e9eae1d71c4efbded813dc6809b39a1b89b4b1154a611fbb132a6de5cbc23.json
+++ b/rust/personhog-identity/.sqlx/query-63cc7113e122f98c5408aa855f10a9cad31fb8a761dbdb8ff449aa84734fd7d2.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE lifecycle_op\n SET lease_expires_at = now() + make_interval(secs => $2),\n attempt = attempt + 1,\n parked_at = NULL,\n parked_reason = NULL\n WHERE op_id = $1 AND completed_at IS NULL\n AND (lease_expires_at IS NULL OR lease_expires_at < now())\n AND (parked_at IS NULL OR $3)\n RETURNING attempt\n ",
+ "query": "\n UPDATE lifecycle_op\n SET lease_expires_at = now() + make_interval(secs => $2),\n attempt = attempt + 1,\n parked_at = NULL,\n parked_reason = NULL\n WHERE op_id IN (\n SELECT op_id FROM lifecycle_op\n WHERE op_id = $1 AND completed_at IS NULL\n AND (lease_expires_at IS NULL OR lease_expires_at < now())\n AND (parked_at IS NULL OR $3)\n FOR UPDATE SKIP LOCKED\n )\n RETURNING attempt\n ",
"describe": {
"columns": [
{
@@ -20,5 +20,5 @@
false
]
},
- "hash": "a32e9eae1d71c4efbded813dc6809b39a1b89b4b1154a611fbb132a6de5cbc23"
+ "hash": "63cc7113e122f98c5408aa855f10a9cad31fb8a761dbdb8ff449aa84734fd7d2"
}
diff --git a/rust/personhog-identity/.sqlx/query-781b6c270dbdb936f7dc64fd7a007b130117f50235c066ee72705f5f3f5a8694.json b/rust/personhog-identity/.sqlx/query-eb0d1e16eed55534b6f443fc08952770230df349729b248934f125bbc38e7bcd.json
similarity index 75%
rename from rust/personhog-identity/.sqlx/query-781b6c270dbdb936f7dc64fd7a007b130117f50235c066ee72705f5f3f5a8694.json
rename to rust/personhog-identity/.sqlx/query-eb0d1e16eed55534b6f443fc08952770230df349729b248934f125bbc38e7bcd.json
index e3b0740aea15..53707d66e9ab 100644
--- a/rust/personhog-identity/.sqlx/query-781b6c270dbdb936f7dc64fd7a007b130117f50235c066ee72705f5f3f5a8694.json
+++ b/rust/personhog-identity/.sqlx/query-eb0d1e16eed55534b6f443fc08952770230df349729b248934f125bbc38e7bcd.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT op_id, op_type, team_id::bigint as \"team_id!\", step, attempt,\n request as \"request: Value\", outcome as \"outcome: Value\",\n created_at, completed_at\n FROM lifecycle_op\n WHERE op_id = $1\n ",
+ "query": "\n SELECT op_id, op_type, team_id::bigint as \"team_id!\", step, attempt,\n request as \"request: Value\", outcome as \"outcome: Value\",\n created_at, completed_at,\n (lease_expires_at IS NOT NULL AND lease_expires_at >= now())\n as \"lease_live!\"\n FROM lifecycle_op\n WHERE op_id = $1\n ",
"describe": {
"columns": [
{
@@ -47,6 +47,11 @@
"ordinal": 8,
"name": "completed_at",
"type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "lease_live!",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -63,8 +68,9 @@
false,
true,
false,
- true
+ true,
+ null
]
},
- "hash": "781b6c270dbdb936f7dc64fd7a007b130117f50235c066ee72705f5f3f5a8694"
+ "hash": "eb0d1e16eed55534b6f443fc08952770230df349729b248934f125bbc38e7bcd"
}
diff --git a/rust/personhog-identity/Cargo.toml b/rust/personhog-identity/Cargo.toml
index 82fda5754cbb..032e895c64e6 100644
--- a/rust/personhog-identity/Cargo.toml
+++ b/rust/personhog-identity/Cargo.toml
@@ -18,6 +18,7 @@ chrono = { workspace = true }
envconfig = { workspace = true }
futures = { workspace = true }
metrics-exporter-prometheus = { workspace = true }
+rand = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
@@ -29,7 +30,6 @@ tracing-subscriber = { workspace = true }
uuid = { workspace = true }
[dev-dependencies]
-rand = { workspace = true }
tokio = { workspace = true, features = ["test-util"] }
[lints]
diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rs
index 90d954fe2a5c..a562b5f25e2c 100644
--- a/rust/personhog-identity/src/lifecycle/engine.rs
+++ b/rust/personhog-identity/src/lifecycle/engine.rs
@@ -20,6 +20,7 @@ use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
+use rand::Rng;
use serde_json::Value;
use sqlx::postgres::PgPool;
use tonic::Status;
@@ -142,6 +143,9 @@ pub struct OpRow {
pub outcome: Option<Value>,
pub created_at: DateTime<Utc>,
pub completed_at: Option<DateTime<Utc>>,
+ /// Whether another driver's lease was live when this row was read — a
+ /// read-time fact for the claim precheck, not part of the checkpoint.
+ pub lease_live: bool,
}
/// Step handlers for one op type. The engine calls [`run_step`] with the
@@ -343,29 +347,42 @@ impl Engine {
continue;
}
}
- None => match self.try_claim(op_id, wait_for_lease).await? {
- Some(attempt) => {
- claim_attempt = Some(attempt);
- if attempt >= self.config.attempt_alert_threshold {
- tracing::warn!(
- op_id = %op_id,
- op_type = %row.op_type,
- step = %row.step,
- attempt,
- "lifecycle op has been claimed unusually often; it may be stuck"
- );
- }
- }
- None => {
+ None => {
+ // A live lease means the claim below cannot succeed, so
+ // don't issue it: claim attempts are writes, and a herd
+ // of pollers writing to a row its owner keeps renewing
+ // and advancing serializes on the row's tuple lock.
+ if row.lease_live {
if !wait_for_lease {
return Err(SagaError::Busy);
}
- // Someone else holds the lease; wait for them to
- // finish or for the lease to lapse.
- tokio::time::sleep(self.config.poll_interval).await;
+ self.poll_pause().await;
continue;
}
- },
+ match self.try_claim(op_id, wait_for_lease).await? {
+ Some(attempt) => {
+ claim_attempt = Some(attempt);
+ if attempt >= self.config.attempt_alert_threshold {
+ tracing::warn!(
+ op_id = %op_id,
+ op_type = %row.op_type,
+ step = %row.step,
+ attempt,
+ "lifecycle op has been claimed unusually often; it may be stuck"
+ );
+ }
+ }
+ None => {
+ if !wait_for_lease {
+ return Err(SagaError::Busy);
+ }
+ // Someone else holds the lease; wait for them to
+ // finish or for the lease to lapse.
+ self.poll_pause().await;
+ continue;
+ }
+ }
+ }
}
if let Err(err) = driver.run_step(&self.pool, &row).await {
@@ -448,7 +465,9 @@ impl Engine {
r#"
SELECT op_id, op_type, team_id::bigint as "team_id!", step, attempt,
request as "request: Value", outcome as "outcome: Value",
- created_at, completed_at
+ created_at, completed_at,
+ (lease_expires_at IS NOT NULL AND lease_expires_at >= now())
+ as "lease_live!"
FROM lifecycle_op
WHERE op_id = $1
"#,
@@ -458,11 +477,24 @@ impl Engine {
.await
}
+ /// Sleep one poll interval, jittered to 0.5–1.5× so waiters released by
+ /// the same lease event spread out instead of re-claiming in lockstep.
+ async fn poll_pause(&self) {
+ let jitter = rand::thread_rng().gen_range(0.5..1.5);
+ tokio::time::sleep(self.config.poll_interval.mul_f64(jitter)).await;
+ }
+
/// Claim the op if its lease is free or lapsed. Returns the new attempt
/// count on success, None when another instance holds a live lease.
/// Only an explicit retry (`unpark`, the execute path) may claim a
/// parked op; the sweeper cannot, even when a park lands after its
/// scan.
+ ///
+ /// `SKIP LOCKED` keeps a claim from queueing behind whoever is writing
+ /// the row right now (a renew, a step advance, a rival claim): the row
+ /// being locked means the lease answer is about to change, so polling
+ /// again beats joining a tuple-lock queue. A skipped row reads as None,
+ /// the same as losing the claim outright.
async fn try_claim(&self, op_id: Uuid, unpark: bool) -> Result<Option<i32>, sqlx::Error> {
sqlx::query_scalar!(
r#"
@@ -471,9 +503,13 @@ impl Engine {
attempt = attempt + 1,
parked_at = NULL,
parked_reason = NULL
- WHERE op_id = $1 AND completed_at IS NULL
- AND (lease_expires_at IS NULL OR lease_expires_at < now())
- AND (parked_at IS NULL OR $3)
+ WHERE op_id IN (
+ SELECT op_id FROM lifecycle_op
+ WHERE op_id = $1 AND completed_at IS NULL
+ AND (lease_expires_at IS NULL OR lease_expires_at < now())
+ AND (parked_at IS NULL OR $3)
+ FOR UPDATE SKIP LOCKED
+ )
RETURNING attempt
"#,
op_id,
diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rs
index 65bc84375cc4..acdeca0cd779 100644
--- a/rust/personhog-identity/src/lifecycle/merge.rs
+++ b/rust/personhog-identity/src/lifecycle/merge.rs
@@ -282,7 +282,9 @@ impl MergeOpExecutor {
r#"
SELECT op_id, op_type, team_id::bigint as "team_id!", step, attempt,
request as "request: Value", outcome as "outcome: Value",
- created_at, completed_at
+ created_at, completed_at,
+ (lease_expires_at IS NOT NULL AND lease_expires_at >= now())
+ as "lease_live!"
FROM lifecycle_op
WHERE op_id = $1
"#,
diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
index e0fa909924e1..73d056b1dfdb 100644
--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
@@ -771,3 +771,41 @@ async fn a_step_that_loses_a_database_conflict_is_retried_not_surfaced() {
ctx.cleanup().await.expect("cleanup");
}
+
+#[tokio::test]
+async fn a_claim_skips_a_row_a_concurrent_writer_holds_instead_of_queueing() {
+ let ctx = TestContext::new().await;
+ let engine = ctx.engine();
+ let driver = DummyDriver::new();
+ let op_id = Uuid::now_v7();
+
+ // Created but not driven: the lease is free, so only the row lock below
+ // stands between resume and a successful claim.
+ engine
+ .create_or_attach(&driver, op_id, ctx.team_id, &json!({"work": 7}))
+ .await
+ .expect("create");
+
+ // Hold the row lock the way any concurrent writer would (a renew, a
+ // step advance, a rival claim mid-flight).
+ let mut tx = ctx.pool.begin().await.expect("begin");
+ sqlx::query("SELECT 1 FROM lifecycle_op WHERE op_id = $1 FOR UPDATE")
+ .bind(op_id)
+ .execute(&mut *tx)
+ .await
+ .expect("lock the op row");
+
+ // The claim must answer Busy promptly rather than queueing on the tuple
+ // until the lock holder commits.
+ let result = tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ engine.resume(&driver, op_id),
+ )
+ .await
+ .expect("resume must not wait out a concurrent writer's row lock");
+ assert!(matches!(result, Err(SagaError::Busy)));
+ assert_eq!(driver.steps_run.load(Ordering::SeqCst), 0);
+
+ tx.rollback().await.expect("rollback");
+ ctx.cleanup().await.expect("cleanup");
+}