Skip to content

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

feat(personhog): time identity leader calls and shadow-store verbs (#98825)

Nick Best846878ab9eb1
diff --git a/nodejs/src/common/persons/metrics.ts b/nodejs/src/common/persons/metrics.ts
index 1b5c75c6b645..20106acfafa9 100644
--- a/nodejs/src/common/persons/metrics.ts
+++ b/nodejs/src/common/persons/metrics.ts
@@ -196,6 +196,13 @@ export const personhogStoreShadowCompareFailedCounter = new Counter({
labelNames: ['verb'],
})
+export const personhogStoreShadowDurationSeconds = new Histogram({
+ name: 'personhog_store_shadow_duration_seconds',
+ help: 'Wall time the shadowed personhog side of a store verb adds to the event pipeline, by verb',
+ labelNames: ['verb'],
+ buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
+})
+
export const personProfileUpdateOutcomeCounter = new Counter({
name: 'person_profile_update_outcome_total',
help: 'Outcome of person profile update operations at event level',
diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
index 9f8ec42165be..6f1ecc36f1f8 100644
--- a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts
@@ -15,6 +15,8 @@ import { PersonhogPersonsStore } from './personhog-persons-store'
import { MergePersonsResult, PersonsBackend, PersonsStore } from './persons-store'
import { RoutingPersonsStore, assertPersonsStoreModeConfig, parsePersonsStoreMode } from './routing-persons-store'
+const mockShadowTimerStop = jest.fn()
+
jest.mock('~/common/persons/metrics', () => ({
personhogStoreShadowErrorsCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personhogStoreShadowSkipsCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
@@ -22,6 +24,9 @@ jest.mock('~/common/persons/metrics', () => ({
personhogStoreShadowComparedCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personhogStoreShadowCompareFailedCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
personhogStoreShadowFoldRedriveCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },
+ personhogStoreShadowDurationSeconds: {
+ labels: jest.fn().mockReturnValue({ startTimer: jest.fn(() => mockShadowTimerStop) }),
+ },
}))
const emptyMergeResult = (): MergePersonsResult => ({ survivor: null, results: [] })
@@ -533,6 +538,7 @@ describe('RoutingPersonsStore', () => {
verb: 'fetchForUpdate',
error: 'Error',
})
+ expect(mockShadowTimerStop).toHaveBeenCalled()
})
it('a shadow verb that outruns its ceiling is abandoned, not waited out', async () => {
diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.ts
index befaa6962393..587dbf2c18d1 100644
--- a/nodejs/src/ingestion/common/persons/routing-persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.ts
@@ -5,6 +5,7 @@ import {
personhogStoreShadowCompareFailedCounter,
personhogStoreShadowComparedCounter,
personhogStoreShadowDivergenceCounter,
+ personhogStoreShadowDurationSeconds,
personhogStoreShadowErrorsCounter,
personhogStoreShadowFoldRedriveCounter,
personhogStoreShadowSkipsCounter,
@@ -150,6 +151,7 @@ export class RoutingPersonsStore implements PersonsStore {
* abandoned and counted as lost fidelity; the bound is per verb.
*/
private async shadowed(verb: string, run: () => Promise<unknown>): Promise<void> {
+ const stopTimer = personhogStoreShadowDurationSeconds.labels({ verb }).startTimer()
let timer: ReturnType<typeof setTimeout> | undefined
const running = run()
// The abandoned leg keeps running against the personhog side; its
@@ -170,6 +172,7 @@ export class RoutingPersonsStore implements PersonsStore {
logger.warn('personhog shadow verb failed', { verb, error: String(error) })
} finally {
clearTimeout(timer)
+ stopTimer()
}
}
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 3b4c3bf829c8..819749c45ccf 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8727,6 +8727,7 @@ dependencies = [
"envconfig",
"futures",
"lifecycle",
+ "metrics",
"metrics-exporter-prometheus",
"personhog-common",
"personhog-proto",
diff --git a/rust/personhog-common/src/client.rs b/rust/personhog-common/src/client.rs
index 11c3c816406f..10b3ce2a0f0d 100644
--- a/rust/personhog-common/src/client.rs
+++ b/rust/personhog-common/src/client.rs
@@ -5,12 +5,17 @@
//! `x-team-id`/`x-person-id` on property writes and strong reads. This
//! client owns that contract so callers cannot get it wrong.
+use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, Instant};
+use metrics::{counter, histogram};
+use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, Endpoint};
-use tonic::{Request, Status};
+use tonic::{Request, Response, Status};
+
+use crate::grpc::{code_as_str, CLIENT_NAME_HEADER};
use personhog_proto::personhog::service::v1::person_hog_service_client::PersonHogServiceClient;
use personhog_proto::personhog::types::v1::{
@@ -26,6 +31,9 @@ pub const READ_CONSISTENCY_HEADER: &str = "x-read-consistency";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
+pub const ROUTER_CLIENT_CALLS_TOTAL: &str = "personhog_router_client_calls_total";
+pub const ROUTER_CLIENT_CALL_DURATION_MS: &str = "personhog_router_client_call_duration_ms";
+
/// Channels opened per router URL when the caller does not choose. One is
/// correct only for low-rate callers; see `with_channels`.
pub const DEFAULT_ROUTER_CHANNELS: usize = 1;
@@ -44,6 +52,7 @@ pub struct RouterClient {
/// than every clone restarting at the first channel.
next: Arc<AtomicUsize>,
request_timeout: Duration,
+ client_name: Option<&'static str>,
}
impl RouterClient {
@@ -79,9 +88,46 @@ impl RouterClient {
clients,
next: Arc::new(AtomicUsize::new(0)),
request_timeout,
+ client_name: None,
})
}
+ /// Stamp every request with `x-client-name`, so the router and leader
+ /// attribute their server-side metrics to this caller instead of
+ /// `unknown`.
+ pub fn with_client_name(mut self, name: &'static str) -> Self {
+ self.client_name = Some(name);
+ self
+ }
+
+ fn request<T>(&self, message: T) -> Request<T> {
+ let mut request = Request::new(message);
+ request.set_timeout(self.request_timeout);
+ if let Some(name) = self.client_name {
+ request
+ .metadata_mut()
+ .insert(CLIENT_NAME_HEADER, MetadataValue::from_static(name));
+ }
+ request
+ }
+
+ async fn timed<T, F>(method: &'static str, call: F) -> Result<T, Status>
+ where
+ F: Future<Output = Result<Response<T>, Status>>,
+ {
+ let start = Instant::now();
+ let result = call.await;
+ let outcome: &'static str = match &result {
+ Ok(_) => "ok",
+ Err(status) => code_as_str(status.code()),
+ };
+ let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
+ counter!(ROUTER_CLIENT_CALLS_TOTAL, "method" => method, "outcome" => outcome).increment(1);
+ histogram!(ROUTER_CLIENT_CALL_DURATION_MS, "method" => method, "outcome" => outcome)
+ .record(duration_ms);
+ result.map(Response::into_inner)
+ }
+
/// The next channel in round-robin order. Selection is load-oblivious:
/// a stalled connection still takes its share, which is acceptable
/// because every channel targets the same interchangeable pod set.
@@ -97,10 +143,11 @@ impl RouterClient {
request: UpdatePersonPropertiesRequest,
) -> Result<UpdatePersonPropertiesResponse, Status> {
let request = self.build_update_request(request);
- self.client()
- .update_person_properties(request)
- .await
- .map(|response| response.into_inner())
+ Self::timed(
+ "UpdatePersonProperties",
+ self.client().update_person_properties(request),
+ )
+ .await
}
/// Person read. Strong reads route to the owning leader and therefore
@@ -113,10 +160,9 @@ impl RouterClient {
consistency: ConsistencyLevel,
) -> Result<Option<Person>, Status> {
let request = self.build_get_person_request(team_id, person_id, consistency);
- self.client()
- .get_person(request)
+ Self::timed("GetPerson", self.client().get_person(request))
.await
- .map(|response| response.into_inner().person)
+ .map(|response| response.person)
}
/// Leader-routed lifecycle fence (saga runner only): freeze the person
@@ -126,13 +172,9 @@ impl RouterClient {
request: FencePersonRequest,
) -> Result<FencePersonResponse, Status> {
let (team_id, person_id) = (request.team_id, request.person_id);
- let mut request = Request::new(request);
- request.set_timeout(self.request_timeout);
+ let mut request = self.request(request);
stamp_person_routing_headers(&mut request, team_id, person_id);
- self.client()
- .fence_person(request)
- .await
- .map(|response| response.into_inner())
+ Self::timed("FencePerson", self.client().fence_person(request)).await
}
/// Leader-routed fence release (saga runner only): committed produces
@@ -142,13 +184,9 @@ impl RouterClient {
request: ReleaseFenceRequest,
) -> Result<ReleaseFenceResponse, Status> {
let (team_id, person_id) = (request.team_id, request.person_id);
- let mut request = Request::new(request);
- request.set_timeout(self.request_timeout);
+ let mut request = self.request(request);
stamp_person_routing_headers(&mut request, team_id, person_id);
- self.client()
- .release_fence(request)
- .await
- .map(|response| response.into_inner())
+ Self::timed("ReleaseFence", self.client().release_fence(request)).await
}
/// Leader-routed merge fold (saga runner only): fold sealed source
@@ -158,13 +196,13 @@ impl RouterClient {
request: FoldPersonDocumentRequest,
) -> Result<FoldPersonDocumentResponse, Status> {
let (team_id, person_id) = (request.team_id, request.person_id);
- let mut request = Request::new(request);
- request.set_timeout(self.request_timeout);
+ let mut request = self.request(request);
stamp_person_routing_headers(&mut request, team_id, person_id);
- self.client()
- .fold_person_document(request)
- .await
- .map(|response| response.into_inner())
+ Self::timed(
+ "FoldPersonDocument",
+ self.client().fold_person_document(request),
+ )
+ .await
}
fn build_update_request(
@@ -172,8 +210,7 @@ impl RouterClient {
request: UpdatePersonPropertiesRequest,
) -> Request<UpdatePersonPropertiesRequest> {
let (team_id, person_id) = (request.team_id, request.person_id);
- let mut request = Request::new(request);
- request.set_timeout(self.request_timeout);
+ let mut request = self.request(request);
stamp_person_routing_headers(&mut request, team_id, person_id);
request
}
@@ -184,7 +221,7 @@ impl RouterClient {
person_id: i64,
consistency: ConsistencyLevel,
) -> Request<GetPersonRequest> {
- let mut request = Request::new(GetPersonRequest {
+ let mut request = self.request(GetPersonRequest {
team_id,
person_id,
read_options: Some(ReadOptions {
@@ -192,7 +229,6 @@ impl RouterClient {
..Default::default()
}),
});
- request.set_timeout(self.request_timeout);
if consistency == ConsistencyLevel::Strong {
stamp_person_routing_headers(&mut request, team_id, person_id);
request.metadata_mut().insert(
@@ -278,6 +314,24 @@ mod tests {
assert!(metadata.get(READ_CONSISTENCY_HEADER).is_none());
}
+ /// The eventual-read branch carries no routing headers, so it is the
+ /// branch most likely to lose the client name in a request-building
+ /// refactor; an unnamed client must stay anonymous so the server label
+ /// falls back to `unknown` rather than an empty string.
+ #[tokio::test]
+ async fn client_name_is_stamped_only_when_configured() {
+ let anonymous = client().build_update_request(UpdatePersonPropertiesRequest::default());
+ assert!(anonymous.metadata().get(CLIENT_NAME_HEADER).is_none());
+
+ let named = client()
+ .with_client_name("personhog-identity")
+ .build_get_person_request(7, 42, ConsistencyLevel::Eventual);
+ assert_eq!(
+ named.metadata().get(CLIENT_NAME_HEADER).unwrap(),
+ "personhog-identity"
+ );
+ }
+
#[rstest]
#[case::strong(ConsistencyLevel::Strong, true)]
#[case::eventual(ConsistencyLevel::Eventual, false)]
diff --git a/rust/personhog-common/src/grpc.rs b/rust/personhog-common/src/grpc.rs
index f8cef71a9b62..eee4bcb1d4f7 100644
--- a/rust/personhog-common/src/grpc.rs
+++ b/rust/personhog-common/src/grpc.rs
@@ -21,7 +21,7 @@ use tower::{Layer, Service};
// ============================================================
/// Header name for client identification in gRPC metadata.
-const CLIENT_NAME_HEADER: &str = "x-client-name";
+pub const CLIENT_NAME_HEADER: &str = "x-client-name";
/// Metadata key marking a FAILED_PRECONDITION as a definitive semantic
/// refusal rather than a routing-race rejection. The router bounces and
diff --git a/rust/personhog-identity/Cargo.toml b/rust/personhog-identity/Cargo.toml
index 032e895c64e6..c72193c4835e 100644
--- a/rust/personhog-identity/Cargo.toml
+++ b/rust/personhog-identity/Cargo.toml
@@ -10,6 +10,7 @@ personhog-proto = { path = "../personhog-proto" }
common-database = { path = "../common/database" }
common-alloc = { path = "../common/alloc" }
common-metrics = { path = "../common/metrics" }
+metrics = { workspace = true }
lifecycle = { path = "../common/lifecycle" }
async-trait = { workspace = true }
diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rs
index 46e2db406c00..fc8fc9476f7f 100644
--- a/rust/personhog-identity/src/lifecycle/delete.rs
+++ b/rust/personhog-identity/src/lifecycle/delete.rs
@@ -40,6 +40,7 @@ use crate::lifecycle::engine::{
advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
STEP_COMPLETED,
};
+use crate::storage::postgres::begin_timed;
/// Bound on concurrent leader calls per step, matching the merge driver.
const LEADER_CALL_CONCURRENCY: usize = 8;
@@ -199,7 +200,7 @@ fn parse_request(op: &OpRow) -> Result<DeleteRequest, SagaError> {
async fn mark(pool: &PgPool, person_table: &str, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
let team_id = op.team_id as i32;
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
// Rows from a previous attempt of this op (crash between the insert and
// the advance): whatever they claimed stays claimed.
@@ -431,7 +432,7 @@ async fn seal(pool: &PgPool, leader: &dyn LifecycleLeader, op: &OpRow) -> Result
}
}
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
sqlx::query!(
r#"
UPDATE lifecycle_op_person lop
@@ -487,7 +488,7 @@ async fn seal(pool: &PgPool, leader: &dyn LifecycleLeader, op: &OpRow) -> Result
/// this version.
async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
let team_id = op.team_id as i32;
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
let mut victims: Vec<i64> = sqlx::query_scalar!(
r#"
@@ -688,7 +689,7 @@ async fn complete(
result.map_err(SagaError::leader)?;
}
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
sqlx::query!(
"UPDATE lifecycle_op_person SET status = $2 WHERE op_id = $1 AND status = 'sealed'",
diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rs
index 810aafb9d8cf..a93b52d8c02e 100644
--- a/rust/personhog-identity/src/lifecycle/merge.rs
+++ b/rust/personhog-identity/src/lifecycle/merge.rs
@@ -54,6 +54,7 @@ use crate::lifecycle::engine::{
advance_step_in_tx, complete_op_in_tx, Engine, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
STEP_COMPLETED,
};
+use crate::storage::postgres::begin_timed;
// Derived from the shared enum so the op-type string cannot drift from
// the leader's fence records or the lifecycle_op CHECK constraint.
@@ -382,10 +383,7 @@ impl MergeOpExecutor {
// 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
- .pool()
- .begin()
+ let mut tx = begin_timed(self.engine.pool())
.await
.map_err(|e| Status::internal(format!("discard begin failed: {e}")))?;
let deleted = sqlx::query!(
@@ -589,7 +587,7 @@ impl MergeDriver {
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 = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
// Authoritative resolution: the handler's classification aged while
// the op row traveled here.
@@ -1063,7 +1061,7 @@ impl MergeDriver {
.map(|s| (s.person_id, s.person_uuid))
.collect();
self.release_fences(op, &remaining).await?;
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
settle_drops(&mut tx, op, &vanished, &identified).await?;
sqlx::query!(
r#"
@@ -1103,7 +1101,7 @@ impl MergeDriver {
return Ok(());
}
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
settle_drops(&mut tx, op, &vanished, &identified).await?;
let sealed_ids: Vec<i64> = sealed.iter().map(|(id, _)| *id).collect();
let sealed_jsons: Vec<Value> = sealed
@@ -1167,7 +1165,7 @@ impl MergeDriver {
.await?;
let pairs: Vec<(i64, Uuid)> = live.iter().map(|s| (s.person_id, s.person_uuid)).collect();
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
sqlx::query!(
r#"
UPDATE lifecycle_op_person SET status = $2
@@ -1457,7 +1455,7 @@ impl MergeDriver {
"version": folded.version,
});
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
sqlx::query!(
"UPDATE lifecycle_op_person SET sealed = $2 WHERE op_id = $1 AND role = $3",
op.op_id,
@@ -1521,7 +1519,7 @@ fn encode_json_map(value: &Value) -> Result<Vec<u8>, SagaError> {
/// source marks stay: they are the fences' durable record until release.
async fn flip(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
let team_id = op.team_id as i32;
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
let target = {
let row = sqlx::query!(
@@ -1859,7 +1857,7 @@ impl MergeDriver {
result?;
}
- let mut tx = pool.begin().await?;
+ let mut tx = begin_timed(pool).await?;
sqlx::query!(
r#"
UPDATE lifecycle_op_person SET status = $2
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index 0901f3b21293..db101545e57a 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -217,7 +217,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let property_writer = Arc::new(
RouterClient::new(&config.router_url, config.leader_request_timeout())
- .expect("Invalid router URL"),
+ .expect("Invalid router URL")
+ .with_client_name("personhog-identity"),
);
// Both sagas' leader surface, reached through the router like the
// property writes.
diff --git a/rust/personhog-identity/src/service/get_or_create.rs b/rust/personhog-identity/src/service/get_or_create.rs
index 799b26e0b1b0..c12520d39071 100644
--- a/rust/personhog-identity/src/service/get_or_create.rs
+++ b/rust/personhog-identity/src/service/get_or_create.rs
@@ -7,6 +7,7 @@
//! changelog — the single ack covers both planes.
use std::collections::{HashMap, HashSet};
+use std::time::Instant;
use chrono::{DateTime, Utc};
use futures::stream::{self, StreamExt};
@@ -24,6 +25,7 @@ use crate::storage::{Person, PersonStub, StubOutcome};
const MAX_CONCURRENT_PROPERTY_WRITES: usize = 8;
const GET_OR_CREATE_TOTAL: &str = "personhog_identity_get_or_create_total";
+const GET_OR_CREATE_PHASE_DURATION: &str = "personhog_identity_get_or_create_phase_duration_ms";
fn count_outcome(outcome: &str) {
common_metrics::inc(
@@ -33,6 +35,11 @@ fn count_outcome(outcome: &str) {
);
}
+fn record_phase(phase: &'static str, start: Instant) {
+ metrics::histogram!(GET_OR_CREATE_PHASE_DURATION, "phase" => phase)
+ .record(start.elapsed().as_secs_f64() * 1000.0);
+}
+
/// Empty bytes and an empty JSON object both mean "no properties to apply".
fn has_properties(raw: &[u8]) -> bool {
!raw.is_empty() && raw.trim_ascii() != b"{}"
@@ -72,11 +79,10 @@ impl PersonHogIdentityService {
.filter(|entry| validate_entry(&self.limits, entry).is_ok())
.map(|entry| (entry.team_id, entry.distinct_id.clone()))
.collect();
- let resolved = self
- .storage
- .resolve_distinct_ids(&keys)
- .await
- .map_err(|e| log_and_convert_error(e, "resolve_distinct_ids"))?;
+ let phase = Instant::now();
+ let resolved = self.storage.resolve_distinct_ids(&keys).await;
+ record_phase("resolve", phase);
+ let resolved = resolved.map_err(|e| log_and_convert_error(e, "resolve_distinct_ids"))?;
// Plan each entry and collect one stub per missing key.
let mut stubs: Vec<PersonStub> = Vec::new();
@@ -101,14 +107,14 @@ impl PersonHogIdentityService {
})
.collect();
+ let phase = Instant::now();
let outcomes = if stubs.is_empty() {
- Vec::new()
+ Ok(Vec::new())
} else {
- self.storage
- .create_person_stubs(&stubs)
- .await
- .map_err(|e| log_and_convert_error(e, "create_person_stubs"))?
+ self.storage.create_person_stubs(&stubs).await
};
+ record_phase("create_stubs", phase);
+ let outcomes = outcomes.map_err(|e| log_and_convert_error(e, "create_person_stubs"))?;
// Lost races re-resolve in one batch: the winner's mapping committed,
// so a fresh resolve finds it.
@@ -117,14 +123,15 @@ impl PersonHogIdentityService {
.filter(|(_, &index)| matches!(outcomes[index], StubOutcome::LostRace))
.map(|(key, _)| key.clone())
.collect();
+ let phase = Instant::now();
let lost_resolved = if lost_keys.is_empty() {
- HashMap::new()
+ Ok(HashMap::new())
} else {
- self.storage
- .resolve_distinct_ids(&lost_keys)
- .await
- .map_err(|e| log_and_convert_error(e, "resolve_after_lost_race"))?
+ self.storage.resolve_distinct_ids(&lost_keys).await
};
+ record_phase("resolve_lost_race", phase);
+ let lost_resolved =
+ lost_resolved.map_err(|e| log_and_convert_error(e, "resolve_after_lost_race"))?;
// Assemble results; created owners go through the leader fan-out.
let lost_race_result = |i: usize| {
@@ -175,6 +182,7 @@ impl PersonHogIdentityService {
results.push(result);
}
+ let phase = Instant::now();
let applied: Vec<(usize, Result<ProtoPerson, Status>)> =
stream::iter(property_writes.into_iter().map(|(i, person)| {
let entry = &entries[i];
@@ -183,11 +191,14 @@ impl PersonHogIdentityService {
.buffered(MAX_CONCURRENT_PROPERTY_WRITES)
.collect()
.await;
+ record_phase("apply_properties", phase);
for (i, result) in applied {
let result = result.map(|person| (person, true));
- if result.is_ok() {
- count_outcome("created");
- }
+ count_outcome(if result.is_ok() {
+ "created"
+ } else {
+ "properties_failed"
+ });
results[i] = Some(result);
}
diff --git a/rust/personhog-identity/src/storage/postgres/mod.rs b/rust/personhog-identity/src/storage/postgres/mod.rs
index b8dabe1b58d1..37ddd126050b 100644
--- a/rust/personhog-identity/src/storage/postgres/mod.rs
+++ b/rust/personhog-identity/src/storage/postgres/mod.rs
@@ -49,7 +49,7 @@ pub(super) async fn acquire_timed(pool: &PgPool) -> sqlx::Result<PoolConnection<
}
/// Begin a primary transaction, recording the acquire wait it contains.
-pub(super) async fn begin_timed(pool: &PgPool) -> sqlx::Result<Transaction<'_, Postgres>> {
+pub(crate) async fn begin_timed(pool: &PgPool) -> sqlx::Result<Transaction<'_, Postgres>> {
let start = Instant::now();
let tx = pool.begin().await;
record_acquire(start);