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.

perf(signals): bound fetch_signals_for_report dedup to the report (#65776)

Paul D'Ambra742a264352d7
diff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md
index 180b57bb5ebc..15159e8be441 100644
--- a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md
+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md
@@ -143,3 +143,12 @@ At 180k docs CURRENT peak*mem was 96 MiB; at 360k it was 174 MiB — memory grow
**Correctness trap (same as the reverse-lookup sibling).** The `report_id IN (...)` filter must stay AFTER the `argMax`: a signal re-grouped from report A to B is matched by the candidate scan (it once carried A) but must be excluded because its _latest_ metadata points to B. Pushing the report_id predicate before the argMax would resurface the stale attribution. Verified identical results between all three shapes including the re-grouped case.
**Takeaway.** Before assuming a wide-column `argMax` is the cost, check whether the analyzer already prunes it (compare `read_bytes` against a content-free variant). When an `argMax ... GROUP BY high_cardinality_id` runs over a whole-history scan just to keep a small slice, bounding the group set with a `key IN (SELECT DISTINCT id WHERE <page predicate>)` prefilter trades a second (cheap, narrow) scan for an aggregation whose memory is bounded by the request page — the right lever for a memory/heavy-tenant-driven p95, even when it reads more bytes.
+
+**Follow-up — the same shape where the wide column _is_ consumed (sibling `_signals_for_report_query`).** The neighbouring query dedups the whole history then filters to a single report, and its outer SELECT _keeps_ `content`, so the analyzer can't prune the `argMax(content)` — the original genuinely reads and buffers content for every document. Same candidate-bound fix, measured at 180k docs / 600 reports / one target report (~300 of its docs):
+
+| Shape | dur_ms | read_rows | read_bytes | peak_mem |
+| ---------------------------------- | ------ | --------- | ---------- | ---------- |
+| Original (dedup-all, filter after) | 583 | 180k | 536 MiB | 943 MiB |
+| Candidate-bounded | 88 | 210k | **30 MiB** | **11 MiB** |
+
+~18x fewer bytes, ~84x less memory, ~6.6x faster — far larger than the pruned-content case above, and on every axis (the extra DISTINCT scan reads only `document_id` + `metadata`, so total bytes still collapses because `content` is now read for one report's docs, not the team's). Lesson: the candidate-bound win scales with how much per-document data the post-filter throws away — biggest when the dedup buffers a wide column (`content`/`embedding`) that downstream actually needs.
diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.py
index 37e3b144c5f8..3840b970a67d 100644
--- a/products/signals/backend/temporal/signal_queries.py
+++ b/products/signals/backend/temporal/signal_queries.py
@@ -43,8 +43,24 @@ def _ensure_tz_aware(value: Union[datetime, str]) -> datetime:
# ---------------------------------------------------------------------------
-def _deduped_signals_subquery(*, include_embedding: bool = False, extra_where: str | None = None) -> str:
- """Build the shared signal dedup subquery with an optional extra document_embeddings filter."""
+def _deduped_signals_subquery(
+ *, include_embedding: bool = False, extra_where: str | None = None, candidate_document_filter: str | None = None
+) -> str:
+ """Build the shared signal dedup subquery with an optional extra document_embeddings filter.
+
+ `candidate_document_filter` bounds the dedup to documents that ever matched the filter, via a
+ `document_id IN (SELECT DISTINCT ... WHERE <filter>)` prefilter — so the argMax aggregation runs
+ over that slice instead of the team's whole signal history (its memory otherwise scales with the
+ team's total signal count). Unlike `extra_where`, the filter selects candidate documents but does
+ NOT restrict which versions feed the argMax, so "latest version wins" is preserved and the caller's
+ own outer filter stays authoritative. Use it for re-groupable fields like `report_id`; use
+ `extra_where` only for fields that are stable across a document's versions (e.g. `source_id`).
+
+ Raises ValueError if both extra_where and candidate_document_filter are supplied — they are
+ mutually exclusive (the extra_where branch returns early and silently drops candidate_document_filter).
+ """
+ if extra_where and candidate_document_filter:
+ raise ValueError("_deduped_signals_subquery: extra_where and candidate_document_filter are mutually exclusive")
selected_columns = [
"document_id",
"argMax(content, inserted_at) as content",
@@ -83,13 +99,25 @@ def _deduped_signals_subquery(*, include_embedding: bool = False, extra_where: s
GROUP BY document_id
"""
+ candidate_bound = ""
+ if candidate_document_filter:
+ candidate_bound = f"""
+ AND document_id IN (
+ SELECT DISTINCT document_id
+ FROM document_embeddings
+ WHERE model_name = {{model_name}}
+ AND product = 'signals'
+ AND document_type = 'signal'
+ AND {candidate_document_filter}
+ )"""
+
return f"""
SELECT
{selected_columns_sql}
FROM document_embeddings
WHERE model_name = {{model_name}}
AND product = 'signals'
- AND document_type = 'signal'
+ AND document_type = 'signal'{candidate_bound}
GROUP BY document_id
"""
@@ -115,7 +143,7 @@ def _signals_for_report_query(*, include_deleted: bool = False, limit: int | Non
content,
metadata,
timestamp
- FROM ({_deduped_signals_subquery()})
+ FROM ({_deduped_signals_subquery(candidate_document_filter="JSONExtractString(metadata, 'report_id') = {report_id}")})
WHERE JSONExtractString(metadata, 'report_id') = {{report_id}}{deleted_filter}
ORDER BY timestamp ASC{limit_clause}
"""
diff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.py
index 8f4032942de0..938eba0d0b68 100644
--- a/products/signals/backend/test/test_signal_queries.py
+++ b/products/signals/backend/test/test_signal_queries.py
@@ -9,13 +9,17 @@ from parameterized import parameterized
from posthog.clickhouse.client import sync_execute
-from products.signals.backend.temporal.signal_queries import EMBEDDING_MODEL, fetch_source_products_for_reports
+from products.signals.backend.temporal.signal_queries import (
+ EMBEDDING_MODEL,
+ fetch_signals_for_report_sync,
+ fetch_source_products_for_reports,
+)
_MODEL_TABLE = f"distributed_posthog_document_embeddings_{EMBEDDING_MODEL.value.replace('-', '_')}"
_EMBEDDING = [0.0] * 1536
-class TestFetchSourceProductsForReports(ClickhouseTestMixin, APIBaseTest):
+class _SignalEmbeddingsTestBase(ClickhouseTestMixin, APIBaseTest):
def _emit_version(
self,
*,
@@ -24,6 +28,7 @@ class TestFetchSourceProductsForReports(ClickhouseTestMixin, APIBaseTest):
source_product: str,
inserted_at: datetime,
deleted: bool = False,
+ content: str = "the signal content",
) -> None:
"""Write one version of a signal document straight to the model-specific embeddings table.
@@ -54,7 +59,7 @@ class TestFetchSourceProductsForReports(ClickhouseTestMixin, APIBaseTest):
document_id,
inserted_at,
inserted_at,
- "the signal content",
+ content,
json.dumps(metadata),
_EMBEDDING,
inserted_at,
@@ -73,6 +78,8 @@ class TestFetchSourceProductsForReports(ClickhouseTestMixin, APIBaseTest):
self.base = datetime.now(UTC) - timedelta(days=2)
sync_execute(f"TRUNCATE TABLE {_MODEL_TABLE}", flush=False, team_id=self.team.pk)
+
+class TestFetchSourceProductsForReports(_SignalEmbeddingsTestBase):
def test_empty_report_ids_returns_empty_without_querying(self) -> None:
# Guards the early return: an empty list would otherwise compile to `report_id IN ()` and raise.
assert fetch_source_products_for_reports(self.team, []) == {}
@@ -134,3 +141,70 @@ class TestFetchSourceProductsForReports(ClickhouseTestMixin, APIBaseTest):
)
assert fetch_source_products_for_reports(self.team, report_ids) == expected
+
+
+class TestFetchSignalsForReportSync(_SignalEmbeddingsTestBase):
+ def _signal_ids(self, report_id: str) -> set[str]:
+ return {s["signal_id"] for s in fetch_signals_for_report_sync(self.team, report_id)}
+
+ def test_returns_only_the_reports_non_deleted_signals(self) -> None:
+ self._emit_version(document_id="a", report_id="rA", source_product="errors", inserted_at=self.base)
+ self._emit_version(document_id="b", report_id="rA", source_product="replay", inserted_at=self.base)
+ self._emit_version(document_id="c", report_id="rB", source_product="surveys", inserted_at=self.base)
+
+ assert self._signal_ids("rA") == {"a", "b"}
+
+ @parameterized.expand(
+ [
+ # A re-grouped signal belongs to its latest report only — the candidate prefilter finds it
+ # (it once carried rOld) but the outer report filter keeps it under rNew, never rOld.
+ ("regrouped_to_new_report", ("rOld", False), ("rNew", False), "rOld", set()),
+ ("regrouped_visible_under_new", ("rOld", False), ("rNew", False), "rNew", {"moving"}),
+ # The latest version's deleted flag wins.
+ ("deleted_in_latest_version", ("rA", False), ("rA", True), "rA", set()),
+ ("revived_in_latest_version", ("rA", True), ("rA", False), "rA", {"moving"}),
+ ]
+ )
+ def test_latest_version_wins(
+ self,
+ _name: str,
+ first: tuple[str, bool],
+ latest: tuple[str, bool],
+ query_report: str,
+ expected_ids: set[str],
+ ) -> None:
+ first_report, first_deleted = first
+ latest_report, latest_deleted = latest
+ self._emit_version(
+ document_id="moving",
+ report_id=first_report,
+ source_product="errors",
+ inserted_at=self.base,
+ deleted=first_deleted,
+ )
+ self._emit_version(
+ document_id="moving",
+ report_id=latest_report,
+ source_product="errors",
+ inserted_at=self.base + timedelta(hours=1),
+ deleted=latest_deleted,
+ )
+
+ assert self._signal_ids(query_report) == expected_ids
+
+ def test_returns_latest_content_for_a_revised_signal(self) -> None:
+ # The dedup must surface the newest version's content, not an arbitrary one.
+ self._emit_version(
+ document_id="x", report_id="rA", source_product="errors", inserted_at=self.base, content="old text"
+ )
+ self._emit_version(
+ document_id="x",
+ report_id="rA",
+ source_product="errors",
+ inserted_at=self.base + timedelta(hours=1),
+ content="new text",
+ )
+
+ signals = fetch_signals_for_report_sync(self.team, "rA")
+
+ assert [s["content"] for s in signals] == ["new text"]