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(replay): instrument ml parquet partitioning and score export sweep (#71571)

Robbie47ea9c9ed895
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts
index c85ec21efe18..058b2b1c8fb7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts
@@ -10,6 +10,10 @@ import { rowsToParquetBuffer } from './parquet-writer'
const cmp = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)
+const DAY_MS = 86_400_000
+// The `dt=` partition is a UTC date, so measure lag and span in whole UTC days to match it.
+const utcDay = (ms: number): number => Math.floor(ms / DAY_MS)
+
export class BlockMetadataParquetStore {
private seq = 0
private readonly nodeId: string
@@ -33,11 +37,13 @@ export class BlockMetadataParquetStore {
rows.sort((a, b) => cmp(a.team_id, b.team_id) || cmp(a.session_id, b.session_id))
let body: Buffer
let key: string
+ let bounds: { minMs: number; maxMs: number }
try {
// Encoding, key derivation, and upload all count as write failures: each leaves the batch to
// replay from Kafka, so the counter must see them, not just the S3 send.
body = await rowsToParquetBuffer(rows)
- key = this.objectKey(minEventDate(rows))
+ bounds = eventTimeBounds(rows)
+ key = this.objectKey(new Date(bounds.minMs).toISOString().slice(0, 10))
await this.s3Client.send(
new PutObjectCommand({
Bucket: this.bucket,
@@ -51,6 +57,12 @@ export class BlockMetadataParquetStore {
throw error
}
MlParquetSinkMetrics.observeWrite(rows.length, body.length)
+ // The object's partition date is its oldest event day, so a mixed-date batch (span > 0) lands most
+ // of its rows under an understated dt. Expose both so a stale partition from a straggler is visible.
+ MlParquetSinkMetrics.observePartition(
+ utcDay(Date.now()) - utcDay(bounds.minMs),
+ utcDay(bounds.maxMs) - utcDay(bounds.minMs)
+ )
logger.info('🪶', 'ml_parquet_metadata_written', { rows: rows.length, bytes: body.length, key })
}
@@ -61,13 +73,20 @@ export class BlockMetadataParquetStore {
}
}
-/** Partition by the earliest event time in the batch (rows can span a window, so the min wins). */
-function minEventDate(rows: MlBlockMetadataRow[]): string {
+/**
+ * Earliest and latest event time in the batch. The earliest sets the object's `dt=` partition (rows can
+ * span a window, so the min wins); the latest lets the caller measure how far the batch's dates spread.
+ */
+function eventTimeBounds(rows: MlBlockMetadataRow[]): { minMs: number; maxMs: number } {
let minMs = rows[0].first_ts_ms
+ let maxMs = rows[0].first_ts_ms
for (const row of rows) {
if (row.first_ts_ms < minMs) {
minMs = row.first_ts_ms
}
+ if (row.first_ts_ms > maxMs) {
+ maxMs = row.first_ts_ms
+ }
}
- return new Date(minMs).toISOString().slice(0, 10)
+ return { minMs, maxMs }
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index 91eb451e641a..43a0d18bb2f3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -1,4 +1,8 @@
-import { Counter } from 'prom-client'
+import { Counter, Histogram } from 'prom-client'
+
+// Days. A batch that spans dates files the whole object under its oldest event date (see objectKey), so
+// these buckets are chosen to separate a same-day batch (span 0) from one dragged back by a straggler.
+const PARTITION_DAY_BUCKETS = [0, 1, 2, 3, 7, 14, 30, 90, 365]
/**
* Metrics for the ML block-metadata Parquet sink (drains the mirror's block-metadata topic to the ML
@@ -36,6 +40,16 @@ export class MlParquetSinkMetrics {
help: 'Batcher flushes by outcome: wrote a Parquet object, or committed offsets with an empty buffer',
labelNames: ['outcome'],
})
+ private static readonly partitionLagDays = new Histogram({
+ name: 'ml_mirror_parquet_sink_partition_lag_days',
+ help: "Days between an object's partition date (its oldest event date) and write time",
+ buckets: PARTITION_DAY_BUCKETS,
+ })
+ private static readonly eventDateSpanDays = new Histogram({
+ name: 'ml_mirror_parquet_sink_event_date_span_days',
+ help: 'Days between the oldest and newest event date in one written object; a non-zero span means a mixed-date batch whose partition date understates most of its rows',
+ buckets: PARTITION_DAY_BUCKETS,
+ })
public static incRowsParsed(count: number): void {
this.rowsParsed.inc(count)
@@ -54,4 +68,8 @@ export class MlParquetSinkMetrics {
public static incFlush(outcome: 'written' | 'empty'): void {
this.flushes.labels(outcome).inc()
}
+ public static observePartition(lagDays: number, spanDays: number): void {
+ this.partitionLagDays.observe(lagDays)
+ this.eventDateSpanDays.observe(spanDays)
+ }
}
diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/metrics.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/metrics.py
new file mode 100644
index 000000000000..ca5603688efa
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/metrics.py
@@ -0,0 +1,35 @@
+"""Tick-level metrics for the surfacing score export sweep.
+
+The workflow gathers partition results with return_exceptions=True and summarizes rather than raising, so a
+tick where every partition fails still completes successfully. These counters make that visible: without
+them a total failure is only a log line, and the workflow's success hides it from any dashboard or alert.
+"""
+
+from posthog.temporal.ai_observability.metrics import get_metric_meter
+
+PARTITIONS_DISPATCHED_COUNTER = "surfacing_score_export_partitions_dispatched"
+PARTITIONS_DISPATCHED_DESCRIPTION = "Partitions dispatched for export in a surfacing score export sweep tick"
+
+PARTITIONS_FAILED_COUNTER = "surfacing_score_export_partitions_failed"
+PARTITIONS_FAILED_DESCRIPTION = "Partitions that failed to export in a surfacing score export sweep tick"
+
+ROWS_EXPORTED_COUNTER = "surfacing_score_export_rows_exported"
+ROWS_EXPORTED_DESCRIPTION = "Score rows exported in a surfacing score export sweep tick"
+
+TICKS_ALL_FAILED_COUNTER = "surfacing_score_export_ticks_all_failed"
+TICKS_ALL_FAILED_DESCRIPTION = (
+ "Sweep ticks where every dispatched partition failed yet the workflow still completed successfully"
+)
+
+
+def record_tick_summary(*, partitions_dispatched: int, partitions_failed: int, total_rows: int) -> None:
+ if partitions_dispatched <= 0:
+ return
+ meter = get_metric_meter()
+ meter.create_counter(PARTITIONS_DISPATCHED_COUNTER, PARTITIONS_DISPATCHED_DESCRIPTION).add(partitions_dispatched)
+ if partitions_failed > 0:
+ meter.create_counter(PARTITIONS_FAILED_COUNTER, PARTITIONS_FAILED_DESCRIPTION).add(partitions_failed)
+ if total_rows > 0:
+ meter.create_counter(ROWS_EXPORTED_COUNTER, ROWS_EXPORTED_DESCRIPTION).add(total_rows)
+ if partitions_failed >= partitions_dispatched:
+ meter.create_counter(TICKS_ALL_FAILED_COUNTER, TICKS_ALL_FAILED_DESCRIPTION).add(1)
diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py
index 9378b86ce56d..864663b42ac3 100644
--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py
+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py
@@ -29,6 +29,7 @@ with workflow.unsafe.imports_passed_through():
export_scores_partition_activity,
list_export_partitions_activity,
)
+ from posthog.temporal.session_replay.surfacing_score_export_sweep.metrics import record_tick_summary
_PATCH_BOUNDED_PARTITION_FANOUT = "surfacing-score-export-bounded-partition-fanout"
@@ -110,4 +111,9 @@ def _summarize(
partitions_failed=summary.partitions_failed,
total_rows=summary.total_rows,
)
+ record_tick_summary(
+ partitions_dispatched=summary.partitions_dispatched,
+ partitions_failed=summary.partitions_failed,
+ total_rows=summary.total_rows,
+ )
return summary
diff --git a/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_workflow.py b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_workflow.py
index afedaf8ba46b..81d5db3c81fe 100644
--- a/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_workflow.py
+++ b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/test_workflow.py
@@ -49,9 +49,15 @@ async def test_bounds_concurrent_partition_activities() -> None:
patch("temporalio.workflow.execute_activity", side_effect=execute_activity),
patch("temporalio.workflow.patched", return_value=True),
patch("temporalio.workflow.logger", MagicMock()),
+ patch(
+ "posthog.temporal.session_replay.surfacing_score_export_sweep.workflow.record_tick_summary"
+ ) as record_summary,
):
result = await ExportSurfacingScoresWorkflow().run(ExportScoresSweepInputs())
assert peak_active == MAX_CONCURRENT_EXPORT_PARTITIONS
assert result.partitions_dispatched == partition_count
assert result.total_rows == partition_count
+ record_summary.assert_called_once_with(
+ partitions_dispatched=partition_count, partitions_failed=0, total_rows=partition_count
+ )