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.

11.8 KB
Raw Blame

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.py The 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 time T0 for a person, then label = 1 if the target event fires in [T0, T0 + horizon_days). T0 is a deterministic hash of person_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. A hash % span remainder would move every time cutoff_ts moved with now(). T0 is always a UTC midnight, because every scoring run cuts off at the start of the prediction date in UTC (ScoringWindow in ../inference/scoring.py). The labeler snaps the anchor (anchor_ts, or now()) to the UTC midnight at or before it, so cutoff_ts (the anchor minus the horizon) is a midnight. The hash picks one of the midnights from the first one after first_ts up to cutoff_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 carry anchor_alignment: "utc_day" (ANCHOR_ALIGNMENT) in their metrics. For an event-defined population (performed_event_within_days with an event, ever_performed_event, ever_performed_target), first_ts is 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_anchors CTE (inside build_training_features_sql()) and build_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 fits TRAINING_SAMPLE_BUDGET (MATERIALIZE_ROW_LIMIT times TRAINING_SAMPLE_HEADROOM), and the SQL is then the unsampled SQL. Above it, the plan keeps every positive and sets the negative sample rate r so the expected sample fills the budget. Positives that alone exceed the budget raise TrainingSampleTooLarge. A negative is kept when its salted hash, cityHash64(concat('sample:', person_id)), falls under r. The draw is per person, so it is stable across runs and independent of the T0 and fold hashes. build_training_features_sql() and build_random_t0_labeler_sql() take the same negative_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 above MATERIALIZE_ROW_LIMIT scores a rolling subset instead (below).

    build_inference_anchors_sql() takes an optional RollingSelection (from rolling_selection()) for a scoring population at or above the cap. It keeps limit anchors: 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 live autoresearch_prediction event of the pipeline before the cutoff, within scored_lookback_days. That window is twice the rotation length in days (runs times cadence_days), and at least ROLLING_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 a type raises rather than being skipped), _build_population_kind_conditions() (semantic population kinds → HogQL, see below), build_target_condition() (event or action target → predicate), NUM_FOLDS = 5 with fold 0 as holdout, and IDENTIFIED_USERS_ONLY.

  • validation.py Pre-flight viability. validate_pipeline_definition() answers "is there enough here to learn anything?" before a run is launched — MIN_TRAINING_ROWS (100), MIN_POSITIVE_EXAMPLES and MIN_NEGATIVE_EXAMPLES (20 each, because holdout AUC is undefined with one class), MIN_IDENTIFIED_FRACTION (0.5). The window validated is the configured training_lookback_days, unclamped, so the estimate describes the data training will see. Returns a ValidationResult carrying ValidationWarnings rather than raising, because the API surfaces them as advice. population_too_large is severity info when training will sample the population or scoring rolls through a population at or above MATERIALIZE_ROW_LIMIT, and error when the positives alone exceed the training budget. low_positives, low_negatives and horizon_exceeds_lookback stay errors.

  • templates.py Built-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 by labeling.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_ONLY is 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_train does 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 T0 is 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.md for what goes wrong when a caller keys on distinct_id instead — 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 reads raw_persons pruned to the member ids.
  • Scan the population's own event where one exists. person_id is not in the events sort key, so a person_id IN (...) membership filter does not narrow an any-event scan. A kind sets member_predicate so the member scans filter on event, 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 from build_training_features_sql().
  • Scorer — ../inference/ materializes the unlabeled population from build_inference_features_sql().
  • API — ../presentation/views/views.py calls validate_pipeline_definition() for the pre-create check and resolve_template() for template-backed creation; resolve_target() lives in ../presentation/views/serializers.py and pairs with build_target_condition().
  • Command — autoresearch_validate is the headless entry to validation.py.
  • Agent-authored SQL — the agent's feature_sql is 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_anchors CTE and build_inference_anchors_sql() symmetrical. They should differ in cutoff, labels, and folds — nothing else.
  • Every activity scan here excludes the product's own autoresearch_prediction event (_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_COMPILERS in labeling.py (handling both row mode and anchor mode), and the required-key rules in the PopulationDefinitionField validator in ../presentation/views/serializers.py. POPULATION_KINDS is 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 join TARGET_RELATIVE_KINDS, which is still a hand-written list — otherwise _target_condition_for resolves 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 HAVING clause of the labeled CTE) and as of the cutoff at inference; only person-property filters apply up front, through raw_persons. Deciding training membership as of now() 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_FOLDS or the holdout fold, every recorded holdout_score in the database becomes incomparable to new ones.
  • If you change the anchor, label, or population contract, update this file to match.