Skip to content

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

fix(session-replay): run surfacing scorer on the session-replay worker (#63990)

Arno Hillen3eae0b480b0b
diff --git a/posthog/management/commands/score_one_chunk.py b/posthog/management/commands/score_one_chunk.py
index 9fd8149c32a0..95d84be3d5f5 100644
--- a/posthog/management/commands/score_one_chunk.py
+++ b/posthog/management/commands/score_one_chunk.py
@@ -5,7 +5,7 @@ and prints the scores. Read-only (writes nothing back). Handy to verify the mode
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).
+Requires `SESSION_SURFACING_MODEL_S3_URI` (see surfacing_scoring_sweep README).
Examples:
./bin/python manage.py score_one_chunk
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 6c082077f8a4..5388e9d3e436 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -640,9 +640,13 @@ 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
+ from posthog.temporal.session_replay.surfacing_scoring_sweep.scorer import warmup_best_effort
- warmup()
+ # Best-effort: surfacing shares this queue with the rest of the
+ # session-replay worker, so a model problem must not crash the
+ # pod. It logs and continues; scoring activities retry until the
+ # model is fixed.
+ warmup_best_effort()
worker = runner.run(
create_worker(
diff --git a/posthog/management/commands/upload_surfacing_model.py b/posthog/management/commands/upload_surfacing_model.py
index b7a5bae63184..2d7c47ecfa63 100644
--- a/posthog/management/commands/upload_surfacing_model.py
+++ b/posthog/management/commands/upload_surfacing_model.py
@@ -2,7 +2,7 @@
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>
+ SESSION_SURFACING_MODEL_S3_URI=s3://<bucket>/<key>
Examples:
./bin/python manage.py upload_surfacing_model ./surfacing_score_xgb_v1.ubj
@@ -84,4 +84,4 @@ class Command(BaseCommand):
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}")
+ self.stdout.write(f" SESSION_SURFACING_MODEL_S3_URI=s3://{bucket}/{key}")
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index fa9d488bd9b2..844d3b71fa4c 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -113,11 +113,12 @@ 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")
+# The XGBoost-based session surfacing scoring sweep runs on the session-replay
+# worker (it's the only OpenMP user there; that worker sets OMP_NUM_THREADS=1).
+# Sharing the queue means start_temporal_worker aggregates its workflow +
+# activities onto the replay worker and warmup() runs on replay-worker boot —
+# no dedicated pod needed (see surfacing_scoring_sweep/README.md).
+SURFACING_SCORING_SWEEP_TASK_QUEUE = SESSION_REPLAY_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/session_replay/surfacing_scoring_sweep/README.md b/posthog/temporal/session_replay/surfacing_scoring_sweep/README.md
index 3d4afa7f36fd..3ae0aab6873c 100644
--- a/posthog/temporal/session_replay/surfacing_scoring_sweep/README.md
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/README.md
@@ -166,42 +166,31 @@ Defaults in `constants.py` are `chunk_size=10_000`, `of_chunks=20`. Tweak
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:
+Surfacing scoring runs on the **session-replay worker** (the queue is aliased:
+`SURFACING_SCORING_SWEEP_TASK_QUEUE = SESSION_REPLAY_TASK_QUEUE`), alongside the
+worker's other replay work (LLM/CH/S3). XGBoost predict is the only OpenMP user
+there, so the worker pins:
```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,
-)
+OMP_NUM_THREADS=1 # one thread per predict; parallelism comes from
+MAX_CONCURRENT_ACTIVITIES=15 # concurrent activities, not libomp fan-out
```
-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.
+`OMP_NUM_THREADS=1` stops libomp from fanning out × `MAX_CONCURRENT_ACTIVITIES`
+and fighting the asyncio reactor / Temporal SDK threads for cores. Predict on
+tabular features is cheap (the bottleneck is fetch + write, not score), so a
+single predict thread is enough and doesn't starve the other replay activities.
### 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`).
+`os.cpu_count()` returns the host's CPU count, not the pod's CPU limit — which is
+why the chart sets `OMP_NUM_THREADS` explicitly rather than deriving it from
+`nproc`.
## 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
+override. `SESSION_SURFACING_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.
@@ -231,7 +220,7 @@ 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
+SESSION_SURFACING_MODEL_S3_URI=s3://<bucket>/surfacing-scoring/surfacing_score_xgb_v1.ubj
```
Plain `aws s3 cp` works too.
diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/scorer.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/scorer.py
index 2d3355451037..1e0cb4fba2b6 100644
--- a/posthog/temporal/session_replay/surfacing_scoring_sweep/scorer.py
+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/scorer.py
@@ -31,7 +31,7 @@ from posthog.temporal.session_replay.surfacing_scoring_sweep.features import fea
logger = structlog.get_logger(__name__)
-_MODEL_S3_URI_ENV_VAR = "SESSION_INTERESTINGNESS_MODEL_S3_URI"
+_MODEL_S3_URI_ENV_VAR = "SESSION_SURFACING_MODEL_S3_URI"
_BOOSTER: xgb.Booster | None = None
# Cached tuple of `_BOOSTER.feature_names` to avoid the C++ → Python attribute
@@ -43,7 +43,7 @@ _BOOSTER_LOCK = threading.Lock()
class ModelNotConfiguredError(RuntimeError):
- """`SESSION_INTERESTINGNESS_MODEL_S3_URI` is not set."""
+ """`SESSION_SURFACING_MODEL_S3_URI` is not set."""
def _fetch_from_s3(uri: str) -> str:
@@ -117,10 +117,31 @@ def warmup() -> None:
fetch latency. Also surfaces `ModelNotConfiguredError` /
`FeatureSchemaDriftError` / `MissingFeatureRangeError` at boot rather
than on the first chunk.
+
+ Raises on any model problem — callers that must not crash (e.g. the shared
+ session-replay worker, where surfacing is one of several workflows) should
+ use `warmup_best_effort()` instead.
"""
_load_booster()
+def warmup_best_effort() -> bool:
+ """`warmup()` that never raises — for the shared session-replay worker.
+
+ Surfacing scoring runs alongside other replay workflows on that worker, so a
+ model problem (env var unset, model missing from S3, schema drift) must not
+ take the whole pod down. Logs and returns False instead; the scoring
+ activities will then fail (and retry per their policy) until the model is
+ fixed, while the rest of the worker keeps running. Returns True on success.
+ """
+ try:
+ warmup()
+ return True
+ except Exception:
+ logger.exception("surfacing_scoring_sweep.warmup_failed_worker_continuing")
+ return False
+
+
def get_feature_names() -> tuple[str, ...]:
"""Return the booster's `feature_names` tuple — the serving feature schema.
diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py
index b2c5e6260647..166cbc7ed5d9 100644
--- a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py
@@ -94,7 +94,7 @@ def wire_booster_as_s3(
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.setenv("SESSION_SURFACING_MODEL_S3_URI", uri)
monkeypatch.setattr(
"posthog.temporal.session_replay.surfacing_scoring_sweep.scorer.object_storage.read_bytes",
lambda key, *, bucket=None: payload,
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
index c5ca944e7474..f8c71496be66 100644
--- a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_scorer.py
+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_scorer.py
@@ -27,6 +27,7 @@ from posthog.temporal.session_replay.surfacing_scoring_sweep.scorer import (
get_feature_names,
predict,
warmup,
+ warmup_best_effort,
)
from posthog.temporal.tests.session_replay.surfacing_scoring_sweep.conftest import (
train_synthetic_booster,
@@ -99,7 +100,7 @@ class TestModelLoading:
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.setenv("SESSION_SURFACING_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,
@@ -108,10 +109,30 @@ class TestModelLoading:
_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)
+ monkeypatch.delenv("SESSION_SURFACING_MODEL_S3_URI", raising=False)
with pytest.raises(scorer_mod.ModelNotConfiguredError):
_load_booster()
+ def test_warmup_best_effort_returns_true_on_success(self, surfacing_booster_path: Path) -> None:
+ assert warmup_best_effort() is True
+ assert scorer_mod._BOOSTER is not None
+
+ def test_warmup_best_effort_does_not_crash_when_no_env_set(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # The session-replay worker calls this on boot; an unset model URI must
+ # NOT take the whole worker down — it logs and returns False.
+ monkeypatch.delenv("SESSION_SURFACING_MODEL_S3_URI", raising=False)
+ assert warmup_best_effort() is False
+ assert scorer_mod._BOOSTER is None
+
+ def test_warmup_best_effort_does_not_crash_when_model_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SESSION_SURFACING_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,
+ )
+ assert warmup_best_effort() is False
+ assert scorer_mod._BOOSTER is None
+
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).
@@ -120,7 +141,7 @@ class TestModelLoading:
booster.save_model(str(src))
payload = src.read_bytes()
- monkeypatch.setenv("SESSION_INTERESTINGNESS_MODEL_S3_URI", "s3://my-bucket/path/to/model.ubj")
+ monkeypatch.setenv("SESSION_SURFACING_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,
@@ -132,8 +153,8 @@ class TestModelLoading:
@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"):
+ monkeypatch.setenv("SESSION_SURFACING_MODEL_S3_URI", uri)
+ with pytest.raises(ValueError, match="SESSION_SURFACING_MODEL_S3_URI"):
_load_booster()