: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
feat(signals): add signal-level embeddings to the inbox ranking dataset (#82464)
Andrew Maguire4bcce8b95d8c
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.pyindex 5d278e81bf74..ab6aeffc038d 100644--- a/posthog/dags/locations/signals.py+++ b/posthog/dags/locations/signals.py@@ -12,6 +12,7 @@ if is_inbox_ranking_registered():assets=[inbox_ranking_dataset.inbox_report_state,inbox_ranking_dataset.inbox_report_embeddings,+ inbox_ranking_dataset.inbox_signal_embeddings,inbox_ranking_dataset.inbox_report_labels,inbox_ranking_dataset.inbox_report_model_data,],diff --git a/posthog/dags/slack_alerts.py b/posthog/dags/slack_alerts.pyindex 98f5a06a2f14..dea1a689723f 100644--- a/posthog/dags/slack_alerts.py+++ b/posthog/dags/slack_alerts.py@@ -105,6 +105,7 @@ def send_slack_alert(context, client, channel: str, blocks: list, fallback_text:ASSET_NAME_PREFIX_OWNERS: tuple[tuple[str, JobOwners], ...] = (("web_", JobOwners.TEAM_WEB_ANALYTICS),("inbox_report_", JobOwners.TEAM_SELF_DRIVING),+ ("inbox_signal_", JobOwners.TEAM_SELF_DRIVING),)diff --git a/posthog/dags/tests/test_slack_alerts.py b/posthog/dags/tests/test_slack_alerts.pyindex b2f0a0962013..48e6e3b6e529 100644--- a/posthog/dags/tests/test_slack_alerts.py+++ b/posthog/dags/tests/test_slack_alerts.py@@ -59,6 +59,17 @@ class TestSlackAlertsRouting:assert result == JobOwners.TEAM_SELF_DRIVING.value+ def test_asset_job_with_inbox_signal_steps_routes_to_self_driving(self):+ mock_run = mock.MagicMock(spec=dagster.DagsterRun)+ mock_run.job_name = "__ASSET_JOB"+ mock_run.tags = {}++ error_message = "Execution of run for \"__ASSET_JOB\" failed. Steps failed: ['inbox_signal_embeddings']."++ result = get_job_owner_for_alert(mock_run, error_message)++ assert result == JobOwners.TEAM_SELF_DRIVING.value+def test_asset_job_without_web_steps_uses_original_owner(self):mock_run = mock.MagicMock(spec=dagster.DagsterRun)mock_run.job_name = "__ASSET_JOB"diff --git a/products/signals/backend/signal_metadata.py b/products/signals/backend/signal_metadata.pyindex c60841f0dc4a..e02bb7cdf476 100644--- a/products/signals/backend/signal_metadata.py+++ b/products/signals/backend/signal_metadata.py@@ -22,6 +22,14 @@ from posthog.models import Team# ClickHouse query filters on it.EMBEDDING_MODEL = EmbeddingModelName.TEXT_EMBEDDING_3_SMALL_1536+# Every signal document is emitted under this key triple — the recently-seen lookup in+# wait_for_signal_in_clickhouse_activity relies on exact key equality with the emit sites.+# They live here rather than beside those emit sites so readers outside the temporal package+# (the inbox-ranking dag) can share them without importing the workflow stack.+SIGNAL_DOCUMENT_PRODUCT = "signals"+SIGNAL_DOCUMENT_TYPE = "signal"+SIGNAL_DOCUMENT_RENDERING = "plain"+@dataclass(frozen=True)class ReportSignalMeta:diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.pyindex 90f5ac61aa5b..f49f5dea2d04 100644--- a/products/signals/backend/temporal/signal_queries.py+++ b/products/signals/backend/temporal/signal_queries.py@@ -19,7 +19,12 @@ from posthog.models import Teamfrom posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connections-from products.signals.backend.signal_metadata import EMBEDDING_MODEL+from products.signals.backend.signal_metadata import (+ EMBEDDING_MODEL,+ SIGNAL_DOCUMENT_PRODUCT,+ SIGNAL_DOCUMENT_RENDERING,+ SIGNAL_DOCUMENT_TYPE,+)from products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.clickhouse import execute_hogql_query_with_retryfrom products.signals.backend.temporal.types import SignalCandidate, SignalData, SignalTypeExample@@ -29,12 +34,6 @@ logger = structlog.get_logger(__name__)WAIT_POLL_INTERVAL_SECONDS = 10-# Every signal document is emitted under this key triple — the recently-seen lookup in-# wait_for_signal_in_clickhouse_activity relies on exact key equality with the emit sites.-SIGNAL_DOCUMENT_PRODUCT = "signals"-SIGNAL_DOCUMENT_TYPE = "signal"-SIGNAL_DOCUMENT_RENDERING = "plain"-# For this long, ClickHouse is polled only when the recently-seen store confirms the# emission (or on the final attempt) — the wait is store-exclusive to keep ClickHouse# load off the polling path. After it, ClickHouse also polls on the fallback cadencediff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex bdaf33f291c0..1b4623b8f2ec 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -9,7 +9,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f## Invariants — do not break-- `dt=` partitions are **immutable snapshots** with deterministic object keys; the only mutation ever applied is an idempotent re-run of the same partition.+- `dt=` partitions are **immutable snapshots** with deterministic object keys; the only mutation ever applied is an idempotent re-run of the same partition. The exception is `inbox_signal_embeddings`, an emission log whose partition holds only that day's inserts — see the README's signal-grain section before touching it. Its re-run must stay **additive** (union with the existing object): the source drops rows it already archived, so a plain overwrite destroys history that exists nowhere else.- Label columns are **cumulative from `LABELS_EPOCH`**; never bake a maturity window or a rolling time bound into the SQL (the saved `inbox_ranking_*` views roll 90 days — that is exactly why their SQL is inlined here with explicit bounds instead of reused).- `latest/` must stay **monotonic** (snapshot-date metadata stamp); backfills must never overwrite it.- Schema changes: additive nullable columns bump `FEATURE_SCHEMA_VERSION`; breaking changes bump the `v1` path segment. The parquet schemas and the row assemblers must stay in exact key agreement — `pa.Table.from_pylist` silently drops unknown keys, and a test guards this.diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 046926dc4d92..73ef49bd35db 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -7,7 +7,7 @@ The one dag today is the **dataset** dag; future ranking dags (training, eval) linbox_ranking/├── common.py # shared: S3 destination config, daily partition def, gating, Parquet IO├── dataset/-│ ├── dag.py # the four dataset assets + job + schedule+│ ├── dag.py # the five dataset assets + job + schedule│ └── queries.py # HogQL label SQL, embeddings SQL, stream merging└── tests/```@@ -16,18 +16,21 @@ Registered via `posthog/dags/locations/signals.py` (US only) and loaded locally## The dataset dag-`inbox_ranking_dataset_job` runs daily at 02:30 UTC (schedule default: running on prod US, stopped everywhere else — including hosted DEV and E2E, which have no dogfood project to read labels from) and builds four assets on one daily partition, each a Parquet object in S3:+`inbox_ranking_dataset_job` runs daily at 02:30 UTC (schedule default: running on prod US, stopped everywhere else — including hosted DEV and E2E, which have no dogfood project to read labels from) and builds five assets on one daily partition, each a Parquet object in S3:```texts3://<bucket>/<prefix>/├── inbox_report_state/v1/dt=YYYY-MM-DD/ # Postgres spine + report state + tabular features├── inbox_report_embeddings/v1/dt=YYYY-MM-DD/ # report_id -> small-1536 vector as of snapshot end├── inbox_report_labels/v1/dt=YYYY-MM-DD/ # cumulative label columns from dogfood telemetry-└── inbox_report_model_data/v1/- ├── dt=YYYY-MM-DD/ # materialized join of the three (the training table)- └── latest/ # rewritten by the newest partition; warehouse tables point here+├── inbox_report_model_data/v1/+│ ├── dt=YYYY-MM-DD/ # materialized join of the three (the training table)+│ └── latest/ # rewritten by the newest partition; warehouse tables point here+└── inbox_signal_embeddings/v1/dt=YYYY-MM-DD/ # one row per signal emitted during the day (signal grain)```+The first four are report grain and land in one table. `inbox_signal_embeddings` is signal grain, feeds the group-level model, and is read on its own — training joins it to `inbox_report_model_data` by `report_id`.+### Partition semantics- Partition `dt=D` snapshots the eligible report inventory (promoted before `D+1 00:00 UTC`, or referenced by any label event before it). Every label aggregate is bounded `event_time < D+1 00:00 UTC`.@@ -37,6 +40,18 @@ s3://<bucket>/<prefix>/- **Backfills are not fully point-in-time**: labels are exact for any past day, embeddings are exact within the source table's 3-month TTL, but report state is read from Postgres as of the run (`features_observed_at` flags this per row).- Report-state mutability reaches **inclusion**, not just feature values: `promoted_at` is cleared on suppression and snooze, so a report promoted before the cutoff and suppressed after it leaves the spine unless a label event referenced it before the cutoff. Forward runs see this only for the 2.5 hours between the cutoff and the schedule; backfills see the full accumulated effect. Deriving the spine from immutable promotion history (`signal_report_status_changed` carries `promoted_at`) is the v2 fix.+### Signal-grain partitions++`inbox_signal_embeddings` is the one asset here whose partitions are **not** full snapshots. `dt=D` holds only the signal documents inserted during D — an emission log — because a cumulative copy at signal grain means a 1536-float vector per signal, fleet-wide, rewritten every day.++- Read the **union** of partitions and take the latest row per `(team_id, signal_id)` at or before the cutoff. `signal_id` (the ClickHouse `document_id`) is caller-supplied and only unique within a team, so the tenant key is part of the identity. That is the same `(team_id, document_id)` latest-wins the report assets do in SQL, moved to read time.+- **The log is best-effort, not complete.** The source is a ReplacingMergeTree versioned by `inserted_at`, and a retraction re-emits the signal under the same sort key, so a merge between the two writes keeps only the retraction. A signal whose report is deleted in the same window it was inserted reaches no partition in its live form, and no query shape recovers it: the merge has already dropped the row.+- The reverse gap is the TTL. A retraction inherits the original event timestamp, so retracting a signal more than three months old writes a row that is already expired and may never be scanned. **Absence of an `is_deleted` row is not proof that a signal is live**, and this archive is not authoritative for deletion — see the retention section below.+- The vectors' source TTL runs from **signal event time**, so this asset is also where signal vectors become durable. Whatever a partition does not capture before its signals age out is gone.+- Consequently **a re-run is additive**: it unions the fresh scan into the rows the partition already holds, keyed by `(team_id, signal_id, embedding_inserted_at)`, so a row the source can no longer supply survives. Overwriting with the scan alone would delete it permanently, and a row count cannot police that — a scan can lose one emission and gain another and land on the same total.+- The count check remains as a backstop: a union can only grow, so a smaller result means the merge itself is broken and the write is refused. Row counts are stamped in S3 object metadata at write time to make that check a `head_object`. A deliberate shrink still means deleting the object by hand.+- Signal text never leaves ClickHouse: the query selects the vector and the structured metadata (weight, source, match graph), not `content` or the free-text metadata fields.+### Configuration| Setting | Default | Meaning |@@ -53,7 +68,7 @@ All reads route to the offline cluster replicas on Cloud (`etl_workload()`), car### Operating it- Backfill any day range from the Dagster UI; partitions start 2026-04-01 (the label epoch). Every asset sits in the `inbox_ranking_etl` pool so concurrent partitions don't each start their own fleet-wide embeddings scan — the pool's limit is a Dagster deployment setting, provisioned with the bucket.-- Failures alert `#alerts-self-driving` (owner `team-self-driving`); assets retry twice with a 60s delay before failing a run. A UI-launched materialization runs under Dagster's implicit `__ASSET_JOB`, which carries no owner tag, so alert routing falls back to matching the `inbox_report_` asset-name prefix.+- Failures alert `#alerts-self-driving` (owner `team-self-driving`); assets retry twice with a 60s delay before failing a run. A UI-launched materialization runs under Dagster's implicit `__ASSET_JOB`, which carries no owner tag, so alert routing falls back to matching the `inbox_report_` and `inbox_signal_` asset-name prefixes.- The job is capped at 3h via `dagster/max_runtime` — the seven label streams run sequentially, each allowed up to 600s, and the join and S3 writes come after them.### Deletion and retention@@ -62,5 +77,6 @@ Partitions are immutable history, so a report deleted later keeps its rows (andThe embedding tombstone nulls the vector in every partition built after it, and `status='deleted'` flows through state from then on.**A re-run does not scrub a deleted report.** Label telemetry lives in the dogfood project and outlives the Postgres row, so a re-run regenerates the report as a label-only row: the id, its action/status/dismissal labels, and its team id come back, only the state columns go null.Scrubbing therefore means deleting the affected `dt=` objects (and rebuilding `latest/`), not re-running the partitions.+The same holds for signal rows, with one addition: a retraction can expire out of the source before any run scans it, so a scrub cannot be driven off `is_deleted` in this archive and has to work from the deleted report's id.Nothing in the team-deletion path knows about this prefix today, so the purge is manual until that is wired up - tracked with the bucket provisioning, and nothing is at risk before then because the assets write nothing until the bucket exists.The bucket is internal-only and access-restricted; a lifecycle policy for old partitions is a provisioning-time decision.diff --git a/products/signals/dags/inbox_ranking/common.py b/products/signals/dags/inbox_ranking/common.pyindex c5caa83e8fd5..da93e27ab81b 100644--- a/products/signals/dags/inbox_ranking/common.py+++ b/products/signals/dags/inbox_ranking/common.py@@ -101,6 +101,7 @@ def s3_client(): # noqa: ANN201SNAPSHOT_DATE_METADATA_KEY = "snapshot-date"+ROW_COUNT_METADATA_KEY = "row-count"def write_parquet(client, bucket: str, key: str, table: pa.Table, snapshot_date: str | None = None) -> None:@@ -111,7 +112,9 @@ def write_parquet(client, bucket: str, key: str, table: pa.Table, snapshot_date:so they grow past both the 5 GB single-request ceiling and what a second in-memory copy of theencoded file costs. `upload_fileobj` switches to a multipart upload on its own once the objectis large enough."""- metadata = {SNAPSHOT_DATE_METADATA_KEY: snapshot_date} if snapshot_date else {}+ metadata = {ROW_COUNT_METADATA_KEY: str(table.num_rows)}+ if snapshot_date:+ metadata[SNAPSHOT_DATE_METADATA_KEY] = snapshot_datewith tempfile.TemporaryFile() as spool:pq.write_table(table, spool, compression="zstd")spool.seek(0)@@ -130,11 +133,62 @@ def object_snapshot_date(client, bucket: str, key: str) -> str | None:return head.get("Metadata", {}).get(SNAPSHOT_DATE_METADATA_KEY)+def object_row_count(client, bucket: str, key: str) -> int | None:+ """The row count stamped on an object at write time, or None when the object is missing (or+ predates the stamp), so callers treat it as unknown rather than empty."""+ try:+ head = client.head_object(Bucket=bucket, Key=key)+ except ClientError as error:+ if error.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):+ return None+ raise+ stamped = head.get("Metadata", {}).get(ROW_COUNT_METADATA_KEY)+ return int(stamped) if stamped is not None else None+++def partition_write_allowed(existing_row_count: int | None, row_count: int) -> bool:+ """Whether a re-run may overwrite a partition it has already written.++ A backstop, not the primary defense: an incremental partition is rewritten from the union of+ what it already holds and what the source still returns (`merge_emission_rows`), so a re-run can+ only ever grow. A smaller count therefore means the union itself is broken, and refusing the+ write keeps a bug from destroying rows the source can no longer supply. An unknown count (no+ object, or one written before the stamp) is not a veto."""+ return existing_row_count is None or row_count >= existing_row_count+++def merge_emission_rows(existing: pa.Table, fresh: pa.Table, key_columns: tuple[str, ...]) -> pa.Table:+ """Union an already-written emission partition with a fresh scan, keeping every archived row.++ A re-run cannot simply overwrite: the source drops rows (a ReplacingMergeTree merge, the TTL),+ so a later scan can be missing an emission this partition already captured, and that emission+ exists nowhere else. Comparing row counts alone would not catch it either, since a scan can lose+ one row and gain another and land on the same total. Keeping the existing rows and appending only+ unseen ones makes a re-run additive, so no re-run can remove archived history.++ Only the key columns are pulled into Python; the wide embedding column stays in Arrow.+ """+ seen = set(zip(*(existing.column(name).to_pylist() for name in key_columns), strict=True))+ fresh_keys = zip(*(fresh.column(name).to_pylist() for name in key_columns), strict=True)+ mask = pa.array([key not in seen for key in fresh_keys], type=pa.bool_())+ return pa.concat_tables([existing, fresh.filter(mask)])++def read_parquet(client, bucket: str, key: str) -> pa.Table:body = client.get_object(Bucket=bucket, Key=key)["Body"].read()return pq.read_table(pa.BufferReader(body))+def read_parquet_if_exists(client, bucket: str, key: str) -> pa.Table | None:+ """The object's rows, or None when it was never written."""+ try:+ return read_parquet(client, bucket, key)+ except ClientError as error:+ if error.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):+ return None+ raise++def ensure_utc(value: datetime.datetime | None) -> datetime.datetime | None:"""ClickHouse drivers return naive UTC datetimes; Parquet timestamp columns want aware ones."""if value is None:diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.pyindex 6fcdcf4f3ee2..34a78d0635aa 100644--- a/products/signals/dags/inbox_ranking/dataset/dag.py+++ b/products/signals/dags/inbox_ranking/dataset/dag.py@@ -1,11 +1,15 @@"""Daily modeling dataset for the Self-driving Inbox report-ranking model.-Four assets on one daily partition, each writing Parquet under the configured S3 prefix:+Five assets on one daily partition, each writing Parquet under the configured S3 prefix:inbox_report_state/v1/dt=D/ Postgres spine + report state + tabular featuresinbox_report_embeddings/v1/dt=D/ report_id -> small-1536 vector as of snapshot endinbox_report_labels/v1/dt=D/ cumulative label columns from the dogfood project's eventsinbox_report_model_data/v1/dt=D/ materialized join of the three, plus a rewritten latest/+ inbox_signal_embeddings/v1/dt=D/ one row per signal emission during D, for the group-level model++The first four are report grain and feed one table; the fifth is signal grain and is read on its+own, joined to the others by report_id at training time.Partition dt=D is a full snapshot of the eligible report inventory (promoted or ever-labeled),with every label aggregate bounded `event_time < D+1 00:00 UTC`. Label columns are cumulative,@@ -16,6 +20,9 @@ are never backfilled into old partitions.Point-in-time caveats, per source:- labels are fully point-in-time for any past day (explicit event-time bound);- embeddings are point-in-time within the underlying table's 3-month TTL (inserted_at bound);+- signal embeddings are exact for any past day within that same TTL, which is measured from signal+ event time — a day whose signals have since aged out cannot be rebuilt, and the asset refuses to+ overwrite a partition with fewer rows rather than quietly shrink it;- report state is current-state-only. A backfilled partition therefore carries *today's* Postgresstate, flagged by features_observed_at being far after snapshot_date. Only forward-run dailypartitions are true point-in-time snapshots. This reaches row *inclusion*, not just feature@@ -42,6 +49,11 @@ from posthog.dags.common import dagster_tagsfrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.report_embeddings import EMBEDDING_DOCUMENT_TYPE, EMBEDDING_PRODUCT, EMBEDDING_RENDERING+from products.signals.backend.signal_metadata import (+ SIGNAL_DOCUMENT_PRODUCT,+ SIGNAL_DOCUMENT_RENDERING,+ SIGNAL_DOCUMENT_TYPE,+)from products.signals.dags.inbox_ranking.common import (DATASET_VERSION,S3_BUCKET_ENV,@@ -50,11 +62,15 @@ from products.signals.dags.inbox_ranking.common import (ensure_utc,latest_is_stale,latest_object_key,+ merge_emission_rows,+ object_row_count,object_snapshot_date,owner_tags,partition_def,partition_object_key,+ partition_write_allowed,read_parquet,+ read_parquet_if_exists,s3_client,skip_unconfigured,snapshot_bounds,@@ -66,6 +82,8 @@ from products.signals.dags.inbox_ranking.dataset.queries import (LABELED_REPORT_IDS_SQL,REPORT_EMBEDDINGS_QUERY_SETTINGS,REPORT_EMBEDDINGS_SQL,+ SIGNAL_EMBEDDINGS_QUERY_SETTINGS,+ SIGNAL_EMBEDDINGS_SQL,etl_workload,hogql_rows,labels_team,@@ -89,6 +107,7 @@ STATE_TABLE = "inbox_report_state"EMBEDDINGS_TABLE = "inbox_report_embeddings"LABELS_TABLE = "inbox_report_labels"MODEL_DATA_TABLE = "inbox_report_model_data"+SIGNAL_EMBEDDINGS_TABLE = "inbox_signal_embeddings"COMMON_ASSET_KWARGS: dict[str, Any] = {"group_name": "inbox_ranking",@@ -149,6 +168,31 @@ _EMBEDDING_FIELDS: list[tuple[str, pa.DataType]] = []EMBEDDINGS_SCHEMA = pa.schema(_EMBEDDING_FIELDS)+_SIGNAL_EMBEDDING_FIELDS: list[tuple[str, pa.DataType]] = [+ ("snapshot_date", pa.date32()),+ ("signal_id", pa.string()),+ ("team_id", pa.int64()),+ ("report_id", pa.string()),+ ("signal_timestamp", _TIMESTAMP),+ ("embedding_inserted_at", _TIMESTAMP),+ ("embedding_small", pa.list_(pa.float32())),+ ("embedding_rendering", pa.string()),+ ("weight", pa.float32()),+ ("source_product", pa.string()),+ ("source_type", pa.string()),+ ("source_id", pa.string()),+ ("is_deleted", pa.bool_()),+ ("match_kind", pa.string()),+ ("match_parent_signal_id", pa.string()),+ ("rejected_signal_count", pa.int32()),+]+SIGNAL_EMBEDDINGS_SCHEMA = pa.schema(_SIGNAL_EMBEDDING_FIELDS)++# What makes one emission distinct from another, so a re-run can tell a row it already archived from+# a genuinely new one. embedding_inserted_at is the version: the source keys a signal by+# (team_id, document_id) and distinguishes its versions by inserted_at.+SIGNAL_EMISSION_KEY = ("team_id", "signal_id", "embedding_inserted_at")+LABEL_FIELDS: list[tuple[str, pa.DataType]] = [("first_impressed_at", _TIMESTAMP),("impression_unit_count", pa.int32()),@@ -509,6 +553,138 @@ def inbox_report_embeddings(context: dagster.AssetExecutionContext) -> None:)[email protected](name=SIGNAL_EMBEDDINGS_TABLE, **COMMON_ASSET_KWARGS)+def inbox_signal_embeddings(context: dagster.AssetExecutionContext) -> None:+ """One row per signal emission in the partition day, for the group-level model.++ This asset is an emission log, not a snapshot, and is the one table in this dag whose partitions+ do not each hold the full inventory: dt=D carries only what was inserted during D. Training+ reads the union of partitions and takes the latest row per (team_id, signal_id) at or before its+ cutoff, the same argMax the other assets do in SQL, moved to read time. The tenant key is part of+ the identity because signal_id is a caller-supplied document_id that is only unique within a team.+ Snapshotting instead would copy a+ 1536-float vector per signal fleet-wide every day, which is several GB daily against tens of MB+ for a day's emissions.++ Writing the day's emissions down also outlives the source table's 3-month TTL, which is measured+ from signal event time. That makes this dag the durable store for signal vectors: whatever is not+ captured before a signal ages out is unrecoverable. A re-run is therefore additive rather than a+ replacement — it unions the fresh scan into what the partition already holds, so a row the source+ can no longer supply survives.++ The log is best-effort, and deliberately so. The source is a ReplacingMergeTree versioned by+ inserted_at, and a retraction re-emits the signal under the same sort key, so a merge between the+ two writes keeps only the retraction. A signal whose report is deleted in the same window it was+ inserted therefore reaches no partition in its live form, and no query shape recovers it, since+ the merge has already dropped the row. The reverse gap is the TTL: a retraction inherits the+ original event timestamp, so retracting a signal more than three months old writes a row that is+ already expired and may never be scanned. Absence of an is_deleted row is not proof a signal is+ live. Closing either gap needs an append-only source or a changed emission contract, both out of+ this asset's scope.+ """+ if skip_unconfigured(context):+ return+ _tag_dagster_queries(context)+ partition_key = context.partition_key+ window_start, window_end = snapshot_bounds(partition_key)+ snapshot_date = datetime.date.fromisoformat(partition_key)++ results = cast(+ list[tuple[Any, ...]],+ sync_execute(+ SIGNAL_EMBEDDINGS_SQL,+ {+ "product": SIGNAL_DOCUMENT_PRODUCT,+ "document_type": SIGNAL_DOCUMENT_TYPE,+ "rendering": SIGNAL_DOCUMENT_RENDERING,+ "window_start": window_start.replace(tzinfo=None),+ "window_end": window_end.replace(tzinfo=None),+ },+ settings=SIGNAL_EMBEDDINGS_QUERY_SETTINGS,+ workload=etl_workload(),+ )+ or [],+ )++ # Column-wise into Arrow, releasing each source row as it is converted, for the same reason the+ # report embeddings asset does it: the vectors are the widest thing this dag holds.+ row_count = len(results)+ deleted_count = 0+ columns: dict[str, list[Any]] = {name: [] for name, _type in _SIGNAL_EMBEDDING_FIELDS}+ for index in range(row_count):+ (+ team_id,+ signal_id,+ report_id,+ timestamp,+ inserted_at,+ embedding,+ weight,+ source_product,+ source_type,+ source_id,+ is_deleted,+ match_kind,+ match_parent_signal_id,+ rejected_signal_count,+ ) = results[index]+ results[index] = ()+ if is_deleted:+ deleted_count += 1+ columns["snapshot_date"].append(snapshot_date)+ columns["signal_id"].append(str(signal_id))+ columns["team_id"].append(int(team_id))+ columns["report_id"].append(report_id)+ columns["signal_timestamp"].append(ensure_utc(timestamp))+ columns["embedding_inserted_at"].append(ensure_utc(inserted_at))+ # A retracted signal is re-emitted with its original text, unlike a report tombstone, so its+ # vector is real content that we have been told to stop showing. A partition written while it+ # was live keeps it; this one records the retraction without carrying the content forward.+ # Whether such a partition exists depends on merge timing — see the docstring's best-effort note.+ columns["embedding_small"].append(None if is_deleted else list(embedding))+ columns["embedding_rendering"].append(SIGNAL_DOCUMENT_RENDERING)+ columns["weight"].append(weight)+ columns["source_product"].append(source_product)+ columns["source_type"].append(source_type)+ columns["source_id"].append(source_id)+ columns["is_deleted"].append(bool(is_deleted))+ columns["match_kind"].append(match_kind)+ columns["match_parent_signal_id"].append(match_parent_signal_id)+ columns["rejected_signal_count"].append(rejected_signal_count)+ del results++ table = pa.Table.from_pydict(columns, schema=SIGNAL_EMBEDDINGS_SCHEMA)++ bucket = dataset_bucket()+ key = partition_object_key(settings.INBOX_RANKING_DATASET_S3_PREFIX, SIGNAL_EMBEDDINGS_TABLE, partition_key)+ client = s3_client()+ # A re-run is additive. The source can no longer supply a row this partition already archived —+ # a merge or the TTL removed it — so overwriting with the fresh scan alone would delete history+ # that exists nowhere else. Row counts cannot police that on their own: a scan can lose one+ # emission and gain another and land on the same total.+ existing = read_parquet_if_exists(client, bucket, key)+ if existing is not None:+ table = merge_emission_rows(existing, table, SIGNAL_EMISSION_KEY)+ existing_row_count = object_row_count(client, bucket, key)+ if not partition_write_allowed(existing_row_count, table.num_rows):+ raise dagster.Failure(+ f"{SIGNAL_EMBEDDINGS_TABLE} dt={partition_key} already holds {existing_row_count} rows and the union "+ f"with this run produced {table.num_rows}: a union can only grow, so this is a bug in the merge rather "+ "than a source change. Refusing the write to keep archived rows the source may no longer hold."+ )+ write_parquet(client, bucket, key, table)+ context.add_output_metadata(+ {+ "rows": dagster.MetadataValue.int(table.num_rows),+ "scanned": dagster.MetadataValue.int(row_count),+ "carried_over": dagster.MetadataValue.int(table.num_rows - row_count),+ "retracted": dagster.MetadataValue.int(deleted_count),+ "reports": dagster.MetadataValue.int(len({report_id for report_id in columns["report_id"] if report_id})),+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),+ }+ )++@dagster.asset(name=LABELS_TABLE, **COMMON_ASSET_KWARGS)def inbox_report_labels(context: dagster.AssetExecutionContext) -> None:if skip_unconfigured(context):@@ -701,7 +877,7 @@ def inbox_report_model_data(context: dagster.AssetExecutionContext) -> None:inbox_ranking_dataset_job = dagster.define_asset_job(name="inbox_ranking_dataset_job",- selection=[STATE_TABLE, EMBEDDINGS_TABLE, LABELS_TABLE, MODEL_DATA_TABLE],+ selection=[STATE_TABLE, EMBEDDINGS_TABLE, SIGNAL_EMBEDDINGS_TABLE, LABELS_TABLE, MODEL_DATA_TABLE],partitions_def=partition_def,# The seven label streams run sequentially and each may take its full 600s query timeout, so an# hour left a slow-but-valid pass no room for the join, the S3 writes, or an asset retry — anddiff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.pyindex a28eaa8b63b1..c9a643e3041e 100644--- a/products/signals/dags/inbox_ranking/dataset/queries.py+++ b/products/signals/dags/inbox_ranking/dataset/queries.py@@ -176,6 +176,66 @@ WHERE product = %(product)sGROUP BY team_id, document_id"""+# Signal documents: the grouping pipeline's own rows in the same table, one per signal, carrying the+# report they grouped into in the metadata JSON. Read incrementally by inserted_at rather than as a+# snapshot — at signal grain a cumulative copy is several GB a day (a 1536-float vector per signal,+# fleet-wide) against tens of MB for one day's emissions.+#+# Rows come back raw, with no argMax dedupe: this scan never builds the wide aggregation states the+# report query needs, and both versions of a re-emitted signal are kept when both survive to be read.+# Readers take the latest row per (team_id, signal_id) at or before their cutoff, because a+# caller-supplied document_id is only unique within a team.+#+# "When both survive" is the honest limit: the source replaces on (team, day, product, document_type,+# rendering, document_id) and a retraction re-emits under that same key, so a merge before this scan+# leaves only the retraction. argMax would not save it — the merge removes the row, it does not hide+# it. The asset docstring records what that costs and why closing it is out of scope here.+#+# Index reality is the report query's, minus the GROUP BY: no team_id sort-key prefix and no+# inserted_at in the sort key, so this full-scans the TTL-bounded table with PREWHERE filtering the+# small columns before the wide embedding column is read. The memory budget is half the report+# scan's because nothing is aggregated.+SIGNAL_EMBEDDINGS_QUERY_SETTINGS: dict[str, int] = {+ "max_execution_time": 600,+ "max_memory_usage": 10 * 1024**3,+}++# `content` is deliberately not selected: the vector is the feature, and the signal's verbatim source+# text has no business leaving ClickHouse. Same for the free-text metadata fields (extra, remediation,+# match_query, reason) — only the structured ones are extracted here.+SIGNAL_EMBEDDINGS_SQL = f"""+SELECT+ team_id,+ document_id,+ nullIf(JSONExtractString(metadata, 'report_id'), '') AS report_id,+ timestamp,+ inserted_at,+ embedding,+ JSONExtractFloat(metadata, 'weight') AS weight,+ nullIf(JSONExtractString(metadata, 'source_product'), '') AS source_product,+ nullIf(JSONExtractString(metadata, 'source_type'), '') AS source_type,+ nullIf(JSONExtractString(metadata, 'source_id'), '') AS source_id,+ JSONExtractBool(metadata, 'deleted') AS is_deleted,+ -- A matched signal's metadata carries parent_signal_id, an unmatched one's carries+ -- rejected_signal_ids, and both carry reason — so the parent check has to come first.+ nullIf(+ multiIf(+ JSONHas(metadata, 'match_metadata', 'parent_signal_id'), 'matched',+ JSONHas(metadata, 'match_metadata', 'reason'), 'no_match',+ ''+ ),+ ''+ ) AS match_kind,+ nullIf(JSONExtractString(metadata, 'match_metadata', 'parent_signal_id'), '') AS match_parent_signal_id,+ JSONLength(metadata, 'match_metadata', 'rejected_signal_ids') AS rejected_signal_count+FROM {EMBEDDINGS_TABLE}+WHERE product = %(product)s+ AND document_type = %(document_type)s+ AND rendering = %(rendering)s+ AND inserted_at >= %(window_start)s+ AND inserted_at < %(window_end)s+"""+IMPRESSIONS_COLUMNS = ("first_impressed_at","impression_unit_count",diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.pyindex 78013a3aee55..e2ad635dc414 100644--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py@@ -4,6 +4,8 @@ from typing import Anyimport pytestfrom posthog.test.base import BaseTest+import pyarrow as pa+from products.signals.backend.models import SignalReportfrom products.signals.dags.inbox_ranking import commonfrom products.signals.dags.inbox_ranking.dataset.dag import (@@ -71,6 +73,62 @@ def test_latest_advances_monotonically_and_backfills_never_clobber_it(existing,assert common.latest_is_stale(existing, partition_key) is expected+ "existing,row_count,expected",+ [+ (None, 0, True),+ (1200, 1200, True),+ (1200, 1500, True),+ (1200, 1199, False),+ (1200, 0, False),+ ],+)+def test_incremental_partitions_never_shrink_on_a_re_run(existing, row_count, expected):+ # Signal vectors are read back out of a table with a 3-month TTL, so a late re-run of an old+ # partition returns fewer rows than it first captured — and those rows no longer exist anywhere+ # else. Overwriting is unrecoverable data loss, so a shrink must fail rather than proceed.+ assert common.partition_write_allowed(existing, row_count) is expected+++def _emission(signal_id: str, inserted_at: datetime.datetime, embedding: list[float] | None):+ return {"team_id": 2, "signal_id": signal_id, "embedding_inserted_at": inserted_at, "embedding_small": embedding}+++_EMISSION_FIELDS: list[tuple[str, pa.DataType]] = [+ ("team_id", pa.int64()),+ ("signal_id", pa.string()),+ ("embedding_inserted_at", pa.timestamp("us", tz="UTC")),+ ("embedding_small", pa.list_(pa.float32())),+]+_EMISSION_SCHEMA = pa.schema(_EMISSION_FIELDS)+++def test_re_running_a_partition_keeps_rows_the_source_no_longer_returns():+ # The source drops rows a partition already archived (a ReplacingMergeTree merge collapses a+ # retracted signal onto its live row, or the TTL expires it), and those rows exist nowhere else.+ # A re-run that wrote only its own scan would delete them permanently. Row counts alone cannot+ # police it: here the scan loses signal a and gains signal c, so the total never changes.+ existing = pa.Table.from_pylist([_emission("a", T1, [0.25]), _emission("b", T1, [0.5])], schema=_EMISSION_SCHEMA)+ fresh = pa.Table.from_pylist([_emission("b", T1, [0.5]), _emission("c", T2, [0.75])], schema=_EMISSION_SCHEMA)++ merged = common.merge_emission_rows(existing, fresh, ("team_id", "signal_id", "embedding_inserted_at"))++ assert merged.column("signal_id").to_pylist() == ["a", "b", "c"]+ # The archived vector survives intact, and b is carried once rather than duplicated.+ assert merged.column("embedding_small").to_pylist() == [[0.25], [0.5], [0.75]]+++def test_a_re_emitted_signal_keeps_both_versions():+ # Versions of one signal are separate emissions, so a later vector must not displace the earlier+ # one the partition archived — that is the history this table exists to hold.+ existing = pa.Table.from_pylist([_emission("a", T1, [0.25])], schema=_EMISSION_SCHEMA)+ fresh = pa.Table.from_pylist([_emission("a", T2, [0.5])], schema=_EMISSION_SCHEMA)++ merged = common.merge_emission_rows(existing, fresh, ("team_id", "signal_id", "embedding_inserted_at"))++ assert merged.column("embedding_inserted_at").to_pylist() == [T1, T2]++def test_snapshot_bounds_cover_the_partition_day():start, end = common.snapshot_bounds("2026-07-29")assert start == datetime.datetime(2026, 7, 29, tzinfo=datetime.UTC)