Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(signals): train inbox ranking only on ai-training-opted-in orgs (#109366)

posthog[bot]1501ca27d77d
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index d89d6bd1de89..8593d1683e43 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -249,7 +249,7 @@ Writes use boto3: ambient AWS config (the node role) when the dedicated bucket i
## 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).
+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 still reads nearly the whole table, even with the training consent `team_id` list, and why that is acceptable).
## Operating it
@@ -257,6 +257,21 @@ All reads route to the offline cluster replicas on Cloud (`etl_workload()`), car
- 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_`, `inbox_signal_`, and `inbox_ranking_` asset-name prefixes.
- Runtime budgets are per job (`dagster/max_runtime`): 3h for the dataset and training jobs, 1h for the shadow job. The 3h figure is what the dataset needs — its seven label streams run sequentially, each allowed up to 600s, and the join and S3 writes come after them. The shadow read is one day of two event families plus the scores objects in its lookback, so it gets an hour.
+## Training consent
+
+The dags train only on reports from organizations whose `Organization.is_ai_training_opted_in` is `True`.
+`False` and `None` both mean no consent.
+`consent.training_consent_team_ids()` returns the consenting teams that hold an inbox report, and every asset reads it once per run.
+
+- `inbox_report_state` keeps only the spine reports of those teams. A label event that names another team's report does not pull it back in. That report's labels still land in `inbox_report_model_data` as a label-only row, which training skips.
+- `inbox_report_embeddings`, `inbox_report_title_embeddings` and `inbox_signal_embeddings` read only those teams, through `team_id IN (...)` in the ClickHouse query.
+- The examples asset drops every state row whose `report_team_id` is not in the current set, before it builds examples. The lookback window reaches partitions written before an organization opted out, so this filter is what makes an opt-out take effect on the next training run.
+
+The filter follows the current setting, so an organization that opts back in is trained on again.
+The state asset and the examples asset record `excluded_no_training_consent_reports` and `excluded_no_training_consent_teams` as metadata, and `inbox_ranking_examples_built` carries the examples counts. They are counts, never ids.
+The unseen scores read the dt=D state snapshot, so the newborn pool shrinks to consenting teams too. Scoring in the sweep and the shadow read do not change.
+The filter does not delete existing partitions or models. A re-run of `inbox_signal_embeddings` stays additive, so rows that an older run wrote remain in that partition. Nothing trains on signal embeddings today, and a future reader must apply the same filter.
+
## Deletion and retention
Partitions are immutable history, so a report deleted later keeps its rows (and vector) in partitions written before the deletion.
diff --git a/products/signals/dags/inbox_ranking/consent.py b/products/signals/dags/inbox_ranking/consent.py
new file mode 100644
index 000000000000..f9710f90357b
--- /dev/null
+++ b/products/signals/dags/inbox_ranking/consent.py
@@ -0,0 +1,25 @@
+"""Which teams' data the inbox-ranking dags may train on.
+
+`Organization.is_ai_training_opted_in` is the organization's consent to train PostHog AI models on
+its data. Only `True` is consent: the column is nullable, and every other surface reads null as
+opted out, so `False` and `None` both keep a team out.
+"""
+
+from posthog.models import Team
+
+from products.signals.backend.models import SignalReport
+
+
+def training_consent_team_ids() -> frozenset[int]:
+ """The teams that hold an inbox report and whose organization allows AI training, as of now.
+
+ Narrowed to teams with a report so the set stays the size of the inbox rather than of the
+ region: the embedding assets send it to ClickHouse as an `IN` list. A team with signals and no
+ report yet is left out, which fails closed.
+ """
+ return frozenset(
+ Team.objects.filter(
+ organization__is_ai_training_opted_in=True,
+ id__in=SignalReport.objects.values("team_id"),
+ ).values_list("id", flat=True)
+ )
diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.py
index 9ee4d1081638..75e88cab7055 100644
--- a/products/signals/dags/inbox_ranking/dataset/dag.py
+++ b/products/signals/dags/inbox_ranking/dataset/dag.py
@@ -90,6 +90,7 @@ from products.signals.dags.inbox_ranking.common import (
snapshot_bounds,
write_parquet,
)
+from products.signals.dags.inbox_ranking.consent import training_consent_team_ids
from products.signals.dags.inbox_ranking.dataset.queries import (
LABEL_DEFAULTS,
LABEL_STREAMS,
@@ -405,18 +406,24 @@ def inbox_report_state(context: dagster.AssetExecutionContext) -> None:
# 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)
+ spine_teams: dict[str, int] = {
+ str(report_id): team_id
+ for report_id, team_id in SignalReport.objects.filter(spine_report_filter(snapshot_end)).values_list(
+ "id", "team_id"
+ )
}
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
- )
+ spine_teams |= {
+ str(report_id): team_id
+ for report_id, team_id in SignalReport.objects.filter(
+ id__in=chunk, created_at__lt=snapshot_end
+ ).values_list("id", "team_id")
}
- ordered_spine_ids = sorted(spine_ids)
+ # A report whose organization has not opted in to AI training never reaches the snapshot. Its
+ # label row still lands in model_data, with no state, and training skips such rows.
+ consent_team_ids = training_consent_team_ids()
+ excluded_teams = {team_id for team_id in spine_teams.values() if team_id not in consent_team_ids}
+ ordered_spine_ids = sorted(report_id for report_id, team_id in spine_teams.items() if team_id in consent_team_ids)
judgments = _artefact_judgments(ordered_spine_ids, snapshot_end)
rows: list[dict[str, Any]] = []
@@ -478,6 +485,10 @@ def inbox_report_state(context: dagster.AssetExecutionContext) -> None:
{
"rows": dagster.MetadataValue.int(len(rows)),
"labeled_report_ids": dagster.MetadataValue.int(len(labeled_ids)),
+ "excluded_no_training_consent_reports": dagster.MetadataValue.int(
+ len(spine_teams) - len(ordered_spine_ids)
+ ),
+ "excluded_no_training_consent_teams": dagster.MetadataValue.int(len(excluded_teams)),
"s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),
}
)
@@ -493,21 +504,28 @@ def _snapshot_report_embeddings(
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": rendering,
- "snapshot_end": snapshot_end.replace(tzinfo=None),
- },
- settings=REPORT_EMBEDDINGS_QUERY_SETTINGS,
- workload=etl_workload(),
+ consent_team_ids = training_consent_team_ids()
+
+ # With no consenting team there is no row to read, so the query is not sent.
+ results = (
+ cast(
+ list[tuple[Any, ...]],
+ sync_execute(
+ REPORT_EMBEDDINGS_SQL,
+ {
+ "product": EMBEDDING_PRODUCT,
+ "document_type": EMBEDDING_DOCUMENT_TYPE,
+ "rendering": rendering,
+ "snapshot_end": snapshot_end.replace(tzinfo=None),
+ "team_ids": sorted(consent_team_ids),
+ },
+ settings=REPORT_EMBEDDINGS_QUERY_SETTINGS,
+ workload=etl_workload(),
+ )
+ or [],
)
- or [],
+ if consent_team_ids
+ else []
)
# Consumed column-wise straight into Arrow, and each source row is released as it is converted.
@@ -556,6 +574,7 @@ def _snapshot_report_embeddings(
{
"rows": dagster.MetadataValue.int(row_count),
"tombstones": dagster.MetadataValue.int(tombstones),
+ "training_consent_teams": dagster.MetadataValue.int(len(consent_team_ids)),
"s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),
}
)
@@ -628,22 +647,28 @@ def inbox_signal_embeddings(context: dagster.AssetExecutionContext) -> None:
partition_key = context.partition_key
window_start, window_end = snapshot_bounds(partition_key)
snapshot_date = datetime.date.fromisoformat(partition_key)
+ consent_team_ids = training_consent_team_ids()
- 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(),
+ 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),
+ "team_ids": sorted(consent_team_ids),
+ },
+ settings=SIGNAL_EMBEDDINGS_QUERY_SETTINGS,
+ workload=etl_workload(),
+ )
+ or [],
)
- or [],
+ if consent_team_ids
+ else []
)
# Column-wise into Arrow, releasing each source row as it is converted, for the same reason the
@@ -719,6 +744,7 @@ def inbox_signal_embeddings(context: dagster.AssetExecutionContext) -> None:
"scanned": dagster.MetadataValue.int(row_count),
"carried_over": dagster.MetadataValue.int(table.num_rows - row_count),
"retracted": dagster.MetadataValue.int(deleted_count),
+ "training_consent_teams": dagster.MetadataValue.int(len(consent_team_ids)),
"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}"),
}
diff --git a/products/signals/dags/inbox_ranking/dataset/queries.py b/products/signals/dags/inbox_ranking/dataset/queries.py
index 5763c3671db7..2dec3276fb8b 100644
--- a/products/signals/dags/inbox_ranking/dataset/queries.py
+++ b/products/signals/dags/inbox_ranking/dataset/queries.py
@@ -177,8 +177,8 @@ WHERE report_id IS NOT NULL AND report_id != ''
# 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
+# rendering, ...) and this cross-team query has only the consenting teams' IN list on that prefix,
+# which covers most inbox teams, so it still scans nearly 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] = {
@@ -199,6 +199,7 @@ FROM {EMBEDDINGS_TABLE}
WHERE product = %(product)s
AND document_type = %(document_type)s
AND rendering = %(rendering)s
+ AND team_id IN %(team_ids)s
AND inserted_at < %(snapshot_end)s
GROUP BY team_id, document_id
"""
@@ -259,6 +260,7 @@ FROM {EMBEDDINGS_TABLE}
WHERE product = %(product)s
AND document_type = %(document_type)s
AND rendering = %(rendering)s
+ AND team_id IN %(team_ids)s
AND inserted_at >= %(window_start)s
AND inserted_at < %(window_end)s
"""
diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.py
index ac2e53d49c47..cc432fcbc748 100644
--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py
+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py
@@ -3,11 +3,14 @@ from typing import Any
import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event
+from unittest.mock import patch
import dagster
import pyarrow as pa
from parameterized import parameterized
+from posthog.models import Organization, Team
+
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.signals.backend.models import SignalReport
from products.signals.backend.ranking.inventory import spine_report_filter
@@ -405,6 +408,36 @@ class TestSpineInclusion(BaseTest):
assert promoted_after_cutoff not in in_spine
assert created_after_cutoff not in in_spine
+ def test_state_snapshot_keeps_only_reports_of_organizations_opted_in_to_ai_training(self):
+ self.organization.is_ai_training_opted_in = True
+ self.organization.save()
+ consenting = self._report(SignalReport.Status.READY)
+ excluded: list[str] = []
+ for consent in (False, None):
+ organization = Organization.objects.create(name=f"consent-{consent}", is_ai_training_opted_in=consent)
+ team = Team.objects.create(organization=organization)
+ report = SignalReport.objects.create(team=team, status=SignalReport.Status.READY, title="t", summary="s")
+ SignalReport.objects.filter(id=report.id).update(created_at=BEFORE_CUTOFF)
+ excluded.append(str(report.id))
+ written: dict[str, Any] = {}
+
+ with (
+ patch.object(dag, "skip_unconfigured", lambda context: False),
+ patch.object(dag, "_tag_dagster_queries", lambda context, query_type: None),
+ # A label event that names an opted-out report must not pull it back into the spine.
+ patch.object(dag, "labels_team", lambda: self.team),
+ patch.object(dag, "hogql_rows", lambda *args, **kwargs: [(excluded[0],)]),
+ patch.object(dag, "s3_client", lambda: None),
+ patch.object(dag, "write_parquet", lambda client, bucket, key, table: written.update(table=table)),
+ dagster.build_asset_context(partition_key=SNAPSHOT_DATE.isoformat()) as context,
+ ):
+ dag.inbox_report_state(context)
+ metadata = context.get_output_metadata("result")
+
+ assert written["table"].column("report_id").to_pylist() == [consenting]
+ assert metadata["excluded_no_training_consent_reports"].value == 2
+ assert metadata["excluded_no_training_consent_teams"].value == 2
+
class TestImpressionsStream(ClickhouseTestMixin, BaseTest):
@parameterized.expand([("labeled_ids", LABELED_REPORT_IDS_SQL), ("impressions", IMPRESSIONS_SQL)])
@@ -554,7 +587,7 @@ class TestStatusStream(ClickhouseTestMixin, BaseTest):
assert row["wrong_dismissal_count"] == (0 if row["status_event_team_id"] == self.team.id else 1)
-def _run_embeddings_asset(monkeypatch, asset, rows):
+def _run_embeddings_asset(monkeypatch, asset, rows, consent_team_ids=frozenset({2})):
"""Run one embeddings asset against a stubbed ClickHouse and S3, and return what it wrote."""
captured: dict[str, Any] = {}
@@ -572,6 +605,9 @@ def _run_embeddings_asset(monkeypatch, asset, rows):
monkeypatch.setattr(dag, "_tag_dagster_queries", lambda context, query_type: None)
monkeypatch.setattr(dag, "dataset_bucket", lambda: "test-bucket")
monkeypatch.setattr(dag, "s3_client", lambda: None)
+ monkeypatch.setattr(dag, "read_parquet_if_exists", lambda *args, **kwargs: None)
+ monkeypatch.setattr(dag, "object_row_count", lambda *args: None)
+ monkeypatch.setattr(dag, "training_consent_team_ids", lambda: consent_team_ids)
monkeypatch.setattr(dag.settings, "INBOX_RANKING_DATASET_S3_PREFIX", "inbox_ranking")
context = dagster.build_asset_context(partition_key=SNAPSHOT_DATE.isoformat())
@@ -605,6 +641,20 @@ def test_an_empty_result_still_writes_the_full_schema(monkeypatch, asset):
assert written["table"].schema == EMBEDDINGS_SCHEMA
+ "asset", [dag.inbox_report_embeddings, dag.inbox_report_title_embeddings, dag.inbox_signal_embeddings]
+)
[email protected]("consent_team_ids", [frozenset({2, 7}), frozenset()])
+def test_embeddings_are_read_only_for_teams_opted_in_to_ai_training(monkeypatch, asset, consent_team_ids):
+ written = _run_embeddings_asset(monkeypatch, asset, [], consent_team_ids)
+
+ if consent_team_ids:
+ assert written["params"]["team_ids"] == [2, 7]
+ else:
+ assert "params" not in written
+ assert written["table"].num_rows == 0
+
+
def test_the_title_snapshot_is_a_leaf_ordered_after_the_join():
selection = dag.inbox_ranking_dataset_job.selection.resolve(
[
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index 69672f4e5f1e..cc84f94cbe9f 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -97,11 +97,13 @@ from products.signals.dags.inbox_ranking.training.dag import (
)
from products.signals.dags.inbox_ranking.training.examples import (
STATE_LAG_LIMIT,
+ ConsentExclusion,
Snapshot,
assemble_snapshot,
birth_day_positives,
build_examples,
cap_examples,
+ drop_without_training_consent,
example_columns,
holdout_mask,
reports_missing_birth_snapshot,
@@ -504,6 +506,25 @@ def test_build_examples_skips_label_only_rows():
assert build_examples(snapshots, head, TABULAR_FEATURE_SET)["report_id"].tolist() == ["a"]
+def test_build_examples_drops_reports_without_training_consent_at_training_time():
+ head = HEADS_BY_NAME["pr_created"]
+ later = D0 + datetime.timedelta(days=head.horizon_days)
+ # opted_out: its organization opted out after these snapshots were written; no_team: a state row
+ # with no readable team; eu: a label-only row with no state.
+ ids = ["consenting", "opted_out", "no_team", "eu"]
+ state = _state(ids, report_team_id=[1, 2, None, None], signal_count=[3, 3, 3, None])
+ snapshots = {
+ D0: Snapshot(date=D0, state=state, labels=_labels(ids)),
+ later: Snapshot(date=later, state=state, labels=_labels(ids, pr_created_count=[1, 1, 1, 1])),
+ }
+
+ kept, excluded = drop_without_training_consent(snapshots, frozenset({1}))
+
+ assert build_examples(kept, head, TABULAR_FEATURE_SET)["report_id"].tolist() == ["consenting"]
+ assert (excluded.reports, excluded.teams) == (2, 1)
+ assert kept[later].labels.index.tolist() == ["consenting", "eu"]
+
+
def test_holdout_mask_cuts_by_report_not_by_row():
examples = pd.DataFrame(
{
@@ -816,7 +837,9 @@ def test_reports_missing_birth_snapshot_counts_only_the_ones_a_partition_gap_cos
pd.NaT,
]
snapshots = {
- date: Snapshot(date=date, state=_state(ids, report_created_at=created), labels=_labels(ids))
+ date: Snapshot(
+ date=date, state=_state(ids, report_created_at=created, report_team_id=[1] * 5), labels=_labels(ids)
+ )
for date in dates
if date != gap
}
@@ -831,6 +854,7 @@ def test_reports_missing_birth_snapshot_counts_only_the_ones_a_partition_gap_cos
monkeypatch.setattr(f"{module}.s3_client", lambda: None)
monkeypatch.setattr(f"{module}.snapshot_dates", lambda *args: dates)
monkeypatch.setattr(f"{module}.load_snapshots", lambda *args, **kwargs: snapshots)
+ monkeypatch.setattr(f"{module}.training_consent_team_ids", lambda: frozenset({1}))
monkeypatch.setattr(f"{module}.embeddings_extras", lambda *args: NO_EXTRAS)
monkeypatch.setattr(f"{module}._write_examples", lambda *args: {})
with dagster.build_asset_context(partition_key=dates[-1].isoformat()) as context:
@@ -1421,6 +1445,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
feature_set=TABULAR_FEATURE_SET.name,
snapshots=20,
backfilled_rows=0,
+ excluded=ConsentExclusion(reports=4, teams=2),
per_head={
"open": HeadExampleCounts(
rows=10,
@@ -1508,6 +1533,8 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
"example_window_start": "2026-07-01",
"example_cap_bound": True,
"feature_set": TABULAR_FEATURE_SET.name,
+ "excluded_no_training_consent_reports": 4,
+ "excluded_no_training_consent_teams": 2,
}.items() <= examples_props.items()
promotion_props = by_event["inbox_ranking_promotion_decided"][0]["properties"]
assert {
@@ -2139,6 +2166,7 @@ def test_only_the_set_whose_snapshot_is_missing_is_skipped(monkeypatch):
monkeypatch.setattr(f"{module}.skip_unconfigured", lambda context: False)
monkeypatch.setattr(f"{module}.s3_client", lambda: None)
monkeypatch.setattr(f"{module}.load_snapshots", lambda *args, **kwargs: {})
+ monkeypatch.setattr(f"{module}.training_consent_team_ids", lambda: frozenset())
monkeypatch.setattr(
f"{module}.embeddings_extras",
lambda context, client, bucket, prefix, partition_key, keys: {
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index ab97449841ca..61bb00dd950e 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -94,6 +94,7 @@ from products.signals.dags.inbox_ranking.common import (
snapshot_bounds,
write_parquet,
)
+from products.signals.dags.inbox_ranking.consent import training_consent_team_ids
from products.signals.dags.inbox_ranking.dataset.dag import (
EMBEDDINGS_TABLE,
LABELS_TABLE,
@@ -104,11 +105,13 @@ from products.signals.dags.inbox_ranking.training.examples import (
BASE_STATE_COLUMNS,
PROVENANCE_LABEL_COLUMNS,
PROVENANCE_STATE_COLUMNS,
+ ConsentExclusion,
HeadExamples,
Snapshot,
assemble_snapshot,
birth_day_positives,
build_head_examples,
+ drop_without_training_consent,
example_columns,
point_in_time_mask,
reports_missing_birth_snapshot,
@@ -407,6 +410,9 @@ def inbox_ranking_training_examples(context: dagster.AssetExecutionContext) -> N
dates = snapshot_dates(partition_key, settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS)
snapshots = load_snapshots(client, bucket, prefix, dates, required=dates[-1])
context.log.info(f"{len(snapshots)} of {len(dates)} snapshots present")
+ snapshots, excluded = drop_without_training_consent(snapshots, training_consent_team_ids())
+ if excluded.reports:
+ context.log.info(f"{excluded.reports} reports from {excluded.teams} teams without AI training consent excluded")
backfilled_rows = sum(int((~point_in_time_mask(snap.state, snap.date)).sum()) for snap in snapshots.values())
if backfilled_rows:
context.log.warning(f"{backfilled_rows} state rows read after the snapshot window are excluded (backfill)")
@@ -421,10 +427,12 @@ def inbox_ranking_training_examples(context: dagster.AssetExecutionContext) -> N
"snapshots": dagster.MetadataValue.int(len(snapshots)),
"backfilled_state_rows_excluded": dagster.MetadataValue.int(backfilled_rows),
"reports_missing_birth_snapshot": dagster.MetadataValue.int(unreachable_reports),
+ "excluded_no_training_consent_reports": dagster.MetadataValue.int(excluded.reports),
+ "excluded_no_training_consent_teams": dagster.MetadataValue.int(excluded.teams),
}
for feature_set in FEATURE_SETS.values():
metadata |= _examples_for_set(
- context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows
+ context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows, excluded
)
context.add_output_metadata(metadata)
@@ -438,6 +446,7 @@ def _examples_for_set(
feature_set: FeatureSet,
snapshots: Mapping[datetime.date, Snapshot],
backfilled_rows: int,
+ excluded: ConsentExclusion,
) -> dict[str, dagster.MetadataValue]:
"""One feature set's examples for the partition, side inputs included, and its asset metadata.
@@ -456,7 +465,7 @@ def _examples_for_set(
context.log.warning(f"{feature_set.name} examples not rebuilt for dt={partition_key}: no {', '.join(missing)}")
return {f"{feature_set.name}_skipped": dagster.MetadataValue.bool(True)}
return _write_examples(
- context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows, extras
+ context, client, bucket, prefix, partition_key, feature_set, snapshots, backfilled_rows, excluded, extras
)
@@ -469,6 +478,7 @@ def _write_examples(
feature_set: FeatureSet,
snapshots: Mapping[datetime.date, Snapshot],
backfilled_rows: int,
+ excluded: ConsentExclusion,
extras: Extras,
) -> dict[str, dagster.MetadataValue]:
"""One feature set's examples for the partition, as its own object and its own events, with
@@ -521,6 +531,7 @@ def _write_examples(
feature_set=feature_set.name,
snapshots=len(snapshots),
backfilled_rows=backfilled_rows,
+ excluded=excluded,
per_head=counts,
),
)
diff --git a/products/signals/dags/inbox_ranking/training/examples.py b/products/signals/dags/inbox_ranking/training/examples.py
index e16339a75b2c..e0a7c6666ded 100644
--- a/products/signals/dags/inbox_ranking/training/examples.py
+++ b/products/signals/dags/inbox_ranking/training/examples.py
@@ -135,6 +135,43 @@ def assemble_snapshot(date: datetime.date, state: pd.DataFrame, labels: pd.DataF
return Snapshot(date=date, state=state, labels=aligned)
+@frozen
+class ConsentExclusion:
+ """What `drop_without_training_consent` removed, as counts only."""
+
+ reports: int
+ teams: int
+
+
+def drop_without_training_consent(
+ snapshots: Mapping[datetime.date, Snapshot], team_ids: frozenset[int]
+) -> tuple[dict[datetime.date, Snapshot], ConsentExclusion]:
+ """`snapshots` without the reports of teams outside `team_ids`, read at training time.
+
+ The dataset dag stops collecting those reports, but the window reaches back over partitions
+ written before an organization opted out. Filtering here makes an opt-out reach the next
+ training run. A state row with no readable team fails closed. Label-only rows have no state and
+ are kept: `example_moments` never makes one a moment, and a report deleted before a later
+ snapshot needs its label row there.
+ """
+ kept: dict[datetime.date, Snapshot] = {}
+ reports: set[object] = set()
+ teams: set[int] = set()
+ for date, snapshot in snapshots.items():
+ state = snapshot.state
+ team = state["report_team_id"] if "report_team_id" in state else pd.Series(float("nan"), index=state.index)
+ excluded = state["signal_count"].notna() & ~team.isin(team_ids)
+ dropped = state.index[excluded.to_numpy()]
+ reports.update(dropped)
+ teams.update(int(team_id) for team_id in team[excluded].dropna())
+ kept[date] = Snapshot(
+ date=date,
+ state=state.drop(dropped),
+ labels=snapshot.labels.drop(snapshot.labels.index.intersection(dropped)),
+ )
+ return kept, ConsentExclusion(reports=len(reports), teams=len(teams))
+
+
def birth_day_mask(state: pd.DataFrame, date: datetime.date) -> pd.Series:
"""True for rows of the reports created on snapshot day `date`.
diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.py
index b9dabd008278..dd39faa28460 100644
--- a/products/signals/dags/inbox_ranking/training/telemetry.py
+++ b/products/signals/dags/inbox_ranking/training/telemetry.py
@@ -21,6 +21,7 @@ from posthog.ph_client import get_client
from products.signals.backend.ranking.serving_manifest import ServingManifest
from products.signals.dags.inbox_ranking.common import snapshot_bounds
+from products.signals.dags.inbox_ranking.training.examples import ConsentExclusion
from products.signals.dags.inbox_ranking.training.promotion import PromotionDecision
from products.signals.dags.inbox_ranking.training.unseen import CANDIDATE_ROLE, HeadGrade
@@ -108,6 +109,7 @@ def examples_events(
feature_set: str,
snapshots: int,
backfilled_rows: int,
+ excluded: ConsentExclusion,
per_head: Mapping[str, HeadExampleCounts],
) -> list[TrainingEvent]:
"""One event per head with its example and positive counts; the run-level counts repeat on each.
@@ -124,6 +126,8 @@ def examples_events(
"run_id": run_id,
"snapshots": snapshots,
"backfilled_state_rows_excluded": backfilled_rows,
+ "excluded_no_training_consent_reports": excluded.reports,
+ "excluded_no_training_consent_teams": excluded.teams,
"head": head,
"rows": counts.rows,
"positives": counts.positives,