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.

feat(signals): add daily inbox ranking modeling dataset dagster job (#75597)

Andrew Maguire2991bfb2ddd3
diff --git a/.dagster_home/workspace.yaml b/.dagster_home/workspace.yaml
index 643ec2155b93..acc64affe3f8 100644
--- a/.dagster_home/workspace.yaml
+++ b/.dagster_home/workspace.yaml
@@ -15,6 +15,7 @@ load_from:
- python_module: posthog.dags.locations.growth
- python_module: posthog.dags.locations.shared
+ - python_module: posthog.dags.locations.signals
- python_module: posthog.dags.locations.ingestion
- python_module: posthog.dags.locations.posthog_ai
- python_module: posthog.dags.locations.web_analytics
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.yml
index 48d2cb3f052f..8bff9b8892dc 100644
--- a/.github/workflows/ci-dagster.yml
+++ b/.github/workflows/ci-dagster.yml
@@ -151,6 +151,7 @@ jobs:
- 'products/error_tracking/backend/**/*.py'
- 'products/event_definitions/backend/**/*.py'
- 'products/growth/backend/**/*.py'
+ - 'products/signals/backend/**/*.py'
- 'products/marketing_analytics/backend/**/*.py'
- 'products/ai_observability/backend/**/*.py'
- 'products/posthog_ai/backend/**/*.py'
diff --git a/posthog/dags/common/owners.py b/posthog/dags/common/owners.py
index b03f79a34151..186a2c7774d7 100644
--- a/posthog/dags/common/owners.py
+++ b/posthog/dags/common/owners.py
@@ -18,5 +18,6 @@ class JobOwners(str, Enum):
TEAM_POSTHOG_AI = "team-posthog-ai"
TEAM_QUERY_PERFORMANCE = "team-query-performance"
TEAM_SECURITY = "team-security"
+ TEAM_SELF_DRIVING = "team-self-driving"
TEAM_WAREHOUSE_SOURCES = "team-warehouse-sources"
TEAM_WEB_ANALYTICS = "team-web-analytics"
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.py
new file mode 100644
index 000000000000..5d278e81bf74
--- /dev/null
+++ b/posthog/dags/locations/signals.py
@@ -0,0 +1,24 @@
+import dagster
+
+from products.signals.dags.inbox_ranking.common import is_inbox_ranking_registered
+from products.signals.dags.inbox_ranking.dataset import dag as inbox_ranking_dataset
+
+from . import loggers, resources
+
+# The inbox-ranking dataset reads US Postgres/ClickHouse plus the US dogfood project's label
+# events; EU has neither, so the definitions register on US (and non-cloud) only.
+if is_inbox_ranking_registered():
+ defs = dagster.Definitions(
+ assets=[
+ inbox_ranking_dataset.inbox_report_state,
+ inbox_ranking_dataset.inbox_report_embeddings,
+ inbox_ranking_dataset.inbox_report_labels,
+ inbox_ranking_dataset.inbox_report_model_data,
+ ],
+ jobs=[inbox_ranking_dataset.inbox_ranking_dataset_job],
+ schedules=[inbox_ranking_dataset.inbox_ranking_dataset_schedule],
+ loggers=loggers,
+ resources=resources,
+ )
+else:
+ defs = dagster.Definitions(loggers=loggers, resources=resources)
diff --git a/posthog/dags/slack_alerts.py b/posthog/dags/slack_alerts.py
index 33e8e2a30675..98f5a06a2f14 100644
--- a/posthog/dags/slack_alerts.py
+++ b/posthog/dags/slack_alerts.py
@@ -25,6 +25,7 @@ notification_channel_per_team = {
JobOwners.TEAM_POSTHOG_AI.value: "#alerts-max-ai",
JobOwners.TEAM_QUERY_PERFORMANCE.value: "#alerts-query-performance",
JobOwners.TEAM_SECURITY.value: "#alerts-security",
+ JobOwners.TEAM_SELF_DRIVING.value: "#alerts-self-driving",
JobOwners.TEAM_WAREHOUSE_SOURCES.value: "#alerts-warehouse-sources",
JobOwners.TEAM_WEB_ANALYTICS.value: "#alerts-web-analytics",
}
@@ -98,6 +99,15 @@ def send_slack_alert(context, client, channel: str, blocks: list, fallback_text:
context.log.exception(f"Failed to send text-only Slack fallback to {channel}: {str(e)}")
+# A manually materialized or backfilled asset runs under Dagster's implicit `__ASSET_JOB`, whose
+# run tags carry no owner, so ownership has to come from the failed step names instead. First
+# matching prefix wins; assets whose names don't start with one of these fall back to the run tag.
+ASSET_NAME_PREFIX_OWNERS: tuple[tuple[str, JobOwners], ...] = (
+ ("web_", JobOwners.TEAM_WEB_ANALYTICS),
+ ("inbox_report_", JobOwners.TEAM_SELF_DRIVING),
+)
+
+
def get_job_owner_for_alert(failed_run: dagster.DagsterRun, error_message: str) -> str:
"""Determine the correct job owner for alert routing, with special handling for asset jobs."""
job_name = failed_run.job_name
@@ -105,16 +115,15 @@ def get_job_owner_for_alert(failed_run: dagster.DagsterRun, error_message: str)
# Special handling for manually launched asset jobs
if job_name == "__ASSET_JOB":
- # Check if the error message contains web_ prefixed failed steps
# Pattern: "Steps failed: ['web_pre_aggregated_bounces', 'web_pre_aggregated_stats']"
- web_step_pattern = r"Steps failed:.*?\[([^\]]+)\]"
- match = re.search(web_step_pattern, error_message)
+ step_pattern = r"Steps failed:.*?\[([^\]]+)\]"
+ match = re.search(step_pattern, error_message)
if match:
steps_text = match.group(1)
- # Check if any step starts with 'web_'
- if re.search(r"'web_[^']*'", steps_text):
- return JobOwners.TEAM_WEB_ANALYTICS.value
+ for prefix, owner in ASSET_NAME_PREFIX_OWNERS:
+ if re.search(rf"'{re.escape(prefix)}[^']*'", steps_text):
+ return owner.value
return job_owner
diff --git a/posthog/dags/tests/test_loggers.py b/posthog/dags/tests/test_loggers.py
index e2c36af6050f..7b107e88562c 100644
--- a/posthog/dags/tests/test_loggers.py
+++ b/posthog/dags/tests/test_loggers.py
@@ -21,6 +21,7 @@ LOCATION_MODULES = [
"posthog_ai",
"revenue_analytics",
"shared",
+ "signals",
"web_analytics",
]
diff --git a/posthog/dags/tests/test_slack_alerts.py b/posthog/dags/tests/test_slack_alerts.py
index 9b0d161bef0c..b2f0a0962013 100644
--- a/posthog/dags/tests/test_slack_alerts.py
+++ b/posthog/dags/tests/test_slack_alerts.py
@@ -48,6 +48,17 @@ class TestSlackAlertsRouting:
assert result == JobOwners.TEAM_WEB_ANALYTICS.value
+ def test_asset_job_with_inbox_report_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_report_labels']."
+
+ 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/posthog/settings/object_storage.py b/posthog/settings/object_storage.py
index d98f414fac65..c70fbd69e133 100644
--- a/posthog/settings/object_storage.py
+++ b/posthog/settings/object_storage.py
@@ -65,6 +65,14 @@ AGENT_BUNDLES_S3_BUCKET = os.getenv("AGENT_BUNDLES_S3_BUCKET") or OBJECT_STORAGE
AI_BLOB_S3_BUCKET = os.getenv("AI_BLOB_S3_BUCKET", "ai-blobs")
AI_BLOB_S3_PREFIX = os.getenv("AI_BLOB_S3_PREFIX", "aio/")
+# Inbox ranking modeling dataset (products/signals/dags/inbox_ranking): daily report-grain
+# Parquet snapshots the ranking model trains on. Unset bucket on Cloud means the dags skip until
+# the dedicated bucket is provisioned; local dev falls back to the object-storage service. The
+# bucket is written by Dagster via boto3 (node role on prod) and read by project-2 warehouse
+# tables and mlhog training via a separate read-only credential.
+INBOX_RANKING_DATASET_S3_BUCKET = os.getenv("INBOX_RANKING_DATASET_S3_BUCKET", "")
+INBOX_RANKING_DATASET_S3_PREFIX = os.getenv("INBOX_RANKING_DATASET_S3_PREFIX", "inbox_ranking")
+
# Identity matching scratch storage (products/growth `identity_matching_job`). The job writes
# per-run Parquet objects via ClickHouse `INSERT INTO FUNCTION s3(...)` and the read API globs
# them back with `s3(...)`, so only the ClickHouse cluster needs bucket access — the Dagster
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index b6b15038b6c0..c62670ed3f5f 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -1346,6 +1346,8 @@ products/signals/
│ ├── signal_queries.py # Canonical HogQL helpers for fetch/search/soft-delete/wait
│ ├── summary.py # SignalReportSummaryWorkflow + report state transition activities
│ └── types.py # Shared dataclasses + signal rendering helpers
+├── dags/
+│ └── inbox_ranking/ # Dagster dags for the report-ranking model (daily modeling dataset) — see its README.md + AGENTS.md
├── skills/ # Signals skills — see skills/AGENTS.md
│ ├── AGENTS.md
│ ├── signals/ # Official PostHog skill (published via posthog_ai/dist): querying signals data
diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.md
new file mode 100644
index 000000000000..bdaf33f291c0
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/AGENTS.md
@@ -0,0 +1,24 @@
+# Agent notes: inbox_ranking dags
+
+Read `README.md` first for what the dataset is and how partitions behave. This file is the guardrails for changing code here.
+
+## Extending
+
+- A new ranking dag (training, eval, ...) is a **sibling subpackage** (`inbox_ranking/<name>/dag.py`) importing shared plumbing from `common.py` — don't grow `dataset/` sideways and don't duplicate the S3/partition helpers.
+- Register new jobs/schedules in `posthog/dags/locations/signals.py`, keep the EU gate (`is_inbox_ranking_registered()`), and remember the ci-dagster paths filter must cover every module a dag file imports (`uv run .github/scripts/check-dagster-paths.py`).
+
+## 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.
+- 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.
+- Cross-team ClickHouse reads stay on the offline workload with explicit guards; team-2 label queries keep their event + timestamp bounds aligned with the events sort key.
+
+## Context that lives outside the repo
+
+The cross-session design record (decision history, label catalog, schema mock, backlog) is the `inbox-ranking` skill in the PostHog skills store — load it with `/phs inbox-ranking` before making design-level changes here.
+
+## Verify loop
+
+`pytest products/signals/dags/inbox_ranking/tests/`, then confirm the location resolves (import `posthog.dags.locations.signals` under Django) and run repo-wide mypy.
diff --git a/products/signals/dags/inbox_ranking/CLAUDE.md b/products/signals/dags/inbox_ranking/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
new file mode 100644
index 000000000000..594e2b0884b1
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -0,0 +1,66 @@
+# Inbox ranking Dagster dags
+
+Dagster jobs for the Self-driving Inbox report-ranking model.
+The one dag today is the **dataset** dag; future ranking dags (training, eval) live as sibling subpackages sharing `common.py`.
+
+```text
+inbox_ranking/
+├── common.py # shared: S3 destination config, daily partition def, gating, Parquet IO
+├── dataset/
+│ ├── dag.py # the four dataset assets + job + schedule
+│ └── queries.py # HogQL label SQL, embeddings SQL, stream merging
+└── tests/
+```
+
+Registered via `posthog/dags/locations/signals.py` (US only) and loaded locally through `.dagster_home/workspace.yaml`.
+
+## 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:
+
+```text
+s3://<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
+```
+
+### 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`.
+- Label columns are **cumulative**: later partitions strictly dominate earlier ones, so training reads features from `dt=D` and labels from any later partition, choosing the label-maturity window at read time. Late labels are never backfilled into old partitions.
+- `latest/` advances **monotonically**: each write stamps a `snapshot-date` in S3 object metadata, and a partition rewrites `latest/` only when it is at or ahead of what `latest/` holds. Delayed retries of the newest day repair it; backfills of older days never clobber it.
+- Rows for reports **outside this dag's region** are label-only: no Postgres state, no embedding, and `report_team_id` null (a US team id and an EU team id of the same number are different teams, so the label stream's id can't be merged in). `status_event_team_id` carries the team the transition itself reported, which is the tenant attribution those rows do have.
+- **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.
+
+### Configuration
+
+| Setting | Default | Meaning |
+| --------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `INBOX_RANKING_DATASET_S3_BUCKET` | unset | Destination bucket. Unset on Cloud makes every asset log and skip, so the dag can deploy before the bucket exists. Unset elsewhere falls back to the deployment's object-storage service (SeaweedFS in dev and CI). |
+| `INBOX_RANKING_DATASET_S3_PREFIX` | `inbox_ranking` | Key prefix under the bucket. |
+
+Writes use boto3: ambient AWS config (the node role) when the dedicated bucket is set, the `OBJECT_STORAGE_*` endpoint and credentials otherwise. Readers (project-level warehouse tables, model training) use a separate read-only credential provisioned with the bucket.
+
+### ClickHouse posture
+
+All reads route to the offline cluster replicas on Cloud (`etl_workload()`), carry the dagster run in `log_comment`, and the cross-team embeddings scan runs under explicit time/memory/spill guards (see `queries.py` for why that scan has no `team_id` sort-key prefix and why that is acceptable).
+
+### 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.
+- The job is capped at 3h via `dagster/max_runtime` — the six label streams run sequentially, each allowed up to 600s, and the join and S3 writes come after them.
+
+### Deletion and retention
+
+Partitions are immutable history, so a report deleted later keeps its rows (and vector) in partitions written before the deletion.
+The 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.
+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.py
new file mode 100644
index 000000000000..c5caa83e8fd5
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/common.py
@@ -0,0 +1,144 @@
+"""Shared plumbing for the inbox-ranking Dagster dags.
+
+Everything here is dag-agnostic: the S3 destination (bucket, prefix, key layout), the daily
+partition scheme, gating, and Parquet IO. Individual dags (dataset today, training/eval later)
+live in sibling packages and import from here so they share one destination and one partition
+definition.
+"""
+
+import datetime
+import tempfile
+
+import boto3
+import dagster
+import pyarrow as pa
+import pyarrow.parquet as pq
+from botocore.exceptions import ClientError
+
+from posthog import settings
+from posthog.dags.common import JobOwners
+
+DATASET_VERSION = "v1"
+
+S3_BUCKET_ENV = "INBOX_RANKING_DATASET_S3_BUCKET"
+
+PARQUET_PART_NAME = "part-00000.parquet"
+
+# Earliest label event worth reading: report-attributed pr_created starts 2026-04-20, and the
+# other label streams start later. Also the earliest backfillable partition.
+# The explicit +00:00 offset is load-bearing: HogQL's toDateTime parses bare datetime strings in
+# the querying team's timezone (US/Pacific for the dogfood project), which would shift every
+# label bound 7-8 hours off the UTC partition boundary. An embedded offset overrides that.
+LABELS_EPOCH = "2026-04-01T00:00:00+00:00"
+
+partition_def = dagster.DailyPartitionsDefinition(start_date="2026-04-01")
+
+owner_tags: dict[str, str] = {"owner": JobOwners.TEAM_SELF_DRIVING.value}
+
+
+def is_inbox_ranking_registered() -> bool:
+ """EU report rows and embeddings are unreachable from a US dag, and labels from every region
+ already land in the US dogfood project, so the whole location registers on US only."""
+ return settings.CLOUD_DEPLOYMENT != "EU"
+
+
+def dataset_unconfigured() -> bool:
+ # On Cloud the dataset must never fall back to the shared object-storage bucket: assets skip
+ # until the dedicated bucket is provisioned. Local dev falls back to the object-storage service.
+ return bool(settings.CLOUD_DEPLOYMENT) and not settings.INBOX_RANKING_DATASET_S3_BUCKET
+
+
+def dataset_bucket() -> str:
+ return settings.INBOX_RANKING_DATASET_S3_BUCKET or settings.OBJECT_STORAGE_BUCKET
+
+
+def partition_object_key(prefix: str, table: str, partition_key: str) -> str:
+ return f"{prefix}/{table}/{DATASET_VERSION}/dt={partition_key}/{PARQUET_PART_NAME}"
+
+
+def latest_object_key(prefix: str, table: str) -> str:
+ return f"{prefix}/{table}/{DATASET_VERSION}/latest/{PARQUET_PART_NAME}"
+
+
+def snapshot_bounds(partition_key: str) -> tuple[datetime.datetime, datetime.datetime]:
+ """Partition dt=D covers [D 00:00, D+1 00:00) UTC; the upper bound is the snapshot end."""
+ day = datetime.date.fromisoformat(partition_key)
+ start = datetime.datetime.combine(day, datetime.time.min, tzinfo=datetime.UTC)
+ return start, start + datetime.timedelta(days=1)
+
+
+def latest_is_stale(existing_snapshot_date: str | None, partition_key: str) -> bool:
+ """latest/ advances monotonically: a partition at or ahead of what latest/ currently holds
+ rewrites it (so delayed retries of the newest day still repair it), while backfills of older
+ days never clobber it. ISO date strings compare chronologically."""
+ return existing_snapshot_date is None or partition_key >= existing_snapshot_date
+
+
+def skip_unconfigured(context: dagster.AssetExecutionContext) -> bool:
+ if dataset_unconfigured():
+ context.log.warning(
+ f"{S3_BUCKET_ENV} is not set on this Cloud deployment; skipping until the dedicated bucket is provisioned"
+ )
+ return True
+ return False
+
+
+# boto3.client("s3") is left untyped on purpose: mypy and pyright resolve it to different stub
+# packages (mypy_boto3_s3 vs types_boto3_s3), so a concrete S3Client annotation can't satisfy both.
+def s3_client(): # noqa: ANN201
+ # The dedicated bucket is reached via ambient AWS config (the node role on prod). Without it,
+ # every other environment (local dev, self-hosted, CI) uses the deployment's object-storage
+ # service, which needs its explicit endpoint and credentials regardless of DEBUG.
+ if settings.INBOX_RANKING_DATASET_S3_BUCKET:
+ return boto3.client("s3")
+ return boto3.client(
+ "s3",
+ endpoint_url=settings.OBJECT_STORAGE_ENDPOINT,
+ aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
+ aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
+ region_name=settings.OBJECT_STORAGE_REGION,
+ )
+
+
+SNAPSHOT_DATE_METADATA_KEY = "snapshot-date"
+
+
+def write_parquet(client, bucket: str, key: str, table: pa.Table, snapshot_date: str | None = None) -> None:
+ """Write one Parquet object at a deterministic key.
+
+ Spooled to a temp file and uploaded with `upload_fileobj` rather than held as bytes for
+ `put_object`: the embeddings and model-data snapshots carry a 1536-float vector per live report,
+ so they grow past both the 5 GB single-request ceiling and what a second in-memory copy of the
+ encoded file costs. `upload_fileobj` switches to a multipart upload on its own once the object
+ is large enough."""
+ metadata = {SNAPSHOT_DATE_METADATA_KEY: snapshot_date} if snapshot_date else {}
+ with tempfile.TemporaryFile() as spool:
+ pq.write_table(table, spool, compression="zstd")
+ spool.seek(0)
+ client.upload_fileobj(spool, bucket, key, ExtraArgs={"Metadata": metadata})
+
+
+def object_snapshot_date(client, bucket: str, key: str) -> str | None:
+ """The snapshot-date stamped on an object at write time, or None when the object is missing
+ (or predates the stamp), so callers treat it as replaceable."""
+ 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
+ return head.get("Metadata", {}).get(SNAPSHOT_DATE_METADATA_KEY)
+
+
+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 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:
+ return None
+ if value.tzinfo is None:
+ return value.replace(tzinfo=datetime.UTC)
+ return value
diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.py
new file mode 100644
index 000000000000..f12100eb0a2d
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/dataset/dag.py
@@ -0,0 +1,733 @@
+"""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:
+
+ inbox_report_state/v1/dt=D/ Postgres spine + report state + tabular features
+ inbox_report_embeddings/v1/dt=D/ report_id -> small-1536 vector as of snapshot end
+ inbox_report_labels/v1/dt=D/ cumulative label columns from the dogfood project's events
+ inbox_report_model_data/v1/dt=D/ materialized join of the three, plus a rewritten latest/
+
+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,
+so later partitions strictly dominate earlier ones: training reads features from dt=D and labels
+from any later partition, choosing the label-maturity window at read time. Late-arriving labels
+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);
+- report state is current-state-only. A backfilled partition therefore carries *today's* Postgres
+ state, flagged by features_observed_at being far after snapshot_date. Only forward-run daily
+ partitions are true point-in-time snapshots. This reaches row *inclusion*, not just feature
+ values: promoted_at is cleared on suppression and snooze, so a report promoted before the cutoff
+ and suppressed after it drops out of the spine unless a label event referenced it in time. A
+ spine derived from immutable promotion history (the status telemetry carries promoted_at) is the
+ fix, and is a v2 change.
+"""
+
+import json
+import datetime
+from collections.abc import Iterator
+from typing import Any, cast
+
+from django.db.models import Q
+
+import dagster
+import pyarrow as pa
+
+from posthog import settings
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tag_queries
+from posthog.dags.common import dagster_tags
+
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.report_embeddings import EMBEDDING_DOCUMENT_TYPE, EMBEDDING_PRODUCT, EMBEDDING_RENDERING
+from products.signals.dags.inbox_ranking.common import (
+ DATASET_VERSION,
+ S3_BUCKET_ENV,
+ dataset_bucket,
+ dataset_unconfigured,
+ ensure_utc,
+ latest_is_stale,
+ latest_object_key,
+ object_snapshot_date,
+ owner_tags,
+ partition_def,
+ partition_object_key,
+ read_parquet,
+ s3_client,
+ skip_unconfigured,
+ snapshot_bounds,
+ write_parquet,
+)
+from products.signals.dags.inbox_ranking.dataset.queries import (
+ LABEL_DEFAULTS,
+ LABEL_STREAMS,
+ LABELED_REPORT_IDS_SQL,
+ REPORT_EMBEDDINGS_QUERY_SETTINGS,
+ REPORT_EMBEDDINGS_SQL,
+ etl_workload,
+ hogql_rows,
+ labels_team,
+ merge_label_streams,
+ valid_report_uuids,
+)
+
+FEATURE_SCHEMA_VERSION = 1
+
+# Statuses a report can be authored straight into and still be in the inbox (`create_scout_report`
+# and `create_custom_agent_ready_report`), which is how a report reaches the spine without a
+# promotion. Suppressed and deleted are absent on purpose: authored-then-hidden is not inventory.
+BORN_VISIBLE_STATUSES = (
+ SignalReport.Status.READY,
+ SignalReport.Status.PENDING_INPUT,
+ SignalReport.Status.IN_PROGRESS,
+ SignalReport.Status.RESOLVED,
+)
+
+STATE_TABLE = "inbox_report_state"
+EMBEDDINGS_TABLE = "inbox_report_embeddings"
+LABELS_TABLE = "inbox_report_labels"
+MODEL_DATA_TABLE = "inbox_report_model_data"
+
+COMMON_ASSET_KWARGS: dict[str, Any] = {
+ "group_name": "inbox_ranking",
+ "partitions_def": partition_def,
+ "tags": owner_tags,
+ # Transient ClickHouse/S3 blips shouldn't fail the daily partition outright.
+ "retry_policy": dagster.RetryPolicy(max_retries=2, delay=60),
+ # Step-level, so it also bounds the implicit __ASSET_JOB runs a multi-day UI backfill launches:
+ # each partition otherwise starts its own fleet-wide embeddings aggregation with a 20 GiB query
+ # budget. The limit itself is a Dagster deployment setting (charts repo), like the duckling
+ # backfill keys; this only names the pool it targets.
+ "pool": "inbox_ranking_etl",
+}
+
+
+def _tag_dagster_queries(context: dagster.AssetExecutionContext) -> None:
+ """Stamp product + feature + dagster run tags into the thread's query tags so every ClickHouse
+ query this asset issues (sync_execute and HogQL alike) is attributable in system.query_log.
+ Both product and feature are required: sync_execute refuses an untagged query in local dev."""
+ tag_queries(product=Product.SIGNALS, feature=Feature.DATA_MODELING)
+ get_query_tags().with_dagster(dagster_tags(context))
+
+
+_TIMESTAMP = pa.timestamp("us", tz="UTC")
+
+_STATE_FIELDS: list[tuple[str, pa.DataType]] = [
+ ("snapshot_date", pa.date32()),
+ ("report_id", pa.string()),
+ ("report_team_id", pa.int64()),
+ ("region", pa.string()),
+ ("status", pa.string()),
+ ("billing_exempt_reason", pa.string()),
+ ("report_created_at", _TIMESTAMP),
+ ("promoted_at", _TIMESTAMP),
+ ("last_run_at", _TIMESTAMP),
+ ("pg_updated_at", _TIMESTAMP),
+ ("report_age_hours", pa.float32()),
+ ("hours_since_promotion", pa.float32()),
+ ("signal_count", pa.int32()),
+ ("total_weight", pa.float32()),
+ ("run_count", pa.int32()),
+ ("priority", pa.string()),
+ ("actionability", pa.string()),
+ ("title_chars", pa.int32()),
+ ("summary_chars", pa.int32()),
+ ("features_observed_at", _TIMESTAMP),
+]
+STATE_SCHEMA = pa.schema(_STATE_FIELDS)
+
+_EMBEDDING_FIELDS: list[tuple[str, pa.DataType]] = [
+ ("snapshot_date", pa.date32()),
+ ("report_id", pa.string()),
+ ("report_team_id", pa.int64()),
+ ("embedding_small", pa.list_(pa.float32())),
+ ("embedding_inserted_at", _TIMESTAMP),
+ ("embedding_rendering", pa.string()),
+ ("is_tombstone", pa.bool_()),
+]
+EMBEDDINGS_SCHEMA = pa.schema(_EMBEDDING_FIELDS)
+
+LABEL_FIELDS: list[tuple[str, pa.DataType]] = [
+ ("first_impressed_at", _TIMESTAMP),
+ ("impression_unit_count", pa.int32()),
+ ("impressed_user_count", pa.int32()),
+ ("first_impression_rank", pa.int32()),
+ ("best_impression_rank", pa.int32()),
+ ("source_products", pa.list_(pa.string())),
+ ("first_opened_at", _TIMESTAMP),
+ ("open_count", pa.int32()),
+ ("opened_user_count", pa.int32()),
+ ("ui_dismiss_count", pa.int32()),
+ ("first_ui_dismissed_at", _TIMESTAMP),
+ ("create_pr_click_count", pa.int32()),
+ ("first_create_pr_clicked_at", _TIMESTAMP),
+ ("discuss_count", pa.int32()),
+ ("snooze_count", pa.int32()),
+ ("feedback_positive_count", pa.int32()),
+ ("feedback_negative_count", pa.int32()),
+ ("first_feedback_at", _TIMESTAMP),
+ ("latest_feedback_sentiment", pa.string()),
+ ("first_resolved_at", _TIMESTAMP),
+ ("first_dismissed_server_at", _TIMESTAMP),
+ ("first_failed_at", _TIMESTAMP),
+ ("first_snoozed_at", _TIMESTAMP),
+ ("latest_status_event", pa.string()),
+ ("latest_status_event_at", _TIMESTAMP),
+ ("dismissal_reason", pa.string()),
+ ("status_event_priority", pa.string()),
+ ("status_event_actionability", pa.string()),
+ ("status_event_team_id", pa.int64()),
+ ("pr_created_count", pa.int32()),
+ ("first_pr_created_at", _TIMESTAMP),
+ ("pr_merged_count", pa.int32()),
+ ("first_pr_merged_at", _TIMESTAMP),
+ ("pr_closed_count", pa.int32()),
+]
+
+_LABELS_FIELDS: list[tuple[str, pa.DataType]] = [
+ ("snapshot_date", pa.date32()),
+ ("report_id", pa.string()),
+ *LABEL_FIELDS,
+]
+LABELS_SCHEMA = pa.schema(_LABELS_FIELDS)
+
+_MODEL_DATA_FIELDS: list[tuple[str, pa.DataType]] = [
+ ("snapshot_date", pa.date32()),
+ ("report_id", pa.string()),
+ ("report_team_id", pa.int64()),
+ ("region", pa.string()),
+ ("dataset_version", pa.string()),
+ ("feature_schema_version", pa.int32()),
+ ("built_at", _TIMESTAMP),
+ ("run_id", pa.string()),
+ ("features_observed_at", _TIMESTAMP),
+ ("status", pa.string()),
+ ("billing_exempt_reason", pa.string()),
+ ("report_created_at", _TIMESTAMP),
+ ("promoted_at", _TIMESTAMP),
+ ("last_run_at", _TIMESTAMP),
+ ("pg_updated_at", _TIMESTAMP),
+ ("report_age_hours", pa.float32()),
+ ("hours_since_promotion", pa.float32()),
+ ("signal_count", pa.int32()),
+ ("total_weight", pa.float32()),
+ ("run_count", pa.int32()),
+ ("priority", pa.string()),
+ ("actionability", pa.string()),
+ ("title_chars", pa.int32()),
+ ("summary_chars", pa.int32()),
+ ("embedding_small", pa.list_(pa.float32())),
+ ("embedding_inserted_at", _TIMESTAMP),
+ ("embedding_rendering", pa.string()),
+ ("has_embedding", pa.bool_()),
+ *LABEL_FIELDS,
+ ("label_provenance_ok", pa.bool_()),
+ ("impressions_cloud_only", pa.bool_()),
+]
+MODEL_DATA_SCHEMA = pa.schema(_MODEL_DATA_FIELDS)
+
+_STATE_PASSTHROUGH_COLUMNS = (
+ "report_team_id",
+ "region",
+ "features_observed_at",
+ "status",
+ "billing_exempt_reason",
+ "report_created_at",
+ "promoted_at",
+ "last_run_at",
+ "pg_updated_at",
+ "report_age_hours",
+ "hours_since_promotion",
+ "signal_count",
+ "total_weight",
+ "run_count",
+ "priority",
+ "actionability",
+ "title_chars",
+ "summary_chars",
+)
+
+
+# Stay far below Postgres's 65,535 bind-parameter cap when expanding id__in filters.
+_ORM_ID_CHUNK = 10_000
+
+
+def _chunked(ids: list[str]) -> Iterator[list[str]]:
+ for offset in range(0, len(ids), _ORM_ID_CHUNK):
+ yield ids[offset : offset + _ORM_ID_CHUNK]
+
+
+def _judgment_value(parsed: dict[str, Any], key: str) -> str | None:
+ # Legacy artefact content is unconstrained JSON; a non-string value must not reach the
+ # pa.string() column, where it would abort the whole partition build.
+ value = parsed.get(key)
+ return value if isinstance(value, str) else None
+
+
+def _artefact_judgments(report_ids: list[str], snapshot_end: datetime.datetime) -> dict[str, dict[str, str | None]]:
+ """Latest priority/actionability judgment per report as of the snapshot cutoff, parsed from
+ the artefact content JSON.
+
+ Artefacts are appended in normal operation but the API permits editing one in place
+ (`update_content` rewrites content and bumps updated_at, leaving created_at alone), so a row's
+ current content is not necessarily what it held at the cutoff. The latest pre-cutoff row is
+ therefore chosen first and then nulled if it was edited afterwards: skipping edited rows during
+ selection instead would hand back the judgment they superseded, which was already stale at the
+ cutoff — silently wrong where null is merely unknown. The genuinely immutable classification is
+ status_event_priority/actionability, snapshotted onto each transition in the label stream."""
+ judgments: dict[str, dict[str, str | None]] = {}
+ for chunk in _chunked(report_ids):
+ artefacts = (
+ SignalReportArtefact.objects.filter(
+ report_id__in=chunk,
+ type__in=[
+ SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,
+ ],
+ created_at__lt=snapshot_end,
+ )
+ .order_by("report_id", "type", "-created_at")
+ .distinct("report_id", "type")
+ .values_list("report_id", "type", "content", "updated_at")
+ )
+ for report_id, artefact_type, content, updated_at in artefacts.iterator(chunk_size=2000):
+ # A null updated_at is a row predating the field, never an edit.
+ if updated_at is not None and updated_at >= snapshot_end:
+ continue
+ try:
+ parsed = json.loads(content)
+ except ValueError:
+ continue
+ # Legacy artefact rows can hold JSON that is not an object; readers tolerate them.
+ if not isinstance(parsed, dict):
+ continue
+ entry = judgments.setdefault(str(report_id), {"priority": None, "actionability": None})
+ if artefact_type == SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT:
+ entry["priority"] = _judgment_value(parsed, "priority")
+ else:
+ entry["actionability"] = _judgment_value(parsed, "actionability")
+ return judgments
+
+
+def spine_report_filter(snapshot_end: datetime.datetime) -> Q:
+ """Reports that were in the inbox before the cutoff.
+
+ Two ways in, because not every visible report was promoted: the pipeline promotes a `potential`
+ report and stamps promoted_at, but the scout and custom-agent authoring paths create a report
+ already in a visible status and never stamp it. Keying only on promotion dropped every
+ directly-authored report until a user happened to interact with it, biasing the inventory toward
+ reports that already had engagement — the wrong bias for a ranking model. A never-promoted report
+ is only eligible while it is still visible, so a promotion after the cutoff (promoted_at set, not
+ null) still cannot leak in through the second branch."""
+ return Q(promoted_at__isnull=False, promoted_at__lt=snapshot_end) | Q(
+ promoted_at__isnull=True, status__in=BORN_VISIBLE_STATUSES, created_at__lt=snapshot_end
+ )
+
+
[email protected](name=STATE_TABLE, **COMMON_ASSET_KWARGS)
+def inbox_report_state(context: dagster.AssetExecutionContext) -> None:
+ if skip_unconfigured(context):
+ return
+ _tag_dagster_queries(context)
+ partition_key = context.partition_key
+ _, snapshot_end = snapshot_bounds(partition_key)
+ snapshot_date = datetime.date.fromisoformat(partition_key)
+ features_observed_at = datetime.datetime.now(datetime.UTC)
+
+ labeled_rows = hogql_rows(
+ LABELED_REPORT_IDS_SQL,
+ team=labels_team(),
+ query_type="inbox_ranking_labeled_report_ids",
+ snapshot_end=snapshot_end,
+ )
+ labeled_ids = valid_report_uuids({row[0] for row in labeled_rows})
+
+ # Spine: reports in the inbox before the cutoff, plus anything a label stream referenced before
+ # it, so raw `potential` noise and reports that appeared after the cutoff stay out. Labeled ids
+ # missing from Postgres (EU reports, hard-deleted rows) still get a model_data row downstream
+ # via the labels asset.
+ spine_ids: set[str] = {
+ str(report_id)
+ for report_id in SignalReport.objects.filter(spine_report_filter(snapshot_end)).values_list("id", flat=True)
+ }
+ for chunk in _chunked(sorted(labeled_ids)):
+ spine_ids |= {
+ str(report_id)
+ for report_id in SignalReport.objects.filter(id__in=chunk, created_at__lt=snapshot_end).values_list(
+ "id", flat=True
+ )
+ }
+ ordered_spine_ids = sorted(spine_ids)
+ judgments = _artefact_judgments(ordered_spine_ids, snapshot_end)
+
+ rows: list[dict[str, Any]] = []
+ for spine_chunk in _chunked(ordered_spine_ids):
+ for report in (
+ SignalReport.objects.filter(id__in=spine_chunk)
+ .values(
+ "id",
+ "team_id",
+ "status",
+ "billing_exempt_reason",
+ "created_at",
+ "promoted_at",
+ "last_run_at",
+ "updated_at",
+ "signal_count",
+ "total_weight",
+ "run_count",
+ "title",
+ "summary",
+ )
+ .iterator(chunk_size=2000)
+ ):
+ report_id = str(report["id"])
+ created_at = ensure_utc(report["created_at"])
+ promoted_at = ensure_utc(report["promoted_at"])
+ judgment = judgments.get(report_id, {})
+ rows.append(
+ {
+ "snapshot_date": snapshot_date,
+ "report_id": report_id,
+ "report_team_id": report["team_id"],
+ "region": (settings.CLOUD_DEPLOYMENT or "local").lower(),
+ "status": report["status"],
+ "billing_exempt_reason": report["billing_exempt_reason"],
+ "report_created_at": created_at,
+ "promoted_at": promoted_at,
+ "last_run_at": ensure_utc(report["last_run_at"]),
+ "pg_updated_at": ensure_utc(report["updated_at"]),
+ "report_age_hours": (snapshot_end - created_at).total_seconds() / 3600 if created_at else None,
+ "hours_since_promotion": (snapshot_end - promoted_at).total_seconds() / 3600
+ if promoted_at
+ else None,
+ "signal_count": report["signal_count"],
+ "total_weight": report["total_weight"],
+ "run_count": report["run_count"],
+ "priority": judgment.get("priority"),
+ "actionability": judgment.get("actionability"),
+ "title_chars": len(report["title"] or ""),
+ "summary_chars": len(report["summary"] or ""),
+ "features_observed_at": features_observed_at,
+ }
+ )
+
+ bucket = dataset_bucket()
+ key = partition_object_key(settings.INBOX_RANKING_DATASET_S3_PREFIX, STATE_TABLE, partition_key)
+ write_parquet(s3_client(), bucket, key, pa.Table.from_pylist(rows, schema=STATE_SCHEMA))
+ context.add_output_metadata(
+ {
+ "rows": dagster.MetadataValue.int(len(rows)),
+ "labeled_report_ids": dagster.MetadataValue.int(len(labeled_ids)),
+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),
+ }
+ )
+
+
[email protected](name=EMBEDDINGS_TABLE, **COMMON_ASSET_KWARGS)
+def inbox_report_embeddings(context: dagster.AssetExecutionContext) -> None:
+ if skip_unconfigured(context):
+ return
+ _tag_dagster_queries(context)
+ partition_key = context.partition_key
+ _, snapshot_end = snapshot_bounds(partition_key)
+ snapshot_date = datetime.date.fromisoformat(partition_key)
+
+ results = cast(
+ list[tuple[Any, ...]],
+ sync_execute(
+ REPORT_EMBEDDINGS_SQL,
+ {
+ "product": EMBEDDING_PRODUCT,
+ "document_type": EMBEDDING_DOCUMENT_TYPE,
+ "rendering": EMBEDDING_RENDERING,
+ "snapshot_end": snapshot_end.replace(tzinfo=None),
+ },
+ settings=REPORT_EMBEDDINGS_QUERY_SETTINGS,
+ workload=etl_workload(),
+ )
+ or [],
+ )
+
+ # Consumed column-wise straight into Arrow, and each source row is released as it is converted.
+ # This is the widest thing the dag holds — a 1536-float vector per live report, fleet-wide — so
+ # the intermediate list of row dicts that from_pylist would need is a whole extra copy of it.
+ row_count = len(results)
+ tombstones = 0
+ report_ids: list[str] = []
+ team_ids: list[int] = []
+ embeddings: list[list[float] | None] = []
+ inserted_ats: list[datetime.datetime | None] = []
+ tombstone_flags: list[bool] = []
+ for index in range(row_count):
+ team_id, document_id, embedding, is_tombstone, inserted_at = results[index]
+ results[index] = ()
+ if is_tombstone:
+ tombstones += 1
+ report_ids.append(str(document_id))
+ team_ids.append(int(team_id))
+ # Tombstoned vectors embed the fixed retraction text, not report content, so they are
+ # useless as features; keep the row for lineage but null the vector.
+ embeddings.append(None if is_tombstone else list(embedding))
+ inserted_ats.append(ensure_utc(inserted_at))
+ tombstone_flags.append(bool(is_tombstone))
+ del results
+
+ table = pa.Table.from_pydict(
+ {
+ "snapshot_date": [snapshot_date] * row_count,
+ "report_id": report_ids,
+ "report_team_id": team_ids,
+ "embedding_small": embeddings,
+ "embedding_inserted_at": inserted_ats,
+ "embedding_rendering": [EMBEDDING_RENDERING] * row_count,
+ "is_tombstone": tombstone_flags,
+ },
+ schema=EMBEDDINGS_SCHEMA,
+ )
+
+ bucket = dataset_bucket()
+ key = partition_object_key(settings.INBOX_RANKING_DATASET_S3_PREFIX, EMBEDDINGS_TABLE, partition_key)
+ write_parquet(s3_client(), bucket, key, table)
+ context.add_output_metadata(
+ {
+ "rows": dagster.MetadataValue.int(row_count),
+ "tombstones": dagster.MetadataValue.int(tombstones),
+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),
+ }
+ )
+
+
[email protected](name=LABELS_TABLE, **COMMON_ASSET_KWARGS)
+def inbox_report_labels(context: dagster.AssetExecutionContext) -> None:
+ if skip_unconfigured(context):
+ return
+ _tag_dagster_queries(context)
+ partition_key = context.partition_key
+ _, snapshot_end = snapshot_bounds(partition_key)
+ team = labels_team()
+
+ stream_rows: dict[str, list[tuple[Any, ...]]] = {}
+ for stream_name, sql, _columns in LABEL_STREAMS:
+ stream_rows[stream_name] = hogql_rows(
+ sql,
+ team=team,
+ query_type=f"inbox_ranking_labels_{stream_name}",
+ snapshot_end=snapshot_end,
+ )
+ context.log.info(f"{stream_name}: {len(stream_rows[stream_name])} reports")
+
+ rows = merge_label_streams(stream_rows, datetime.date.fromisoformat(partition_key))
+ bucket = dataset_bucket()
+ key = partition_object_key(settings.INBOX_RANKING_DATASET_S3_PREFIX, LABELS_TABLE, partition_key)
+ write_parquet(s3_client(), bucket, key, pa.Table.from_pylist(rows, schema=LABELS_SCHEMA))
+ context.add_output_metadata(
+ {
+ "rows": dagster.MetadataValue.int(len(rows)),
+ **{
+ f"{stream_name}_reports": dagster.MetadataValue.int(len(stream_rows[stream_name]))
+ for stream_name, _, _ in LABEL_STREAMS
+ },
+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),
+ }
+ )
+
+
+def label_provenance_ok(
+ pg_status: str | None,
+ pg_updated_at: datetime.datetime | None,
+ latest_status_event: str | None,
+ *,
+ report_team_id: int | None,
+ status_event_team_id: int | None,
+ snapshot_end: datetime.datetime,
+) -> bool:
+ """Status labels cross-checked against Postgres current state (the label-telemetry PR's
+ security-review requirement): the report must exist in Postgres, its status telemetry must be
+ about that report's tenant, and its latest status event must either match the current status or
+ be explained by the cutoff.
+
+ The only legitimate mismatch is a status that moved after the label window closed — labels are
+ bounded at the cutoff, Postgres is read at run time. Any *earlier* write is no excuse: signal
+ ingestion bumps `updated_at` without touching status, so accepting one would let stale or forged
+ status telemetry pass as soon as the report saw unrelated activity."""
+ if pg_status is None:
+ return False
+ if latest_status_event is None:
+ return True
+ # The transition reported a tenant; a real emit always carries the report's own. Naming a
+ # different team (or no readable team at all) means the event isn't about this report, however
+ # well its status happens to line up.
+ if report_team_id is None or status_event_team_id != report_team_id:
+ return False
+ if latest_status_event == pg_status:
+ return True
+ return pg_updated_at is not None and pg_updated_at >= snapshot_end
+
+
+def assemble_model_rows(
+ state_rows: list[dict[str, Any]],
+ embedding_rows: list[dict[str, Any]],
+ label_rows: list[dict[str, Any]],
+ *,
+ snapshot_date: datetime.date,
+ built_at: datetime.datetime,
+ run_id: str,
+) -> list[dict[str, Any]]:
+ """Join the three sub-tables on report_id into the wide training rows.
+
+ The row set is the union of state and labels: label-only rows (EU reports, hard-deleted
+ reports) survive with null state so their label history stays real, while embedding-only
+ reports (never promoted, never labeled) stay out of the spine.
+
+ A deleted report is indistinguishable from an EU one here — both are label rows with no
+ Postgres row — so re-running a partition cannot scrub one. See the README's retention section:
+ scrubbing means deleting the objects.
+ """
+ _, snapshot_end = snapshot_bounds(snapshot_date.isoformat())
+ state_by_id = {row["report_id"]: row for row in state_rows}
+ embedding_by_id = {row["report_id"]: row for row in embedding_rows}
+ labels_by_id = {row["report_id"]: row for row in label_rows}
+
+ rows: list[dict[str, Any]] = []
+ for report_id in sorted(set(state_by_id) | set(labels_by_id)):
+ state = state_by_id.get(report_id)
+ embedding = embedding_by_id.get(report_id)
+ labels = labels_by_id.get(report_id)
+
+ row: dict[str, Any] = {
+ "snapshot_date": snapshot_date,
+ "report_id": report_id,
+ "dataset_version": DATASET_VERSION,
+ "feature_schema_version": FEATURE_SCHEMA_VERSION,
+ "built_at": built_at,
+ "run_id": run_id,
+ }
+ for column in _STATE_PASSTHROUGH_COLUMNS:
+ row[column] = state.get(column) if state else None
+ if row["report_team_id"] is None and embedding:
+ row["report_team_id"] = embedding["report_team_id"]
+
+ if embedding is not None:
+ # Tombstoned rows already carry a null vector in the sub-table.
+ row["embedding_small"] = embedding["embedding_small"]
+ row["embedding_inserted_at"] = embedding["embedding_inserted_at"]
+ row["embedding_rendering"] = embedding["embedding_rendering"]
+ else:
+ row["embedding_small"] = None
+ row["embedding_inserted_at"] = None
+ row["embedding_rendering"] = None
+ row["has_embedding"] = row["embedding_small"] is not None
+
+ for column in LABEL_DEFAULTS:
+ row[column] = labels.get(column, LABEL_DEFAULTS[column]) if labels else LABEL_DEFAULTS[column]
+
+ row["label_provenance_ok"] = label_provenance_ok(
+ row["status"],
+ row["pg_updated_at"],
+ row["latest_status_event"],
+ report_team_id=row["report_team_id"],
+ status_event_team_id=row["status_event_team_id"],
+ snapshot_end=snapshot_end,
+ )
+ # Desktop Code app does not emit impressions yet, so p(open) negatives are cloud-only;
+ # recorded per row so the caveat travels with the data.
+ row["impressions_cloud_only"] = True
+ rows.append(row)
+ return rows
+
+
+ name=MODEL_DATA_TABLE,
+ deps=[STATE_TABLE, EMBEDDINGS_TABLE, LABELS_TABLE],
+ **COMMON_ASSET_KWARGS,
+)
+def inbox_report_model_data(context: dagster.AssetExecutionContext) -> None:
+ if skip_unconfigured(context):
+ return
+ partition_key = context.partition_key
+ snapshot_date = datetime.date.fromisoformat(partition_key)
+ built_at = datetime.datetime.now(datetime.UTC)
+ bucket = dataset_bucket()
+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX
+ client = s3_client()
+
+ state_rows = read_parquet(client, bucket, partition_object_key(prefix, STATE_TABLE, partition_key)).to_pylist()
+ embedding_rows = read_parquet(
+ client, bucket, partition_object_key(prefix, EMBEDDINGS_TABLE, partition_key)
+ ).to_pylist()
+ label_rows = read_parquet(client, bucket, partition_object_key(prefix, LABELS_TABLE, partition_key)).to_pylist()
+
+ rows = assemble_model_rows(
+ state_rows,
+ embedding_rows,
+ label_rows,
+ snapshot_date=snapshot_date,
+ built_at=built_at,
+ run_id=context.run.run_id,
+ )
+ table = pa.Table.from_pylist(rows, schema=MODEL_DATA_SCHEMA)
+
+ partition_key_path = partition_object_key(prefix, MODEL_DATA_TABLE, partition_key)
+ write_parquet(client, bucket, partition_key_path, table, snapshot_date=partition_key)
+ latest_key = latest_object_key(prefix, MODEL_DATA_TABLE)
+ wrote_latest = latest_is_stale(object_snapshot_date(client, bucket, latest_key), partition_key)
+ if wrote_latest:
+ write_parquet(client, bucket, latest_key, table, snapshot_date=partition_key)
+
+ with_state = sum(1 for row in rows if row["status"] is not None)
+ context.add_output_metadata(
+ {
+ "rows": dagster.MetadataValue.int(len(rows)),
+ "rows_with_state": dagster.MetadataValue.int(with_state),
+ "rows_with_embedding": dagster.MetadataValue.int(sum(1 for row in rows if row["has_embedding"])),
+ "rows_provenance_ok": dagster.MetadataValue.int(sum(1 for row in rows if row["label_provenance_ok"])),
+ "wrote_latest": dagster.MetadataValue.bool(wrote_latest),
+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{partition_key_path}"),
+ }
+ )
+
+
+inbox_ranking_dataset_job = dagster.define_asset_job(
+ name="inbox_ranking_dataset_job",
+ selection=[STATE_TABLE, EMBEDDINGS_TABLE, LABELS_TABLE, MODEL_DATA_TABLE],
+ partitions_def=partition_def,
+ # The six 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 — and
+ # the label windows only grow, since they accumulate from LABELS_EPOCH.
+ tags={**owner_tags, "dagster/max_runtime": str(3 * 60 * 60)},
+)
+
+
+# On Cloud the assets self-disable while the destination bucket is unset, so the schedule can
+# default to RUNNING and the dataset starts flowing the moment infra provisions the bucket.
+# Everywhere else (local dev loads this location via workspace.yaml, self-hosted) it stays
+# stopped: those environments have no dogfood project, so a running schedule would only produce
+# a failed run every day.
+ cron_schedule="30 2 * * *",
+ job=inbox_ranking_dataset_job,
+ execution_timezone="UTC",
+ # Only prod US runs on its own: the dogfood project this dag reads labels from lives there, so
+ # a DEV or E2E deployment (also `is_cloud()`) would fail every daily run on the missing team.
+ # Those deployments still register the location and can trigger a run by hand.
+ default_status=dagster.DefaultScheduleStatus.RUNNING
+ if settings.CLOUD_DEPLOYMENT == "US"
+ else dagster.DefaultScheduleStatus.STOPPED,
+ tags=owner_tags,
+)
+def inbox_ranking_dataset_schedule(
+ context: dagster.ScheduleEvaluationContext,
+) -> dagster.RunRequest | dagster.SkipReason:
+ # Skip rather than launch a run whose assets would all take their early return: a run that
+ # materializes every asset without writing an object reads as a healthy partition, and once the
+ # bucket lands the schedule has already moved past those dates. Skipped ticks leave the
+ # partitions plainly unmaterialized and backfillable.
+ if dataset_unconfigured():
+ return dagster.SkipReason(f"{S3_BUCKET_ENV} is not set; skipping until the dedicated bucket is provisioned")
+ # Derived from the tick rather than wall-clock now() so a delayed or replayed tick still
+ # builds the partition it was scheduled for; run_key dedupes a re-evaluated tick.
+ previous_day = context.scheduled_execution_time.date() - datetime.timedelta(days=1)
+ return dagster.RunRequest(partition_key=previous_day.isoformat(), run_key=previous_day.isoformat())
diff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.py
new file mode 100644
index 000000000000..5a7903caa00a
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/dataset/queries.py
@@ -0,0 +1,456 @@
+"""SQL and row-shaping for the inbox-ranking dataset assets.
+
+The label SQL inlines the canonical `inbox_ranking_*` warehouse-view logic (versioned in the
+inbox-ranking skill's references/views.md) with explicit event-time bounds instead of the views'
+rolling 90-day window, which would silently drop old labels from backfilled partitions. Every
+query is bounded `[{labels_epoch}, {snapshot_end})` so a partition is reproducible for any past
+day.
+"""
+
+import uuid
+import datetime
+from typing import Any
+
+import dagster
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.cloud_utils import is_cloud
+from posthog.models import Team
+
+from products.signals.dags.inbox_ranking.common import LABELS_EPOCH, ensure_utc
+
+# All regions' label telemetry lands in the US dogfood project (PostHog internal, team 2).
+LABELS_TEAM_ID = 2
+
+# Naming scheme from products/error_tracking/backend/indexed_embedding.py (the shared
+# document-embeddings infrastructure): distributed_posthog_document_embeddings_<model_name>.
+EMBEDDINGS_TABLE = "distributed_posthog_document_embeddings_text_embedding_3_small_1536"
+
+
+def labels_team() -> Team:
+ try:
+ return Team.objects.get(id=LABELS_TEAM_ID)
+ except Team.DoesNotExist:
+ raise dagster.Failure(
+ f"Labels team {LABELS_TEAM_ID} does not exist in this environment; the inbox ranking "
+ "dataset can only be built where the dogfood project is present"
+ )
+
+
+def etl_workload() -> Workload:
+ """Route ETL reads to the offline cluster replicas on Cloud so they never compete with
+ customer-facing queries; local and self-hosted deployments have no offline cluster."""
+ return Workload.OFFLINE if is_cloud() else Workload.DEFAULT
+
+
+def utc_bound(value: datetime.datetime) -> str:
+ """Render a UTC instant for a HogQL toDateTime() placeholder. The explicit +00:00 offset is
+ load-bearing: HogQL parses bare datetime strings in the querying team's timezone (US/Pacific
+ for the dogfood project), which would silently shift every bound 7-8 hours."""
+ return value.astimezone(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%S+00:00")
+
+
+def hogql_rows(sql: str, *, team: Team, query_type: str, snapshot_end: datetime.datetime) -> list[tuple[Any, ...]]:
+ response = execute_hogql_query(
+ query=sql,
+ team=team,
+ query_type=query_type,
+ placeholders={
+ "labels_epoch": ast.Constant(value=LABELS_EPOCH),
+ "snapshot_end": ast.Constant(value=utc_bound(snapshot_end)),
+ },
+ limit_context=LimitContext.SAVED_QUERY,
+ workload=etl_workload(),
+ # The label window grows cumulatively from LABELS_EPOCH, so these aggregates need more
+ # than the 60s HogQL default; the sort key (team, date, event) keeps the scan bounded.
+ settings=HogQLGlobalSettings(max_execution_time=600),
+ # The dag runs without a user; the read is a trusted internal ETL over the dogfood project.
+ bypass_warehouse_access_control=True,
+ )
+ return [tuple(row) for row in response.results or []]
+
+
+def canonical_report_uuid(report_id: str) -> str | None:
+ """Canonical lowercase-hyphenated form of a client-supplied report id, or None when it cannot
+ be a report UUID. Canonicalizing (not just validating) matters because a case or hyphenation
+ variant would otherwise survive as a separate label-only row instead of joining its report."""
+ try:
+ return str(uuid.UUID(report_id))
+ except ValueError:
+ return None
+
+
+def valid_report_uuids(report_ids: set[str]) -> set[str]:
+ """Label events are client-supplied; drop ids that cannot be report UUIDs before ORM lookups."""
+ return {canonical for report_id in report_ids if (canonical := canonical_report_uuid(report_id)) is not None}
+
+
+# The `Inbox report feedback` producer contract (frontend/src/scenes/inbox/inboxAnalytics.ts emits
+# exactly these two). Applied to the labeled-id spine and the feedback stream alike, so an event
+# whose sentiment is missing or off-contract carries no label and can neither mint a label-only
+# training row nor stamp a feedback label onto a real report.
+FEEDBACK_SENTIMENTS_SQL = "toString(properties.sentiment) IN ('positive', 'negative')"
+
+# The feedback filter rides as a second predicate rather than its own UNION branch so the whole
+# select keeps one sort-key-aligned `event IN (...)` scan.
+LABELED_REPORT_IDS_SQL = f"""
+SELECT DISTINCT report_id
+FROM (
+ SELECT JSONExtractString(imp, 'report_id') AS report_id
+ FROM events
+ ARRAY JOIN JSONExtractArrayRaw(coalesce(properties.impressions, '[]')) AS imp
+ WHERE event = 'Inbox reports impressed'
+ AND timestamp >= toDateTime({{labels_epoch}}) AND timestamp < toDateTime({{snapshot_end}})
+ UNION ALL
+ SELECT toString(properties.report_id) AS report_id
+ FROM events
+ WHERE event IN (
+ 'Inbox report opened',
+ 'Inbox report action',
+ 'Inbox report feedback',
+ 'signal_report_status_changed'
+ )
+ AND (event != 'Inbox report feedback' OR {FEEDBACK_SENTIMENTS_SQL})
+ AND timestamp >= toDateTime({{labels_epoch}}) AND timestamp < toDateTime({{snapshot_end}})
+ UNION ALL
+ SELECT toString(properties.signal_report_id) AS report_id
+ FROM events
+ WHERE event IN ('pr_created', 'pr_merged', 'pr_closed')
+ AND timestamp >= toDateTime({{labels_epoch}}) AND timestamp < toDateTime({{snapshot_end}})
+)
+WHERE report_id != ''
+"""
+
+# Point-in-time caveat: the source is a ReplacingMergeTree versioned by inserted_at, so merges
+# keep only the newest version of each key. A run that happens after a re-embedding or tombstone
+# superseded the vector that existed on the snapshot day can therefore return no row for that
+# report — mostly a backfill concern, but forward runs are exposed too, for the 2.5 hours between
+# the snapshot cutoff and the 02:30 schedule. Reports are embedded once at promotion, so this only
+# bites the rare re-render; the vector reappears on the next partition, and embedding_inserted_at
+# lineage records which version each row actually carries.
+#
+# Index reality: the sharded table orders by (team_id, toDate(timestamp), product, document_type,
+# rendering, ...) and this cross-team query has no team_id prefix, so it scans the whole table.
+# That is acceptable because the 3-month TTL bounds the table and PREWHERE filters the small
+# string columns before the wide embedding column is read; the settings below cap the blast
+# radius and keep the distributed GROUP BY (1536-float argMax states) memory-efficient.
+REPORT_EMBEDDINGS_QUERY_SETTINGS: dict[str, int] = {
+ "max_execution_time": 600,
+ "max_memory_usage": 20 * 1024**3,
+ "max_bytes_before_external_group_by": 10 * 1024**3,
+ "distributed_aggregation_memory_efficient": 1,
+}
+
+REPORT_EMBEDDINGS_SQL = f"""
+SELECT
+ team_id,
+ document_id,
+ argMax(embedding, inserted_at) AS embedding,
+ argMax(JSONExtractBool(metadata, 'deleted'), inserted_at) AS is_tombstone,
+ max(inserted_at) AS embedding_inserted_at
+FROM {EMBEDDINGS_TABLE}
+WHERE product = %(product)s
+ AND document_type = %(document_type)s
+ AND rendering = %(rendering)s
+ AND inserted_at < %(snapshot_end)s
+GROUP BY team_id, document_id
+"""
+
+IMPRESSIONS_COLUMNS = (
+ "first_impressed_at",
+ "impression_unit_count",
+ "impressed_user_count",
+ "first_impression_rank",
+ "best_impression_rank",
+ "source_products",
+)
+# Ranks come from client-supplied JSON, so they can be any Int64, and JSONExtractInt yields 0 for
+# a missing or non-numeric value. The producer contract (frontend/src/scenes/inbox/inboxAnalytics.ts)
+# is 1-based, so anything below 1 is malformed; anything above int32 would raise on the Parquet
+# conversion and fail the whole fleet-wide labels asset. Both are nulled out, and the impression
+# still counts toward the impression/user counts.
+_IMPRESSION_RANK = (
+ "if(JSONExtractInt(imp, 'rank') >= 1 AND JSONExtractInt(imp, 'rank') <= 2147483647, "
+ "JSONExtractInt(imp, 'rank'), NULL)"
+)
+IMPRESSIONS_SQL = f"""
+SELECT
+ JSONExtractString(imp, 'report_id') AS report_id,
+ min(timestamp) AS first_impressed_at,
+ count() AS impression_unit_count,
+ uniq(distinct_id) AS impressed_user_count,
+ argMinIf({_IMPRESSION_RANK}, timestamp, {_IMPRESSION_RANK} IS NOT NULL) AS first_impression_rank,
+ min({_IMPRESSION_RANK}) AS best_impression_rank,
+ argMax(JSONExtract(imp, 'source_products', 'Array(String)'), timestamp) AS source_products
+FROM events
+ARRAY JOIN JSONExtractArrayRaw(coalesce(properties.impressions, '[]')) AS imp
+WHERE event = 'Inbox reports impressed'
+ AND timestamp >= toDateTime({{labels_epoch}}) AND timestamp < toDateTime({{snapshot_end}})
+GROUP BY report_id
+HAVING report_id != ''
+"""
+
+OPENS_COLUMNS = ("first_opened_at", "open_count", "opened_user_count")
+OPENS_SQL = """
+SELECT
+ toString(properties.report_id) AS report_id,
+ min(timestamp) AS first_opened_at,
+ count() AS open_count,
+ uniq(distinct_id) AS opened_user_count
+FROM events
+WHERE event = 'Inbox report opened'
+ AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})
+ AND toString(properties.report_id) != ''
+GROUP BY report_id
+"""
+
+ACTIONS_COLUMNS = (
+ "ui_dismiss_count",
+ "first_ui_dismissed_at",
+ "create_pr_click_count",
+ "first_create_pr_clicked_at",
+ "discuss_count",
+ "snooze_count",
+)
+# Bulk action rows carry no report_id and are excluded; bulk dismissals are recovered from the
+# server-side status stream instead. minIf misses fill non-nullable datetimes with epoch 0, hence
+# the nullIf(..., fromUnixTimestamp(0)) wraps here and below.
+ACTIONS_SQL = """
+SELECT
+ toString(properties.report_id) AS report_id,
+ countIf(toString(properties.action_type) = 'dismiss') AS ui_dismiss_count,
+ nullIf(minIf(timestamp, toString(properties.action_type) = 'dismiss'), fromUnixTimestamp(0)) AS first_ui_dismissed_at,
+ countIf(toString(properties.action_type) = 'create_pr') AS create_pr_click_count,
+ nullIf(minIf(timestamp, toString(properties.action_type) = 'create_pr'), fromUnixTimestamp(0)) AS first_create_pr_clicked_at,
+ countIf(toString(properties.action_type) = 'discuss') AS discuss_count,
+ countIf(toString(properties.action_type) = 'snooze') AS snooze_count
+FROM events
+WHERE event = 'Inbox report action'
+ AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})
+ AND toString(properties.report_id) != ''
+GROUP BY report_id
+"""
+
+STATUS_COLUMNS = (
+ "first_resolved_at",
+ "first_dismissed_server_at",
+ "first_failed_at",
+ "first_snoozed_at",
+ "latest_status_event",
+ "latest_status_event_at",
+ "dismissal_reason",
+ "status_event_priority",
+ "status_event_actionability",
+ "status_event_team_id",
+)
+# The inner query dedupes at-least-once analytics delivery within 10-minute buckets; events.timestamp
+# is qualified because the min()/max() aliases shadow the raw column in WHERE/GROUP BY.
+#
+# A bucket keeps both its first and last timestamp because the grouping can also collapse genuine
+# repeats — dismiss, restore, dismiss again inside ten minutes is one bucket of two real events.
+# `first_*` reads the bucket's first timestamp and everything latest-wins reads its last, so the
+# intervening restore can no longer out-rank the dismissal that actually came after it.
+#
+# status_event_priority/actionability are the classification the *event* carried, which is why
+# capture_status_change_analytics snapshots them onto every transition: artefacts can be re-judged
+# or edited, so the state asset's cutoff-observed judgment is not necessarily what was true when
+# the outcome happened. Both are kept — state for features, these for label-time provenance.
+STATUS_SQL = """
+SELECT
+ report_id,
+ nullIf(minIf(first_timestamp, outcome = 'resolved'), fromUnixTimestamp(0)) AS first_resolved_at,
+ nullIf(minIf(first_timestamp, outcome = 'dismissed'), fromUnixTimestamp(0)) AS first_dismissed_server_at,
+ nullIf(minIf(first_timestamp, outcome = 'failed'), fromUnixTimestamp(0)) AS first_failed_at,
+ nullIf(minIf(first_timestamp, outcome = 'snoozed'), fromUnixTimestamp(0)) AS first_snoozed_at,
+ argMax(status, last_timestamp) AS latest_status_event,
+ max(last_timestamp) AS latest_status_event_at,
+ -- argMax skips NULL values, so this is the reason from the latest *reasoned* transition (the
+ -- intended semantic: reasons only accompany dismissals/snoozes), not necessarily paired with
+ -- latest_status_event above.
+ argMax(dismissal_reason, last_timestamp) AS dismissal_reason,
+ -- These two must stay paired with latest_status_event, so coalesce/nullIf keeps argMax from
+ -- skipping a null: a judgment artefact can be deleted, and then the latest transition
+ -- genuinely carries none. Plain argMax would reach back to an older transition and present
+ -- its classification as the one this outcome was judged at.
+ nullIf(argMax(coalesce(event_priority, ''), last_timestamp), '') AS status_event_priority,
+ nullIf(argMax(coalesce(event_actionability, ''), last_timestamp), '') AS status_event_actionability,
+ -- The owning team as the transition itself reported it. This is the only tenant attribution a
+ -- label-only row can have: reports outside this dag's region have no Postgres state and no
+ -- embedding here. Deliberately *not* merged into report_team_id, which is a US team id by
+ -- construction — team ids are per-region, so an EU 42 and a US 42 are different teams and
+ -- nothing on the event says which region emitted it.
+ toInt(argMax(coalesce(event_team_id, ''), last_timestamp)) AS status_event_team_id
+FROM (
+ SELECT
+ min(events.timestamp) AS first_timestamp,
+ max(events.timestamp) AS last_timestamp,
+ toString(properties.report_id) AS report_id,
+ toString(properties.previous_status) AS previous_status,
+ toString(properties.status) AS status,
+ multiIf(
+ toString(properties.status) = 'suppressed', 'dismissed',
+ toString(properties.status) = 'resolved', 'resolved',
+ toString(properties.status) = 'failed', 'failed',
+ toString(properties.previous_status) IN ('ready', 'resolved') AND toString(properties.status) = 'potential', 'snoozed',
+ 'other'
+ ) AS outcome,
+ -- Latest event in the bucket rather than any(): identical for the duplicate deliveries this
+ -- grouping targets, and the one that matches last_timestamp when it collapsed real repeats.
+ nullIf(argMax(toString(properties.dismissal_reason), events.timestamp), '') AS dismissal_reason,
+ nullIf(argMax(toString(properties.priority), events.timestamp), '') AS event_priority,
+ nullIf(argMax(toString(properties.actionability), events.timestamp), '') AS event_actionability,
+ nullIf(argMax(toString(properties.team_id), events.timestamp), '') AS event_team_id
+ FROM events
+ WHERE event = 'signal_report_status_changed'
+ AND events.timestamp >= toDateTime({labels_epoch}) AND events.timestamp < toDateTime({snapshot_end})
+ AND toString(properties.report_id) != ''
+ GROUP BY
+ report_id,
+ previous_status,
+ status,
+ toStartOfInterval(events.timestamp, INTERVAL 10 MINUTE)
+)
+GROUP BY report_id
+"""
+
+PR_COLUMNS = (
+ "pr_created_count",
+ "first_pr_created_at",
+ "pr_merged_count",
+ "first_pr_merged_at",
+ "pr_closed_count",
+)
+PR_EVENTS_SQL = """
+SELECT
+ toString(properties.signal_report_id) AS report_id,
+ countIf(event = 'pr_created') AS pr_created_count,
+ nullIf(minIf(timestamp, event = 'pr_created'), fromUnixTimestamp(0)) AS first_pr_created_at,
+ countIf(event = 'pr_merged') AS pr_merged_count,
+ nullIf(minIf(timestamp, event = 'pr_merged'), fromUnixTimestamp(0)) AS first_pr_merged_at,
+ countIf(event = 'pr_closed') AS pr_closed_count
+FROM events
+WHERE event IN ('pr_created', 'pr_merged', 'pr_closed')
+ AND timestamp >= toDateTime({labels_epoch}) AND timestamp < toDateTime({snapshot_end})
+ AND properties.signal_report_id IS NOT NULL
+ AND toString(properties.signal_report_id) != ''
+GROUP BY report_id
+"""
+
+FEEDBACK_COLUMNS = (
+ "feedback_positive_count",
+ "feedback_negative_count",
+ "first_feedback_at",
+ "latest_feedback_sentiment",
+)
+# The thumbs at the end of a report body. Feedback-only (the report stays in the inbox), so it is
+# not recoverable from the action or status streams. Only the rating event is aggregated; the
+# optional `Inbox report feedback note` rides separately and carries no additional label.
+FEEDBACK_SQL = f"""
+SELECT
+ toString(properties.report_id) AS report_id,
+ countIf(toString(properties.sentiment) = 'positive') AS feedback_positive_count,
+ countIf(toString(properties.sentiment) = 'negative') AS feedback_negative_count,
+ min(timestamp) AS first_feedback_at,
+ argMax(toString(properties.sentiment), timestamp) AS latest_feedback_sentiment
+FROM events
+WHERE event = 'Inbox report feedback'
+ AND {FEEDBACK_SENTIMENTS_SQL}
+ AND timestamp >= toDateTime({{labels_epoch}}) AND timestamp < toDateTime({{snapshot_end}})
+ AND toString(properties.report_id) != ''
+GROUP BY report_id
+"""
+
+LABEL_STREAMS: tuple[tuple[str, str, tuple[str, ...]], ...] = (
+ ("impressions", IMPRESSIONS_SQL, IMPRESSIONS_COLUMNS),
+ ("opens", OPENS_SQL, OPENS_COLUMNS),
+ ("actions", ACTIONS_SQL, ACTIONS_COLUMNS),
+ ("feedback", FEEDBACK_SQL, FEEDBACK_COLUMNS),
+ ("status_changes", STATUS_SQL, STATUS_COLUMNS),
+ ("pr_events", PR_EVENTS_SQL, PR_COLUMNS),
+)
+
+# Every label column a report can have, with its no-events default. Streams overwrite their own
+# columns; the merge keeps counts at 0 (not null) so head derivations need no null handling.
+LABEL_DEFAULTS: dict[str, Any] = {
+ "first_impressed_at": None,
+ "impression_unit_count": 0,
+ "impressed_user_count": 0,
+ "first_impression_rank": None,
+ "best_impression_rank": None,
+ "source_products": None,
+ "first_opened_at": None,
+ "open_count": 0,
+ "opened_user_count": 0,
+ "ui_dismiss_count": 0,
+ "first_ui_dismissed_at": None,
+ "create_pr_click_count": 0,
+ "first_create_pr_clicked_at": None,
+ "discuss_count": 0,
+ "snooze_count": 0,
+ "feedback_positive_count": 0,
+ "feedback_negative_count": 0,
+ "first_feedback_at": None,
+ "latest_feedback_sentiment": None,
+ "first_resolved_at": None,
+ "first_dismissed_server_at": None,
+ "first_failed_at": None,
+ "first_snoozed_at": None,
+ "latest_status_event": None,
+ "latest_status_event_at": None,
+ "dismissal_reason": None,
+ "status_event_priority": None,
+ "status_event_actionability": None,
+ "status_event_team_id": None,
+ "pr_created_count": 0,
+ "first_pr_created_at": None,
+ "pr_merged_count": 0,
+ "first_pr_merged_at": None,
+ "pr_closed_count": 0,
+}
+
+_TIMESTAMP_LABEL_COLUMNS = frozenset(name for name in LABEL_DEFAULTS if name.endswith("_at"))
+
+
+def canonical_stream_rows(rows: list[tuple[Any, ...]]) -> dict[str, tuple[Any, ...]]:
+ """One row per canonical report id, dropping ids that cannot be report UUIDs.
+
+ ClickHouse groups on the raw client-supplied id, so spelling variants of one UUID arrive as
+ separate rows that canonicalize onto the same report. The canonically spelled row wins, so a
+ forged alias can never overwrite a real report's aggregates; between aliases the smallest raw
+ id wins, so the choice does not depend on ClickHouse's row order."""
+ best: dict[str, tuple[tuple[bool, str], tuple[Any, ...]]] = {}
+ for row in rows:
+ raw_id = str(row[0])
+ report_id = canonical_report_uuid(raw_id)
+ if report_id is None:
+ continue
+ rank = (raw_id != report_id, raw_id)
+ current = best.get(report_id)
+ if current is None or rank < current[0]:
+ best[report_id] = (rank, row)
+ return {report_id: row for report_id, (_rank, row) in best.items()}
+
+
+def merge_label_streams(
+ stream_rows: dict[str, list[tuple[Any, ...]]], snapshot_date: datetime.date
+) -> list[dict[str, Any]]:
+ """Merge the per-stream aggregates (each row `(report_id, *stream_columns)`) into one labels
+ row per report, filling unseen streams with LABEL_DEFAULTS. Report ids are canonicalized and
+ rows with impossible ids dropped, so forged or malformed client events cannot mint label-only
+ training rows."""
+ merged: dict[str, dict[str, Any]] = {}
+ columns_by_stream = {name: columns for name, _, columns in LABEL_STREAMS}
+ for stream_name, rows in stream_rows.items():
+ columns = columns_by_stream[stream_name]
+ for report_id, row in canonical_stream_rows(rows).items():
+ entry = merged.setdefault(
+ report_id,
+ {"snapshot_date": snapshot_date, "report_id": report_id, **LABEL_DEFAULTS},
+ )
+ for column, value in zip(columns, row[1:], strict=True):
+ entry[column] = ensure_utc(value) if column in _TIMESTAMP_LABEL_COLUMNS else value
+ return list(merged.values())
diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.py
new file mode 100644
index 000000000000..3baff19cf6f2
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py
@@ -0,0 +1,277 @@
+import datetime
+from typing import Any
+
+import pytest
+from posthog.test.base import BaseTest
+
+from products.signals.backend.models import SignalReport
+from products.signals.dags.inbox_ranking import common
+from products.signals.dags.inbox_ranking.dataset.dag import (
+ MODEL_DATA_SCHEMA,
+ assemble_model_rows,
+ label_provenance_ok,
+ spine_report_filter,
+)
+from products.signals.dags.inbox_ranking.dataset.queries import (
+ LABEL_DEFAULTS,
+ LABEL_STREAMS,
+ merge_label_streams,
+ utc_bound,
+ valid_report_uuids,
+)
+
+SNAPSHOT_DATE = datetime.date(2026, 7, 29)
+BUILT_AT = datetime.datetime(2026, 7, 30, 2, 30, tzinfo=datetime.UTC)
+T1 = datetime.datetime(2026, 7, 20, 10, 0, tzinfo=datetime.UTC)
+T2 = datetime.datetime(2026, 7, 21, 10, 0, tzinfo=datetime.UTC)
+SNAPSHOT_END = datetime.datetime(2026, 7, 30, tzinfo=datetime.UTC)
+AFTER_SNAPSHOT_END = datetime.datetime(2026, 7, 30, 1, 0, tzinfo=datetime.UTC)
+BEFORE_CUTOFF = datetime.datetime(2026, 7, 28, 9, 0, tzinfo=datetime.UTC)
+UUID_A = "0198c0e8-93c8-0000-38f5-a934eeb1b93e"
+UUID_B = "0198c0e8-93c8-0000-38f5-a934eeb1b93f"
+
+
+def test_s3_key_layout_is_stable():
+ # The layout is an external contract: the project-2 warehouse table url_pattern and mlhog
+ # training both point at these paths, so a change here silently breaks them.
+ assert (
+ common.partition_object_key("inbox_ranking", "inbox_report_model_data", "2026-07-29")
+ == "inbox_ranking/inbox_report_model_data/v1/dt=2026-07-29/part-00000.parquet"
+ )
+ assert (
+ common.latest_object_key("inbox_ranking", "inbox_report_model_data")
+ == "inbox_ranking/inbox_report_model_data/v1/latest/part-00000.parquet"
+ )
+
+
+ "cloud_deployment,bucket,expected_unconfigured",
+ [
+ ("US", "", True),
+ ("US", "posthog-inbox-ranking", False),
+ (None, "", False),
+ ],
+)
+def test_cloud_requires_dedicated_bucket(monkeypatch, cloud_deployment, bucket, expected_unconfigured):
+ monkeypatch.setattr(common.settings, "CLOUD_DEPLOYMENT", cloud_deployment)
+ monkeypatch.setattr(common.settings, "INBOX_RANKING_DATASET_S3_BUCKET", bucket)
+ assert common.dataset_unconfigured() is expected_unconfigured
+
+
+ "existing,partition_key,expected",
+ [
+ (None, "2026-07-29", True),
+ ("2026-07-28", "2026-07-29", True),
+ ("2026-07-29", "2026-07-29", True),
+ ("2026-07-29", "2026-07-20", False),
+ ],
+)
+def test_latest_advances_monotonically_and_backfills_never_clobber_it(existing, partition_key, expected):
+ assert common.latest_is_stale(existing, partition_key) is expected
+
+
+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)
+ assert end == datetime.datetime(2026, 7, 30, tzinfo=datetime.UTC)
+
+
+def test_valid_report_uuids_canonicalizes_and_drops_junk():
+ # Case/hyphenation variants must collapse onto the canonical id, or a forged variant would
+ # survive as a separate label-only training row instead of joining its report.
+ assert valid_report_uuids({UUID_A, UUID_A.upper(), "not-a-uuid", ""}) == {UUID_A}
+
+
+def test_utc_bound_carries_an_explicit_offset():
+ # HogQL parses bare datetime strings in the querying team's timezone (US/Pacific for the
+ # dogfood project); dropping the offset silently shifts every label bound by 7-8 hours.
+ assert utc_bound(datetime.datetime(2026, 7, 30, tzinfo=datetime.UTC)) == "2026-07-30T00:00:00+00:00"
+ pacific_instant = datetime.datetime(2026, 7, 29, 17, 0, tzinfo=datetime.timezone(datetime.timedelta(hours=-7)))
+ assert utc_bound(pacific_instant) == "2026-07-30T00:00:00+00:00"
+
+
+def test_merge_label_streams_fills_defaults_and_maps_columns():
+ stream_rows: dict[str, list[tuple[Any, ...]]] = {
+ "impressions": [(UUID_A, T1.replace(tzinfo=None), 5, 2, 3, 1, ["error_tracking"])],
+ "opens": [(UUID_A.upper(), T2, 4, 2), (UUID_B, T2, 1, 1)],
+ "actions": [("bogus-id", 1, T1, 1, T1, 1, 1)],
+ "status_changes": [],
+ "pr_events": [],
+ }
+ rows = {row["report_id"]: row for row in merge_label_streams(stream_rows, SNAPSHOT_DATE)}
+
+ # The uppercase open joins UUID_A's row, and the bogus action id mints no row.
+ assert set(rows) == {UUID_A, UUID_B}
+ r1 = rows[UUID_A]
+ assert r1["impression_unit_count"] == 5
+ assert r1["impressed_user_count"] == 2
+ assert r1["first_impression_rank"] == 3
+ assert r1["best_impression_rank"] == 1
+ assert r1["source_products"] == ["error_tracking"]
+ assert r1["first_impressed_at"] == T1
+ assert r1["open_count"] == 4
+ r2 = rows[UUID_B]
+ assert r2["impression_unit_count"] == 0
+ assert r2["first_impressed_at"] is None
+ assert r2["pr_created_count"] == 0
+
+
[email protected]("alias_first", [True, False])
+def test_alias_spellings_never_overwrite_the_canonical_rows_aggregates(alias_first):
+ # ClickHouse groups on the raw client-supplied id, so a forged uppercase or unhyphenated
+ # spelling arrives as its own row and would otherwise overwrite the real report's counts with
+ # whatever order the rows came back in.
+ alias = (UUID_A.upper(), T1, 999, 999)
+ canonical = (UUID_A, T2, 4, 2)
+ rows = [alias, canonical] if alias_first else [canonical, alias]
+
+ merged = merge_label_streams({"opens": rows}, SNAPSHOT_DATE)
+
+ assert [row["report_id"] for row in merged] == [UUID_A]
+ assert merged[0]["open_count"] == 4
+ assert merged[0]["first_opened_at"] == T2
+
+
+def test_stream_row_width_mismatch_fails_loudly():
+ with pytest.raises(ValueError):
+ merge_label_streams({"opens": [(UUID_A, T1, 4)]}, SNAPSHOT_DATE)
+
+
+def test_label_stream_columns_all_exist_in_defaults():
+ for _name, _sql, columns in LABEL_STREAMS:
+ assert set(columns) <= set(LABEL_DEFAULTS)
+
+
+ "pg_status,pg_updated_at,latest_event,event_team_id,expected",
+ [
+ (None, None, "resolved", 2, False),
+ ("resolved", T1, None, None, True),
+ ("resolved", T1, "resolved", 2, True),
+ # A mismatch is only excused by a Postgres write after the cutoff — the transition the label
+ # window couldn't see. An earlier one is unrelated activity (ingestion bumps updated_at).
+ ("potential", AFTER_SNAPSHOT_END, "resolved", 2, True),
+ ("potential", T2, "resolved", 2, False),
+ # Telemetry naming another tenant isn't about this report, however well the status lines up.
+ ("resolved", T1, "resolved", 99, False),
+ ("resolved", T1, "resolved", None, False),
+ ],
+)
+def test_label_provenance_cross_check(pg_status, pg_updated_at, latest_event, event_team_id, expected):
+ assert (
+ label_provenance_ok(
+ pg_status,
+ pg_updated_at,
+ latest_event,
+ report_team_id=2,
+ status_event_team_id=event_team_id,
+ snapshot_end=SNAPSHOT_END,
+ )
+ is expected
+ )
+
+
+def _state_row(report_id: str, **overrides):
+ return {
+ "report_id": report_id,
+ "report_team_id": 2,
+ "region": "us",
+ "status": "ready",
+ "pg_updated_at": T2,
+ "features_observed_at": BUILT_AT,
+ **overrides,
+ }
+
+
+def _embedding_row(report_id: str, **overrides):
+ return {
+ "report_id": report_id,
+ "report_team_id": 2,
+ "embedding_small": [0.1, 0.2],
+ "embedding_inserted_at": T1,
+ "embedding_rendering": "title_summary_v1",
+ "is_tombstone": False,
+ **overrides,
+ }
+
+
+def test_assemble_model_rows_spine_and_join():
+ state = [_state_row("r1"), _state_row("r2")]
+ embeddings = [
+ _embedding_row("r1"),
+ _embedding_row("r2", embedding_small=None, is_tombstone=True),
+ _embedding_row("r4"),
+ ]
+ labels = [
+ {
+ "report_id": "r1",
+ "open_count": 4,
+ "latest_status_event": "ready",
+ "latest_status_event_at": T1,
+ "status_event_team_id": 2,
+ }
+ ]
+
+ rows = {
+ row["report_id"]: row
+ for row in assemble_model_rows(
+ state, embeddings, labels, snapshot_date=SNAPSHOT_DATE, built_at=BUILT_AT, run_id="run-1"
+ )
+ }
+
+ # Spine is state union labels: the embedding-only report never promoted or labeled stays out.
+ assert set(rows) == {"r1", "r2"}
+ assert rows["r1"]["has_embedding"] is True
+ assert rows["r1"]["open_count"] == 4
+ assert rows["r1"]["label_provenance_ok"] is True
+ assert rows["r2"]["has_embedding"] is False
+ assert rows["r2"]["embedding_small"] is None
+ assert rows["r2"]["open_count"] == 0
+
+
+def test_assemble_model_rows_keeps_label_only_reports_with_null_state():
+ labels = [{"report_id": "r9", "pr_created_count": 2}]
+ rows = assemble_model_rows([], [], labels, snapshot_date=SNAPSHOT_DATE, built_at=BUILT_AT, run_id="run-1")
+ assert len(rows) == 1
+ assert rows[0]["status"] is None
+ assert rows[0]["pr_created_count"] == 2
+ assert rows[0]["label_provenance_ok"] is False
+
+
+def test_assembled_rows_match_the_parquet_schema_exactly():
+ # pa.Table.from_pylist silently drops dict keys missing from the schema, so a column added to
+ # the assembler but not the schema (or vice versa) would vanish without this check.
+ rows = assemble_model_rows(
+ [_state_row("r1")],
+ [_embedding_row("r1")],
+ [{"report_id": "r1"}],
+ snapshot_date=SNAPSHOT_DATE,
+ built_at=BUILT_AT,
+ run_id="run-1",
+ )
+ assert set(rows[0]) == set(MODEL_DATA_SCHEMA.names)
+
+
+class TestSpineInclusion(BaseTest):
+ def _report(self, status, *, promoted_at=None, created_at=BEFORE_CUTOFF):
+ report = SignalReport.objects.create(team=self.team, status=status, title="t", summary="s")
+ SignalReport.objects.filter(id=report.id).update(created_at=created_at, promoted_at=promoted_at)
+ return str(report.id)
+
+ def test_spine_covers_authored_and_promoted_reports_as_of_the_cutoff(self):
+ promoted = self._report(SignalReport.Status.POTENTIAL, promoted_at=BEFORE_CUTOFF)
+ born_visible = self._report(SignalReport.Status.READY)
+ promoted_after_cutoff = self._report(SignalReport.Status.READY, promoted_at=AFTER_SNAPSHOT_END)
+ self._report(SignalReport.Status.POTENTIAL)
+ self._report(SignalReport.Status.SUPPRESSED)
+ created_after_cutoff = self._report(SignalReport.Status.READY, created_at=AFTER_SNAPSHOT_END)
+
+ in_spine = {
+ str(report_id)
+ for report_id in SignalReport.objects.filter(spine_report_filter(SNAPSHOT_END)).values_list("id", flat=True)
+ }
+
+ assert in_spine == {promoted, born_visible}
+ assert promoted_after_cutoff not in in_spine
+ assert created_after_cutoff not in in_spine