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(session-replay): unblock surfacing scoring sweep (#64406)

Tue Haulund82c446919e48
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py
index b24983acd671..643d32173a86 100644
--- a/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py
@@ -53,6 +53,7 @@ from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import (
TARGET_CHUNK_SIZE,
)
from posthog.temporal.session_replay.surfacing_scoring_sweep.features import (
+ ID_COLUMNS,
MODEL_FEATURE_SCHEMA_VERSION,
FeatureValidationError,
out_of_contract_row_mask,
@@ -121,6 +122,15 @@ async def list_chunks_activity(_inputs: ScoreSessionsBatchInputs) -> ListChunksR
# --------------------------------------------------------------------------- #
+def _build_features_dataframe(rows: list[tuple], columns: list[str]) -> pd.DataFrame:
+ """Coerce all-NULL feature columns (driver returns all-`None` → pandas `object`) to float so they pass `validate_features`; typed columns are left untouched so genuine dtype drift still fails the chunk."""
+ df = pd.DataFrame(rows, columns=pd.Index(columns))
+ for col in df.columns:
+ if col not in ID_COLUMNS and df[col].dtype == object and df[col].isna().all():
+ df[col] = df[col].astype(float)
+ return df
+
+
def _fetch_features_dataframe(spec: ChunkSpec) -> pd.DataFrame:
"""Run the feature SELECT and return a pandas DataFrame."""
result = cast(
@@ -142,7 +152,7 @@ def _fetch_features_dataframe(spec: ChunkSpec) -> pd.DataFrame:
)
rows, column_metadata = result
columns = [name for name, _type in column_metadata]
- return pd.DataFrame(rows, columns=pd.Index(columns))
+ return _build_features_dataframe(rows, columns)
def _build_partial_row(
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/sql.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/sql.py
index 46d0f7a8bd5c..fdaea2dfb79c 100644
--- a/posthog/temporal/session_replay/surfacing_scoring_sweep/sql.py
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/sql.py
@@ -2,8 +2,9 @@
The serving SELECT mirrors the training query in four CTEs:
- 1. `eligible_sessions`: hash-partitioned slice of unscored sessions
- (`HAVING max(surfacing_score) IS NULL`) from `session_replay_events`.
+ 1. `eligible_sessions`: hash-partitioned slice of unscored, eventful sessions
+ (`HAVING max(surfacing_score) IS NULL AND sum(event_count) > 0`) from
+ `session_replay_events`.
It carries `distinct_id` and `min_first_timestamp` to the producer
because the partial-row Kafka writeback must reuse the real distinct_id
(the `sipHash64(distinct_id)` shard key) and session-start timestamp
@@ -242,6 +243,9 @@ WITH eligible_sessions AS (
GROUP BY team_id, session_id
HAVING max(surfacing_score) IS NULL
AND started_at >= now() - toIntervalDay(%(lookback_days)s)
+ -- Eventless sessions have no features, so the inner join always drops them;
+ -- excluding them here stops them starving the LIMIT and being re-picked every tick.
+ AND sum(event_count) > 0
-- ORDER BY makes LIMIT deterministic across the two CTE evaluations
-- (CH inlines CTEs as subqueries — without a stable order, the GLOBAL IN
-- subquery and the final FROM could pick different subsets and the
@@ -352,6 +356,8 @@ FROM (
GROUP BY team_id, session_id
HAVING max(surfacing_score) IS NULL
AND min(min_first_timestamp) >= now() - toIntervalDay(%(lookback_days)s)
+ -- Match fetch_features_sql: eventless sessions aren't scorable backlog.
+ AND sum(event_count) > 0
)
""".strip()
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/ch_insert_helpers.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/ch_insert_helpers.py
index 35f785a7c0ec..2c72f64b6c13 100644
--- a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/ch_insert_helpers.py
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/ch_insert_helpers.py
@@ -21,6 +21,7 @@ INSERT INTO sharded_session_replay_events (
first_url,
snapshot_source,
snapshot_library,
+ event_count,
surfacing_score
)
SELECT
@@ -32,6 +33,7 @@ SELECT
argMinState(cast(NULL, 'Nullable(String)'), now64(6) - INTERVAL 1 HOUR),
argMinState(cast(NULL, 'LowCardinality(Nullable(String))'), now64(6) - INTERVAL 1 HOUR),
argMinState(cast(NULL, 'Nullable(String)'), now64(6) - INTERVAL 1 HOUR),
+ %(event_count)s,
%(surfacing_score)s
"""
@@ -45,6 +47,7 @@ INSERT INTO sharded_session_replay_events (
first_url,
snapshot_source,
snapshot_library,
+ event_count,
surfacing_score
)
SELECT
@@ -56,6 +59,7 @@ SELECT
argMinState(cast(NULL, 'Nullable(String)'), toDateTime64(%(start)s, 6, 'UTC')),
argMinState(cast(NULL, 'LowCardinality(Nullable(String))'), toDateTime64(%(start)s, 6, 'UTC')),
argMinState(cast(NULL, 'Nullable(String)'), toDateTime64(%(start)s, 6, 'UTC')),
+ %(event_count)s,
%(surfacing_score)s
"""
@@ -67,12 +71,14 @@ def insert_session_replay_event(
distinct_id: str = "d1",
start: datetime | None = None,
end: datetime | None = None,
+ event_count: int = 1,
surfacing_score: float | None = None,
) -> None:
params = {
"session_id": session_id,
"team_id": team_id,
"distinct_id": distinct_id,
+ "event_count": event_count,
"surfacing_score": surfacing_score,
}
if start is None:
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_activities.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_activities.py
index 6e8a71971202..2825c82af498 100644
--- a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_activities.py
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_activities.py
@@ -11,6 +11,7 @@ from temporalio.exceptions import ApplicationError
from temporalio.testing import ActivityEnvironment
from posthog.temporal.session_replay.surfacing_scoring_sweep.activities import (
+ _build_features_dataframe,
_build_partial_row,
list_chunks_activity,
score_chunk_activity,
@@ -21,7 +22,11 @@ from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import (
SCORE_CHUNK_HEARTBEAT_TIMEOUT,
TARGET_CHUNK_SIZE,
)
-from posthog.temporal.session_replay.surfacing_scoring_sweep.features import FeatureValidationError
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import (
+ ID_COLUMNS,
+ FeatureValidationError,
+ validate_features,
+)
from posthog.temporal.session_replay.surfacing_scoring_sweep.types import ChunkSpec, ScoreSessionsBatchInputs
ACTIVITIES_MODULE = "posthog.temporal.session_replay.surfacing_scoring_sweep.activities"
@@ -62,6 +67,60 @@ class TestBuildPartialRow:
assert row["last_timestamp"] == "2026-05-07 10:00:00.000001"
+class TestBuildFeaturesDataframe:
+ def _rows(self, feature_names: tuple[str, ...], null_feature: str | None) -> tuple[list[tuple], list[str]]:
+ columns = [*ID_COLUMNS, *feature_names]
+ rows = [
+ (
+ 1,
+ f"sess-{i}",
+ f"user-{i}",
+ datetime(2026, 5, 7, 10, 0, 0),
+ *(None if name == null_feature else 0.1 for name in feature_names),
+ )
+ for i in range(2)
+ ]
+ return rows, columns
+
+ def test_all_null_feature_column_is_coerced_to_float_and_validates(
+ self, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ # Reproduces the production failure: a `x / nullIf(denom, 0)` feature is
+ # NULL for every row in a chunk of simple sessions. The driver returns
+ # all-None, which pandas infers as object dtype unless we coerce.
+ rows, columns = self._rows(feature_names_for_tests, null_feature="inter_action_gap_mean_ms")
+
+ df = _build_features_dataframe(rows, columns)
+
+ assert df["inter_action_gap_mean_ms"].dtype.kind == "f"
+ assert df["inter_action_gap_mean_ms"].isna().all()
+ validate_features(df, feature_names=feature_names_for_tests)
+
+ def test_id_columns_keep_native_dtypes(self, feature_names_for_tests: tuple[str, ...]) -> None:
+ rows, columns = self._rows(feature_names_for_tests, null_feature=None)
+
+ df = _build_features_dataframe(rows, columns)
+
+ assert df["session_id"].dtype.kind == "O"
+ assert df["min_first_timestamp"].dtype.kind == "M"
+
+ def test_non_numeric_feature_drift_is_left_for_validation_to_reject(
+ self, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ # Coercion only touches all-NULL columns, so genuine SQL drift (a typed
+ # non-numeric column) stays object dtype and fails loudly at the validator
+ # — a non-retryable FeatureValidationError, not a silently coerced NaN.
+ rows, columns = self._rows(feature_names_for_tests, null_feature=None)
+ bad = list(rows[0])
+ bad[len(ID_COLUMNS)] = "not-a-number" # first feature column
+
+ df = _build_features_dataframe([tuple(bad)], columns)
+
+ assert df[feature_names_for_tests[0]].dtype.kind == "O"
+ with pytest.raises(FeatureValidationError):
+ validate_features(df, feature_names=feature_names_for_tests)
+
+
class TestScoreChunkActivity:
@pytest.mark.asyncio
async def test_empty_chunk_returns_zero_without_touching_model(self, surfacing_booster_path: object) -> None:
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_score_chunk_pipeline_clickhouse.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_score_chunk_pipeline_clickhouse.py
index f24dc788e603..2e371d102c62 100644
--- a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_score_chunk_pipeline_clickhouse.py
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_score_chunk_pipeline_clickhouse.py
@@ -162,6 +162,23 @@ class TestScoreChunkPipelineClickhouse(ClickhouseTestMixin, BaseTest):
assert df.empty, "INNER JOIN should drop sessions with no replay features"
+ def test_eventless_session_is_excluded_even_with_features(self) -> None:
+ # A session with no replay events can't be scored; it must be dropped at
+ # the eligibility stage (not just by the join) so it never consumes the
+ # chunk's LIMIT budget — even though a features row exists for it here.
+ insert_session_replay_event(
+ team_id=self.team.id,
+ session_id=self.session_id,
+ distinct_id=self.distinct_id,
+ start=self.session_start,
+ event_count=0,
+ )
+ self._seed_replay_features()
+
+ spec = ChunkSpec(chunk_id=0, of_chunks=1, chunk_size=10, lookback_days=7)
+ df = _fetch_features_dataframe(spec)
+ assert df.empty
+
def test_already_scored_session_is_excluded(self) -> None:
insert_session_replay_event(
team_id=self.team.id,
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_clickhouse.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_clickhouse.py
index 9ddb7bc825ff..bedf818499b1 100644
--- a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_clickhouse.py
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_clickhouse.py
@@ -1,7 +1,9 @@
from __future__ import annotations
import re
+from collections.abc import Callable
+import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin
from posthog.clickhouse.client import sync_execute
@@ -51,6 +53,10 @@ class TestFetchFeaturesSqlShape:
assert "AND min_first_timestamp >= now() - toIntervalDay(%(lookback_days)s + 1)" in sql
assert "AND started_at >= now() - toIntervalDay(%(lookback_days)s)" in sql
+ @pytest.mark.parametrize("sql_fn", [fetch_features_sql, count_unscored_sql])
+ def test_excludes_eventless_sessions(self, sql_fn: Callable[[], str]) -> None:
+ assert "AND sum(event_count) > 0" in sql_fn()
+
def test_count_unscored_has_raw_row_prefilter(self) -> None:
sql = count_unscored_sql()
assert "AND min_first_timestamp >= now() - toIntervalDay(%(lookback_days)s + 1)" in sql