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.

25.1 KB
Raw Blame

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.
  • 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.
  • Every dataset asset that holds report vectors or a fleet-wide report spine takes HEAVY_ASSET_KWARGS, so it carries MEMORY_HEAVY_OP_TAG and the dataset job's executor runs it alone among the heavy steps, and it reports peak_rss_metadata(). Use the tag, not a deps edge, to keep heavy steps apart. report_embeddings_table reads its rows in REPORT_EMBEDDINGS_PAGES hash-bucket pages and holds only one page as Python objects. Never read the fleet's vectors in one sync_execute.
  • 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 engagement moment (a UI event, or first_fixed_at for fixed) 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). It writes every kind of ALL_PROJECT_VECTOR_KINDS from CONTEXT_LABEL_COLUMNS. LABEL_COLUMNS holds the UI engagement columns only, without first_fixed_at.
  • inbox_user_vectors is a leaf with its own USER_VECTORS_SCHEMA_VERSION: keep it out of inbox_report_model_data's deps. Its deps=[PROJECT_VECTORS_TABLE, USER_INTERACTIONS_TABLE] keep it after the project vectors, so two reads of the embeddings snapshot do not share the run pod's memory. It builds its rows through user_vectors() with the same consent re-filter and team_organizations mapping as the pair lane, so its dt=D rows equal what pair_user_vectors rebuilds for a report born on D+1; a test pins that parity. user_hash covers each kind's name, n_reports and vector only, so a day that adds no report keeps a user's hash.
  • inbox_engagement_export is a leaf with its own ENGAGEMENT_EXPORT_SCHEMA_VERSION, read by another region. It writes to the mirror store only under serving_engagement_key, because the mirror's write grant covers only <prefix>/serving/. Keep its columns exactly ENGAGEMENT_EXPORT_COLUMNS (report ids and engagement timestamps) and its rows limited to reports with no SignalReport in this region: no team ids, counts, text or vectors leave the region. A mirror failure logs and must not fail the asset. Keep the local-share guard before the write: when the local report lookup finds no local report (no_local_reports) or a share below ENGAGEMENT_EXPORT_MIN_LOCAL_SHARE (local_share_collapsed), the asset writes nothing and still succeeds. Its inbox_ranking_engagement_export_published event carries counts only, never a report id or a team id.
  • inbox_mirror_project_vectors (mirror/dag.py) is the only inbox-ranking asset that registers on EU (is_inbox_ranking_mirror_registered()). It reads this region's report vectors through report_embeddings_table and the engagement export through serving_engagement_key, and writes only to this region's object store at serving_project_vectors_key. Keep it on the same project_vectors() and the same consent rule as inbox_project_vectors, so the two regions build their vectors the same way. A missing, too old or unknown-schema export fails the asset rather than writing vectors without engagement. The two regions deploy apart, so the reader takes the current export schema version and the one before it: a v1 export has no first_fixed_at, so its day carries four kinds and no fixed rows.
  • inbox_activity_summary_vectors is a leaf with its own ACTIVITY_SUMMARY_VECTORS_SCHEMA_VERSION: keep it out of inbox_report_model_data's deps, and never select the summary text (content). It is the only durable copy of the activity summary vectors once the source TTL passes, so a re-run must keep the rows the source no longer returns (merge_activity_summary_vectors). Training reads a user's vector at a moment through activity_vector_as_of, never the newest vector of the user.
  • Register new jobs/schedules in posthog/dags/locations/signals.py (or signals_ml.py for a torch-dependent dag), 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 specifics

  • products/signals/backend/ranking/features.py holds a FeatureSet per feature universe (it lives in the backend so the scoring sweep owns it and the dag imports it). The embedding sets are also the serving contract: the sweep builds each model's matrix through the set's own build_matrix, and refuses a booster whose feature_names or feature_schema_version disagree with its set. A change to a set's features means bumping that set's schema_version, and the sweep must be able to compute it at scoring time — nothing impression-derived, nothing that needs the label streams.

  • A model declares its feature set in metadata.json and is checked against that set, not against one global contract. Adding a set means an entry in FEATURE_SETS. Do not reintroduce a module-global feature list into the training path: several sets live side by side.

  • A set that reads a side input declares it in extras_keys, and reports per-row availability through buildable. The example builder drops the rows buildable returns False for.

  • An embedding set is a ReportEmbeddingsFeatureSet parameterized by the extras key it reads, one rendering each. A set reads its own key only: never add a fallback to another rendering's vector. title_embeddings is retired (RETIRED_MODEL_NAMES), so nothing trains on the inbox_report_title_embeddings snapshot. A snapshot carries a vector per live report, so load one rendering at a time: a further embedding family must cost runtime rather than peak memory.

  • A missing side-input object leaves its key out, so only the sets reading it are skipped and their partitions stay as they are. An empty object keeps its key and takes the ordinary thin-input path. Do not collapse the two: the first must not write over a partition, and the second is a day the family really has nothing to fit.

  • Both buildable and build_matrix take the moment being built as as_of, and a side input that changes over a report's life must honor it. The report vector does: reports are re-embedded when their text changes, so the snapshot's latest vector often postdates the moment, and taking it would train on text that did not exist yet. Never widen a set's side input to the latest value for convenience.

  • example_grain and max_examples_per_head are per set, because the examples object is. Every set defaults to the birth grain so the families target the same scoring moment; side-input availability and row budgets can still change their training populations. report_embeddings is the reason the budget exists (1536 columns per row). A budget limits history and never samples inside a day: cap_examples keeps whole report-creation days, newest first, so the kept label rate stays the population rate and the scores stay calibrated. Never reintroduce a positive-keeping sample: it raises the base rate the model fits, and a holdout cut from the same sample hides it.

  • feature_vector (one row, serving) and feature_frame (vectorized, training) must agree row for row; a test pins it. Change both together.

  • Examples are one row per report, on the snapshot of the day it was created, labeled from the snapshot horizon_days later. The scoring-moment and report grains stay selectable for re-scoring families, so keep the holdout cut by report: a row-level split leaks near-duplicate snapshots of the same report the moment a set asks for one of them. The moments are chosen before the features are built, so a set under a row budget never builds columns for rows it then drops; keep that order.

  • inbox_ranking_models/v1/<model_name>/dt=D/ is history like the dataset partitions: the only mutation is a re-run of the same partition, which replaces the prefix in full (stale head files are deleted). inbox_ranking_models/v1/served.json is the only object written outside a partition, and only inbox_ranking_promote_job writes it, when a person runs it. No asset may write served.json or a <model_name>/champion.json: the champion assets record a decision and nothing else. The old champion.json files stay as the cross-family role's input.

  • The model is read in three layers: training (train metrics), test (the random-by-report holdout, which drives promotion) and online (inbox_ranking_served_scores, the scoring sweep's live scores of each day's newborns, graded by inbox_ranking_unseen_graded at each head's horizon). Do not add an offline rescoring of the newborn pool beside the online layer: the sweep already scores it with every model key the manifest names.

  • served_score_rows keeps the earliest scored event per (report, model key) and takes model_role from the event's roles. Grades stay per (model_name, model_version, model_role) and are never pooled across versions. A re-run that reads no event is refused when the partition already holds rows, and so is one that reads fewer families than the object holds, because the newborn state snapshot behind those rows ages out and the dt=D+horizon grade reads them.

  • Every scored row carries head_readable, and an unreadable head is still graded: a head that misses min_holdout_positives on one day's holdout still gets a number from the pooled online grade. Keep the promotion gate reading readable from the candidate metadata: an unreadable head must not decide a promotion.

  • model_name is the model recipe, and every model object, scored row, grade and event carries it. A family is an entry in MODEL_FAMILIES (training/families.py) naming the feature set it is fit on, its learner and the location that trains it; the signals_ml location trains every family (nn/dag.py), and the grader and the events need no change to gain a family. families_trained_in(MAIN_LOCATION) is empty: the main location fits no model. The per-head XGBoost families are retired (RETIRED_MODEL_NAMES), and the sweep keeps the xgboost handler so an old version stays servable by key for a rollback. A candidate is graded only against the served model of its own model_name; the served pointer itself can name any family. Do not fold the family into model_version, which the dashboard filters as a date.

  • A recipe change (features, heads, horizons, learner or training settings, DATASET_VERSION) needs a new model_name, such as nn_v3, because the promotion gate grades a candidate only against the served model of its own name. Every candidate writes recipe and recipe_hash (training/recipe.py), and the candidate asset fails before it writes when the hash differs from the newest hashed version of the name at or before its partition, a re-run of the same partition included. Keep anything that changes daily (dates, run_id, counts, metrics) out of the recipe, or every retrain fails. Do not add an override for the check: the fix is a new name.

  • A family whose metadata.json, examples object or side input is missing for a partition is logged and skipped, so one family does not cost every family's series. The champion asset raises only when no family has a candidate at all.

  • Skipping is not the same as rebuilding from nothing, and the difference is destructive. An empty examples object produces an empty candidate, and the candidate's prefix cleanup then deletes the boosters that partition already holds, which served.json or a pin can be pointing at. So when a side input is unavailable, leave the partition's objects alone rather than writing empty ones over them.

  • The champion is compared to a candidate on the candidate's holdout, through the champion's train-only fit (model.holdout.onnx). Keep writing that file: without it the gate falls back to the champion's stored AUC, which was measured on a different set of reports.

  • The example builder reads labels aligned to the state spine (assemble_snapshot): no label row means all-zero labels, not "absent". It drops rows whose features_observed_at is a backfill (STATE_LAG_LIMIT) and, for status-derived heads, rows that fail label_provenance_ok.

  • The serving path reads the deployment's own object store, never the dataset bucket: the Temporal workers have no credential for that bucket, and keeping it that way is why the manifest asset copies what the sweep needs. serving/models/<key>/ holds a version's metadata.json and its model files, serving/manifest.json names the models one pass scores. The holdout boosters grade a promotion and must stay behind.

  • An entry's files come from ServingManifestEntry.files: one <head>.ubj per head for xgboost, and the one model.onnx that model_file names for onnx. The copy step and the model store read that property, and the pin check reads the same names from each head's file in metadata.json, so a new model kind with another file layout keeps the two in step. Keep onnxruntime and xgboost imports inside the handlers' load: a test pins that importing the sweep loads neither.

  • The manifest schema and the object keys live in products/signals/backend/ranking/serving_manifest.py, next to the feature contract, because the dag writes them and the sweep reads them. Its validators run at write time, so the dag refuses a manifest the sweep could not act on; the entry cap is the ranking_score artefact's, so a manifest can never produce a row the artefact refuses.

  • The recent role keeps the newest INBOX_RANKING_SERVING_RECENT_VERSIONS versions of the served model_name, read from the last 2N partitions, so each version gets several days of online scores. The challenger role keeps the newest readable version of each other serving family (serving_families()), read from its last 2 partitions. Each one passes the pin check before composition, because one missing file fails the publish. Keep the order under the cap as served, recent, challenger, pinned, cross-family. Each recent entry is one more model per sweep pass, so measure the sweep's duration, peak RSS and scored and deferred counts on the inbox_ranking_sweep_finished log before and after a change to N.

  • Publishing order is load-bearing. Every model copy finishes before manifest.json is written, so a failed copy leaves the previous manifest and the previous models serving. A model version is immutable, so a version whose metadata.json is already at the target is not copied again. A run with nothing to publish, such as a run without served.json, writes nothing rather than an empty manifest. The served model passes the same check as a pin (_pin_metadata) before composition.

  • The manifest asset copies the dt=D inbox_user_vectors day to serving/user_vectors/<D>/ before manifest.json and names it in user_vectors. No model reads it yet, so a missing day or a failed copy only logs and leaves the key out; it never blocks a publish. Never copy user vectors to the mirror: the mirror's manifest always names none.

  • When a manifest entry has reads_project_vectors, the dt=D inbox_project_vectors day is copied to serving/project_vectors/<D>/ before manifest.json, and the manifest names it in project_vectors. A missing day fails the publish, like a missing model file. Never copy project vectors to the mirror, and never read the body of a mirror object: they are per-team data of the deployment that owns the teams. The mirror's manifest names the mirror region's own day only after _mirror_project_vectors checks its object metadata (PROJECT_VECTORS_*_METADATA_KEY in serving_manifest.py) within MIRROR_PROJECT_VECTORS_MAX_LAG_DAYS. Without such a day it names none, and a served model that reads them keeps the mirror on its previous manifest. _project_vectors_refusal takes the current project-vectors schema version and the one before it, so a mirror region that deploys later does not hold the mirror on an old manifest. Training and serving build the project and has_history inputs through the one project_inputs in features.py; keep PROJECT_VECTOR_KINDS and MIN_PROJECT_HISTORY_REPORTS there. Only a report-grain experiment can set its family's project_vector_kinds to other kinds from ALL_PROJECT_VECTOR_KINDS; the pair lane and user_offsets stay on PROJECT_VECTOR_KINDS. Serving loads every kind of the day and gives each model its own kinds in its own order. A model that reads a kind the day has no rows for is skipped with project_vector_kinds_missing, and a served model that hits it fails the pass like no_project_vectors; never feed it all-zero vectors instead.

  • HEADS holds only the heads the inbox reads (HeadRanker in backend/ranking/inbox_sort.py). Add a head there only together with a surface that reads it. The promotion gate skips a champion head that is not in HEADS, so a trim does not block promotion.

  • nn_v3 and nn_with_prio_v2 are trained by the signals_ml location (nn/dag.py), never by the main one. They share one inbox_ranking_nn_examples object, and each has its own candidate and champion asset from family_assets. The nn_v3 assets keep the names inbox_ranking_nn_model_{candidate,champion}, so their Dagster history continues. A later family's candidate depends on the previous family's champion, for memory and not for data: two candidates at once can exceed the job's memory limit. A family whose set reads a state column the examples object lacks skips with a warning rather than training on zeros. torch is imported only inside the candidate asset's body (through nn/train.py and multihead/network.py). signals_ml must import without torch, and test_multihead_network.py pins that. Its decision goes through decide_family_champion in training/dag.py, graded through the incumbent's model.holdout.onnx. Keep signals_ml commented out in .dagster_home/workspace.yaml, and keep its schedule (04:30 UTC) running by default on prod US only.

  • An experiment is a MODEL_FAMILIES entry with experiment=True, a baseline serving family and an expires day. Only inbox_ranking_nn_experiments_job (nn/experiments.py) trains it, with its own schedule and resource tags, so a modeling idea never adds to the nn job's runtime or memory budget. It reads the day's inbox_ranking_nn_examples object and never rebuilds it. An experiment never enters the serving manifest, and _pin_metadata refuses its key, so the promote job, the served pointer and the pins cannot name it. To serve its recipe, register it as a serving family under a new model_name. Its metadata.json carries a vs_baseline block: the experiment and the baseline fit with each of EXPERIMENT_SEEDS on the same train rows and graded on the same holdout rows. An A/A experiment (nn_with_prio_aa_v1) copies its baseline's recipe and sets seed_offset, so its arm fits on other seeds: on the baseline's own seeds the two arms are one fit and every delta is zero. An extra side input for an experiment goes through the registry in training/side_inputs.py, which refuses a frame without a timezone-aware as_of_column and drops rows known after the partition end. A feature set reads it through rows_as_of.

  • inbox_ranking_nn_pair_examples (nn/pairs.py) has one row per (report example, impressed user), with its own PAIR_EXAMPLES_SCHEMA_VERSION. Its own job has no schedule, and the experiments job builds it for the same partition before the pair experiments, only on a day with a live pair experiment. Keep the report experiments asset free of a dependency on it, so a failed pair step skips the pair experiments only. It takes its report rows and holdout from the open head's rows of the day's inbox_ranking_nn_examples object and never rebuilds them. Its impressions and labels come from the dt=B+PAIR_HORIZON_DAYS interactions partition, and its user inputs are as of the start of day B, so the target report is never in the user's history. The object holds no vector: a reader rebuilds the user vectors with pair_user_vectors. user_vectors() lives next to project_vectors() and shares known_before and _usable_embeddings with it; never give it its own as-of rule or embedding gate.

  • A pair-grain family (grain="pair") is always an experiment, trained by nn/pair_lane.py in the experiments job. Its baseline is another pair experiment and its reference a report-grain serving family. family_problems checks both at import. Keep the report-grain vs_baseline block, its events and the report families' recipe free of pair fields: an added recipe key changes every serving family's hash, and check_recipe then fails each retrain. Fit the reference on report train rows only, so no holdout pair's report trains it.

  • A pair set (PairUserHistoryFeatureSet) is the user-history contract of a pair family. Its set with user_history off is the pair baseline: the same width, the same reviewer flag, and zero in every user column and user offset whatever the pair rows hold. Build each arm's inputs from the pair rows for that arm's set, never from another arm's inputs. The report part may be built once per report, but the user columns and offsets are per pair, so one user's history never reaches another user's pair of the same report. A pair set stays out of FEATURE_SETS, because the state loader reads every registered set's columns and the state snapshot has no pair columns.

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. The exception is inbox_signal_embeddings, an emission log whose partition holds only that day's inserts — see the README's signal-grain section before touching it. Its re-run must stay additive (union with the existing object): the source drops rows it already archived, so a plain overwrite destroys history that exists nowhere else. inbox_activity_summary_vectors is the same kind of log (dt=D holds the vectors generated during D), and its re-run keeps every row the source no longer returns.
  • 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).
  • Every cumulative outcome count ships with the column holding the moment its first counted event arrived, declared as a pair in OUTCOME_FIRST_EVENT_COLUMNS (a test fails on an unpaired count). A count alone dates an outcome only to the whole cumulative window, so a horizon label or a time-to-outcome read has nothing but a proxy without that moment. The timestamp must use the same predicate as its count, or the pair describes different events.
  • Every STATUS_SQL aggregate reads only the latest transition's tenant (event_team_id = latest_event_team_id). report_id and team_id come from event properties, so the tenant an event names is claimed and not proven. An unscoped aggregate lets an event that names another team set a label, and label_provenance_ok checks only the latest transition. A forged-event invariance test over STATUS_COLUMNS fails on an unscoped aggregate.
  • 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.