: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.
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 fromcommon.py— don't growdataset/sideways and don't duplicate the S3/partition helpers. inbox_report_title_embeddingsis a leaf: never add it toinbox_report_model_data'sdepsor give that join a title column, or a failure in the title snapshot fails the training table. Its owndeps=[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 carriesMEMORY_HEAVY_OP_TAGand the dataset job's executor runs it alone among the heavy steps, and it reportspeak_rss_metadata(). Use the tag, not adepsedge, to keep heavy steps apart.report_embeddings_tablereads its rows inREPORT_EMBEDDINGS_PAGEShash-bucket pages and holds only one page as Python objects. Never read the fleet's vectors in onesync_execute. inbox_user_report_interactionsis a leaf with its ownUSER_INTERACTIONS_SCHEMA_VERSION: keep it out ofinbox_report_model_data'sdeps, and never stamp it withFEATURE_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 intraining_consent_team_ids().inbox_project_vectorsis a leaf with its ownPROJECT_VECTORS_SCHEMA_VERSION: keep it out ofinbox_report_model_data'sdeps. Itsdeps=[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_vectorstakes a report into a vector only when its vector landed and its engagement moment (a UI event, orfirst_fixed_atforfixed) happened strictly beforeas_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 ofALL_PROJECT_VECTOR_KINDSfromCONTEXT_LABEL_COLUMNS.LABEL_COLUMNSholds the UI engagement columns only, withoutfirst_fixed_at.inbox_user_vectorsis a leaf with its ownUSER_VECTORS_SCHEMA_VERSION: keep it out ofinbox_report_model_data'sdeps. Itsdeps=[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 throughuser_vectors()with the same consent re-filter andteam_organizationsmapping as the pair lane, so its dt=D rows equal whatpair_user_vectorsrebuilds for a report born on D+1; a test pins that parity.user_hashcovers each kind's name,n_reportsand vector only, so a day that adds no report keeps a user's hash.inbox_engagement_exportis a leaf with its ownENGAGEMENT_EXPORT_SCHEMA_VERSION, read by another region. It writes to the mirror store only underserving_engagement_key, because the mirror's write grant covers only<prefix>/serving/. Keep its columns exactlyENGAGEMENT_EXPORT_COLUMNS(report ids and engagement timestamps) and its rows limited to reports with noSignalReportin 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 belowENGAGEMENT_EXPORT_MIN_LOCAL_SHARE(local_share_collapsed), the asset writes nothing and still succeeds. Itsinbox_ranking_engagement_export_publishedevent 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 throughreport_embeddings_tableand the engagement export throughserving_engagement_key, and writes only to this region's object store atserving_project_vectors_key. Keep it on the sameproject_vectors()and the same consent rule asinbox_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 nofirst_fixed_at, so its day carries four kinds and nofixedrows.inbox_activity_summary_vectorsis a leaf with its ownACTIVITY_SUMMARY_VECTORS_SCHEMA_VERSION: keep it out ofinbox_report_model_data'sdeps, 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 throughactivity_vector_as_of, never the newest vector of the user.- Register new jobs/schedules in
posthog/dags/locations/signals.py(orsignals_ml.pyfor 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.pyholds aFeatureSetper 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 ownbuild_matrix, and refuses a booster whosefeature_namesorfeature_schema_versiondisagree with its set. A change to a set's features means bumping that set'sschema_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.jsonand is checked against that set, not against one global contract. Adding a set means an entry inFEATURE_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 throughbuildable. The example builder drops the rowsbuildablereturns False for.An embedding set is a
ReportEmbeddingsFeatureSetparameterized by theextraskey it reads, one rendering each. A set reads its own key only: never add a fallback to another rendering's vector.title_embeddingsis retired (RETIRED_MODEL_NAMES), so nothing trains on theinbox_report_title_embeddingssnapshot. 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
buildableandbuild_matrixtake the moment being built asas_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_grainandmax_examples_per_headare 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_embeddingsis the reason the budget exists (1536 columns per row). A budget limits history and never samples inside a day:cap_exampleskeeps 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) andfeature_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_dayslater. 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.jsonis the only object written outside a partition, and onlyinbox_ranking_promote_jobwrites it, when a person runs it. No asset may writeserved.jsonor a<model_name>/champion.json: the champion assets record a decision and nothing else. The oldchampion.jsonfiles 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 byinbox_ranking_unseen_gradedat 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_rowskeeps the earliest scored event per (report, model key) and takesmodel_rolefrom 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 missesmin_holdout_positiveson one day's holdout still gets a number from the pooled online grade. Keep the promotion gate readingreadablefrom the candidate metadata: an unreadable head must not decide a promotion.model_nameis the model recipe, and every model object, scored row, grade and event carries it. A family is an entry inMODEL_FAMILIES(training/families.py) naming the feature set it is fit on, itslearnerand thelocationthat trains it; thesignals_mllocation 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 thexgboosthandler so an old version stays servable by key for a rollback. A candidate is graded only against the served model of its ownmodel_name; the served pointer itself can name any family. Do not fold the family intomodel_version, which the dashboard filters as a date.A recipe change (features, heads, horizons, learner or training settings,
DATASET_VERSION) needs a newmodel_name, such asnn_v3, because the promotion gate grades a candidate only against the served model of its own name. Every candidate writesrecipeandrecipe_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.jsonor 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 whosefeatures_observed_atis a backfill (STATE_LAG_LIMIT) and, for status-derived heads, rows that faillabel_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'smetadata.jsonand its model files,serving/manifest.jsonnames 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>.ubjper head forxgboost, and the onemodel.onnxthatmodel_filenames foronnx. The copy step and the model store read that property, and the pin check reads the same names from each head'sfileinmetadata.json, so a new model kind with another file layout keeps the two in step. Keeponnxruntimeandxgboostimports 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 theranking_scoreartefact's, so a manifest can never produce a row the artefact refuses.The
recentrole keeps the newestINBOX_RANKING_SERVING_RECENT_VERSIONSversions of the servedmodel_name, read from the last 2N partitions, so each version gets several days of online scores. Thechallengerrole 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 theinbox_ranking_sweep_finishedlog before and after a change to N.Publishing order is load-bearing. Every model copy finishes before
manifest.jsonis written, so a failed copy leaves the previous manifest and the previous models serving. A model version is immutable, so a version whosemetadata.jsonis already at the target is not copied again. A run with nothing to publish, such as a run withoutserved.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_vectorsday toserving/user_vectors/<D>/beforemanifest.jsonand names it inuser_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=Dinbox_project_vectorsday is copied toserving/project_vectors/<D>/beforemanifest.json, and the manifest names it inproject_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_vectorschecks its object metadata (PROJECT_VECTORS_*_METADATA_KEYinserving_manifest.py) withinMIRROR_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_refusaltakes 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 theprojectandhas_historyinputs through the oneproject_inputsinfeatures.py; keepPROJECT_VECTOR_KINDSandMIN_PROJECT_HISTORY_REPORTSthere. Only a report-grain experiment can set its family'sproject_vector_kindsto other kinds fromALL_PROJECT_VECTOR_KINDS; the pair lane anduser_offsetsstay onPROJECT_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 withproject_vector_kinds_missing, and a served model that hits it fails the pass likeno_project_vectors; never feed it all-zero vectors instead.HEADSholds only the heads the inbox reads (HeadRankerinbackend/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 inHEADS, so a trim does not block promotion.nn_v3andnn_with_prio_v2are trained by thesignals_mllocation (nn/dag.py), never by the main one. They share oneinbox_ranking_nn_examplesobject, and each has its own candidate and champion asset fromfamily_assets. Thenn_v3assets keep the namesinbox_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 (throughnn/train.pyandmultihead/network.py).signals_mlmust import without torch, andtest_multihead_network.pypins that. Its decision goes throughdecide_family_championintraining/dag.py, graded through the incumbent'smodel.holdout.onnx. Keepsignals_mlcommented 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_FAMILIESentry withexperiment=True, abaselineserving family and anexpiresday. Onlyinbox_ranking_nn_experiments_job(nn/experiments.py) trains it, with its own schedule and resource tags, so a modeling idea never adds to thennjob's runtime or memory budget. It reads the day'sinbox_ranking_nn_examplesobject and never rebuilds it. An experiment never enters the serving manifest, and_pin_metadatarefuses 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 newmodel_name. Itsmetadata.jsoncarries avs_baselineblock: the experiment and the baseline fit with each ofEXPERIMENT_SEEDSon 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 setsseed_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 intraining/side_inputs.py, which refuses a frame without a timezone-awareas_of_columnand drops rows known after the partition end. A feature set reads it throughrows_as_of.inbox_ranking_nn_pair_examples(nn/pairs.py) has one row per (report example, impressed user), with its ownPAIR_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 theopenhead's rows of the day'sinbox_ranking_nn_examplesobject and never rebuilds them. Its impressions and labels come from the dt=B+PAIR_HORIZON_DAYSinteractions 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 withpair_user_vectors.user_vectors()lives next toproject_vectors()and sharesknown_beforeand_usable_embeddingswith it; never give it its own as-of rule or embedding gate.A pair-grain family (
grain="pair") is always an experiment, trained bynn/pair_lane.pyin the experiments job. Its baseline is another pair experiment and itsreferencea report-grain serving family.family_problemschecks both at import. Keep the report-grainvs_baselineblock, its events and the report families' recipe free of pair fields: an added recipe key changes every serving family's hash, andcheck_recipethen 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 withuser_historyoff 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 ofFEATURE_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 isinbox_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_vectorsis 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 savedinbox_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_SQLaggregate reads only the latest transition's tenant (event_team_id = latest_event_team_id).report_idandteam_idcome 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, andlabel_provenance_okchecks only the latest transition. A forged-event invariance test overSTATUS_COLUMNSfails 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 thev1path segment. The parquet schemas and the row assemblers must stay in exact key agreement —pa.Table.from_pylistsilently 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.