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(aio): serialize sentiment classifier inference across threads (#109059)

posthog[bot]5e9569e124f3
diff --git a/posthog/temporal/ai_observability/sentiment/model.py b/posthog/temporal/ai_observability/sentiment/model.py
index 4386c35aab79..5de396df229b 100644
--- a/posthog/temporal/ai_observability/sentiment/model.py
+++ b/posthog/temporal/ai_observability/sentiment/model.py
@@ -29,6 +29,8 @@ from posthog.temporal.ai_observability.sentiment.schema import SentimentResult
logger = structlog.get_logger(__name__)
_model_lock = threading.Lock()
+# The Rust fast tokenizer is not thread-safe, and asyncio.to_thread callers share one pipeline.
+_inference_lock = threading.Lock()
_pipeline_cache: dict[str, Any] = {}
@@ -111,5 +113,6 @@ def classify(texts: list[str]) -> list[SentimentResult]:
pipe = _load_pipeline()
# Pipeline with top_k=None returns list of list[dict] for batch input
- batch_results = pipe(texts, batch_size=CLASSIFY_BATCH_SIZE)
+ with _inference_lock:
+ batch_results = pipe(texts, batch_size=CLASSIFY_BATCH_SIZE)
return [_parse_single_result(result) for result in batch_results]
diff --git a/posthog/temporal/ai_observability/sentiment/tests/test_model.py b/posthog/temporal/ai_observability/sentiment/tests/test_model.py
index cdb7c8e192d9..2d2e93c019f8 100644
--- a/posthog/temporal/ai_observability/sentiment/tests/test_model.py
+++ b/posthog/temporal/ai_observability/sentiment/tests/test_model.py
@@ -1,7 +1,11 @@
+import threading
+from concurrent.futures import ThreadPoolExecutor
+
from unittest.mock import MagicMock, patch
from parameterized import parameterized
+from posthog.temporal.ai_observability.sentiment import model
from posthog.temporal.ai_observability.sentiment.model import classify
from posthog.temporal.ai_observability.sentiment.schema import SentimentResult
@@ -17,6 +21,27 @@ def _make_pipeline_output(label: str, score: float) -> list[dict[str, object]]:
return [{"label": name, "score": s} for name, s in labels_scores.items()]
+class _SignallingLock:
+ """Wraps a real lock and signals when a second thread tries to take it."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._attempts = 0
+ self._attempts_lock = threading.Lock()
+ self.second_acquire_attempted = threading.Event()
+
+ def __enter__(self) -> "_SignallingLock":
+ with self._attempts_lock:
+ self._attempts += 1
+ if self._attempts == 2:
+ self.second_acquire_attempted.set()
+ assert self._lock.acquire(timeout=5)
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ self._lock.release()
+
+
class TestClassifyBatch:
@parameterized.expand(
[
@@ -100,3 +125,35 @@ class TestClassifyBatch:
assert result[0].scores["neutral"] == 0.0
assert result[0].scores["negative"] == 0.0
assert result[0].scores["positive"] == 0.95
+
+ @patch("posthog.temporal.ai_observability.sentiment.model._load_pipeline")
+ def test_concurrent_calls_never_run_pipeline_in_parallel(self, mock_load: MagicMock):
+ first_call_entered = threading.Event()
+ release_first_call = threading.Event()
+ signalling_lock = _SignallingLock()
+ pipe_calls = 0
+
+ def fake_pipe(texts: list[str], batch_size: int) -> list[list[dict[str, object]]]:
+ nonlocal pipe_calls
+ pipe_calls += 1
+ if pipe_calls == 1:
+ first_call_entered.set()
+ assert release_first_call.wait(timeout=5)
+ return [_make_pipeline_output("positive", 0.9) for _ in texts]
+
+ mock_load.return_value = fake_pipe
+
+ with (
+ patch.object(model, "_inference_lock", signalling_lock),
+ ThreadPoolExecutor(max_workers=2) as executor,
+ ):
+ first = executor.submit(classify, ["first"])
+ assert first_call_entered.wait(timeout=5)
+ second = executor.submit(classify, ["second"])
+ assert signalling_lock.second_acquire_attempted.wait(timeout=5)
+ assert pipe_calls == 1
+ release_first_call.set()
+ results = [first.result(timeout=5), second.result(timeout=5)]
+
+ assert pipe_calls == 2
+ assert all(r[0].label == "positive" for r in results)