: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(autoresearch): add the API foundation and pipeline CRUD (13/22) (#89143)
Andrew Maguire1201d17322d1
diff --git a/products/autoresearch/backend/dataset/test_target.py b/products/autoresearch/backend/dataset/test_target.pyindex f4aef6ee161c..f32cdf958b1c 100644--- a/products/autoresearch/backend/dataset/test_target.py+++ b/products/autoresearch/backend/dataset/test_target.py@@ -1,5 +1,8 @@from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events+from parameterized import parameterized+from rest_framework import serializers as drf_serializers+from posthog.schema import HogQLQueryfrom posthog.hogql_queries.query_runner import ExecutionMode@@ -7,6 +10,7 @@ from posthog.models import Organization, Teamfrom products.actions.backend.models.action import Actionfrom products.autoresearch.backend.dataset.labeling import build_target_condition+from products.autoresearch.backend.presentation.views.serializers import resolve_targetfrom products.autoresearch.backend.query import run_hogql_rowsfrom products.autoresearch.backend.testing import TeamScopedTestMixin@@ -76,6 +80,73 @@ class TestBuildTargetCondition(TeamScopedTestMixin, APIBaseTest):)+class TestResolveTarget(TeamScopedTestMixin, APIBaseTest):+ def test_event_target_normalizes_definition(self):+ event, definition = resolve_target(team=self.team, target_event="$pageview", target_definition=None)+ assert event == "$pageview"+ assert definition == {"type": "event"}++ def test_empty_event_target_raises(self):+ with self.assertRaises(drf_serializers.ValidationError):+ resolve_target(team=self.team, target_event="", target_definition=None)++ def test_action_target_backfills_event_from_action_name(self):+ action = Action.objects.create(+ team=self.team, name="Interacted with file", steps_json=[{"event": "uploaded_file"}]+ )+ event, definition = resolve_target(+ team=self.team, target_event="", target_definition={"type": "action", "action_id": action.id}+ )+ assert event == "Interacted with file"+ assert definition == {"type": "action", "action_id": action.id}++ def test_action_target_keeps_explicit_event_label(self):+ action = Action.objects.create(team=self.team, name="Some action", steps_json=[{"event": "uploaded_file"}])+ event, definition = resolve_target(+ team=self.team,+ target_event="custom label",+ target_definition={"type": "action", "action_id": action.id},+ )+ assert event == "custom label"++ def test_missing_action_id_raises(self):+ with self.assertRaises(drf_serializers.ValidationError):+ resolve_target(team=self.team, target_event="", target_definition={"type": "action"})++ def test_action_in_a_sibling_environment_of_the_project_resolves(self):+ other_environment = Team.objects.create(organization=self.organization, project=self.project, name="Other env")+ action = Action.objects.create(team=self.team, name="Root team action", steps_json=[{"event": "uploaded_file"}])+ event, definition = resolve_target(+ team=other_environment, target_event="", target_definition={"type": "action", "action_id": action.id}+ )+ assert event == "Root team action"+ assert definition == {"type": "action", "action_id": action.id}++ @parameterized.expand(+ [+ ("names_the_prediction_event", [{"event": "autoresearch_prediction"}]),+ ("matches_any_event", [{"url": "/app", "url_matching": "contains"}]),+ ("one_step_of_several", [{"event": "uploaded_file"}, {"event": "autoresearch_prediction"}]),+ ]+ )+ def test_action_that_can_match_the_prediction_event_raises(self, _name: str, steps_json: list[dict]):+ action = Action.objects.create(team=self.team, name="Broad", steps_json=steps_json)+ with self.assertRaises(drf_serializers.ValidationError) as ctx:+ resolve_target(+ team=self.team, target_event="", target_definition={"type": "action", "action_id": action.id}+ )+ assert "target_definition" in ctx.exception.detail++ def test_foreign_action_raises(self):+ other_org = Organization.objects.create(name="Other")+ other_team = Team.objects.create(organization=other_org, name="Other")+ action = Action.objects.create(team=other_team, name="Foreign", steps_json=[{"event": "uploaded_file"}])+ with self.assertRaises(drf_serializers.ValidationError):+ resolve_target(+ team=self.team, target_event="", target_definition={"type": "action", "action_id": action.id}+ )++class TestTargetConditionAgainstClickhouse(ClickhouseTestMixin, APIBaseTest):def _count(self, cond: str, values: dict) -> int:sql = f"SELECT count() FROM events WHERE {cond}"diff --git a/products/autoresearch/backend/evaluation/AGENTS.md b/products/autoresearch/backend/evaluation/AGENTS.mdindex 5b7777f42671..4e9394c2f32c 100644--- a/products/autoresearch/backend/evaluation/AGENTS.md+++ b/products/autoresearch/backend/evaluation/AGENTS.md@@ -6,7 +6,7 @@ Training measures a model against a holdout slice of history. This package measuIt is the only honest number in the product. A holdout AUC of 0.93 says the model separates history well; the realized AUC says whether it predicted the future.-This package landed ahead of its callers. `../presentation/` and `../temporal/` arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.+This package landed ahead of its scheduler. `../temporal/` arrives in a later piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.## What lives herediff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.pyindex b15b91e18c47..31545d666490 100644--- a/products/autoresearch/backend/facade/api.py+++ b/products/autoresearch/backend/facade/api.py@@ -9,9 +9,217 @@ Scope is set at the entry boundary, so every read and write here takes ``team_idfilters on it. Business rules live in the modules behind this facade, not in the views."""+from typing import Any+from uuid import UUID++from products.actions.backend.models.action import Action++from ..dataset.labeling import (+ POPULATION_KINDS as _POPULATION_KINDS,+ PREDICTION_EVENT_NAME as _PREDICTION_EVENT_NAME,+)+from ..models import AutoresearchModel, AutoresearchPipeline+from .contracts import InvalidTarget, Pipeline, PipelineNotFound, PipelineWrite+AUTORESEARCH_FLAG = "autoresearch"def flag_key() -> str:"""The feature flag that gates every autoresearch surface."""return AUTORESEARCH_FLAG+++# ── Mappers ────────────────────────────────────────────────────────────────+++def _pipeline_to_contract(+ row: AutoresearchPipeline,+ *,+ champion_holdout_auc: float | None = None,+ champion_realized_auc: float | None = None,+) -> Pipeline:+ return Pipeline(+ id=row.id,+ name=row.name,+ description=row.description,+ target_event=row.target_event,+ # A row created outside the API keeps the column default ({}); it means the bare event+ # target, which is the shape the read schema declares.+ target_definition=row.target_definition or {"type": "event"},+ horizon_days=row.horizon_days,+ training_lookback_days=row.training_lookback_days,+ training_population=row.training_population or {},+ inference_population=row.inference_population or {},+ cadence_days=row.cadence_days,+ iteration_budget=row.iteration_budget,+ # The column is nullable (an admin can clear it); read that as no budget left+ # rather than widening the contract type.+ iteration_budget_remaining=row.iteration_budget_remaining or 0,+ success_auc=row.success_auc,+ plateau_iterations=row.plateau_iterations,+ output_person_property=row.output_person_property,+ status=row.status,+ created_by=row.created_by,+ created_at=row.created_at,+ updated_at=row.updated_at,+ last_scored_at=row.last_scored_at,+ champion_holdout_auc=champion_holdout_auc,+ champion_realized_auc=champion_realized_auc,+ )+++def _pipeline_with_champion(row: AutoresearchPipeline) -> Pipeline:+ champion = row.models.filter(role=AutoresearchModel.Role.CHAMPION).order_by("-created_at").first()+ return _pipeline_to_contract(+ row,+ champion_holdout_auc=champion.holdout_score if champion else None,+ champion_realized_auc=champion.realized_score if champion else None,+ )+++# ── Row lookups (internal) ─────────────────────────────────────────────────+++def _pipeline_row(team_id: int, pipeline_id: str | UUID, *, live_only: bool = False) -> AutoresearchPipeline:+ """One pipeline in this team.++ ``live_only`` excludes archived rows, which is what the pipeline's own detail routes do: an+ archived pipeline is gone as far as they are concerned, so acting on one is a 404 rather than+ a refusal that admits it exists. Routes nested under a pipeline id keep seeing archived rows,+ so they can explain why the write is refused.+ """+ qs = AutoresearchPipeline.objects.for_team(team_id)+ if live_only:+ qs = qs.exclude(status=AutoresearchPipeline.Status.ARCHIVED)+ try:+ return qs.get(pk=str(pipeline_id))+ except (AutoresearchPipeline.DoesNotExist, ValueError, TypeError):+ raise PipelineNotFound("Pipeline not found.")+++# ── Pipelines ──────────────────────────────────────────────────────────────+++def list_pipelines(team_id: int, *, offset: int, limit: int) -> tuple[list[Pipeline], int]:+ """One page of the team's non-archived pipelines, newest first, plus the total count."""+ qs = (+ AutoresearchPipeline.objects.for_team(team_id)+ .exclude(status=AutoresearchPipeline.Status.ARCHIVED)+ .select_related("created_by")+ .order_by("-created_at")+ )+ count = qs.count()+ return [_pipeline_with_champion(row) for row in qs[offset : offset + limit]], count+++def get_pipeline(team_id: int, pipeline_id: str | UUID) -> Pipeline:+ return _pipeline_with_champion(_pipeline_row(team_id, pipeline_id, live_only=True))+++def create_pipeline(team_id: int, *, fields: dict[str, Any], created_by: Any) -> Pipeline:+ row = AutoresearchPipeline.objects.create(+ team_id=team_id,+ created_by=created_by,+ iteration_budget_remaining=fields.get("iteration_budget", 50),+ **fields,+ )+ return _pipeline_with_champion(row)+++def update_pipeline(team_id: int, pipeline_id: str | UUID, *, fields: dict[str, Any]) -> Pipeline:+ row = _pipeline_row(team_id, pipeline_id, live_only=True)+ for key, value in fields.items():+ setattr(row, key, value)+ row.save()+ return _pipeline_with_champion(row)+++def delete_pipeline(team_id: int, pipeline_id: str | UUID) -> None:+ _pipeline_row(team_id, pipeline_id, live_only=True).delete()+++def pipeline_has_models(team_id: int, pipeline_id: str | UUID) -> bool:+ """Whether any model has been trained for this pipeline yet.++ The model-defining fields freeze once this is true — scoring keeps loading the trained+ artifact, so changing them would silently answer a different question.+ """+ return _pipeline_row(team_id, pipeline_id, live_only=True).models.exists()+++def get_pipeline_definition(team_id: int, pipeline_id: str | UUID) -> PipelineWrite:+ """The stored values of the fields a write body can carry, for change detection."""+ row = _pipeline_row(team_id, pipeline_id)+ return PipelineWrite(+ name=row.name,+ description=row.description,+ target_event=row.target_event,+ target_definition=row.target_definition or {},+ horizon_days=row.horizon_days,+ training_lookback_days=row.training_lookback_days,+ training_population=row.training_population or {},+ inference_population=row.inference_population or {},+ cadence_days=row.cadence_days,+ iteration_budget=row.iteration_budget,+ success_auc=row.success_auc,+ plateau_iterations=row.plateau_iterations,+ output_person_property=row.output_person_property,+ )+++def output_person_property_taken(team_id: int, value: str, *, exclude_pipeline_id: str | UUID | None = None) -> bool:+ """Whether a live pipeline on this team already writes to that person property.++ Two pipelines writing the same property would clobber each other's scores.+ """+ qs = AutoresearchPipeline.objects.for_team(team_id).filter(output_person_property=value)+ qs = qs.exclude(status=AutoresearchPipeline.Status.ARCHIVED)+ if exclude_pipeline_id is not None:+ qs = qs.exclude(pk=str(exclude_pipeline_id))+ return qs.exists()+++def resolve_action_target(project_id: int, action_id: Any) -> tuple[str, int]:+ """Resolve an action target to ``(action_name, action_id)``, scoped to the project.++ Actions live on the project's root team, so the lookup matches the labeler's+ (``team__project_id``) rather than the pipeline's own team, which would miss them from+ any other environment of the project.++ Raises ``PipelineNotFound`` when the action is missing, soft-deleted, or belongs to another+ project, so a foreign action id cannot be probed through this endpoint, and ``InvalidTarget``+ when a step could match the product's own prediction event: the labeler and online+ validation exclude that event from every scan, so such a target could never be+ observed as an outcome.+ """+ try:+ action = Action.objects.get(id=action_id, team__project_id=project_id, deleted=False)+ except (Action.DoesNotExist, ValueError, TypeError, OverflowError):+ raise PipelineNotFound(f"Action {action_id} was not found in this project.")+ step_events = action.get_step_events()+ if any(event is None or event == PREDICTION_EVENT_NAME for event in step_events):+ raise InvalidTarget(+ f"Action {action_id} has a step that can match '{PREDICTION_EVENT_NAME}'. "+ "Every step of a target action must name an event other than the prediction event."+ )+ return action.name or "", int(action_id)+++# ── Recipe validation surface for the presentation layer ───────────────────++# The semantic population kinds the labeler can compile. Presentation validates a submitted+# spec against this so an uncompilable population is refused at creation, not at query time.+POPULATION_KINDS = _POPULATION_KINDS++# The event this product emits. It is excluded from every labeler and validation scan, so it+# can never be a target.+PREDICTION_EVENT_NAME = _PREDICTION_EVENT_NAME+++# ── Choice vocabularies for the presentation layer ─────────────────────────++# The (value, label) pairs behind each status-like field. Presentation declares its+# ChoiceFields from these so the generated enum components keep the names and labels the+# model-bound serializers produced — including the one shared with another product, which+# `ENUM_NAME_OVERRIDES` pins by value set.+PIPELINE_STATUS_CHOICES = AutoresearchPipeline.Status.choicesdiff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.pyindex 4aeed3fe5986..49861530fed1 100644--- a/products/autoresearch/backend/facade/contracts.py+++ b/products/autoresearch/backend/facade/contracts.py@@ -4,4 +4,105 @@ Contract types for autoresearch.Stable, framework-free frozen dataclasses that define what this product exposes tothe rest of the codebase, and what its own presentation layer serializes. No Djangoimports.++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 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 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 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.+ """+++# ── Model-backed read contracts ────────────────────────────────────────────+++@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+ success_auc: float | None+ plateau_iterations: int+ output_person_property: str+ 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+++# ── 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+ success_auc: float | None = None+ plateau_iterations: int = 10+ output_person_property: str = ""diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.mdindex 65a672099f4d..52ea8c7488fb 100644--- a/products/autoresearch/backend/inference/AGENTS.md+++ b/products/autoresearch/backend/inference/AGENTS.md@@ -7,7 +7,7 @@ This is the cheap, boring, high-frequency half of the product — it runs on theThe cardinal rule: **inference never refits a persisted model.** A bundle is fitted once, at training completion, and every cadence loads that `model.pkl`. A recipe-only champion has no persisted model, so it fits its allowlisted sklearn class in process on every cadence; that is the cost of a champion without a bundle, not a refit.-This package landed ahead of its callers. `../presentation/`, `../temporal/`, and `../evaluation/` arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.+This package landed ahead of its scheduler. `../temporal/` arrives in a later piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.## What lives herediff --git a/products/autoresearch/backend/presentation/AGENTS.md b/products/autoresearch/backend/presentation/AGENTS.mdnew file mode 100644index 000000000000..47efe945cfff--- /dev/null+++ b/products/autoresearch/backend/presentation/AGENTS.md@@ -0,0 +1,45 @@+# API++The HTTP surface — and, because of how PostHog's codegen works, considerably more than that.++These serializers are the source of truth for three downstream artifacts: the REST API itself, the generated frontend TypeScript types, and the 29 `autoresearch-*` MCP tools that the sandbox agent uses to drive its own training run.+A vague `help_text` here becomes a vague tool description that a model has to guess at. Treat serializer annotations as agent-facing documentation, because they are.++This package lands one endpoint group at a time. Pipeline CRUD is here; the pre-create helpers, the lifecycle actions, the read-only model and run viewsets, the training-run agent surface, and suggestions arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464). The MCP tools arrive at the end of it.++## What lives here++- `views.py`+ One viewset so far, registered in `../routes.py` under the `project_autoresearch_pipelines` basename.+ - `AutoresearchPipelineViewSet` — full CRUD.+- `serializers.py`+ Request and response shapes, plus `resolve_target()`, which turns a pipeline's `target_event` or `target_definition` (an action reference) into the resolved target the rest of the product uses.+ It refuses the product's own `autoresearch_prediction` event, and an action with a step that can match it, because the labeler and online validation exclude that event from every scan.++## Access control++Every viewset sets `scope_object = "autoresearch"` and splits `scope_object_read_actions` / `scope_object_write_actions`, so custom actions are classified explicitly rather than inheriting a default.+`AutoresearchAccessPermission` gates on the `autoresearch` feature flag via `../access.py`.++**A new `@action` must be added to one of those two lists.** Omitting it is not a compile error and not a test failure — it is a permissions bug.++## Where the rest of the system meets this package++- **Routing** — `../routes.py` (`register_routes`).+- **Frontend types** — generated into `../../frontend/generated/` via drf-spectacular + Orval. Never hand-edit those; change the serializer and regenerate with `hogli build:openapi`.+- **Calls into** — `../dataset/` (`resolve_target`).++## Declare the response when it differs from the request++`create` validates with `AutoresearchPipelineCreateSerializer` but responds with `AutoresearchPipelineSerializer`. drf-spectacular infers responses from `get_serializer_class()`, so without an explicit `responses=` it documents the _write_ shape as the response.++That broke the MCP build: `autoresearch-create` sets `enrich_url: '{id}'`, the generated handler read `result.id`, and the declared type had no `id`. Now pinned with `@extend_schema(responses={201: AutoresearchPipelineSerializer})`.++Any action whose response shape differs from its request needs the same treatment — the mismatch is invisible in Python and only shows up as a TypeScript error two codegen steps downstream.++## When editing this flow++- **Annotate everything.** `help_text` on fields, `@extend_schema` on custom actions. These flow straight into MCP tool schemas and generated types; an unannotated action produces an empty schema an agent cannot use.+- **Classify every new `@action`** into `scope_object_read_actions` or `scope_object_write_actions`.+- Regenerate after serializer changes (`hogli build:openapi`) and commit the generated files — CI checks for drift.+- **If you add an endpoint, update this file to match.**diff --git a/products/autoresearch/backend/presentation/CLAUDE.md b/products/autoresearch/backend/presentation/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/products/autoresearch/backend/presentation/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/products/autoresearch/backend/presentation/views/__init__.py b/products/autoresearch/backend/presentation/views/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.pynew file mode 100644index 000000000000..98730fd1fabb--- /dev/null+++ b/products/autoresearch/backend/presentation/views/serializers.py@@ -0,0 +1,550 @@+import re+from dataclasses import replace+from typing import Any++from drf_spectacular.utils import extend_schema_field, extend_schema_serializer+from rest_framework import serializers+from rest_framework.fields import empty+from rest_framework_dataclasses.serializers import DataclassSerializer++from posthog.api.shared import UserBasicSerializer++from products.autoresearch.backend.facade import api+from products.autoresearch.backend.facade.contracts import Pipeline, PipelineWrite++POPULATION_KINDS = api.POPULATION_KINDS++# (value, label) pairs, not bare values: drf-spectacular builds each enum component's name and+# its label list from them, and `ENUM_NAME_OVERRIDES` matches on the value set.+PIPELINE_STATUS_CHOICES = api.PIPELINE_STATUS_CHOICES++TARGET_EVENT_MAX_LENGTH = 255+OUTPUT_PERSON_PROPERTY_MAX_LENGTH = 255++# The target event is interpolated into the sandboxed training agent's prompt brief, so reject+# characters that could break out of it (control chars incl. newlines, backticks, template braces)+# while keeping real event names ('$pageview', 'signed up', 'app.download-file') valid.+_FORBIDDEN_TARGET_EVENT_CHARS = re.compile(r"[\x00-\x1f\x7f`{}]")++_OUTPUT_PERSON_PROPERTY_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_$.\-]*$")+++def _validate_target_event_value(value: str, *, error_key: str) -> None:+ if len(value) > TARGET_EVENT_MAX_LENGTH:+ raise serializers.ValidationError(+ {error_key: f"Target event names are limited to {TARGET_EVENT_MAX_LENGTH} characters."}+ )+ if _FORBIDDEN_TARGET_EVENT_CHARS.search(value):+ raise serializers.ValidationError(+ {error_key: "Target event names cannot contain control characters, backticks, or braces."}+ )+++def resolve_target(+ *,+ team: Any,+ target_event: str,+ target_definition: dict[str, Any] | None,+) -> tuple[str, dict[str, Any]]:+ """+ Validate and normalize a prediction target, returning (target_event, target_definition).++ Two shapes:+ - event target → target_event must be non-empty; the definition is normalized to+ ``{"type": "event"}``. Any other event-shaped definition (e.g. one carrying filters)+ is rejected — the labeler only compiles the bare event and action shapes, so accepting+ filters here would silently ignore them.+ - action target → ``{"type": "action", "action_id": N}``. The action must belong to+ ``team`` (IDOR guard). target_event is backfilled from the action name when not+ supplied, so display and output-person-property derivation keep working unchanged.++ The resolved event is bounded and charset-checked in both branches — an action name can be+ longer (400 chars) and freer than target_event's field validation allows, and the value ends+ up in the training agent's prompt brief.++ Both branches refuse the product's own ``autoresearch_prediction`` event, as the event+ itself or as an action step that can match it: the labeler and online validation exclude+ it from every scan, so such a target would never be observed as an outcome.++ Raises serializers.ValidationError on a missing/foreign action, an empty event target, an+ unsupported definition shape, an unsafe/oversized resolved event, or a target that names+ the prediction event.+ """+ definition = target_definition or {}+ if definition.get("type") == "action":+ action_id = definition.get("action_id")+ if not isinstance(action_id, int) or isinstance(action_id, bool) or action_id < 1:+ raise serializers.ValidationError(+ {"target_definition": "Action target requires a positive integer 'action_id'."}+ )+ try:+ action_name, action_id = api.resolve_action_target(team.project_id, action_id)+ except (api.PipelineNotFound, api.InvalidTarget) as exc:+ raise serializers.ValidationError({"target_definition": str(exc)}) from exc+ resolved_event = target_event or action_name or f"action_{action_id}"+ _validate_target_event_value(resolved_event, error_key="target_event" if target_event else "target_definition")+ return resolved_event, {"type": "action", "action_id": int(action_id)}++ if not target_event:+ raise serializers.ValidationError(+ {"target_event": "Provide a target_event, or an action target via target_definition."}+ )+ if definition and (definition.get("type") != "event" or set(definition) != {"type"}):+ raise serializers.ValidationError(+ {+ "target_definition": (+ 'Unsupported target_definition. Pass {"type": "action", "action_id": N} to predict an action, '+ "or omit target_definition to predict target_event. Event filters are not supported."+ )+ }+ )+ if target_event == api.PREDICTION_EVENT_NAME:+ raise serializers.ValidationError(+ {+ "target_event": f"'{api.PREDICTION_EVENT_NAME}' is the event this product emits, so it cannot be a target."+ }+ )+ _validate_target_event_value(target_event, error_key="target_event")+ return target_event, {"type": "event"}+++# ── Typed schema wrappers for JSONField -----------------------------------+++@extend_schema_field(+ {+ "oneOf": [+ {+ "type": "object",+ "title": "EventTarget",+ "description": "Predict target_event. The default when target_definition is omitted.",+ "properties": {"type": {"type": "string", "enum": ["event"]}},+ "required": ["type"],+ "additionalProperties": False,+ },+ {+ "type": "object",+ "title": "ActionTarget",+ "description": "Predict a PostHog action in this project.",+ "properties": {+ "type": {"type": "string", "enum": ["action"]},+ "action_id": {"type": "integer", "minimum": 1, "description": "ID of the action to predict."},+ },+ "required": ["type", "action_id"],+ "additionalProperties": False,+ },+ ],+ "description": (+ 'Target definition. Two supported shapes: {"type": "event"} (predict target_event; the default) '+ 'or {"type": "action", "action_id": N} (predict a PostHog action). Event filters are not supported.'+ ),+ "example": {"type": "event"},+ }+)+class TargetDefinitionField(serializers.JSONField):+ def to_internal_value(self, data: Any) -> Any:+ value = super().to_internal_value(data)+ if not isinstance(value, dict):+ raise serializers.ValidationError(+ 'Target definition must be an object, e.g. {"type": "event"} or {"type": "action", "action_id": N}.'+ )+ return value+++# Required keys per semantic population kind, mirrored by the compiler in+# dataset/labeling.py (_build_population_kind_conditions). Validated here so an+# uncompilable spec is rejected at creation instead of failing at query time.+_POPULATION_KIND_REQUIRED_DAYS: dict[str, str | None] = {+ "performed_event_within_days": "days",+ "person_first_seen_within_days": "days",+ "active_not_performed_target": "active_within_days",+ "ever_performed_event": None,+ "ever_performed_target": None,+}+_POPULATION_KIND_REQUIRES_EVENT = frozenset({"ever_performed_event"})+_POPULATION_DAYS_MAX = 730+++@extend_schema_field(+ {+ "type": "object",+ "description": (+ "Population definition. Two shapes: a property filter object "+ '({"properties": [{"key": ..., "type": "person"|"event", "operator": ..., "value": ...}]}) '+ 'or a semantic spec ({"kind": ..., ...}) as returned by autoresearch-resolve-template-create. '+ "Supported kinds: 'performed_event_within_days' (did event, or any event, in last 'days' days), "+ "'person_first_seen_within_days' (first seen within 'days' days), "+ "'active_not_performed_target' (any event in last 'active_within_days' days and has not done the "+ "pipeline's target), "+ "'ever_performed_event' (did 'event' at least once in the training lookback window), "+ "'ever_performed_target' (did the pipeline's target at least once in the training lookback window). "+ "Use {} for all identified users."+ ),+ "example": {"properties": [{"key": "email", "type": "person", "operator": "is_set"}]},+ }+)+class PopulationDefinitionField(serializers.JSONField):+ def to_internal_value(self, data: Any) -> Any:+ value = super().to_internal_value(data)+ if not isinstance(value, dict):+ raise serializers.ValidationError("Population must be an object. Use {} for all identified users.")+ properties = value.get("properties")+ if properties is not None and (+ not isinstance(properties, list) or any(not isinstance(p, dict) for p in properties)+ ):+ raise serializers.ValidationError("Population 'properties' must be a list of filter objects.")+ kind = value.get("kind")+ if kind is None:+ return value+ if kind not in POPULATION_KINDS:+ raise serializers.ValidationError(+ f"Unknown population kind '{kind}'. Supported kinds: {', '.join(sorted(POPULATION_KINDS))}."+ )+ days_key = _POPULATION_KIND_REQUIRED_DAYS[kind]+ if days_key is not None:+ days = value.get(days_key)+ if not isinstance(days, int) or isinstance(days, bool) or not 1 <= days <= _POPULATION_DAYS_MAX:+ raise serializers.ValidationError(+ f"Population '{days_key}' must be a whole number between 1 and {_POPULATION_DAYS_MAX}."+ )+ if kind in _POPULATION_KIND_REQUIRES_EVENT:+ event = value.get("event")+ if not event or not isinstance(event, str):+ raise serializers.ValidationError(+ f"Population kind '{kind}' needs an 'event' naming the event it applies to."+ )+ return value+++# ── Core serializers ------------------------------------------------------+++@extend_schema_serializer(component_name="AutoresearchPipeline")+# Read representation of a pipeline. Every field is declared explicitly so the generated+# AutoresearchPipeline component keeps the shape it had when this was a ModelSerializer.+class AutoresearchPipelineSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="Unique UUID of this pipeline.")+ name = serializers.CharField(max_length=255, help_text="Display name for the pipeline.")+ description = serializers.CharField(required=False, allow_blank=True, help_text="Optional free-text description.")+ target_event = serializers.CharField(+ max_length=255, help_text="PostHog event name to predict, e.g. '$pageview' or 'signed_up'."+ )+ target_definition = TargetDefinitionField(+ help_text='Resolved target definition: {"type": "event"} or {"type": "action", "action_id": N}.'+ )+ horizon_days = serializers.IntegerField(+ min_value=-2147483648,+ max_value=2147483647,+ required=False,+ help_text="Prediction horizon in days. The model predicts whether the target event occurs within this window.",+ )+ training_lookback_days = serializers.IntegerField(+ min_value=-2147483648,+ max_value=2147483647,+ required=False,+ help_text="How far back to look for training examples. Larger windows give more data but may include stale behavior.",+ )+ training_population = PopulationDefinitionField(+ help_text="Population used for training. Defines which users can appear as training examples."+ )+ inference_population = PopulationDefinitionField(+ help_text="Population scored daily. Typically broader than the training population."+ )+ cadence_days = serializers.IntegerField(+ min_value=-2147483648,+ max_value=2147483647,+ required=False,+ help_text="Re-score the inference population every N days.",+ )+ iteration_budget = serializers.IntegerField(+ min_value=-2147483648,+ max_value=2147483647,+ required=False,+ help_text="Total training iterations allowed for the autoresearch loop.",+ )+ iteration_budget_remaining = serializers.IntegerField(+ read_only=True, help_text="Iterations remaining in the current budget."+ )+ success_auc = serializers.FloatField(+ required=False,+ allow_null=True,+ help_text="Target AUC threshold. Training stops early if this score is reached.",+ )+ plateau_iterations = serializers.IntegerField(+ min_value=-2147483648,+ max_value=2147483647,+ required=False,+ help_text="Stop training if no AUC improvement is seen in this many consecutive iterations.",+ )+ output_person_property = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=255,+ help_text="Person property name that stores the daily prediction score, e.g. 'predicted_p_pageview'.",+ )+ status = serializers.ChoiceField(+ choices=PIPELINE_STATUS_CHOICES,+ read_only=True,+ help_text="Pipeline lifecycle status: draft, bootstrapping, running, converged, paused, or archived.",+ )+ created_by = UserBasicSerializer(read_only=True)+ created_at = serializers.DateTimeField(read_only=True)+ updated_at = serializers.DateTimeField(read_only=True)+ last_scored_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="Timestamp of the most recent completed inference run."+ )+ champion_holdout_auc = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Offline holdout AUC of the current champion model (predictive accuracy on held-out training data).",+ )+ champion_realized_auc = serializers.FloatField(+ read_only=True,+ allow_null=True,+ help_text="Realized online AUC of the current champion model, computed from mature predictions against actual outcomes.",+ )++ class Meta:+ dataclass = Pipeline+ fields = [+ "id",+ "name",+ "description",+ "target_event",+ "target_definition",+ "horizon_days",+ "training_lookback_days",+ "training_population",+ "inference_population",+ "cadence_days",+ "iteration_budget",+ "iteration_budget_remaining",+ "success_auc",+ "plateau_iterations",+ "output_person_property",+ "status",+ "created_by",+ "created_at",+ "updated_at",+ "last_scored_at",+ "champion_holdout_auc",+ "champion_realized_auc",+ ]+++@extend_schema_serializer(component_name="AutoresearchPipelineCreate")+# Create and update body for a pipeline. Validation that needs to read stored rows — the action+# target, whether a model already exists, whether the output property is taken — goes through+# the facade.+class AutoresearchPipelineCreateSerializer(DataclassSerializer):+ name = serializers.CharField(max_length=255, help_text="Display name for the pipeline.")+ description = serializers.CharField(required=False, allow_blank=True, help_text="Optional free-text description.")+ target_event = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=255,+ help_text=(+ "PostHog event name to predict, e.g. '$pageview' or 'signed_up'. "+ "Omit when predicting an action target (pass target_definition instead)."+ ),+ )+ target_definition = TargetDefinitionField(+ required=False,+ default=dict,+ help_text=(+ 'Omit (or pass {"type": "event"}) to predict target_event; pass '+ '{"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted.'+ ),+ )+ horizon_days = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=365,+ help_text="Prediction horizon in days (1-365). The model predicts whether the target event occurs within this window.",+ )+ training_lookback_days = serializers.IntegerField(+ required=False,+ min_value=7,+ max_value=730,+ help_text="How far back to look for training examples (7-730 days). Larger windows give more data but may include stale behavior. Default: 180.",+ )+ training_population = PopulationDefinitionField(+ required=False,+ default=dict,+ help_text="Training population filter. Use {} for all identified users.",+ )+ inference_population = PopulationDefinitionField(+ required=False,+ default=dict,+ help_text="Inference population filter. Defaults to training_population if not set.",+ )+ cadence_days = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=365,+ help_text="Re-score the inference population every N days (1-365). Default: 1.",+ )+ iteration_budget = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=500,+ help_text="Total training iterations allowed for the autoresearch loop (1-500). Default: 50.",+ )+ success_auc = serializers.FloatField(+ required=False,+ allow_null=True,+ min_value=0.0,+ max_value=1.0,+ help_text="Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.",+ )+ plateau_iterations = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=2147483647,+ help_text="Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.",+ )+ output_person_property = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=255,+ help_text=(+ "Person property name for the prediction score, e.g. 'predicted_p_pageview'. "+ "Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot "+ "start with $ (reserved for PostHog's own properties); must be unique among this project's "+ "non-archived pipelines."+ ),+ )++ class Meta:+ dataclass = PipelineWrite+ fields = [+ "name",+ "description",+ "target_event",+ "target_definition",+ "horizon_days",+ "training_lookback_days",+ "training_population",+ "inference_population",+ "cadence_days",+ "iteration_budget",+ "success_auc",+ "plateau_iterations",+ "output_person_property",+ ]++ # Fields a trained model was fit against. Once any model exists they are frozen: scoring keeps+ # loading the trained artifact, so changing them would silently answer a different question.+ MODEL_DEFINING_FIELDS = (+ "target_event",+ "target_definition",+ "horizon_days",+ "training_lookback_days",+ "training_population",+ "inference_population",+ )++ @property+ def _pipeline_id(self) -> Any:+ return self.context.get("pipeline_id")++ def validate_output_person_property(self, value: str) -> str:+ if value and not _OUTPUT_PERSON_PROPERTY_RE.fullmatch(value):+ raise serializers.ValidationError(+ "Use only letters, digits, and _ $ . - characters, and do not start with $ (reserved for "+ "PostHog's own properties), e.g. 'predicted_p_signup_7d'."+ )+ return value++ @staticmethod+ def _supplied(data: Any, name: str) -> bool:+ """Whether the request body carried this field.++ ``DataclassSerializer`` leaves an unset field as the ``empty`` sentinel rather than the+ dataclass default, which is the only way to tell "absent" from "sent as the default".+ """+ return getattr(data, name, empty) is not empty++ @classmethod+ def _value(cls, data: Any, name: str, fallback: Any = None) -> Any:+ return getattr(data, name) if cls._supplied(data, name) else fallback++ def _validate_model_defining_fields_unchanged(self, team: Any, data: Any) -> None:+ pipeline_id = self._pipeline_id+ if not api.pipeline_has_models(team.pk, pipeline_id):+ return+ stored = api.get_pipeline_definition(team.pk, pipeline_id)+ changed = []+ for field_name in self.MODEL_DEFINING_FIELDS:+ if not self._supplied(data, field_name):+ continue+ current, new = getattr(stored, field_name), getattr(data, field_name)+ if field_name == "target_definition":+ # An empty stored definition and the normalized {"type": "event"} mean the same thing.+ current, new = current or {"type": "event"}, new or {"type": "event"}+ if new != current:+ changed.append(field_name)+ if changed:+ raise serializers.ValidationError(+ dict.fromkeys(+ changed,+ "This field cannot be changed after a model has been trained for this pipeline. "+ "Create a new pipeline to predict a different target.",+ )+ )++ def _derive_output_person_property(self, data: Any) -> str:+ raw = self._value(data, "target_event") or "target"+ safe_name = re.sub(r"[^a-z0-9._-]+", "_", raw.lstrip("$").lower()) or "target"+ # Include the horizon so two pipelines predicting the same target over different+ # horizons don't $set the same person property and clobber each other's scores.+ horizon = self._value(data, "horizon_days") or 7+ derived = f"predicted_p_{safe_name}_{horizon}d"+ if len(derived) > OUTPUT_PERSON_PROPERTY_MAX_LENGTH:+ raise serializers.ValidationError(+ {+ "output_person_property": (+ "The auto-derived property name is too long for this target. "+ "Pass output_person_property explicitly."+ )+ }+ )+ return derived++ def validate(self, data: Any) -> Any:+ # DataclassSerializer hands us the constructed dataclass, not a dict, and it is frozen —+ # so derived values are collected here and applied with one `replace`.+ team = self.context["get_team"]()+ updates: dict[str, Any] = {}+ # On a partial update that doesn't touch the target, leave it untouched —+ # only resolve when creating or when a target field is actually supplied.+ is_update = self._pipeline_id is not None+ target_supplied = self._supplied(data, "target_event") or self._supplied(data, "target_definition")+ if not is_update or target_supplied:+ target_event, target_definition = resolve_target(+ team=team,+ target_event=self._value(data, "target_event", ""),+ target_definition=self._value(data, "target_definition"),+ )+ updates["target_event"] = target_event+ updates["target_definition"] = target_definition+ if is_update:+ self._validate_model_defining_fields_unchanged(team, replace(data, **updates) if updates else data)+ output_person_property = self._value(data, "output_person_property")+ if not is_update and not output_person_property:+ output_person_property = self._derive_output_person_property(replace(data, **updates) if updates else data)+ updates["output_person_property"] = output_person_property+ if output_person_property and api.output_person_property_taken(+ team.pk, output_person_property, exclude_pipeline_id=self._pipeline_id+ ):+ raise serializers.ValidationError(+ {+ "output_person_property": (+ f"Another pipeline in this project already writes to '{output_person_property}'. "+ "Choose a different output_person_property."+ )+ }+ )+ if not is_update and not self._value(data, "inference_population"):+ updates["inference_population"] = self._value(data, "training_population", {})+ return replace(data, **updates) if updates else datadiff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.pynew file mode 100644index 000000000000..616a19eaec40--- /dev/null+++ b/products/autoresearch/backend/presentation/views/views.py@@ -0,0 +1,194 @@+"""+DRF views for autoresearch.++Responsibilities:+- Validate incoming JSON (via serializers)+- Call facade functions+- Convert contracts to JSON responses++No business logic here — that lives behind ``facade/api.py``.+"""++from dataclasses import fields+from typing import Any, cast++import structlog+from drf_spectacular.utils import extend_schema+from rest_framework import viewsets+from rest_framework.exceptions import NotFound+from rest_framework.fields import empty+from rest_framework.permissions import BasePermission+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.views import APIView++from posthog.api.documentation import PostHogAutoSchema+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.models.user import User++from products.autoresearch.backend.facade import api+from products.autoresearch.backend.facade.access import has_autoresearch_access+from products.autoresearch.backend.facade.contracts import PipelineNotFound++from .serializers import AutoresearchPipelineCreateSerializer, AutoresearchPipelineSerializer++logger = structlog.get_logger(__name__)+++class FacadePathParamSchema(PostHogAutoSchema):+ """Types a facade-backed viewset's UUID path parameters.++ drf-spectacular reads a path parameter's type off the viewset's ``queryset`` model. These+ viewsets reach their data through the facade and declare no queryset, so each id is spelled+ out here instead. Declaring them through ``@extend_schema`` would not work: that appends the+ parameter to every operation in the viewset, including the collection routes whose path has+ no id in it. This hook only ever sees variables the path actually contains.+ """++ def _resolve_path_parameters(self, variables: Any) -> Any:+ declared = getattr(self.view, "uuid_path_parameters", {})+ resolved = []+ for parameter in super()._resolve_path_parameters(variables):+ description = declared.get(parameter["name"])+ if parameter["name"] not in declared:+ resolved.append(parameter)+ continue+ # Rebuilt rather than mutated, so the keys keep the order drf-spectacular emits.+ rebuilt: dict[str, Any] = {}+ for key, value in parameter.items():+ if key == "schema":+ rebuilt["schema"] = {"type": "string", "format": "uuid"}+ if description:+ rebuilt["description"] = description+ elif key == "description" and description:+ continue+ else:+ rebuilt[key] = value+ resolved.append(rebuilt)+ return resolved+++class AutoresearchAccessPermission(BasePermission):+ """Gate the autoresearch product behind the `autoresearch` feature flag."""++ message = "Autoresearch is not enabled for this team."++ def has_permission(self, request: Request, view: APIView) -> bool:+ team_id = getattr(view, "team_id", None)+ return has_autoresearch_access(request.user, team_id=team_id)+++class _FacadePaginationMixin:+ # Drives the standard ``LimitOffsetPagination`` envelope from a facade ``(page, count)``+ # result. The facade does the slicing, so the paginator's state is set directly rather than+ # handed a queryset — keeping the param names, default page size, and ``count`` / ``next`` /+ # ``previous`` shape identical to the model-backed viewsets.+ def _paginate_via_facade(self, request: Request, fetch: Any, serializer_class: Any) -> Response:+ paginator = self.paginator # type: ignore[attr-defined]+ limit = paginator.get_limit(request)+ offset = paginator.get_offset(request)+ page, count = fetch(offset=offset, limit=limit)+ paginator.request = request+ paginator.limit = limit+ paginator.offset = offset+ paginator.count = count+ serializer = serializer_class(instance=page, many=True)+ return paginator.get_paginated_response(serializer.data)+++def _pipeline_write_fields(validated: Any) -> dict[str, Any]:+ """The fields to persist.++ ``validated`` is the write contract, where a field the request body did not carry is left as+ the ``empty`` sentinel. Skipping those is what stops a PATCH writing a default over a field+ the caller never mentioned; the values ``validate()`` derived are real, so they carry through.+ """+ return {+ f.name: getattr(validated, f.name) for f in fields(validated) if getattr(validated, f.name, empty) is not empty+ }+++@extend_schema(tags=["autoresearch"])+class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin, viewsets.ModelViewSet):+ """+ Manage autoresearch prediction pipelines.++ A pipeline defines a target event, population, and horizon. The autoresearch+ training loop finds the best predictive recipe; the inference workflow scores+ users daily and emits autoresearch_prediction events.+ """++ schema = FacadePathParamSchema()+ uuid_path_parameters = {"id": "A UUID string identifying this autoresearch pipeline."}+ scope_object = "autoresearch"+ scope_object_read_actions = ["list", "retrieve"]+ scope_object_write_actions = ["create", "update", "partial_update", "destroy"]+ permission_classes = [AutoresearchAccessPermission]+ serializer_class = AutoresearchPipelineSerializer+ queryset = None # data is reached through the facade; declared for router/schema only++ def get_serializer_class(self) -> type[AutoresearchPipelineSerializer | AutoresearchPipelineCreateSerializer]:+ if self.action in ("create", "partial_update", "update"):+ return AutoresearchPipelineCreateSerializer+ return AutoresearchPipelineSerializer++ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return self._paginate_via_facade(+ request,+ lambda offset, limit: api.list_pipelines(self.team_id, offset=offset, limit=limit),+ AutoresearchPipelineSerializer,+ )++ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ try:+ pipeline = api.get_pipeline(self.team_id, self.kwargs["pk"])+ except PipelineNotFound:+ raise NotFound("Pipeline not found.")+ return Response(AutoresearchPipelineSerializer(instance=pipeline).data)++ @extend_schema(+ request=AutoresearchPipelineCreateSerializer,+ # `create` responds with the read serializer, not the write one. Without this,+ # drf-spectacular infers the response from `get_serializer_class()` and the+ # generated client loses `id` — which `enrich_url: '{id}'` needs.+ responses={201: AutoresearchPipelineSerializer},+ )+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ serializer = AutoresearchPipelineCreateSerializer(data=request.data, context=self.get_serializer_context())+ serializer.is_valid(raise_exception=True)+ pipeline = api.create_pipeline(+ self.team_id,+ fields=_pipeline_write_fields(serializer.validated_data),+ created_by=cast(User, request.user),+ )+ output = AutoresearchPipelineSerializer(instance=pipeline)+ headers = self.get_success_headers(output.data)+ return Response(output.data, status=201, headers=headers)++ def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ partial = kwargs.pop("partial", False)+ context = {**self.get_serializer_context(), "pipeline_id": self.kwargs["pk"]}+ serializer = AutoresearchPipelineCreateSerializer(data=request.data, partial=partial, context=context)+ # Validation reads the stored pipeline (the trained-model guard), so a missing or archived+ # id surfaces there first and must map to the same 404 as the write.+ try:+ serializer.is_valid(raise_exception=True)+ pipeline = api.update_pipeline(+ self.team_id,+ self.kwargs["pk"],+ fields=_pipeline_write_fields(serializer.validated_data),+ )+ except PipelineNotFound:+ raise NotFound("Pipeline not found.")+ return Response(AutoresearchPipelineSerializer(instance=pipeline).data)++ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ kwargs["partial"] = True+ return self.update(request, *args, **kwargs)++ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ try:+ api.delete_pipeline(self.team_id, self.kwargs["pk"])+ except PipelineNotFound:+ raise NotFound("Pipeline not found.")+ return Response(status=204)diff --git a/products/autoresearch/backend/routes.py b/products/autoresearch/backend/routes.pynew file mode 100644index 000000000000..7b17d12560e0--- /dev/null+++ b/products/autoresearch/backend/routes.py@@ -0,0 +1,12 @@+from posthog.api.routing import RouterRegistry++import products.autoresearch.backend.presentation.views.views as autoresearch+++def register_routes(routers: RouterRegistry) -> None:+ routers.projects.register(+ r"autoresearch",+ autoresearch.AutoresearchPipelineViewSet,+ "project_autoresearch_pipelines",+ ["project_id"],+ )diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.pynew file mode 100644index 000000000000..19cbbe2cf977--- /dev/null+++ b/products/autoresearch/backend/tests/test_api.py@@ -0,0 +1,356 @@+import uuid+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status++from posthog.models import Organization, Team++from products.actions.backend.models.action import Action+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline+from products.autoresearch.backend.presentation.views.serializers import (+ AutoresearchPipelineCreateSerializer,+ PopulationDefinitionField,+)+from products.autoresearch.backend.testing import TeamScopedTestMixin+++class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self.base_url = f"/api/projects/{self.team.pk}/autoresearch"+ self._flag_patcher = patch(+ "products.autoresearch.backend.access.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self._flag_patcher.start()+ self.addCleanup(self._flag_patcher.stop)++ def _make_pipeline(self, **kwargs) -> AutoresearchPipeline:+ defaults = {+ "team": self.team,+ "created_by": self.user,+ "name": "Test Pipeline",+ "target_event": "$pageview",+ "horizon_days": 7,+ "iteration_budget": 50,+ "iteration_budget_remaining": 50,+ }+ defaults.update(kwargs)+ return AutoresearchPipeline.objects.create(**defaults)++ # ──────────────────────────────────────────── CRUD ────────────────────────────────────────────++ def test_create_pipeline(self):+ resp = self.client.post(+ f"{self.base_url}/",+ {"name": "My Pipeline", "target_event": "$signup", "horizon_days": 14},+ format="json",+ )+ assert resp.status_code == status.HTTP_201_CREATED+ data = resp.json()+ assert data["name"] == "My Pipeline"+ assert data["target_event"] == "$signup"+ assert data["status"] == "draft"+ # Auto-derived output property carries the horizon so same-target/different-horizon+ # pipelines don't $set the same person property.+ assert data["output_person_property"] == "predicted_p_signup_14d"+ assert AutoresearchPipeline.objects.filter(team=self.team, name="My Pipeline").exists()++ def test_create_pipeline_with_action_target(self):+ action = Action.objects.create(+ team=self.team, name="Interacted with file", steps_json=[{"event": "uploaded_file"}]+ )+ resp = self.client.post(+ f"{self.base_url}/",+ {+ "name": "Action Pipeline",+ "target_definition": {"type": "action", "action_id": action.id},+ "horizon_days": 14,+ },+ format="json",+ )+ assert resp.status_code == status.HTTP_201_CREATED, resp.json()+ data = resp.json()+ assert data["target_definition"] == {"type": "action", "action_id": action.id}+ # target_event is backfilled from the action name for display + property derivation.+ assert data["target_event"] == "Interacted with file"+ assert data["output_person_property"] == "predicted_p_interacted_with_file_14d"++ def test_create_pipeline_with_foreign_action_rejected(self):+ other_org = Organization.objects.create(name="Other Org")+ other_team = Team.objects.create(organization=other_org, name="Other Team")+ action = Action.objects.create(team=other_team, name="Foreign", steps_json=[{"event": "uploaded_file"}])+ resp = self.client.post(+ f"{self.base_url}/",+ {"name": "Bad", "target_definition": {"type": "action", "action_id": action.id}},+ format="json",+ )+ assert resp.status_code == status.HTTP_400_BAD_REQUEST++ def test_create_pipeline_with_deleted_action_rejected(self):+ action = Action.objects.create(+ team=self.team, name="Gone", steps_json=[{"event": "uploaded_file"}], deleted=True+ )+ resp = self.client.post(+ f"{self.base_url}/",+ {"name": "Bad", "target_definition": {"type": "action", "action_id": action.id}},+ format="json",+ )+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ assert resp.json()["attr"] == "target_definition"++ def test_create_pipeline_without_target_rejected(self):+ resp = self.client.post(f"{self.base_url}/", {"name": "No target"}, format="json")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST++ def test_list_pipelines_for_team(self):+ self._make_pipeline(name="Pipeline A")+ self._make_pipeline(name="Pipeline B")+ resp = self.client.get(f"{self.base_url}/")+ assert resp.status_code == status.HTTP_200_OK+ assert resp.json()["count"] == 2++ def test_archived_pipelines_excluded_from_list(self):+ self._make_pipeline(name="Active")+ self._make_pipeline(name="Archived", status=AutoresearchPipeline.Status.ARCHIVED)+ resp = self.client.get(f"{self.base_url}/")+ assert resp.json()["count"] == 1+ assert resp.json()["results"][0]["name"] == "Active"++ def test_retrieve_pipeline(self):+ pipeline = self._make_pipeline()+ resp = self.client.get(f"{self.base_url}/{pipeline.id}/")+ assert resp.status_code == status.HTTP_200_OK+ assert resp.json()["id"] == str(pipeline.id)+ assert resp.json()["target_definition"] == {"type": "event"}++ def test_other_team_cannot_access_pipeline(self):+ other_org = Organization.objects.create(name="Other Org")+ other_team = Team.objects.create(organization=other_org, name="Other Team")+ pipeline = AutoresearchPipeline.objects.create(+ team=other_team,+ created_by=self.user,+ name="Other Team Pipeline",+ target_event="$click",+ iteration_budget=50,+ iteration_budget_remaining=50,+ )+ resp = self.client.get(f"/api/projects/{other_team.pk}/autoresearch/{pipeline.id}/")+ assert resp.status_code in (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND)++ # ──────────────────────────────────────── lifecycle actions ────────────────────────────────────++ # ─────────────────────────────────────── validate action ──────────────────────────────────────++ # ──────────────────────────────────────── train action ────────────────────────────────────────++ # ──────────────────────────────────── update restrictions ─────────────────────────────────────++ def _make_trained_pipeline(self) -> AutoresearchPipeline:+ pipeline = self._make_pipeline()+ AutoresearchModel.objects.create(+ pipeline=pipeline,+ role=AutoresearchModel.Role.CHAMPION,+ model_recipe={"stub": True},+ recipe_hash="abc123",+ )+ return pipeline++ @parameterized.expand(+ [+ ("target_event", {"target_event": "other_event"}),+ ("horizon_days", {"horizon_days": 30}),+ ("training_lookback_days", {"training_lookback_days": 90}),+ ("training_population", {"training_population": {"kind": "ever_performed_event"}}),+ ("inference_population", {"inference_population": {"kind": "ever_performed_event"}}),+ ]+ )+ def test_model_defining_fields_frozen_after_training(self, field: str, payload: dict):+ pipeline = self._make_trained_pipeline()+ resp = self.client.patch(f"{self.base_url}/{pipeline.id}/", payload, format="json")+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ pipeline.refresh_from_db()+ assert getattr(pipeline, field) != payload[field]++ def test_metadata_editable_after_training(self):+ pipeline = self._make_trained_pipeline()+ resp = self.client.patch(+ f"{self.base_url}/{pipeline.id}/",+ {"name": "Renamed", "cadence_days": 3, "iteration_budget": 20},+ format="json",+ )+ assert resp.status_code == status.HTTP_200_OK, resp.json()+ pipeline.refresh_from_db()+ assert pipeline.name == "Renamed"+ assert pipeline.cadence_days == 3++ def test_resubmitting_unchanged_target_after_training_is_allowed(self):+ pipeline = self._make_trained_pipeline()+ resp = self.client.patch(f"{self.base_url}/{pipeline.id}/", {"target_event": "$pageview"}, format="json")+ assert resp.status_code == status.HTTP_200_OK, resp.json()++ @parameterized.expand([("archived",), ("unknown",)])+ def test_update_of_missing_pipeline_returns_404(self, case: str):+ if case == "archived":+ pipeline_id = self._make_pipeline(status=AutoresearchPipeline.Status.ARCHIVED).id+ else:+ pipeline_id = uuid.uuid4()+ resp = self.client.patch(f"{self.base_url}/{pipeline_id}/", {"name": "Renamed"}, format="json")+ assert resp.status_code == status.HTTP_404_NOT_FOUND++ def test_target_editable_before_any_model_is_trained(self):+ pipeline = self._make_pipeline()+ resp = self.client.patch(f"{self.base_url}/{pipeline.id}/", {"horizon_days": 30}, format="json")+ assert resp.status_code == status.HTTP_200_OK, resp.json()+ pipeline.refresh_from_db()+ assert pipeline.horizon_days == 30++ # ─────────────────────────────── output_person_property guards ────────────────────────────────++ def test_output_person_property_collision_rejected(self):+ self._make_pipeline(name="First", output_person_property="predicted_p_signup_7d")+ resp = self.client.post(+ f"{self.base_url}/",+ {"name": "Second", "target_event": "other_event", "output_person_property": "predicted_p_signup_7d"},+ format="json",+ )+ assert resp.status_code == status.HTTP_400_BAD_REQUEST+ assert resp.json()["attr"] == "output_person_property"++ def test_derived_output_person_property_collision_rejected(self):+ self._make_pipeline(name="First", output_person_property="predicted_p_signup_14d")+ # Same target + horizon derives the same property name.+ resp = self.client.post(+ f"{self.base_url}/",+ {"name": "Second", "target_event": "$signup", "horizon_days": 14},+ format="json",+ )+ assert resp.status_code == status.HTTP_400_BAD_REQUEST++ def test_oversized_action_name_target_rejected(self):+ action = Action.objects.create(team=self.team, name="x" * 300, steps_json=[{"event": "uploaded_file"}])+ resp = self.client.post(+ f"{self.base_url}/",+ {"name": "Oversized", "target_definition": {"type": "action", "action_id": action.id}},+ format="json",+ )+ assert resp.status_code == status.HTTP_400_BAD_REQUEST++ # ─────────────────────────────────── nested resources ─────────────────────────────────────────+++class TestPipelineCreateSerializerValidation(SimpleTestCase):+ # Field- and target-shape validation runs in memory, so these cases never need a DB.+ # The endpoint wiring (bad body -> 400) is covered by the APIBaseTest create tests above.++ def _serializer(self, **overrides: Any) -> AutoresearchPipelineCreateSerializer:+ data: dict[str, Any] = {"name": "Pipeline", "target_event": "$pageview", **overrides}+ return AutoresearchPipelineCreateSerializer(data=data, context={"get_team": lambda: None})++ @parameterized.expand(+ [+ ("horizon_days_below_min", "horizon_days", 0),+ ("horizon_days_above_max", "horizon_days", 366),+ ("lookback_below_min", "training_lookback_days", 6),+ ("lookback_above_max", "training_lookback_days", 731),+ ("cadence_below_min", "cadence_days", 0),+ ("cadence_above_max", "cadence_days", 366),+ ("iteration_budget_below_min", "iteration_budget", 0),+ ("iteration_budget_above_max", "iteration_budget", 501),+ ("plateau_iterations_below_min", "plateau_iterations", 0),+ ("success_auc_below_min", "success_auc", -0.1),+ ("success_auc_above_max", "success_auc", 1.5),+ ]+ )+ def test_out_of_range_numeric_field_rejected(self, _name: str, field: str, value: float) -> None:+ serializer = self._serializer(**{field: value})+ assert not serializer.is_valid()+ assert field in serializer.errors++ @parameterized.expand(+ [+ ("not_an_object", ["properties"]),+ ("properties_not_a_list", {"properties": {"key": "email"}}),+ ("unknown_kind", {"kind": "bogus"}),+ ("missing_days", {"kind": "performed_event_within_days"}),+ ("days_not_int", {"kind": "person_first_seen_within_days", "days": "14"}),+ ("days_out_of_range", {"kind": "performed_event_within_days", "days": 100000}),+ ("missing_event_for_repeat", {"kind": "ever_performed_event"}),+ ]+ )+ def test_uncompilable_population_rejected(self, _name: str, population: Any) -> None:+ serializer = self._serializer(training_population=population)+ assert not serializer.is_valid()+ assert "training_population" in serializer.errors++ @parameterized.expand(+ [+ ("empty", {}),+ ("properties", {"properties": [{"key": "email", "type": "person", "operator": "is_set"}]}),+ ("kind_any_event", {"kind": "performed_event_within_days", "days": 30}),+ ("kind_with_event", {"kind": "ever_performed_event", "event": "checkout"}),+ ("kind_adoption", {"kind": "active_not_performed_target", "active_within_days": 30}),+ ("kind_repeat_target", {"kind": "ever_performed_target"}),+ ]+ )+ def test_compilable_population_accepted(self, _name: str, population: Any) -> None:+ # Field-level only: the full serializer's validate() needs the DB for the+ # output_person_property collision check, which SimpleTestCase forbids.+ assert PopulationDefinitionField().run_validation(population) == population++ @parameterized.expand(+ [+ ("newline", "signup\ncomplete"),+ ("backtick", "signup`whoami`"),+ ("template_braces", "signup {{instructions}}"),+ ("control_char", "signup\x07"),+ ]+ )+ def test_injection_shaped_target_event_rejected(self, _name: str, target_event: str) -> None:+ serializer = self._serializer(target_event=target_event)+ assert not serializer.is_valid()+ assert "target_event" in serializer.errors++ def test_own_prediction_event_rejected_as_target(self) -> None:+ serializer = self._serializer(target_event="autoresearch_prediction")+ assert not serializer.is_valid()+ assert "target_event" in serializer.errors++ @parameterized.expand(+ [+ ("event_with_filters", {"type": "event", "filters": [{"key": "$current_url"}]}),+ ("legacy_event_shape", {"event": "$pageview", "filters": []}),+ ("unknown_type", {"type": "cohort", "cohort_id": 1}),+ ("not_an_object", "action"),+ ("list", [{"type": "event"}]),+ ("action_id_missing", {"type": "action"}),+ ("action_id_string", {"type": "action", "action_id": "1"}),+ ("action_id_bool", {"type": "action", "action_id": True}),+ ("action_id_zero", {"type": "action", "action_id": 0}),+ ("action_id_overflows_int", {"type": "action", "action_id": 1e400}),+ ]+ )+ def test_unsupported_target_definition_rejected(self, _name: str, definition: Any) -> None:+ serializer = self._serializer(target_definition=definition)+ assert not serializer.is_valid()+ assert "target_definition" in serializer.errors++ @parameterized.expand(+ [+ ("space", "predicted p"),+ ("backtick", "predicted`p"),+ ("braces", "predicted{p}"),+ ("newline", "predicted\np"),+ ("posthog_namespace", "$browser"),+ ]+ )+ def test_invalid_output_person_property_shape_rejected(self, _name: str, value: str) -> None:+ serializer = self._serializer(output_person_property=value)+ assert not serializer.is_valid()+ assert "output_person_property" in serializer.errorsdiff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.mdindex 3c4343443127..90aaef5d2c18 100644--- a/products/autoresearch/backend/training/AGENTS.md+++ b/products/autoresearch/backend/training/AGENTS.md@@ -7,7 +7,7 @@ This is the expensive half of the product. A real run costs roughly a dollar inThe other half is `../inference/`, which consumes what this package produces and must never re-fit.-This package landed ahead of its callers. `../presentation/`, `../temporal/`, `../management/`, and `../evaluation/` arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.+This package landed ahead of its callers. `../temporal/` and the `autoresearch_train` command arrive in later pieces of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the references to them below describe where they will sit.## What lives herediff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..105683b628c4--- /dev/null+++ b/products/autoresearch/frontend/generated/api.schemas.ts@@ -0,0 +1,401 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+/**+ * * `draft` - Draft+ * * `bootstrapping` - Bootstrapping+ * * `running` - Running+ * * `converged` - Converged+ * * `paused` - Paused+ * * `archived` - Archived+ */+export type AutoresearchPipelineStatusEnumApi =+ (typeof AutoresearchPipelineStatusEnumApi)[keyof typeof AutoresearchPipelineStatusEnumApi]++export const AutoresearchPipelineStatusEnumApi = {+ Draft: 'draft',+ Bootstrapping: 'bootstrapping',+ Running: 'running',+ Converged: 'converged',+ Paused: 'paused',+ Archived: 'archived',+} as const++/**+ * * `engineering` - Engineering+ * * `data` - Data+ * * `product` - Product Management+ * * `founder` - Founder+ * * `leadership` - Leadership+ * * `marketing` - Marketing+ * * `sales` - Sales / Success+ * * `student` - Student+ * * `other` - Other+ */+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]++export const RoleAtOrganizationEnumApi = {+ Engineering: 'engineering',+ Data: 'data',+ Product: 'product',+ Founder: 'founder',+ Leadership: 'leadership',+ Marketing: 'marketing',+ Sales: 'sales',+ Student: 'student',+ Other: 'other',+} as const++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++/**+ * @nullable+ */+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null++export interface UserBasicApi {+ readonly id: number+ readonly uuid: string+ /**+ * @maxLength 200+ * @nullable+ */+ distinct_id?: string | null+ /** @maxLength 150 */+ first_name?: string+ /** @maxLength 150 */+ last_name?: string+ /** @maxLength 254 */+ email: string+ /** @nullable */+ is_email_verified?: boolean | null+ /** @nullable */+ readonly hedgehog_config: UserBasicApiHedgehogConfig+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null+}++/**+ * Resolved target definition: {"type": "event"} or {"type": "action", "action_id": N}.+ */+export type AutoresearchPipelineApiTargetDefinition =+ | {+ type: 'event'+ }+ | {+ type: 'action'+ /**+ * ID of the action to predict.+ * @minimum 1+ */+ action_id: number+ }++/**+ * Population used for training. Defines which users can appear as training examples.+ */+export type AutoresearchPipelineApiTrainingPopulation = { [key: string]: unknown }++/**+ * Population scored daily. Typically broader than the training population.+ */+export type AutoresearchPipelineApiInferencePopulation = { [key: string]: unknown }++export interface AutoresearchPipelineApi {+ /** Unique UUID of this pipeline. */+ readonly id: string+ /**+ * Display name for the pipeline.+ * @maxLength 255+ */+ name: string+ /** Optional free-text description. */+ description?: string+ /**+ * PostHog event name to predict, e.g. '$pageview' or 'signed_up'.+ * @maxLength 255+ */+ target_event: string+ /** Resolved target definition: {"type": "event"} or {"type": "action", "action_id": N}. */+ target_definition: AutoresearchPipelineApiTargetDefinition+ /**+ * Prediction horizon in days. The model predicts whether the target event occurs within this window.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ horizon_days?: number+ /**+ * How far back to look for training examples. Larger windows give more data but may include stale behavior.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ training_lookback_days?: number+ /** Population used for training. Defines which users can appear as training examples. */+ training_population: AutoresearchPipelineApiTrainingPopulation+ /** Population scored daily. Typically broader than the training population. */+ inference_population: AutoresearchPipelineApiInferencePopulation+ /**+ * Re-score the inference population every N days.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ cadence_days?: number+ /**+ * Total training iterations allowed for the autoresearch loop.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ iteration_budget?: number+ /** Iterations remaining in the current budget. */+ readonly iteration_budget_remaining: number+ /**+ * Target AUC threshold. Training stops early if this score is reached.+ * @nullable+ */+ success_auc?: number | null+ /**+ * Stop training if no AUC improvement is seen in this many consecutive iterations.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ plateau_iterations?: number+ /**+ * Person property name that stores the daily prediction score, e.g. 'predicted_p_pageview'.+ * @maxLength 255+ */+ output_person_property?: string+ /** Pipeline lifecycle status: draft, bootstrapping, running, converged, paused, or archived.+ *+ * * `draft` - Draft+ * * `bootstrapping` - Bootstrapping+ * * `running` - Running+ * * `converged` - Converged+ * * `paused` - Paused+ * * `archived` - Archived */+ readonly status: AutoresearchPipelineStatusEnumApi+ readonly created_by: UserBasicApi+ readonly created_at: string+ readonly updated_at: string+ /**+ * Timestamp of the most recent completed inference run.+ * @nullable+ */+ readonly last_scored_at: string | null+ /**+ * Offline holdout AUC of the current champion model (predictive accuracy on held-out training data).+ * @nullable+ */+ readonly champion_holdout_auc: number | null+ /**+ * Realized online AUC of the current champion model, computed from mature predictions against actual outcomes.+ * @nullable+ */+ readonly champion_realized_auc: number | null+}++export interface PaginatedAutoresearchPipelineListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: AutoresearchPipelineApi[]+}++/**+ * Omit (or pass {"type": "event"}) to predict target_event; pass {"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted.+ */+export type AutoresearchPipelineCreateApiTargetDefinition =+ | {+ type: 'event'+ }+ | {+ type: 'action'+ /**+ * ID of the action to predict.+ * @minimum 1+ */+ action_id: number+ }++/**+ * Training population filter. Use {} for all identified users.+ */+export type AutoresearchPipelineCreateApiTrainingPopulation = { [key: string]: unknown }++/**+ * Inference population filter. Defaults to training_population if not set.+ */+export type AutoresearchPipelineCreateApiInferencePopulation = { [key: string]: unknown }++export interface AutoresearchPipelineCreateApi {+ /**+ * Display name for the pipeline.+ * @maxLength 255+ */+ name: string+ /** Optional free-text description. */+ description?: string+ /**+ * PostHog event name to predict, e.g. '$pageview' or 'signed_up'. Omit when predicting an action target (pass target_definition instead).+ * @maxLength 255+ */+ target_event?: string+ /** Omit (or pass {"type": "event"}) to predict target_event; pass {"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted. */+ target_definition?: AutoresearchPipelineCreateApiTargetDefinition+ /**+ * Prediction horizon in days (1-365). The model predicts whether the target event occurs within this window.+ * @minimum 1+ * @maximum 365+ */+ horizon_days?: number+ /**+ * How far back to look for training examples (7-730 days). Larger windows give more data but may include stale behavior. Default: 180.+ * @minimum 7+ * @maximum 730+ */+ training_lookback_days?: number+ /** Training population filter. Use {} for all identified users. */+ training_population?: AutoresearchPipelineCreateApiTrainingPopulation+ /** Inference population filter. Defaults to training_population if not set. */+ inference_population?: AutoresearchPipelineCreateApiInferencePopulation+ /**+ * Re-score the inference population every N days (1-365). Default: 1.+ * @minimum 1+ * @maximum 365+ */+ cadence_days?: number+ /**+ * Total training iterations allowed for the autoresearch loop (1-500). Default: 50.+ * @minimum 1+ * @maximum 500+ */+ iteration_budget?: number+ /**+ * Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ success_auc?: number | null+ /**+ * Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.+ * @minimum 1+ * @maximum 2147483647+ */+ plateau_iterations?: number+ /**+ * Person property name for the prediction score, e.g. 'predicted_p_pageview'. Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot start with $ (reserved for PostHog's own properties); must be unique among this project's non-archived pipelines.+ * @maxLength 255+ */+ output_person_property?: string+}++/**+ * Omit (or pass {"type": "event"}) to predict target_event; pass {"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted.+ */+export type PatchedAutoresearchPipelineCreateApiTargetDefinition =+ | {+ type: 'event'+ }+ | {+ type: 'action'+ /**+ * ID of the action to predict.+ * @minimum 1+ */+ action_id: number+ }++/**+ * Training population filter. Use {} for all identified users.+ */+export type PatchedAutoresearchPipelineCreateApiTrainingPopulation = { [key: string]: unknown }++/**+ * Inference population filter. Defaults to training_population if not set.+ */+export type PatchedAutoresearchPipelineCreateApiInferencePopulation = { [key: string]: unknown }++export interface PatchedAutoresearchPipelineCreateApi {+ /**+ * Display name for the pipeline.+ * @maxLength 255+ */+ name?: string+ /** Optional free-text description. */+ description?: string+ /**+ * PostHog event name to predict, e.g. '$pageview' or 'signed_up'. Omit when predicting an action target (pass target_definition instead).+ * @maxLength 255+ */+ target_event?: string+ /** Omit (or pass {"type": "event"}) to predict target_event; pass {"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted. */+ target_definition?: PatchedAutoresearchPipelineCreateApiTargetDefinition+ /**+ * Prediction horizon in days (1-365). The model predicts whether the target event occurs within this window.+ * @minimum 1+ * @maximum 365+ */+ horizon_days?: number+ /**+ * How far back to look for training examples (7-730 days). Larger windows give more data but may include stale behavior. Default: 180.+ * @minimum 7+ * @maximum 730+ */+ training_lookback_days?: number+ /** Training population filter. Use {} for all identified users. */+ training_population?: PatchedAutoresearchPipelineCreateApiTrainingPopulation+ /** Inference population filter. Defaults to training_population if not set. */+ inference_population?: PatchedAutoresearchPipelineCreateApiInferencePopulation+ /**+ * Re-score the inference population every N days (1-365). Default: 1.+ * @minimum 1+ * @maximum 365+ */+ cadence_days?: number+ /**+ * Total training iterations allowed for the autoresearch loop (1-500). Default: 50.+ * @minimum 1+ * @maximum 500+ */+ iteration_budget?: number+ /**+ * Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ success_auc?: number | null+ /**+ * Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.+ * @minimum 1+ * @maximum 2147483647+ */+ plateau_iterations?: number+ /**+ * Person property name for the prediction score, e.g. 'predicted_p_pageview'. Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot start with $ (reserved for PostHog's own properties); must be unique among this project's non-archived pipelines.+ * @maxLength 255+ */+ output_person_property?: string+}++export type AutoresearchListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.tsnew file mode 100644index 000000000000..159524857b38--- /dev/null+++ b/products/autoresearch/frontend/generated/api.ts@@ -0,0 +1,165 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type {+ AutoresearchListParams,+ AutoresearchPipelineApi,+ AutoresearchPipelineCreateApi,+ PaginatedAutoresearchPipelineListApi,+ PatchedAutoresearchPipelineCreateApi,+} from './api.schemas'++export const getAutoresearchListUrl = (projectId: string, params?: AutoresearchListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/autoresearch/?${stringifiedParams}`+ : `/api/projects/${projectId}/autoresearch/`+}++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const autoresearchList = async (+ projectId: string,+ params?: AutoresearchListParams,+ options?: RequestInit+): Promise<PaginatedAutoresearchPipelineListApi> => {+ return apiMutator<PaginatedAutoresearchPipelineListApi>(getAutoresearchListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getAutoresearchCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/autoresearch/`+}++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const autoresearchCreate = async (+ projectId: string,+ autoresearchPipelineCreateApi: AutoresearchPipelineCreateApi,+ options?: RequestInit+): Promise<AutoresearchPipelineApi> => {+ return apiMutator<AutoresearchPipelineApi>(getAutoresearchCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(autoresearchPipelineCreateApi),+ })+}++export const getAutoresearchRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/`+}++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const autoresearchRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<AutoresearchPipelineApi> => {+ return apiMutator<AutoresearchPipelineApi>(getAutoresearchRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getAutoresearchUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/`+}++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const autoresearchUpdate = async (+ projectId: string,+ id: string,+ autoresearchPipelineCreateApi: AutoresearchPipelineCreateApi,+ options?: RequestInit+): Promise<AutoresearchPipelineCreateApi> => {+ return apiMutator<AutoresearchPipelineCreateApi>(getAutoresearchUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(autoresearchPipelineCreateApi),+ })+}++export const getAutoresearchPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/`+}++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const autoresearchPartialUpdate = async (+ projectId: string,+ id: string,+ patchedAutoresearchPipelineCreateApi?: PatchedAutoresearchPipelineCreateApi,+ options?: RequestInit+): Promise<AutoresearchPipelineCreateApi> => {+ return apiMutator<AutoresearchPipelineCreateApi>(getAutoresearchPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedAutoresearchPipelineCreateApi),+ })+}++export const getAutoresearchDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/autoresearch/${id}/`+}++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const autoresearchDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getAutoresearchDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..374da72802dd--- /dev/null+++ b/products/autoresearch/frontend/generated/api.zod.ts@@ -0,0 +1,346 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const autoresearchCreateBodyNameMax = 255++export const autoresearchCreateBodyTargetEventMax = 255++export const autoresearchCreateBodyHorizonDaysMax = 365++export const autoresearchCreateBodyTrainingLookbackDaysMin = 7+export const autoresearchCreateBodyTrainingLookbackDaysMax = 730++export const autoresearchCreateBodyCadenceDaysMax = 365++export const autoresearchCreateBodyIterationBudgetMax = 500++export const autoresearchCreateBodySuccessAucMin = 0+export const autoresearchCreateBodySuccessAucMax = 1++export const autoresearchCreateBodyPlateauIterationsMax = 2147483647++export const autoresearchCreateBodyOutputPersonPropertyMax = 255++export const AutoresearchCreateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(autoresearchCreateBodyNameMax).describe('Display name for the pipeline.'),+ description: zod.string().optional().describe('Optional free-text description.'),+ target_event: zod+ .string()+ .max(autoresearchCreateBodyTargetEventMax)+ .optional()+ .describe(+ "PostHog event name to predict, e.g. '$pageview' or 'signed_up'. Omit when predicting an action target (pass target_definition instead)."+ ),+ target_definition: zod+ .union([+ zod+ .object({+ type: zod.enum(['event']),+ })+ .describe('Predict target_event. The default when target_definition is omitted.'),+ zod+ .object({+ type: zod.enum(['action']),+ action_id: zod.number().min(1).describe('ID of the action to predict.'),+ })+ .describe('Predict a PostHog action in this project.'),+ ])+ .optional()+ .describe(+ 'Omit (or pass {\"type\": \"event\"}) to predict target_event; pass {\"type\": \"action\", \"action_id\": N} to predict a PostHog action. No other shapes are accepted.'+ ),+ horizon_days: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyHorizonDaysMax)+ .optional()+ .describe(+ 'Prediction horizon in days (1-365). The model predicts whether the target event occurs within this window.'+ ),+ training_lookback_days: zod+ .number()+ .min(autoresearchCreateBodyTrainingLookbackDaysMin)+ .max(autoresearchCreateBodyTrainingLookbackDaysMax)+ .optional()+ .describe(+ 'How far back to look for training examples (7-730 days). Larger windows give more data but may include stale behavior. Default: 180.'+ ),+ training_population: zod+ .looseObject({})+ .optional()+ .describe('Training population filter. Use {} for all identified users.'),+ inference_population: zod+ .looseObject({})+ .optional()+ .describe('Inference population filter. Defaults to training_population if not set.'),+ cadence_days: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyCadenceDaysMax)+ .optional()+ .describe('Re-score the inference population every N days (1-365). Default: 1.'),+ iteration_budget: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyIterationBudgetMax)+ .optional()+ .describe('Total training iterations allowed for the autoresearch loop (1-500). Default: 50.'),+ success_auc: zod+ .number()+ .min(autoresearchCreateBodySuccessAucMin)+ .max(autoresearchCreateBodySuccessAucMax)+ .nullish()+ .describe('Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.'),+ plateau_iterations: zod+ .number()+ .min(1)+ .max(autoresearchCreateBodyPlateauIterationsMax)+ .optional()+ .describe('Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.'),+ output_person_property: zod+ .string()+ .max(autoresearchCreateBodyOutputPersonPropertyMax)+ .optional()+ .describe(+ "Person property name for the prediction score, e.g. 'predicted_p_pageview'. Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot start with $ (reserved for PostHog's own properties); must be unique among this project's non-archived pipelines."+ ),+})++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const autoresearchUpdateBodyNameMax = 255++export const autoresearchUpdateBodyTargetEventMax = 255++export const autoresearchUpdateBodyHorizonDaysMax = 365++export const autoresearchUpdateBodyTrainingLookbackDaysMin = 7+export const autoresearchUpdateBodyTrainingLookbackDaysMax = 730++export const autoresearchUpdateBodyCadenceDaysMax = 365++export const autoresearchUpdateBodyIterationBudgetMax = 500++export const autoresearchUpdateBodySuccessAucMin = 0+export const autoresearchUpdateBodySuccessAucMax = 1++export const autoresearchUpdateBodyPlateauIterationsMax = 2147483647++export const autoresearchUpdateBodyOutputPersonPropertyMax = 255++export const AutoresearchUpdateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(autoresearchUpdateBodyNameMax).describe('Display name for the pipeline.'),+ description: zod.string().optional().describe('Optional free-text description.'),+ target_event: zod+ .string()+ .max(autoresearchUpdateBodyTargetEventMax)+ .optional()+ .describe(+ "PostHog event name to predict, e.g. '$pageview' or 'signed_up'. Omit when predicting an action target (pass target_definition instead)."+ ),+ target_definition: zod+ .union([+ zod+ .object({+ type: zod.enum(['event']),+ })+ .describe('Predict target_event. The default when target_definition is omitted.'),+ zod+ .object({+ type: zod.enum(['action']),+ action_id: zod.number().min(1).describe('ID of the action to predict.'),+ })+ .describe('Predict a PostHog action in this project.'),+ ])+ .optional()+ .describe(+ 'Omit (or pass {\"type\": \"event\"}) to predict target_event; pass {\"type\": \"action\", \"action_id\": N} to predict a PostHog action. No other shapes are accepted.'+ ),+ horizon_days: zod+ .number()+ .min(1)+ .max(autoresearchUpdateBodyHorizonDaysMax)+ .optional()+ .describe(+ 'Prediction horizon in days (1-365). The model predicts whether the target event occurs within this window.'+ ),+ training_lookback_days: zod+ .number()+ .min(autoresearchUpdateBodyTrainingLookbackDaysMin)+ .max(autoresearchUpdateBodyTrainingLookbackDaysMax)+ .optional()+ .describe(+ 'How far back to look for training examples (7-730 days). Larger windows give more data but may include stale behavior. Default: 180.'+ ),+ training_population: zod+ .looseObject({})+ .optional()+ .describe('Training population filter. Use {} for all identified users.'),+ inference_population: zod+ .looseObject({})+ .optional()+ .describe('Inference population filter. Defaults to training_population if not set.'),+ cadence_days: zod+ .number()+ .min(1)+ .max(autoresearchUpdateBodyCadenceDaysMax)+ .optional()+ .describe('Re-score the inference population every N days (1-365). Default: 1.'),+ iteration_budget: zod+ .number()+ .min(1)+ .max(autoresearchUpdateBodyIterationBudgetMax)+ .optional()+ .describe('Total training iterations allowed for the autoresearch loop (1-500). Default: 50.'),+ success_auc: zod+ .number()+ .min(autoresearchUpdateBodySuccessAucMin)+ .max(autoresearchUpdateBodySuccessAucMax)+ .nullish()+ .describe('Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.'),+ plateau_iterations: zod+ .number()+ .min(1)+ .max(autoresearchUpdateBodyPlateauIterationsMax)+ .optional()+ .describe('Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.'),+ output_person_property: zod+ .string()+ .max(autoresearchUpdateBodyOutputPersonPropertyMax)+ .optional()+ .describe(+ "Person property name for the prediction score, e.g. 'predicted_p_pageview'. Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot start with $ (reserved for PostHog's own properties); must be unique among this project's non-archived pipelines."+ ),+})++/**+ * Manage autoresearch prediction pipelines.+ *+ * A pipeline defines a target event, population, and horizon. The autoresearch+ * training loop finds the best predictive recipe; the inference workflow scores+ * users daily and emits autoresearch_prediction events.+ */+export const autoresearchPartialUpdateBodyNameMax = 255++export const autoresearchPartialUpdateBodyTargetEventMax = 255++export const autoresearchPartialUpdateBodyHorizonDaysMax = 365++export const autoresearchPartialUpdateBodyTrainingLookbackDaysMin = 7+export const autoresearchPartialUpdateBodyTrainingLookbackDaysMax = 730++export const autoresearchPartialUpdateBodyCadenceDaysMax = 365++export const autoresearchPartialUpdateBodyIterationBudgetMax = 500++export const autoresearchPartialUpdateBodySuccessAucMin = 0+export const autoresearchPartialUpdateBodySuccessAucMax = 1++export const autoresearchPartialUpdateBodyPlateauIterationsMax = 2147483647++export const autoresearchPartialUpdateBodyOutputPersonPropertyMax = 255++export const AutoresearchPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(autoresearchPartialUpdateBodyNameMax).optional().describe('Display name for the pipeline.'),+ description: zod.string().optional().describe('Optional free-text description.'),+ target_event: zod+ .string()+ .max(autoresearchPartialUpdateBodyTargetEventMax)+ .optional()+ .describe(+ "PostHog event name to predict, e.g. '$pageview' or 'signed_up'. Omit when predicting an action target (pass target_definition instead)."+ ),+ target_definition: zod+ .union([+ zod+ .object({+ type: zod.enum(['event']),+ })+ .describe('Predict target_event. The default when target_definition is omitted.'),+ zod+ .object({+ type: zod.enum(['action']),+ action_id: zod.number().min(1).describe('ID of the action to predict.'),+ })+ .describe('Predict a PostHog action in this project.'),+ ])+ .optional()+ .describe(+ 'Omit (or pass {\"type\": \"event\"}) to predict target_event; pass {\"type\": \"action\", \"action_id\": N} to predict a PostHog action. No other shapes are accepted.'+ ),+ horizon_days: zod+ .number()+ .min(1)+ .max(autoresearchPartialUpdateBodyHorizonDaysMax)+ .optional()+ .describe(+ 'Prediction horizon in days (1-365). The model predicts whether the target event occurs within this window.'+ ),+ training_lookback_days: zod+ .number()+ .min(autoresearchPartialUpdateBodyTrainingLookbackDaysMin)+ .max(autoresearchPartialUpdateBodyTrainingLookbackDaysMax)+ .optional()+ .describe(+ 'How far back to look for training examples (7-730 days). Larger windows give more data but may include stale behavior. Default: 180.'+ ),+ training_population: zod+ .looseObject({})+ .optional()+ .describe('Training population filter. Use {} for all identified users.'),+ inference_population: zod+ .looseObject({})+ .optional()+ .describe('Inference population filter. Defaults to training_population if not set.'),+ cadence_days: zod+ .number()+ .min(1)+ .max(autoresearchPartialUpdateBodyCadenceDaysMax)+ .optional()+ .describe('Re-score the inference population every N days (1-365). Default: 1.'),+ iteration_budget: zod+ .number()+ .min(1)+ .max(autoresearchPartialUpdateBodyIterationBudgetMax)+ .optional()+ .describe('Total training iterations allowed for the autoresearch loop (1-500). Default: 50.'),+ success_auc: zod+ .number()+ .min(autoresearchPartialUpdateBodySuccessAucMin)+ .max(autoresearchPartialUpdateBodySuccessAucMax)+ .nullish()+ .describe('Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.'),+ plateau_iterations: zod+ .number()+ .min(1)+ .max(autoresearchPartialUpdateBodyPlateauIterationsMax)+ .optional()+ .describe('Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.'),+ output_person_property: zod+ .string()+ .max(autoresearchPartialUpdateBodyOutputPersonPropertyMax)+ .optional()+ .describe(+ "Person property name for the prediction score, e.g. 'predicted_p_pageview'. Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot start with $ (reserved for PostHog's own properties); must be unique among this project's non-archived pipelines."+ ),+})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ff3ff46979e0..cbe9058ad50f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11136,6 +11136,229 @@ export namespace Schemas {P4: 'P4',} as const;+ /**+ * Resolved target definition: {"type": "event"} or {"type": "action", "action_id": N}.+ */+ export type AutoresearchPipelineTargetDefinition = {+ type: 'event';+ } | {+ type: 'action';+ /**+ * ID of the action to predict.+ * @minimum 1+ */+ action_id: number;+ };++ /**+ * Population used for training. Defines which users can appear as training examples.+ */+ export type AutoresearchPipelineTrainingPopulation = { [key: string]: unknown };++ /**+ * Population scored daily. Typically broader than the training population.+ */+ export type AutoresearchPipelineInferencePopulation = { [key: string]: unknown };++ /**+ * * `draft` - Draft+ * * `bootstrapping` - Bootstrapping+ * * `running` - Running+ * * `converged` - Converged+ * * `paused` - Paused+ * * `archived` - Archived+ */+ export type AutoresearchPipelineStatusEnum = typeof AutoresearchPipelineStatusEnum[keyof typeof AutoresearchPipelineStatusEnum];+++ export const AutoresearchPipelineStatusEnum = {+ Draft: 'draft',+ Bootstrapping: 'bootstrapping',+ Running: 'running',+ Converged: 'converged',+ Paused: 'paused',+ Archived: 'archived',+ } as const;++ export interface AutoresearchPipeline {+ /** Unique UUID of this pipeline. */+ readonly id: string;+ /**+ * Display name for the pipeline.+ * @maxLength 255+ */+ name: string;+ /** Optional free-text description. */+ description?: string;+ /**+ * PostHog event name to predict, e.g. '$pageview' or 'signed_up'.+ * @maxLength 255+ */+ target_event: string;+ /** Resolved target definition: {"type": "event"} or {"type": "action", "action_id": N}. */+ target_definition: AutoresearchPipelineTargetDefinition;+ /**+ * Prediction horizon in days. The model predicts whether the target event occurs within this window.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ horizon_days?: number;+ /**+ * How far back to look for training examples. Larger windows give more data but may include stale behavior.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ training_lookback_days?: number;+ /** Population used for training. Defines which users can appear as training examples. */+ training_population: AutoresearchPipelineTrainingPopulation;+ /** Population scored daily. Typically broader than the training population. */+ inference_population: AutoresearchPipelineInferencePopulation;+ /**+ * Re-score the inference population every N days.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ cadence_days?: number;+ /**+ * Total training iterations allowed for the autoresearch loop.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ iteration_budget?: number;+ /** Iterations remaining in the current budget. */+ readonly iteration_budget_remaining: number;+ /**+ * Target AUC threshold. Training stops early if this score is reached.+ * @nullable+ */+ success_auc?: number | null;+ /**+ * Stop training if no AUC improvement is seen in this many consecutive iterations.+ * @minimum -2147483648+ * @maximum 2147483647+ */+ plateau_iterations?: number;+ /**+ * Person property name that stores the daily prediction score, e.g. 'predicted_p_pageview'.+ * @maxLength 255+ */+ output_person_property?: string;+ /** Pipeline lifecycle status: draft, bootstrapping, running, converged, paused, or archived.+ *+ * * `draft` - Draft+ * * `bootstrapping` - Bootstrapping+ * * `running` - Running+ * * `converged` - Converged+ * * `paused` - Paused+ * * `archived` - Archived */+ readonly status: AutoresearchPipelineStatusEnum;+ readonly created_by: UserBasic;+ readonly created_at: string;+ readonly updated_at: string;+ /**+ * Timestamp of the most recent completed inference run.+ * @nullable+ */+ readonly last_scored_at: string | null;+ /**+ * Offline holdout AUC of the current champion model (predictive accuracy on held-out training data).+ * @nullable+ */+ readonly champion_holdout_auc: number | null;+ /**+ * Realized online AUC of the current champion model, computed from mature predictions against actual outcomes.+ * @nullable+ */+ readonly champion_realized_auc: number | null;+ }++ /**+ * Omit (or pass {"type": "event"}) to predict target_event; pass {"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted.+ */+ export type AutoresearchPipelineCreateTargetDefinition = {+ type: 'event';+ } | {+ type: 'action';+ /**+ * ID of the action to predict.+ * @minimum 1+ */+ action_id: number;+ };++ /**+ * Training population filter. Use {} for all identified users.+ */+ export type AutoresearchPipelineCreateTrainingPopulation = { [key: string]: unknown };++ /**+ * Inference population filter. Defaults to training_population if not set.+ */+ export type AutoresearchPipelineCreateInferencePopulation = { [key: string]: unknown };++ export interface AutoresearchPipelineCreate {+ /**+ * Display name for the pipeline.+ * @maxLength 255+ */+ name: string;+ /** Optional free-text description. */+ description?: string;+ /**+ * PostHog event name to predict, e.g. '$pageview' or 'signed_up'. Omit when predicting an action target (pass target_definition instead).+ * @maxLength 255+ */+ target_event?: string;+ /** Omit (or pass {"type": "event"}) to predict target_event; pass {"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted. */+ target_definition?: AutoresearchPipelineCreateTargetDefinition;+ /**+ * Prediction horizon in days (1-365). The model predicts whether the target event occurs within this window.+ * @minimum 1+ * @maximum 365+ */+ horizon_days?: number;+ /**+ * How far back to look for training examples (7-730 days). Larger windows give more data but may include stale behavior. Default: 180.+ * @minimum 7+ * @maximum 730+ */+ training_lookback_days?: number;+ /** Training population filter. Use {} for all identified users. */+ training_population?: AutoresearchPipelineCreateTrainingPopulation;+ /** Inference population filter. Defaults to training_population if not set. */+ inference_population?: AutoresearchPipelineCreateInferencePopulation;+ /**+ * Re-score the inference population every N days (1-365). Default: 1.+ * @minimum 1+ * @maximum 365+ */+ cadence_days?: number;+ /**+ * Total training iterations allowed for the autoresearch loop (1-500). Default: 50.+ * @minimum 1+ * @maximum 500+ */+ iteration_budget?: number;+ /**+ * Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ success_auc?: number | null;+ /**+ * Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.+ * @minimum 1+ * @maximum 2147483647+ */+ plateau_iterations?: number;+ /**+ * Person property name for the prediction score, e.g. 'predicted_p_pageview'. Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot start with $ (reserved for PostHog's own properties); must be unique among this project's non-archived pipelines.+ * @maxLength 255+ */+ output_person_property?: string;+ }+/*** Discovered detail fields and their value distributions.*/@@ -56468,6 +56691,15 @@ export namespace Schemas {results?: AsyncDeletionStatus[];}+ export interface PaginatedAutoresearchPipelineList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: AutoresearchPipeline[];+ }+export interface PaginatedBatchExportBackfillList {/** @nullable */next?: string | null;@@ -63625,6 +63857,93 @@ export namespace Schemas {readonly updated_at?: string | null;}+ /**+ * Omit (or pass {"type": "event"}) to predict target_event; pass {"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted.+ */+ export type PatchedAutoresearchPipelineCreateTargetDefinition = {+ type: 'event';+ } | {+ type: 'action';+ /**+ * ID of the action to predict.+ * @minimum 1+ */+ action_id: number;+ };++ /**+ * Training population filter. Use {} for all identified users.+ */+ export type PatchedAutoresearchPipelineCreateTrainingPopulation = { [key: string]: unknown };++ /**+ * Inference population filter. Defaults to training_population if not set.+ */+ export type PatchedAutoresearchPipelineCreateInferencePopulation = { [key: string]: unknown };++ export interface PatchedAutoresearchPipelineCreate {+ /**+ * Display name for the pipeline.+ * @maxLength 255+ */+ name?: string;+ /** Optional free-text description. */+ description?: string;+ /**+ * PostHog event name to predict, e.g. '$pageview' or 'signed_up'. Omit when predicting an action target (pass target_definition instead).+ * @maxLength 255+ */+ target_event?: string;+ /** Omit (or pass {"type": "event"}) to predict target_event; pass {"type": "action", "action_id": N} to predict a PostHog action. No other shapes are accepted. */+ target_definition?: PatchedAutoresearchPipelineCreateTargetDefinition;+ /**+ * Prediction horizon in days (1-365). The model predicts whether the target event occurs within this window.+ * @minimum 1+ * @maximum 365+ */+ horizon_days?: number;+ /**+ * How far back to look for training examples (7-730 days). Larger windows give more data but may include stale behavior. Default: 180.+ * @minimum 7+ * @maximum 730+ */+ training_lookback_days?: number;+ /** Training population filter. Use {} for all identified users. */+ training_population?: PatchedAutoresearchPipelineCreateTrainingPopulation;+ /** Inference population filter. Defaults to training_population if not set. */+ inference_population?: PatchedAutoresearchPipelineCreateInferencePopulation;+ /**+ * Re-score the inference population every N days (1-365). Default: 1.+ * @minimum 1+ * @maximum 365+ */+ cadence_days?: number;+ /**+ * Total training iterations allowed for the autoresearch loop (1-500). Default: 50.+ * @minimum 1+ * @maximum 500+ */+ iteration_budget?: number;+ /**+ * Target AUC threshold (0-1). Training stops early if reached. Default: 0.75.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ success_auc?: number | null;+ /**+ * Stop training if no improvement in this many consecutive iterations (at least 1). Default: 10.+ * @minimum 1+ * @maximum 2147483647+ */+ plateau_iterations?: number;+ /**+ * Person property name for the prediction score, e.g. 'predicted_p_pageview'. Auto-derived from target_event if omitted. Letters, digits, and _ $ . - only, and it cannot start with $ (reserved for PostHog's own properties); must be unique among this project's non-archived pipelines.+ * @maxLength 255+ */+ output_person_property?: string;+ }+/*** Request body for create/partial_update on BatchExportViewSet.*@@ -96244,6 +96563,17 @@ export namespace Schemas {offset?: number;};+ export type AutoresearchListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type BatchExportsListParams = {/*** Number of results to return per page.