:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): add daily per-team project vectors for inbox ranking (#115465)
posthog[bot]0c62c66e4b37
diff --git a/posthog/dags/locations/signals.py b/posthog/dags/locations/signals.pyindex 7b1794abba57..74a1f2804390 100644--- a/posthog/dags/locations/signals.py+++ b/posthog/dags/locations/signals.py@@ -22,6 +22,7 @@ if is_inbox_ranking_registered():inbox_ranking_dataset.inbox_report_title_embeddings,inbox_ranking_dataset.inbox_report_reviewers,inbox_ranking_dataset.inbox_user_report_interactions,+ inbox_ranking_dataset.inbox_project_vectors,inbox_ranking_training.inbox_ranking_training_examples,inbox_ranking_training.inbox_ranking_model_candidate,inbox_ranking_training.inbox_ranking_model_champion,diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex 8300d4341bf2..5ecef58d717a 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -7,6 +7,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- 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.- `inbox_report_title_embeddings` is a **leaf**: never add it to `inbox_report_model_data`'s `deps` or give that join a title column, or a failure in the title snapshot fails the training table. Its own `deps=[MODEL_DATA_TABLE]` exists for memory, not data — two full sets of 1536-float vectors must not be held at once in the run pod. Raising the pod memory limit is not the first resort.- `inbox_user_report_interactions` is a **leaf** with its own `USER_INTERACTIONS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`, and never stamp it with `FEATURE_SCHEMA_VERSION`, or a user-grain change sets off the labels refresh sensor. It writes a row only for a report in this region's Postgres whose team is in `training_consent_team_ids()`.+- `inbox_project_vectors` is a **leaf** with its own `PROJECT_VECTORS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`. Its `deps=[EMBEDDINGS_TABLE, LABELS_TABLE]` keep it after the embeddings snapshot, so the two vector-heavy steps do not share the run pod's memory. `project_vectors` takes a report into a vector only when its vector landed and its UI engagement happened strictly before `as_of`; never widen that to the latest snapshot value. A report born on day D reads the dt=D−1 vectors (see the README).- 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`).## Training dag specificsdiff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 845b8525d897..8951d8080c0b 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -7,7 +7,8 @@ inbox_ranking/├── common.py # shared: S3 destination config, daily partition def, gating, Parquet IO├── dataset/│ ├── dag.py # the dataset assets + job + schedule-│ └── queries.py # HogQL label SQL, embeddings SQL, stream merging+│ ├── queries.py # HogQL label SQL, embeddings SQL, stream merging+│ └── project_vectors.py # per-team context vectors (pure function)├── training/│ ├── dag.py # examples → candidate → champion assets + job + schedule│ ├── examples.py # birth-grain training examples over the snapshots@@ -21,7 +22,7 @@ Registered via `posthog/dags/locations/signals.py` (US only) and loaded locally## The dataset dag-`inbox_ranking_dataset_job` runs daily at 02:30 UTC (schedule default: running on prod US, stopped everywhere else — including hosted DEV and E2E, which have no dogfood project to read labels from) and builds eight assets on one daily partition, each a Parquet object in S3:+`inbox_ranking_dataset_job` runs daily at 02:30 UTC (schedule default: running on prod US, stopped everywhere else — including hosted DEV and E2E, which have no dogfood project to read labels from) and builds nine assets on one daily partition, each a Parquet object in S3:```texts3://<bucket>/<prefix>/@@ -34,7 +35,8 @@ s3://<bucket>/<prefix>/├── inbox_signal_embeddings/v1/dt=YYYY-MM-DD/ # one row per signal emitted during the day (signal grain)├── inbox_report_title_embeddings/v1/dt=YYYY-MM-DD/ # the same shape, for the title-only rendering├── inbox_report_reviewers/v1/dt=YYYY-MM-DD/ # one row per suggested reviewer of each spine report-└── inbox_user_report_interactions/v1/dt=YYYY-MM-DD/ # cumulative interactions per (report, person)+├── inbox_user_report_interactions/v1/dt=YYYY-MM-DD/ # cumulative interactions per (report, person)+└── inbox_project_vectors/v1/dt=YYYY-MM-DD/ # per-team mean report vectors of past engagement, by kind```The first four are report grain and land in one table. `inbox_signal_embeddings` is signal grain, feeds the group-level model, and is read on its own — training joins it to `inbox_report_model_data` by `report_id`.@@ -47,6 +49,30 @@ The first four are report grain and land in one table. `inbox_signal_embeddings`- An entry that maps to no member stays as a row with a null `user_distinct_id`, so a reviewer with no history is counted and not dropped.- **The asset is current-state-only.** The index is rebuilt in full on every reviewer change, and reviewer artefacts can be edited in place or deleted, so no earlier set can be rebuilt. A forward-run partition holds the set at run time (at most a few hours after the cutoff). A backfilled partition holds today's set, flagged by `features_observed_at`. History starts on the day the asset first ran.+### Project vectors++`inbox_project_vectors` is a (team, kind) leaf with context vectors for a ranking model that reads a team's engagement history next to the report's own vector.+`dataset/project_vectors.py` holds the pure function `project_vectors(labels, embeddings, as_of)`, and the asset calls it with `as_of` = the end of dt=D.++| `kind` | Mean of |+| --------- | ------------------------------------------------------------------------------------------------ |+| `typical` | every report vector of the team |+| `open` | the last 50 reports anyone on the team opened before `as_of` |+| `action` | the last 50 reports anyone on the team acted on through a UI intent action (`UI_ACTION_COLUMNS`) |+| `dismiss` | the last 50 reports anyone on the team dismissed from the UI |++- The columns are `team_id`, `kind`, `vector` (small-1536), `n_reports` and `as_of`.+- The inputs are the dt=D `inbox_report_embeddings` and `inbox_report_labels` snapshots only. The engagement moments are the labels' first-event timestamps of the inbox app events, so MCP reads and agent actions never count. A project is a team, not an organization.+- A kind with fewer than `MIN_HISTORY_REPORTS` reports keeps its row, with its real `n_reports` and an all-zero vector. A team with no report vector before `as_of` has no rows.+- The asset filters the embeddings snapshot through `training_consent_team_ids()` again, so an opt-out after the snapshot was written takes effect.+- **It is a leaf.** Nothing joins it, it is not in `inbox_report_model_data`'s deps, and its object carries its own `PROJECT_VECTORS_SCHEMA_VERSION`, so a failure here does not fail the training table. Its deps on the embeddings and labels assets keep it after the embeddings snapshot, so the two vector-heavy steps do not share the run pod's memory.++Point-in-time contract:++- A report born on day D uses the project vectors of dt=D−1. Their `as_of` is D 00:00 UTC, strictly before the birth, and that matches serving, where the sweep reads the newest snapshot.+- A report enters a vector only when its vector landed and its engagement happened strictly before `as_of`. The snapshot holds only the latest vector per report, so a report re-embedded after `as_of` is left out rather than read with text it did not have yet.+- The training side can rebuild any past day by calling the function on newer snapshots with an earlier `as_of`. No backfill is needed while the vectors are inside the embedding TTL.+### 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`.diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.pyindex d90e8e28a040..264e216e7436 100644--- a/products/signals/dags/inbox_ranking/dataset/dag.py+++ b/products/signals/dags/inbox_ranking/dataset/dag.py@@ -1,6 +1,6 @@"""Daily modeling dataset for the Self-driving Inbox report-ranking model.-Seven assets on one daily partition, each writing Parquet under the configured S3 prefix:+Nine assets on one daily partition, each writing Parquet under the configured S3 prefix:inbox_report_state/v1/dt=D/ Postgres spine + report-state columnsinbox_report_embeddings/v1/dt=D/ report_id -> small-1536 vector as of snapshot end@@ -10,6 +10,7 @@ Seven assets on one daily partition, each writing Parquet under the configured Sinbox_report_title_embeddings/v1/dt=D/ the same shape, for the title-only renderinginbox_report_reviewers/v1/dt=D/ one row per suggested reviewer of each spine reportinbox_user_report_interactions/v1/dt=D/ cumulative interactions at (report, person) grain+ inbox_project_vectors/v1/dt=D/ per-team mean report vectors of past engagement, by kindThe first four are report grain and feed one table. inbox_signal_embeddings is signal grain and isread on its own, joined to the others by report_id at training time. inbox_report_title_embeddings@@ -17,7 +18,8 @@ is a report-grain leaf: nothing joins it, and the training side pairs it to inboby report_id when it measures one rendering against the other. inbox_report_reviewers is a(report, reviewer) leaf with its own schema version: nothing joins it, and the training side pairsit to the report tables by report_id. inbox_user_report_interactions is a (report, person) grain-leaf with its own schema version, so nothing joins it either.+leaf with its own schema version, so nothing joins it either. inbox_project_vectors is a+(team, kind) leaf with its own schema version, built from the embeddings and labels snapshots.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,@@ -64,6 +66,7 @@ from django.db.models import Count, Minimport dagsterimport pyarrow as pa+import pyarrow.compute as pcfrom posthog import settingsfrom posthog.clickhouse.client import sync_execute@@ -117,6 +120,14 @@ from products.signals.dags.inbox_ranking.common import (write_parquet,)from products.signals.dags.inbox_ranking.consent import training_consent_team_ids+from products.signals.dags.inbox_ranking.dataset.project_vectors import (+ EMBEDDING_COLUMNS,+ LABEL_COLUMNS,+ MIN_HISTORY_REPORTS,+ PROJECT_VECTORS_SCHEMA_VERSION,+ VECTOR_KINDS,+ project_vectors,+)from products.signals.dags.inbox_ranking.dataset.queries import (LABEL_DEFAULTS,LABEL_STREAMS,@@ -154,6 +165,7 @@ MODEL_DATA_TABLE = "inbox_report_model_data"SIGNAL_EMBEDDINGS_TABLE = "inbox_signal_embeddings"REVIEWERS_TABLE = "inbox_report_reviewers"USER_INTERACTIONS_TABLE = "inbox_user_report_interactions"+PROJECT_VECTORS_TABLE = "inbox_project_vectors"# The reviewers asset is a leaf with its own columns, so its schema moves apart from# FEATURE_SCHEMA_VERSION. The same rule applies: additive nullable columns bump it.@@ -1335,6 +1347,58 @@ def inbox_user_report_interactions(context: dagster.AssetExecutionContext) -> No)+ name=PROJECT_VECTORS_TABLE,+ # Read after the embeddings snapshot has finished, so its vectors and the snapshot query's do+ # not share the run pod's memory. Nothing joins this asset, so its failure does not fail the+ # training table.+ deps=[EMBEDDINGS_TABLE, LABELS_TABLE],+ **COMMON_ASSET_KWARGS,+)+def inbox_project_vectors(context: dagster.AssetExecutionContext) -> None:+ """Per-team context vectors as of the partition end, for a report born on the next day."""+ if skip_unconfigured(context):+ return+ partition_key = context.partition_key+ _, snapshot_end = snapshot_bounds(partition_key)+ bucket = dataset_bucket()+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX+ client = s3_client()++ embeddings = read_parquet(+ client, bucket, partition_object_key(prefix, EMBEDDINGS_TABLE, partition_key), list(EMBEDDING_COLUMNS)+ )+ # The snapshot was filtered when it was written. Filter it again, so an opt-out since then counts.+ consent_team_ids = training_consent_team_ids()+ consented = embeddings.filter(+ pc.is_in(embeddings.column("report_team_id"), value_set=pa.array(sorted(consent_team_ids), type=pa.int64()))+ )+ excluded_reports = embeddings.num_rows - consented.num_rows+ del embeddings+ labels = read_parquet(+ client, bucket, partition_object_key(prefix, LABELS_TABLE, partition_key), list(LABEL_COLUMNS)+ )+ table = project_vectors(labels, consented, snapshot_end)++ key = partition_object_key(prefix, PROJECT_VECTORS_TABLE, partition_key)+ write_parquet(client, bucket, key, table, schema_version=PROJECT_VECTORS_SCHEMA_VERSION)+ counts = table.select(["kind", "n_reports"]).to_pylist()+ context.add_output_metadata(+ {+ "rows": dagster.MetadataValue.int(table.num_rows),+ "teams": dagster.MetadataValue.int(len(set(table.column("team_id").to_pylist()))),+ **{+ f"teams_with_{kind}_history": dagster.MetadataValue.int(+ sum(1 for row in counts if row["kind"] == kind and row["n_reports"] >= MIN_HISTORY_REPORTS)+ )+ for kind in VECTOR_KINDS+ },+ "excluded_no_training_consent_reports": dagster.MetadataValue.int(excluded_reports),+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),+ }+ )++def label_provenance_ok(pg_status: str | None,pg_updated_at: datetime.datetime | None,@@ -1501,6 +1565,7 @@ inbox_ranking_dataset_job = dagster.define_asset_job(TITLE_EMBEDDINGS_TABLE,REVIEWERS_TABLE,USER_INTERACTIONS_TABLE,+ PROJECT_VECTORS_TABLE,],# The seven label streams run sequentially and each may take its full 600s query timeout, so an# hour left a slow-but-valid pass no room for the join, the S3 writes, or an asset retry — anddiff --git a/products/signals/dags/inbox_ranking/dataset/project_vectors.py b/products/signals/dags/inbox_ranking/dataset/project_vectors.pynew file mode 100644index 000000000000..cdc2e71643d0--- /dev/null+++ b/products/signals/dags/inbox_ranking/dataset/project_vectors.py@@ -0,0 +1,146 @@+"""Per-team context vectors for the inbox ranking model.++A team's engagement history carries ranking signal beyond a report's own vector: a report similar+to what the team opened or acted on before is more likely to get the same engagement. Each team+gets one vector per kind, as of a moment:++ typical the mean of every report vector the team had+ open the mean of the last `HISTORY_LIMIT` reports anyone on the team opened+ action the same, over the reports anyone acted on through a UI intent action+ dismiss the same, over the reports anyone dismissed from the UI++Only human UI engagement counts: the open, action and dismiss moments come from the inbox app+events, so MCP reads and agent actions never reach a vector. A project is a team, not an+organization.+"""++import datetime+from collections import defaultdict+from collections.abc import Sequence++import numpy as np+import pyarrow as pa+import pyarrow.compute as pc++from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS+from products.signals.dags.inbox_ranking.dataset.queries import ACTION_TYPES+from products.signals.dags.inbox_ranking.training.heads import UI_ACTION_COLUMNS++# A leaf with its own columns, so its schema moves apart from FEATURE_SCHEMA_VERSION.+PROJECT_VECTORS_SCHEMA_VERSION = 1++HISTORY_LIMIT = 50+# Below this many reports, a mean is mostly one report's text and says little about the team.+MIN_HISTORY_REPORTS = 5++TYPICAL = "typical"+OPEN = "open"+ACTION = "action"+DISMISS = "dismiss"+VECTOR_KINDS = (TYPICAL, OPEN, ACTION, DISMISS)++OPEN_COLUMN = "first_opened_at"+DISMISS_COLUMN = "first_ui_dismissed_at"+UI_ACTION_FIRST_COLUMNS = tuple(first for _, count, first in ACTION_TYPES if count in UI_ACTION_COLUMNS)+LABEL_COLUMNS = ("report_id", OPEN_COLUMN, DISMISS_COLUMN, *UI_ACTION_FIRST_COLUMNS)+EMBEDDING_COLUMNS = ("report_id", "report_team_id", "embedding_small", "embedding_inserted_at", "is_tombstone")++_PROJECT_VECTORS_FIELDS: list[tuple[str, pa.DataType]] = [+ ("team_id", pa.int64()),+ ("kind", pa.string()),+ ("vector", pa.list_(pa.float32())),+ ("n_reports", pa.int32()),+ ("as_of", pa.timestamp("us", tz="UTC")),+]+PROJECT_VECTORS_SCHEMA = pa.schema(_PROJECT_VECTORS_FIELDS)+++def project_vectors(labels: pa.Table, embeddings: pa.Table, as_of: datetime.datetime) -> pa.Table:+ """One row per (team, kind) for every team with a report vector before `as_of`.++ `labels` is an `inbox_report_labels` snapshot and `embeddings` an `inbox_report_embeddings`+ snapshot, both at or after `as_of`. A later snapshot rebuilds an earlier day: a report enters a+ vector only when its vector landed and its engagement happened strictly before `as_of`. The+ snapshot keeps only the latest vector per report, so a report re-embedded after `as_of` is left+ out rather than read with text it did not have yet.++ A kind with fewer than `MIN_HISTORY_REPORTS` reports keeps its row, with its real `n_reports`+ and an all-zero vector, so a reader can tell a thin history from a missing team.+ """+ usable = _usable_embeddings(embeddings, as_of)+ matrix = (+ pc.list_flatten(usable.column("embedding_small").combine_chunks())+ .to_numpy(zero_copy_only=False)+ .reshape(-1, EMBEDDING_DIMENSIONS)+ )+ report_ids = [str(report_id) for report_id in usable.column("report_id").to_pylist()]+ rows_by_team: dict[int, list[int]] = defaultdict(list)+ for index, team_id in enumerate(usable.column("report_team_id").to_pylist()):+ if team_id is not None:+ rows_by_team[team_id].append(index)+ engaged_at = _engaged_at(labels)++ rows: list[dict[str, object]] = []+ for team_id in sorted(rows_by_team):+ team_rows = rows_by_team[team_id]+ rows.append(_vector_row(team_id, TYPICAL, matrix, team_rows, as_of))+ for kind in (OPEN, ACTION, DISMISS):+ moments = engaged_at[kind]+ engaged = [+ (moment, index)+ for index in team_rows+ if (moment := moments.get(report_ids[index])) is not None and moment < as_of+ ]+ latest = [index for _, index in sorted(engaged, reverse=True)[:HISTORY_LIMIT]]+ rows.append(_vector_row(team_id, kind, matrix, latest, as_of))+ return pa.Table.from_pylist(rows, schema=PROJECT_VECTORS_SCHEMA)+++def _usable_embeddings(embeddings: pa.Table, as_of: datetime.datetime) -> pa.Table:+ """The rows with a full-width, live vector that landed before `as_of`.++ Only the narrow columns are pulled into Python; the vectors stay in Arrow."""+ widths = pc.list_value_length(embeddings.column("embedding_small")).to_pylist()+ mask = pa.array(+ [+ team_id is not None+ and not is_tombstone+ and width == EMBEDDING_DIMENSIONS+ and inserted_at is not None+ and inserted_at < as_of+ for team_id, is_tombstone, width, inserted_at in zip(+ embeddings.column("report_team_id").to_pylist(),+ embeddings.column("is_tombstone").to_pylist(),+ widths,+ embeddings.column("embedding_inserted_at").to_pylist(),+ strict=True,+ )+ ],+ type=pa.bool_(),+ )+ return embeddings.filter(mask).select(["report_id", "report_team_id", "embedding_small"])+++def _engaged_at(labels: pa.Table) -> dict[str, dict[str, datetime.datetime]]:+ """The first UI engagement moment of each kind per report."""+ engaged_at: dict[str, dict[str, datetime.datetime]] = {OPEN: {}, ACTION: {}, DISMISS: {}}+ for row in labels.select(list(LABEL_COLUMNS)).to_pylist():+ report_id = row["report_id"]+ if row[OPEN_COLUMN] is not None:+ engaged_at[OPEN][report_id] = row[OPEN_COLUMN]+ if row[DISMISS_COLUMN] is not None:+ engaged_at[DISMISS][report_id] = row[DISMISS_COLUMN]+ actions = [row[column] for column in UI_ACTION_FIRST_COLUMNS if row[column] is not None]+ if actions:+ engaged_at[ACTION][report_id] = min(actions)+ return engaged_at+++def _vector_row(+ team_id: int, kind: str, matrix: np.ndarray, indices: Sequence[int], as_of: datetime.datetime+) -> dict[str, object]:+ if len(indices) < MIN_HISTORY_REPORTS:+ vector = np.zeros(EMBEDDING_DIMENSIONS, dtype=np.float32)+ else:+ vector = matrix[list(indices)].mean(axis=0, dtype=np.float64).astype(np.float32)+ return {"team_id": team_id, "kind": kind, "vector": vector, "n_reports": len(indices), "as_of": as_of}diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.pyindex 5b7cd7f10e36..f145b62c1d00 100644--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py@@ -1104,10 +1104,16 @@ def test_the_leaf_snapshots_run_in_the_job_without_feeding_the_join():dag.inbox_report_title_embeddings,dag.inbox_report_reviewers,dag.inbox_user_report_interactions,+ dag.inbox_project_vectors,])model_data_deps = {key.path[-1] for key in dag.inbox_report_model_data.keys_by_input_name.values()}- for leaf in (dag.TITLE_EMBEDDINGS_TABLE, dag.REVIEWERS_TABLE, dag.USER_INTERACTIONS_TABLE):+ for leaf in (+ dag.TITLE_EMBEDDINGS_TABLE,+ dag.REVIEWERS_TABLE,+ dag.USER_INTERACTIONS_TABLE,+ dag.PROJECT_VECTORS_TABLE,+ ):assert dagster.AssetKey(leaf) in selectionassert leaf not in model_data_depsdiff --git a/products/signals/dags/inbox_ranking/tests/test_project_vectors.py b/products/signals/dags/inbox_ranking/tests/test_project_vectors.pynew file mode 100644index 000000000000..c57ad31339aa--- /dev/null+++ b/products/signals/dags/inbox_ranking/tests/test_project_vectors.py@@ -0,0 +1,148 @@+import datetime+from typing import Any++import pytest++import dagster+import pyarrow as pa+from parameterized import parameterized++from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS+from products.signals.dags.inbox_ranking import common+from products.signals.dags.inbox_ranking.dataset import dag+from products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_SCHEMA, LABELS_SCHEMA+from products.signals.dags.inbox_ranking.dataset.project_vectors import (+ HISTORY_LIMIT,+ MIN_HISTORY_REPORTS,+ PROJECT_VECTORS_SCHEMA,+ PROJECT_VECTORS_SCHEMA_VERSION,+ project_vectors,+)++AS_OF = datetime.datetime(2026, 7, 30, tzinfo=datetime.UTC)+BEFORE = AS_OF - datetime.timedelta(days=3)+AFTER = AS_OF + datetime.timedelta(hours=1)+++def _report_id(team_id: int, index: int) -> str:+ return f"report-{team_id}-{index}"+++def _embeddings(reports: list[tuple[int, int, float, datetime.datetime]]) -> pa.Table:+ return pa.Table.from_pylist(+ [+ {+ "snapshot_date": AS_OF.date(),+ "report_id": _report_id(team_id, index),+ "report_team_id": team_id,+ "embedding_small": [value] * EMBEDDING_DIMENSIONS,+ "embedding_inserted_at": inserted_at,+ "embedding_rendering": "title_summary_v1",+ "is_tombstone": False,+ }+ for team_id, index, value, inserted_at in reports+ ],+ schema=EMBEDDINGS_SCHEMA,+ )+++def _labels(engagements: list[tuple[int, int, str, datetime.datetime]]) -> pa.Table:+ return pa.Table.from_pylist(+ [+ {"snapshot_date": AS_OF.date(), "report_id": _report_id(team_id, index), column: moment}+ for team_id, index, column, moment in engagements+ ],+ schema=LABELS_SCHEMA,+ )+++def _rows_by_key(table: pa.Table) -> dict[tuple[int, str], dict[str, Any]]:+ return {(row["team_id"], row["kind"]): row for row in table.to_pylist()}+++ [+ ("open", "first_opened_at"),+ ("action", "first_implement_clicked_at"),+ ("action", "first_reviewer_removed_at"),+ ("dismiss", "first_ui_dismissed_at"),+ ]+)+def test_only_engagement_and_vectors_before_as_of_enter_a_vector(kind: str, column: str) -> None:+ reports = [(2, index, 1.0, BEFORE) for index in range(MIN_HISTORY_REPORTS)]+ reports += [(2, 100, 9.0, BEFORE), (2, 101, 9.0, AFTER)]+ engagements = [(2, index, column, BEFORE) for index in range(MIN_HISTORY_REPORTS)]+ # Engaged after as_of, and engaged in time with a vector re-embedded after as_of.+ engagements += [(2, 100, column, AFTER), (2, 101, column, BEFORE)]++ rows = _rows_by_key(project_vectors(_labels(engagements), _embeddings(reports), AS_OF))++ assert rows[(2, kind)]["n_reports"] == MIN_HISTORY_REPORTS+ assert rows[(2, kind)]["vector"] == pytest.approx([1.0] * EMBEDDING_DIMENSIONS)+ assert rows[(2, "typical")]["n_reports"] == MIN_HISTORY_REPORTS + 1+++def test_vectors_never_mix_teams_and_keep_the_latest_history() -> None:+ history = HISTORY_LIMIT + 3+ reports = [(2, index, float(index < 3), BEFORE) for index in range(history)]+ reports += [(7, index, 5.0, BEFORE) for index in range(MIN_HISTORY_REPORTS)]+ # Team 2's three oldest opens hold the 1.0 vectors, so the latest HISTORY_LIMIT opens average to 0.+ engagements = [+ (2, index, "first_opened_at", BEFORE + datetime.timedelta(minutes=index)) for index in range(history)+ ]+ engagements += [(7, index, "first_opened_at", BEFORE) for index in range(MIN_HISTORY_REPORTS)]++ table = project_vectors(_labels(engagements), _embeddings(reports), AS_OF)+ rows = _rows_by_key(table)++ assert table.schema == PROJECT_VECTORS_SCHEMA+ assert rows[(2, "open")]["n_reports"] == HISTORY_LIMIT+ assert rows[(2, "open")]["vector"] == pytest.approx([0.0] * EMBEDDING_DIMENSIONS)+ assert rows[(2, "typical")]["vector"] == pytest.approx([3 / history] * EMBEDDING_DIMENSIONS)+ assert rows[(7, "open")]["vector"] == pytest.approx([5.0] * EMBEDDING_DIMENSIONS)+ assert rows[(7, "typical")]["vector"] == pytest.approx([5.0] * EMBEDDING_DIMENSIONS)+++def test_a_team_below_the_history_threshold_keeps_a_zero_vector_row() -> None:+ thin = MIN_HISTORY_REPORTS - 1+ reports = [(2, index, 1.0, BEFORE) for index in range(thin)]+ engagements = [(2, index, "first_create_pr_clicked_at", BEFORE) for index in range(thin)]++ rows = _rows_by_key(project_vectors(_labels(engagements), _embeddings(reports), AS_OF))++ assert {kind: row["n_reports"] for (_, kind), row in rows.items()} == {+ "typical": thin,+ "open": 0,+ "action": thin,+ "dismiss": 0,+ }+ for row in rows.values():+ assert row["vector"] == [0.0] * EMBEDDING_DIMENSIONS+++def test_the_asset_writes_only_teams_opted_in_to_ai_training(monkeypatch) -> None:+ partition_key = (AS_OF.date() - datetime.timedelta(days=1)).isoformat()+ reports = [(team_id, index, 1.0, BEFORE) for team_id in (2, 7) for index in range(MIN_HISTORY_REPORTS)]+ snapshots = {+ common.partition_object_key("inbox_ranking", dag.EMBEDDINGS_TABLE, partition_key): _embeddings(reports),+ common.partition_object_key("inbox_ranking", dag.LABELS_TABLE, partition_key): _labels([]),+ }+ captured: dict[str, Any] = {}++ def fake_write_parquet(client, bucket, key, table, snapshot_date=None, schema_version=None):+ captured.update(key=key, table=table, schema_version=schema_version)++ monkeypatch.setattr(dag, "skip_unconfigured", lambda context: False)+ monkeypatch.setattr(dag, "dataset_bucket", lambda: "test-bucket")+ monkeypatch.setattr(dag, "s3_client", lambda: None)+ monkeypatch.setattr(dag, "read_parquet", lambda client, bucket, key, columns=None: snapshots[key].select(columns))+ monkeypatch.setattr(dag, "write_parquet", fake_write_parquet)+ monkeypatch.setattr(dag, "training_consent_team_ids", lambda: frozenset({7}))+ monkeypatch.setattr(dag.settings, "INBOX_RANKING_DATASET_S3_PREFIX", "inbox_ranking")++ dag.inbox_project_vectors(dagster.build_asset_context(partition_key=partition_key))++ assert captured["key"] == common.partition_object_key("inbox_ranking", dag.PROJECT_VECTORS_TABLE, partition_key)+ assert captured["schema_version"] == PROJECT_VECTORS_SCHEMA_VERSION+ assert set(captured["table"].column("team_id").to_pylist()) == {7}+ assert set(captured["table"].column("as_of").to_pylist()) == {AS_OF}