: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.
Dataset
What the prediction problem actually is: who is in the population, what counts as a positive example, and whether the question is answerable at all.
Nothing here trains or scores anything. It is the shared vocabulary that ../training/ and ../inference/ both compile against — which is the whole point. If the trainer and the scorer disagreed about what a row means, the resulting model would be quietly wrong rather than loudly broken.
What lives here
labeling.pyThe single source of truth for "what does a training example look like?", and the most load-bearing module in the product.A training example is a
(person, T0, label)triple: pick an anchor timeT0for a person, thenlabel = 1if the target event fires in[T0, T0 + horizon_days).T0is a deterministic hash ofperson_id, placed at a fixed fraction of the user's[first_ts, cutoff_ts)span, so it is stable across runs and spread across the full lookback rather than clustered at the most-recent feasible point — one row per person, sampled once in their history. Ahash % spanremainder would move every timecutoff_tsmoved withnow().T0is always a UTC midnight, because every scoring run cuts off at the start of the prediction date in UTC (ScoringWindowin../inference/scoring.py). The labeler snaps the anchor (anchor_ts, ornow()) to the UTC midnight at or before it, socutoff_ts(the anchor minus the horizon) is a midnight. The hash picks one of the midnights from the first one afterfirst_tsup tocutoff_ts, so every T0 has at least one event before it. A T0 at any second would give the features part-day activity and a cutoff hour that scoring never has, and inflate the holdout score.build_eligible_count_sql()uses the same snapped cutoff. Models trained this way carryanchor_alignment: "utc_day"(ANCHOR_ALIGNMENT) in their metrics. For an event-defined population (performed_event_within_dayswith an event,ever_performed_event,ever_performed_target),first_tsis the user's first population event, not their first event of any kind. The other populations still start the span at the first event of any kind.Three call sites share this module so they cannot drift: the wizard's live estimate (sampled), the trainer (full materialization with fold split), and inference (cutoff = the start of the prediction date in UTC). That is why the training-side
labeled_anchorsCTE (insidebuild_training_features_sql()) andbuild_inference_anchors_sql()live here rather than next to their callers.Training anchors are case-control sampled above the budget.
TrainingSample.plan()keeps every anchor when the labeled population fitsTRAINING_SAMPLE_BUDGET(MATERIALIZE_ROW_LIMITtimesTRAINING_SAMPLE_HEADROOM), and the SQL is then the unsampled SQL. Above it, the plan keeps every positive and sets the negative sample raterso the expected sample fills the budget. Positives that alone exceed the budget raiseTrainingSampleTooLarge. A negative is kept when its salted hash,cityHash64(concat('sample:', person_id)), falls underr. The draw is per person, so it is stable across runs and independent of the T0 and fold hashes.build_training_features_sql()andbuild_random_t0_labeler_sql()take the samenegative_sample_rate, so the trainer's rows and the anchor count describe one sample. Holdout AUC does not change under negative sampling; probabilities do, so scoring applies the prior correction (see../inference/AGENTS.md). Only training samples. Inference aboveMATERIALIZE_ROW_LIMITscores a rolling subset instead (below).build_inference_anchors_sql()takes an optionalRollingSelection(fromrolling_selection()) for a scoring population at or above the cap. It keepslimitanchors: first the people the pipeline never scored, then the oldest last score, then the most recent member event, then a person hash. The last score is the latest liveautoresearch_predictionevent of the pipeline before the cutoff, withinscored_lookback_days. That window is twice the rotation length in days (runs timescadence_days), and at leastROLLING_SCORE_MIN_LOOKBACK_DAYS, so a person scored at the start of a rotation never ranks with the never-scored. A backfill event is person-less, so it does not count. Every key reads events before the cutoff, so a retry of the same prediction date selects the same people.Also here:
_compile_population_filters()(property filters → HogQL; a cohort filter, an unknown operator, or a filter without atyperaises rather than being skipped),_build_population_kind_conditions()(semantic population kinds → HogQL, see below),build_target_condition()(event or action target → predicate),NUM_FOLDS = 5with fold 0 as holdout, andIDENTIFIED_USERS_ONLY.validation.pyPre-flight viability.validate_pipeline_definition()answers "is there enough here to learn anything?" before a run is launched —MIN_TRAINING_ROWS(100),MIN_POSITIVE_EXAMPLESandMIN_NEGATIVE_EXAMPLES(20 each, because holdout AUC is undefined with one class),MIN_IDENTIFIED_FRACTION(0.5). The window validated is the configuredtraining_lookback_days, unclamped, so the estimate describes the data training will see. Returns aValidationResultcarryingValidationWarnings rather than raising, because the API surfaces them as advice.population_too_largeis severityinfowhen training will sample the population or scoring rolls through a population at or aboveMATERIALIZE_ROW_LIMIT, anderrorwhen the positives alone exceed the training budget.low_positives,low_negativesandhorizon_exceeds_lookbackstay errors.templates.pyBuilt-in starting points. A template resolves to the same pipeline config shape as a fully custom pipeline, so creation and validation behave identically either way — there is no separate template code path downstream. Population specs use a semantic format (performed_event_within_days,person_first_seen_within_days,active_not_performed_target,ever_performed_event,ever_performed_target) that is compiled to HogQL bylabeling.py. The target-relative kinds compile against the pipeline's target predicate, so an action target is matched by its matcher and not by its display name.resolve_activity_event()picks the team's real activity event, preferring$pageview→$screen→$autocapture, because "active user" means different things on web and mobile.
Mental model
A pipeline definition is declarative. This package is what turns it into SQL.
pipeline (target, population, horizon, lookback)
│
├─ build_training_features_sql → labeled_anchors CTE: one T0 per person, hashed to a UTC midnight,
│ └─ + labels + fold spread over lookback — the trainer's labeled population
│
└─ build_inference_anchors_sql → cutoff = UTC day start, no labels, no folds
└─ the scorer's population
The two branches differ only in cutoff and whether labels and folds are attached. Everything else — population filters, identified-user restriction, target predicate — is shared code, deliberately.
Things that bite
IDENTIFIED_USERS_ONLYis on. Autoresearch trains on identified users only, so raw event counts badly overstate available training data on anonymous-heavy datasets. A target with thousands of events can yield a few dozen usable rows.- Validation is advisory, not enforcing.
autoresearch_traindoes not call it. A target that fails on volume will still train — deliberately, so thin local datasets are workable, but it means "the run completed" does not mean "the data was sufficient." - Random
T0is a modeling decision, not an implementation detail. Spreading anchors across the lookback keeps the model from over-fitting to one moment in calendar time. Changing it to most-recent-feasible would change what every model in the product means. - Everything keys on
person_id. See../inference/AGENTS.mdfor what goes wrong when a caller keys ondistinct_idinstead — it fails silently. - Never read
person.*off an events scan here. It joins the team's whole persons table into the scan, and on a high-volume project the query times out before it starts. Identity and person-property filters go through_person_rows_sql(), which readsraw_personspruned to the member ids. - Scan the population's own event where one exists.
person_idis not in the events sort key, so aperson_id IN (...)membership filter does not narrow an any-event scan. A kind setsmember_predicateso the member scans filter onevent, which the sort key prunes. An event-property filter keeps the any-event scan, because it can match any event.
Where the rest of the system meets this package
- Trainer —
../training/materializes the labeled population frombuild_training_features_sql(). - Scorer —
../inference/materializes the unlabeled population frombuild_inference_features_sql(). - API —
../presentation/views/views.pycallsvalidate_pipeline_definition()for the pre-create check andresolve_template()for template-backed creation;resolve_target()lives in../presentation/views/serializers.pyand pairs withbuild_target_condition(). - Command —
autoresearch_validateis the headless entry tovalidation.py. - Agent-authored SQL — the agent's
feature_sqlis spliced against these anchors via_substitute_anchors(). The{anchors}placeholder is part of the agent's contract, so it is documented in the brief in../training/runner.py. Substitution is quote-aware: comments are stripped, a{anchors}inside a string literal is kept as a value, and a trailing;is dropped so the SQL can be nested.
When editing this flow
- Any change to what a row means goes here and only here. If you add a cutoff rule, a population kind, or a label variant next to a caller instead, the trainer and scorer will drift and the failure will be silent.
- Keep the training-side
labeled_anchorsCTE andbuild_inference_anchors_sql()symmetrical. They should differ in cutoff, labels, and folds — nothing else. - Every activity scan here excludes the product's own
autoresearch_predictionevent (_own_events_excluded_clause()). A live cadence writes one per scored person, so counting it would keep a person eligible forever on nothing but their own predictions. Add the clause to any new events scan. - New population kinds need the semantic spec in
templates.py, a compiler function registered in_POPULATION_KIND_COMPILERSinlabeling.py(handling both row mode and anchor mode), and the required-key rules in thePopulationDefinitionFieldvalidator in../presentation/views/serializers.py.POPULATION_KINDSis derived from that registry, so a kind cannot exist without a compiler; the write-time validator rejects an unregistered kind at creation. A target-relative kind also has to joinTARGET_RELATIVE_KINDS, which is still a hand-written list — otherwise_target_condition_forresolves no target and the compiler raises at query time. - Every population kind and every event-property filter is evaluated per user at T0 during training (the
HAVINGclause of the labeled CTE) and as of the cutoff at inference; only person-property filters apply up front, throughraw_persons. Deciding training membership as ofnow()would admit users on activity after T0, including the outcome window, and excluding "ever performed the target" users with a plain row filter would delete exactly the users whose post-T0 adoption provides the positive labels. - Fold 0 is the holdout everywhere. If you change
NUM_FOLDSor the holdout fold, every recordedholdout_scorein the database becomes incomparable to new ones. - If you change the anchor, label, or population contract, update this file to match.