: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(cohorts): instrument processor with hotpath (#119082)
Matheus Batista14689dbea53f
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 6a270db41d83..536a2822885a 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2807,6 +2807,7 @@ dependencies = ["dashmap 6.1.0","envconfig","futures",+ "hotpath","lifecycle","metrics","metrics-exporter-prometheus",@@ -5727,6 +5728,50 @@ dependencies = ["windows-link",]+[[package]]+name = "hotpath"+version = "0.28.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2ee4f8d17ebe2400fa845f079acf9ede235be6472512876779af45f7890f934"+dependencies = [+ "arc-swap",+ "cfg-if",+ "crossbeam-channel",+ "futures-core",+ "hdrhistogram",+ "hotpath-drain",+ "hotpath-macros",+ "libc",+ "pin-project-lite",+ "prost 0.14.3",+ "quanta 0.12.6",+ "regex-lite",+ "serde",+ "serde_json",+ "time",+ "tiny_http",+ "tokio",+ "tracing",+ "tracing-subscriber",+]++[[package]]+name = "hotpath-drain"+version = "0.28.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd9e65572a429f44a48c360559a3f59028579b53e1df07c5f31dc147d2b94a50"++[[package]]+name = "hotpath-macros"+version = "0.28.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b90aafbaf5f6af01ee9db2888644b15995f5306e5c280aec8261feb3e5e214a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "hstr"version = "3.0.4"diff --git a/rust/cohort-stream-processor/Cargo.toml b/rust/cohort-stream-processor/Cargo.tomlindex e2829220a5fc..90cbef16ff32 100644--- a/rust/cohort-stream-processor/Cargo.toml+++ b/rust/cohort-stream-processor/Cargo.toml@@ -31,6 +31,9 @@ common-liveness = { path = "../common/liveness" }# hold their per-partition maps behind sharded locks (no global mutex on the hot path).dashmap = { workspace = true }envconfig = { workspace = true }+# Opt-in profiling. Every hotpath macro and wrapper is a no-op unless the `hotpath` feature is on.+# Profile an optimized build: `cargo run --release -p cohort-stream-processor --features hotpath`.+hotpath = { version = "0.28", features = ["tokio", "sqlx"] }# `join_all` for routing each poll's per-partition sub-batches concurrently, so a full channel on# one partition can't head-of-line-block the sends to the others. Same version dedup uses.futures = { workspace = true }@@ -66,6 +69,12 @@ uuid = { workspace = true }# `statvfs` for the store-filesystem utilization sample (`observability::disk`).nix = { version = "0.31", features = ["fs"] }+[features]+default = []+hotpath = ["hotpath/hotpath"]+hotpath-alloc = ["hotpath", "hotpath/hotpath-alloc"]+hotpath-prometheus = ["hotpath", "hotpath/hotpath-prometheus"]+[dev-dependencies]# Integration tests in `tests/` build `TeamFilters` via `freeze(UTC)`, so they name `chrono_tz::UTC`# directly (a normal dependency is not in scope for the separate integration-test crates).diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rsindex 548e91cef338..adf4ed36f449 100644--- a/rust/cohort-stream-processor/src/consumers/events.rs+++ b/rust/cohort-stream-processor/src/consumers/events.rs@@ -228,6 +228,7 @@ impl EventDispatcher {/// dispatch ceiling only for what lands. Events for a partition in `held` (already paused behind an/// older holdover) skip the send and are returned to queue behind it. Returns the un-dispatched/// events per partition for the caller to hold and pause.+ #[hotpath::measure(impl_type = "EventDispatcher")]pub fn dispatch_events_nonblocking(&self,batch: Vec<ConsumedEvent>,@@ -1239,6 +1240,7 @@ impl CohortStreamEventsConsumer {gauge!(PENDING_HELD_EVENTS).set(backpressure.held_message_count() as f64);}+ #[hotpath::measure(impl_type = "CohortStreamEventsConsumer")]async fn consume_batch(&self) -> ConsumeOutcome {let mut outcome = ConsumeOutcome {events: Vec::with_capacity(self.recv_batch_size),diff --git a/rust/cohort-stream-processor/src/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rsindex febdbcd3b897..9fd067d9e805 100644--- a/rust/cohort-stream-processor/src/filters/manager.rs+++ b/rust/cohort-stream-processor/src/filters/manager.rs@@ -207,6 +207,7 @@ impl CatalogHandle {/// The staleness metrics are stamped here rather than in [`run_refresh_loop`] so the boot load/// in `main` counts too — otherwise a pod that booted fine and then lost its refresh loop would/// look identical to one that never loaded.+ #[hotpath::measure(impl_type = "CatalogHandle")]pub async fn refresh(&self, pool: &PgPool) -> Result<CatalogStats, CatalogRefreshError> {match self.refresh_from(|| load_realtime_cohorts(pool)).await {Ok(stats) => {diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rsindex 38bf909fdcde..58a76969fc4c 100644--- a/rust/cohort-stream-processor/src/main.rs+++ b/rust/cohort-stream-processor/src/main.rs@@ -48,10 +48,13 @@ use cohort_stream_processor::workers::{MergeWorkerDeps, PersonSeedDeps, ReconcileBacklog, ReconcileDeps,};+// Under `hotpath-alloc`, `#[hotpath::main]` installs its counting allocator around jemalloc instead.+#[cfg(not(feature = "hotpath-alloc"))]common_alloc::used!();const SERVICE_NAME: &str = "cohort-stream-processor";+#[hotpath::main(allocator = common_alloc::DefaultAllocator)]fn main() -> Result<()> {let config = Config::init_from_env().context("Failed to load configuration from environment variables")?;@@ -64,6 +67,7 @@ fn main() -> Result<()> {let runtime = runtime_builder.build().context("Failed to build tokio runtime")?;+ hotpath::tokio_runtime!(runtime.handle());runtime.block_on(async_main(config))}@@ -822,5 +826,10 @@ fn init_tracing() {.boxed()};- tracing_subscriber::registry().with(log_layer).init();+ let subscriber = tracing_subscriber::registry().with(log_layer);+ // Without `hotpath`, this returns an unfiltered no-op layer. That layer lifts the max level to+ // TRACE, so every DEBUG/TRACE call site builds its event, sqlx's per-query log included.+ #[cfg(feature = "hotpath")]+ let subscriber = subscriber.with(hotpath::sqlx_tracing_layer());+ subscriber.init();}diff --git a/rust/cohort-stream-processor/src/store/handle.rs b/rust/cohort-stream-processor/src/store/handle.rsindex fb43cd35da43..f6087f1a3b37 100644--- a/rust/cohort-stream-processor/src/store/handle.rs+++ b/rust/cohort-stream-processor/src/store/handle.rs@@ -117,7 +117,9 @@ pub struct StoreHandle {maintenance_permits: Option<Arc<Semaphore>>,}+#[hotpath::measure_all]impl StoreHandle {+ #[hotpath::skip]pub fn new(store: CohortStore, config: OffloadConfig) -> Self {// `0` = unbounded: model it as the absence of a semaphore so the offload path skips permit// acquisition entirely.@@ -130,6 +132,7 @@ impl StoreHandle {}}+ #[hotpath::skip]fn lane_permits(&self, lane: ReadLane) -> Option<&Arc<Semaphore>> {match lane {ReadLane::Event => self.event_permits.as_ref(),@@ -139,6 +142,7 @@ impl StoreHandle {/// Whether a read on `lane` runs inline under the current mode. Off is always inline; under/// Maintenance only the Event lane is inline (maintenance offloads); under All nothing is inline.+ #[hotpath::skip]fn read_runs_inline(&self, lane: ReadLane) -> bool {match self.mode {OffloadMode::Off => true,@@ -151,6 +155,7 @@ impl StoreHandle {/// Run a read op, offloading per mode + lane. Inline runs record no offload metrics, so Off adds/// no measurement overhead; the rocks-level metrics inside `CohortStore` fire on both paths.+ #[hotpath::skip]async fn read<T, F>(&self, op: &'static str, lane: ReadLane, f: F) -> Result<T, StoreError>whereT: Send + 'static,@@ -167,6 +172,7 @@ impl StoreHandle {/// `flush_wal_sync` (`is_fsync`): the fsync is the expensive syscall, memtable writes are cheap,/// so the fsync offloads while ordinary commits stay on the caller's thread. Under Off all/// inline, under All all offloaded.+ #[hotpath::skip]async fn write<T, F>(&self, op: &'static str, is_fsync: bool, f: F) -> Result<T, StoreError>whereT: Send + 'static,@@ -190,6 +196,7 @@ impl StoreHandle {/// label follows the permit so that `store_offload_inflight{lane="maintenance"}` counts every/// holder of a maintenance permit, sections included. Keeping stats on this executor is what/// lets `mode` stay matched in exactly the three executors (`read`, `write`, `section`).+ #[hotpath::skip]async fn section<T, F>(&self,op: &'static str,@@ -213,6 +220,7 @@ impl StoreHandle {/// The single offload path. Acquires the lane permit on the async side (cancellable), then moves/// it into the blocking closure so its hold time is exactly the op's execution — never spanning/// the post-spawn wake, which would couple hold time to runtime saturation.+ #[hotpath::skip]async fn offload<T, F>(&self,op: &'static str,@@ -389,6 +397,7 @@ impl StoreHandle {/// Start process-local dirty capture for one queued reconcile job. The returned lease owns the/// registration and disables it on drop.+ #[hotpath::skip]pub fn track_stage2_dirty(&self, prefix: Stage2CohortPrefix) -> Stage2DirtyTrackingGuard {self.store.track_stage2_dirty(prefix)}diff --git a/rust/cohort-stream-processor/src/workers/cascade_path.rs b/rust/cohort-stream-processor/src/workers/cascade_path.rsindex 56ed91a70739..7fce6d46f0d0 100644--- a/rust/cohort-stream-processor/src/workers/cascade_path.rs+++ b/rust/cohort-stream-processor/src/workers/cascade_path.rs@@ -38,6 +38,7 @@ use crate::workers::worker::{produce_cascades, produce_membership};/// Re-evaluate every referrer of the flipped cohort carried by one `cohort_cascade_events` message,/// emit their flips, continue the chain, and settle the cascade offset.#[allow(clippy::too_many_arguments)]+#[hotpath::measure]pub(crate) async fn handle_cascade(partition_id: u16,handle: &StoreHandle,diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rsindex a6a73d677d2a..5de75ff43e96 100644--- a/rust/cohort-stream-processor/src/workers/event_path.rs+++ b/rust/cohort-stream-processor/src/workers/event_path.rs@@ -339,6 +339,7 @@ pub fn process_event_gated(////// Sequential awaits only: the batched read must observe the prior event's committed writes, so the/// read and commit are never joined or reordered.+#[hotpath::measure]pub(crate) async fn process_event_offloaded(partition_id: u16,handle: &StoreHandle,@@ -389,6 +390,7 @@ fn record_snapshot_keys(snapshot: &EventSnapshotRaw) {/// Resolve everything up to the pre-event read: gating, behavioral evaluation and applies, and the/// person plan (fingerprints only — the person record read and evaluation happen in the fold).+#[hotpath::measure]pub(crate) fn plan_event(partition_id: u16,filters: &TeamFilters,@@ -446,6 +448,7 @@ pub(crate) fn plan_event(/// Fold the pre-event `snapshot` into the behavioral rows and the person record, staging the writes/// into a [`StagedBatch`] for the caller to commit. Pure w.r.t. the store. Returns/// [`FoldResult::Skip`] on a person-props parse failure.+#[hotpath::measure]pub(crate) fn fold_event(filters: &TeamFilters,read: ReadPlan,diff --git a/rust/cohort-stream-processor/src/workers/merge_gc.rs b/rust/cohort-stream-processor/src/workers/merge_gc.rsindex 5908602e4cac..015c84d76115 100644--- a/rust/cohort-stream-processor/src/workers/merge_gc.rs+++ b/rust/cohort-stream-processor/src/workers/merge_gc.rs@@ -83,6 +83,7 @@ impl MergeGcCursor {/// GC one partition's three merge CFs for one tick. `marker_cutoff_ms` gates the two idempotence/// markers; `tombstone_cutoff_ms` (longer) gates tombstones.+#[hotpath::measure]pub fn handle_merge_gc(partition_id: u16,store: &CohortStore,diff --git a/rust/cohort-stream-processor/src/workers/merge_path.rs b/rust/cohort-stream-processor/src/workers/merge_path.rsindex 4a065497bcf1..4fca02cf7cb2 100644--- a/rust/cohort-stream-processor/src/workers/merge_path.rs+++ b/rust/cohort-stream-processor/src/workers/merge_path.rs@@ -170,6 +170,7 @@ impl MergeWorkerDeps {}#[allow(clippy::too_many_arguments)]+#[hotpath::measure]pub(crate) async fn handle_merge(partition_id: u16,handle: &StoreHandle,@@ -344,6 +345,7 @@ pub(crate) async fn handle_merge(}#[allow(clippy::too_many_arguments)]+#[hotpath::measure]pub(crate) async fn handle_apply(partition_id: u16,handle: &StoreHandle,@@ -502,6 +504,7 @@ const REDRIVE_MAX_ATTEMPTS_PER_TICK: usize = 8;/// the next few ticks' worth of work staged without copying the whole outbox each tick.const SCAN_PENDING_TRANSFERS_LIMIT: usize = REDRIVE_MAX_ATTEMPTS_PER_TICK * 8;+#[hotpath::measure]pub(crate) async fn handle_redrive(partition_id: u16,handle: &StoreHandle,diff --git a/rust/cohort-stream-processor/src/workers/reconcile.rs b/rust/cohort-stream-processor/src/workers/reconcile.rsindex be9647299095..cc66434e7a47 100644--- a/rust/cohort-stream-processor/src/workers/reconcile.rs+++ b/rust/cohort-stream-processor/src/workers/reconcile.rs@@ -372,6 +372,7 @@ fn evaluate_guard(/// Advance the queue head by at most one scan page or one marker produce per tick.#[allow(clippy::too_many_arguments)]+#[hotpath::measure]pub(crate) async fn handle_reconcile_drain(partition_id: u16,handle: &StoreHandle,diff --git a/rust/cohort-stream-processor/src/workers/seed_apply.rs b/rust/cohort-stream-processor/src/workers/seed_apply.rsindex e5caa939b557..71883dce9196 100644--- a/rust/cohort-stream-processor/src/workers/seed_apply.rs+++ b/rust/cohort-stream-processor/src/workers/seed_apply.rs@@ -1157,6 +1157,7 @@ pub(crate) async fn handle_seed_groups(/// Apply one group of a collection: its mark lands in `marks`, a hold publishes at once. The/// caller publishes `marks` only after the collection's last group (see [`BatchMarks`]), which is/// what lets the partition worker apply the groups one per round with live batches in between.+#[hotpath::measure]pub(crate) async fn apply_seed_group(deps: ApplyDeps<'_>,queue: &mut EvictionQueue<BehavioralKey>,diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rsindex 1d0f89f8b2cb..a50c82f7a615 100644--- a/rust/cohort-stream-processor/src/workers/stage2_path.rs+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs@@ -33,6 +33,7 @@ use crate::workers::composition_inputs::ReferenceSource;/// read runs on. Every caller passes `Event`: the seed paths, which read on `Maintenance`, go/// through [`recompute_stage2_by_person`](super::stage2_person_inputs::recompute_stage2_by_person)/// instead, whose store sections draw the maintenance permit.+#[hotpath::measure]pub async fn compose_stage2(partition_id: u16,handle: &StoreHandle,diff --git a/rust/cohort-stream-processor/src/workers/sweep_path.rs b/rust/cohort-stream-processor/src/workers/sweep_path.rsindex 745aee1ce390..58ddd4886e07 100644--- a/rust/cohort-stream-processor/src/workers/sweep_path.rs+++ b/rust/cohort-stream-processor/src/workers/sweep_path.rs@@ -326,6 +326,7 @@ impl PreparedSweep {/// Run at most one sweep batch, then return so the worker can select again. No-op when nothing is/// due.#[allow(clippy::too_many_arguments)]+#[hotpath::measure]pub(crate) async fn run_sweep_turn(partition_id: u16,handle: &StoreHandle,diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex 0deb7eae4c8a..783ca05201aa 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -707,6 +707,7 @@ pub(crate) fn count_by_status(changes: &[CohortMembershipChange]) -> (u64, u64)/// Produce membership `changes`, await one ack per change, and record metrics. Returns the failed/// or missing/extra-ack count (`0` = fully acked). The caller owns the per-site warn and recovery/// action.+#[hotpath::measure]pub(crate) async fn produce_membership(sink: &Arc<dyn MembershipSink>,changes: Vec<CohortMembershipChange>,@@ -752,6 +753,7 @@ pub(crate) fn first_cascades(/// missing/extra-ack count (`0` when empty or fully acked). The caller owns the recovery posture:/// the event path holds the offset; the sweep/merge paths drop (at-most-once). Shared by the/// first-hop leg and onward-hop consumer legs.+#[hotpath::measure]pub(crate) async fn produce_cascades(merge: &MergeWorkerDeps,cascades: Vec<CascadeMessage>,@@ -777,6 +779,7 @@ struct EventEffects {}#[allow(clippy::too_many_arguments)]+#[hotpath::measure]async fn handle_event(partition_id: u16,handle: &StoreHandle,