: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(signals): bound source-products dedup to the page's reports (#65763)
Paul D'Ambra8673b53f1014
diff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.mdindex 1f634b66d2ff..180b57bb5ebc 100644--- a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md@@ -119,3 +119,27 @@ B was 46% slower than A and used ~10× the memory. C was 4.6× faster than A and**Caveats.** Team 2's snapshot has `count() == countDistinct(id)` (tens of millions of each), meaning background merges had already deduplicated the table before we measured. `FINAL` therefore had no actual merge work to do, only the planner overhead and the no-parallel-reads cost. On a team with active person updates, A's wall-clock and memory would shift up; B would shift even more (argMax over more rows per group). The relative ordering of "materialization dominates" should hold.**Takeaway.** The blanket "FINAL bad, argMax good" framing is wrong in at least one important case: argMax over a wide column (`properties` blobs) buffers the winning value per group in the GROUP BY hash table, which can blow memory up by 10× while making the query slower than just letting `FINAL` stream. The safe rewrite hierarchy for moving off `FROM ... FINAL` is: (1) use a materialized column if one exists, (2) argMax over a narrow column you actually need, (3) only fall back to argMax over the wide column as a last resort. If none of those apply, `FINAL` may genuinely be the cheapest option.++---++## 2026-06-24: ClickHouse prunes unused `argMax(content)`; the real win is bounding the dedup, not dropping columns++**Context.** `products/signals/backend/temporal/signal_queries.py::fetch_source_products_for_reports` runs on every inbox report-list load (`signals.reports.list.fetch_source_products`, APM 7d p50 ~155ms / p95 ~1.4s). It deduped the team's whole signal history with `_deduped_signals_subquery()` (`argMax(content), argMax(metadata), argMax(timestamp) GROUP BY document_id` over `document_embeddings`) then filtered `report_id IN (<~25 page reports>)` on the OUTER query. `document_embeddings` is model-routed `ReplacingMergeTree`, `ORDER BY (team_id, toDate(timestamp), product, document_type, rendering, cityHash64(document_id))`, 3-month TTL; `report_id` lives in the `metadata` JSON, so nothing prunes — every load scans ~3 months of the team's signals.++**The proposed smell was partly wrong.** The hypothesis was "it `argMax`'s the big `content` string for every document, then throws it away." Measured against local synthetic single-team data (incompressible 3KB `content`), `read_bytes` for the original was **identical** to a variant that never selects content — ClickHouse's analyzer drops the `argMax(content)`/`argMax(timestamp)` because the outer query never references those aliases. Dead-column elimination already handled it; "drop the unused content argMax" buys ~0 at the ClickHouse layer.++**What actually costs.** The `argMax(metadata) GROUP BY document_id` over the _whole history_ — its hash table holds metadata per distinct document, so peak memory scales with the team's total signal count.++**Three shapes, local synthetic data (median of 5 from `system.query_log`), 360k rows / 360k docs, 600 reports, page = 25 reports:**++| Shape | dur_ms | read_rows | read_bytes | peak_mem |+| ----------------------------------------------------------------------------------------------------------- | ------ | --------- | ---------- | ------------ |+| CURRENT (dedup-all, filter after) | 192 | 360k | 39.5 MiB | 174 MiB |+| CANDIDATE (`document_id IN (SELECT DISTINCT ... WHERE report_id IN page)`, then argMax, filter still after) | 157 | 720k | 76 MiB | **14.3 MiB** |+| LEAN (single scan, `argMax(JSONExtract(...scalars))` instead of full metadata blob) | 309 | 360k | 39.5 MiB | 171 MiB |++At 180k docs CURRENT peak*mem was 96 MiB; at 360k it was 174 MiB — memory grows ~linearly with team history. CANDIDATE went 2.6 MiB -> 14.3 MiB over the same doubling: bounded by signals in the \_displayed page's reports*, not the whole history. The wall-clock crossover (CANDIDATE faster) lands exactly on the signal-heavy teams that drive the p95 tail. CANDIDATE's cost is 2x metadata I/O (a second full-history `JSONExtract(report_id)` scan to build the candidate set) — cheap and parallel relative to the memory it saves. LEAN (drop the blob, argMax narrow scalars, single scan) was no better than CURRENT on memory at scale and noisier, so it was rejected.++**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.diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.pyindex 095c9fe825a9..37e3b144c5f8 100644--- a/products/signals/backend/temporal/signal_queries.py+++ b/products/signals/backend/temporal/signal_queries.py@@ -96,7 +96,6 @@ def _deduped_signals_subquery(*, include_embedding: bool = False, extra_where: s# Backwards-compatible aliases for callers that import the shared query constants directly._DEDUPED_SIGNALS_SUBQUERY = _deduped_signals_subquery()-_DEDUPED_SIGNALS_WITH_EMBEDDING_SUBQUERY = _deduped_signals_subquery(include_embedding=True)def _signals_for_report_query(*, include_deleted: bool = False, limit: int | None = None) -> str:@@ -585,22 +584,46 @@ def fetch_source_products_for_reports(team: Team, report_ids: list[str]) -> dict"""Return a mapping of report_id -> distinct source_products for those reports.Only includes non-deleted signals. Source products are returned in sorted order.++ Bounds the argMax dedup to documents that ever carried one of these report_ids, instead+ of deduping the team's whole signal history. The unbounded dedup's memory grows with the+ team's total signal count; the candidate-bounded form keeps it proportional to the signals+ in the requested page's reports, which is what flattens the tail on signal-heavy teams.+ The report_id filter stays AFTER the argMax so "latest version wins" holds: a signal that+ was re-grouped to a different report is matched by the candidate scan (it once carried this+ report_id) but excluded by the outer filter (its latest metadata points elsewhere) — the+ same correctness trap fetch_report_ids_for_source_ids documents."""if not report_ids:return {}- ch_query = f"""+ ch_query = """SELECT report_id, arraySort(groupUniqArray(source_product)) as source_productsFROM (SELECTJSONExtractString(metadata, 'report_id') as report_id,JSONExtractBool(metadata, 'deleted') as is_deleted,JSONExtractString(metadata, 'source_product') as source_product- FROM ({_deduped_signals_subquery()})+ FROM (+ SELECT argMax(metadata, inserted_at) as metadata+ FROM document_embeddings+ WHERE model_name = {model_name}+ AND product = 'signals'+ AND document_type = 'signal'+ AND document_id IN (+ SELECT DISTINCT document_id+ FROM document_embeddings+ WHERE model_name = {model_name}+ AND product = 'signals'+ AND document_type = 'signal'+ AND JSONExtractString(metadata, 'report_id') IN ({report_ids})+ )+ GROUP BY document_id+ ))WHERE NOT is_deletedAND report_id != ''- AND report_id IN ({{report_ids}})+ AND report_id IN ({report_ids})AND source_product != ''GROUP BY report_id"""diff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.pynew file mode 100644index 000000000000..8f4032942de0--- /dev/null+++ b/products/signals/backend/test/test_signal_queries.py@@ -0,0 +1,136 @@+from __future__ import annotations++import json+from datetime import UTC, datetime, timedelta++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++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++_MODEL_TABLE = f"distributed_posthog_document_embeddings_{EMBEDDING_MODEL.value.replace('-', '_')}"+_EMBEDDING = [0.0] * 1536+++class TestFetchSourceProductsForReports(ClickhouseTestMixin, APIBaseTest):+ def _emit_version(+ self,+ *,+ document_id: str,+ report_id: str,+ source_product: str,+ inserted_at: datetime,+ deleted: bool = False,+ ) -> None:+ """Write one version of a signal document straight to the model-specific embeddings table.++ Multiple versions of the same document_id (varying inserted_at) model the+ ReplacingMergeTree's pre-merge state that the argMax dedup has to resolve.+ """+ metadata = {+ "report_id": report_id,+ "source_product": source_product,+ "source_type": "some_type",+ "source_id": f"src-{document_id}",+ "deleted": deleted,+ }+ sync_execute(+ f"""+ INSERT INTO {_MODEL_TABLE} (+ team_id, product, document_type, rendering, document_id,+ timestamp, inserted_at, content, metadata, embedding,+ _timestamp, _offset, _partition+ ) VALUES+ """,+ [+ (+ self.team.pk,+ "signals",+ "signal",+ "plain",+ document_id,+ inserted_at,+ inserted_at,+ "the signal content",+ json.dumps(metadata),+ _EMBEDDING,+ inserted_at,+ 0,+ 0,+ )+ ],+ flush=False,+ team_id=self.team.pk,+ )++ def setUp(self) -> None:+ super().setUp()+ # Anchor to "now" so rows stay inside the table's 3-month TTL window; assertions depend+ # only on the relative inserted_at ordering between versions, not the absolute timestamp.+ self.base = datetime.now(UTC) - timedelta(days=2)+ sync_execute(f"TRUNCATE TABLE {_MODEL_TABLE}", flush=False, team_id=self.team.pk)++ 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, []) == {}++ def test_maps_each_report_to_its_sorted_distinct_source_products(self) -> None:+ self._emit_version(document_id="d1", report_id="rA", source_product="errors", inserted_at=self.base)+ self._emit_version(document_id="d2", report_id="rA", source_product="replay", inserted_at=self.base)+ # duplicate source_product within a report collapses to one entry+ self._emit_version(document_id="d3", report_id="rA", source_product="errors", inserted_at=self.base)+ self._emit_version(document_id="d4", report_id="rB", source_product="surveys", inserted_at=self.base)++ result = fetch_source_products_for_reports(self.team, ["rA", "rB"])++ assert result == {"rA": ["errors", "replay"], "rB": ["surveys"]}++ def test_only_returns_requested_reports(self) -> None:+ self._emit_version(document_id="d1", report_id="wanted", source_product="errors", inserted_at=self.base)+ self._emit_version(document_id="d2", report_id="unwanted", source_product="replay", inserted_at=self.base)++ result = fetch_source_products_for_reports(self.team, ["wanted"])++ assert result == {"wanted": ["errors"]}++ @parameterized.expand(+ [+ # A signal re-grouped to a different report must count under its latest report only —+ # never the old one. Pushing the report_id filter before the argMax would resurface it+ # under rOld; keeping it after preserves "latest version wins".+ ("regrouped_to_new_report", ("rOld", False), ("rNew", False), ["rOld", "rNew"], {"rNew": ["errors"]}),+ # Soft-delete re-emits the signal with deleted=True and a newer inserted_at -> it drops out.+ ("deleted_in_latest_version", ("rA", False), ("rA", True), ["rA"], {}),+ # ...and a delete that was later undone (newer non-deleted version) comes back.+ ("revived_in_latest_version", ("rA", True), ("rA", False), ["rA"], {"rA": ["errors"]}),+ ]+ )+ def test_latest_version_wins(+ self,+ _name: str,+ first: tuple[str, bool],+ latest: tuple[str, bool],+ report_ids: list[str],+ expected: dict[str, list[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 fetch_source_products_for_reports(self.team, report_ids) == expected