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(session-replay): run the surfacing score sweep against session_replay_events (#60084)

Arno Hillen1c58af889128
diff --git a/posthog/hogql/database/schema/session_replay_events.py b/posthog/hogql/database/schema/session_replay_events.py
index aaeb4b69123f..d963373871ea 100644
--- a/posthog/hogql/database/schema/session_replay_events.py
+++ b/posthog/hogql/database/schema/session_replay_events.py
@@ -215,6 +215,7 @@ SESSION_REPLAY_EVENTS_COMMON_FIELDS: dict[str, FieldOrTable] = {
"ai_tags_fixed": DatabaseField(name="ai_tags_fixed", nullable=True),
"ai_tags_freeform": DatabaseField(name="ai_tags_freeform", nullable=True),
"ai_highlighted": IntegerDatabaseField(name="ai_highlighted", nullable=False),
+ "surfacing_score": DatabaseField(name="surfacing_score", nullable=True),
"events": LazyJoin(
from_field=["session_id"],
join_table=EventsTable(),
@@ -289,6 +290,7 @@ def select_from_session_replay_events_table(requested_fields: dict[str, list[str
name="groupUniqArrayArray", args=[ast.Field(chain=[table_name, "ai_tags_freeform"])]
),
"ai_highlighted": ast.Call(name="max", args=[ast.Field(chain=[table_name, "ai_highlighted"])]),
+ "surfacing_score": ast.Call(name="max", args=[ast.Field(chain=[table_name, "surfacing_score"])]),
}
select_fields: list[ast.Expr] = []
diff --git a/posthog/hogql/test/__snapshots__/test_resolver.ambr b/posthog/hogql/test/__snapshots__/test_resolver.ambr
index 533b6b1965e9..47e9439dbaef 100644
--- a/posthog/hogql/test/__snapshots__/test_resolver.ambr
+++ b/posthog/hogql/test/__snapshots__/test_resolver.ambr
@@ -3991,6 +3991,9 @@
start_time: {
hidden: False
},
+ surfacing_score: {
+ hidden: False
+ },
team_id: {
hidden: False
}
@@ -4411,6 +4414,26 @@
type: <recursion ...>
}
},
+ {
+ alias: "surfacing_score"
+ expr: {
+ chain: [
+ "e",
+ "surfacing_score"
+ ]
+ from_asterisk: True
+ type: {
+ name: "surfacing_score"
+ table_type: <recursion ...>
+ }
+ }
+ from_asterisk: False
+ hidden: True
+ type: {
+ alias: "surfacing_score"
+ type: <recursion ...>
+ }
+ },
{
alias: "start_time"
expr: {
@@ -4710,7 +4733,8 @@
size: <recursion ...>,
snapshot_library: <recursion ...>,
snapshot_source: <recursion ...>,
- start_time: <recursion ...>
+ start_time: <recursion ...>,
+ surfacing_score: <recursion ...>
}
ctes: {}
is_lambda_type: False
diff --git a/posthog/management/commands/score_one_chunk.py b/posthog/management/commands/score_one_chunk.py
new file mode 100644
index 000000000000..9fd8149c32a0
--- /dev/null
+++ b/posthog/management/commands/score_one_chunk.py
@@ -0,0 +1,113 @@
+"""Manual smoke-test for the session surfacing scoring pipeline.
+
+Pulls one bucket of unscored sessions from ClickHouse, runs the XGBoost booster,
+and prints the scores. Read-only (writes nothing back). Handy to verify the model
+loads and predicts in a fresh env, eyeball the score distribution, or reproduce a
+prod scoring failure locally with the same SQL the activity runs.
+
+Requires `SESSION_INTERESTINGNESS_MODEL_S3_URI` (see surfacing_scoring_sweep README).
+
+Examples:
+ ./bin/python manage.py score_one_chunk
+ ./bin/python manage.py score_one_chunk --chunk-size 50 --lookback-days 30
+ ./bin/python manage.py score_one_chunk --chunk-id 7 --of-chunks 20
+
+Defaults are small so the output is readable; production uses chunk_size=10_000,
+of_chunks=20.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandParser
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep.activities import _fetch_features_dataframe
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import (
+ FeatureValidationError,
+ out_of_contract_row_mask,
+ validate_features,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.scorer import get_feature_names, predict
+from posthog.temporal.session_replay.surfacing_scoring_sweep.types import ChunkSpec
+
+
+class Command(BaseCommand):
+ help = "Score one chunk of unscored sessions and print the results (no writeback)."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument(
+ "--chunk-id",
+ type=int,
+ default=0,
+ help="Hash bucket id; must be < --of-chunks. Defaults to 0.",
+ )
+ parser.add_argument(
+ "--of-chunks",
+ type=int,
+ default=1,
+ help="Total number of hash buckets. Defaults to 1 (every session in this bucket).",
+ )
+ parser.add_argument(
+ "--chunk-size",
+ type=int,
+ default=10,
+ help="Max rows to fetch + score. Defaults to 10 for legible output.",
+ )
+ parser.add_argument(
+ "--lookback-days",
+ type=int,
+ default=7,
+ help="Only consider sessions newer than this many days. Defaults to 7 (matches prod).",
+ )
+
+ def handle(self, *_args: Any, **options: Any) -> None:
+ spec = ChunkSpec(
+ chunk_id=options["chunk_id"],
+ of_chunks=options["of_chunks"],
+ chunk_size=options["chunk_size"],
+ lookback_days=options["lookback_days"],
+ )
+
+ self.stdout.write(self.style.NOTICE(f"Fetching with {spec} ..."))
+ df = _fetch_features_dataframe(spec)
+ self.stdout.write(f" rows={len(df)} cols={len(df.columns)}")
+ if df.empty:
+ self.stdout.write(self.style.WARNING("No unscored sessions in this bucket — nothing to score."))
+ return
+
+ feature_names = get_feature_names()
+ self.stdout.write(f" booster.feature_names: {len(feature_names)} features")
+
+ try:
+ validate_features(df, feature_names=feature_names)
+ except FeatureValidationError as e:
+ self.stdout.write(
+ self.style.ERROR(
+ f"validate_features failed: {e}\n"
+ " → SQL output drifted from the booster's expected schema. "
+ "Run `pytest posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_alignment.py` "
+ "to localize the mismatch."
+ )
+ )
+ return
+
+ bad_rows = out_of_contract_row_mask(df, feature_names=feature_names)
+ if bad_rows.any():
+ self.stdout.write(
+ self.style.WARNING(f"Dropping {int(bad_rows.sum())} row(s) with out-of-contract feature values.")
+ )
+ df = df.loc[~bad_rows]
+ if df.empty:
+ self.stdout.write(self.style.WARNING("All rows dropped — nothing to score."))
+ return
+
+ scores = predict(df)
+ self.stdout.write(self.style.SUCCESS(f"Scored {len(scores)} session(s):"))
+ for session_id, team_id, score in zip(df["session_id"], df["team_id"], scores, strict=True):
+ self.stdout.write(f" team={team_id} session={session_id} score={float(score):.4f}")
+
+ self.stdout.write("")
+ self.stdout.write(
+ f" min={float(scores.min()):.4f} max={float(scores.max()):.4f} mean={float(scores.mean()):.4f}"
+ )
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index dead21436dbc..6c082077f8a4 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -146,6 +146,10 @@ from posthog.temporal.session_replay.summarization_sweep import (
SUMMARIZATION_SWEEP_ACTIVITIES,
SUMMARIZATION_SWEEP_WORKFLOWS,
)
+from posthog.temporal.session_replay.surfacing_scoring_sweep import (
+ SURFACING_SCORING_SWEEP_ACTIVITIES,
+ SURFACING_SCORING_SWEEP_WORKFLOWS,
+)
from posthog.temporal.sync_person_distinct_ids import (
ACTIVITIES as SYNC_PERSON_DISTINCT_IDS_ACTIVITIES,
WORKFLOWS as SYNC_PERSON_DISTINCT_IDS_WORKFLOWS,
@@ -386,6 +390,11 @@ _task_queue_specs = [
LOGS_ALERTING_WORKFLOWS,
LOGS_ALERTING_ACTIVITIES,
),
+ (
+ settings.SURFACING_SCORING_SWEEP_TASK_QUEUE,
+ SURFACING_SCORING_SWEEP_WORKFLOWS,
+ SURFACING_SCORING_SWEEP_ACTIVITIES,
+ ),
]
# Note: When running locally, many task queues resolve to the same queue name.
@@ -630,6 +639,11 @@ class Command(BaseCommand):
)
logger.info("Starting Temporal Worker")
+ if task_queue == settings.SURFACING_SCORING_SWEEP_TASK_QUEUE:
+ from posthog.temporal.session_replay.surfacing_scoring_sweep.scorer import warmup
+
+ warmup()
+
worker = runner.run(
create_worker(
temporal_host,
diff --git a/posthog/management/commands/upload_surfacing_model.py b/posthog/management/commands/upload_surfacing_model.py
new file mode 100644
index 000000000000..b7a5bae63184
--- /dev/null
+++ b/posthog/management/commands/upload_surfacing_model.py
@@ -0,0 +1,87 @@
+"""Upload a trained XGBoost booster (.ubj) to object storage.
+
+Uses `posthog.storage.object_storage` so it works against prod S3, staging, and
+local object storage with no config changes. After upload, set on the worker:
+ SESSION_INTERESTINGNESS_MODEL_S3_URI=s3://<bucket>/<key>
+
+Examples:
+ ./bin/python manage.py upload_surfacing_model ./surfacing_score_xgb_v1.ubj
+ ./bin/python manage.py upload_surfacing_model ./surfacing_score_xgb_v1.ubj --bucket my-bucket --key surfacing-scoring/surfacing_score_xgb_v2.ubj
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+import xgboost as xgb
+
+from posthog.storage import object_storage
+from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import MODEL_S3_KEY
+from posthog.temporal.session_replay.surfacing_scoring_sweep.feature_schema import (
+ FeatureSchemaDriftError,
+ assert_serving_schema_parity,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import MissingFeatureRangeError
+
+
+class Command(BaseCommand):
+ help = "Upload a session surfacing booster (.ubj) to object storage."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument(
+ "path",
+ type=str,
+ help="Local path to the .ubj booster file to upload.",
+ )
+ parser.add_argument(
+ "--bucket",
+ type=str,
+ default=None,
+ help=f"Target bucket. Defaults to settings.OBJECT_STORAGE_BUCKET ({settings.OBJECT_STORAGE_BUCKET!r}).",
+ )
+ parser.add_argument(
+ "--key",
+ type=str,
+ default=MODEL_S3_KEY,
+ help=f"Object key. Defaults to {MODEL_S3_KEY!r}.",
+ )
+ parser.add_argument(
+ "--skip-validate",
+ action="store_true",
+ help="Skip xgb.Booster.load_model() round-trip + feature_names check.",
+ )
+
+ def handle(self, *_args: Any, **options: Any) -> None:
+ source = Path(options["path"])
+ if not source.is_file():
+ raise CommandError(f"Source file {source!r} does not exist or is not a regular file.")
+
+ if not options["skip_validate"]:
+ try:
+ booster = xgb.Booster()
+ booster.load_model(str(source))
+ except Exception as e:
+ raise CommandError(f"xgboost rejected {source!r}: {e}")
+ names = tuple(booster.feature_names or ())
+ if not names:
+ raise CommandError(
+ f"{source!r} has no feature_names. Pass `feature_names=` to xgb.DMatrix at train time."
+ )
+ try:
+ assert_serving_schema_parity(names)
+ except (FeatureSchemaDriftError, MissingFeatureRangeError) as e:
+ raise CommandError(f"booster doesn't match current SQL/FEATURE_RANGES:\n{e}")
+ self.stdout.write(f" validated: {len(names)} features, {source.stat().st_size} bytes")
+
+ bucket = options["bucket"] or settings.OBJECT_STORAGE_BUCKET
+ key = options["key"]
+ self.stdout.write(self.style.NOTICE(f"Uploading {source} → s3://{bucket}/{key} ..."))
+
+ object_storage.write_from_file(file_name=key, file_path=str(source), bucket=bucket)
+
+ self.stdout.write(self.style.SUCCESS(f"Uploaded. Wire on the worker:"))
+ self.stdout.write(f" SESSION_INTERESTINGNESS_MODEL_S3_URI=s3://{bucket}/{key}")
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 6d8af40038c0..fa9d488bd9b2 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -113,6 +113,11 @@ MESSAGING_TASK_QUEUE = _set_temporal_task_queue("messaging-task-queue")
ANALYTICS_PLATFORM_TASK_QUEUE = _set_temporal_task_queue("analytics-platform-task-queue")
SESSION_REPLAY_TASK_QUEUE = _set_temporal_task_queue("session-replay-task-queue")
REPLAY_VISION_TASK_QUEUE = _set_temporal_task_queue("replay-vision-task-queue")
+# Dedicated queue for the XGBoost-based session surfacing scoring sweep. Workers
+# pulling this queue need libomp + xgboost installed and a sized CPU budget
+# (see posthog/temporal/session_replay/surfacing_scoring_sweep/README.md for
+# `OMP_NUM_THREADS` guidance).
+SURFACING_SCORING_SWEEP_TASK_QUEUE = _set_temporal_task_queue("surfacing-scoring-sweep-task-queue")
WEEKLY_DIGEST_TASK_QUEUE = _set_temporal_task_queue("weekly-digest-task-queue")
LLMA_EVALS_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-evals-task-queue")
LLMA_SENTIMENT_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-sentiment-task-queue")
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 474546380fd6..8a1af78cb8b0 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -71,6 +71,7 @@ from posthog.temporal.session_replay.replay_count_metrics.types import ReplayCou
from posthog.temporal.session_replay.summarization_sweep.reconciler import (
create_summarization_sweep_reconciler_schedule,
)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.schedule import create_surfacing_scoring_sweep_schedule
from posthog.temporal.usage_report.types import RunUsageReportsInputs
from posthog.temporal.warehouse_sources_queue_partition_management.schedule import (
create_warehouse_sources_queue_partition_management_schedule,
@@ -684,6 +685,7 @@ schedules = [
create_evaluation_clustering_schedule,
cleanup_legacy_session_summarization_schedules,
create_summarization_sweep_reconciler_schedule,
+ create_surfacing_scoring_sweep_schedule,
create_ducklake_compaction_schedule,
create_purge_deleted_recording_metadata_schedule,
create_experiment_regular_metrics_schedules,
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/README.md b/posthog/temporal/session_replay/surfacing_scoring_sweep/README.md
new file mode 100644
index 000000000000..3d4afa7f36fd
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/README.md
@@ -0,0 +1,310 @@
+# Session surfacing scoring
+
+Temporal pipeline that runs an XGBoost model over recently-created sessions and
+writes the resulting surfacing score (a Float32 in `[0, 1]`) onto
+`session_replay_events.surfacing_score`.
+
+The score is intended to drive downstream session-summarization work — sessions
+with higher scores are prioritized.
+
+## Architecture
+
+```text
+Schedule (every 5 min, ScheduleOverlapPolicy.SKIP)
+ │
+ ▼
+ScoreSessionsBatchWorkflow (parent — scaffolding only)
+ │
+ ├── list_chunks_activity (one cheap CH count, returns N specs)
+ │
+ └── asyncio.gather over chunks
+ score_chunk_activity(spec) (× N, runs in parallel)
+ internally:
+ 1. CH SELECT eligible (hash-partitioned, IS NULL) sessions
+ from session_replay_events, INNER JOIN feature CTEs over
+ session_replay_features (same expressions as the
+ training query)
+ 2. validate_features (hard fail on schema drift)
+ 3. xgboost.Booster.predict
+ 4. get_producer(REPLAY) → Kafka topic
+ (clickhouse_session_replay_events)
+ 5. existing session_replay_events_mv merges the partial row
+ into the real session row in writable_session_replay_events
+ 6. return ChunkResult(scored=N)
+```
+
+### Score writeback path
+
+Producer side (`activities._publish_scores`):
+
+- One JSONEachRow message per scored session on
+ `KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS` — the same topic ingestion uses.
+- The payload carries `session_id`, `team_id`, `distinct_id`, an identity-value
+ for every other column the Kafka table has, plus `surfacing_score`.
+- `distinct_id` MUST be the session's real distinct_id — `writable_session_replay_events`
+ shards on `sipHash64(distinct_id)`, so a wrong value would route the partial
+ row to a different shard than the real session rows and the AggregatingMergeTree
+ could never merge them. The eligible_sessions CTE surfaces it via `any(distinct_id)`.
+- `first/last_timestamp = min_first_timestamp + 1µs` so min/max/argMin on
+ the MV side keep the real session's values — using now() would shift
+ max_last_timestamp forward by however long the scorer takes.
+- `producer.flush(timeout=30s)` runs after the loop so the activity doesn't
+ ack `scored=N` to the workflow before librdkafka has actually delivered.
+
+Consumer side (no per-pipeline CH objects — we piggyback on ingestion):
+
+- `kafka_session_replay_events` (Kafka engine) — already consumes from this topic.
+- `session_replay_events_mv` aggregates with `GROUP BY session_id, team_id`
+ and writes the `max(surfacing_score)` into the existing session row in
+ `writable_session_replay_events`. Every identity-value column we sent merges
+ as a no-op into the existing aggregates (sum of 0, max of NULL, etc.).
+
+Identical pattern to the AI summarization writeback in
+`posthog/temporal/session_replay/session_summary/activities/video_based/a7d_tag_and_highlight_session.py`.
+
+### Two CH tables, one pipeline
+
+- **`session_replay_events`** is where the score lives now (`surfacing_score`,
+ `SimpleAggregateFunction(max, Nullable(Float32))`, write-once via the `IS NULL`
+ filter on the read side and `max` on merge so a real score never gets clobbered
+ by NULL). It sits alongside the existing AI-generated columns
+ (`ai_tags_fixed`, `ai_tags_freeform`, `ai_highlighted`) — same write pattern.
+- **`session_replay_features`** is where the model's input features live
+ (the table populated by the replay feature pipeline). The pipeline keys
+ on `(team_id, session_id)` with string `session_id`; the JOIN back to
+ `session_replay_events` is a direct String-to-String match (no UUID
+ byte-swap dance — that complexity disappeared when we moved off the
+ `raw_sessions_v3.session_id_v7` UInt128 column).
+
+The serving SELECT mirrors the training query verbatim: same
+`aggregated_sufficient_statistics` and `replay_features` CTE shape, same
+column names, same arithmetic — so any drift between training and serving
+shows up as a `validate_features` failure rather than silent score skew.
+
+### Feature schema sync (SQL ↔ FEATURE_RANGES ↔ booster)
+
+The serving SQL and `FEATURE_RANGES` together define the **feature universe**;
+they must stay identical (same columns, same order). The booster is the
+source of truth for **which** of those features the model scores, and may use
+a **subset** — a simpler model can run against the richer query without a
+retrain or serving change.
+
+| Artifact | Source of truth for | Relationship |
+| ----------------------------------------------- | ------------------------------ | ---------------------- |
+| `fetch_features_sql()` final SELECT aliases | What ClickHouse returns | == `FEATURE_RANGES` |
+| `FEATURE_RANGES` keys in `features.py` | Runtime dtype/range validation | == SQL aliases |
+| `booster.feature_names` in the S3-hosted `.ubj` | What XGBoost predicts on | ⊆ the SQL / ranges set |
+
+`feature_schema.py` enforces this:
+
+- `assert_sql_matches_feature_ranges()` — SQL aliases **equal** `FEATURE_RANGES`
+ keys (the universe is consistent).
+- `assert_ranges_cover(booster)` / `assert_booster_matches_sql(booster)` — every
+ booster feature is **in** the universe (subset). Extra universe columns the
+ booster ignores are fine; `feature_matrix` selects the booster's by name, so
+ serving column order is irrelevant to predictions.
+
+Enforced at:
+
+- **Worker boot**: `scorer.warmup()` fetches the booster from S3 and runs
+ `assert_serving_schema_parity()` — a booster needing a column the SQL doesn't
+ produce fails before accepting chunks.
+- **CI** (`test_sql_alignment.py`): SQL ↔ FEATURE_RANGES equality, plus
+ subset-booster parity (a proper-subset booster passes; one needing an
+ unknown column fails).
+
+To **extend** the universe: update `sql.py` SELECT + `FEATURE_RANGES` together,
+bump `MODEL_FEATURE_SCHEMA_VERSION`, rerun the alignment tests. A new booster
+that uses any subset of the universe deploys without further code changes —
+just upload the `.ubj` (see [Uploading a model to S3](#uploading-a-model-to-s3)).
+
+Sessions without replay features are dropped by the inner join and stay
+NULL in `session_replay_events`. They re-appear on subsequent ticks until
+they age out of the lookback window. That's deliberate — the model can't
+score them, and writing a sentinel would either need a separate column or
+break the write-once semantics. Keep the lookback tight so the wasted scan
+cost is bounded.
+
+### Why this shape
+
+- **Workflow stays tiny** — no per-session work in workflow code, payloads stay
+ far below the 2 MiB Temporal hard limit.
+- **Hash partitioning** by `cityHash64(session_id) % of_chunks` gives every
+ session exactly one bucket. Note this is a different key than the table's
+ `sipHash64(distinct_id)` sharding key — the chunk fan-out only needs balanced
+ buckets, not co-location with the data.
+- **Idempotent on retry** — each chunk re-queries with
+ `HAVING max(surfacing_score) IS NULL`, so a partial-failure retry
+ naturally skips already-scored sessions. No claim/lock table needed.
+- **No Redis, no S3** — every chunk is fetch-predict-write end-to-end inside
+ one activity. Add Redis only if/when fetch and predict need to live on
+ different worker pools (e.g., GPU vs CPU).
+- **No dedicated Kafka triplet** — score writeback piggybacks on the existing
+ replay ingestion topic + Kafka table + MV. We don't add a new Kafka topic,
+ a new consumer group, or a new MV — the score is just another column written
+ back via the same partial-row pattern as `ai_highlighted` and `is_deleted`.
+ At-least-once delivery is harmless because the score column is
+ `SimpleAggregateFunction(max, …)` and the pipeline only ever produces a
+ single score per session.
+
+## Throughput sizing
+
+200k sessions / 5 min = ~667/sec. With XGBoost predict on tabular features,
+the bottleneck is fetch + write, not score.
+
+| chunk_size | of_chunks | concurrent on 2 workers | per-chunk wall time | tick wall time |
+| ---------- | --------- | ----------------------- | ------------------- | -------------- |
+| 5,000 | 40 | 4 in flight | ~15s | ~150s |
+| **10,000** | **20** | **4 in flight** | **~25s** | **~125s** |
+| 20,000 | 10 | 4 in flight | ~45s | ~115s |
+
+Defaults in `constants.py` are `chunk_size=10_000`, `of_chunks=20`. Tweak
+`TARGET_SESSIONS_PER_TICK` and `DEFAULT_OF_CHUNKS` for capacity changes.
+
+## libomp thread budgeting
+
+XGBoost on Linux uses `libgomp`; on macOS it uses `libomp`. Both are OpenMP
+runtimes controlled by `OMP_NUM_THREADS`.
+
+The single most important worker config: **don't oversubscribe cores.**
+
+Recommended worker container env:
+
+```bash
+# Inside the worker pod, set OMP_NUM_THREADS to (CPU limit - 1) so libomp
+# doesn't contend with the asyncio reactor and Temporal SDK threads.
+OMP_NUM_THREADS=$(($(getconf _NPROCESSORS_ONLN) - 1))
+```
+
+Pair with **low Temporal concurrency** so each predict gets the whole CPU:
+
+```python
+Worker(
+ ...,
+ task_queue=settings.SURFACING_SCORING_SWEEP_TASK_QUEUE,
+ max_concurrent_activities=2, # not 32 — let libomp do the parallelism
+ max_concurrent_workflow_tasks=20,
+)
+```
+
+The other valid setup is the inverse — `OMP_NUM_THREADS=1` and
+`max_concurrent_activities=$(nproc)`. Pick one parallelism layer; the bug
+that gets you in production is leaving both at default and finding 32×N
+threads fighting for N cores.
+
+### Containers + cgroups gotcha
+
+`os.cpu_count()` returns the host's CPU count, not the pod's CPU limit. Set
+`OMP_NUM_THREADS` explicitly from the pod's allocated quota (or read
+`/sys/fs/cgroup/cpu.max`).
+
+## Model file
+
+S3 is the **single source of truth** — no bundled fallback, no local-file
+override. `SESSION_INTERESTINGNESS_MODEL_S3_URI` (`s3://bucket/key`) is
+required on every surfacing worker. Prod, staging, and local dev (against
+MinIO) all use the same code path: fetch once per pod, cache to a
+tempfile, roll pods to pick up new models.
+
+Unset → `ModelNotConfiguredError` at worker boot. Warm with
+`scorer.warmup()` so the S3 fetch isn't on the first chunk's path.
+
+`xgboost==3.2.0` is a top-level dependency (pulls `nvidia-nccl-cu12`
+~322 MB on Linux even in CPU mode) — deliberate trade-off for a single
+worker image.
+
+### Uploading a model to S3
+
+```bash
+./bin/python manage.py upload_surfacing_model ./surfacing_score_xgb_v1.ubj
+# → s3://<settings.OBJECT_STORAGE_BUCKET>/surfacing-scoring/surfacing_score_xgb_v1.ubj
+
+# Override bucket/key for versioned rollouts:
+./bin/python manage.py upload_surfacing_model ./surfacing_score_xgb_v2.ubj \
+ --bucket my-bucket --key surfacing-scoring/surfacing_score_xgb_v2.ubj
+```
+
+The command uses the same `posthog.storage.object_storage` client the
+worker reads with (works against prod S3, staging, and local MinIO) and
+validates the `.ubj` before upload (`--skip-validate` to bypass).
+
+Then on the worker pod, roll to pick up the new model:
+
+```bash
+SESSION_INTERESTINGNESS_MODEL_S3_URI=s3://<bucket>/surfacing-scoring/surfacing_score_xgb_v1.ubj
+```
+
+Plain `aws s3 cp` works too.
+
+## Updating features
+
+The trained XGBoost booster file is the **single source of truth** for which
+features the model takes. `feature_names` is embedded inside the `.ubj` file
+when training calls `xgb.DMatrix(..., feature_names=...)`, and serving reads
+it back via `scorer.get_feature_names()`. A retrained booster with a
+different feature set updates serving without a code change to `features.py`.
+
+What still needs to be kept in sync **outside** the booster file:
+
+1. `sql.fetch_features_sql` — the SELECT column list (plus the
+ `_AGGREGATED_STATS_FRAGMENT` and `_REPLAY_FEATURES_FRAGMENT` CTEs that
+ produce them) must produce a column named exactly the same as every
+ `feature_names` entry, in the same order. `test_sql_alignment.py`
+ asserts this at CI time; `validate_features` enforces it again at
+ runtime as a defense in depth.
+2. `features.FEATURE_RANGES` — runtime dtype + value-bounds contract.
+ xgboost does **not** carry value ranges in the model file, so this is
+ the runtime guard against "model trained on [0, 1] but the SQL started
+ returning 9999". `assert_ranges_cover` runs inside `_load_booster` at
+ warmup; any feature in the booster without a `FEATURE_RANGES` entry
+ raises `MissingFeatureRangeError` before a single chunk is dispatched.
+ `test_sql_alignment.py` also asserts equality (not just superset) so
+ stale entries get flagged in CI too.
+
+Workflow when changing features:
+
+1. Update SQL (`_AGGREGATED_STATS_FRAGMENT`, `_REPLAY_FEATURES_FRAGMENT`,
+ final SELECT) + `FEATURE_RANGES` to match.
+2. Bump `features.MODEL_FEATURE_SCHEMA_VERSION`.
+3. `pytest .../test_sql_alignment.py` passes when SQL and FEATURE_RANGES agree.
+4. Retrain and upload the new `.ubj` (see [Uploading a model to
+ S3](#uploading-a-model-to-s3)); roll workers. `assert_serving_schema_parity`
+ fails boot loudly if the new booster's `feature_names` don't match.
+
+`validate_features` is a hard gate — any mismatch raises
+`FeatureValidationError`, marked `non_retryable=True` in the workflow so a
+schema bug fails fast rather than burning retries.
+
+## Schedule lifecycle
+
+Singleton, region-scoped (one Schedule per Temporal cluster). Use
+`schedule.a_upsert_schedule()` to register/update during deploy and
+`schedule.a_delete_schedule_if_exists()` to retire it.
+
+The schedule fires every 5 min with `ScheduleOverlapPolicy.SKIP` — if a tick
+is still running when the next is due, the new one is dropped (the next
+tick's CH `IS NULL` filter naturally picks up whatever the slow tick missed).
+
+## Open follow-ups
+
+These are deliberately out of scope for the initial PR:
+
+- **Extend the feature set.** The initial production booster covers the
+ 36 features the live `session_replay_features` DDL exposes today. To add
+ more (e.g. `*_path_visit_count`, `network_4xx_count`, `mutation_count`,
+ `unique_form_field_count`), land them in
+ `posthog/session_recordings/sql/session_replay_feature_sql.py` (CH
+ migration + Kafka MV) first, then retrain + upload + update
+ `sql.py`/`FEATURE_RANGES` (gated by `test_sql_alignment.py`).
+- **Integration test for `score_chunk_activity`.** Unit coverage exists for
+ `validate_features` and `scorer` (load + predict + thread safety + range
+ guards). The end-to-end activity flow against real CH is still untested;
+ start with a fixture-backed smoke test of `fetch_features_sql`.
+- **Backfill.** Existing `session_replay_events` rows have NULL scores, which
+ is fine for "score going forward". If we ever want to score historical
+ sessions, write a one-off Dagster job that walks
+ `cityHash64(session_id) % N` buckets and triggers the same
+ `score_chunk_activity` per bucket.
+- **Metrics.** Expose `total_scored`, `chunks_failed`, and the chunk-wall-time
+ histogram to whatever observability stack the `SURFACING_SCORING_SWEEP_TASK_QUEUE`
+ worker pool uses.
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/__init__.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/__init__.py
new file mode 100644
index 000000000000..e99cb0d2dc62
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/__init__.py
@@ -0,0 +1,13 @@
+"""Temporal pipeline that writes surfacing scores onto session_replay_events.
+
+See README.md in this directory for the architecture rationale.
+"""
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep.activities import (
+ list_chunks_activity,
+ score_chunk_activity,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.workflow import ScoreSessionsBatchWorkflow
+
+SURFACING_SCORING_SWEEP_WORKFLOWS = [ScoreSessionsBatchWorkflow]
+SURFACING_SCORING_SWEEP_ACTIVITIES = [list_chunks_activity, score_chunk_activity]
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py
new file mode 100644
index 000000000000..c993e8146014
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py
@@ -0,0 +1,313 @@
+"""Temporal activities for the session surfacing scoring pipeline.
+
+Two activities:
+ * `list_chunks_activity` — runs once per workflow tick to gauge backlog
+ and emit deterministic chunk specs. Cheap.
+ * `score_chunk_activity` — runs once per chunk; does fetch-features
+ (CH SELECT) → predict (XGBoost) → publish-scores (Kafka) end to end.
+ The work for each chunk is fully self-contained: no Redis, no S3, no
+ cross-activity state.
+
+Score writeback piggybacks on the existing `KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS`
+topic + `session_replay_events_mv` — same pattern as the AI-summary writeback
+in `posthog.temporal.session_replay.session_summary.activities.video_based.
+a7d_tag_and_highlight_session`. We send a partial-row Kafka message with
+identity values for every non-score column; the MV's `max(surfacing_score)`
+aggregation merges the score onto the real session row in the AggregatingMergeTree.
+
+Idempotency guarantees:
+ * Hash partitioning (`cityHash64(session_id) %% of_chunks = chunk_id`)
+ gives every session exactly one bucket.
+ * The CH SELECT filters `HAVING max(surfacing_score) IS NULL` —
+ sessions already scored in a previous attempt are skipped naturally.
+ * `surfacing_score` is `SimpleAggregateFunction(max, ...)` and the
+ Temporal pipeline only ever writes a single score per session, so even if
+ Kafka redelivers a message after a worker crash the merge is a no-op.
+ * Re-running a failed `score_chunk_activity` thus never double-scores
+ a session and never burns the same CPU twice on already-written rows.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from typing import Any, cast
+
+import numpy as np
+import pandas as pd
+import structlog
+from asgiref.sync import sync_to_async
+from temporalio import activity
+from temporalio.exceptions import ApplicationError
+
+from posthog.clickhouse.client import sync_execute
+from posthog.kafka_client.routing import get_producer
+from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS
+from posthog.models.event.util import format_clickhouse_timestamp
+from posthog.temporal.session_replay.surfacing_scoring_sweep import sql as surfacing_scoring_sweep_sql
+from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import (
+ CH_FEATURE_QUERY_MAX_MEMORY_BYTES,
+ CH_FEATURE_QUERY_TIMEOUT_S,
+ DEFAULT_OF_CHUNKS,
+ KAFKA_PRODUCE_FLUSH_TIMEOUT_S,
+ SCORE_LOOKBACK_DAYS,
+ TARGET_CHUNK_SIZE,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import (
+ MODEL_FEATURE_SCHEMA_VERSION,
+ FeatureValidationError,
+ out_of_contract_row_mask,
+ validate_features,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.scorer import get_feature_names, predict
+from posthog.temporal.session_replay.surfacing_scoring_sweep.types import (
+ ChunkResult,
+ ChunkSpec,
+ ListChunksResult,
+ ScoreSessionsBatchInputs,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+# --------------------------------------------------------------------------- #
+# list_chunks_activity #
+# --------------------------------------------------------------------------- #
+
+
+def _count_unscored_in_one_bucket(lookback_days: int, of_chunks: int) -> int:
+ rows = cast(
+ list[tuple[int]],
+ sync_execute(
+ surfacing_scoring_sweep_sql.count_unscored_sql(),
+ {"lookback_days": lookback_days, "of_chunks": of_chunks},
+ settings={
+ "max_execution_time": CH_FEATURE_QUERY_TIMEOUT_S,
+ "max_memory_usage": CH_FEATURE_QUERY_MAX_MEMORY_BYTES,
+ },
+ ),
+ )
+ return int(rows[0][0]) if rows else 0
+
+
+async def list_chunks_activity(_inputs: ScoreSessionsBatchInputs) -> ListChunksResult:
+ lookback_days = SCORE_LOOKBACK_DAYS
+ of_chunks = DEFAULT_OF_CHUNKS
+ chunk_size = TARGET_CHUNK_SIZE
+
+ sampled = await sync_to_async(_count_unscored_in_one_bucket, thread_sensitive=False)(lookback_days, of_chunks)
+ estimated_total = sampled * of_chunks
+
+ chunks = [
+ ChunkSpec(
+ chunk_id=i,
+ of_chunks=of_chunks,
+ chunk_size=chunk_size,
+ lookback_days=lookback_days,
+ )
+ for i in range(of_chunks)
+ ]
+ logger.info(
+ "surfacing_scoring_sweep.list_chunks.dispatched",
+ of_chunks=of_chunks,
+ chunk_size=chunk_size,
+ estimated_unscored_sessions=estimated_total,
+ )
+ return ListChunksResult(chunks=chunks, estimated_unscored_sessions=estimated_total)
+
+
+# --------------------------------------------------------------------------- #
+# score_chunk_activity #
+# --------------------------------------------------------------------------- #
+
+
+def _fetch_features_dataframe(spec: ChunkSpec) -> pd.DataFrame:
+ """Run the feature SELECT and return a pandas DataFrame."""
+ result = cast(
+ tuple[list[tuple], list[tuple[str, str]]],
+ sync_execute(
+ surfacing_scoring_sweep_sql.fetch_features_sql(),
+ {
+ "lookback_days": spec.lookback_days,
+ "of_chunks": spec.of_chunks,
+ "chunk_id": spec.chunk_id,
+ "chunk_size": spec.chunk_size,
+ },
+ settings={
+ "max_execution_time": CH_FEATURE_QUERY_TIMEOUT_S,
+ "max_memory_usage": CH_FEATURE_QUERY_MAX_MEMORY_BYTES,
+ },
+ with_column_types=True,
+ ),
+ )
+ rows, column_metadata = result
+ columns = [name for name, _type in column_metadata]
+ return pd.DataFrame(rows, columns=pd.Index(columns))
+
+
+def _build_partial_row(
+ *,
+ team_id: int,
+ session_id: str,
+ distinct_id: str,
+ min_first_timestamp: datetime,
+ score: float,
+) -> dict[str, Any]:
+ """Identity-value Kafka payload that merges cleanly into session_replay_events.
+
+ Mirrors `tag_and_highlight_session_activity._produce_to_kafka`:
+
+ * Timestamps use `min_first_timestamp + 1µs` so min(first_timestamp),
+ argMin(first_url, first_timestamp), and max(last_timestamp) all keep
+ the real session's values — never the partial row's. Using now() would
+ shift max_last_timestamp forward by however long the scorer takes.
+ * `block_url=None` is critical: groupArray(block_url) drops nulls. An empty
+ string would pollute `block_urls` and break the length-match check in
+ listBlocks downstream.
+ * `first_url=None`, `snapshot_*=None`: argMin* drops nulls, so the real
+ session's first_url survives even though we wrote with an "earlier"
+ timestamp.
+ * `distinct_id` MUST be the session's real distinct_id — it's the
+ Distributed sharding key (`sipHash64(distinct_id)`). A wrong value would
+ route this partial row to a different shard than the real session rows,
+ forcing every read on this session into a cross-shard merge.
+ """
+ ts = min_first_timestamp + timedelta(microseconds=1)
+ if ts.tzinfo is None:
+ ts = ts.replace(tzinfo=UTC)
+ partial_ts = format_clickhouse_timestamp(ts)
+ return {
+ "session_id": session_id,
+ "team_id": team_id,
+ "distinct_id": distinct_id,
+ "first_timestamp": partial_ts,
+ "last_timestamp": partial_ts,
+ "block_url": None,
+ "first_url": None,
+ "urls": [],
+ "click_count": 0,
+ "keypress_count": 0,
+ "mouse_activity_count": 0,
+ "active_milliseconds": 0,
+ "console_log_count": 0,
+ "console_warn_count": 0,
+ "console_error_count": 0,
+ "size": 0,
+ "event_count": 0,
+ "message_count": 0,
+ "snapshot_source": None,
+ "snapshot_library": None,
+ "retention_period_days": None,
+ "is_deleted": 0,
+ "ai_tags_fixed": [],
+ "ai_tags_freeform": [],
+ "ai_highlighted": 0,
+ "surfacing_score": score,
+ }
+
+
+def _publish_scores(df: pd.DataFrame, scores: np.ndarray) -> int:
+ """Produce one Kafka message per scored session and flush before returning.
+
+ Rides the same `session_replay_events_mv` as ingestion, whose
+ `max(surfacing_score)` merges the score onto the real session row.
+
+ Per-row produce keeps retries simple: a mid-loop crash just re-runs the
+ chunk, and already-produced sessions are either skipped next tick (once CH
+ has consumed, via `HAVING max(surfacing_score) IS NULL`) or harmlessly
+ re-merged by the `max`-typed column.
+
+ Returns the row count handed off to the producer (after flush), which
+ `score_chunk_activity` reports as `ChunkResult.scored`.
+ """
+ if df.empty:
+ return 0
+
+ producer = get_producer(topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS)
+ team_ids = df["team_id"].to_numpy()
+ session_ids = df["session_id"].to_numpy()
+ distinct_ids = df["distinct_id"].to_numpy()
+ min_first_timestamps = df["min_first_timestamp"].to_numpy()
+ rows_published = 0
+ for team_id, session_id, distinct_id, min_first_timestamp, score in zip(
+ team_ids, session_ids, distinct_ids, min_first_timestamps, scores, strict=True
+ ):
+ producer.produce(
+ topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS,
+ data=_build_partial_row(
+ team_id=int(team_id),
+ session_id=str(session_id),
+ distinct_id=str(distinct_id),
+ min_first_timestamp=pd.Timestamp(min_first_timestamp).to_pydatetime(),
+ score=float(score),
+ ),
+ )
+ rows_published += 1
+
+ # Don't ack until librdkafka has flushed.
+ remaining = producer.flush(timeout=KAFKA_PRODUCE_FLUSH_TIMEOUT_S)
+ if remaining > 0:
+ raise RuntimeError(
+ f"{remaining} surfacing_score message(s) not delivered within "
+ f"{KAFKA_PRODUCE_FLUSH_TIMEOUT_S}s — chunk will retry"
+ )
+
+ return rows_published
+
+
+async def score_chunk_activity(spec: ChunkSpec) -> ChunkResult:
+ """Score one hash-partitioned chunk of unscored sessions, end to end."""
+ activity.heartbeat({"phase": "fetch", "chunk_id": spec.chunk_id})
+ df = await sync_to_async(_fetch_features_dataframe, thread_sensitive=False)(spec)
+
+ if df.empty:
+ return ChunkResult(chunk_id=spec.chunk_id, scored=0)
+
+ feature_names = await sync_to_async(get_feature_names, thread_sensitive=False)()
+
+ activity.logger.info(
+ "surfacing_scoring_sweep.fetched",
+ chunk_id=spec.chunk_id,
+ rows=len(df),
+ feature_schema_version=MODEL_FEATURE_SCHEMA_VERSION,
+ feature_count=len(feature_names),
+ )
+
+ try:
+ validate_features(df, feature_names=feature_names)
+ except FeatureValidationError as e:
+ raise ApplicationError(
+ f"feature validation failed for chunk {spec.chunk_id}: {e}",
+ type="FeatureValidationError",
+ non_retryable=True,
+ ) from e
+
+ # Value-level violations are data-driven (replay payloads are
+ # client-controlled), so drop just the offending sessions — failing the
+ # chunk would deterministically re-fail this hash bucket every tick.
+ bad_rows = out_of_contract_row_mask(df, feature_names=feature_names)
+ if bad_rows.any():
+ activity.logger.warning(
+ "surfacing_scoring_sweep.rows_out_of_contract",
+ chunk_id=spec.chunk_id,
+ dropped=int(bad_rows.sum()),
+ rows=len(df),
+ )
+ df = df.loc[~bad_rows]
+ if df.empty:
+ return ChunkResult(chunk_id=spec.chunk_id, scored=0)
+
+ activity.heartbeat({"phase": "predict", "chunk_id": spec.chunk_id, "rows": len(df)})
+ scores = await sync_to_async(predict, thread_sensitive=False)(df)
+
+ activity.heartbeat({"phase": "publish", "chunk_id": spec.chunk_id, "rows": len(df)})
+ published = await sync_to_async(_publish_scores, thread_sensitive=False)(df, scores)
+
+ activity.logger.info(
+ "surfacing_scoring_sweep.chunk_done",
+ chunk_id=spec.chunk_id,
+ scored=published,
+ feature_count=len(feature_names),
+ )
+ return ChunkResult(chunk_id=spec.chunk_id, scored=published)
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/constants.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/constants.py
new file mode 100644
index 000000000000..52cdab7c5860
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/constants.py
@@ -0,0 +1,63 @@
+"""Static config for the session surfacing scoring pipeline.
+
+The pipeline runs on a fixed Schedule (every SCHEDULE_INTERVAL) and per tick
+scores up to TARGET_SESSIONS_PER_TICK unscored sessions, sharded into
+DEFAULT_OF_CHUNKS deterministic hash buckets.
+"""
+
+from datetime import timedelta
+
+WORKFLOW_NAME = "score-sessions-batch"
+SCHEDULE_ID = "surfacing-scoring-sweep-batch"
+SCHEDULE_TYPE = "surfacing-scoring-sweep"
+
+MODEL_S3_KEY = "surfacing-scoring/surfacing_score_xgb_v1.ubj"
+
+# Pipeline cadence. Must align with the consumer's freshness expectation —
+# 5m gives the model 5 minutes of headroom between fetch and re-tick, which
+# is comfortable for chunks of TARGET_CHUNK_SIZE on a single libomp worker.
+SCHEDULE_INTERVAL = timedelta(minutes=5)
+
+# Per-tick budget. The pipeline will pick up to this many unscored sessions per
+# tick across all chunks. Sized so the schedule keeps up with steady-state
+# session creation; transient backlogs drain across consecutive ticks.
+TARGET_SESSIONS_PER_TICK = 200_000
+
+# Deterministic hash partitioning over `cityHash64(session_id) % DEFAULT_OF_CHUNKS`.
+# 20 buckets × ~10k sessions = TARGET_SESSIONS_PER_TICK, matched to a 5min budget.
+# Skew is bounded by hash uniformity (~10% per-bucket variance is normal).
+DEFAULT_OF_CHUNKS = 20
+TARGET_CHUNK_SIZE = TARGET_SESSIONS_PER_TICK // DEFAULT_OF_CHUNKS
+
+# Window for "score eligible" rows. Older sessions are intentionally left
+# unscored — if a session hasn't been scored within this window its features
+# are no longer useful for downstream summarization.
+SCORE_LOOKBACK_DAYS = 7
+
+# ClickHouse query budget. Enforced server-side via `max_execution_time` so a
+# runaway scan can't eat the whole activity timeout.
+CH_FEATURE_QUERY_TIMEOUT_S = 60
+
+# Server-side memory ceiling for the sweep queries. A background job must
+# never compete with interactive queries for cluster memory — better to fail
+# the chunk (it retries next tick) than to OOM a shard.
+CH_FEATURE_QUERY_MAX_MEMORY_BYTES = 10 * 1024 * 1024 * 1024 # 10 GiB
+
+# librdkafka flush budget after producing a chunk. Kafka writeback is async —
+# `produce()` enqueues, `flush()` blocks until every message has been ack'd by
+# the broker. 30s leaves headroom for a one-replica-down hiccup without busting
+# the activity timeout (4m).
+KAFKA_PRODUCE_FLUSH_TIMEOUT_S = 30
+
+# Activity timeouts. Sized for chunks of TARGET_CHUNK_SIZE on libomp-parallel
+# XGBoost predict (CH read ~10s + predict ~1s + Kafka produce+flush ~5s = ~20s
+# typical). The 4-minute ceiling absorbs CH replica failover / one slow shard /
+# a Kafka leader election.
+SCORE_CHUNK_ACTIVITY_TIMEOUT = timedelta(minutes=4)
+# > CH_FEATURE_QUERY_TIMEOUT_S (no heartbeat during the SELECT)
+SCORE_CHUNK_HEARTBEAT_TIMEOUT = timedelta(seconds=90)
+LIST_CHUNKS_ACTIVITY_TIMEOUT = timedelta(seconds=30)
+
+# Parent workflow has to outlive its longest in-flight chunk activity, but
+# must not stretch into the next 5-min tick.
+WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=4, seconds=30)
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/feature_schema.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/feature_schema.py
new file mode 100644
index 000000000000..7e8ca3a17433
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/feature_schema.py
@@ -0,0 +1,67 @@
+"""Parity checks for fetch_features_sql(), FEATURE_RANGES, and booster.feature_names."""
+
+from __future__ import annotations
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import FEATURE_RANGES, assert_ranges_cover
+from posthog.temporal.session_replay.surfacing_scoring_sweep.sql import feature_columns_in_select, fetch_features_sql
+
+
+class FeatureSchemaDriftError(Exception):
+ """Serving artifacts disagree on the feature column set or order."""
+
+
+def get_sql_feature_names() -> tuple[str, ...]:
+ """Feature column aliases from fetch_features_sql() in SELECT order."""
+ names = feature_columns_in_select(fetch_features_sql())
+ if not names:
+ raise FeatureSchemaDriftError(
+ "Could not parse feature aliases from fetch_features_sql(). "
+ "The final SELECT must list `<rf>.<feature>` columns one per line."
+ )
+ return names
+
+
+def assert_sql_matches_feature_ranges() -> None:
+ """Hard-fail if SQL aliases diverge from FEATURE_RANGES keys."""
+ sql_names = get_sql_feature_names()
+ range_names = tuple(FEATURE_RANGES.keys())
+ if sql_names != range_names:
+ raise FeatureSchemaDriftError(
+ "fetch_features_sql() drifted from FEATURE_RANGES.\n"
+ f" SQL aliases ({len(sql_names)}): {list(sql_names)}\n"
+ f" FEATURE_RANGES ({len(range_names)}): {list(range_names)}\n"
+ f" In SQL not ranges: {sorted(set(sql_names) - set(range_names))}\n"
+ f" In ranges not SQL: {sorted(set(range_names) - set(sql_names))}\n"
+ "Update sql.py and features.py together, then bump MODEL_FEATURE_SCHEMA_VERSION."
+ )
+
+
+def assert_booster_matches_sql(booster_names: tuple[str, ...]) -> None:
+ """Hard-fail if the booster needs a feature the SQL doesn't produce.
+
+ The booster is the source of truth for *which* features the model scores;
+ the serving SQL must produce a superset of them (it may expose extra
+ columns the booster ignores — `feature_matrix` selects the booster's by
+ name). The only fatal drift is a booster feature the SQL never produces.
+ """
+ if not booster_names:
+ raise FeatureSchemaDriftError(
+ "Booster has no feature_names. Train with explicit feature_names= on xgb.DMatrix."
+ )
+ sql_names = get_sql_feature_names()
+ not_produced = [name for name in booster_names if name not in set(sql_names)]
+ if not_produced:
+ raise FeatureSchemaDriftError(
+ "Booster needs feature(s) fetch_features_sql() does not produce.\n"
+ f" SQL aliases ({len(sql_names)}): {list(sql_names)}\n"
+ f" Booster names ({len(booster_names)}): {list(booster_names)}\n"
+ f" In booster not SQL: {sorted(not_produced)}\n"
+ "Add these columns to fetch_features_sql() (and FEATURE_RANGES), or retrain."
+ )
+
+
+def assert_serving_schema_parity(booster_names: tuple[str, ...]) -> None:
+ """Run SQL ↔ FEATURE_RANGES ↔ booster parity checks."""
+ assert_sql_matches_feature_ranges()
+ assert_ranges_cover(booster_names)
+ assert_booster_matches_sql(booster_names)
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/features.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/features.py
new file mode 100644
index 000000000000..2ed284d98b81
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/features.py
@@ -0,0 +1,279 @@
+"""Runtime range contract + parity validation for the session surfacing model.
+
+The XGBoost booster is the single source of truth for *which* features the model
+takes (its `.ubj` embeds `feature_names`); the worker reads them via
+`scorer.get_feature_names()`, so a retrained booster updates serving with no code
+change here. What stays in this module:
+
+ * `FEATURE_RANGES`: per-feature dtype-kind + value bounds. xgboost carries no
+ runtime value bounds, so this guards against "trained on [0, 1] but the SQL
+ started returning 9999". Every booster feature must have an entry, else
+ warmup raises `MissingFeatureRangeError`.
+ * `validate_features(df, feature_names=...)`: hard gate before predict —
+ the booster's features must be present and well-typed. The serving SQL
+ may expose a superset (extra columns the booster ignores); only a
+ *missing* booster feature is a wiring bug, so it fails the whole chunk.
+ * `out_of_contract_row_mask(df, feature_names=...)`: per-row flag for
+ non-finite/out-of-range values. Replay payloads are client-controlled, so one
+ crafted session must not fail its whole hash bucket; callers drop flagged rows
+ and score the rest.
+
+Updating features: extend `FEATURE_RANGES` and `sql.fetch_features_sql`'s alias
+list together (they define the feature universe), bump
+`MODEL_FEATURE_SCHEMA_VERSION`. The booster may use a subset of that universe, so
+a simpler model deploys unchanged. Drift fails loudly: a booster feature with no
+range entry raises at warmup; a booster feature the SQL never produces raises
+`FeatureSchemaDriftError`. Extra SQL columns the booster ignores are fine.
+
+Dtype notes: rates/ratios/shares are CH `Float64`; zero denominators become NaN
+(XGBoost handles it; validation accepts NaN but not +/-inf). Pass-through counts
+(`viewport_resize_count`, `selection_copy_count`, `unique_form_fields`) come back
+as int, which pandas infers as int64 or float64 depending on NULLs; validation
+accepts both.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import dataclass
+
+import numpy as np
+import pandas as pd
+
+# Bump on every breaking feature-set change. Logged per chunk so distribution
+# shifts can be correlated with deploys.
+MODEL_FEATURE_SCHEMA_VERSION = 3
+
+# Columns that identify the row but are NOT model features. Stripped before
+# predict; re-attached for the INSERT.
+ID_COLUMNS: tuple[str, ...] = ("team_id", "session_id", "distinct_id", "min_first_timestamp")
+
+# Per-dtype-kind groupings used in `FEATURE_RANGES` below.
+# `'iuf'` accepts int / unsigned int / float — useful for pass-through counts
+# whose pandas dtype depends on whether NULLs are present in a given chunk.
+_NUMERIC = "iuf"
+_FLOAT = "f"
+
+
+@dataclass(frozen=True)
+class FeatureSpec:
+ """Allowed dtype family + value range for a single feature.
+
+ `dtype_kind` is one or more of numpy's dtype.kind tags concatenated
+ ('i' int, 'u' unsigned int, 'f' float, 'b' bool). A range of `None` on
+ either end disables that side of the bounds check.
+ """
+
+ dtype_kind: str
+ min_value: float | None = None
+ max_value: float | None = None
+
+
+# Per-feature contracts. Bounds aren't statistical — they're the universe
+# of values the model has ever been trained on. Anything outside is a wiring
+# bug (negative count, infinity from a bad division), not just a distribution
+# shift. Generous upper bounds are deliberate: the goal is to catch wiring
+# bugs without flagging legitimate outliers.
+#
+# Rates: 0+, no upper bound (1k events/sec is unusual but possible).
+# Ratios: 0..1 with a tiny epsilon for FP error.
+# Mouse mean coords: any float (mouse can be off-screen).
+# Counts: non-negative.
+_RATE = FeatureSpec(_FLOAT, 0.0, None)
+_RATIO = FeatureSpec(_FLOAT, 0.0, 1.0 + 1e-6)
+_NONNEG_FLOAT = FeatureSpec(_FLOAT, 0.0, None)
+_ANY_FLOAT = FeatureSpec(_FLOAT, None, None)
+_NONNEG_COUNT = FeatureSpec(_NUMERIC, 0, None)
+
+
+FEATURE_RANGES: dict[str, FeatureSpec] = {
+ "event_rate": _RATE,
+ "click_rate": _RATE,
+ "keypress_rate": _RATE,
+ "mouse_activity_rate": _RATE,
+ "rage_click_rate": _RATE,
+ "dead_click_rate": _RATE,
+ "quick_back_rate": _RATE,
+ "page_visit_rate": _RATE,
+ "text_selection_rate": _RATE,
+ "scroll_event_rate": _RATE,
+ "console_error_rate": _RATE,
+ "console_error_after_click_rate": _RATE,
+ "network_request_rate": _RATE,
+ "network_failed_request_rate": _RATE,
+ "mouse_mean_x": _ANY_FLOAT,
+ "mouse_mean_y": _ANY_FLOAT,
+ "mouse_stddev_x": _NONNEG_FLOAT,
+ "mouse_stddev_y": _NONNEG_FLOAT,
+ "mouse_distance_per_s": _NONNEG_FLOAT,
+ "mouse_direction_change_rate": _NONNEG_FLOAT,
+ "mouse_velocity_mean": _NONNEG_FLOAT,
+ "mouse_velocity_stddev": _NONNEG_FLOAT,
+ "scroll_magnitude_per_s": _NONNEG_FLOAT,
+ "scroll_magnitude_per_event": _NONNEG_FLOAT,
+ "scroll_direction_reversal_rate": _RATE,
+ "rapid_scroll_reversal_rate": _RATE,
+ "max_scroll_y": _NONNEG_FLOAT,
+ "inter_action_gap_mean_ms": _NONNEG_FLOAT,
+ "inter_action_gap_stddev_ms": _NONNEG_FLOAT,
+ "max_idle_gap_ms": _NONNEG_FLOAT,
+ "network_request_duration_mean_ms": _NONNEG_FLOAT,
+ "network_request_duration_stddev_ms": _NONNEG_FLOAT,
+ "network_failure_ratio": _RATIO,
+ "network_4xx_ratio": _RATIO,
+ "network_5xx_ratio": _RATIO,
+ "scroll_to_top_rate": _RATE,
+ "backspace_ratio": _RATIO,
+ "long_idle_gap_share": _RATIO,
+ "console_warn_rate": _RATE,
+ "mutation_rate": _RATE,
+ "viewport_resize_count": _NONNEG_COUNT,
+ "touch_event_rate": _RATE,
+ "selection_copy_count": _NONNEG_COUNT,
+ "login_path_visit_share": _RATIO,
+ "signup_path_visit_share": _RATIO,
+ "checkout_path_visit_share": _RATIO,
+ "cart_path_visit_share": _RATIO,
+ "billing_path_visit_share": _RATIO,
+ "settings_path_visit_share": _RATIO,
+ "account_path_visit_share": _RATIO,
+ "error_path_visit_share": _RATIO,
+ "not_found_path_visit_share": _RATIO,
+ "admin_path_visit_share": _RATIO,
+ "dashboard_path_visit_share": _RATIO,
+ "onboarding_path_visit_share": _RATIO,
+ "cancel_path_visit_share": _RATIO,
+ "refund_path_visit_share": _RATIO,
+ "unique_url_share": _RATIO,
+ "click_target_share": _RATIO,
+ "unique_form_fields": _NONNEG_COUNT,
+ "page_revisit_share": _RATIO,
+ # Raw counts the current production booster consumes alongside the share
+ # variants above (the SQL surfaces both). uniqCombinedMerge estimates and
+ # a (visits - unique) difference — all non-negative counts.
+ "unique_urls": _NONNEG_COUNT,
+ "unique_click_targets": _NONNEG_COUNT,
+ "page_revisit_count": _NONNEG_COUNT,
+}
+
+
+class FeatureValidationError(Exception):
+ """Raised when a chunk's feature DataFrame doesn't match the trained schema."""
+
+
+class MissingFeatureRangeError(Exception):
+ """Booster declares a feature_name with no FEATURE_RANGES entry."""
+
+
+def assert_ranges_cover(feature_names: Iterable[str]) -> None:
+ """Hard-fail at warmup if any booster feature lacks a runtime range contract.
+
+ Adding a new feature to the booster without adding a `FEATURE_RANGES` entry
+ is a programming error: the validator wouldn't know what to bounds-check
+ against, and bad CH output for the new column would slip through silently.
+ Catch it once at boot, before any chunk runs.
+ """
+ names = tuple(feature_names)
+ if not names:
+ raise MissingFeatureRangeError(
+ "Booster has no feature_names. Train with explicit feature_names "
+ "(pass `feature_names=` to xgb.DMatrix at training time) so serving can pin its schema."
+ )
+ missing = [n for n in names if n not in FEATURE_RANGES]
+ if missing:
+ raise MissingFeatureRangeError(
+ f"Booster declares {len(missing)} feature(s) without a FEATURE_RANGES entry: "
+ f"{missing}. Add a FEATURE_RANGES entry (dtype-kind + value range) for each "
+ "before deploying this model."
+ )
+
+
+def _check_columns(df: pd.DataFrame, feature_names: tuple[str, ...]) -> None:
+ """Hard-fail only if a booster feature is absent from the frame.
+
+ The serving SQL may expose a superset of columns — the booster is the
+ source of truth for which subset it scores, and `feature_matrix` selects
+ those columns by name (so the frame's column order and any extra,
+ non-booster columns are irrelevant to predictions). The wiring bug worth
+ failing the chunk for is a booster feature the SQL stopped producing.
+ """
+ expected = set(feature_names)
+ actual_features = {c for c in df.columns if c not in ID_COLUMNS}
+ missing = expected - actual_features
+ if missing:
+ raise FeatureValidationError(
+ f"Feature column set mismatch: missing={sorted(missing)}. "
+ f"The serving SQL must produce every booster feature. "
+ f"Expected: {sorted(expected)}. Got (non-id): {sorted(actual_features)}."
+ )
+
+
+def _check_dtype(name: str, series: pd.Series, allowed_kinds: str) -> None:
+ """Validate a column's dtype.kind matches one of `allowed_kinds`."""
+ kind = series.dtype.kind
+ if kind not in allowed_kinds:
+ raise FeatureValidationError(
+ f"Feature {name!r} has dtype {series.dtype} (kind={kind!r}); expected one of kinds {list(allowed_kinds)!r}."
+ )
+
+
+def validate_features(df: pd.DataFrame, *, feature_names: tuple[str, ...]) -> None:
+ """Hard-fail if `df` doesn't match the trained model's expected schema.
+
+ Column set/order and dtype mismatches can only come from the SQL drifting
+ away from the booster — never from row data — so they abort the chunk.
+ Value-level violations are data-driven; flag those per-row with
+ `out_of_contract_row_mask` instead.
+
+ `feature_names` must be the booster's `feature_names` (production callers
+ get this via `scorer.get_feature_names()`). Pure function; no global state.
+
+ Raises:
+ FeatureValidationError: any column or dtype mismatch.
+ """
+ if df.empty:
+ return
+
+ _check_columns(df, feature_names)
+ for name in feature_names:
+ series: pd.Series = df.loc[:, name]
+ spec = FEATURE_RANGES[name]
+ _check_dtype(name, series, spec.dtype_kind)
+
+
+def out_of_contract_row_mask(df: pd.DataFrame, *, feature_names: tuple[str, ...]) -> pd.Series:
+ """Boolean mask of rows whose feature values break the trained contract.
+
+ Flags +/-inf (a feature-engineering bug — division returning inf) and
+ values outside `FEATURE_RANGES` bounds. NaN passes — XGBoost handles it
+ natively, and our SQL deliberately produces NULL (→ NaN) when
+ denominators are zero.
+
+ Replay events are client-controlled, so a single crafted session can
+ produce an out-of-range derived feature. Flagging per-row lets callers
+ drop just the offending sessions instead of failing the whole chunk
+ (which would deterministically re-fail the same hash bucket every tick
+ until the bad session ages past the lookback window).
+
+ O(rows × features). On a 10k-row chunk × 61 features this is single-digit ms.
+ """
+ mask = pd.Series(False, index=df.index)
+ for name in feature_names:
+ series: pd.Series = df.loc[:, name]
+ spec = FEATURE_RANGES[name]
+ if series.dtype.kind == "f":
+ arr = series.to_numpy()
+ mask |= ~(np.isfinite(arr) | np.isnan(arr))
+ if spec.min_value is not None:
+ mask |= series.lt(spec.min_value).fillna(False)
+ if spec.max_value is not None:
+ mask |= series.gt(spec.max_value).fillna(False)
+ return mask
+
+
+def feature_matrix(df: pd.DataFrame, *, feature_names: tuple[str, ...]) -> pd.DataFrame:
+ """Strip ID columns; return a DataFrame with feature columns in trained order.
+
+ Preserves row order so callers can re-attach scores positionally.
+ """
+ return df.loc[:, list(feature_names)]
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/schedule.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/schedule.py
new file mode 100644
index 000000000000..aaf549e3dce5
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/schedule.py
@@ -0,0 +1,101 @@
+"""Singleton Schedule lifecycle for the session scoring tick.
+
+This is intentionally a single global Schedule, not per-team — the underlying
+work is regional (one CH cluster per region) and the chunk fan-out is sized
+for total per-region throughput. Use `a_upsert_schedule()` once per region
+during deploy to register the Schedule against that region's Temporal
+cluster.
+
+The Schedule fires at SCHEDULE_INTERVAL with `ScheduleOverlapPolicy.SKIP`:
+if a tick is still running when the next tick is due, we skip the new tick
+rather than running two scoring batches concurrently. Concurrent ticks on
+the same hash partition would still be safe (the `IS NULL` filter handles
+double-up), but skipping avoids burning duplicate CH read cost.
+"""
+
+from __future__ import annotations
+
+from django.conf import settings
+
+import structlog
+from temporalio import common
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleIntervalSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+)
+from temporalio.common import SearchAttributePair, TypedSearchAttributes
+
+from posthog.temporal.common.client import async_connect
+from posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_schedule_exists, a_update_schedule
+from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY
+from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import (
+ SCHEDULE_ID,
+ SCHEDULE_INTERVAL,
+ SCHEDULE_TYPE,
+ WORKFLOW_EXECUTION_TIMEOUT,
+ WORKFLOW_NAME,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.types import ScoreSessionsBatchInputs
+
+logger = structlog.get_logger(__name__)
+
+
+def _build_schedule() -> Schedule:
+ return Schedule(
+ action=ScheduleActionStartWorkflow(
+ WORKFLOW_NAME,
+ ScoreSessionsBatchInputs(),
+ id=WORKFLOW_NAME, # singleton workflow id; dedupes overlapping ticks
+ task_queue=settings.SURFACING_SCORING_SWEEP_TASK_QUEUE,
+ execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,
+ retry_policy=common.RetryPolicy(maximum_attempts=1),
+ ),
+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=SCHEDULE_INTERVAL)]),
+ policy=SchedulePolicy(
+ overlap=ScheduleOverlapPolicy.SKIP,
+ catchup_window=SCHEDULE_INTERVAL,
+ ),
+ )
+
+
+async def create_surfacing_scoring_sweep_schedule(client: Client) -> None:
+ """Create-or-update the scoring Schedule using a shared Temporal client.
+
+ Registered in `posthog/temporal/schedule.py`'s deploy-time `schedules` list,
+ so `manage.py schedule_temporal_workflows` upserts it on every deploy.
+ """
+ schedule = _build_schedule()
+ search_attributes = TypedSearchAttributes(
+ search_attributes=[SearchAttributePair(key=POSTHOG_SCHEDULE_TYPE_KEY, value=SCHEDULE_TYPE)]
+ )
+ if await a_schedule_exists(client, SCHEDULE_ID):
+ await a_update_schedule(client, SCHEDULE_ID, schedule, search_attributes=search_attributes)
+ logger.info("surfacing_scoring_sweep.schedule_updated", schedule_id=SCHEDULE_ID)
+ else:
+ await a_create_schedule(
+ client, SCHEDULE_ID, schedule, trigger_immediately=False, search_attributes=search_attributes
+ )
+ logger.info("surfacing_scoring_sweep.schedule_created", schedule_id=SCHEDULE_ID)
+
+
+async def a_upsert_schedule() -> None:
+ """Create-or-update the scoring Schedule. Safe to call repeatedly."""
+ client = await async_connect()
+ await create_surfacing_scoring_sweep_schedule(client)
+
+
+async def a_delete_schedule_if_exists() -> None:
+ """Idempotent teardown — used when retiring the pipeline in a region."""
+ client = await async_connect()
+ if not await a_schedule_exists(client, SCHEDULE_ID):
+ return
+ try:
+ await a_delete_schedule(client, SCHEDULE_ID)
+ logger.info("surfacing_scoring_sweep.schedule_deleted", schedule_id=SCHEDULE_ID)
+ except Exception as e:
+ logger.warning("surfacing_scoring_sweep.delete_schedule_failed", error=str(e))
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/scorer.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/scorer.py
new file mode 100644
index 000000000000..2d3355451037
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/scorer.py
@@ -0,0 +1,176 @@
+"""XGBoost booster lifecycle for the session surfacing scorer.
+
+The booster is loaded **once per worker process** and held as a module-level
+singleton. XGBoost predict releases the GIL and is parallelized internally
+by libomp; we want libomp to use the worker pod's full CPU budget on a
+single chunk at a time, not split it across many concurrent activities (see
+`README.md` for the OMP_NUM_THREADS guidance).
+
+S3 is the single source of truth for the model (no bundled fallback). On
+first load we fetch the booster, cache it in a tempfile, and run
+`assert_serving_schema_parity` — SQL, FEATURE_RANGES, and the booster
+cannot drift.
+"""
+
+from __future__ import annotations
+
+import os
+import tempfile
+import threading
+from urllib.parse import urlparse
+
+import numpy as np
+import pandas as pd
+import xgboost as xgb
+import structlog
+
+from posthog.storage import object_storage
+from posthog.temporal.session_replay.surfacing_scoring_sweep.feature_schema import assert_serving_schema_parity
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import feature_matrix
+
+logger = structlog.get_logger(__name__)
+
+
+_MODEL_S3_URI_ENV_VAR = "SESSION_INTERESTINGNESS_MODEL_S3_URI"
+
+_BOOSTER: xgb.Booster | None = None
+# Cached tuple of `_BOOSTER.feature_names` to avoid the C++ → Python attribute
+# lookup on the predict hot path. Set in lockstep with `_BOOSTER`; reset to
+# None whenever `_BOOSTER` is reset (test fixtures clear both).
+_FEATURE_NAMES: tuple[str, ...] | None = None
+_S3_CACHED_PATH: str | None = None
+_BOOSTER_LOCK = threading.Lock()
+
+
+class ModelNotConfiguredError(RuntimeError):
+ """`SESSION_INTERESTINGNESS_MODEL_S3_URI` is not set."""
+
+
+def _fetch_from_s3(uri: str) -> str:
+ parsed = urlparse(uri)
+ if parsed.scheme != "s3" or not parsed.netloc or not parsed.path.lstrip("/"):
+ raise ValueError(f"{_MODEL_S3_URI_ENV_VAR} must be 's3://bucket/key', got {uri!r}")
+ bucket, key = parsed.netloc, parsed.path.lstrip("/")
+ payload = object_storage.read_bytes(key, bucket=bucket)
+ if payload is None:
+ raise FileNotFoundError(f"{uri} returned no body")
+ # delete=False: xgb.Booster.load_model reopens the path itself.
+ with tempfile.NamedTemporaryFile(suffix=".ubj", delete=False) as fh:
+ fh.write(payload)
+ return fh.name
+
+
+def _model_path() -> str:
+ global _S3_CACHED_PATH
+ s3_uri = os.environ.get(_MODEL_S3_URI_ENV_VAR)
+ if not s3_uri:
+ raise ModelNotConfiguredError(
+ f"Set {_MODEL_S3_URI_ENV_VAR}=s3://bucket/key. "
+ "See surfacing_scoring_sweep/README.md → 'Uploading a model to S3'."
+ )
+ if _S3_CACHED_PATH is None:
+ _S3_CACHED_PATH = _fetch_from_s3(s3_uri)
+ logger.info("surfacing_scoring_sweep.model_fetched_from_s3", uri=s3_uri, path=_S3_CACHED_PATH)
+ return _S3_CACHED_PATH
+
+
+def _load_booster() -> xgb.Booster:
+ """Cache + return the booster; thread-safe under high `max_concurrent_activities`.
+
+ Held under a lock only on first load. Subsequent calls hit the fast path
+ (one global-not-None check), so the lock isn't on the per-predict path.
+
+ On first load: runs assert_serving_schema_parity and caches feature_names.
+ """
+ global _BOOSTER, _FEATURE_NAMES
+ cached_booster = _BOOSTER
+ if cached_booster is not None:
+ return cached_booster
+
+ with _BOOSTER_LOCK:
+ cached_booster = _BOOSTER
+ if cached_booster is not None:
+ return cached_booster
+
+ path = _model_path()
+ loaded_booster = xgb.Booster()
+ loaded_booster.load_model(path)
+
+ names: tuple[str, ...] = tuple(loaded_booster.feature_names or ())
+ assert_serving_schema_parity(names)
+
+ logger.info(
+ "surfacing_scoring_sweep.model_loaded",
+ path=path,
+ num_features=len(names),
+ feature_names=list(names),
+ )
+ _BOOSTER = loaded_booster
+ _FEATURE_NAMES = names
+ return loaded_booster
+
+
+def warmup() -> None:
+ """Eagerly load the booster on worker startup.
+
+ Call from the worker bootstrap so the first chunk doesn't pay the S3
+ fetch latency. Also surfaces `ModelNotConfiguredError` /
+ `FeatureSchemaDriftError` / `MissingFeatureRangeError` at boot rather
+ than on the first chunk.
+ """
+ _load_booster()
+
+
+def get_feature_names() -> tuple[str, ...]:
+ """Return the booster's `feature_names` tuple — the serving feature schema.
+
+ Triggers a load if the booster hasn't been loaded yet (idempotent).
+ This is what activities call to drive `validate_features` and to log the
+ feature count, instead of importing a hard-coded constant from
+ `features.py`. Booster file = single source of truth for which features
+ the model takes.
+ """
+ cached_names = _FEATURE_NAMES
+ if cached_names is not None:
+ return cached_names
+ _load_booster()
+ cached_names = _FEATURE_NAMES
+ if cached_names is None:
+ raise RuntimeError("Booster loaded but feature names cache is empty")
+ return cached_names
+
+
+class ScoreRangeError(Exception):
+ """Booster returned scores outside [0, 1] — model is likely misconfigured."""
+
+
+def predict(df: pd.DataFrame) -> np.ndarray:
+ """Score a chunk's feature DataFrame and return a 1-D float32 array in [0, 1].
+
+ `df` must already have passed `validate_features` — predict is the hot
+ path and skips re-validation. Returned array is positionally aligned
+ with `df.index`.
+ """
+ booster = _load_booster()
+ feature_names = get_feature_names()
+
+ # Empty input — short-circuit before DMatrix, which doesn't accept zero-row
+ # frames whose columns have `object` dtype (the pandas default for empties).
+ if df.empty:
+ return np.empty(0, dtype=np.float32)
+
+ features = feature_matrix(df, feature_names=feature_names)
+ dmat = xgb.DMatrix(features, feature_names=list(feature_names))
+ raw = booster.predict(dmat)
+
+ scores = np.asarray(raw, dtype=np.float32).reshape(-1)
+ # Scores below 0 or above 1 indicate a model mismatch (e.g. trained as
+ # regression when it should be probability) — easier to debug here than
+ # downstream in CH.
+ if scores.size and (scores.min() < 0.0 or scores.max() > 1.0):
+ raise ScoreRangeError(
+ f"Booster returned scores outside [0, 1]: min={scores.min()}, max={scores.max()}. "
+ "Model is likely not configured for probability output (objective should be "
+ "binary:logistic / reg:logistic, or the booster needs an inverse_link wrapper)."
+ )
+ return scores
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/sql.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/sql.py
new file mode 100644
index 000000000000..46d0f7a8bd5c
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/sql.py
@@ -0,0 +1,387 @@
+"""ClickHouse statements for the session surfacing scoring pipeline.
+
+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`.
+ 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
+ (+1µs), or the AggregatingMergeTree can't merge the score onto the
+ existing session row.
+ 2. `aggregated_sufficient_statistics`: raw aggregates from
+ `session_replay_features`, filtered via `(team_id, session_id) GLOBAL IN`
+ (each shard scans only its local rows) with the same lookback as training.
+ 3. `replay_features`: derives the trained rates/ratios; carries `team_id`
+ so the final join shares a primary-key prefix and can't cross tenants.
+ 4. Final SELECT: inner-joins on `(team_id, session_id)`; sessions without
+ features stay NULL and re-appear next tick until they age out of lookback.
+
+CTE evaluation note: ClickHouse inlines `WITH ... AS` as a subquery, so
+`eligible_sessions` is evaluated twice (GLOBAL IN, then final FROM). The
+`ORDER BY session_id` before the LIMIT keeps the two evaluations consistent;
+without it the inner join silently drops the mismatch.
+
+Score writeback reuses the replay-ingestion Kafka topic (one JSONEachRow
+message per session), the same pattern as the AI-summary writeback: the MV
+does a partial-column insert and the AggregatingMergeTree merges
+`max(surfacing_score)` onto the existing row.
+
+Feature alignment contract: the final SELECT alias list must match the
+booster's `feature_names` exactly (set + order). `feature_columns_in_select`
+extracts it so `test_sql_alignment.py` asserts parity at CI and worker boot
+re-asserts against the S3 booster. Drift silently mis-scores sessions.
+"""
+
+import re
+
+# Distributed table names — hardcoded because there are no shared Python
+# helpers in the codebase that re-export them. Source of truth lives in
+# `posthog/session_recordings/sql/session_replay_event_sql.py` and
+# `posthog/session_recordings/sql/session_replay_feature_sql.py`.
+SESSION_REPLAY_EVENTS_TABLE = "session_replay_events"
+SESSION_REPLAY_FEATURES_TABLE = "session_replay_features"
+
+
+# --------------------------------------------------------------------------- #
+# Aggregate fragment over `session_replay_features`. #
+# Identical column-by-column to the training query's CTE. #
+# --------------------------------------------------------------------------- #
+_AGGREGATED_STATS_FRAGMENT = """
+SELECT
+ f.team_id,
+ f.session_id,
+ dateDiff('second', min(f.min_first_timestamp), max(f.max_last_timestamp)) AS session_duration_s,
+ sum(f.event_count) AS event_count,
+ sum(f.click_count) AS click_count,
+ sum(f.keypress_count) AS keypress_count,
+ sum(f.mouse_activity_count) AS mouse_activity_count,
+ sum(f.rage_click_count) AS rage_click_count,
+ sum(f.dead_click_count) AS dead_click_count,
+ sum(f.quick_back_count) AS quick_back_count,
+ sum(f.page_visit_count) AS page_visit_count,
+ sum(f.text_selection_count) AS text_selection_count,
+ sum(f.scroll_event_count) AS scroll_event_count,
+ sum(f.console_error_count) AS console_error_count,
+ sum(f.console_error_after_click_count) AS console_error_after_click_count,
+ sum(f.network_request_count) AS network_request_count,
+ sum(f.network_failed_request_count) AS network_failed_request_count,
+ sum(f.mouse_position_count) AS mouse_position_count,
+ sum(f.mouse_sum_x) AS mouse_sum_x,
+ sum(f.mouse_sum_x_squared) AS mouse_sum_x_squared,
+ sum(f.mouse_sum_y) AS mouse_sum_y,
+ sum(f.mouse_sum_y_squared) AS mouse_sum_y_squared,
+ sum(f.mouse_distance_traveled) AS mouse_distance_traveled,
+ sum(f.mouse_direction_change_count) AS mouse_direction_change_count,
+ sum(f.mouse_velocity_sum) AS mouse_velocity_sum,
+ sum(f.mouse_velocity_sum_of_squares) AS mouse_velocity_sum_of_squares,
+ sum(f.mouse_velocity_count) AS mouse_velocity_count,
+ sum(f.total_scroll_magnitude) AS total_scroll_magnitude,
+ sum(f.scroll_direction_reversal_count) AS scroll_direction_reversal_count,
+ sum(f.rapid_scroll_reversal_count) AS rapid_scroll_reversal_count,
+ max(f.max_scroll_y) AS max_scroll_y,
+ sum(f.inter_action_gap_count) AS inter_action_gap_count,
+ sum(f.inter_action_gap_sum_ms) AS inter_action_gap_sum_ms,
+ sum(f.inter_action_gap_sum_of_squares_ms) AS inter_action_gap_sum_of_squares_ms,
+ max(f.max_idle_gap_ms) AS max_idle_gap_ms,
+ sum(f.network_request_duration_sum) AS network_request_duration_sum,
+ sum(f.network_request_duration_sum_of_squares) AS network_request_duration_sum_of_squares,
+ sum(f.network_request_duration_count) AS network_request_duration_count,
+ sum(f.scroll_to_top_count) AS scroll_to_top_count,
+ sum(f.backspace_count) AS backspace_count,
+ sum(f.long_idle_gap_count) AS long_idle_gap_count,
+ sum(f.console_warn_count) AS console_warn_count,
+ sum(f.network_4xx_count) AS network_4xx_count,
+ sum(f.network_5xx_count) AS network_5xx_count,
+ sum(f.mutation_count) AS mutation_count,
+ sum(f.viewport_resize_count) AS viewport_resize_count,
+ sum(f.touch_event_count) AS touch_event_count,
+ sum(f.selection_copy_count) AS selection_copy_count,
+ sum(f.login_path_visit_count) AS login_path_visit_count,
+ sum(f.signup_path_visit_count) AS signup_path_visit_count,
+ sum(f.checkout_path_visit_count) AS checkout_path_visit_count,
+ sum(f.cart_path_visit_count) AS cart_path_visit_count,
+ sum(f.billing_path_visit_count) AS billing_path_visit_count,
+ sum(f.settings_path_visit_count) AS settings_path_visit_count,
+ sum(f.account_path_visit_count) AS account_path_visit_count,
+ sum(f.error_path_visit_count) AS error_path_visit_count,
+ sum(f.not_found_path_visit_count) AS not_found_path_visit_count,
+ sum(f.admin_path_visit_count) AS admin_path_visit_count,
+ sum(f.dashboard_path_visit_count) AS dashboard_path_visit_count,
+ sum(f.onboarding_path_visit_count) AS onboarding_path_visit_count,
+ sum(f.cancel_path_visit_count) AS cancel_path_visit_count,
+ sum(f.refund_path_visit_count) AS refund_path_visit_count,
+ uniqCombinedMerge(12)(f.unique_url_count) AS unique_urls,
+ uniqCombinedMerge(12)(f.unique_click_target_count) AS unique_click_targets,
+ uniqCombinedMerge(12)(f.unique_form_field_count) AS unique_form_fields
+FROM {features_table} AS f
+WHERE (f.team_id, f.session_id) GLOBAL IN (SELECT team_id, session_id FROM eligible_sessions)
+ AND f.min_first_timestamp >= now() - toIntervalDay(%(lookback_days)s)
+GROUP BY f.team_id, f.session_id
+""".strip()
+
+
+# --------------------------------------------------------------------------- #
+# Derived feature fragment over the aggregated stats CTE. #
+# Identical column-by-column to the training query's `replay_features` CTE. #
+# --------------------------------------------------------------------------- #
+_REPLAY_FEATURES_FRAGMENT = """
+SELECT
+ f.team_id,
+ f.session_id,
+ f.event_count / nullIf(f.session_duration_s, 0) AS event_rate,
+ f.click_count / nullIf(f.session_duration_s, 0) AS click_rate,
+ f.keypress_count / nullIf(f.session_duration_s, 0) AS keypress_rate,
+ f.mouse_activity_count / nullIf(f.session_duration_s, 0) AS mouse_activity_rate,
+ f.rage_click_count / nullIf(f.session_duration_s, 0) AS rage_click_rate,
+ f.dead_click_count / nullIf(f.session_duration_s, 0) AS dead_click_rate,
+ f.quick_back_count / nullIf(f.session_duration_s, 0) AS quick_back_rate,
+ f.page_visit_count / nullIf(f.session_duration_s, 0) AS page_visit_rate,
+ f.text_selection_count / nullIf(f.session_duration_s, 0) AS text_selection_rate,
+ f.scroll_event_count / nullIf(f.session_duration_s, 0) AS scroll_event_rate,
+ f.console_error_count / nullIf(f.session_duration_s, 0) AS console_error_rate,
+ f.console_error_after_click_count / nullIf(f.session_duration_s, 0) AS console_error_after_click_rate,
+ f.network_request_count / nullIf(f.session_duration_s, 0) AS network_request_rate,
+ f.network_failed_request_count / nullIf(f.session_duration_s, 0) AS network_failed_request_rate,
+ f.mouse_sum_x / nullIf(f.mouse_position_count, 0) AS mouse_mean_x,
+ f.mouse_sum_y / nullIf(f.mouse_position_count, 0) AS mouse_mean_y,
+ sqrt(greatest(0, f.mouse_sum_x_squared / nullIf(f.mouse_position_count, 0)
+ - pow(f.mouse_sum_x / nullIf(f.mouse_position_count, 0), 2))) AS mouse_stddev_x,
+ sqrt(greatest(0, f.mouse_sum_y_squared / nullIf(f.mouse_position_count, 0)
+ - pow(f.mouse_sum_y / nullIf(f.mouse_position_count, 0), 2))) AS mouse_stddev_y,
+ f.mouse_distance_traveled / nullIf(f.session_duration_s, 0) AS mouse_distance_per_s,
+ f.mouse_direction_change_count / nullIf(f.mouse_distance_traveled, 0) AS mouse_direction_change_rate,
+ f.mouse_velocity_sum / nullIf(f.mouse_velocity_count, 0) AS mouse_velocity_mean,
+ sqrt(greatest(0, f.mouse_velocity_sum_of_squares / nullIf(f.mouse_velocity_count, 0)
+ - pow(f.mouse_velocity_sum / nullIf(f.mouse_velocity_count, 0), 2))) AS mouse_velocity_stddev,
+ f.total_scroll_magnitude / nullIf(f.session_duration_s, 0) AS scroll_magnitude_per_s,
+ f.total_scroll_magnitude / nullIf(f.scroll_event_count, 0) AS scroll_magnitude_per_event,
+ f.scroll_direction_reversal_count / nullIf(f.session_duration_s, 0) AS scroll_direction_reversal_rate,
+ f.rapid_scroll_reversal_count / nullIf(f.session_duration_s, 0) AS rapid_scroll_reversal_rate,
+ f.max_scroll_y,
+ f.inter_action_gap_sum_ms / nullIf(f.inter_action_gap_count, 0) AS inter_action_gap_mean_ms,
+ sqrt(greatest(0, f.inter_action_gap_sum_of_squares_ms / nullIf(f.inter_action_gap_count, 0)
+ - pow(f.inter_action_gap_sum_ms / nullIf(f.inter_action_gap_count, 0), 2))) AS inter_action_gap_stddev_ms,
+ f.max_idle_gap_ms,
+ f.network_request_duration_sum / nullIf(f.network_request_duration_count, 0) AS network_request_duration_mean_ms,
+ sqrt(greatest(0, f.network_request_duration_sum_of_squares / nullIf(f.network_request_duration_count, 0)
+ - pow(f.network_request_duration_sum / nullIf(f.network_request_duration_count, 0), 2))) AS network_request_duration_stddev_ms,
+ f.network_failed_request_count / nullIf(f.network_request_count, 0) AS network_failure_ratio,
+ f.network_4xx_count / nullIf(f.network_request_count, 0) AS network_4xx_ratio,
+ f.network_5xx_count / nullIf(f.network_request_count, 0) AS network_5xx_ratio,
+ f.scroll_to_top_count / nullIf(f.session_duration_s, 0) AS scroll_to_top_rate,
+ f.backspace_count / nullIf(f.keypress_count, 0) AS backspace_ratio,
+ f.long_idle_gap_count / nullIf(f.inter_action_gap_count, 0) AS long_idle_gap_share,
+ f.console_warn_count / nullIf(f.session_duration_s, 0) AS console_warn_rate,
+ f.mutation_count / nullIf(f.session_duration_s, 0) AS mutation_rate,
+ f.viewport_resize_count,
+ f.touch_event_count / nullIf(f.session_duration_s, 0) AS touch_event_rate,
+ f.selection_copy_count,
+ f.login_path_visit_count / nullIf(f.page_visit_count, 0) AS login_path_visit_share,
+ f.signup_path_visit_count / nullIf(f.page_visit_count, 0) AS signup_path_visit_share,
+ f.checkout_path_visit_count / nullIf(f.page_visit_count, 0) AS checkout_path_visit_share,
+ f.cart_path_visit_count / nullIf(f.page_visit_count, 0) AS cart_path_visit_share,
+ f.billing_path_visit_count / nullIf(f.page_visit_count, 0) AS billing_path_visit_share,
+ f.settings_path_visit_count / nullIf(f.page_visit_count, 0) AS settings_path_visit_share,
+ f.account_path_visit_count / nullIf(f.page_visit_count, 0) AS account_path_visit_share,
+ f.error_path_visit_count / nullIf(f.page_visit_count, 0) AS error_path_visit_share,
+ f.not_found_path_visit_count / nullIf(f.page_visit_count, 0) AS not_found_path_visit_share,
+ f.admin_path_visit_count / nullIf(f.page_visit_count, 0) AS admin_path_visit_share,
+ f.dashboard_path_visit_count / nullIf(f.page_visit_count, 0) AS dashboard_path_visit_share,
+ f.onboarding_path_visit_count / nullIf(f.page_visit_count, 0) AS onboarding_path_visit_share,
+ f.cancel_path_visit_count / nullIf(f.page_visit_count, 0) AS cancel_path_visit_share,
+ f.refund_path_visit_count / nullIf(f.page_visit_count, 0) AS refund_path_visit_share,
+ f.unique_urls / nullIf(f.page_visit_count, 0) AS unique_url_share,
+ f.unique_click_targets / nullIf(f.click_count, 0) AS click_target_share,
+ f.unique_form_fields,
+ greatest(0, f.page_visit_count - f.unique_urls) / nullIf(f.page_visit_count, 0) AS page_revisit_share,
+ f.unique_urls AS unique_urls,
+ f.unique_click_targets AS unique_click_targets,
+ greatest(0, f.page_visit_count - f.unique_urls) AS page_revisit_count
+FROM aggregated_sufficient_statistics f
+""".strip()
+
+
+def fetch_features_sql(
+ replay_events_table: str = SESSION_REPLAY_EVENTS_TABLE,
+ features_table: str = SESSION_REPLAY_FEATURES_TABLE,
+) -> str:
+ """Return the parameterized SELECT used by `score_chunk_activity`.
+
+ Bound parameters: %(of_chunks)s, %(chunk_id)s, %(lookback_days)s, %(chunk_size)s.
+
+ Returned columns: `team_id`, `session_id`, `distinct_id`, `min_first_timestamp`,
+ then the feature columns. The feature alias list must match the booster's
+ `feature_names` (= `scorer.get_feature_names()`); `validate_features`
+ enforces this on every chunk. Row count <= chunk_size, minus any
+ sessions that have no replay features (inner-joined out).
+
+ `distinct_id` and `min_first_timestamp` are surfaced specifically so the
+ writeback can build an identity-value Kafka payload that (a) routes to
+ the right shard via the sipHash64(distinct_id) sharding key and (b)
+ cannot corrupt min/max/argMin aggregates on the existing session rows.
+ """
+ return f"""
+WITH eligible_sessions AS (
+ SELECT
+ team_id,
+ session_id,
+ any(distinct_id) AS distinct_id,
+ -- Aliased away from the raw column name: CH expands a same-named
+ -- SELECT alias into WHERE, which would turn the raw-row prefilter
+ -- below into an illegal aggregate-in-WHERE.
+ min(min_first_timestamp) AS started_at
+ FROM {replay_events_table}
+ -- Raw-row prefilter with a +1 day buffer so the scan prunes on the
+ -- min_first_timestamp ordering key instead of aggregating the whole
+ -- table. The exact lookback cut stays in HAVING on the aggregated min;
+ -- the buffer keeps the HAVING result identical for any session whose
+ -- rows span less than a day.
+ WHERE cityHash64(session_id) %% %(of_chunks)s = %(chunk_id)s
+ AND min_first_timestamp >= now() - toIntervalDay(%(lookback_days)s + 1)
+ GROUP BY team_id, session_id
+ HAVING max(surfacing_score) IS NULL
+ AND started_at >= now() - toIntervalDay(%(lookback_days)s)
+ -- 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
+ -- inner join would silently drop the difference).
+ ORDER BY session_id
+ LIMIT %(chunk_size)s
+),
+aggregated_sufficient_statistics AS (
+ {_AGGREGATED_STATS_FRAGMENT.format(features_table=features_table)}
+),
+replay_features AS (
+ {_REPLAY_FEATURES_FRAGMENT}
+)
+SELECT
+ e.team_id,
+ e.session_id,
+ e.distinct_id,
+ e.started_at AS min_first_timestamp,
+ rf.event_rate,
+ rf.click_rate,
+ rf.keypress_rate,
+ rf.mouse_activity_rate,
+ rf.rage_click_rate,
+ rf.dead_click_rate,
+ rf.quick_back_rate,
+ rf.page_visit_rate,
+ rf.text_selection_rate,
+ rf.scroll_event_rate,
+ rf.console_error_rate,
+ rf.console_error_after_click_rate,
+ rf.network_request_rate,
+ rf.network_failed_request_rate,
+ rf.mouse_mean_x,
+ rf.mouse_mean_y,
+ rf.mouse_stddev_x,
+ rf.mouse_stddev_y,
+ rf.mouse_distance_per_s,
+ rf.mouse_direction_change_rate,
+ rf.mouse_velocity_mean,
+ rf.mouse_velocity_stddev,
+ rf.scroll_magnitude_per_s,
+ rf.scroll_magnitude_per_event,
+ rf.scroll_direction_reversal_rate,
+ rf.rapid_scroll_reversal_rate,
+ rf.max_scroll_y,
+ rf.inter_action_gap_mean_ms,
+ rf.inter_action_gap_stddev_ms,
+ rf.max_idle_gap_ms,
+ rf.network_request_duration_mean_ms,
+ rf.network_request_duration_stddev_ms,
+ rf.network_failure_ratio,
+ rf.network_4xx_ratio,
+ rf.network_5xx_ratio,
+ rf.scroll_to_top_rate,
+ rf.backspace_ratio,
+ rf.long_idle_gap_share,
+ rf.console_warn_rate,
+ rf.mutation_rate,
+ rf.viewport_resize_count,
+ rf.touch_event_rate,
+ rf.selection_copy_count,
+ rf.login_path_visit_share,
+ rf.signup_path_visit_share,
+ rf.checkout_path_visit_share,
+ rf.cart_path_visit_share,
+ rf.billing_path_visit_share,
+ rf.settings_path_visit_share,
+ rf.account_path_visit_share,
+ rf.error_path_visit_share,
+ rf.not_found_path_visit_share,
+ rf.admin_path_visit_share,
+ rf.dashboard_path_visit_share,
+ rf.onboarding_path_visit_share,
+ rf.cancel_path_visit_share,
+ rf.refund_path_visit_share,
+ rf.unique_url_share,
+ rf.click_target_share,
+ rf.unique_form_fields,
+ rf.page_revisit_share,
+ -- Raw counts the current production booster consumes directly. The richer
+ -- query keeps the share/ratio variants above; surfacing both lets a simpler
+ -- booster (a subset of these columns) score against this superset query
+ -- without retraining or a serving code change.
+ rf.unique_urls,
+ rf.unique_click_targets,
+ rf.page_revisit_count
+FROM eligible_sessions e
+INNER JOIN replay_features rf ON rf.team_id = e.team_id AND rf.session_id = e.session_id
+""".strip()
+
+
+def count_unscored_sql(replay_events_table: str = SESSION_REPLAY_EVENTS_TABLE) -> str:
+ """Return a cheap COUNT estimate of unscored sessions in one hash bucket.
+
+ Bound parameters: %(lookback_days)s, %(of_chunks)s.
+
+ Sampling one bucket and extrapolating (× of_chunks in the caller) is a
+ cheap backlog estimate, far cheaper than scanning every unscored session.
+ """
+ return f"""
+SELECT count()
+FROM (
+ SELECT session_id
+ FROM {replay_events_table}
+ -- Same raw-row prefilter as fetch_features_sql — see comment there.
+ WHERE cityHash64(session_id) %% %(of_chunks)s = 0
+ AND min_first_timestamp >= now() - toIntervalDay(%(lookback_days)s + 1)
+ GROUP BY team_id, session_id
+ HAVING max(surfacing_score) IS NULL
+ AND min(min_first_timestamp) >= now() - toIntervalDay(%(lookback_days)s)
+)
+""".strip()
+
+
+# --------------------------------------------------------------------------- #
+# Feature-alignment helper #
+# --------------------------------------------------------------------------- #
+
+# Matches an `<alias>.<column>` line in the final SELECT (optional trailing
+# comma). The alias is `e` for ID columns or `rf` for features; the caller
+# filters by alias.
+_SELECT_ALIAS_RE = re.compile(r"^\s*(\w+)\.(\w+)\s*,?\s*$", re.MULTILINE)
+
+
+def feature_columns_in_select(sql: str, *, feature_table_alias: str = "rf") -> tuple[str, ...]:
+ """Return the ordered tuple of feature column aliases from the final SELECT.
+
+ Backs the SQL/booster parity test in `test_sql_alignment.py`: drift from
+ the booster's `feature_names` silently mis-scores sessions, so the test
+ catches it at CI. Returns the empty tuple on a malformed final SELECT
+ (the caller treats that as a hard fail).
+ """
+ # Anchor on the final `)SELECT ... FROM` so we don't pick up `<alias>.<col>`
+ # references inside earlier CTEs' ON clauses or aggregate args.
+ final_select = re.search(
+ r"\)\s*SELECT\b(?P<body>.*?)\bFROM\s+eligible_sessions\b",
+ sql,
+ flags=re.DOTALL | re.IGNORECASE,
+ )
+ if not final_select:
+ return ()
+ body = final_select.group("body")
+ return tuple(name for alias, name in _SELECT_ALIAS_RE.findall(body) if alias == feature_table_alias)
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/types.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/types.py
new file mode 100644
index 000000000000..16bd37d5f7b9
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/types.py
@@ -0,0 +1,56 @@
+"""Dataclasses for the surfacing-scoring workflow inputs and outputs.
+
+All payloads are intentionally tiny so they fit comfortably under Temporal's
+~2 MiB payload limit. Session IDs and feature vectors never flow through
+the workflow — each activity re-queries ClickHouse for its slice using the
+deterministic hash partition encoded in `ChunkSpec`.
+"""
+
+from dataclasses import dataclass, field
+
+
+@dataclass
+class ScoreSessionsBatchInputs:
+ """Top-level workflow input. Empty by design — all sizing is in constants.py.
+
+ A future per-region or per-team variant can extend this without breaking
+ existing schedules: extra fields default to None and current scheduler
+ logic ignores them.
+ """
+
+ pass
+
+
+@dataclass
+class ChunkSpec:
+ """Identifies one hash-partitioned slice of unscored sessions.
+
+ `chunk_id` and `of_chunks` define a `cityHash64(session_id) % of_chunks`
+ bucket. The activity that receives this re-queries CH for its slice — the
+ spec carries no session data, so it's safe to fan out hundreds of these
+ in a single workflow without payload pressure.
+ """
+
+ chunk_id: int
+ of_chunks: int
+ chunk_size: int
+ lookback_days: int
+
+
+@dataclass
+class ListChunksResult:
+ chunks: list[ChunkSpec] = field(default_factory=list)
+ estimated_unscored_sessions: int = 0
+
+
+@dataclass
+class ChunkResult:
+ chunk_id: int
+ scored: int = 0
+
+
+@dataclass
+class ScoreSessionsBatchResult:
+ total_scored: int = 0
+ chunks_dispatched: int = 0
+ chunks_failed: int = 0
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py
new file mode 100644
index 000000000000..2bf636043061
--- /dev/null
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py
@@ -0,0 +1,118 @@
+"""Parent workflow for session surfacing scoring.
+
+Per tick (driven by `schedule.py`):
+ 1. `list_chunks_activity` plans the fan-out — N deterministic hash-partitioned
+ chunks, each carrying a `(chunk_id, of_chunks, chunk_size)` spec only.
+ 2. All chunks are dispatched via `asyncio.gather` so they run in parallel
+ across the worker pool. Each `score_chunk_activity` is fully self-
+ contained (fetch + predict + write happen inside one activity).
+
+The workflow stays tiny on purpose:
+ * No per-session work in the workflow code path (workflow CPU is precious).
+ * Inputs/outputs are summary counts only — the actual scores are written
+ to ClickHouse from inside the activity, never returned through the
+ workflow boundary (Temporal's 2 MiB payload limit).
+ * Idempotent on retry — the CH `HAVING IS NULL` filter inside each chunk
+ activity skips already-scored sessions automatically.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ActivityError
+
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import (
+ LIST_CHUNKS_ACTIVITY_TIMEOUT,
+ SCORE_CHUNK_ACTIVITY_TIMEOUT,
+ SCORE_CHUNK_HEARTBEAT_TIMEOUT,
+ WORKFLOW_NAME,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.types import (
+ ChunkResult,
+ ChunkSpec,
+ ScoreSessionsBatchInputs,
+ ScoreSessionsBatchResult,
+)
+
+# Activity functions are referenced through `workflow.execute_activity`'s string
+# name so Django doesn't need to be reachable from the workflow sandbox.
+with workflow.unsafe.imports_passed_through():
+ from posthog.temporal.session_replay.surfacing_scoring_sweep.activities import (
+ list_chunks_activity,
+ score_chunk_activity,
+ )
+
+
[email protected](name=WORKFLOW_NAME)
+class ScoreSessionsBatchWorkflow(PostHogWorkflow):
+ """One tick of the scoring pipeline."""
+
+ inputs_cls = ScoreSessionsBatchInputs
+
+ @workflow.run
+ async def run(self, inputs: ScoreSessionsBatchInputs) -> ScoreSessionsBatchResult:
+ plan = await workflow.execute_activity(
+ list_chunks_activity,
+ inputs,
+ start_to_close_timeout=LIST_CHUNKS_ACTIVITY_TIMEOUT,
+ retry_policy=RetryPolicy(
+ maximum_attempts=2,
+ ),
+ )
+
+ if not plan.chunks:
+ workflow.logger.info("surfacing_scoring_sweep.no_work", estimated=plan.estimated_unscored_sessions)
+ return ScoreSessionsBatchResult()
+
+ results = await asyncio.gather(
+ *(self._score_chunk(spec) for spec in plan.chunks),
+ return_exceptions=True,
+ )
+
+ return _summarize(plan.chunks, results)
+
+ async def _score_chunk(self, spec: ChunkSpec) -> ChunkResult:
+ return await workflow.execute_activity(
+ score_chunk_activity,
+ spec,
+ start_to_close_timeout=SCORE_CHUNK_ACTIVITY_TIMEOUT,
+ heartbeat_timeout=SCORE_CHUNK_HEARTBEAT_TIMEOUT,
+ retry_policy=RetryPolicy(
+ # Single attempt: a retry after a 4-min activity timeout cannot
+ # fit inside the 4m30s workflow budget, so it would be killed
+ # mid-flight by workflow expiry anyway. Failed chunks stay NULL
+ # in CH and the next 5-min tick is the natural retry.
+ maximum_attempts=1,
+ non_retryable_error_types=["FeatureValidationError", "ScoreRangeError", "ModelNotConfiguredError"],
+ ),
+ )
+
+
+def _summarize(chunks: list[ChunkSpec], results: list[ChunkResult | BaseException]) -> ScoreSessionsBatchResult:
+ """Roll per-chunk results up to a tick-level summary.
+
+ Failed chunks are counted but don't bring the workflow down — their
+ sessions stay NULL in CH and pick up on the next 5-min tick.
+ """
+ summary = ScoreSessionsBatchResult(chunks_dispatched=len(chunks))
+ for r in results:
+ if isinstance(r, BaseException):
+ summary.chunks_failed += 1
+ if isinstance(r, ActivityError):
+ workflow.logger.warning(
+ "surfacing_scoring_sweep.chunk_activity_failed",
+ error=str(r),
+ )
+ continue
+ summary.total_scored += r.scored
+ workflow.logger.info(
+ "surfacing_scoring_sweep.tick_done",
+ chunks_dispatched=summary.chunks_dispatched,
+ chunks_failed=summary.chunks_failed,
+ total_scored=summary.total_scored,
+ )
+ return summary
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/__init__.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
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
new file mode 100644
index 000000000000..35f785a7c0ec
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/ch_insert_helpers.py
@@ -0,0 +1,108 @@
+"""CH insert helpers for surfacing_scoring_sweep integration tests.
+
+Partial inserts into writable_session_replay_events fail on argMin LC/String
+type mismatches — use sharded_session_replay_events with argMinState instead.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+from posthog.clickhouse.client import sync_execute
+
+_INSERT_SESSION_REPLAY_EVENT_NOW_SQL = """
+INSERT INTO sharded_session_replay_events (
+ session_id,
+ team_id,
+ distinct_id,
+ min_first_timestamp,
+ max_last_timestamp,
+ first_url,
+ snapshot_source,
+ snapshot_library,
+ surfacing_score
+)
+SELECT
+ %(session_id)s,
+ %(team_id)s,
+ %(distinct_id)s,
+ now64(6) - INTERVAL 1 HOUR,
+ now64(6),
+ 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),
+ %(surfacing_score)s
+"""
+
+_INSERT_SESSION_REPLAY_EVENT_AT_SQL = """
+INSERT INTO sharded_session_replay_events (
+ session_id,
+ team_id,
+ distinct_id,
+ min_first_timestamp,
+ max_last_timestamp,
+ first_url,
+ snapshot_source,
+ snapshot_library,
+ surfacing_score
+)
+SELECT
+ %(session_id)s,
+ %(team_id)s,
+ %(distinct_id)s,
+ toDateTime64(%(start)s, 6, 'UTC'),
+ toDateTime64(%(end)s, 6, 'UTC'),
+ 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')),
+ %(surfacing_score)s
+"""
+
+
+def insert_session_replay_event(
+ *,
+ team_id: int,
+ session_id: str,
+ distinct_id: str = "d1",
+ start: datetime | None = None,
+ end: datetime | None = None,
+ surfacing_score: float | None = None,
+) -> None:
+ params = {
+ "session_id": session_id,
+ "team_id": team_id,
+ "distinct_id": distinct_id,
+ "surfacing_score": surfacing_score,
+ }
+ if start is None:
+ sync_execute(_INSERT_SESSION_REPLAY_EVENT_NOW_SQL, params)
+ return
+
+ at_params: dict[str, Any] = {
+ **params,
+ "start": start,
+ "end": end or start,
+ }
+ sync_execute(_INSERT_SESSION_REPLAY_EVENT_AT_SQL, at_params)
+
+
+def insert_replay_features(
+ *,
+ team_id: int,
+ session_id: str,
+ distinct_id: str = "d1",
+ event_count: int = 42,
+) -> None:
+ sync_execute(
+ "INSERT INTO writable_session_replay_features "
+ "(session_id, team_id, distinct_id, min_first_timestamp, max_last_timestamp, event_count) "
+ "SELECT %(session_id)s, %(team_id)s, %(distinct_id)s, "
+ "now64(6) - INTERVAL 1 HOUR, now64(6), %(event_count)s",
+ {
+ "session_id": session_id,
+ "team_id": team_id,
+ "distinct_id": distinct_id,
+ "event_count": event_count,
+ },
+ )
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py
new file mode 100644
index 000000000000..b2c5e6260647
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py
@@ -0,0 +1,111 @@
+"""Shared fixtures for the surfacing_scoring_sweep tests.
+
+`feature_names_for_tests` (= `tuple(FEATURE_RANGES.keys())`) is the schema
+for tests that don't load a real booster — the runtime range contract
+doubles as the test schema so the two stay in lockstep.
+
+`surfacing_booster_path` trains a tiny booster in-memory and wires it
+behind a mocked S3 fetch so tests exercise the production code path
+(scorer is S3-only — no local-file fallback).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Generator
+from pathlib import Path
+
+import pytest
+
+import numpy as np
+import pandas as pd
+import xgboost as xgb
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep import scorer as scorer_mod
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import FEATURE_RANGES
+
+
+def feature_names_for_tests() -> tuple[str, ...]:
+ """Feature schema used by tests that don't load a real booster.
+
+ Production gets this from `scorer.get_feature_names()` (= booster.feature_names).
+ For unit tests of `validate_features` / `feature_matrix`, we use the
+ `FEATURE_RANGES` dict's keys — that's the runtime range contract and is
+ guaranteed to cover the booster (validated by `assert_ranges_cover` at
+ warmup), so it's a safe stand-in here.
+ """
+ return tuple(FEATURE_RANGES.keys())
+
+
+def feature_frame(feature_names_for_tests: tuple[str, ...]) -> pd.DataFrame:
+ """A small, valid feature DataFrame keyed by the test feature schema."""
+ rng = np.random.default_rng(123)
+ rows = 16
+ data = rng.random((rows, len(feature_names_for_tests))).astype(np.float32)
+ return pd.DataFrame(data, columns=list(feature_names_for_tests))
+
+
+def reset_scorer_singleton() -> None:
+ """Clear cached booster + feature names + S3 tempfile path. Public for test_scorer.py."""
+ scorer_mod._BOOSTER = None
+ scorer_mod._FEATURE_NAMES = None
+ scorer_mod._S3_CACHED_PATH = None
+
+
[email protected](autouse=True)
+def _scorer_singleton_clean_slate() -> Generator[None]:
+ """Every test in this directory starts and ends with a fresh scorer singleton."""
+ reset_scorer_singleton()
+ yield
+ reset_scorer_singleton()
+
+
+def train_synthetic_booster(
+ feature_names: tuple[str, ...],
+ *,
+ seed: int = 42,
+ rows: int = 128,
+) -> xgb.Booster:
+ """Tiny 2-tree binary:logistic booster with feature_names baked in.
+
+ Labels are `first_feature > 0.5` so the booster has real signal.
+ For non-logistic objectives, build the DMatrix + train directly.
+ """
+ rng = np.random.default_rng(seed)
+ data = rng.random((rows, len(feature_names))).astype(np.float32)
+ df = pd.DataFrame(data, columns=list(feature_names))
+ labels = (df[feature_names[0]] > 0.5).astype(np.int32).to_numpy()
+ dmat = xgb.DMatrix(df, label=labels, feature_names=list(feature_names))
+ return xgb.train(
+ {"objective": "binary:logistic", "max_depth": 2, "eta": 0.5, "verbosity": 0},
+ dmat,
+ num_boost_round=2,
+ )
+
+
+def wire_booster_as_s3(
+ monkeypatch: pytest.MonkeyPatch, booster_path: Path, uri: str = "s3://test-bucket/model.ubj"
+) -> None:
+ """Point the scorer at `booster_path` via a mocked S3 fetch.
+
+ Sets the S3 URI env var and patches `object_storage.read_bytes` so the
+ scorer's production path (`_fetch_from_s3` → tempfile) loads the bytes
+ we already have on disk. Same code path as prod, zero network.
+ """
+ payload = booster_path.read_bytes()
+ monkeypatch.setenv("SESSION_INTERESTINGNESS_MODEL_S3_URI", uri)
+ monkeypatch.setattr(
+ "posthog.temporal.session_replay.surfacing_scoring_sweep.scorer.object_storage.read_bytes",
+ lambda key, *, bucket=None: payload,
+ )
+
+
+def surfacing_booster_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Trained booster on FEATURE_RANGES.keys(); wired behind a mocked S3 fetch."""
+ booster = train_synthetic_booster(tuple(FEATURE_RANGES.keys()))
+ path = tmp_path / "model.ubj"
+ booster.save_model(str(path))
+ wire_booster_as_s3(monkeypatch, path)
+ return path
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/fixtures/training_feature_query.sql b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/fixtures/training_feature_query.sql
new file mode 100644
index 000000000000..3382b03ab572
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/fixtures/training_feature_query.sql
@@ -0,0 +1,153 @@
+WITH unlabeled_sessions AS (
+ SELECT session_id
+ FROM session_replay_events
+ WHERE min_first_timestamp >= now() - INTERVAL {interval} DAY
+ AND session_id NOT IN {{seen_ids:Array(String)}}
+ GROUP BY session_id
+ HAVING length(groupUniqArrayArray(ai_tags_fixed)) = 0
+ ORDER BY cityHash64(session_id, {seed})
+ LIMIT {pool_size}
+),
+aggregated_sufficient_statistics AS (
+ SELECT
+ f.session_id,
+ dateDiff('second', min(f.min_first_timestamp), max(f.max_last_timestamp)) AS session_duration_s,
+ sum(f.event_count) AS event_count,
+ sum(f.click_count) AS click_count,
+ sum(f.keypress_count) AS keypress_count,
+ sum(f.mouse_activity_count) AS mouse_activity_count,
+ sum(f.rage_click_count) AS rage_click_count,
+ sum(f.dead_click_count) AS dead_click_count,
+ sum(f.quick_back_count) AS quick_back_count,
+ sum(f.page_visit_count) AS page_visit_count,
+ sum(f.text_selection_count) AS text_selection_count,
+ sum(f.scroll_event_count) AS scroll_event_count,
+ sum(f.console_error_count) AS console_error_count,
+ sum(f.console_error_after_click_count) AS console_error_after_click_count,
+ sum(f.network_request_count) AS network_request_count,
+ sum(f.network_failed_request_count) AS network_failed_request_count,
+ sum(f.mouse_position_count) AS mouse_position_count,
+ sum(f.mouse_sum_x) AS mouse_sum_x,
+ sum(f.mouse_sum_x_squared) AS mouse_sum_x_squared,
+ sum(f.mouse_sum_y) AS mouse_sum_y,
+ sum(f.mouse_sum_y_squared) AS mouse_sum_y_squared,
+ sum(f.mouse_distance_traveled) AS mouse_distance_traveled,
+ sum(f.mouse_direction_change_count) AS mouse_direction_change_count,
+ sum(f.mouse_velocity_sum) AS mouse_velocity_sum,
+ sum(f.mouse_velocity_sum_of_squares) AS mouse_velocity_sum_of_squares,
+ sum(f.mouse_velocity_count) AS mouse_velocity_count,
+ sum(f.total_scroll_magnitude) AS total_scroll_magnitude,
+ sum(f.scroll_direction_reversal_count) AS scroll_direction_reversal_count,
+ sum(f.rapid_scroll_reversal_count) AS rapid_scroll_reversal_count,
+ max(f.max_scroll_y) AS max_scroll_y,
+ sum(f.inter_action_gap_count) AS inter_action_gap_count,
+ sum(f.inter_action_gap_sum_ms) AS inter_action_gap_sum_ms,
+ sum(f.inter_action_gap_sum_of_squares_ms) AS inter_action_gap_sum_of_squares_ms,
+ max(f.max_idle_gap_ms) AS max_idle_gap_ms,
+ sum(f.network_request_duration_sum) AS network_request_duration_sum,
+ sum(f.network_request_duration_sum_of_squares) AS network_request_duration_sum_of_squares,
+ sum(f.network_request_duration_count) AS network_request_duration_count,
+ sum(f.scroll_to_top_count) AS scroll_to_top_count,
+ sum(f.backspace_count) AS backspace_count,
+ sum(f.long_idle_gap_count) AS long_idle_gap_count,
+ sum(f.console_warn_count) AS console_warn_count,
+ sum(f.network_4xx_count) AS network_4xx_count,
+ sum(f.network_5xx_count) AS network_5xx_count,
+ sum(f.mutation_count) AS mutation_count,
+ sum(f.viewport_resize_count) AS viewport_resize_count,
+ sum(f.touch_event_count) AS touch_event_count,
+ sum(f.selection_copy_count) AS selection_copy_count,
+ sum(f.login_path_visit_count) AS login_path_visit_count,
+ sum(f.signup_path_visit_count) AS signup_path_visit_count,
+ sum(f.checkout_path_visit_count) AS checkout_path_visit_count,
+ sum(f.cart_path_visit_count) AS cart_path_visit_count,
+ sum(f.billing_path_visit_count) AS billing_path_visit_count,
+ sum(f.settings_path_visit_count) AS settings_path_visit_count,
+ sum(f.account_path_visit_count) AS account_path_visit_count,
+ sum(f.error_path_visit_count) AS error_path_visit_count,
+ sum(f.not_found_path_visit_count) AS not_found_path_visit_count,
+ sum(f.admin_path_visit_count) AS admin_path_visit_count,
+ sum(f.dashboard_path_visit_count) AS dashboard_path_visit_count,
+ sum(f.onboarding_path_visit_count) AS onboarding_path_visit_count,
+ sum(f.cancel_path_visit_count) AS cancel_path_visit_count,
+ sum(f.refund_path_visit_count) AS refund_path_visit_count,
+ uniqCombinedMerge(12)(f.unique_url_count) AS unique_urls,
+ uniqCombinedMerge(12)(f.unique_click_target_count) AS unique_click_targets,
+ uniqCombinedMerge(12)(f.unique_form_field_count) AS unique_form_fields
+ FROM session_replay_features AS f
+ WHERE f.session_id GLOBAL IN (SELECT session_id FROM unlabeled_sessions)
+ AND f.min_first_timestamp >= now() - INTERVAL {interval} DAY
+ GROUP BY f.session_id
+)
+SELECT
+ f.session_id,
+ f.event_count / nullIf(f.session_duration_s, 0) AS event_rate,
+ f.click_count / nullIf(f.session_duration_s, 0) AS click_rate,
+ f.keypress_count / nullIf(f.session_duration_s, 0) AS keypress_rate,
+ f.mouse_activity_count / nullIf(f.session_duration_s, 0) AS mouse_activity_rate,
+ f.rage_click_count / nullIf(f.session_duration_s, 0) AS rage_click_rate,
+ f.dead_click_count / nullIf(f.session_duration_s, 0) AS dead_click_rate,
+ f.quick_back_count / nullIf(f.session_duration_s, 0) AS quick_back_rate,
+ f.page_visit_count / nullIf(f.session_duration_s, 0) AS page_visit_rate,
+ f.text_selection_count / nullIf(f.session_duration_s, 0) AS text_selection_rate,
+ f.scroll_event_count / nullIf(f.session_duration_s, 0) AS scroll_event_rate,
+ f.console_error_count / nullIf(f.session_duration_s, 0) AS console_error_rate,
+ f.console_error_after_click_count / nullIf(f.session_duration_s, 0) AS console_error_after_click_rate,
+ f.network_request_count / nullIf(f.session_duration_s, 0) AS network_request_rate,
+ f.network_failed_request_count / nullIf(f.session_duration_s, 0) AS network_failed_request_rate,
+ f.mouse_sum_x / nullIf(f.mouse_position_count, 0) AS mouse_mean_x,
+ f.mouse_sum_y / nullIf(f.mouse_position_count, 0) AS mouse_mean_y,
+ sqrt(greatest(0, f.mouse_sum_x_squared / nullIf(f.mouse_position_count, 0)
+ - pow(f.mouse_sum_x / nullIf(f.mouse_position_count, 0), 2))) AS mouse_stddev_x,
+ sqrt(greatest(0, f.mouse_sum_y_squared / nullIf(f.mouse_position_count, 0)
+ - pow(f.mouse_sum_y / nullIf(f.mouse_position_count, 0), 2))) AS mouse_stddev_y,
+ f.mouse_distance_traveled / nullIf(f.session_duration_s, 0) AS mouse_distance_per_s,
+ f.mouse_direction_change_count / nullIf(f.mouse_distance_traveled, 0) AS mouse_direction_change_rate,
+ f.mouse_velocity_sum / nullIf(f.mouse_velocity_count, 0) AS mouse_velocity_mean,
+ sqrt(greatest(0, f.mouse_velocity_sum_of_squares / nullIf(f.mouse_velocity_count, 0)
+ - pow(f.mouse_velocity_sum / nullIf(f.mouse_velocity_count, 0), 2))) AS mouse_velocity_stddev,
+ f.total_scroll_magnitude / nullIf(f.session_duration_s, 0) AS scroll_magnitude_per_s,
+ f.total_scroll_magnitude / nullIf(f.scroll_event_count, 0) AS scroll_magnitude_per_event,
+ f.scroll_direction_reversal_count / nullIf(f.session_duration_s, 0) AS scroll_direction_reversal_rate,
+ f.rapid_scroll_reversal_count / nullIf(f.session_duration_s, 0) AS rapid_scroll_reversal_rate,
+ f.max_scroll_y,
+ f.inter_action_gap_sum_ms / nullIf(f.inter_action_gap_count, 0) AS inter_action_gap_mean_ms,
+ sqrt(greatest(0, f.inter_action_gap_sum_of_squares_ms / nullIf(f.inter_action_gap_count, 0)
+ - pow(f.inter_action_gap_sum_ms / nullIf(f.inter_action_gap_count, 0), 2))) AS inter_action_gap_stddev_ms,
+ f.max_idle_gap_ms,
+ f.network_request_duration_sum / nullIf(f.network_request_duration_count, 0) AS network_request_duration_mean_ms,
+ sqrt(greatest(0, f.network_request_duration_sum_of_squares / nullIf(f.network_request_duration_count, 0)
+ - pow(f.network_request_duration_sum / nullIf(f.network_request_duration_count, 0), 2))) AS network_request_duration_stddev_ms,
+ f.network_failed_request_count / nullIf(f.network_request_count, 0) AS network_failure_ratio,
+ f.network_4xx_count / nullIf(f.network_request_count, 0) AS network_4xx_ratio,
+ f.network_5xx_count / nullIf(f.network_request_count, 0) AS network_5xx_ratio,
+ f.scroll_to_top_count / nullIf(f.session_duration_s, 0) AS scroll_to_top_rate,
+ f.backspace_count / nullIf(f.keypress_count, 0) AS backspace_ratio,
+ f.long_idle_gap_count / nullIf(f.inter_action_gap_count, 0) AS long_idle_gap_share,
+ f.console_warn_count / nullIf(f.session_duration_s, 0) AS console_warn_rate,
+ f.mutation_count / nullIf(f.session_duration_s, 0) AS mutation_rate,
+ f.viewport_resize_count,
+ f.touch_event_count / nullIf(f.session_duration_s, 0) AS touch_event_rate,
+ f.selection_copy_count,
+ f.login_path_visit_count / nullIf(f.page_visit_count, 0) AS login_path_visit_share,
+ f.signup_path_visit_count / nullIf(f.page_visit_count, 0) AS signup_path_visit_share,
+ f.checkout_path_visit_count / nullIf(f.page_visit_count, 0) AS checkout_path_visit_share,
+ f.cart_path_visit_count / nullIf(f.page_visit_count, 0) AS cart_path_visit_share,
+ f.billing_path_visit_count / nullIf(f.page_visit_count, 0) AS billing_path_visit_share,
+ f.settings_path_visit_count / nullIf(f.page_visit_count, 0) AS settings_path_visit_share,
+ f.account_path_visit_count / nullIf(f.page_visit_count, 0) AS account_path_visit_share,
+ f.error_path_visit_count / nullIf(f.page_visit_count, 0) AS error_path_visit_share,
+ f.not_found_path_visit_count / nullIf(f.page_visit_count, 0) AS not_found_path_visit_share,
+ f.admin_path_visit_count / nullIf(f.page_visit_count, 0) AS admin_path_visit_share,
+ f.dashboard_path_visit_count / nullIf(f.page_visit_count, 0) AS dashboard_path_visit_share,
+ f.onboarding_path_visit_count / nullIf(f.page_visit_count, 0) AS onboarding_path_visit_share,
+ f.cancel_path_visit_count / nullIf(f.page_visit_count, 0) AS cancel_path_visit_share,
+ f.refund_path_visit_count / nullIf(f.page_visit_count, 0) AS refund_path_visit_share,
+ f.unique_urls / nullIf(f.page_visit_count, 0) AS unique_url_share,
+ f.unique_click_targets / nullIf(f.click_count, 0) AS click_target_share,
+ f.unique_form_fields,
+ greatest(0, f.page_visit_count - f.unique_urls) / nullIf(f.page_visit_count, 0) AS page_revisit_share,
+ f.unique_urls AS unique_urls,
+ f.unique_click_targets AS unique_click_targets,
+ greatest(0, f.page_visit_count - f.unique_urls) AS page_revisit_count
+FROM aggregated_sufficient_statistics f
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/sql_alignment_helpers.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/sql_alignment_helpers.py
new file mode 100644
index 000000000000..e9804567ffd8
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/sql_alignment_helpers.py
@@ -0,0 +1,97 @@
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+_TRAINING_QUERY_PATH = Path(__file__).parent / "fixtures" / "training_feature_query.sql"
+_AS_ALIAS_RE = re.compile(r"\bAS\s+(\w+)\b", re.IGNORECASE)
+_PASSTHROUGH_COL_RE = re.compile(r"^f\.(\w+)$", re.IGNORECASE)
+
+
+def load_training_query_sql() -> str:
+ return _TRAINING_QUERY_PATH.read_text()
+
+
+def _balanced_cte_body(sql: str, cte_name: str) -> str:
+ marker = f"{cte_name} AS ("
+ start = sql.index(marker) + len(marker)
+ depth = 1
+ index = start
+ while index < len(sql) and depth > 0:
+ char = sql[index]
+ if char == "(":
+ depth += 1
+ elif char == ")":
+ depth -= 1
+ index += 1
+ return sql[start : index - 1]
+
+
+def select_list_body(sql_fragment: str) -> str:
+ upper = sql_fragment.upper()
+ select_index = upper.find("SELECT")
+ if select_index < 0:
+ raise ValueError("Could not locate SELECT in SQL fragment")
+ from_index = upper.find("FROM", select_index + len("SELECT"))
+ if from_index < 0:
+ raise ValueError("Could not locate FROM in SQL fragment")
+ return sql_fragment[select_index + len("SELECT") : from_index]
+
+
+def _split_select_items(body: str) -> tuple[str, ...]:
+ items: list[str] = []
+ current: list[str] = []
+ depth = 0
+ for char in body:
+ if char == "(":
+ depth += 1
+ current.append(char)
+ elif char == ")":
+ depth -= 1
+ current.append(char)
+ elif char == "," and depth == 0:
+ item = "".join(current).strip()
+ if item:
+ items.append(item)
+ current = []
+ else:
+ current.append(char)
+ item = "".join(current).strip()
+ if item:
+ items.append(item)
+ return tuple(items)
+
+
+def _alias_from_select_item(item: str) -> str | None:
+ as_match = _AS_ALIAS_RE.search(item)
+ if as_match:
+ return as_match.group(1)
+ passthrough_match = _PASSTHROUGH_COL_RE.match(item.strip())
+ if passthrough_match:
+ return passthrough_match.group(1)
+ return None
+
+
+def feature_aliases_from_select_body(body: str) -> tuple[str, ...]:
+ return tuple(alias for item in _split_select_items(body) if (alias := _alias_from_select_item(item)) is not None)
+
+
+def training_aggregated_stat_aliases() -> tuple[str, ...]:
+ sql = load_training_query_sql()
+ cte_body = _balanced_cte_body(sql, "aggregated_sufficient_statistics")
+ return feature_aliases_from_feature_select(select_list_body(cte_body))
+
+
+def training_derived_feature_aliases() -> tuple[str, ...]:
+ sql = load_training_query_sql()
+ from_marker = "FROM aggregated_sufficient_statistics f"
+ from_index = sql.index(from_marker)
+ select_index = sql.rfind("SELECT", 0, from_index)
+ if select_index < 0:
+ raise AssertionError("Could not locate training query final SELECT")
+ body = sql[select_index + len("SELECT") : from_index]
+ return feature_aliases_from_feature_select(body)
+
+
+def feature_aliases_from_feature_select(body: str) -> tuple[str, ...]:
+ return tuple(alias for alias in feature_aliases_from_select_body(body) if alias not in {"session_id", "team_id"})
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
new file mode 100644
index 000000000000..6e8a71971202
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_activities.py
@@ -0,0 +1,182 @@
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+from unittest import mock
+
+import numpy as np
+import pandas as pd
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import ActivityEnvironment
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep.activities import (
+ _build_partial_row,
+ list_chunks_activity,
+ score_chunk_activity,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import (
+ CH_FEATURE_QUERY_TIMEOUT_S,
+ DEFAULT_OF_CHUNKS,
+ 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.types import ChunkSpec, ScoreSessionsBatchInputs
+
+ACTIVITIES_MODULE = "posthog.temporal.session_replay.surfacing_scoring_sweep.activities"
+
+
+class TestListChunksActivity:
+ @pytest.mark.asyncio
+ async def test_always_dispatches_all_hash_buckets(self) -> None:
+ with mock.patch(f"{ACTIVITIES_MODULE}._count_unscored_in_one_bucket", return_value=0):
+ result = await ActivityEnvironment().run(list_chunks_activity, ScoreSessionsBatchInputs())
+
+ assert len(result.chunks) == DEFAULT_OF_CHUNKS
+ assert result.estimated_unscored_sessions == 0
+ assert {spec.chunk_id for spec in result.chunks} == set(range(DEFAULT_OF_CHUNKS))
+ for spec in result.chunks:
+ assert spec.of_chunks == DEFAULT_OF_CHUNKS
+ assert spec.chunk_size == TARGET_CHUNK_SIZE
+
+ @pytest.mark.asyncio
+ async def test_extrapolates_backlog_estimate_from_bucket_zero_sample(self) -> None:
+ with mock.patch(f"{ACTIVITIES_MODULE}._count_unscored_in_one_bucket", return_value=42):
+ result = await ActivityEnvironment().run(list_chunks_activity, ScoreSessionsBatchInputs())
+
+ assert result.estimated_unscored_sessions == 42 * DEFAULT_OF_CHUNKS
+
+
+class TestBuildPartialRow:
+ def test_naive_datetime_is_treated_as_utc(self) -> None:
+ naive = datetime(2026, 5, 7, 10, 0, 0)
+ row = _build_partial_row(
+ team_id=1,
+ session_id="sess",
+ distinct_id="user",
+ min_first_timestamp=naive,
+ score=0.5,
+ )
+ assert row["first_timestamp"] == "2026-05-07 10:00:00.000001"
+ assert row["last_timestamp"] == "2026-05-07 10:00:00.000001"
+
+
+class TestScoreChunkActivity:
+ @pytest.mark.asyncio
+ async def test_empty_chunk_returns_zero_without_touching_model(self, surfacing_booster_path: object) -> None:
+ spec = ChunkSpec(chunk_id=0, of_chunks=1, chunk_size=10, lookback_days=7)
+ empty = pd.DataFrame(columns=pd.Index(["team_id", "session_id", "distinct_id", "min_first_timestamp"]))
+
+ with (
+ mock.patch(f"{ACTIVITIES_MODULE}._fetch_features_dataframe", return_value=empty),
+ mock.patch(f"{ACTIVITIES_MODULE}.get_feature_names") as get_names_mock,
+ mock.patch(f"{ACTIVITIES_MODULE}.predict") as predict_mock,
+ ):
+ result = await ActivityEnvironment().run(score_chunk_activity, spec)
+
+ assert result.scored == 0
+ get_names_mock.assert_not_called()
+ predict_mock.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_feature_validation_error_is_non_retryable(self, surfacing_booster_path: object) -> None:
+ spec = ChunkSpec(chunk_id=0, of_chunks=1, chunk_size=10, lookback_days=7)
+ df = pd.DataFrame({"team_id": [1], "session_id": ["s"], "distinct_id": ["d"], "event_rate": [0.1]})
+
+ with (
+ mock.patch(f"{ACTIVITIES_MODULE}._fetch_features_dataframe", return_value=df),
+ mock.patch(f"{ACTIVITIES_MODULE}.get_feature_names", return_value=("event_rate", "click_rate")),
+ mock.patch(
+ f"{ACTIVITIES_MODULE}.validate_features",
+ side_effect=FeatureValidationError("missing columns"),
+ ),
+ ):
+ with pytest.raises(ApplicationError) as exc_info:
+ await ActivityEnvironment().run(score_chunk_activity, spec)
+
+ assert exc_info.value.non_retryable is True
+ assert exc_info.value.type == "FeatureValidationError"
+
+ @pytest.mark.asyncio
+ async def test_happy_path_scores_and_publishes(self, surfacing_booster_path: object) -> None:
+ spec = ChunkSpec(chunk_id=0, of_chunks=1, chunk_size=10, lookback_days=7)
+ feature_names = ("event_rate",)
+ df = pd.DataFrame(
+ {
+ "team_id": [1],
+ "session_id": ["sess-1"],
+ "distinct_id": ["user-1"],
+ "min_first_timestamp": pd.to_datetime(["2026-05-07 10:00:00+00:00"]),
+ "event_rate": [0.2],
+ }
+ )
+
+ with (
+ mock.patch(f"{ACTIVITIES_MODULE}._fetch_features_dataframe", return_value=df),
+ mock.patch(f"{ACTIVITIES_MODULE}.get_feature_names", return_value=feature_names),
+ mock.patch(f"{ACTIVITIES_MODULE}.validate_features"),
+ mock.patch(f"{ACTIVITIES_MODULE}.predict", return_value=np.array([0.42], dtype=np.float32)),
+ mock.patch(f"{ACTIVITIES_MODULE}._publish_scores", return_value=1) as publish_mock,
+ ):
+ result = await ActivityEnvironment().run(score_chunk_activity, spec)
+
+ assert result.scored == 1
+ publish_mock.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_out_of_contract_row_is_dropped_not_chunk_blocking(self, surfacing_booster_path: object) -> None:
+ spec = ChunkSpec(chunk_id=0, of_chunks=1, chunk_size=10, lookback_days=7)
+ feature_names = ("event_rate",)
+ df = pd.DataFrame(
+ {
+ "team_id": [1, 1],
+ "session_id": ["sess-bad", "sess-good"],
+ "distinct_id": ["user-1", "user-2"],
+ "min_first_timestamp": pd.to_datetime(["2026-05-07 10:00:00+00:00", "2026-05-07 11:00:00+00:00"]),
+ "event_rate": [-1.0, 0.2],
+ }
+ )
+
+ with (
+ mock.patch(f"{ACTIVITIES_MODULE}._fetch_features_dataframe", return_value=df),
+ mock.patch(f"{ACTIVITIES_MODULE}.get_feature_names", return_value=feature_names),
+ mock.patch(f"{ACTIVITIES_MODULE}.predict", return_value=np.array([0.42], dtype=np.float32)),
+ mock.patch(f"{ACTIVITIES_MODULE}._publish_scores", return_value=1) as publish_mock,
+ ):
+ result = await ActivityEnvironment().run(score_chunk_activity, spec)
+
+ assert result.scored == 1
+ published_df = publish_mock.call_args.args[0]
+ assert published_df["session_id"].tolist() == ["sess-good"]
+
+ @pytest.mark.asyncio
+ async def test_all_rows_out_of_contract_returns_zero_scored(self, surfacing_booster_path: object) -> None:
+ spec = ChunkSpec(chunk_id=0, of_chunks=1, chunk_size=10, lookback_days=7)
+ feature_names = ("event_rate",)
+ df = pd.DataFrame(
+ {
+ "team_id": [1],
+ "session_id": ["sess-bad"],
+ "distinct_id": ["user-1"],
+ "min_first_timestamp": pd.to_datetime(["2026-05-07 10:00:00+00:00"]),
+ "event_rate": [float("inf")],
+ }
+ )
+
+ with (
+ mock.patch(f"{ACTIVITIES_MODULE}._fetch_features_dataframe", return_value=df),
+ mock.patch(f"{ACTIVITIES_MODULE}.get_feature_names", return_value=feature_names),
+ mock.patch(f"{ACTIVITIES_MODULE}.predict") as predict_mock,
+ mock.patch(f"{ACTIVITIES_MODULE}._publish_scores") as publish_mock,
+ ):
+ result = await ActivityEnvironment().run(score_chunk_activity, spec)
+
+ assert result.scored == 0
+ predict_mock.assert_not_called()
+ publish_mock.assert_not_called()
+
+
+class TestPipelineTimeouts:
+ def test_heartbeat_timeout_exceeds_clickhouse_query_timeout(self) -> None:
+ assert SCORE_CHUNK_HEARTBEAT_TIMEOUT.total_seconds() > CH_FEATURE_QUERY_TIMEOUT_S
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_features.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_features.py
new file mode 100644
index 000000000000..3aa9b3a721d9
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_features.py
@@ -0,0 +1,237 @@
+"""Unit tests for `surfacing_scoring_sweep.features.validate_features`.
+
+The function is the runtime gate between the CH SELECT and the XGBoost
+predict — every drift mode that could mis-score sessions in production is
+covered here. Tests are pure pandas, no CH or xgboost in the picture.
+
+`validate_features` and `feature_matrix` take `feature_names` explicitly, so
+these tests don't need a real booster — they pass the test fixture's
+`feature_names_for_tests` (= `FEATURE_RANGES.keys()`).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+import numpy as np
+import pandas as pd
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import (
+ FEATURE_RANGES,
+ FeatureValidationError,
+ MissingFeatureRangeError,
+ assert_ranges_cover,
+ feature_matrix,
+ out_of_contract_row_mask,
+ validate_features,
+)
+
+
+class TestValidateFeaturesHappyPaths:
+ def test_zero_row_dataframe_passes(self, feature_names_for_tests: tuple[str, ...]) -> None:
+ row = dict.fromkeys(feature_names_for_tests, 0.0)
+ validate_features(pd.DataFrame([row]), feature_names=feature_names_for_tests)
+
+ def test_empty_dataframe_passes(self, feature_names_for_tests: tuple[str, ...]) -> None:
+ validate_features(
+ pd.DataFrame(columns=pd.Index(feature_names_for_tests)),
+ feature_names=feature_names_for_tests,
+ )
+
+ def test_nan_passes_for_float_features(
+ self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ # XGBoost handles NaN natively; our SQL deliberately produces NULL → NaN
+ # when denominators are zero. NaN must not be rejected.
+ feature_frame.loc[0, "event_rate"] = float("nan")
+ feature_frame.loc[1, "mouse_mean_x"] = float("nan")
+ validate_features(feature_frame, feature_names=feature_names_for_tests)
+
+ def test_id_columns_alongside_features_pass(
+ self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ # The CH SELECT returns id columns + features in one frame. validate_features
+ # must accept that layout, not just bare features.
+ df = feature_frame.copy()
+ df["team_id"] = 42
+ df["session_id"] = "00000000-0000-7000-0000-000000000000"
+ df["distinct_id"] = "user-1"
+ df["min_first_timestamp"] = pd.Timestamp("2026-01-01")
+ validate_features(df, feature_names=feature_names_for_tests)
+
+
+class TestValidateFeaturesColumnSet:
+ def test_missing_column_raises(self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]) -> None:
+ df = feature_frame.drop(columns=["click_rate"])
+ with pytest.raises(FeatureValidationError, match=r"missing=\['click_rate'\]"):
+ validate_features(df, feature_names=feature_names_for_tests)
+
+ def test_extra_feature_column_is_tolerated(
+ self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ # The serving SQL may expose a superset of columns; the booster scores
+ # its own subset (feature_matrix selects by name), so extra columns the
+ # booster ignores must not fail the chunk.
+ df = feature_frame.copy()
+ df["unused_extra_feature"] = 0.0
+ validate_features(df, feature_names=feature_names_for_tests)
+
+ def test_subset_booster_validates_against_superset_frame(
+ self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ # Models the production case: a simpler booster (a subset of the
+ # query's features) scored against the full feature frame.
+ subset = feature_names_for_tests[: len(feature_names_for_tests) // 2]
+ validate_features(feature_frame, feature_names=subset)
+
+ def test_reordered_columns_are_tolerated(
+ self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ # Column order is irrelevant: feature_matrix reorders to the trained
+ # order by name before DMatrix construction.
+ cols = list(feature_frame.columns)
+ cols[0], cols[1] = cols[1], cols[0]
+ validate_features(feature_frame.loc[:, cols], feature_names=feature_names_for_tests)
+
+
+class TestOutOfContractRowMask:
+ @pytest.mark.parametrize(
+ ("column", "bad_value"),
+ [
+ ("event_rate", -0.5),
+ ("network_failure_ratio", 1.5),
+ ("page_revisit_share", 1.5),
+ ("mouse_stddev_x", -1.0),
+ ("selection_copy_count", -1),
+ ("event_rate", float("inf")),
+ ("event_rate", float("-inf")),
+ ],
+ )
+ def test_out_of_contract_value_flags_only_its_row(
+ self,
+ column: str,
+ bad_value: Any,
+ feature_frame: pd.DataFrame,
+ feature_names_for_tests: tuple[str, ...],
+ ) -> None:
+ good_row = feature_frame.iloc[0].copy()
+ df = pd.DataFrame([feature_frame.iloc[0], good_row]).reset_index(drop=True)
+ df.loc[0, column] = bad_value
+
+ mask = out_of_contract_row_mask(df, feature_names=feature_names_for_tests)
+
+ assert mask.tolist() == [True, False]
+
+ @pytest.mark.parametrize(
+ ("column", "value"),
+ [
+ # Rates have no upper bound — high counts on short sessions can produce
+ # arbitrarily large rates. Don't false-positive on legitimate data.
+ ("event_rate", 1e6),
+ # mouse_mean_x has no lower bound — mouse can be off-screen.
+ ("mouse_mean_x", -1234.5),
+ # NaN passes — XGBoost handles it natively, SQL produces NULL on zero denominators.
+ ("network_failure_ratio", float("nan")),
+ ],
+ )
+ def test_in_contract_value_is_not_flagged(
+ self,
+ column: str,
+ value: float,
+ feature_frame: pd.DataFrame,
+ feature_names_for_tests: tuple[str, ...],
+ ) -> None:
+ feature_frame.loc[0, column] = value
+
+ mask = out_of_contract_row_mask(feature_frame, feature_names=feature_names_for_tests)
+
+ assert not mask.any()
+
+
+class TestValidateFeaturesDtypes:
+ def test_string_dtype_rejected_for_numeric_feature(
+ self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ df = feature_frame.copy()
+ df["event_rate"] = df["event_rate"].astype(str)
+ with pytest.raises(FeatureValidationError, match="dtype"):
+ validate_features(df, feature_names=feature_names_for_tests)
+
+ def test_int_dtype_accepted_for_count_column(
+ self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ # Count columns can come back as int64 (no NULLs) or float64 (some NULLs)
+ # depending on what's in the chunk — both must pass.
+ df = feature_frame.copy()
+ df["selection_copy_count"] = df["selection_copy_count"].astype(np.int64)
+ validate_features(df, feature_names=feature_names_for_tests)
+
+ def test_float_dtype_accepted_for_count_column(
+ self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ df = feature_frame.copy()
+ df["selection_copy_count"] = df["selection_copy_count"].astype(np.float64)
+ validate_features(df, feature_names=feature_names_for_tests)
+
+
+class TestFeatureMatrix:
+ def test_strips_id_columns(self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]) -> None:
+ df = feature_frame.copy()
+ df["team_id"] = 1
+ df["session_id"] = "00000000-0000-7000-0000-000000000000"
+ df["distinct_id"] = "user-1"
+ df["min_first_timestamp"] = pd.Timestamp("2026-01-01")
+
+ out = feature_matrix(df, feature_names=feature_names_for_tests)
+
+ assert list(out.columns) == list(feature_names_for_tests)
+ assert "team_id" not in out.columns
+ assert "session_id" not in out.columns
+ assert "distinct_id" not in out.columns
+ assert "min_first_timestamp" not in out.columns
+ assert len(out) == len(feature_frame)
+
+ def test_preserves_row_order(self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]) -> None:
+ # Predict re-attaches scores positionally — a row reorder here would
+ # cross-write scores to the wrong sessions.
+ out = feature_matrix(feature_frame, feature_names=feature_names_for_tests)
+ first = feature_names_for_tests[0]
+ pd.testing.assert_series_equal(out[first], feature_frame[first])
+
+ def test_reorders_to_trained_order(
+ self, feature_frame: pd.DataFrame, feature_names_for_tests: tuple[str, ...]
+ ) -> None:
+ # Even if the input frame has features in a different order (e.g. CH
+ # returns them in a different sequence after a refactor), feature_matrix
+ # must hand back columns in the trained order so DMatrix construction
+ # is consistent.
+ shuffled_cols = list(reversed(feature_names_for_tests))
+ out = feature_matrix(feature_frame.loc[:, shuffled_cols], feature_names=feature_names_for_tests)
+ assert list(out.columns) == list(feature_names_for_tests)
+
+
+class TestAssertRangesCover:
+ def test_passes_when_every_name_has_a_range(self) -> None:
+ # The test fixture is exactly `FEATURE_RANGES.keys()` — should always pass.
+ assert_ranges_cover(tuple(FEATURE_RANGES.keys()))
+
+ def test_passes_for_subset_of_ranges(self) -> None:
+ # A retrained booster might use fewer features than `FEATURE_RANGES`
+ # covers (e.g. dropped a low-importance one). Only "missing" coverage
+ # is an error; "extra" range entries are dead-but-harmless.
+ first_three = tuple(list(FEATURE_RANGES.keys())[:3])
+ assert_ranges_cover(first_three)
+
+ def test_raises_when_booster_declares_uncovered_feature(self) -> None:
+ # Booster ships with a name that has no FEATURE_RANGES entry → operator
+ # forgot to add the runtime range contract for the new feature.
+ with pytest.raises(MissingFeatureRangeError, match="bogus_new_feature"):
+ assert_ranges_cover(("event_rate", "bogus_new_feature"))
+
+ def test_raises_when_booster_has_no_feature_names(self) -> None:
+ # Model was trained without explicit feature_names — serving cannot
+ # match SELECT aliases against a nameless schema.
+ with pytest.raises(MissingFeatureRangeError, match="no feature_names"):
+ assert_ranges_cover(())
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_publish_scores.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_publish_scores.py
new file mode 100644
index 000000000000..ac1748f0276b
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_publish_scores.py
@@ -0,0 +1,194 @@
+"""Tests for the Kafka writeback path in `score_chunk_activity`.
+
+`_publish_scores` produces JSONEachRow messages onto
+`KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS` — the same topic ingestion uses. The
+existing `session_replay_events_mv` merges the partial row into the real session
+row via `max(surfacing_score)` on the AggregatingMergeTree side. We
+verify three pieces of the contract:
+
+1. Payload shape matches what `kafka_session_replay_events` + the MV expect:
+ every column the Kafka table has, with identity values for non-score fields
+ so the partial row never corrupts the real session's aggregates.
+2. `distinct_id` is carried through faithfully — it's the sharding key on
+ `writable_session_replay_events`, so a wrong value would route the partial
+ row to a different shard than the real session rows.
+3. Per-row produce + final flush — the activity must not return until every
+ message has been ack'd by the broker, otherwise the workflow happily reports
+ `scored=N` while messages are still buffered in librdkafka.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import pytest
+from unittest import mock
+
+import numpy as np
+import pandas as pd
+
+from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS
+from posthog.temporal.session_replay.surfacing_scoring_sweep.activities import _publish_scores
+from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import KAFKA_PRODUCE_FLUSH_TIMEOUT_S
+
+ACTIVITIES_MODULE = "posthog.temporal.session_replay.surfacing_scoring_sweep.activities"
+
+
+def _producer_mock(get_producer_mock: mock.MagicMock) -> mock.MagicMock:
+ producer = get_producer_mock.return_value
+ producer.flush.return_value = 0
+ return producer
+
+
+def id_frame() -> pd.DataFrame:
+ """A minimal frame with the four ID columns `_publish_scores` reads from."""
+ return pd.DataFrame(
+ {
+ "team_id": [1, 2, 42],
+ "session_id": [
+ "01939d3e-7c80-7b56-bf8d-1e74e5c3b3a1",
+ "01939d3e-7c80-7b56-bf8d-1e74e5c3b3a2",
+ "01939d3e-7c80-7b56-bf8d-1e74e5c3b3a3",
+ ],
+ "distinct_id": ["user-a", "user-b", "user-c"],
+ "min_first_timestamp": pd.to_datetime(
+ [
+ "2026-05-07 10:00:00+00:00",
+ "2026-05-07 10:01:00+00:00",
+ "2026-05-07 10:02:00+00:00",
+ ]
+ ),
+ }
+ )
+
+
+class TestPublishScores:
+ def test_no_rows_skips_producer_entirely(self) -> None:
+ empty = pd.DataFrame({"team_id": [], "session_id": [], "distinct_id": [], "min_first_timestamp": []})
+ with mock.patch(f"{ACTIVITIES_MODULE}.get_producer") as get_producer_mock:
+ published = _publish_scores(empty, np.empty(0, dtype=np.float32))
+ assert published == 0
+ # Empty frame → no producer resolution. Avoids creating the
+ # singleton in unit tests that don't exercise the topic.
+ get_producer_mock.assert_not_called()
+
+ def test_publishes_one_message_per_row_and_flushes_once(self, id_frame: pd.DataFrame) -> None:
+ scores = np.array([0.1, 0.5, 0.9], dtype=np.float32)
+ with mock.patch(f"{ACTIVITIES_MODULE}.get_producer") as get_producer_mock:
+ producer = _producer_mock(get_producer_mock)
+ published = _publish_scores(id_frame, scores)
+
+ assert published == 3
+ assert producer.produce.call_count == 3
+
+ # Topic fixed across all rows; routes to KafkaClusterProfile.REPLAY.
+ for call in producer.produce.call_args_list:
+ assert call.kwargs["topic"] == KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS
+
+ # One get_producer() lookup for the loop, none for flush (we reuse
+ # the same singleton). flush is called once after the loop.
+ get_producer_mock.assert_called_once_with(topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS)
+ producer.flush.assert_called_once_with(timeout=KAFKA_PRODUCE_FLUSH_TIMEOUT_S)
+
+ def test_payload_carries_score_and_distinct_id(self, id_frame: pd.DataFrame) -> None:
+ """The score and distinct_id are the only two non-identity fields in the payload."""
+ scores = np.array([0.1, 0.5, 0.9], dtype=np.float32)
+ with mock.patch(f"{ACTIVITIES_MODULE}.get_producer") as get_producer_mock:
+ _producer_mock(get_producer_mock)
+ _publish_scores(id_frame, scores)
+
+ payloads = [call.kwargs["data"] for call in get_producer_mock.return_value.produce.call_args_list]
+ assert [p["session_id"] for p in payloads] == [
+ "01939d3e-7c80-7b56-bf8d-1e74e5c3b3a1",
+ "01939d3e-7c80-7b56-bf8d-1e74e5c3b3a2",
+ "01939d3e-7c80-7b56-bf8d-1e74e5c3b3a3",
+ ]
+ assert [p["team_id"] for p in payloads] == [1, 2, 42]
+ assert [p["distinct_id"] for p in payloads] == ["user-a", "user-b", "user-c"]
+ assert [p["surfacing_score"] for p in payloads] == [
+ pytest.approx(0.1, rel=1e-5),
+ pytest.approx(0.5, rel=1e-5),
+ pytest.approx(0.9, rel=1e-5),
+ ]
+
+ def test_identity_values_preserve_aggregates(self, id_frame: pd.DataFrame) -> None:
+ """Every non-score column uses identity values so the partial row
+ cannot corrupt the real session's aggregates on the MV side.
+
+ See `_build_partial_row` for the per-column rationale — this test pins
+ the contract so a future "let's just send last_timestamp=now()"
+ change blows up loudly.
+ """
+ with mock.patch(f"{ACTIVITIES_MODULE}.get_producer") as get_producer_mock:
+ _producer_mock(get_producer_mock)
+ _publish_scores(id_frame, np.array([0.42, 0.42, 0.42], dtype=np.float32))
+
+ for call in get_producer_mock.return_value.produce.call_args_list:
+ payload = call.kwargs["data"]
+ # Null arrays / strings → MV's groupArray/argMin drops them.
+ assert payload["block_url"] is None
+ assert payload["first_url"] is None
+ assert payload["snapshot_source"] is None
+ assert payload["snapshot_library"] is None
+ assert payload["retention_period_days"] is None
+ assert payload["urls"] == []
+ assert payload["ai_tags_fixed"] == []
+ assert payload["ai_tags_freeform"] == []
+ # sum() identity = 0.
+ assert payload["click_count"] == 0
+ assert payload["keypress_count"] == 0
+ assert payload["mouse_activity_count"] == 0
+ assert payload["active_milliseconds"] == 0
+ assert payload["console_log_count"] == 0
+ assert payload["console_warn_count"] == 0
+ assert payload["console_error_count"] == 0
+ assert payload["size"] == 0
+ assert payload["event_count"] == 0
+ assert payload["message_count"] == 0
+ # max(UInt8) identity = 0.
+ assert payload["is_deleted"] == 0
+ assert payload["ai_highlighted"] == 0
+
+ def test_timestamps_use_session_start_plus_one_microsecond(self) -> None:
+ """The partial row's first/last_timestamp = min_first_timestamp + 1µs.
+
+ That guarantees min(first_timestamp) and argMin(first_url, first_timestamp)
+ on the MV side keep the real session's earliest row over our partial row.
+ """
+ session_start = datetime(2026, 5, 7, 10, 0, 0, tzinfo=UTC)
+ df = pd.DataFrame(
+ {
+ "team_id": [7],
+ "session_id": ["sess-1"],
+ "distinct_id": ["user-z"],
+ "min_first_timestamp": pd.to_datetime([session_start]),
+ }
+ )
+ with mock.patch(f"{ACTIVITIES_MODULE}.get_producer") as get_producer_mock:
+ _producer_mock(get_producer_mock)
+ _publish_scores(df, np.array([0.42], dtype=np.float32))
+
+ (call,) = get_producer_mock.return_value.produce.call_args_list
+ payload = call.kwargs["data"]
+ assert payload["first_timestamp"] == "2026-05-07 10:00:00.000001"
+ assert payload["last_timestamp"] == "2026-05-07 10:00:00.000001"
+
+ def test_flush_timeout_raises_for_activity_retry(self, id_frame: pd.DataFrame) -> None:
+ with mock.patch(f"{ACTIVITIES_MODULE}.get_producer") as get_producer_mock:
+ producer = get_producer_mock.return_value
+ producer.flush.return_value = 2
+ with pytest.raises(RuntimeError, match="not delivered"):
+ _publish_scores(id_frame, np.array([0.1, 0.5, 0.9], dtype=np.float32))
+
+ def test_score_dtype_is_python_float(self, id_frame: pd.DataFrame) -> None:
+ # confluent-kafka-python's JSON serializer can't handle numpy scalars —
+ # `float(score)` is the cast that protects us. Pin the behavior so a
+ # future "optimization" doesn't pass np.float32 straight through.
+ scores = np.array([0.1, 0.5, 0.9], dtype=np.float32)
+ with mock.patch(f"{ACTIVITIES_MODULE}.get_producer") as get_producer_mock:
+ _producer_mock(get_producer_mock)
+ _publish_scores(id_frame, scores)
+ for call in get_producer_mock.return_value.produce.call_args_list:
+ score = call.kwargs["data"]["surfacing_score"]
+ assert type(score) is float
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_schedule.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_schedule.py
new file mode 100644
index 000000000000..cda19f8fb835
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_schedule.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+from django.conf import settings
+
+from temporalio.client import ScheduleActionStartWorkflow
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import (
+ SCHEDULE_INTERVAL,
+ WORKFLOW_EXECUTION_TIMEOUT,
+ WORKFLOW_NAME,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.schedule import _build_schedule
+
+
+def _start_workflow_action() -> ScheduleActionStartWorkflow:
+ action = _build_schedule().action
+ assert isinstance(action, ScheduleActionStartWorkflow)
+ return action
+
+
+class TestSurfacingScoringSchedule:
+ def test_schedule_targets_dedicated_task_queue(self) -> None:
+ assert _start_workflow_action().task_queue == settings.SURFACING_SCORING_SWEEP_TASK_QUEUE
+
+ def test_schedule_starts_score_sessions_batch_workflow(self) -> None:
+ assert _start_workflow_action().workflow == WORKFLOW_NAME
+
+ def test_schedule_skips_overlapping_ticks(self) -> None:
+ from temporalio.client import ScheduleOverlapPolicy
+
+ schedule = _build_schedule()
+ assert schedule.policy.overlap == ScheduleOverlapPolicy.SKIP
+
+ def test_schedule_interval_and_execution_timeout(self) -> None:
+ schedule = _build_schedule()
+ action = schedule.action
+ assert isinstance(action, ScheduleActionStartWorkflow)
+ assert schedule.spec.intervals[0].every == SCHEDULE_INTERVAL
+ assert action.execution_timeout == WORKFLOW_EXECUTION_TIMEOUT
+
+ def test_schedule_is_wired_into_deploy_registry(self) -> None:
+ # Without this entry the schedule is never upserted on deploy and the
+ # workflow never fires. Guards that exact regression.
+ from posthog.temporal.schedule import schedules # noqa: PLC0415 — heavy registry import, kept off module load
+ from posthog.temporal.session_replay.surfacing_scoring_sweep.schedule import ( # noqa: PLC0415
+ create_surfacing_scoring_sweep_schedule,
+ )
+
+ assert create_surfacing_scoring_sweep_schedule in schedules
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
new file mode 100644
index 000000000000..f24dc788e603
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_score_chunk_pipeline_clickhouse.py
@@ -0,0 +1,210 @@
+"""End-to-end check that fetch → validate → predict works against real ClickHouse.
+
+Booster comes from the `surfacing_booster_path` fixture (prod uses S3).
+Catches SQL/booster schema drift the static `test_sql_alignment.py` can't —
+specifically dtype-from-CH bugs.
+
+Prereqs that the local CH database needs:
+ * `surfacing_score` column on `session_replay_events` (added by an
+ ALTER migration that ships alongside this test).
+ * `session_replay_features` populated with at least the columns the model
+ reads (every feature this test inserts is in the live DDL today).
+
+What the test deliberately does NOT cover:
+ * Kafka writeback (`_publish_scores`) — that's covered by `test_publish_scores.py`.
+ * Multi-chunk fan-out — `test_score_chunk_activity_unit.py` would, the workflow
+ shape itself is a separate test surface.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+from posthog.clickhouse.client import sync_execute
+from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL
+from posthog.session_recordings.sql.session_replay_feature_sql import TRUNCATE_SESSION_REPLAY_FEATURES_TABLE_SQL
+from posthog.temporal.session_replay.surfacing_scoring_sweep.activities import _fetch_features_dataframe
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import ID_COLUMNS, validate_features
+from posthog.temporal.session_replay.surfacing_scoring_sweep.scorer import get_feature_names, predict
+from posthog.temporal.session_replay.surfacing_scoring_sweep.types import ChunkSpec
+from posthog.temporal.tests.session_replay.surfacing_scoring_sweep.ch_insert_helpers import insert_session_replay_event
+
+
[email protected]("surfacing_booster_path")
+class TestScoreChunkPipelineClickhouse(ClickhouseTestMixin, BaseTest):
+ """One realistic session, full pipeline, synthetic booster."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ # Both target tables aren't in posthog/conftest.py's truncate list —
+ # other tests can leave residue around. Wipe them before every run so
+ # the assertions on row counts / scores don't get poisoned.
+ sync_execute(TRUNCATE_SESSION_REPLAY_FEATURES_TABLE_SQL())
+ sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())
+
+ # Fresh UUID per test → timestamp is "now-ish", which the SQL's
+ # `min_first_timestamp >= now() - INTERVAL N DAY` filter requires.
+ self.session_id: str = str(uuid.uuid4())
+ self.distinct_id: str = "d1"
+ self.session_start: datetime = datetime.now(tz=UTC) - timedelta(seconds=30)
+
+ def _seed_unscored_session(self) -> None:
+ """Insert a NULL-score session_replay_events row matching self.session_id.
+
+ Mirrors what real ingestion writes (one chunk row with min/max timestamps)
+ but leaves surfacing_score NULL so the HAVING filter picks the row up.
+ """
+ insert_session_replay_event(
+ team_id=self.team.id,
+ session_id=self.session_id,
+ distinct_id=self.distinct_id,
+ start=self.session_start,
+ )
+
+ def _seed_replay_features(self) -> None:
+ """Insert one session_replay_features row with realistic-ish counts.
+
+ Values are chosen to make every derived rate non-trivial (so the
+ booster sees signal, not all-zeros) and to exercise both numerator
+ and denominator inputs to each rate/ratio. Anything we don't insert
+ defaults to 0 (SimpleAggregateFunction(sum, ...) initial state),
+ which surfaces as NaN after a `nullIf(_, 0)` divide — which the
+ validator passes through and XGBoost handles natively.
+ """
+ sync_execute(
+ "INSERT INTO writable_session_replay_features ("
+ " session_id, team_id, distinct_id,"
+ " min_first_timestamp, max_last_timestamp,"
+ # 30s session, lots of activity → non-zero rates
+ " event_count, click_count, keypress_count, mouse_activity_count,"
+ " scroll_event_count, page_visit_count, text_selection_count,"
+ " rage_click_count, dead_click_count, quick_back_count,"
+ " console_error_count, console_error_after_click_count,"
+ " network_request_count, network_failed_request_count,"
+ # Mouse stats — sums match what'd come out of a real session
+ " mouse_position_count, mouse_sum_x, mouse_sum_x_squared,"
+ " mouse_sum_y, mouse_sum_y_squared,"
+ " mouse_distance_traveled, mouse_direction_change_count,"
+ " mouse_velocity_sum, mouse_velocity_sum_of_squares, mouse_velocity_count,"
+ # Scroll stats
+ " total_scroll_magnitude, scroll_direction_reversal_count,"
+ " rapid_scroll_reversal_count, max_scroll_y,"
+ # Action gap stats
+ " inter_action_gap_count, inter_action_gap_sum_ms,"
+ " inter_action_gap_sum_of_squares_ms, max_idle_gap_ms,"
+ # Network duration stats
+ " network_request_duration_sum, network_request_duration_sum_of_squares,"
+ " network_request_duration_count"
+ ") SELECT "
+ " %(session_id)s, %(team_id)s, %(distinct_id)s,"
+ " now64(6) - INTERVAL 30 SECOND, now64(6),"
+ " 250, 12, 80, 200,"
+ " 60, 5, 8,"
+ " 0, 1, 2,"
+ " 3, 1,"
+ " 30, 1,"
+ " 150, 75000, 45000000,"
+ " 60000, 36000000,"
+ " 4500.5, 30,"
+ " 500.0, 2000.0, 50,"
+ " 1200.0, 4, 1, 1800.0,"
+ " 20, 5000.0, 1500000.0, 4500.0,"
+ " 3000.0, 400000.0, 30",
+ {"session_id": self.session_id, "team_id": self.team.id, "distinct_id": self.distinct_id},
+ )
+
+ def test_full_pipeline_produces_score_in_unit_interval(self) -> None:
+ self._seed_unscored_session()
+ self._seed_replay_features()
+
+ # of_chunks=1 puts every session in the single bucket (cityHash64 % 1 = 0)
+ # so we don't need to predict which bucket SESSION_ID lands in.
+ spec = ChunkSpec(chunk_id=0, of_chunks=1, chunk_size=10, lookback_days=7)
+ df = _fetch_features_dataframe(spec)
+
+ feature_names = get_feature_names()
+
+ # Shape contract: ID columns + every booster feature, exactly the row count we seeded.
+ assert len(df) == 1, f"expected 1 row from the SELECT, got {len(df)}"
+ for col in ID_COLUMNS:
+ assert col in df.columns, f"id column {col!r} missing from SELECT output"
+ for name in feature_names:
+ assert name in df.columns, f"feature {name!r} missing from SELECT output"
+
+ # ID columns must round-trip the values we seeded — these are what the
+ # producer relies on (shard routing + identity-value timestamp).
+ row = df.iloc[0]
+ assert str(row["session_id"]) == self.session_id
+ assert int(row["team_id"]) == self.team.id
+ assert str(row["distinct_id"]) == self.distinct_id
+ assert row["min_first_timestamp"] is not None
+
+ # The validator is the same gate the production activity uses — if
+ # this raises, the SQL drifted from the booster (which `test_sql_alignment.py`
+ # would also catch, but proving it on real CH output covers dtype-from-CH bugs
+ # the static test can't).
+ validate_features(df, feature_names=feature_names)
+
+ scores = predict(df)
+ assert scores.shape == (1,)
+ score = float(scores[0])
+ assert 0.0 <= score <= 1.0, f"booster returned out-of-range score {score}"
+
+ def test_session_without_replay_features_is_inner_joined_out(self) -> None:
+ self._seed_unscored_session()
+
+ spec = ChunkSpec(chunk_id=0, of_chunks=1, chunk_size=10, lookback_days=7)
+ df = _fetch_features_dataframe(spec)
+
+ assert df.empty, "INNER JOIN should drop sessions with no replay features"
+
+ def test_already_scored_session_is_excluded(self) -> None:
+ insert_session_replay_event(
+ team_id=self.team.id,
+ session_id=self.session_id,
+ distinct_id=self.distinct_id,
+ start=self.session_start,
+ surfacing_score=0.75,
+ )
+ 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_stale_features_outside_lookback_are_excluded(self) -> None:
+ self._seed_unscored_session()
+ sync_execute(
+ "INSERT INTO writable_session_replay_features ("
+ " session_id, team_id, distinct_id, min_first_timestamp, max_last_timestamp, event_count"
+ ") SELECT %(session_id)s, %(team_id)s, %(distinct_id)s, "
+ "now64(6) - INTERVAL 30 DAY, now64(6) - INTERVAL 29 DAY, 100",
+ {"session_id": self.session_id, "team_id": self.team.id, "distinct_id": self.distinct_id},
+ )
+
+ spec = ChunkSpec(chunk_id=0, of_chunks=1, chunk_size=10, lookback_days=7)
+ df = _fetch_features_dataframe(spec)
+ assert df.empty
+
+ def test_hash_partitioning_respects_chunk_id(self) -> None:
+ self._seed_unscored_session()
+ self._seed_replay_features()
+
+ matching_chunk = None
+ for chunk_id in range(8):
+ spec = ChunkSpec(chunk_id=chunk_id, of_chunks=8, chunk_size=10, lookback_days=7)
+ if not _fetch_features_dataframe(spec).empty:
+ matching_chunk = chunk_id
+ break
+
+ assert matching_chunk is not None, "session should land in exactly one hash bucket"
+
+ for chunk_id in range(8):
+ if chunk_id == matching_chunk:
+ continue
+ spec = ChunkSpec(chunk_id=chunk_id, of_chunks=8, chunk_size=10, lookback_days=7)
+ assert _fetch_features_dataframe(spec).empty
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_scorer.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_scorer.py
new file mode 100644
index 000000000000..c5ca944e7474
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_scorer.py
@@ -0,0 +1,238 @@
+"""Integration tests for `surfacing_scoring_sweep.scorer`.
+
+Boosters come from the shared `surfacing_booster_path` fixture (binary:logistic
+on `FEATURE_RANGES.keys()`) or are trained inline via `train_synthetic_booster`
+when a test needs a custom shape (regression objective, custom feature set, etc).
+
+Singleton cleanup is autouse from conftest.py — tests just set env vars and call.
+"""
+
+from __future__ import annotations
+
+import threading
+from pathlib import Path
+
+import pytest
+from unittest import mock
+
+import numpy as np
+import pandas as pd
+import xgboost as xgb
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep import scorer as scorer_mod
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import FEATURE_RANGES, MissingFeatureRangeError
+from posthog.temporal.session_replay.surfacing_scoring_sweep.scorer import (
+ ScoreRangeError,
+ _load_booster,
+ get_feature_names,
+ predict,
+ warmup,
+)
+from posthog.temporal.tests.session_replay.surfacing_scoring_sweep.conftest import (
+ train_synthetic_booster,
+ wire_booster_as_s3,
+)
+
+_TRAINING_FEATURE_NAMES: tuple[str, ...] = tuple(FEATURE_RANGES.keys())
+
+
+def regression_model_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """`reg:squarederror` booster with labels in [0, 100] — predicts > 1, trips ScoreRangeError."""
+ rng = np.random.default_rng(7)
+ data = rng.random((128, len(_TRAINING_FEATURE_NAMES))).astype(np.float32)
+ df = pd.DataFrame(data, columns=list(_TRAINING_FEATURE_NAMES))
+ labels = (df[_TRAINING_FEATURE_NAMES[0]] * 100).to_numpy() # [0, 100] → predicts well above 1
+ dmat = xgb.DMatrix(df, label=labels, feature_names=list(_TRAINING_FEATURE_NAMES))
+ booster = xgb.train(
+ {"objective": "reg:squarederror", "max_depth": 2, "eta": 0.5, "verbosity": 0},
+ dmat,
+ num_boost_round=2,
+ )
+ model_path = tmp_path / "regression_model.ubj"
+ booster.save_model(str(model_path))
+ wire_booster_as_s3(monkeypatch, model_path)
+ return model_path
+
+
+class TestModelLoading:
+ def test_load_booster_loads_from_s3(self, surfacing_booster_path: Path) -> None:
+ booster = _load_booster()
+ # If load failed, _load_booster would raise; getting a Booster back is
+ # the main assertion. num_features is a cheap sanity probe.
+ assert booster.num_features() == len(_TRAINING_FEATURE_NAMES)
+
+ def test_load_booster_caches_singleton(self, surfacing_booster_path: Path) -> None:
+ # The hot path (every chunk's predict) hits this. It must hand back
+ # the same Booster object on every call, not re-load from disk.
+ first = _load_booster()
+ second = _load_booster()
+ third = _load_booster()
+ assert first is second is third
+
+ def test_load_booster_thread_safe(self, surfacing_booster_path: Path) -> None:
+ # If `max_concurrent_activities > 1`, the first chunks contend on
+ # _load_booster simultaneously. The double-checked lock must produce
+ # exactly one booster. We probe for that by snapshotting the cache
+ # mid-flight from many threads and asserting they all converge.
+ boosters = []
+ barrier = threading.Barrier(8)
+
+ def worker() -> None:
+ barrier.wait()
+ boosters.append(_load_booster())
+
+ threads = [threading.Thread(target=worker) for _ in range(8)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert len(boosters) == 8
+ assert all(b is boosters[0] for b in boosters)
+
+ def test_warmup_loads_eagerly(self, surfacing_booster_path: Path) -> None:
+ assert scorer_mod._BOOSTER is None
+ warmup()
+ assert scorer_mod._BOOSTER is not None
+
+ def test_load_booster_raises_when_s3_returns_none(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # If S3 returns None (object missing), we must raise loudly so the
+ # operator sees the misconfig instead of getting silent NaN scores.
+ monkeypatch.setenv("SESSION_INTERESTINGNESS_MODEL_S3_URI", "s3://bucket/missing.ubj")
+ monkeypatch.setattr(
+ "posthog.temporal.session_replay.surfacing_scoring_sweep.scorer.object_storage.read_bytes",
+ lambda key, *, bucket=None: None,
+ )
+ with pytest.raises(FileNotFoundError):
+ _load_booster()
+
+ def test_load_booster_raises_when_no_env_set(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("SESSION_INTERESTINGNESS_MODEL_S3_URI", raising=False)
+ with pytest.raises(scorer_mod.ModelNotConfiguredError):
+ _load_booster()
+
+ def test_load_booster_fetches_once_and_caches(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ # The fetch is cached in _S3_CACHED_PATH; a second _load_booster call
+ # must not re-fetch from S3 (would defeat the per-pod-once design).
+ booster = train_synthetic_booster(_TRAINING_FEATURE_NAMES, seed=11)
+ src = tmp_path / "from_s3.ubj"
+ booster.save_model(str(src))
+ payload = src.read_bytes()
+
+ monkeypatch.setenv("SESSION_INTERESTINGNESS_MODEL_S3_URI", "s3://my-bucket/path/to/model.ubj")
+ with mock.patch(
+ "posthog.temporal.session_replay.surfacing_scoring_sweep.scorer.object_storage.read_bytes",
+ return_value=payload,
+ ) as read_bytes_mock:
+ loaded = _load_booster()
+ _load_booster()
+ assert loaded.num_features() == len(_TRAINING_FEATURE_NAMES)
+ read_bytes_mock.assert_called_once_with("path/to/model.ubj", bucket="my-bucket")
+
+ @pytest.mark.parametrize("uri", ["model.ubj", "s3://only-bucket", "s3:///key-only", "http://wrong/scheme"])
+ def test_load_booster_rejects_malformed_s3_uri(self, monkeypatch: pytest.MonkeyPatch, uri: str) -> None:
+ monkeypatch.setenv("SESSION_INTERESTINGNESS_MODEL_S3_URI", uri)
+ with pytest.raises(ValueError, match="SESSION_INTERESTINGNESS_MODEL_S3_URI"):
+ _load_booster()
+
+
+class TestGetFeatureNames:
+ def test_returns_booster_feature_names(self, surfacing_booster_path: Path) -> None:
+ # The booster IS the source of truth — get_feature_names must hand
+ # back exactly what training pinned in the model file, in order.
+ names = get_feature_names()
+ assert names == _TRAINING_FEATURE_NAMES
+
+ def test_triggers_lazy_load_on_first_call(self, surfacing_booster_path: Path) -> None:
+ assert scorer_mod._BOOSTER is None
+ get_feature_names()
+ assert scorer_mod._BOOSTER is not None
+
+ def test_caches_after_first_load(self, surfacing_booster_path: Path) -> None:
+ # Per-predict overhead matters; `_FEATURE_NAMES` is a cached tuple so
+ # we don't pay a C++ -> Python attr crossing on every chunk.
+ first = get_feature_names()
+ second = get_feature_names()
+ assert first is second # exact same tuple object
+
+ def test_load_raises_when_booster_has_features_outside_ranges(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ # A retrained booster that introduces a feature without a
+ # FEATURE_RANGES entry must fail at warmup, not on the first chunk —
+ # otherwise the validator wouldn't know what to bounds-check against
+ # and bad CH output for the new column would slip through silently.
+ booster = train_synthetic_booster(("event_rate", "bogus_new_feature"), seed=0, rows=64)
+ model_path = tmp_path / "uncovered_model.ubj"
+ booster.save_model(str(model_path))
+ wire_booster_as_s3(monkeypatch, model_path)
+
+ with pytest.raises(MissingFeatureRangeError, match="bogus_new_feature"):
+ _load_booster()
+
+
+class TestPredict:
+ def test_predict_returns_scores_in_unit_interval(
+ self, surfacing_booster_path: Path, feature_frame: pd.DataFrame
+ ) -> None:
+ # Booster was trained binary:logistic — every prediction must land in [0, 1].
+ scores = predict(feature_frame)
+
+ assert isinstance(scores, np.ndarray)
+ assert scores.dtype == np.float32
+ assert scores.shape == (len(feature_frame),)
+ assert scores.min() >= 0.0
+ assert scores.max() <= 1.0
+
+ def test_predict_handles_nan_features(self, surfacing_booster_path: Path, feature_frame: pd.DataFrame) -> None:
+ # Our SQL produces NaN when denominators are zero (nullIf(...)).
+ # XGBoost handles NaN natively; predict must not raise or crash.
+ feature_frame.loc[0, "event_rate"] = float("nan")
+ feature_frame.loc[1, "mouse_velocity_mean"] = float("nan")
+
+ scores = predict(feature_frame)
+
+ assert np.isfinite(scores).all()
+
+ def test_predict_with_id_columns_alongside_features(
+ self, surfacing_booster_path: Path, feature_frame: pd.DataFrame
+ ) -> None:
+ # The CH SELECT returns id columns + features mixed together. predict
+ # delegates to feature_matrix, which strips ids; this end-to-end test
+ # protects that contract.
+ df = feature_frame.copy()
+ df["team_id"] = 42
+ df["session_id"] = "00000000-0000-7000-0000-000000000000"
+ df["distinct_id"] = "user-1"
+ df["min_first_timestamp"] = pd.Timestamp("2026-01-01")
+
+ scores = predict(df)
+
+ assert scores.shape == (len(feature_frame),)
+
+ def test_predict_is_invariant_to_input_column_order(
+ self, surfacing_booster_path: Path, feature_frame: pd.DataFrame
+ ) -> None:
+ # We pass feature_names into DMatrix so XGBoost reorders by name, not
+ # position. That means we get the same scores regardless of how the
+ # caller orders the columns — a regression here would silently mis-score.
+ scores_a = predict(feature_frame)
+ shuffled = feature_frame.loc[:, list(reversed(_TRAINING_FEATURE_NAMES))]
+ scores_b = predict(shuffled)
+
+ np.testing.assert_array_equal(scores_a, scores_b)
+
+ def test_predict_empty_dataframe(self, surfacing_booster_path: Path) -> None:
+ df = pd.DataFrame(columns=pd.Index(_TRAINING_FEATURE_NAMES))
+ scores = predict(df)
+ assert scores.shape == (0,)
+
+
+class TestPredictGuards:
+ def test_score_out_of_range_raises(self, regression_model_path: Path, feature_frame: pd.DataFrame) -> None:
+ # Training a regression model with labels in [0, 100] → predictions
+ # well above 1. predict must reject this loudly rather than write
+ # garbage scores into ClickHouse.
+ with pytest.raises(ScoreRangeError, match=r"outside \[0, 1\]"):
+ predict(feature_frame)
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_alignment.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_alignment.py
new file mode 100644
index 000000000000..dfe06108b970
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_alignment.py
@@ -0,0 +1,95 @@
+"""CI guard: fetch_features_sql(), FEATURE_RANGES, and a synthetic booster stay aligned.
+
+Prod model lives in S3; `assert_serving_schema_parity` re-runs at worker boot.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+import xgboost as xgb
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep.feature_schema import (
+ FeatureSchemaDriftError,
+ assert_booster_matches_sql,
+ assert_serving_schema_parity,
+ assert_sql_matches_feature_ranges,
+ get_sql_feature_names,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import FEATURE_RANGES
+from posthog.temporal.session_replay.surfacing_scoring_sweep.sql import feature_columns_in_select, fetch_features_sql
+from posthog.temporal.tests.session_replay.surfacing_scoring_sweep.conftest import train_synthetic_booster
+
+
+def _feature_names(model_path: Path) -> tuple[str, ...]:
+ booster = xgb.Booster()
+ booster.load_model(str(model_path))
+ return tuple(booster.feature_names or ())
+
+
+class TestServingFeatureSchemaParity:
+ def test_sql_select_aliases_match_feature_ranges(self) -> None:
+ assert_sql_matches_feature_ranges()
+
+ def test_sql_select_aliases_match_booster_feature_names(self, surfacing_booster_path: Path) -> None:
+ assert_booster_matches_sql(_feature_names(surfacing_booster_path))
+
+ def test_full_serving_schema_parity(self, surfacing_booster_path: Path) -> None:
+ assert_serving_schema_parity(_feature_names(surfacing_booster_path))
+
+ def test_every_feature_range_entry_is_produced_by_sql(self) -> None:
+ # FEATURE_RANGES is the documented universe of serving features; every
+ # entry must be a real SQL column (no stale entries). The booster is
+ # allowed to use a subset of these — that's covered below.
+ missing = set(FEATURE_RANGES.keys()) - set(get_sql_feature_names())
+ assert not missing, f"FEATURE_RANGES has entries the SQL never produces: {sorted(missing)}"
+
+ def test_strict_subset_booster_passes_parity(self) -> None:
+ # The production booster is simpler than the serving query: it scores a
+ # proper subset of the SQL's feature columns. The parity gate must
+ # accept that — the whole point of the superset contract.
+ sql_names = get_sql_feature_names()
+ subset = sql_names[::2]
+ assert set(subset) < set(sql_names), "test setup: subset must be proper"
+ booster = train_synthetic_booster(subset)
+ assert_serving_schema_parity(tuple(booster.feature_names or ()))
+
+ def test_booster_needing_unknown_feature_fails_parity(self) -> None:
+ # A booster that needs a column the SQL never produces is fatal drift.
+ booster = train_synthetic_booster((*get_sql_feature_names()[:4], "feature_the_sql_never_produces"))
+ with pytest.raises(FeatureSchemaDriftError, match="does not produce"):
+ assert_booster_matches_sql(tuple(booster.feature_names or ()))
+
+
+class TestFeatureColumnsInSelectParser:
+ """Self-tests for the regex parser that powers the parity check."""
+
+ def test_extracts_feature_aliases_from_real_sql(self) -> None:
+ aliases = get_sql_feature_names()
+ assert len(aliases) > 0
+ assert len(aliases) == len(set(aliases)), f"Duplicate aliases in SQL: {aliases}"
+
+ def test_ignores_id_columns(self) -> None:
+ aliases = feature_columns_in_select(fetch_features_sql())
+ assert "team_id" not in aliases
+ assert "session_id" not in aliases
+ assert "distinct_id" not in aliases
+ assert "min_first_timestamp" not in aliases
+
+ def test_returns_empty_tuple_on_malformed_input(self) -> None:
+ assert feature_columns_in_select("not a SQL statement at all") == ()
+
+ def test_respects_alias_argument(self) -> None:
+ synthetic = (
+ "WITH cte AS (SELECT 1)\n"
+ ") SELECT\n"
+ " e.team_id,\n"
+ " rf.feature_a,\n"
+ " other.ignored,\n"
+ " rf.feature_b\n"
+ "FROM eligible_sessions e"
+ )
+ assert feature_columns_in_select(synthetic, feature_table_alias="rf") == ("feature_a", "feature_b")
+ assert feature_columns_in_select(synthetic, feature_table_alias="other") == ("ignored",)
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
new file mode 100644
index 000000000000..9ddb7bc825ff
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_sql_clickhouse.py
@@ -0,0 +1,155 @@
+from __future__ import annotations
+
+import re
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+from posthog.clickhouse.client import sync_execute
+from posthog.session_recordings.sql.session_replay_feature_sql import TRUNCATE_SESSION_REPLAY_FEATURES_TABLE_SQL
+from posthog.temporal.session_replay.surfacing_scoring_sweep.sql import count_unscored_sql, fetch_features_sql
+from posthog.temporal.tests.session_replay.surfacing_scoring_sweep.ch_insert_helpers import (
+ insert_replay_features,
+ insert_session_replay_event,
+)
+
+
+class TestFetchFeaturesSqlShape:
+ def test_targets_session_replay_events(self) -> None:
+ sql = fetch_features_sql()
+ assert "FROM session_replay_events" in sql
+
+ def test_global_in_filters_on_team_id_and_session_id_tuple(self) -> None:
+ sql = fetch_features_sql()
+ assert "(f.team_id, f.session_id) GLOBAL IN" in sql
+
+ def test_aggregated_stats_filters_features_by_lookback(self) -> None:
+ sql = fetch_features_sql()
+ assert "f.min_first_timestamp >= now() - toIntervalDay(%(lookback_days)s)" in sql
+
+ def test_eligible_sessions_orders_before_limit(self) -> None:
+ sql = fetch_features_sql()
+ match = re.search(
+ r"eligible_sessions\s+AS\s+\(.*?ORDER BY\s+session_id\s+LIMIT\s+%\(chunk_size\)s",
+ sql,
+ re.DOTALL,
+ )
+ assert match is not None, "ORDER BY session_id must precede LIMIT in the eligible_sessions CTE"
+
+ def test_final_join_uses_team_id_and_session_id(self) -> None:
+ sql = fetch_features_sql()
+ assert "rf.team_id = e.team_id AND rf.session_id = e.session_id" in sql
+
+ def test_surfaces_distinct_id_and_min_first_timestamp(self) -> None:
+ sql = fetch_features_sql()
+ assert "any(distinct_id) AS distinct_id" in sql
+ assert "min(min_first_timestamp) AS started_at" in sql
+ assert "e.distinct_id," in sql
+ assert "e.started_at AS min_first_timestamp," in sql
+
+ def test_eligible_sessions_has_raw_row_prefilter_and_exact_having_cut(self) -> None:
+ sql = fetch_features_sql()
+ assert "AND min_first_timestamp >= now() - toIntervalDay(%(lookback_days)s + 1)" in sql
+ assert "AND started_at >= now() - toIntervalDay(%(lookback_days)s)" in sql
+
+ 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
+ assert "AND min(min_first_timestamp) >= now() - toIntervalDay(%(lookback_days)s)" in sql
+
+ def test_count_unscored_includes_lookback_and_chunking(self) -> None:
+ sql = count_unscored_sql()
+ assert "%(lookback_days)s" in sql
+ assert "%(of_chunks)s" in sql
+ assert "FROM session_replay_events" in sql
+
+
+class TestEligibleSessionsJoinClickhouse(ClickhouseTestMixin, BaseTest):
+ SESSION_ID = "01939d3e-7c80-7b56-bf8d-1e74e5c3b3a1"
+
+ def setUp(self) -> None:
+ super().setUp()
+ sync_execute(TRUNCATE_SESSION_REPLAY_FEATURES_TABLE_SQL())
+
+ def _insert_session_replay_event(
+ self,
+ *,
+ team_id: int,
+ session_id: str,
+ distinct_id: str = "d1",
+ surfacing_score: float | None = None,
+ ) -> None:
+ insert_session_replay_event(
+ team_id=team_id,
+ session_id=session_id,
+ distinct_id=distinct_id,
+ surfacing_score=surfacing_score,
+ )
+
+ def _insert_replay_features(self, *, team_id: int, session_id: str, event_count: int = 42) -> None:
+ insert_replay_features(team_id=team_id, session_id=session_id, event_count=event_count)
+
+ @staticmethod
+ def _eligible_sessions_join_sql() -> str:
+ return """
+ WITH eligible_sessions AS (
+ SELECT
+ team_id,
+ session_id,
+ any(distinct_id) AS distinct_id,
+ min(min_first_timestamp) AS min_first_timestamp
+ FROM session_replay_events
+ WHERE team_id = %(team_id)s
+ GROUP BY team_id, session_id
+ HAVING max(surfacing_score) IS NULL
+ ORDER BY session_id
+ LIMIT 100
+ )
+ SELECT e.team_id, e.session_id, e.distinct_id, sum(f.event_count) AS ec
+ FROM eligible_sessions e
+ INNER JOIN session_replay_features AS f
+ ON f.team_id = e.team_id AND f.session_id = e.session_id
+ WHERE (f.team_id, f.session_id) GLOBAL IN (
+ SELECT team_id, session_id FROM eligible_sessions
+ )
+ GROUP BY e.team_id, e.session_id, e.distinct_id
+ """
+
+ def test_join_matches_on_string_session_id(self) -> None:
+ self._insert_session_replay_event(team_id=self.team.id, session_id=self.SESSION_ID)
+ self._insert_replay_features(team_id=self.team.id, session_id=self.SESSION_ID, event_count=42)
+
+ rows = sync_execute(self._eligible_sessions_join_sql(), {"team_id": self.team.id})
+ assert len(rows) == 1
+ team_id, session_id, distinct_id, event_count = rows[0]
+ assert team_id == self.team.id
+ assert session_id == self.SESSION_ID
+ assert distinct_id == "d1"
+ assert event_count == 42
+
+ def test_team_id_isolation_in_join(self) -> None:
+ other_team_id = self.team.id + 9999
+ self._insert_session_replay_event(team_id=self.team.id, session_id=self.SESSION_ID)
+ self._insert_replay_features(team_id=other_team_id, session_id=self.SESSION_ID)
+
+ rows = sync_execute(self._eligible_sessions_join_sql(), {"team_id": self.team.id})
+ assert rows == []
+
+ def test_having_excludes_scored_sessions(self) -> None:
+ scored_session = "01939d3e-7c80-7b56-bf8d-1e74e5c3b3a2"
+ self._insert_session_replay_event(team_id=self.team.id, session_id=self.SESSION_ID)
+ self._insert_session_replay_event(team_id=self.team.id, session_id=scored_session, surfacing_score=0.5)
+ self._insert_replay_features(team_id=self.team.id, session_id=self.SESSION_ID)
+ self._insert_replay_features(team_id=self.team.id, session_id=scored_session)
+
+ rows = sync_execute(self._eligible_sessions_join_sql(), {"team_id": self.team.id})
+ assert len(rows) == 1
+ assert rows[0][1] == self.SESSION_ID
+
+ def test_count_unscored_excludes_scored_sessions(self) -> None:
+ scored_session = "01939d3e-7c80-7b56-bf8d-1e74e5c3b3a2"
+ self._insert_session_replay_event(team_id=self.team.id, session_id=self.SESSION_ID)
+ self._insert_session_replay_event(team_id=self.team.id, session_id=scored_session, surfacing_score=0.5)
+
+ rows = sync_execute(count_unscored_sql(), {"lookback_days": 365, "of_chunks": 1})
+ # Other tests may leave residual unscored sessions on shared CH state.
+ assert rows[0][0] >= 1
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_training_query_alignment.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_training_query_alignment.py
new file mode 100644
index 000000000000..e13ed02fc62a
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_training_query_alignment.py
@@ -0,0 +1,38 @@
+from __future__ import annotations
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep.feature_schema import get_sql_feature_names
+from posthog.temporal.session_replay.surfacing_scoring_sweep.sql import (
+ _AGGREGATED_STATS_FRAGMENT,
+ _REPLAY_FEATURES_FRAGMENT,
+ fetch_features_sql,
+)
+from posthog.temporal.tests.session_replay.surfacing_scoring_sweep.sql_alignment_helpers import (
+ feature_aliases_from_feature_select,
+ load_training_query_sql,
+ select_list_body,
+ training_aggregated_stat_aliases,
+ training_derived_feature_aliases,
+)
+
+
+class TestTrainingQueryAlignment:
+ def test_aggregated_stats_columns_match_training_query(self) -> None:
+ training = set(training_aggregated_stat_aliases())
+ serving = set(feature_aliases_from_feature_select(select_list_body(_AGGREGATED_STATS_FRAGMENT)))
+ assert serving - {"team_id"} == training
+
+ def test_derived_feature_expressions_match_training_query(self) -> None:
+ training = training_derived_feature_aliases()
+ serving = feature_aliases_from_feature_select(_REPLAY_FEATURES_FRAGMENT)
+ assert serving == training
+
+ def test_training_fixture_includes_features_lookback_filter(self) -> None:
+ sql = load_training_query_sql()
+ assert "f.min_first_timestamp >= now() - INTERVAL" in sql
+
+ def test_serving_sql_includes_features_lookback_filter(self) -> None:
+ sql = fetch_features_sql()
+ assert "f.min_first_timestamp >= now() - toIntervalDay(%(lookback_days)s)" in sql
+
+ def test_serving_feature_aliases_match_training_derived_features(self) -> None:
+ assert get_sql_feature_names() == training_derived_feature_aliases()
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_upload_surfacing_model.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_upload_surfacing_model.py
new file mode 100644
index 000000000000..9dfbdd13a24f
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_upload_surfacing_model.py
@@ -0,0 +1,75 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from unittest import mock
+
+from django.core.management.base import CommandError
+
+from posthog.management.commands.upload_surfacing_model import Command
+from posthog.temporal.session_replay.surfacing_scoring_sweep.features import FEATURE_RANGES
+from posthog.temporal.tests.session_replay.surfacing_scoring_sweep.conftest import train_synthetic_booster
+
+
+def valid_booster_path(tmp_path: Path) -> Path:
+ booster = train_synthetic_booster(tuple(FEATURE_RANGES.keys()))
+ path = tmp_path / "model.ubj"
+ booster.save_model(str(path))
+ return path
+
+
+def _run_upload(**options: object) -> None:
+ Command().handle(**options)
+
+
+class TestUploadSurfacingModelCommand:
+ def test_rejects_missing_file(self) -> None:
+ with pytest.raises(CommandError, match="does not exist"):
+ _run_upload(path="/tmp/definitely-missing-model.ubj", bucket=None, key="k.ubj", skip_validate=False)
+
+ def test_rejects_booster_with_schema_drift(self, tmp_path: Path) -> None:
+ # Drift now means a feature the SQL universe doesn't contain (a subset
+ # of real features is valid — see test_uploads_strict_subset_booster).
+ drifted = train_synthetic_booster(("event_rate", "feature_the_sql_never_produces"))
+ path = tmp_path / "drifted.ubj"
+ drifted.save_model(str(path))
+
+ with pytest.raises(CommandError, match="doesn't match current SQL/FEATURE_RANGES"):
+ _run_upload(path=str(path), bucket=None, key="k.ubj", skip_validate=False)
+
+ def test_uploads_valid_booster(self, valid_booster_path: Path) -> None:
+ with mock.patch(
+ "posthog.management.commands.upload_surfacing_model.object_storage.write_from_file"
+ ) as write_mock:
+ _run_upload(path=str(valid_booster_path), bucket="test-bucket", key="k.ubj", skip_validate=False)
+
+ write_mock.assert_called_once_with(file_name="k.ubj", file_path=str(valid_booster_path), bucket="test-bucket")
+
+ def test_uploads_strict_subset_booster(self, tmp_path: Path) -> None:
+ # The production booster scores a subset of the serving query's features;
+ # the upload validator must accept it.
+ subset = tuple(FEATURE_RANGES.keys())[::2]
+ booster = train_synthetic_booster(subset)
+ path = tmp_path / "subset.ubj"
+ booster.save_model(str(path))
+
+ with mock.patch(
+ "posthog.management.commands.upload_surfacing_model.object_storage.write_from_file"
+ ) as write_mock:
+ _run_upload(path=str(path), bucket="test-bucket", key="k.ubj", skip_validate=False)
+
+ write_mock.assert_called_once()
+
+ def test_skip_validate_bypasses_schema_check(self, tmp_path: Path) -> None:
+ drifted = train_synthetic_booster(("event_rate", "feature_the_sql_never_produces"))
+ path = tmp_path / "drifted.ubj"
+ drifted.save_model(str(path))
+
+ with mock.patch(
+ "posthog.management.commands.upload_surfacing_model.object_storage.write_from_file"
+ ) as write_mock:
+ _run_upload(path=str(path), bucket=None, key="k.ubj", skip_validate=True)
+
+ write_mock.assert_called_once()
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py
new file mode 100644
index 000000000000..bc2f8247795b
--- /dev/null
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py
@@ -0,0 +1,180 @@
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from unittest import mock
+
+import temporalio.worker
+from temporalio import activity
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Worker
+
+from posthog.temporal.session_replay.surfacing_scoring_sweep.constants import WORKFLOW_NAME
+from posthog.temporal.session_replay.surfacing_scoring_sweep.types import (
+ ChunkResult,
+ ChunkSpec,
+ ListChunksResult,
+ ScoreSessionsBatchInputs,
+ ScoreSessionsBatchResult,
+)
+from posthog.temporal.session_replay.surfacing_scoring_sweep.workflow import ScoreSessionsBatchWorkflow, _summarize
+
+
+def _plan(chunks: list[ChunkSpec], *, estimated: int = 0) -> ListChunksResult:
+ return ListChunksResult(chunks=chunks, estimated_unscored_sessions=estimated)
+
+
+def _chunk(chunk_id: int, *, of_chunks: int = 4) -> ChunkSpec:
+ return ChunkSpec(chunk_id=chunk_id, of_chunks=of_chunks, chunk_size=10, lookback_days=7)
+
+
+def _as_batch_result(result: ScoreSessionsBatchResult | dict[str, int]) -> ScoreSessionsBatchResult:
+ if isinstance(result, ScoreSessionsBatchResult):
+ return result
+ return ScoreSessionsBatchResult(**result)
+
+
+class TestSummarize:
+ def test_aggregates_scored_and_failed_chunks(self) -> None:
+ chunks = [_chunk(0), _chunk(1), _chunk(2)]
+ results: list[ChunkResult | BaseException] = [
+ ChunkResult(chunk_id=0, scored=3),
+ RuntimeError("ch timeout"),
+ ChunkResult(chunk_id=2, scored=7),
+ ]
+ with mock.patch("posthog.temporal.session_replay.surfacing_scoring_sweep.workflow.workflow.logger"):
+ summary = _summarize(chunks, results)
+ assert summary == ScoreSessionsBatchResult(total_scored=10, chunks_dispatched=3, chunks_failed=1)
+
+
+async def test_workflow_noop_when_plan_has_no_chunks() -> None:
+ @activity.defn(name="list_chunks_activity")
+ async def list_chunks_empty(_inputs: ScoreSessionsBatchInputs) -> ListChunksResult:
+ return _plan([])
+
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ScoreSessionsBatchWorkflow],
+ activities=[list_chunks_empty],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ WORKFLOW_NAME,
+ ScoreSessionsBatchInputs(),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ parsed = _as_batch_result(result)
+ assert parsed.total_scored == 0
+ assert parsed.chunks_dispatched == 0
+ assert parsed.chunks_failed == 0
+
+
+async def test_workflow_fans_out_chunks_and_aggregates_scores() -> None:
+ chunks = [_chunk(i) for i in range(4)]
+
+ @activity.defn(name="list_chunks_activity")
+ async def list_chunks_mocked(_inputs: ScoreSessionsBatchInputs) -> ListChunksResult:
+ return _plan(chunks, estimated=40)
+
+ @activity.defn(name="score_chunk_activity")
+ async def score_chunk_mocked(spec: ChunkSpec) -> ChunkResult:
+ return ChunkResult(chunk_id=spec.chunk_id, scored=spec.chunk_id + 1)
+
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ScoreSessionsBatchWorkflow],
+ activities=[list_chunks_mocked, score_chunk_mocked],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ WORKFLOW_NAME,
+ ScoreSessionsBatchInputs(),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ parsed = _as_batch_result(result)
+ assert parsed.chunks_dispatched == 4
+ assert parsed.chunks_failed == 0
+ assert parsed.total_scored == 1 + 2 + 3 + 4
+
+
+async def test_workflow_tolerates_partial_chunk_failures() -> None:
+ chunks = [_chunk(i) for i in range(3)]
+
+ @activity.defn(name="list_chunks_activity")
+ async def list_chunks_mocked(_inputs: ScoreSessionsBatchInputs) -> ListChunksResult:
+ return _plan(chunks)
+
+ @activity.defn(name="score_chunk_activity")
+ async def score_chunk_one_fails(spec: ChunkSpec) -> ChunkResult:
+ if spec.chunk_id == 1:
+ raise RuntimeError("slow shard")
+ return ChunkResult(chunk_id=spec.chunk_id, scored=5)
+
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ScoreSessionsBatchWorkflow],
+ activities=[list_chunks_mocked, score_chunk_one_fails],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ WORKFLOW_NAME,
+ ScoreSessionsBatchInputs(),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ parsed = _as_batch_result(result)
+ assert parsed.chunks_dispatched == 3
+ assert parsed.chunks_failed == 1
+ assert parsed.total_scored == 10
+
+
+async def test_workflow_survives_empty_chunk_results() -> None:
+ chunks = [_chunk(0), _chunk(1)]
+
+ @activity.defn(name="list_chunks_activity")
+ async def list_chunks_mocked(_inputs: ScoreSessionsBatchInputs) -> ListChunksResult:
+ return _plan(chunks)
+
+ @activity.defn(name="score_chunk_activity")
+ async def score_chunk_empty(spec: ChunkSpec) -> ChunkResult:
+ return ChunkResult(chunk_id=spec.chunk_id, scored=0)
+
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ScoreSessionsBatchWorkflow],
+ activities=[list_chunks_mocked, score_chunk_empty],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ WORKFLOW_NAME,
+ ScoreSessionsBatchInputs(),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ parsed = _as_batch_result(result)
+ assert parsed.total_scored == 0
+ assert parsed.chunks_failed == 0
+ assert parsed.chunks_dispatched == 2
diff --git a/pyproject.toml b/pyproject.toml
index dbf958a7691e..fb5cb636d5ac 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -148,6 +148,7 @@ dependencies = [
"umap-learn~=0.5.0",
"tbb==2022.3.1; sys_platform == 'linux' and platform_machine == 'x86_64'",
"whitenoise~=6.10.0",
+ "xgboost==3.2.0",
"xmlsec==1.3.17",
"zstd==1.5.7.2",
"zxcvbn==4.5.0",
diff --git a/uv.lock b/uv.lock
index 7085fb342e72..ab7d8ce75802 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4697,6 +4697,7 @@ name = "nvidia-nccl-cu12"
version = "2.27.3"
source = { registry = "https://pypi.org/simple" }
wheels = [
+ { url = "https://files.pythonhosted.org/packages/4b/7b/8354b784cf73b0ba51e566b4baba3ddd44fe8288a3d39ef1e06cd5417226/nvidia_nccl_cu12-2.27.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9ddf1a245abc36c550870f26d537a9b6087fb2e2e3d6e0ef03374c6fd19d984f", size = 322397768, upload-time = "2025-06-03T21:57:30.234Z" },
{ url = "https://files.pythonhosted.org/packages/5c/5b/4e4fff7bad39adf89f735f2bc87248c81db71205b62bcc0d5ca5b606b3c3/nvidia_nccl_cu12-2.27.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:adf27ccf4238253e0b826bce3ff5fa532d65fc42322c8bfdfaf28024c0fbe039", size = 322364134, upload-time = "2025-06-03T21:58:04.013Z" },
]
@@ -5687,6 +5688,7 @@ dependencies = [
{ name = "user-agents" },
{ name = "webauthn" },
{ name = "whitenoise" },
+ { name = "xgboost" },
{ name = "xmlsec" },
{ name = "zstd" },
{ name = "zxcvbn" },
@@ -5960,6 +5962,7 @@ requires-dist = [
{ name = "user-agents", specifier = "~=2.2.0" },
{ name = "webauthn", specifier = ">=2.1.0,<2.3.0" },
{ name = "whitenoise", specifier = "~=6.10.0" },
+ { name = "xgboost", specifier = "==3.2.0" },
{ name = "xmlsec", specifier = "==1.3.17" },
{ name = "zstd", specifier = "==1.5.7.2" },
{ name = "zxcvbn", specifier = "==4.5.0" },
@@ -9145,6 +9148,36 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/2d/82/f56956041adef78f849db6b289b282e72b55ab8045a75abad81898c28d19/wrapt-1.17.2-py3-none-any.whl", hash = "sha256:b18f2d1533a71f069c7f82d524a52599053d4c7166e9dd374ae2136b7f40f7c8", size = 23594, upload-time = "2025-01-14T10:35:44.018Z" },
]
+[[package]]
+name = "wsproto"
+version = "1.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "h11" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c9/4a/44d3c295350d776427904d73c189e10aeae66d7f555bb2feee16d1e4ba5a/wsproto-1.2.0.tar.gz", hash = "sha256:ad565f26ecb92588a3e43bc3d96164de84cd9902482b130d0ddbaa9664a85065", size = 53425, upload-time = "2022-08-23T19:58:21.447Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/78/58/e860788190eba3bcce367f74d29c4675466ce8dddfba85f7827588416f01/wsproto-1.2.0-py3-none-any.whl", hash = "sha256:b9acddd652b585d75b20477888c56642fdade28bdfd3579aa24a4d2c037dd736", size = 24226, upload-time = "2022-08-23T19:58:19.96Z" },
+]
+
+[[package]]
+name = "xgboost"
+version = "3.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+ { name = "nvidia-nccl-cu12", marker = "sys_platform == 'linux'" },
+ { name = "scipy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/91/bb/1eb0242409d22db725d7a88088e6cfd6556829fb0736f9ff69aa9f1e9455/xgboost-3.2.0.tar.gz", hash = "sha256:99b0e9a2a64896cdaf509c5e46372d336c692406646d20f2af505003c0c5d70d", size = 1263936, upload-time = "2026-02-10T11:03:05.542Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2d/49/6e4cdd877c24adf56cb3586bc96d93d4dcd780b5ea1efb32e1ee0de08bae/xgboost-3.2.0-py3-none-macosx_10_15_x86_64.whl", hash = "sha256:2f661966d3e322536d9c448090a870fcba1e32ee5760c10b7c46bac7a342079a", size = 2507014, upload-time = "2026-02-10T10:50:57.44Z" },
+ { url = "https://files.pythonhosted.org/packages/93/f1/c09ef1add609453aa3ba5bafcd0d1c1a805c1263c0b60138ec968f8ec296/xgboost-3.2.0-py3-none-macosx_12_0_arm64.whl", hash = "sha256:eabbd40d474b8dbf6cb3536325f9150b9e6f0db32d18de9914fb3227d0bef5b7", size = 2328527, upload-time = "2026-02-10T10:51:17.502Z" },
+ { url = "https://files.pythonhosted.org/packages/96/9f/d9914a7b8df842832850b1a18e5f47aaa071c217cdd1da2ae9deb291018b/xgboost-3.2.0-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:852eabc6d3b3702a59bf78dbfdcd1cb9c4d3a3b6e5ed1f8781d8b9512354fdd2", size = 131100954, upload-time = "2026-02-10T11:02:42.704Z" },
+ { url = "https://files.pythonhosted.org/packages/79/98/679de17c2caa4fd3b0b4386ecf7377301702cb0afb22930a07c142fcb1d8/xgboost-3.2.0-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:99b4a6bbcb47212fec5cf5fbe12347215f073c08967431b0122cfbd1ee70312c", size = 131748579, upload-time = "2026-02-10T10:54:40.424Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/3d/1661dd114a914a67e3f7ab66fa1382e7599c2a8c340f314ad30a3e2b4d08/xgboost-3.2.0-py3-none-win_amd64.whl", hash = "sha256:0d169736fd836fc13646c7ab787167b3a8110351c2c6bc770c755ee1618f0442", size = 101681668, upload-time = "2026-02-10T10:59:31.202Z" },
+]
+
[[package]]
name = "xmlsec"
version = "1.3.17"