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.

17.3 KB
Raw Blame
"""
Contract types for autoresearch.

Stable, framework-free frozen dataclasses that define what this product exposes to
the rest of the codebase, and what its own presentation layer serializes. No Django
imports.

These use ``pydantic.dataclasses.dataclass`` rather than the stdlib variant — same
syntax and ``is_dataclass()`` compatibility, but with runtime validation on
construction, so structural mistakes from mappers surface at the facade boundary
instead of producing a malformed payload deeper in a caller.

Some contracts use the stdlib variant instead. A contract a ``DataclassSerializer``
constructs from a partial request body needs defaults on every field and no runtime
validation of the half-built value, which pydantic would reject.
"""

from dataclasses import (
    dataclass as stdlib_dataclass,
    field,
)
from datetime import date, datetime
from typing import Any
from uuid import UUID

from pydantic.dataclasses import dataclass


class PipelineNotFound(LookupError):
    """No pipeline with that id in this team."""


class TrainingRunNotFound(LookupError):
    """No training run with that id in this team."""


class SuggestionNotFound(LookupError):
    """No suggestion with that id on this pipeline."""


class AutoresearchConflict(ValueError):
    """The request is well-formed but the pipeline or run is in the wrong state for it.

    The viewset maps it to a 400 with the message as-is, so the message is user-facing copy.
    """


class TrainingRunCapReached(Exception):
    """The project has started its limit of sandbox training runs in the last 24 hours.

    The viewset maps it to a 429, so the message is user-facing copy.
    """

    def __init__(self, *, used: int, limit: int, next_slot_at: datetime | None) -> None:
        self.used = used
        self.limit = limit
        self.next_slot_at = next_slot_at
        if limit == 0 or next_slot_at is None:
            message = "Training runs are turned off for this project. Contact support to turn them on."
        else:
            message = (
                f"This project started {used} training runs in the last 24 hours, and its limit is {limit}. "
                f"The next run can start after {next_slot_at:%H:%M} UTC."
            )
        super().__init__(message)


class LivePipelineCapReached(AutoresearchConflict):
    """The project already has its limit of live pipelines, so another cannot go live.

    An ``AutoresearchConflict``, so the viewsets map it to a 400 with the message as-is, and the
    message is user-facing copy.
    """

    def __init__(self, *, used: int, limit: int) -> None:
        self.used = used
        self.limit = limit
        if limit == 0:
            message = "Active models are turned off for this project. Contact support to turn them on."
        else:
            message = (
                f"This project has reached its limit of {limit} active models. Pause or delete one to start another."
            )
        super().__init__(message)


class InvalidTarget(ValueError):
    """The target names something the labeler cannot honor.

    The serializer maps it to a validation error on ``target_definition``, so the message is
    user-facing copy.
    """


class ArtifactNotFound(LookupError):
    """No artifact at that path in the run's bundle."""


class InvalidArtifactPath(ValueError):
    """The artifact path escapes the bundle prefix or is otherwise unusable."""


class ArtifactStorageUnavailable(RuntimeError):
    """Object storage refused or failed the artifact write, so nothing was stored.

    The viewset maps it to a 503 with the message as-is, so the message is user-facing copy.
    """


# ── Model-backed read contracts ────────────────────────────────────────────


@dataclass(frozen=True)
class TrainingTrendPoint:
    iteration_number: int
    best_holdout_score: float


@dataclass(frozen=True)
class LiveTrainingRun:
    """Progress of the pipeline's pending or running training run, read from its live iteration rows."""

    id: UUID
    iteration_budget: int
    experiment_count: int
    best_holdout_score: float | None
    latest_agent_description: str
    latest_summary: str | None
    trend: list[TrainingTrendPoint]


@dataclass(frozen=True)
class PredictionCoverage:
    """How much of the inference population had a champion score when a live run scored, and how old the scores were."""

    population: int
    with_score: int
    never_scored: int
    age_days_avg: float | None
    age_days_p50: float | None
    age_days_p90: float | None
    age_days_max: float | None
    lookback_days: int


@dataclass(frozen=True)
class RealizedAucPoint:
    prediction_date: date
    realized_auc: float


@dataclass(frozen=True, config={"arbitrary_types_allowed": True})
class Pipeline:
    """One prediction pipeline: a target, a population, and a horizon.

    ``created_by`` carries the core ``User`` row rather than a projection of it, so the
    presentation layer keeps serializing it through core's ``UserBasicSerializer`` and the
    generated ``UserBasic`` component stays as it was.
    """

    id: UUID
    name: str
    description: str
    target_event: str
    target_definition: dict[str, Any]
    horizon_days: int
    training_lookback_days: int
    training_population: dict[str, Any]
    inference_population: dict[str, Any]
    cadence_days: int
    iteration_budget: int
    iteration_budget_remaining: int
    iterations_per_run: int
    research_interval_days: int | None
    agent_model: str | None
    agent_reasoning_effort: str | None
    effective_agent_model: str
    effective_agent_reasoning_effort: str | None
    training_phase: str
    next_research_at: datetime | None
    not_promoted_reason: str | None
    success_auc: float | None
    plateau_iterations: int
    output_person_property: str
    write_person_property: bool
    status: str
    created_by: Any
    created_at: datetime
    updated_at: datetime
    last_scored_at: datetime | None
    champion_holdout_auc: float | None
    champion_realized_auc: float | None
    champion_lift_at_10: float | None
    champion_is_preliminary: bool | None
    champion_realized_auc_trend: list[RealizedAucPoint]
    champion_training_trend: list[TrainingTrendPoint]
    people_scored: int | None
    likely_count: int | None
    likely_threshold: float | None
    first_check_expected_at: datetime | None
    coverage: PredictionCoverage | None
    training_run_count: int
    experiment_count: int
    live_training_run: LiveTrainingRun | None


@dataclass(frozen=True)
class Model:
    """A persisted, versioned champion or challenger recipe."""

    id: UUID
    pipeline: UUID
    role: str
    recipe_hash: str
    model_recipe: dict[str, Any]
    model_explanation: dict[str, Any]
    holdout_score: float | None
    realized_score: float | None
    calibration_error: float | None
    metrics: dict[str, Any]
    source_training_run: UUID | None
    agent_description: str
    trained_on_start: date | None
    trained_on_end: date | None
    is_preliminary: bool
    promoted_at: datetime | None
    archived_at: datetime | None
    created_at: datetime
    updated_at: datetime
    in_shadow_set: bool


@dataclass(frozen=True)
class IterationTrailEntry:
    """Compact view of one iteration, for the history feed and the Training tab."""

    iteration_number: int
    status: str
    holdout_score: float | None
    train_score: float | None
    agent_description: str
    summary: str | None
    headline: str | None
    model_spec: dict[str, Any]
    recipe_snapshot: dict[str, Any]


@dataclass(frozen=True)
class TrainingRunSummaryLadderItem:
    iteration_number: int
    holdout_score: float | None
    model_class: str
    agent_description: str


@dataclass(frozen=True)
class TrainingRunSummary:
    """Tier-1 distilled summary of a completed run — what a new run reads first."""

    target_event: str
    horizon_days: int
    best_holdout_score: float | None
    champion_promoted: bool
    champion_model_class: str
    kept_ladder: list[TrainingRunSummaryLadderItem]
    dead_ends: list[TrainingRunSummaryLadderItem]
    recommended_next: str
    distillation: str
    report_notebook_short_id: str


@dataclass(frozen=True)
class TrainingRun:
    """One bounded training session backed by a Task/TaskRun sandbox."""

    id: UUID
    pipeline: UUID
    task_id: UUID | None
    task_run_id: UUID | None
    task_url: str | None
    status: str
    kickoff_reason: str | None
    agent_runtime_adapter: str | None
    agent_model: str | None
    agent_model_label: str | None
    agent_reasoning_effort: str | None
    iteration_budget: int
    iteration_count: int
    best_holdout_score: float | None
    summary: dict[str, Any] | None
    reader_summary: str | None
    headline: str | None
    next_steps: list[str] | None
    iterations: list[IterationTrailEntry]
    error: str
    started_at: datetime | None
    completed_at: datetime | None
    created_at: datetime


@dataclass(frozen=True)
class Iteration:
    """One recipe attempt within a training run."""

    id: UUID
    pipeline: UUID
    training_run: UUID
    iteration_number: int
    recipe_hash: str
    recipe_snapshot: dict[str, Any]
    model_spec: dict[str, Any]
    train_score: float | None
    holdout_score: float | None
    status: str
    agent_description: str
    summary: str | None
    headline: str | None
    agent_confidence: float | None
    parent_suggestion: UUID | None
    created_at: datetime


@dataclass(frozen=True, config={"arbitrary_types_allowed": True})
class Suggestion:
    """A free-text hypothesis injected into a running pipeline by a user or agent."""

    id: UUID
    pipeline: UUID
    prompt: str
    priority: str
    status: str
    source: str
    agent_response: str
    created_by: Any
    linked_iteration_ids: list[UUID]
    created_at: datetime
    updated_at: datetime


@dataclass(frozen=True)
class Run:
    """Generic operational run: inference or validation."""

    id: UUID
    pipeline: UUID
    model: UUID | None
    run_type: str
    status: str
    rows_scored: int | None
    metrics: dict[str, Any]
    coverage: PredictionCoverage | None
    error: str
    started_at: datetime | None
    completed_at: datetime | None
    created_at: datetime


@dataclass(frozen=True)
class AgentReasoningEffortOption:
    value: str
    label: str


@dataclass(frozen=True)
class AgentModelOption:
    model: str
    label: str
    runtime_adapter: str
    supported_efforts: list[AgentReasoningEffortOption]
    cost_multiplier: str | None


@dataclass(frozen=True)
class AgentModelOptions:
    """The models a pipeline's training agent may run on, and what a blank setting resolves to."""

    default_model: str
    default_model_label: str
    default_reasoning_effort: str | None
    models: list[AgentModelOption]


@dataclass(frozen=True)
class ProjectLimits:
    """The project's autoresearch limits, and how much of each it is using now."""

    max_training_runs_per_day: int
    training_runs_used: int
    # When the next training run can start, while the project is at its daily limit.
    next_slot_at: datetime | None
    max_iterations_per_run: int
    max_live_pipelines: int
    live_pipelines: int


# ── Write contracts ────────────────────────────────────────────────────────


@stdlib_dataclass(frozen=True)
class PipelineWrite:
    """A create or update body for a pipeline.

    Stdlib dataclass with a default on every field, so the wrapping ``DataclassSerializer``
    can build it from a partial (PATCH) body. Which fields are actually applied is decided
    by the raw request keys, not by these defaults.
    """

    name: str = ""
    description: str = ""
    target_event: str = ""
    target_definition: dict[str, Any] = field(default_factory=dict)
    horizon_days: int = 7
    training_lookback_days: int = 180
    training_population: dict[str, Any] = field(default_factory=dict)
    inference_population: dict[str, Any] = field(default_factory=dict)
    cadence_days: int = 1
    iteration_budget: int = 50
    iterations_per_run: int = 5
    research_interval_days: int | None = 7
    agent_model: str | None = None
    agent_reasoning_effort: str | None = None
    success_auc: float | None = None
    plateau_iterations: int = 10
    output_person_property: str = ""
    write_person_property: bool = False


# ── Validation and template contracts ──────────────────────────────────────


@dataclass(frozen=True)
class ValidationWarning:
    code: str
    message: str
    severity: str


@dataclass(frozen=True)
class PipelineValidation:
    """Volume, base rate, and warnings for a proposed pipeline definition."""

    can_proceed: bool
    requires_acknowledgement: bool
    estimated_training_rows: int | None
    positive_count: int | None
    negative_count: int | None
    base_rate: float | None
    inference_population_size: int | None
    warnings: list[ValidationWarning]
    error: str | None


@dataclass(frozen=True)
class TemplateInfo:
    key: str
    display_name: str
    description: str
    default_horizon_days: int
    requires_user_event: bool
    requires_activity_resolution: bool
    notes: str


@dataclass(frozen=True)
class ResolvedTemplate:
    template_key: str
    display_name: str
    description: str
    suggested_name: str
    target_event: str
    resolved_activity_event: str | None
    activity_event_alternatives: list[str]
    horizon_days: int
    training_lookback_days: int
    training_population: dict[str, Any]
    inference_population: dict[str, Any]
    output_person_property: str
    notes: str


# ── Training-run history ───────────────────────────────────────────────────


@dataclass(frozen=True)
class TrainingRunHistoryEntry:
    run_id: UUID
    pipeline_id: UUID
    is_current_pipeline: bool
    target_event: str
    horizon_days: int
    best_holdout_score: float | None
    iteration_count: int
    completed_at: datetime | None
    summary: dict[str, Any] | None
    iterations: list[IterationTrailEntry]


@dataclass(frozen=True)
class TrainingRunHistory:
    runs: list[TrainingRunHistoryEntry]


# ── Online performance ─────────────────────────────────────────────────────


@dataclass(frozen=True)
class CalibrationBin:
    n: int
    mean_p_y: float
    positive_rate: float


@dataclass(frozen=True)
class ConfusionCounts:
    tp: int
    fp: int
    fn: int
    tn: int
    n_flagged: int
    precision: float | None
    recall: float | None


@dataclass(frozen=True)
class ConfusionByCutoff:
    top_10: ConfusionCounts
    top_20: ConfusionCounts
    likely: ConfusionCounts


@dataclass(frozen=True)
class OnlinePerformanceRow:
    """One model's realized metrics for one validated prediction date."""

    validation_run_id: UUID
    prediction_date: date
    horizon_days: int
    weekday: int
    model_id: UUID
    emitted_role: str
    current_role: str
    n_scored: int
    n_positive: int
    base_rate: float
    mean_p_y: float | None
    realized_auc: float | None
    realized_auc_ci_low: float | None
    realized_auc_ci_high: float | None
    brier_score: float | None
    calibration_error: float | None
    lift_at_10: float | None
    lift_at_20: float | None
    average_precision: float | None
    confusion: ConfusionByCutoff | None
    likely_threshold: float | None
    calibration_bins: list[CalibrationBin] | None
    warning: str | None
    validated_at: datetime | None


@dataclass(frozen=True)
class PredictionSegmentThresholds:
    """The pipeline's current cut points between the Likely, Possible and Unlikely segments."""

    likely_threshold: float
    possible_threshold: float
    likely_lift: float
    base_rate: float | None
    base_rate_dates: int
    base_rate_source: str
    champion_mean_p_y: float | None
    champion_base_rate: float | None
    scores_miscalibrated: bool


@dataclass(frozen=True)
class OnlinePerformance:
    rows: list[OnlinePerformanceRow]
    segment_thresholds: PredictionSegmentThresholds


# ── Artifact bundle ────────────────────────────────────────────────────────


@dataclass(frozen=True)
class ArtifactList:
    paths: list[str]
    count: int


@dataclass(frozen=True)
class StoredArtifact:
    path: str
    size_bytes: int
    sha256: str


@dataclass(frozen=True)
class ArtifactContent:
    path: str
    size_bytes: int
    sha256: str
    content_base64: str


@dataclass(frozen=True)
class ArtifactDeleteResult:
    path: str
    deleted: bool


# ── Feature materialization ────────────────────────────────────────────────


@dataclass(frozen=True)
class MaterializedFeatures:
    """Sandbox paths and shape of the parquet the agent reads with ``pd.read_parquet``."""

    train_features_path: str
    train_labels_path: str
    holdout_features_path: str
    holdout_labels_path: str
    n_train: int
    n_holdout: int
    n_features: int
    feature_cols: list[str]
    elapsed_s: float
    rows_read: int
    hints: list[str]