Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(autoresearch): make writing scores to person profiles opt-in (#116276)

posthog[bot]8fd086bea028
diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txt
index f1bed0ee997d..5069a1eed4c3 100644
--- a/.github/new-events-schema-targets.txt
+++ b/.github/new-events-schema-targets.txt
@@ -52,6 +52,7 @@ posthog/tasks/test/test_ai_observability_usage_report.py
posthog/tasks/test/test_usage_report.py
posthog/temporal/tests/test_clickhouse.py
posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+products/autoresearch/backend/inference/test_person_property.py
products/batch_exports/backend/tests/api/test_serializers.py
products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py
products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ffad414cd7ae..f13969ff56e6 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6627,37 +6627,37 @@ snapshots:
products-autoresearch-model-detail-scene--agent-research-wide--wide--light:
hash: v1.k794b7964.a8249c53caa4af1687731fd2fd05785c8edf78cdb4e9c8c1250bb064585249ca.G_lrb4ODihzN6JFOpzGe1T2zGGhL_54bVGOc2XE7BQk
products-autoresearch-model-detail-scene--coverage-below-cap--narrow--dark:
- hash: v1.k794b7964.152ee821492c266c89b740640ef7a91a4f67257a384bc2c6d526cc84df685d14.Rw2tjHmhWsFwm2-n-i1sOVP227F8AkhWTS4Lt96rV8k
+ hash: v1.k794b7964.e0ad2e627d68765547c107f5f8d1f2ad214de6b3c7fddcaf973c8d0c47abd3e8.iRRLGCI7qO0vmHNg6YvjDatNxsPN2em2kVattLKAiGs
products-autoresearch-model-detail-scene--coverage-below-cap--narrow--light:
- hash: v1.k794b7964.49da15b6115df1ac9364011595574996e88cf019db42521523a5c2baa9f9b1ed.OViBJ-jKe1xbmR5VT9GEBzjaKGOlGfOmy3vt55yJzlw
+ hash: v1.k794b7964.aec1ae6a00c7427670f6135dae52d56677c54fb53e5758e69b7346c16cdae37b.2iZR9IIkb6y6sxGAiKD2EsI-u5tDSWBgkN907mjpTDs
products-autoresearch-model-detail-scene--coverage-below-cap--wide--dark:
- hash: v1.k794b7964.6a7b41bb0e7beedd0bb605cd56099c6e0b68e0763f05ea70466b0792b01bea65.rxmdkr5Hds-9epbgQHCU1jhMN6pjWxhse5uOkXxKcqY
+ hash: v1.k794b7964.cc04bd7f5ec373525138bbecf02f80bd8cbc6394592ee4b42c85c57a1d514f3f.i-VZTvX_rMYfziwa8kLZPsPDl20dpqS7u8oeYhRG3A4
products-autoresearch-model-detail-scene--coverage-below-cap--wide--light:
- hash: v1.k794b7964.b7d2d5609f5244526f724f4bd1f985809ed173037c3f12d2186b6a84b33a2a40.KPa_6jMPIsFyDRBQ8x0OYBaQRabumSRljZF0V0Ppfbk
+ hash: v1.k794b7964.44190881d804f06a308b936579d5835132559fbc010c71d27e0da3ff546682a7.MEntQARRTPLytO6A5BvDIzvK99ymXL56wLee9XBJnEM
products-autoresearch-model-detail-scene--coverage-rolling-mid-cycle--narrow--dark:
- hash: v1.k794b7964.0e9f6a634a0ce036704e1ae40a3a269e520bb35965107459543d845835129f58.8wO2TTB9MQvDYz419LZaHyj792zNN0nuSgWi9IOkcpI
+ hash: v1.k794b7964.ccd7a20ff535fe95e61babc516fa43a468dc24c2f8797b31d1048e968523e318.GuPa2Ead-Gt6rv6bqLx3cWuwKu2sgPjzRNvf3404FoA
products-autoresearch-model-detail-scene--coverage-rolling-mid-cycle--narrow--light:
- hash: v1.k794b7964.600621aa236383eef70dc1f93a10227a8ce6dbdcd52647237d8c9bcb8cdbfe9e._-R_fAQOI97_1m_hsbtEMILj9l19VGbisuIuqd_69zo
+ hash: v1.k794b7964.971dd01d1fc5af25292cea1c52873a730d10908ee5e06e52a203763d2fb9d462.8TESrElkTZgtke-2_6CLBvTaXlBFtix5WFKH2aa7s7M
products-autoresearch-model-detail-scene--coverage-rolling-mid-cycle--wide--dark:
- hash: v1.k794b7964.9de0a95c8650d81633b5a014306cc9dba9e2fa0fbf732a22c4b43a06e298a677.ShGdwT0g2nNVVdCP1R7qxV6Q0lVKhONgs9mNWTA1UnE
+ hash: v1.k794b7964.43c93b09a6f48e0af0bf0c96644caf9543bc11a3d36ba66c93aaf22e3f37fa32.-vNHWJfaOLjIHwARFcZwmzKTcaU8OJ90PkypEZPrec8
products-autoresearch-model-detail-scene--coverage-rolling-mid-cycle--wide--light:
- hash: v1.k794b7964.25e07fb2d2107ed96de9d03d0428f51ae61eb16f841050869a581d723258c959.KRtSWvEhwEuncr2ol08z8iIu7V2xxsbgwSNt85R1R_Q
+ hash: v1.k794b7964.e295509a5e39839aab5363bffc3375d6cbd345c5a9da070df38540bb0c891641.wRuc8EBh3yd38_qxX7vQFEZUIDfC1fXtfrdEqjxW-dA
products-autoresearch-model-detail-scene--coverage-with-failed-runs--narrow--dark:
- hash: v1.k794b7964.5c238af99fab1ef0a4bef33f7837051ff977331581e39db887102bd673d2b895.bOwR6Kx4sbqPEEBS0t_ZcOqavzfAZ6gDOuA6z333akQ
+ hash: v1.k794b7964.5963446ff4d2fbd24e2f99323132a7c9cf4377887132724526847177d1b9197b.BBEs6WQWgAHV9bN-SZqCzxB5eH1Rhc2b6IwFlfQeWFY
products-autoresearch-model-detail-scene--coverage-with-failed-runs--narrow--light:
- hash: v1.k794b7964.fcc55a250637ae170122988f33efb7fffb8bb56e5c35317adf7456eb1f84387c.9eZcjMzAx5TX821Zl8bvWDoL3QSkSw-fNCzb4xKClF4
+ hash: v1.k794b7964.b7b5786cfa01e6ea48fdb3b0c706d6b95ea0c7246c1584543e6c628585c5a5b5.J9sJ5wYjlIbYpFB5on3rT9A675Rm3GWfVQoP1dYJnGo
products-autoresearch-model-detail-scene--coverage-with-failed-runs--wide--dark:
- hash: v1.k794b7964.9dd89ae970aca27680b939c019f8059a5d663877792ef275e74d6168bdc9dde5.KZj-dscfV0eEI0FfEhY7MMHj0wlwrl9RlRAfmi2sHro
+ hash: v1.k794b7964.073ed0d4859386827dd0e45de3cf5eb857867e74e1b44f2fa4ede4a108742cca.hVQJteiYVN-fx70VzB55DOgKQVvHoDNtPEqzxqho5Ko
products-autoresearch-model-detail-scene--coverage-with-failed-runs--wide--light:
- hash: v1.k794b7964.f14c2b3b63be611e3cdeeed2245735275173023ebe329b5fc1c59db97eec06a7.4gkAnNzehTz5TnzTvL5ZRcGFFtBZuQHrqec9fivPXAA
+ hash: v1.k794b7964.e50fd4ee2847fe0504c0aebc10c7eedb34d1ed4d2eff05b68848bc6f45b9f0d9.3zl510wgOjWMfOqmOycvoGw-M4D9VGx-OBni0PdNeok
products-autoresearch-model-detail-scene--narrow--narrow--dark:
- hash: v1.k794b7964.e2ce91abe916cc3d09981c402e94c5955916495ea349799a305f81701d29b614.8X3qhSGbaIwj_LXSOsSn_Z4ltPGVduDSZZWBzFM9Nmc
+ hash: v1.k794b7964.8d62dc0e26c677229f657685e9a91ff35456e8ea8a947afa92782e2b3359eb4e.YtQHUt83vFWkDF3SKK0iSQnyLikqzTYog0_46H_jOEg
products-autoresearch-model-detail-scene--narrow--narrow--light:
- hash: v1.k794b7964.34f873e1e7b38e50ef3d10247e46bc4b7ba1783d034edf72aa481272e6991cb1.xFlmMX2BFoLZvwPTTJTRCkc_jvPBk96TmD_dkIHv-ks
+ hash: v1.k794b7964.0f661f759d129a6f7471dad9eb7ea718b277e9bc2fb4a358266c88728563a7b0.rD84hUqYFrkI6ozIGHI3WlGTQ0wABa-drzyJtcL7wKQ
products-autoresearch-model-detail-scene--wide--wide--dark:
- hash: v1.k794b7964.45c778a22654973af271374665ae90b360501f18f1120c1e6080d00bf3e6478a.yenXnAEGj_qMppblaiuW3r5phbVYzqT3J-nD4aPizRk
+ hash: v1.k794b7964.08cb30b029cdb46e530a0849f3c1912f695d42456cbca5d4b195dfb42adfef0f.JFZqnMmbLhsHPnTYbmsXhsHyD-XTqR5OG9y1XOQbHRM
products-autoresearch-model-detail-scene--wide--wide--light:
- hash: v1.k794b7964.0e0a17654d0069447e8fe931049ded5d55c96e6aa3c60a1b601282e396ce334d.JIJB_oDt2a3xzX9u0TS72b1GwQY-i1Xu9wWUaJ0jsRQ
+ hash: v1.k794b7964.ecad442bd20835b444ce550f04430e1618cfd5f55a5ee820bd8ab22c58f0092a.B5JEmPyIbg5WOLnSOT3Z1v8UXRfjf7_dGwCw6quT8-s
products-autoresearch-probability-histogram--bimodal--dark:
hash: v1.k794b7964.f95d3982e7c08f2e1b51655520f15e37293aa98e5ca87126a5653d2300bd776b.2G0LsuSx-SLqWn1Oxm_bUHSqfeDPFF6Pof0vDvhZEHM
products-autoresearch-probability-histogram--bimodal--light:
diff --git a/products/autoresearch/AGENTS.md b/products/autoresearch/AGENTS.md
index 062c78218435..5b7da3ceaaec 100644
--- a/products/autoresearch/AGENTS.md
+++ b/products/autoresearch/AGENTS.md
@@ -17,7 +17,7 @@ AutoresearchPipeline the standing question (target, population, horizon
├─ AutoresearchTrainingRun one attempt to find a better model
│ └─ AutoresearchIteration one experiment inside that attempt (kept / discarded)
├─ AutoresearchModel a trained model, role = champion | challenger | archived
- ├─ AutoresearchRun one execution of inference or validation
+ ├─ AutoresearchRun one execution of inference, validation, or person property cleanup
└─ AutoresearchSuggestion a human- or agent-authored hypothesis for the next run to explore
```
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index 25c95003978e..89eb26d5b725 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -22,6 +22,8 @@ from django.db import transaction
from django.db.models import Count, F, Prefetch, Q
from django.utils import timezone as django_timezone
+import structlog
+
from posthog.dataclasses import frozen
from posthog.models.team import Team
from posthog.models.user import User
@@ -108,6 +110,8 @@ from .contracts import (
ValidationWarning,
)
+logger = structlog.get_logger(__name__)
+
AUTORESEARCH_FLAG = "autoresearch"
@@ -376,6 +380,7 @@ def _pipeline_to_contract(
success_auc=row.success_auc,
plateau_iterations=row.plateau_iterations,
output_person_property=row.output_person_property,
+ write_person_property=row.write_person_property,
status=row.status,
created_by=row.created_by,
created_at=row.created_at,
@@ -603,6 +608,19 @@ 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 pipeline_writes_person_property(team_id: int, pipeline_id: str | UUID) -> bool:
+ """Whether a live pipeline writes its output property, so archiving or deleting it starts a cleanup."""
+ pipeline_uuid = _as_uuid(pipeline_id)
+ if pipeline_uuid is None:
+ return False
+ return (
+ AutoresearchPipeline.objects.for_team(team_id)
+ .exclude(status=AutoresearchPipeline.Status.ARCHIVED)
+ .filter(pk=pipeline_uuid, write_person_property=True)
+ .exists()
+ )
+
+
def create_pipeline(team_id: int, *, fields: dict[str, Any], created_by: Any) -> Pipeline:
row = AutoresearchPipeline.objects.create(
team_id=team_id,
@@ -638,11 +656,15 @@ def _changes_model_definition(row: AutoresearchPipeline, fields: dict[str, Any])
return False
-def update_pipeline(team_id: int, pipeline_id: str | UUID, *, fields: dict[str, Any]) -> Pipeline:
+def update_pipeline(
+ team_id: int, pipeline_id: str | UUID, *, fields: dict[str, Any], user_id: int | None = None
+) -> Pipeline:
"""Update a pipeline. Refuses a change to what it predicts while a run is live or once a model exists.
The row lock serializes this with ``start_training``, so a run cannot start between the
live-run check and the write, and a concurrent delete waits instead of racing the save.
+
+ Turning ``write_person_property`` off starts a cleanup that removes the output property from persons.
"""
pipeline_uuid = _as_uuid(pipeline_id)
if pipeline_uuid is None:
@@ -668,18 +690,32 @@ def update_pipeline(team_id: int, pipeline_id: str | UUID, *, fields: dict[str,
"What the pipeline predicts cannot change after a model has been trained. "
"Create a new pipeline to predict a different target."
)
+ renames_property = (
+ fields.get("output_person_property", row.output_person_property) != row.output_person_property
+ )
+ # A rename while writing would leave the old property on persons with no cleanup to remove it.
+ if row.write_person_property and fields.get("write_person_property", True) and renames_property:
+ raise AutoresearchConflict(
+ "Turn off writing scores to person profiles before you rename the person property. "
+ "Turning it off removes the old property from the people this model scored."
+ )
+ stops_writing = row.write_person_property and fields.get("write_person_property") is False
+ cleanup_property = row.output_person_property
for key, value in fields.items():
setattr(row, key, value)
# Only the request's fields, so the write never touches a column the request did not set.
row.save(update_fields=[*fields, "updated_at"])
+ if stops_writing:
+ _queue_property_cleanup(row, output_property=cleanup_property, user_id=user_id)
return _pipeline_with_champion(row)
-def delete_pipeline(team_id: int, pipeline_id: str | UUID) -> None:
+def delete_pipeline(team_id: int, pipeline_id: str | UUID, *, user_id: int | None = None) -> None:
"""Delete a pipeline and its rows. Refused while a training run is live.
The TaskRun is linked only by id, so a cascade would leave its paid sandbox running with
- nothing to report to.
+ nothing to report to. A pipeline that wrote its output property starts a cleanup, which
+ records no run because the runs go with the pipeline.
"""
pipeline_uuid = _as_uuid(pipeline_id)
if pipeline_uuid is None:
@@ -696,6 +732,8 @@ def delete_pipeline(team_id: int, pipeline_id: str | UUID) -> None:
raise PipelineNotFound("Pipeline not found.")
if _has_live_training_run(team_id, row):
raise AutoresearchConflict("A training run is in progress. Wait for it to finish before deleting.")
+ if row.write_person_property:
+ _queue_property_cleanup(row, output_property=row.output_person_property, user_id=user_id, record_run=False)
row.delete()
@@ -707,11 +745,12 @@ _STATUS_TRANSITION_SOURCES: dict[str, frozenset[str]] = {
}
-def set_pipeline_status(team_id: int, pipeline_id: str | UUID, *, status: str) -> Pipeline:
+def set_pipeline_status(team_id: int, pipeline_id: str | UUID, *, status: str, user_id: int | None = None) -> Pipeline:
"""Archive, pause, or resume a pipeline.
The row lock serializes this with a concurrent lifecycle change and with ``start_training``,
so a stale read cannot revive an archived pipeline, and archival cannot race a new run.
+ Archiving a pipeline that writes its output property starts a cleanup.
"""
pipeline_uuid = _as_uuid(pipeline_id)
if pipeline_uuid is None:
@@ -734,9 +773,89 @@ def set_pipeline_status(team_id: int, pipeline_id: str | UUID, *, status: str) -
raise AutoresearchConflict("A training run is in progress. Wait for it to finish before archiving.")
row.status = status
row.save(update_fields=["status", "updated_at"])
+ if status == AutoresearchPipeline.Status.ARCHIVED and row.write_person_property:
+ _queue_property_cleanup(row, output_property=row.output_person_property, user_id=user_id)
return _pipeline_with_champion(row)
+def _queue_property_cleanup(
+ row: AutoresearchPipeline, *, output_property: str, user_id: int | None, record_run: bool = True
+) -> None:
+ """Start the cleanup workflow once the caller's transaction commits, so it reads the committed setting."""
+ if not output_property:
+ return
+ run = (
+ AutoresearchRun.objects.create(
+ pipeline=row,
+ run_type=AutoresearchRun.RunType.PROPERTY_CLEANUP,
+ status=AutoresearchRun.Status.PENDING,
+ started_at=django_timezone.now(),
+ metrics={"output_person_property": output_property},
+ )
+ if record_run
+ else None
+ )
+ # Read the ids now: a deleted row has no pk by the time the commit callback runs.
+ team_id, pipeline_id, written_since = row.team_id, str(row.pk), row.created_at.isoformat()
+ transaction.on_commit(
+ lambda: _start_property_cleanup(
+ team_id=team_id,
+ pipeline_id=pipeline_id,
+ output_property=output_property,
+ written_since=written_since,
+ run=run,
+ user_id=user_id,
+ )
+ )
+
+
+def _start_property_cleanup(
+ *,
+ team_id: int,
+ pipeline_id: str,
+ output_property: str,
+ written_since: str,
+ run: AutoresearchRun | None,
+ user_id: int | None,
+) -> None:
+ # The Temporal client and the workflow module load only when a cleanup starts.
+ from posthog.temporal.common.client import sync_connect # noqa: PLC0415
+
+ from ..temporal.workflows import ( # noqa: PLC0415
+ PROPERTY_CLEANUP_WORKFLOW_TIMEOUT,
+ AutoresearchPropertyCleanupWorkflow,
+ PropertyCleanupWorkflowInput,
+ property_cleanup_workflow_id,
+ )
+
+ try:
+ client = sync_connect()
+ asyncio.run(
+ client.start_workflow(
+ AutoresearchPropertyCleanupWorkflow.run,
+ PropertyCleanupWorkflowInput(
+ pipeline_id=pipeline_id,
+ team_id=team_id,
+ output_property=output_property,
+ written_since=written_since,
+ run_id=str(run.pk) if run else None,
+ user_id=user_id,
+ ),
+ id=property_cleanup_workflow_id(pipeline_id, str(run.pk) if run else str(uuid4())),
+ task_queue=settings.AUTORESEARCH_TASK_QUEUE,
+ execution_timeout=PROPERTY_CLEANUP_WORKFLOW_TIMEOUT,
+ )
+ )
+ except Exception as exc:
+ logger.exception("autoresearch_property_cleanup_start_failed", pipeline_id=pipeline_id)
+ if run is not None:
+ AutoresearchRun.objects.for_team(team_id).filter(pk=run.pk).update(
+ status=AutoresearchRun.Status.FAILED,
+ error=f"Could not start the property cleanup: {exc}"[:2000],
+ completed_at=django_timezone.now(),
+ )
+
+
def _has_live_training_run(team_id: int, pipeline: AutoresearchPipeline) -> bool:
return (
AutoresearchTrainingRun.objects.for_team(team_id)
@@ -774,6 +893,7 @@ def get_pipeline_definition(team_id: int, pipeline_id: str | UUID) -> PipelineWr
success_auc=row.success_auc,
plateau_iterations=row.plateau_iterations,
output_person_property=row.output_person_property,
+ write_person_property=row.write_person_property,
)
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 6dc28c8fb7d8..985af0ea28a9 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -133,6 +133,7 @@ class Pipeline:
success_auc: float | None
plateau_iterations: int
output_person_property: str
+ write_person_property: bool
status: str
created_by: Any
created_at: datetime
@@ -322,6 +323,7 @@ class PipelineWrite:
success_auc: float | None = None
plateau_iterations: int = 10
output_person_property: str = ""
+ write_person_property: bool = False
# ── Validation and template contracts ──────────────────────────────────────
diff --git a/products/autoresearch/backend/inference/AGENTS.md b/products/autoresearch/backend/inference/AGENTS.md
index 9919cad07084..e43de498297e 100644
--- a/products/autoresearch/backend/inference/AGENTS.md
+++ b/products/autoresearch/backend/inference/AGENTS.md
@@ -34,6 +34,10 @@ The cardinal rule: **inference never refits a persisted model.** A bundle is fit
A completed live run also records `metrics["likely_count"]`, the people it scored at or above the current Likely cut point from `../evaluation/segment_thresholds.py`, and that cut point as `metrics["likely_threshold"]`. The score distribution keeps only quantiles, so the model list reads the count from here instead of querying the prediction events. Backfill and shadow runs do not record it.
`_resolve_distinct_ids()` maps the `person_id` everything is keyed on back to one current `distinct_id` through personhog (`get_persons_by_uuids`), never from event history, because an id read off old events can belong to someone else after a merge or split.
+- `person_property.py`
+ A live champion event carries `$set` of `output_person_property` only while the pipeline's `write_person_property` is on. New pipelines start with it off; pipelines created before the setting existed were migrated to on. Scoring re-reads the setting right before its batch goes out (`_still_writes_person_property()`, which also treats an archived pipeline as off), next to `_require_still_champion()`.
+ `remove_output_person_property()` removes the property again. It reads the current `person_id` of every champion `autoresearch_prediction` from this pipeline since it was created that carries `$set` of the property (so a merge survivor counts, and a prediction made while writing was off does not), in pages of 50,000, and checks them against `persons` that still hold the property 1,000 at a time. A person who got the same property name from somewhere else keeps it. It resolves each to a current distinct id with `_resolve_distinct_ids()`, and sends `$unset` through `capture_batch_internal()`. Before each page it calls `cleanup_stop_reason()`, so the cleanup stops when someone turns the setting back on for the same property name, or when another live pipeline writes the same property name. The facade starts it (`AutoresearchPropertyCleanupWorkflow`) when the setting goes from on to off, or when a pipeline with it on is archived or deleted. A cleanup records an `AutoresearchRun` with `run_type` `property_cleanup`, except after a delete.
+
## Query budget
Every HogQL query goes through `run_hogql()` in `../query.py` with a `QueryContext`: a limit context, which sets `max_execution_time`, and a ClickHouse workload. The entry point chooses it and passes it down explicitly. No code decides it from where it runs.
diff --git a/products/autoresearch/backend/inference/person_property.py b/products/autoresearch/backend/inference/person_property.py
new file mode 100644
index 000000000000..f38efa8b8c43
--- /dev/null
+++ b/products/autoresearch/backend/inference/person_property.py
@@ -0,0 +1,238 @@
+"""
+Remove a pipeline's output person property from the persons it wrote it to.
+
+Live scoring writes the champion's score to ``output_person_property`` only while the
+pipeline's ``write_person_property`` is on. When someone turns it off, or archives or deletes a
+pipeline that had it on, ``remove_output_person_property()`` sends ``$unset`` for the property
+to each person who still has it and got it from a live champion prediction of the pipeline.
+Persons who got the same property from somewhere else keep it.
+``AutoresearchPropertyCleanupWorkflow`` in ``../temporal/workflows.py`` runs it.
+
+The cleanup is safe to repeat: ``$unset`` of a missing property does nothing, and each page
+reads only the persons who still hold the property.
+"""
+
+from collections.abc import Callable
+from datetime import UTC, datetime
+from typing import Any
+from uuid import UUID
+
+import structlog
+
+from posthog.schema import HogQLQuery
+
+from posthog.api.capture import capture_batch_internal
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
+from posthog.hogql_queries.query_runner import ExecutionMode
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.autoresearch.backend.dataset.labeling import PREDICTION_EVENT_NAME
+from products.autoresearch.backend.inference.scoring import _resolve_distinct_ids
+from products.autoresearch.backend.models import AutoresearchModel, AutoresearchPipeline
+from products.autoresearch.backend.query import BATCH_QUERY, QueryContext, run_hogql
+
+logger = structlog.get_logger(__name__)
+
+EVENT_SOURCE = "autoresearch_property_cleanup"
+CLEANUP_PAGE_SIZE = 1000
+# HogQL returns at most 50,000 rows per query.
+SCORED_PAGE_SIZE = 50_000
+
+STOP_REENABLED = "reenabled"
+STOP_PROPERTY_IN_USE = "property_in_use"
+
+
+class PropertyCleanupError(Exception):
+ """Raised when a page of ``$unset`` events is not fully accepted, so the activity retries."""
+
+
+@frozen
+class CleanupOutcome:
+ persons_cleared: int
+ # Why the cleanup ended before it reached every person, or None when it finished.
+ stopped: str | None = None
+
+
+def cleanup_stop_reason(*, team_id: int, pipeline_id: str, output_property: str) -> str | None:
+ """
+ Why the property must stay on persons now, or None.
+
+ The pipeline writes it again when someone turned the setting back on for the same name.
+ Another live pipeline can claim the name after an archive, and its scores must not be removed.
+ """
+ pipelines = AutoresearchPipeline.objects.for_team(team_id).exclude(status=AutoresearchPipeline.Status.ARCHIVED)
+ if pipelines.filter(pk=pipeline_id, write_person_property=True, output_person_property=output_property).exists():
+ return STOP_REENABLED
+ if (
+ pipelines.exclude(pk=pipeline_id)
+ .filter(output_person_property=output_property, write_person_property=True)
+ .exists()
+ ):
+ return STOP_PROPERTY_IN_USE
+ return None
+
+
+def remove_output_person_property(
+ *,
+ team: Team,
+ pipeline_id: str,
+ output_property: str,
+ user: User | None,
+ written_since: str | None = None,
+ query_context: QueryContext = BATCH_QUERY,
+ on_page: Callable[[int], None] | None = None,
+) -> CleanupOutcome:
+ """
+ Send ``$unset`` for ``output_property`` to the persons this pipeline wrote it to, one page at a time.
+
+ ``written_since`` (ISO timestamp, the pipeline's creation) bounds the prediction-event scan.
+ The persons the pipeline scored come from its events in pages of ``SCORED_PAGE_SIZE``, so a
+ large population reads the event history a few times, not once per page of ``$unset``.
+
+ Before each page it checks ``cleanup_stop_reason()``, so a re-enable stops the cleanup within
+ one page. ``on_page`` receives the running count after each page.
+ """
+ cleared = 0
+ after: str | None = None
+ while True:
+ scored = _scored_person_ids(
+ team=team,
+ pipeline_id=pipeline_id,
+ output_property=output_property,
+ written_since=written_since,
+ after=after,
+ user=user,
+ query_context=query_context,
+ )
+ for start in range(0, len(scored), CLEANUP_PAGE_SIZE):
+ if stopped := cleanup_stop_reason(
+ team_id=team.pk, pipeline_id=pipeline_id, output_property=output_property
+ ):
+ logger.info("autoresearch_property_cleanup_stopped", pipeline_id=pipeline_id, reason=stopped)
+ return CleanupOutcome(persons_cleared=cleared, stopped=stopped)
+ holders = _holders(
+ team=team,
+ output_property=output_property,
+ person_ids=scored[start : start + CLEANUP_PAGE_SIZE],
+ user=user,
+ query_context=query_context,
+ )
+ if not holders:
+ continue
+ distinct_id_by_person = _resolve_distinct_ids(team=team, pipeline_id=pipeline_id, person_ids=holders)
+ _send_unsets(
+ team=team,
+ pipeline_id=pipeline_id,
+ output_property=output_property,
+ distinct_ids=list(distinct_id_by_person.values()),
+ )
+ cleared += len(distinct_id_by_person)
+ if on_page is not None:
+ on_page(cleared)
+ if len(scored) < SCORED_PAGE_SIZE:
+ return CleanupOutcome(persons_cleared=cleared)
+ after = scored[-1]
+
+
+def _scored_person_ids(
+ *,
+ team: Team,
+ pipeline_id: str,
+ output_property: str,
+ written_since: str | None,
+ after: str | None,
+ user: User | None,
+ query_context: QueryContext,
+) -> list[str]:
+ """The current person ids the pipeline's live champion predictions set the property on, in id order.
+
+ Only events that carry ``$set`` of the property count, because a prediction made while writing
+ was off left the person's own value alone. ``person_id`` resolves merges, so a person who
+ absorbed a scored person is included.
+ """
+ values: dict[str, Any] = {
+ "pipeline_id": pipeline_id,
+ "property": output_property,
+ "event": PREDICTION_EVENT_NAME,
+ "champion": AutoresearchModel.Role.CHAMPION.value,
+ }
+ after_clause = ""
+ if after is not None:
+ after_clause = "AND person_id > toUUID({after})"
+ values["after"] = after
+ since_clause = ""
+ if written_since is not None:
+ since_clause = "AND timestamp >= {written_since}"
+ values["written_since"] = datetime.fromisoformat(written_since)
+ tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)
+ result = run_hogql(
+ team=team,
+ query=HogQLQuery(
+ query=f"""
+ SELECT DISTINCT person_id FROM events
+ WHERE event = {{event}}
+ AND properties.$autoresearch_pipeline_id = {{pipeline_id}}
+ AND properties.$autoresearch_model_role = {{champion}}
+ AND properties.$set[{{property}}] IS NOT NULL
+ {since_clause} {after_clause}
+ ORDER BY person_id
+ LIMIT {SCORED_PAGE_SIZE}
+ """,
+ values=values,
+ ),
+ user=user,
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ query_context=query_context,
+ )
+ return [str(row[0]) for row in result.rows]
+
+
+def _holders(
+ *, team: Team, output_property: str, person_ids: list[str], user: User | None, query_context: QueryContext
+) -> list[str]:
+ """Which of ``person_ids`` still hold the property."""
+ tag_queries(product=Product.AUTORESEARCH, feature=Feature.QUERY)
+ result = run_hogql(
+ team=team,
+ query=HogQLQuery(
+ query=f"""
+ SELECT id FROM persons
+ WHERE id IN {{person_ids}} AND JSONHas(properties, {{property}})
+ ORDER BY id
+ LIMIT {CLEANUP_PAGE_SIZE}
+ """,
+ values={"property": output_property, "person_ids": [UUID(person_id) for person_id in person_ids]},
+ ),
+ user=user,
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ query_context=query_context,
+ )
+ return [str(row[0]) for row in result.rows]
+
+
+def _send_unsets(*, team: Team, pipeline_id: str, output_property: str, distinct_ids: list[str]) -> None:
+ if not distinct_ids:
+ return
+ timestamp = datetime.now(UTC)
+ events = [
+ {
+ "event": "$set",
+ "distinct_id": distinct_id,
+ "timestamp": timestamp,
+ "properties": {"$unset": [output_property], "$autoresearch_pipeline_id": pipeline_id},
+ "options": {"process_person_profile": True},
+ }
+ for distinct_id in distinct_ids
+ ]
+ result = capture_batch_internal(
+ events=events, token=team.api_token, event_source=EVENT_SOURCE, process_person_profile=True
+ )
+ # A warning means capture stored the event with person processing switched off, so the $unset never lands.
+ if not result.succeeded() or result.warnings:
+ raise PropertyCleanupError(
+ f"Property cleanup events were not all accepted ({len(result.dropped)} dropped, "
+ f"{len(result.retried)} exhausted retries, {len(result.unaccounted)} unaccounted, "
+ f"{len(result.warnings)} stored with a warning)"
+ )
diff --git a/products/autoresearch/backend/inference/scoring.py b/products/autoresearch/backend/inference/scoring.py
index b1b4470953a0..7211b5a0e2ed 100644
--- a/products/autoresearch/backend/inference/scoring.py
+++ b/products/autoresearch/backend/inference/scoring.py
@@ -10,6 +10,8 @@ autoresearch_prediction event per person.
- After a live champion run completes, every other model in the shadow set scores the
same people (``_score_shadow_set()``). A shadow model emits person-less events with the
``shadow`` role and no ``$set``, and records its own inference run.
+- A live champion event carries ``$set: {output_person_property: p_y}`` only while the
+ pipeline's ``write_person_property`` is on. ``person_property.py`` removes the property again.
Event shape:
event: autoresearch_prediction
@@ -612,18 +614,18 @@ def _emit_predictions(
_require_still_in_shadow_set(pipeline=pipeline, model=model)
else:
_require_still_champion(model)
- # Live runs attach each prediction to the real person: a real distinct_id, a processed
- # person profile, and a $set of the output property. Backfills and shadow scores stay
- # person-less (they exist for online validation, which keys on $autoresearch_person_id)
- # so a past-dated or shadow $set cannot clobber the champion's live score.
+ # Live runs attach each prediction to the real person: a real distinct_id and a processed
+ # person profile, plus a $set of the output property when the pipeline opts in. Backfills
+ # and shadow scores stay person-less (they exist for online validation, which keys on
+ # $autoresearch_person_id) so a past-dated or shadow $set cannot clobber the champion's live score.
distinct_id_by_person = (
{}
if person_less
else _resolve_distinct_ids(
- team=team, pipeline=pipeline, person_ids=[str(row["distinct_id"]) for row in scored.rows], user=user
+ team=team, pipeline_id=str(pipeline.pk), person_ids=[str(row["distinct_id"]) for row in scored.rows]
)
)
- output_property = pipeline.output_person_property
+ output_property = pipeline.output_person_property if _still_writes_person_property(pipeline) else ""
events: list[dict[str, Any]] = []
for row in scored.rows:
@@ -737,6 +739,18 @@ def _require_still_champion(model: AutoresearchModel) -> None:
)
+def _still_writes_person_property(pipeline: AutoresearchPipeline) -> bool:
+ """
+ Re-read the opt-in right before the events go out, so a run that started before someone
+ turned it off, or archived the pipeline, does not write the property after the cleanup started.
+ """
+ return (
+ AutoresearchPipeline.objects.filter(pk=pipeline.pk, write_person_property=True)
+ .exclude(status=AutoresearchPipeline.Status.ARCHIVED)
+ .exists()
+ )
+
+
def _require_still_in_shadow_set(*, pipeline: AutoresearchPipeline, model: AutoresearchModel) -> None:
"""The shadow counterpart of ``_require_still_champion()``: a model that left the set does not emit."""
shadow_ids = {member.pk for member in shadow_set(pipeline) if member.role != AutoresearchModel.Role.CHAMPION}
@@ -1159,9 +1173,7 @@ def _count_population(
return int(result.rows[0][0])
-def _resolve_distinct_ids(
- *, team: Team, pipeline: AutoresearchPipeline, person_ids: list[str], user: User
-) -> dict[str, str]:
+def _resolve_distinct_ids(*, team: Team, pipeline_id: str, person_ids: list[str]) -> dict[str, str]:
"""
Map each person_id to one of that person's current distinct_ids.
@@ -1175,7 +1187,7 @@ def _resolve_distinct_ids(
if len(resolvable) != len(person_ids):
logger.warning(
"autoresearch_unresolvable_person_ids",
- pipeline_id=str(pipeline.pk),
+ pipeline_id=pipeline_id,
skipped=len(person_ids) - len(resolvable),
)
if not resolvable:
@@ -1183,7 +1195,7 @@ def _resolve_distinct_ids(
try:
persons = get_persons_by_uuids(team.pk, resolvable, distinct_id_limit=1)
except Exception as exc:
- logger.exception("autoresearch_identity_resolution_failed", pipeline_id=str(pipeline.pk))
+ logger.exception("autoresearch_identity_resolution_failed", pipeline_id=pipeline_id)
raise InferenceRunError(
"Identity resolution failed; failing the run rather than emitting every prediction person-less"
) from exc
diff --git a/products/autoresearch/backend/inference/test_inference.py b/products/autoresearch/backend/inference/test_inference.py
index 10fa51cb93df..3e347b7f602b 100644
--- a/products/autoresearch/backend/inference/test_inference.py
+++ b/products/autoresearch/backend/inference/test_inference.py
@@ -154,8 +154,22 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):
):
return run_inference_for_pipeline(pipeline=pipeline, model=model)
- def test_run_inference_emits_one_batch_and_records_the_run(self):
- pipeline, model = self._make_pipeline_and_model()
+ @parameterized.expand(
+ [
+ ("writes_the_property", True, True, False),
+ ("leaves_persons_alone_when_off", False, False, False),
+ ("rechecks_the_setting_before_sending", True, False, False),
+ ("archived_before_sending", True, True, True),
+ ]
+ )
+ def test_run_inference_emits_one_batch_and_records_the_run(
+ self, _name: str, write_at_start: bool, write_at_send: bool, archived_at_send: bool
+ ):
+ pipeline, model = self._make_pipeline_and_model(write_person_property=write_at_start)
+ if write_at_send != write_at_start:
+ AutoresearchPipeline.objects.filter(pk=pipeline.pk).update(write_person_property=write_at_send)
+ if archived_at_send:
+ AutoresearchPipeline.objects.filter(pk=pipeline.pk).update(status=AutoresearchPipeline.Status.ARCHIVED)
capture = _capture_accepting_everything()
run = self._run_live(pipeline, model, capture, resolved={"user-1": "real-distinct-id"})
@@ -173,13 +187,16 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):
by_person = {e["properties"]["$autoresearch_person_id"]: e for e in events}
assert {e["properties"]["$autoresearch_prediction_date"] for e in events} == {run.metrics["prediction_date"]}
assert {e["properties"]["$autoresearch_run_id"] for e in events} == {str(run.pk)}
- # A resolved person is attached to their real distinct_id and gets the output property;
- # an unresolved one stays person-less so a UUID never becomes a person.
+ # A resolved person is attached to their real distinct_id, and gets the output property only
+ # while the pipeline opts in; an unresolved one stays person-less so a UUID never becomes a person.
assert by_person["user-1"]["distinct_id"] == "real-distinct-id"
assert by_person["user-1"]["options"] == {"process_person_profile": True}
- assert by_person["user-1"]["properties"]["$set"] == {
- "predicted_p_pageview": by_person["user-1"]["properties"]["$autoresearch_p_y"]
- }
+ if write_at_send and not archived_at_send:
+ assert by_person["user-1"]["properties"]["$set"] == {
+ "predicted_p_pageview": by_person["user-1"]["properties"]["$autoresearch_p_y"]
+ }
+ else:
+ assert "$set" not in by_person["user-1"]["properties"]
assert by_person["user-2"]["distinct_id"] == "user-2"
assert by_person["user-2"]["options"] == {"process_person_profile": False}
assert "$set" not in by_person["user-2"]["properties"]
@@ -187,7 +204,7 @@ class TestRunInferencePipeline(TeamScopedTestMixin, BaseTest):
assert pipeline.last_scored_at is not None
def test_a_sampled_model_emits_prior_corrected_scores_with_the_raw_score_and_rate(self):
- pipeline, model = self._make_pipeline_and_model()
+ pipeline, model = self._make_pipeline_and_model(write_person_property=True)
model.artifact_prefix = "tasks/autoresearch/team_1/pipeline_x/run_y"
model.negative_sample_rate = 0.25
model.save(update_fields=["artifact_prefix", "negative_sample_rate"])
@@ -835,7 +852,7 @@ class TestResolveDistinctIds(TeamScopedTestMixin, BaseTest):
]
mapping = _resolve_distinct_ids(
- team=self.team, pipeline=self._pipeline(), person_ids=[with_id, without_id, not_a_uuid], user=self.user
+ team=self.team, pipeline_id=str(self._pipeline().pk), person_ids=[with_id, without_id, not_a_uuid]
)
assert mapping == {with_id: "real-id"}
@@ -847,7 +864,7 @@ class TestResolveDistinctIds(TeamScopedTestMixin, BaseTest):
# Emitting every prediction person-less would leave the output property unset for the
# whole population while the run reported success.
with self.assertRaises(InferenceRunError):
- _resolve_distinct_ids(team=self.team, pipeline=self._pipeline(), person_ids=[str(uuid4())], user=self.user)
+ _resolve_distinct_ids(team=self.team, pipeline_id=str(self._pipeline().pk), person_ids=[str(uuid4())])
class TestAnchorsRecipeQueries(TeamScopedTestMixin, BaseTest):
@@ -1092,6 +1109,7 @@ class TestShadowScoring(TeamScopedTestMixin, BaseTest):
target_event="$pageview",
horizon_days=7,
output_person_property="predicted_p_pageview",
+ write_person_property=True,
)
self.sql_by_prefix: dict[str, str] = {}
self.champion = self._model("champion", _ANCHORS_FEATURE_SQL, role=AutoresearchModel.Role.CHAMPION)
diff --git a/products/autoresearch/backend/inference/test_person_property.py b/products/autoresearch/backend/inference/test_person_property.py
new file mode 100644
index 000000000000..ffde3e766110
--- /dev/null
+++ b/products/autoresearch/backend/inference/test_person_property.py
@@ -0,0 +1,96 @@
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.api.capture import CaptureInternalResult
+
+from products.autoresearch.backend.dataset.labeling import PREDICTION_EVENT_NAME
+from products.autoresearch.backend.inference import person_property
+from products.autoresearch.backend.inference.person_property import STOP_REENABLED, remove_output_person_property
+from products.autoresearch.backend.models import AutoresearchPipeline
+from products.autoresearch.backend.testing import TeamScopedTestMixin
+
+_PROPERTY = "predicted_p_pageview_7d"
+
+
+class TestRemoveOutputPersonProperty(TeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
+ @parameterized.expand(
+ [
+ ("removes_from_every_holder", None),
+ ("stops_when_turned_back_on", _PROPERTY),
+ ("continues_when_turned_back_on_for_another_name", "renamed_score"),
+ ]
+ )
+ def test_unsets_the_property_on_persons_that_hold_it(self, _name: str, reenable_with: str | None):
+ pipeline = AutoresearchPipeline.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="Cleanup",
+ target_event="$pageview",
+ output_person_property=_PROPERTY,
+ write_person_property=False,
+ )
+ for distinct_id in ("holder-1", "holder-2"):
+ holder = _create_person(team_id=self.team.pk, distinct_ids=[distinct_id], properties={_PROPERTY: 0.4})
+ _create_event(
+ team=self.team,
+ event=PREDICTION_EVENT_NAME,
+ distinct_id=distinct_id,
+ properties={
+ "$autoresearch_pipeline_id": str(pipeline.pk),
+ "$autoresearch_model_role": "champion",
+ "$autoresearch_person_id": str(holder.uuid),
+ "$set": {_PROPERTY: 0.4},
+ },
+ )
+ # Holds the same property from another source, and this pipeline never scored them.
+ _create_person(team_id=self.team.pk, distinct_ids=["bystander"], properties={_PROPERTY: 0.9})
+ # Scored while writing was off, so the property they hold is their own.
+ scored_while_off = _create_person(
+ team_id=self.team.pk, distinct_ids=["scored-while-off"], properties={_PROPERTY: 0.7}
+ )
+ _create_event(
+ team=self.team,
+ event=PREDICTION_EVENT_NAME,
+ distinct_id="scored-while-off",
+ properties={
+ "$autoresearch_pipeline_id": str(pipeline.pk),
+ "$autoresearch_model_role": "champion",
+ "$autoresearch_person_id": str(scored_while_off.uuid),
+ },
+ )
+ flush_persons_and_events()
+
+ def accept(**kwargs: object) -> CaptureInternalResult:
+ if reenable_with is not None:
+ AutoresearchPipeline.objects.filter(pk=pipeline.pk).update(
+ write_person_property=True, output_person_property=reenable_with
+ )
+ return CaptureInternalResult(status_code=200)
+
+ capture = MagicMock(side_effect=accept)
+ # One person per page, so the re-enable lands between the two holders.
+ with (
+ patch.object(person_property, "CLEANUP_PAGE_SIZE", 1),
+ patch.object(person_property, "capture_batch_internal", capture),
+ ):
+ outcome = remove_output_person_property(
+ team=self.team,
+ pipeline_id=str(pipeline.pk),
+ output_property=_PROPERTY,
+ user=self.user,
+ written_since=pipeline.created_at.isoformat(),
+ )
+
+ events = [event for call in capture.call_args_list for event in call.kwargs["events"]]
+ assert all(event["properties"]["$unset"] == [_PROPERTY] for event in events)
+ assert all(call.kwargs["process_person_profile"] for call in capture.call_args_list)
+ unset_for = {event["distinct_id"] for event in events}
+ if reenable_with == _PROPERTY:
+ assert len(unset_for) == 1 and unset_for < {"holder-1", "holder-2"}
+ assert outcome.stopped == STOP_REENABLED
+ else:
+ assert unset_for == {"holder-1", "holder-2"}
+ assert outcome.stopped is None
+ assert outcome.persons_cleared == len(unset_for)
diff --git a/products/autoresearch/backend/migrations/0005_write_person_property.py b/products/autoresearch/backend/migrations/0005_write_person_property.py
new file mode 100644
index 000000000000..18e75a76e24b
--- /dev/null
+++ b/products/autoresearch/backend/migrations/0005_write_person_property.py
@@ -0,0 +1,41 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("autoresearch", "0004_reader_summaries"),
+ ]
+
+ operations = [
+ # Existing pipelines already write their scores, so they keep doing it. New pipelines start off.
+ migrations.AddField(
+ model_name="autoresearchpipeline",
+ name="write_person_property",
+ field=models.BooleanField(
+ db_default=True,
+ default=False,
+ help_text="Whether live scoring writes the champion's score to output_person_property on each scored person",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="autoresearchpipeline",
+ name="write_person_property",
+ field=models.BooleanField(
+ db_default=False,
+ default=False,
+ help_text="Whether live scoring writes the champion's score to output_person_property on each scored person",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="autoresearchrun",
+ name="run_type",
+ field=models.CharField(
+ choices=[
+ ("inference", "Inference"),
+ ("validation", "Validation"),
+ ("property_cleanup", "Property cleanup"),
+ ],
+ max_length=20,
+ ),
+ ),
+ ]
diff --git a/products/autoresearch/backend/migrations/max_migration.txt b/products/autoresearch/backend/migrations/max_migration.txt
index 82dc5609d7e2..e6d6fe49140b 100644
--- a/products/autoresearch/backend/migrations/max_migration.txt
+++ b/products/autoresearch/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0004_reader_summaries
+0005_write_person_property
diff --git a/products/autoresearch/backend/models.py b/products/autoresearch/backend/models.py
index e9095615ca3b..17a55da989fb 100644
--- a/products/autoresearch/backend/models.py
+++ b/products/autoresearch/backend/models.py
@@ -115,6 +115,11 @@ class AutoresearchPipeline(TeamScopedRootMixin, UUIDModel):
default="",
help_text="Person property name for champion scores, e.g. 'predicted_p_pageview'",
)
+ write_person_property = models.BooleanField(
+ default=False,
+ db_default=False,
+ help_text="Whether live scoring writes the champion's score to output_person_property on each scored person",
+ )
status = models.CharField(max_length=20, choices=Status.choices, default=Status.DRAFT)
created_at = models.DateTimeField(auto_now_add=True)
@@ -448,11 +453,12 @@ class AutoresearchSuggestion(PipelineScopedModel):
class AutoresearchRun(PipelineScopedModel):
- """Generic operational run: inference or validation."""
+ """Generic operational run: inference, validation, or person property cleanup."""
class RunType(models.TextChoices):
INFERENCE = "inference", "Inference"
VALIDATION = "validation", "Validation"
+ PROPERTY_CLEANUP = "property_cleanup", "Property cleanup"
class Status(models.TextChoices):
PENDING = "pending", "Pending"
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 12ca750235e3..1839b81650e2 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -660,6 +660,13 @@ class AutoresearchPipelineSerializer(DataclassSerializer):
max_length=255,
help_text="Person property name that stores the daily prediction score, e.g. 'predicted_p_pageview'.",
)
+ write_person_property = serializers.BooleanField(
+ read_only=True,
+ help_text=(
+ "Whether live scoring writes the champion's score to output_person_property on each scored person. "
+ "Feature flags, cohorts, workflows and insights that target people by score need it on."
+ ),
+ )
status = serializers.ChoiceField(
choices=PIPELINE_STATUS_CHOICES,
read_only=True,
@@ -767,6 +774,7 @@ class AutoresearchPipelineSerializer(DataclassSerializer):
"success_auc",
"plateau_iterations",
"output_person_property",
+ "write_person_property",
"status",
"created_by",
"created_at",
@@ -871,6 +879,15 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):
"non-archived pipelines."
),
)
+ write_person_property = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Write the champion's score to output_person_property on each scored person at every live scoring run. "
+ "Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. "
+ "Prediction events, validation and segments work without it. Turning it off, or archiving or deleting "
+ "the pipeline while it is on, removes the property from the people it scored."
+ ),
+ )
class Meta:
dataclass = PipelineWrite
@@ -888,6 +905,7 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):
"success_auc",
"plateau_iterations",
"output_person_property",
+ "write_person_property",
]
# Fields a trained model was fit against. Once any model exists they are frozen: scoring keeps
@@ -985,6 +1003,19 @@ class AutoresearchPipelineCreateSerializer(DataclassSerializer):
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 is_update and (
+ self._supplied(data, "output_person_property") or self._supplied(data, "write_person_property")
+ ):
+ stored = api.get_pipeline_definition(team.pk, self._pipeline_id)
+ writes = self._value(data, "write_person_property", stored.write_person_property)
+ if writes and not self._value(data, "output_person_property", stored.output_person_property):
+ raise serializers.ValidationError(
+ {
+ "output_person_property": (
+ "Set a person property name before you turn on writing scores to person profiles."
+ )
+ }
+ )
if output_person_property and api.output_person_property_taken(
team.pk, output_person_property, exclude_pipeline_id=self._pipeline_id
):
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.py
index b025b6ac9b4e..c2c8adc2df69 100644
--- a/products/autoresearch/backend/presentation/views/views.py
+++ b/products/autoresearch/backend/presentation/views/views.py
@@ -254,6 +254,19 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
if _is_training_agent_sandbox(request, self.team_id):
raise PermissionDenied("Pipelines cannot be changed from inside a sandbox.")
+ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
+ # Scores on persons and the cleanup's $unset are person writes, so any request that turns
+ # them on or off, or archives or deletes a pipeline that writes them, needs person:write
+ # like /score does.
+ if self.action in ("create", "update", "partial_update"):
+ writes_persons = "write_person_property" in request.data
+ elif self.action in ("archive", "destroy") and not getattr(self, "swagger_fake_view", False):
+ # Schema generation has no pipeline to read, so it documents the base scopes.
+ writes_persons = api.pipeline_writes_person_property(self.team_id, self.kwargs["pk"])
+ else:
+ writes_persons = False
+ return ["autoresearch:write", "person:write"] if writes_persons else None
+
def get_throttles(self) -> list[BaseThrottle]:
# Several unsampled ClickHouse scans per call, so a personal API key gets the ClickHouse budget.
if self.action in ("resolve_template", "validate_definition", "run_inference", "run_validation"):
@@ -298,6 +311,7 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
headers = self.get_success_headers(output.data)
return Response(output.data, status=201, headers=headers)
+ @extend_schema(request=AutoresearchPipelineCreateSerializer, responses={200: AutoresearchPipelineSerializer})
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"]}
@@ -310,6 +324,7 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
self.team_id,
self.kwargs["pk"],
fields=_pipeline_write_fields(_validated_with_sentinels(serializer)),
+ user_id=request.user.pk,
)
except PipelineNotFound:
raise NotFound("Pipeline not found.")
@@ -317,6 +332,8 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
raise ValidationError(str(exc)) from exc
return Response(AutoresearchPipelineSerializer(instance=pipeline).data)
+ # Both respond with the read serializer, so the generated client keeps `id` for `enrich_url`.
+ @extend_schema(request=AutoresearchPipelineCreateSerializer, responses={200: AutoresearchPipelineSerializer})
def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
kwargs["partial"] = True
return self.update(request, *args, **kwargs)
@@ -330,7 +347,7 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
)
def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
try:
- api.delete_pipeline(self.team_id, self.kwargs["pk"])
+ api.delete_pipeline(self.team_id, self.kwargs["pk"], user_id=self.request.user.pk)
except PipelineNotFound:
raise NotFound("Pipeline not found.")
except AutoresearchConflict as exc:
@@ -639,6 +656,7 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
summary="Archive a pipeline",
description=(
"Soft-delete a pipeline. Stops daily scoring and training. Predictions and metrics are preserved. "
+ "When write_person_property is on, a cleanup run removes output_person_property from the people it scored. "
"Refused while a training run is in progress."
),
)
@@ -686,7 +704,9 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, _FacadePaginationMixin
def _set_status(self, status: str) -> Response:
try:
- pipeline = api.set_pipeline_status(self.team_id, self.kwargs["pk"], status=status)
+ pipeline = api.set_pipeline_status(
+ self.team_id, self.kwargs["pk"], status=status, user_id=self.request.user.pk
+ )
except PipelineNotFound:
raise NotFound("Pipeline not found.")
except AutoresearchConflict as exc:
diff --git a/products/autoresearch/backend/temporal/AGENTS.md b/products/autoresearch/backend/temporal/AGENTS.md
index e2619a7e2e67..365a63e1b9aa 100644
--- a/products/autoresearch/backend/temporal/AGENTS.md
+++ b/products/autoresearch/backend/temporal/AGENTS.md
@@ -11,6 +11,7 @@ Scoring, validation and training live in `../inference/`, `../evaluation/`, and
- `AutoresearchInferenceWorkflow` (`autoresearch-inference`) — `activity_run_inference` for one pipeline. The activity reads the current champion itself, so a retry after a mid-scoring promotion scores with the new one.
- `AutoresearchValidationWorkflow` (`autoresearch-validation`) — `activity_run_validation` for one pipeline.
- `activity_kickoff_training` — launches a training run for a pipeline that is due.
+ - `AutoresearchPropertyCleanupWorkflow` (`autoresearch-property-cleanup`) — `activity_remove_person_property` removes a pipeline's output person property from persons (`../inference/person_property.py`), then runs a reconcile pass an hour later for scores that were still ingesting during the first pass. The run row stays `running` until the reconcile pass ends, and a retry adds to the count on the row. When the activity runs out of retries, the workflow fails the run with `activity_fail_cleanup_run`. The facade starts it, not the coordinator, with one workflow id per cleanup request.
Each workflow has a typed input/result dataclass pair (`InferenceWorkflowInput` / `InferenceWorkflowResult`, and so on). Activities are named with a `autoresearch-<workflow>.<activity>` convention.
diff --git a/products/autoresearch/backend/temporal/__init__.py b/products/autoresearch/backend/temporal/__init__.py
index 67290619aedd..0e2df6276c4c 100644
--- a/products/autoresearch/backend/temporal/__init__.py
+++ b/products/autoresearch/backend/temporal/__init__.py
@@ -8,9 +8,12 @@ temporal-worker-self-driving fleet polls.
from .workflows import (
AutoresearchCoordinatorWorkflow,
AutoresearchInferenceWorkflow,
+ AutoresearchPropertyCleanupWorkflow,
AutoresearchValidationWorkflow,
+ activity_fail_cleanup_run,
activity_kickoff_training,
activity_load_active_pipelines,
+ activity_remove_person_property,
activity_run_inference,
activity_run_validation,
)
@@ -18,12 +21,15 @@ from .workflows import (
WORKFLOWS = [
AutoresearchCoordinatorWorkflow,
AutoresearchInferenceWorkflow,
+ AutoresearchPropertyCleanupWorkflow,
AutoresearchValidationWorkflow,
]
ACTIVITIES = [
+ activity_fail_cleanup_run,
activity_kickoff_training,
activity_load_active_pipelines,
+ activity_remove_person_property,
activity_run_inference,
activity_run_validation,
]
@@ -33,5 +39,6 @@ __all__ = [
"WORKFLOWS",
"AutoresearchCoordinatorWorkflow",
"AutoresearchInferenceWorkflow",
+ "AutoresearchPropertyCleanupWorkflow",
"AutoresearchValidationWorkflow",
]
diff --git a/products/autoresearch/backend/temporal/test_workflows.py b/products/autoresearch/backend/temporal/test_workflows.py
index 4c636db44a4f..9d8bf019e3be 100644
--- a/products/autoresearch/backend/temporal/test_workflows.py
+++ b/products/autoresearch/backend/temporal/test_workflows.py
@@ -1,6 +1,8 @@
+import uuid
from datetime import UTC, datetime, timedelta
from typing import Any, Optional
+import pytest
import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -9,11 +11,15 @@ from django.test import SimpleTestCase
from django.utils import timezone as django_timezone
from parameterized import parameterized
+from temporalio import activity
+from temporalio.client import WorkflowFailureError
from temporalio.exceptions import ApplicationError
-from temporalio.testing import ActivityEnvironment
+from temporalio.testing import ActivityEnvironment, WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.models import User
+from products.autoresearch.backend.inference.person_property import CleanupOutcome
from products.autoresearch.backend.models import (
AutoresearchModel,
AutoresearchPipeline,
@@ -24,10 +30,14 @@ from products.autoresearch.backend.query import BATCH_QUERY
from products.autoresearch.backend.temporal.workflows import (
_VALIDATION_ATTEMPT_TIMEOUT,
RESCUE_ITERATION_BUDGET,
+ AutoresearchPropertyCleanupWorkflow,
+ FailCleanupRunInput,
InferenceWorkflowResult,
KickoffTrainingInput,
KickoffTrainingResult,
LoadActivePipelinesInput,
+ PropertyCleanupWorkflowInput,
+ PropertyCleanupWorkflowResult,
RunInferenceInput,
RunInferenceResult,
RunValidationInput,
@@ -35,6 +45,7 @@ from products.autoresearch.backend.temporal.workflows import (
ValidationWorkflowResult,
activity_kickoff_training,
activity_load_active_pipelines,
+ activity_remove_person_property,
activity_run_inference,
activity_run_validation,
evaluate_pipeline_outcome,
@@ -250,6 +261,49 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):
claim_deadline = mock_validation.call_args.kwargs["claim_deadline"]
assert django_timezone.now() < claim_deadline < django_timezone.now() + _VALIDATION_ATTEMPT_TIMEOUT
+ @parameterized.expand(
+ [
+ ("first_pass_leaves_the_run_open", False, None, AutoresearchRun.Status.RUNNING, 5),
+ ("retry_adds_to_the_failed_attempt", False, 2, AutoresearchRun.Status.RUNNING, 7),
+ ("reconcile_pass_adds_to_the_first", True, 3, AutoresearchRun.Status.COMPLETED, 8),
+ ]
+ )
+ @patch("products.autoresearch.backend.temporal.workflows.remove_output_person_property")
+ def test_property_cleanup_run_stays_open_until_the_reconcile_pass(
+ self,
+ _name: str,
+ final_pass: bool,
+ cleared_before: int | None,
+ expected_status: str,
+ expected_cleared: int,
+ mock_remove: MagicMock,
+ ) -> None:
+ pipeline = self._create_pipeline(output_person_property="predicted_p_pageview")
+ run = AutoresearchRun.objects.create(
+ pipeline=pipeline,
+ run_type=AutoresearchRun.RunType.PROPERTY_CLEANUP,
+ status=AutoresearchRun.Status.PENDING,
+ rows_scored=cleared_before,
+ )
+ mock_remove.return_value = CleanupOutcome(persons_cleared=5)
+ result = ActivityEnvironment().run(
+ activity_remove_person_property,
+ PropertyCleanupWorkflowInput(
+ pipeline_id=str(pipeline.id),
+ team_id=self.team.id,
+ output_property="predicted_p_pageview",
+ run_id=str(run.pk),
+ final_pass=final_pass,
+ ),
+ )
+ run.refresh_from_db()
+ assert (run.status, run.rows_scored, result.persons_cleared) == (
+ expected_status,
+ expected_cleared,
+ expected_cleared,
+ )
+ assert (run.completed_at is not None) == final_pass
+
@parameterized.expand(
[
("open_scheduled_row_is_reused", {}, True),
@@ -475,3 +529,53 @@ class TestCoordinatorActivities(TeamScopedTestMixin, BaseTest):
pipeline.refresh_from_db()
assert pipeline.iteration_budget_remaining == 20
+
+
+ "first_pass,expected_passes,expected_failed_run",
+ [
+ ("finishes", [False, True], None),
+ ("stops", [False], None),
+ ("fails", [False], "run-1"),
+ ],
+)
+async def test_property_cleanup_workflow_reconciles_and_fails_the_run(
+ first_pass: str, expected_passes: list[bool], expected_failed_run: str | None
+) -> None:
+ passes: list[bool] = []
+ failed_runs: list[str] = []
+
+ @activity.defn(name="autoresearch-property-cleanup.remove_person_property")
+ async def remove(inp: PropertyCleanupWorkflowInput) -> PropertyCleanupWorkflowResult:
+ passes.append(inp.final_pass)
+ if first_pass == "fails":
+ raise ApplicationError("capture is down", non_retryable=True)
+ stopped = "reenabled" if first_pass == "stops" else None
+ return PropertyCleanupWorkflowResult(persons_cleared=1, status="completed", stopped=stopped)
+
+ @activity.defn(name="autoresearch-property-cleanup.fail_run")
+ async def fail_run(inp: FailCleanupRunInput) -> None:
+ failed_runs.append(inp.run_id)
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue="cleanup-test",
+ workflows=[AutoresearchPropertyCleanupWorkflow],
+ activities=[remove, fail_run],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await env.client.start_workflow(
+ AutoresearchPropertyCleanupWorkflow.run,
+ PropertyCleanupWorkflowInput(pipeline_id="p", team_id=1, output_property="score", run_id="run-1"),
+ id=str(uuid.uuid4()),
+ task_queue="cleanup-test",
+ )
+ if first_pass == "fails":
+ with pytest.raises(WorkflowFailureError):
+ await handle.result()
+ else:
+ await handle.result()
+
+ assert passes == expected_passes
+ assert failed_runs == ([expected_failed_run] if expected_failed_run else [])
diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.py
index 57fb143f6a77..b1144c78cd1e 100644
--- a/products/autoresearch/backend/temporal/workflows.py
+++ b/products/autoresearch/backend/temporal/workflows.py
@@ -1,7 +1,7 @@
"""
-Temporal workflows for autoresearch inference and online validation.
+Temporal workflows for autoresearch inference, online validation, and person property cleanup.
-Both workflows are regular Temporal workflows (not TaskRun/agent sandboxes) because
+These workflows are regular Temporal workflows (not TaskRun/agent sandboxes) because
scoring and validation are deterministic pipelines. Training runs through Task/TaskRun.
Activities are synchronous — Temporal runs them in a thread pool, which is correct
@@ -11,21 +11,23 @@ for Django ORM + HogQL queries. Workflows are async and only orchestrate activit
from __future__ import annotations
from collections.abc import Awaitable
-from dataclasses import field
+from dataclasses import field, replace
from datetime import date, timedelta
from typing import Optional, TypeVar, cast
import structlog
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
-from temporalio.exceptions import ApplicationError
+from temporalio.exceptions import ActivityError, ApplicationError
with workflow.unsafe.imports_passed_through():
import asyncio as _asyncio
from django.db import transaction
+ from django.db.models import QuerySet
from django.utils import timezone as django_timezone
+ from posthog.models.team.team import Team
from posthog.models.user import User
from products.actions.backend.models.action import Action
@@ -38,6 +40,7 @@ with workflow.unsafe.imports_passed_through():
fail_stale_inference_runs,
find_unscorable_champion,
)
+ from products.autoresearch.backend.inference.person_property import remove_output_person_property
from products.autoresearch.backend.inference.sandbox import SandboxInferenceError, _resolve_acting_user
from products.autoresearch.backend.inference.scoring import run_inference_for_pipeline
from products.autoresearch.backend.models import (
@@ -399,6 +402,150 @@ class AutoresearchValidationWorkflow(PostHogWorkflow):
)
+# ── Person property cleanup ───────────────────────────────────────────────────
+
+
+@frozen
+class PropertyCleanupWorkflowInput:
+ pipeline_id: str
+ team_id: int
+ # Carried in the input, because a deleted pipeline has no row to read them from.
+ output_property: str
+ # The pipeline's creation time, so the scan for its prediction events stays bounded.
+ written_since: Optional[str] = None
+ # The AutoresearchRun row the cleanup fills. None for a deleted pipeline.
+ run_id: Optional[str] = None
+ # Who turned the setting off, archived, or deleted, so HogQL applies their access.
+ user_id: Optional[int] = None
+ # The first pass leaves the run open, so the run completes only after the reconcile pass.
+ final_pass: bool = True
+
+
+@frozen
+class PropertyCleanupWorkflowResult:
+ persons_cleared: int
+ status: str
+ stopped: Optional[str] = None
+
+
+# A page reads at most CLEANUP_PAGE_SIZE persons and sends one capture batch, so one attempt covers
+# a large population. The cleanup restarts from the first person that still holds the property.
+_CLEANUP_RETRY = RetryPolicy(maximum_attempts=3, initial_interval=timedelta(minutes=1))
+_CLEANUP_ATTEMPT_TIMEOUT = timedelta(hours=2)
+# A scoring batch capture accepted just before the opt-out can still be ingesting when the first pass
+# runs, and its $set lands after it. A second pass after this delay removes those.
+_RECONCILE_DELAY = timedelta(hours=1)
+# Two passes of up to three attempts each, plus the delay between them and the retry backoff.
+PROPERTY_CLEANUP_WORKFLOW_TIMEOUT = timedelta(hours=16)
+
+
[email protected](name="autoresearch-property-cleanup.remove_person_property")
+def activity_remove_person_property(inp: PropertyCleanupWorkflowInput) -> PropertyCleanupWorkflowResult:
+ """Send $unset for the pipeline's output property to the persons it wrote it to.
+
+ The run row is updated through the queryset, because deleting the pipeline also deletes its runs.
+ The count continues from the row, so a retry or the reconcile pass adds to what earlier attempts
+ cleared. A failed attempt leaves the run open, and the workflow fails it once retries run out.
+ """
+ with HeartbeaterSync(), team_scope(inp.team_id):
+ _update_cleanup_run(inp.run_id, status=AutoresearchRun.Status.RUNNING, error="", completed_at=None)
+ cleared_before = _cleanup_run_count(inp.run_id)
+ team = Team.objects.get(pk=inp.team_id)
+ user = User.objects.filter(pk=inp.user_id, is_active=True).first() if inp.user_id else None
+ outcome = remove_output_person_property(
+ team=team,
+ pipeline_id=inp.pipeline_id,
+ output_property=inp.output_property,
+ written_since=inp.written_since,
+ user=user,
+ query_context=BATCH_QUERY,
+ on_page=lambda cleared: _update_cleanup_run(inp.run_id, rows_scored=cleared_before + cleared),
+ )
+ cleared = cleared_before + outcome.persons_cleared
+ done = inp.final_pass or outcome.stopped is not None
+ status = AutoresearchRun.Status.COMPLETED if done else AutoresearchRun.Status.RUNNING
+ _update_cleanup_run(
+ inp.run_id,
+ status=status,
+ rows_scored=cleared,
+ metrics={"output_person_property": inp.output_property, "stopped": outcome.stopped},
+ completed_at=django_timezone.now() if done else None,
+ )
+ return PropertyCleanupWorkflowResult(persons_cleared=cleared, status=status, stopped=outcome.stopped)
+
+
+@frozen
+class FailCleanupRunInput:
+ run_id: str
+ error: str
+
+
[email protected](name="autoresearch-property-cleanup.fail_run")
+def activity_fail_cleanup_run(inp: FailCleanupRunInput) -> None:
+ """Fail the run after the cleanup ran out of retries, timed out, or lost its worker."""
+ _update_cleanup_run(
+ inp.run_id, status=AutoresearchRun.Status.FAILED, error=inp.error[:2000], completed_at=django_timezone.now()
+ )
+
+
+def _cleanup_runs(run_id: str) -> QuerySet[AutoresearchRun]:
+ return AutoresearchRun.objects.filter(pk=run_id, run_type=AutoresearchRun.RunType.PROPERTY_CLEANUP)
+
+
+def _update_cleanup_run(run_id: str | None, **fields: object) -> None:
+ if run_id is not None:
+ _cleanup_runs(run_id).update(**fields)
+
+
+def _cleanup_run_count(run_id: str | None) -> int:
+ if run_id is None:
+ return 0
+ return _cleanup_runs(run_id).values_list("rows_scored", flat=True).first() or 0
+
+
+def property_cleanup_workflow_id(pipeline_id: str, request_id: str) -> str:
+ """One workflow per cleanup request, so a request never waits on, or is lost to, an earlier one that is stopping."""
+ return f"autoresearch-property-cleanup-{pipeline_id}-{request_id}"
+
+
[email protected](name="autoresearch-property-cleanup")
+class AutoresearchPropertyCleanupWorkflow(PostHogWorkflow):
+ """
+ Removes a pipeline's output person property from persons, after someone turns off
+ write_person_property, or archives or deletes a pipeline that had it on. A reconcile pass
+ runs after _RECONCILE_DELAY for scores that were still ingesting during the first pass.
+ """
+
+ inputs_cls = PropertyCleanupWorkflowInput
+
+ @workflow.run
+ async def run(self, inp: PropertyCleanupWorkflowInput) -> PropertyCleanupWorkflowResult:
+ try:
+ first = await self._remove(replace(inp, final_pass=False))
+ if first.stopped is not None:
+ return first
+ await workflow.sleep(_RECONCILE_DELAY)
+ return await self._remove(replace(inp, final_pass=True))
+ except ActivityError as exc:
+ if inp.run_id is not None:
+ await workflow.execute_activity(
+ activity_fail_cleanup_run,
+ FailCleanupRunInput(run_id=inp.run_id, error=str(exc.cause or exc)),
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=5),
+ )
+ raise
+
+ async def _remove(self, inp: PropertyCleanupWorkflowInput) -> PropertyCleanupWorkflowResult:
+ return await workflow.execute_activity(
+ activity_remove_person_property,
+ inp,
+ start_to_close_timeout=_CLEANUP_ATTEMPT_TIMEOUT,
+ heartbeat_timeout=_HEARTBEAT_TIMEOUT,
+ retry_policy=_CLEANUP_RETRY,
+ )
+
+
# ── Coordinator workflow I/O ──────────────────────────────────────────────────
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index 59c070edc96c..e2aa021c2c8b 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -117,6 +117,8 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
# 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"
+ # A new model scores without writing to person profiles until someone opts in.
+ assert data["write_person_property"] is False
assert AutoresearchPipeline.objects.filter(team=self.team, name="My Pipeline").exists()
def test_create_pipeline_with_action_target(self):
@@ -582,6 +584,49 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
pipeline.refresh_from_db()
assert pipeline.status == AutoresearchPipeline.Status.ARCHIVED
+ @parameterized.expand(
+ [
+ ("turned_off", True, "patch", True, True),
+ ("already_off", False, "patch", False, False),
+ ("archived_while_on", True, "archive", True, True),
+ ("archived_while_off", False, "archive", False, False),
+ ("paused_while_on", True, "pause", False, False),
+ ("deleted_while_on", True, "delete", True, False),
+ ]
+ )
+ def test_property_cleanup_starts_only_when_a_writing_pipeline_stops(
+ self, _name: str, writing: bool, change: str, starts_cleanup: bool, records_run: bool
+ ):
+ pipeline = self._make_pipeline(
+ status=AutoresearchPipeline.Status.RUNNING,
+ output_person_property="predicted_p_pageview_7d",
+ write_person_property=writing,
+ )
+ url = f"{self.base_url}/{pipeline.id}/"
+ with (
+ patch(f"{_FACADE}._start_property_cleanup") as start_cleanup,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ if change == "patch":
+ resp = self.client.patch(url, {"write_person_property": False}, format="json")
+ elif change == "delete":
+ resp = self.client.delete(url)
+ else:
+ resp = self.client.post(f"{url}{change}/")
+ assert resp.status_code in (status.HTTP_200_OK, status.HTTP_204_NO_CONTENT), resp.content
+
+ assert start_cleanup.called == starts_cleanup
+ cleanup_runs = AutoresearchRun.objects.for_team(self.team.pk).filter(
+ run_type=AutoresearchRun.RunType.PROPERTY_CLEANUP
+ )
+ assert cleanup_runs.count() == (1 if records_run else 0)
+ if starts_cleanup:
+ kwargs = start_cleanup.call_args.kwargs
+ assert kwargs["output_property"] == "predicted_p_pageview_7d"
+ assert kwargs["pipeline_id"] == str(pipeline.pk)
+ assert kwargs["user_id"] == self.user.pk
+ assert (kwargs["run"] is not None) == records_run
+
def test_train_archived_pipeline_returns_404(self):
pipeline = self._make_pipeline(status=AutoresearchPipeline.Status.ARCHIVED)
# Archived pipelines are excluded from the queryset so the endpoint returns 404
@@ -783,6 +828,80 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {with_all}")
assert self.client.post(missing).status_code == status.HTTP_404_NOT_FOUND
+ @parameterized.expand(
+ [
+ ("patch_person_writes", "patch", "", {"write_person_property": False}, None, True),
+ ("patch_other_fields", "patch", "", {"name": "Renamed"}, None, False),
+ ("create_with_person_writes", "post", None, {"write_person_property": True}, None, True),
+ ("archive_writing_pipeline", "post", "archive/", None, True, True),
+ ("archive_other_pipeline", "post", "archive/", None, False, False),
+ ("delete_writing_pipeline", "delete", "", None, True, True),
+ ]
+ )
+ def test_person_writes_need_person_write(
+ self,
+ _name: str,
+ method: str,
+ suffix: str | None,
+ body: dict | None,
+ pipeline_writes: bool | None,
+ needs_person_write: bool,
+ ):
+ if suffix is None:
+ url = f"{self.base_url}/"
+ else:
+ pipeline_id = (
+ self._make_pipeline(
+ status=AutoresearchPipeline.Status.RUNNING,
+ output_person_property="predicted_p_pageview_7d",
+ write_person_property=pipeline_writes,
+ ).id
+ if pipeline_writes is not None
+ else uuid.uuid4()
+ )
+ url = f"{self.base_url}/{pipeline_id}/{suffix}"
+ self.client.logout()
+ with patch(f"{_FACADE}._start_property_cleanup"):
+ for scopes, refused in (
+ (["autoresearch:write"], needs_person_write),
+ (["autoresearch:write", "person:write"], False),
+ ):
+ key = self.create_personal_api_key_with_scopes(scopes)
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key}")
+ resp = getattr(self.client, method)(url, body, format="json")
+ assert (resp.status_code == status.HTTP_403_FORBIDDEN) == refused, (scopes, resp.content)
+
+ @parameterized.expand(
+ [
+ ("while_writing", True, {}, status.HTTP_400_BAD_REQUEST),
+ ("while_off", False, {}, status.HTTP_200_OK),
+ ("while_turning_writes_off", True, {"write_person_property": False}, status.HTTP_200_OK),
+ ("blank_while_writing", True, {"output_person_property": ""}, status.HTTP_400_BAD_REQUEST),
+ (
+ "blank_while_turning_writes_on",
+ False,
+ {"output_person_property": "", "write_person_property": True},
+ status.HTTP_400_BAD_REQUEST,
+ ),
+ ]
+ )
+ def test_renaming_the_person_property_needs_writes_off(self, _name: str, writing: bool, extra: dict, expected: int):
+ pipeline = self._make_pipeline(
+ status=AutoresearchPipeline.Status.RUNNING,
+ output_person_property="predicted_p_pageview_7d",
+ write_person_property=writing,
+ )
+ with patch(f"{_FACADE}._start_property_cleanup"):
+ resp = self.client.patch(
+ f"{self.base_url}/{pipeline.id}/",
+ {"output_person_property": "predicted_p_pageview_renamed", **extra},
+ format="json",
+ )
+ assert resp.status_code == expected, resp.content
+ pipeline.refresh_from_db()
+ renamed = expected == status.HTTP_200_OK
+ assert (pipeline.output_person_property == "predicted_p_pageview_renamed") == renamed
+
# ──────────────────────────────────────── train action ────────────────────────────────────────
def test_start_training(self):
diff --git a/products/autoresearch/frontend/ModelCardMenu.tsx b/products/autoresearch/frontend/ModelCardMenu.tsx
index bcc0e2aeea92..358dc2a15901 100644
--- a/products/autoresearch/frontend/ModelCardMenu.tsx
+++ b/products/autoresearch/frontend/ModelCardMenu.tsx
@@ -55,8 +55,9 @@ export function ModelCardMenu({ pipeline }: { pipeline: AutoresearchPipelineApi
onClick={() => {
LemonDialog.open({
title: `Delete "${pipeline.name}"?`,
- description:
- 'The model, its training runs, and prediction metadata will be removed. Emitted autoresearch_prediction events stay in the events stream, and the prediction person property stays on each scored person.',
+ description: pipeline.write_person_property
+ ? 'The model, its training runs, and prediction metadata will be removed. Emitted autoresearch_prediction events stay in the events stream. The prediction person property is removed from the people this model scored.'
+ : 'The model, its training runs, and prediction metadata will be removed. Emitted autoresearch_prediction events stay in the events stream.',
primaryButton: {
children: 'Delete',
status: 'danger',
diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts
index 0ca1543a7c46..77c977265b28 100644
--- a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts
+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts
@@ -8,6 +8,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { initKeaTests } from '~/test/init'
import {
+ PROPERTY_CLEANUP_POLL_INTERVAL_MS,
SCORE_RUN_POLL_INTERVAL_MS,
TRAINING_RUN_POLL_INTERVAL_MS,
autoresearchPipelineLogic,
@@ -210,6 +211,36 @@ describe('autoresearchPipelineLogic', () => {
}
})
+ it('reloads runs while a person property cleanup is live, then stops', async () => {
+ jest.clearAllMocks()
+ jest.useFakeTimers()
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AUTORESEARCH], { [FEATURE_FLAGS.AUTORESEARCH]: true })
+ mockRetrieve.mockResolvedValue({ id: 'pipeline-1', name: 'Model' })
+ mockModelsList.mockResolvedValue({ results: [], next: null })
+ mockTrainingRunsList.mockResolvedValue({ results: [], next: null })
+ const cleanup = { id: 'cleanup-1', run_type: 'property_cleanup' } as const
+ mockRunsList
+ .mockResolvedValueOnce({ results: [makeScoreRun({ ...cleanup, status: 'running' })], next: null })
+ .mockResolvedValue({ results: [makeScoreRun({ ...cleanup, status: 'completed' })], next: null })
+ const logic = autoresearchPipelineLogic({ id: 'pipeline-1' })
+ try {
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadRunsSuccess'])
+ expect(logic.cache.disposables.registry.has('cleanupPoll')).toBe(true)
+
+ await expectLogic(logic, () =>
+ jest.advanceTimersByTime(PROPERTY_CLEANUP_POLL_INTERVAL_MS)
+ ).toDispatchActions(['loadRuns', 'loadRunsSuccess'])
+ expect(logic.values.latestPropertyCleanupRun?.status).toEqual('completed')
+ expect(logic.cache.disposables.registry.has('cleanupPoll')).toBe(false)
+ } finally {
+ logic.unmount()
+ jest.useRealTimers()
+ }
+ })
+
it.each([
['resumes a run started a minute ago', 60 * 1000, 'score-run-1'],
['ignores a run that has been running past the stale cutoff', 6 * 60 * 60 * 1000, null],
diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
index 45312781ab75..8a85d8b26fcf 100644
--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts
+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
@@ -32,6 +32,7 @@ import {
import {
autoresearchModelsList,
autoresearchOnlinePerformanceRetrieve,
+ autoresearchPartialUpdate,
autoresearchPauseCreate,
autoresearchResumeCreate,
autoresearchRetrieve,
@@ -110,12 +111,18 @@ export function pipelineTabFromUrl(value: unknown): AutoresearchPipelineTab | nu
return LEGACY_PIPELINE_TABS[value] ?? null
}
+/** Where a person changed whether scores are written to person profiles. */
+export type PersonPropertyToggleSource = 'actions_panel' | 'setup_tab'
+
/** How often the Score now button checks a running scoring run. */
export const SCORE_RUN_POLL_INTERVAL_MS = 5000
/** How often the Agent research tab reloads training runs while one is pending or running. */
export const TRAINING_RUN_POLL_INTERVAL_MS = 10000
+/** How often the runs reload while a person property cleanup is pending or running. A cleanup takes over an hour. */
+export const PROPERTY_CLEANUP_POLL_INTERVAL_MS = 30000
+
function isTrainingRunLive(run: AutoresearchTrainingRunApi): boolean {
return run.status === 'pending' || run.status === 'running'
}
@@ -298,6 +305,7 @@ export interface autoresearchPipelineLogicValues {
firstCheck: dayjs.Dayjs | null
hasLiveTrainingRun: boolean
latestChampionPerformance: OnlinePerformanceRowApi | null
+ latestPropertyCleanupRun: AutoresearchRunApi | null
lifecycleSteps: LifecycleStep[] | null
modelByTrainingRun: Record<string, AutoresearchModelApi>
models: AutoresearchModelApi[]
@@ -307,6 +315,7 @@ export interface autoresearchPipelineLogicValues {
onlinePerformance: OnlinePerformanceRowApi[]
onlinePerformanceError: boolean
onlinePerformanceLoading: boolean
+ personPropertyDisabledReason: string | undefined
pipeline: AutoresearchPipelineApi | null
pipelineError: boolean
pipelineLoading: boolean
@@ -326,6 +335,7 @@ export interface autoresearchPipelineLogicValues {
runsLoaded: boolean
runsLoading: boolean
savingCohortSegment: PredictionSegmentKey | null
+ savingWritePersonProperty: boolean
scoreResult: AutoresearchRunApi | null
scoreResultLoading: boolean
scoringCoverage: ScoringCoverage | null
@@ -673,6 +683,16 @@ export interface autoresearchPipelineLogicActions {
setTabFromUrl: (tab: AutoresearchPipelineTab | null) => {
tab: AutoresearchPipelineTab | null
}
+ setWritePersonProperty: (
+ enabled: boolean,
+ source: PersonPropertyToggleSource
+ ) => {
+ enabled: boolean
+ source: PersonPropertyToggleSource
+ }
+ setWritePersonPropertyFinished: () => {
+ value: true
+ }
startScorePolling: () => {
value: true
}
@@ -792,6 +812,11 @@ export interface autoresearchPipelineLogicMeta {
) => ExperimentLogGroup[]
agentNotes: (trainingRuns: AutoresearchTrainingRunApi[]) => AgentNotes | null
defaultTab: (pipeline: AutoresearchPipelineApi | null) => AutoresearchPipelineTab
+ latestPropertyCleanupRun: (runs: AutoresearchRunApi[]) => AutoresearchRunApi | null
+ personPropertyDisabledReason: (
+ pipeline: AutoresearchPipelineApi | null,
+ savingWritePersonProperty: boolean
+ ) => string | undefined
activeTab: (
selectedTab: AutoresearchPipelineTab | null,
defaultTab: AutoresearchPipelineTab
@@ -844,6 +869,8 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
experimentDetailsOpened: (point: SearchPoint) => ({ point }),
saveSegmentCohort: (segment: PredictionSegmentKey) => ({ segment }),
saveSegmentCohortFinished: true,
+ setWritePersonProperty: (enabled: boolean, source: PersonPropertyToggleSource) => ({ enabled, source }),
+ setWritePersonPropertyFinished: true,
setSegmentThresholds: (thresholds: PredictionSegmentThresholdsApi) => ({ thresholds }),
}),
reducers({
@@ -922,6 +949,13 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
saveSegmentCohortFinished: () => null,
},
],
+ savingWritePersonProperty: [
+ false,
+ {
+ setWritePersonProperty: () => true,
+ setWritePersonPropertyFinished: () => false,
+ },
+ ],
segmentThresholds: [
null as PredictionSegmentThresholdsApi | null,
{
@@ -1428,6 +1462,20 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
(pipeline: AutoresearchPipelineApi | null): AutoresearchPipelineTab =>
pipeline?.last_scored_at ? 'predictions' : 'agent_research',
],
+ latestPropertyCleanupRun: [
+ (s) => [s.runs],
+ (runs: AutoresearchRunApi[]): AutoresearchRunApi | null =>
+ runs.find((run) => run.run_type === 'property_cleanup') ?? null,
+ ],
+ personPropertyDisabledReason: [
+ (s) => [s.pipeline, s.savingWritePersonProperty],
+ (pipeline: AutoresearchPipelineApi | null, savingWritePersonProperty: boolean): string | undefined =>
+ savingWritePersonProperty
+ ? 'Wait for the person profile setting to save'
+ : pipeline && !pipeline.write_person_property
+ ? 'Turn on "Write scores to person profiles" to target people by score'
+ : undefined,
+ ],
activeTab: [
(s) => [s.selectedTab, s.defaultTab],
(
@@ -1544,6 +1592,16 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
if (values.activeScoreRun) {
actions.startScorePolling()
}
+ // Follow the cleanup to the end, so the setting shows when it finished or failed.
+ const cleanup = values.latestPropertyCleanupRun
+ if (!cleanup || !isScoreRunInProgress(cleanup)) {
+ cache.disposables.dispose('cleanupPoll')
+ } else if (!cache.disposables.registry.has('cleanupPoll')) {
+ cache.disposables.add(() => {
+ const timer = window.setInterval(() => actions.loadRuns(), PROPERTY_CLEANUP_POLL_INTERVAL_MS)
+ return () => clearInterval(timer)
+ }, 'cleanupPoll')
+ }
},
startScorePolling: () => {
if (cache.disposables.registry.has('scorePoll')) {
@@ -1690,6 +1748,44 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
setAccuracyCutoff: ({ cutoff }) => {
posthog.capture('autoresearch model accuracy cutoff changed', { pipeline_id: props.id, cutoff })
},
+ setWritePersonProperty: async ({ enabled, source }) => {
+ if (!values.currentTeamId) {
+ actions.setWritePersonPropertyFinished()
+ return
+ }
+ const teamId = String(values.currentTeamId)
+ try {
+ actions.loadPipelineSuccess(
+ await autoresearchPartialUpdate(teamId, props.id, { write_person_property: enabled })
+ )
+ posthog.capture('autoresearch model person property toggled', {
+ pipeline_id: props.id,
+ enabled,
+ source,
+ })
+ if (enabled) {
+ lemonToast.success(
+ 'Scores are now written to person profiles. People get the property over the next few scoring runs.'
+ )
+ } else {
+ // The cleanup records a run, so reload the runs to show it.
+ actions.loadRuns()
+ lemonToast.success(
+ 'Scores are no longer written to person profiles. The property is being removed.'
+ )
+ }
+ } catch {
+ posthog.capture('autoresearch model action failed', {
+ action: 'person_property',
+ pipeline_id: props.id,
+ enabled,
+ source,
+ })
+ lemonToast.error("Couldn't change the setting. Try again.")
+ } finally {
+ actions.setWritePersonPropertyFinished()
+ }
+ },
saveSegmentCohort: async ({ segment }) => {
const { pipeline, currentProjectId, segmentThresholds } = values
const definition = values.segmentDefinitions?.find(({ key }) => key === segment)
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index fbb12982a378..c16f12da2ba7 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -239,6 +239,8 @@ export interface AutoresearchPipelineApi {
* @maxLength 255
*/
output_person_property?: string
+ /** Whether live scoring writes the champion's score to output_person_property on each scored person. Feature flags, cohorts, workflows and insights that target people by score need it on. */
+ readonly write_person_property: boolean
/** Pipeline lifecycle status: draft, bootstrapping, running, converged, paused, or archived.
*
* * `draft` - Draft
@@ -406,6 +408,8 @@ export interface AutoresearchPipelineCreateApi {
* @maxLength 255
*/
output_person_property?: string
+ /** Write the champion's score to output_person_property on each scored person at every live scoring run. Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. Prediction events, validation and segments work without it. Turning it off, or archiving or deleting the pipeline while it is on, removes the property from the people it scored. */
+ write_person_property?: boolean
}
/**
@@ -563,6 +567,7 @@ export interface PaginatedAutoresearchModelListApi {
/**
* * `inference` - Inference
* * `validation` - Validation
+ * * `property_cleanup` - Property cleanup
*/
export type AutoresearchRunRunTypeEnumApi =
(typeof AutoresearchRunRunTypeEnumApi)[keyof typeof AutoresearchRunRunTypeEnumApi]
@@ -570,6 +575,7 @@ export type AutoresearchRunRunTypeEnumApi =
export const AutoresearchRunRunTypeEnumApi = {
Inference: 'inference',
Validation: 'validation',
+ PropertyCleanup: 'property_cleanup',
} as const
/**
@@ -606,7 +612,8 @@ export interface AutoresearchRunApi {
/** Type of run: 'inference' (daily scoring) or 'validation' (outcome evaluation).
*
* * `inference` - Inference
- * * `validation` - Validation */
+ * * `validation` - Validation
+ * * `property_cleanup` - Property cleanup */
run_type: AutoresearchRunRunTypeEnumApi
/** Run status: pending, running, completed, or failed.
*
@@ -1519,6 +1526,8 @@ export interface PatchedAutoresearchPipelineCreateApi {
* @maxLength 255
*/
output_person_property?: string
+ /** Write the champion's score to output_person_property on each scored person at every live scoring run. Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. Prediction events, validation and segments work without it. Turning it off, or archiving or deleting the pipeline while it is on, removes the property from the people it scored. */
+ write_person_property?: boolean
}
export interface ConfusionCountsApi {
diff --git a/products/autoresearch/frontend/generated/api.ts b/products/autoresearch/frontend/generated/api.ts
index 1f41959b799f..3efd4fdcf0cb 100644
--- a/products/autoresearch/frontend/generated/api.ts
+++ b/products/autoresearch/frontend/generated/api.ts
@@ -680,8 +680,8 @@ export const autoresearchUpdate = async (
id: string,
autoresearchPipelineCreateApi: AutoresearchPipelineCreateApi,
options?: RequestInit
-): Promise<AutoresearchPipelineCreateApi> => {
- return apiMutator<AutoresearchPipelineCreateApi>(getAutoresearchUpdateUrl(projectId, id), {
+): Promise<AutoresearchPipelineApi> => {
+ return apiMutator<AutoresearchPipelineApi>(getAutoresearchUpdateUrl(projectId, id), {
...options,
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -705,8 +705,8 @@ export const autoresearchPartialUpdate = async (
id: string,
patchedAutoresearchPipelineCreateApi?: PatchedAutoresearchPipelineCreateApi,
options?: RequestInit
-): Promise<AutoresearchPipelineCreateApi> => {
- return apiMutator<AutoresearchPipelineCreateApi>(getAutoresearchPartialUpdateUrl(projectId, id), {
+): Promise<AutoresearchPipelineApi> => {
+ return apiMutator<AutoresearchPipelineApi>(getAutoresearchPartialUpdateUrl(projectId, id), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -737,7 +737,7 @@ export const getAutoresearchArchiveCreateUrl = (projectId: string, id: string) =
}
/**
- * Soft-delete a pipeline. Stops daily scoring and training. Predictions and metrics are preserved. Refused while a training run is in progress.
+ * Soft-delete a pipeline. Stops daily scoring and training. Predictions and metrics are preserved. When write_person_property is on, a cleanup run removes output_person_property from the people it scored. Refused while a training run is in progress.
* @summary Archive a pipeline
*/
export const autoresearchArchiveCreate = async (
diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.ts
index f645749dd576..92675665a24c 100644
--- a/products/autoresearch/frontend/generated/api.zod.ts
+++ b/products/autoresearch/frontend/generated/api.zod.ts
@@ -119,6 +119,12 @@ export const AutoresearchCreateBody = /* @__PURE__ */ zod.object({
.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."
),
+ write_person_property: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Write the champion's score to output_person_property on each scored person at every live scoring run. Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. Prediction events, validation and segments work without it. Turning it off, or archiving or deleting the pipeline while it is on, removes the property from the people it scored."
+ ),
})
/**
@@ -578,6 +584,12 @@ export const AutoresearchUpdateBody = /* @__PURE__ */ zod.object({
.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."
),
+ write_person_property: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Write the champion's score to output_person_property on each scored person at every live scoring run. Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. Prediction events, validation and segments work without it. Turning it off, or archiving or deleting the pipeline while it is on, removes the property from the people it scored."
+ ),
})
/**
@@ -690,6 +702,12 @@ export const AutoresearchPartialUpdateBody = /* @__PURE__ */ zod.object({
.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."
),
+ write_person_property: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Write the champion's score to output_person_property on each scored person at every live scoring run. Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. Prediction events, validation and segments work without it. Turning it off, or archiving or deleting the pipeline while it is on, removes the property from the people it scored."
+ ),
})
/**
diff --git a/products/autoresearch/frontend/pipeline/PersonPropertySetting.tsx b/products/autoresearch/frontend/pipeline/PersonPropertySetting.tsx
new file mode 100644
index 000000000000..4fc323fb71a9
--- /dev/null
+++ b/products/autoresearch/frontend/pipeline/PersonPropertySetting.tsx
@@ -0,0 +1,89 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonDialog, LemonSwitch } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+
+import { PersonPropertyToggleSource, autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
+import type { AutoresearchRunApi } from '../generated/api.schemas'
+
+/** The switch that decides whether scoring writes each score to the person profile, with the last cleanup's state. */
+export function PersonPropertySetting({ source }: { source: PersonPropertyToggleSource }): JSX.Element | null {
+ const { pipeline, savingWritePersonProperty, latestPropertyCleanupRun } = useValues(autoresearchPipelineLogic)
+ const { setWritePersonProperty } = useActions(autoresearchPipelineLogic)
+
+ const outputProperty = pipeline?.output_person_property
+ if (!pipeline || !outputProperty) {
+ return null
+ }
+ const enabled = !!pipeline.write_person_property
+
+ const onChange = (checked: boolean): void => {
+ if (checked) {
+ setWritePersonProperty(true, source)
+ return
+ }
+ LemonDialog.open({
+ title: 'Stop writing scores to person profiles?',
+ description: `The ${outputProperty} property will be removed from the people this model scored. Feature flags, cohorts and workflows that use it will stop matching those people. Prediction events, segments and accuracy checks keep working.`,
+ primaryButton: {
+ children: 'Stop writing scores',
+ status: 'danger',
+ onClick: () => setWritePersonProperty(false, source),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+
+ return (
+ <div className="flex flex-col gap-1">
+ <LemonSwitch
+ bordered
+ fullWidth
+ label="Write scores to person profiles"
+ checked={enabled}
+ onChange={onChange}
+ loading={savingWritePersonProperty}
+ disabledReason={savingWritePersonProperty ? 'The setting is saving' : undefined}
+ data-attr={`autoresearch-person-property-toggle-${source}`}
+ />
+ <p className="text-xs text-secondary mb-0">
+ {enabled ? (
+ <span>
+ <span>Each scoring run sets </span>
+ <code>{outputProperty}</code>
+ <span>
+ {' '}
+ on the people it scores. People who were not scored yet get it over the next few scoring
+ runs.
+ </span>
+ </span>
+ ) : (
+ <span>
+ <span>
+ Turn this on to target people by score in feature flags, cohorts, workflows and insights.
+ Scores go to the{' '}
+ </span>
+ <code>{outputProperty}</code>
+ <span> person property.</span>
+ </span>
+ )}
+ </p>
+ {latestPropertyCleanupRun && !enabled && (
+ <p className="text-xs text-secondary mb-0">{cleanupStatus(latestPropertyCleanupRun)}</p>
+ )}
+ </div>
+ )
+}
+
+function cleanupStatus(run: AutoresearchRunApi): string {
+ if (run.status === 'pending' || run.status === 'running') {
+ return 'Removing the property from people who have it. This takes at least an hour, because a second pass removes scores that arrived late.'
+ }
+ if (run.status === 'failed') {
+ return "Couldn't remove the property from everyone this model scored. Turn the setting on and off again to retry."
+ }
+ const removedFrom = run.rows_scored ?? 0
+ const when = run.completed_at ? ` on ${dayjs(run.completed_at).format('MMM D, YYYY')}` : ''
+ return `Removed the property from ${removedFrom.toLocaleString()} ${removedFrom === 1 ? 'person' : 'people'}${when}.`
+}
diff --git a/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx b/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx
index 5601006d5b3f..a36e98af822e 100644
--- a/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx
+++ b/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx
@@ -9,10 +9,12 @@ import {
likelySegmentWorkflowUrl,
predictionBreakdownInsightUrl,
} from '../predictionSegments'
+import { PersonPropertySetting } from './PersonPropertySetting'
import { SectionCard } from './SectionCard'
export function PredictionActionsPanel(): JSX.Element | null {
- const { pipeline, segmentThresholds, segmentDefinitions } = useValues(autoresearchPipelineLogic)
+ const { pipeline, segmentThresholds, segmentDefinitions, personPropertyDisabledReason } =
+ useValues(autoresearchPipelineLogic)
const { reportPredictionLinkClicked } = useActions(autoresearchPipelineLogic)
const outputProperty = pipeline?.output_person_property
@@ -20,13 +22,15 @@ export function PredictionActionsPanel(): JSX.Element | null {
return null
}
const likelyRange = segmentDefinitions?.[0].probabilityRange.toLowerCase() ?? 'as likely'
- const segmentsLoading = !segmentThresholds ? 'Segments are still loading' : undefined
+ const segmentsLoading =
+ personPropertyDisabledReason ?? (!segmentThresholds ? 'Segments are still loading' : undefined)
return (
<SectionCard
title="Act on these predictions"
description="Each link opens a prefilled draft. Review it, then save."
>
+ <PersonPropertySetting source="actions_panel" />
<div className="flex flex-col gap-1">
<LemonButton
icon={<IconFlag />}
@@ -50,7 +54,12 @@ export function PredictionActionsPanel(): JSX.Element | null {
</LemonButton>
<LemonButton
icon={<IconGraph />}
- to={predictionBreakdownInsightUrl(pipeline, outputProperty)}
+ to={
+ personPropertyDisabledReason
+ ? undefined
+ : predictionBreakdownInsightUrl(pipeline, outputProperty)
+ }
+ disabledReason={personPropertyDisabledReason}
onClick={() => reportPredictionLinkClicked('insight')}
data-attr="autoresearch-predictions-create-insight"
fullWidth
diff --git a/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx b/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx
index beae077c0ae1..c76ff9d1cacb 100644
--- a/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx
+++ b/products/autoresearch/frontend/pipeline/PredictionSegmentCards.tsx
@@ -9,7 +9,7 @@ import { eventName } from '../pipelineQuestion'
import { PredictionSegmentDefinition, formatProbability, predictionSegmentPeopleUrl } from '../predictionSegments'
function SegmentCard({ segment }: { segment: PredictionSegmentDefinition }): JSX.Element {
- const { pipeline, predictionSegments, savingCohortSegment, segmentThresholds } =
+ const { pipeline, predictionSegments, savingCohortSegment, segmentThresholds, personPropertyDisabledReason } =
useValues(autoresearchPipelineLogic)
const { saveSegmentCohort } = useActions(autoresearchPipelineLogic)
@@ -50,11 +50,13 @@ function SegmentCard({ segment }: { segment: PredictionSegmentDefinition }): JSX
data-attr={`autoresearch-segment-save-cohort-${segment.key}`}
loading={savingCohortSegment === segment.key}
disabledReason={
- !stats
- ? 'Segments are still loading'
- : savingCohortSegment
- ? 'A cohort is being saved'
- : undefined
+ personPropertyDisabledReason
+ ? personPropertyDisabledReason
+ : !stats
+ ? 'Segments are still loading'
+ : savingCohortSegment
+ ? 'A cohort is being saved'
+ : undefined
}
onClick={() => saveSegmentCohort(segment.key)}
>
@@ -72,9 +74,11 @@ function SegmentCard({ segment }: { segment: PredictionSegmentDefinition }): JSX
disabledReason={
!outputProperty
? 'The model has no output property'
- : !segmentThresholds
- ? 'Segments are still loading'
- : undefined
+ : personPropertyDisabledReason
+ ? personPropertyDisabledReason
+ : !segmentThresholds
+ ? 'Segments are still loading'
+ : undefined
}
>
View people
diff --git a/products/autoresearch/frontend/pipeline/SetupTab.tsx b/products/autoresearch/frontend/pipeline/SetupTab.tsx
index 3b5fa0068ead..4a82d3f053e7 100644
--- a/products/autoresearch/frontend/pipeline/SetupTab.tsx
+++ b/products/autoresearch/frontend/pipeline/SetupTab.tsx
@@ -7,6 +7,7 @@ import { dayjs } from 'lib/dayjs'
import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
import { AutoresearchPipelineApi } from '../generated/api.schemas'
import { MetricCard } from './MetricCard'
+import { PersonPropertySetting } from './PersonPropertySetting'
import { SectionCard } from './SectionCard'
export function SetupTab(): JSX.Element {
@@ -35,6 +36,7 @@ export function SetupTab(): JSX.Element {
/>
</div>
</div>
+ <PersonPropertySetting source="setup_tab" />
<div>
<DetailRow label="Output person property">
<code>{pipeline.output_person_property ?? '—'}</code>
diff --git a/products/autoresearch/mcp/AGENTS.md b/products/autoresearch/mcp/AGENTS.md
index 46ee9c63eef8..1869127fa956 100644
--- a/products/autoresearch/mcp/AGENTS.md
+++ b/products/autoresearch/mcp/AGENTS.md
@@ -24,7 +24,7 @@ Tools are opt-in: `pnpm --filter=@posthog/mcp run scaffold-yaml -- --candidates
`autoresearch-score-create` scores today's prediction date on demand, so an MCP caller does not have to wait for the daily run after a champion is promoted. The training sandbox never sees it, because `TRAINING_MCP_SCOPES` has no `person:write`.
-Pipeline lifecycle (`archive`, `pause`, `resume`) stays disabled. The inference-run list is enabled so callers can check the status of background scoring.
+Pipeline lifecycle (`archive`, `pause`, `resume`) stays disabled. `autoresearch-partial-update` is enabled, needs `person:write`, and is marked destructive, because turning `write_person_property` off removes the property from the people the pipeline scored. The endpoint asks for `person:write` only when the request changes that field. The inference-run list is enabled so callers can check the status of background scoring.
The split matters when you change a description. An agent-facing description is a **contract**: `autoresearch-training-runs-iterations-create` has to tell the agent what a valid `feature_sql` looks like, because the server will reject anything that is not a read-only `SELECT` keyed on `person_id` and the agent has no other way to learn that.
diff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yaml
index a4b8f503b997..40d0761590bd 100644
--- a/products/autoresearch/mcp/tools.yaml
+++ b/products/autoresearch/mcp/tools.yaml
@@ -42,8 +42,9 @@ tools:
label and the source of the derived output property name). An action target needs the action:read scope.
horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from
target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique
- among the project's non-archived pipelines. After creating, call autoresearch-train-create to start an
- asynchronous agent training run.
+ among the project's non-archived pipelines. Scores are written to that person property only when
+ write_person_property is true (default false); prediction events, validation and segments work without it.
+ After creating, call autoresearch-train-create to start an asynchronous agent training run.
exclude_params:
- id
- created_by
@@ -169,6 +170,36 @@ tools:
the date had few positives. Rows exist only after a prediction horizon has elapsed and online validation has
run. Use limit to bound the number of dates (default 60).
feature_flag: autoresearch
+ autoresearch-partial-update:
+ operation: autoresearch_partial_update
+ enabled: true
+ scopes:
+ - autoresearch:write
+ - person:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ enrich_url: '{id}'
+ title: Update a pipeline
+ description: >
+ Change fields of an existing pipeline. Send only the fields to change. Use write_person_property to turn
+ person profile writes on or off. When it is on, each live scoring run writes the champion's score to
+ output_person_property on the people it scores, so feature flags, cohorts, workflows and insights can target
+ people by score. Scores fill in over the next few scoring runs, not all at once. Turning it off starts a
+ cleanup run that removes the property from the people this pipeline scored (see autoresearch-runs-list).
+ Changing write_person_property needs the person:write scope. Prediction events, online validation and
+ segments work with it off. target_event, target_definition, horizon_days, training_lookback_days and the two
+ populations cannot change once a model has been trained.
+ exclude_params:
+ - id
+ - created_by
+ - created_at
+ - updated_at
+ - last_scored_at
+ - status
+ - iteration_budget_remaining
+ feature_flag: autoresearch
autoresearch-pause-create:
operation: autoresearch_pause_create
enabled: false
diff --git a/products/autoresearch/skills/working-with-autoresearch/SKILL.md b/products/autoresearch/skills/working-with-autoresearch/SKILL.md
index 912c94703bee..1817a84a2669 100644
--- a/products/autoresearch/skills/working-with-autoresearch/SKILL.md
+++ b/products/autoresearch/skills/working-with-autoresearch/SKILL.md
@@ -23,7 +23,7 @@ For example, "which active users will open a report in the next 7 days?".
3. The server picks the **champion** from the kept experiments. The agent proposes; the backend decides.
4. Every cadence (daily by default, at 02:00 UTC), the champion scores the inference population.
Each scored person gets an `autoresearch_prediction` event with their probability.
- A person who resolves to a current distinct ID also gets the model's output person property, for example `predicted_p_adopt_insights_14d`.
+ When the model's `write_person_property` is on, a person who resolves to a current distinct ID also gets the model's output person property, for example `predicted_p_adopt_insights_14d`. It is off by default for new models. Turn it on with `autoresearch-partial-update` before you target people by score in a flag, cohort, workflow or insight. Turning it off removes the property from the people the model scored. Changing the setting needs the `person:write` scope.
5. When a prediction date's horizon has passed, online validation checks the scores against what really happened and records **realized AUC**.
In the PostHog UI the entity is a **model**. The API and tools call it a **pipeline**. Use "model" when you talk to people.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 580fe372b084..7794f68b232b 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1090,7 +1090,7 @@
}
},
"autoresearch-create": {
- "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. After creating, call autoresearch-train-create to start an asynchronous agent training run.",
+ "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. Scores are written to that person property only when write_person_property is true (default false); prediction events, validation and segments work without it. After creating, call autoresearch-train-create to start an asynchronous agent training run.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "Create a pipeline",
@@ -1179,6 +1179,21 @@
},
"feature_flag": "autoresearch"
},
+ "autoresearch-partial-update": {
+ "description": "Change fields of an existing pipeline. Send only the fields to change. Use write_person_property to turn person profile writes on or off. When it is on, each live scoring run writes the champion's score to output_person_property on the people it scores, so feature flags, cohorts, workflows and insights can target people by score. Scores fill in over the next few scoring runs, not all at once. Turning it off starts a cleanup run that removes the property from the people this pipeline scored (see autoresearch-runs-list). Changing write_person_property needs the person:write scope. Prediction events, online validation and segments work with it off. target_event, target_definition, horizon_days, training_lookback_days and the two populations cannot change once a model has been trained.",
+ "category": "Autoresearch",
+ "feature": "autoresearch",
+ "summary": "Update a pipeline",
+ "title": "Update a pipeline",
+ "required_scopes": ["autoresearch:write", "person:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "autoresearch"
+ },
"autoresearch-resolve-template-create": {
"description": "Start here to create a pipeline from a template. Resolve a template key and optional overrides into a ready-to-use pipeline config. An unknown key returns 400. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target_event is auto-resolved from your event schema — review resolved_activity_event and activity_event_alternatives, then re-resolve with a target_event override if the chosen event is wrong. For 'feature_adoption' and 'repeat_key_behavior', supply target_event (required). After resolving: (1) call autoresearch-validate-create with the resolved target_event, horizon_days, training_lookback_days, training_population and inference_population, so validation counts the same window the pipeline will use; (2) if can_proceed is true, call autoresearch-create with name set to suggested_name and the same five fields plus output_person_property. For an action target, pass the same target_definition to both calls; target_event then only labels it, and both calls need the action:read scope.",
"category": "Autoresearch",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d3c7bcbe6c53..14ebf29f024e 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1105,7 +1105,7 @@
}
},
"autoresearch-create": {
- "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. After creating, call autoresearch-train-create to start an asynchronous agent training run.",
+ "description": "Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this endpoint does not block on validation errors. The prediction target is either an event (pass target_event, e.g. '$pageview') or a PostHog action (pass target_definition = {\"type\": \"action\", \"action_id\": N} to predict a multi-step / property / autocapture matcher; target_event is then optional; it is the display label and the source of the derived output property name). An action target needs the action:read scope. horizon_days defaults to 7. The output person property (e.g. 'predicted_p_pageview') is auto-derived from target_event, or from the action name when target_event is omitted, if you do not set it. It must be unique among the project's non-archived pipelines. Scores are written to that person property only when write_person_property is true (default false); prediction events, validation and segments work without it. After creating, call autoresearch-train-create to start an asynchronous agent training run.",
"category": "Autoresearch",
"feature": "autoresearch",
"summary": "Create a pipeline",
@@ -1194,6 +1194,21 @@
},
"feature_flag": "autoresearch"
},
+ "autoresearch-partial-update": {
+ "description": "Change fields of an existing pipeline. Send only the fields to change. Use write_person_property to turn person profile writes on or off. When it is on, each live scoring run writes the champion's score to output_person_property on the people it scores, so feature flags, cohorts, workflows and insights can target people by score. Scores fill in over the next few scoring runs, not all at once. Turning it off starts a cleanup run that removes the property from the people this pipeline scored (see autoresearch-runs-list). Changing write_person_property needs the person:write scope. Prediction events, online validation and segments work with it off. target_event, target_definition, horizon_days, training_lookback_days and the two populations cannot change once a model has been trained.",
+ "category": "Autoresearch",
+ "feature": "autoresearch",
+ "summary": "Update a pipeline",
+ "title": "Update a pipeline",
+ "required_scopes": ["autoresearch:write", "person:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "autoresearch"
+ },
"autoresearch-resolve-template-create": {
"description": "Start here to create a pipeline from a template. Resolve a template key and optional overrides into a ready-to-use pipeline config. An unknown key returns 400. For activity-based templates ('likely_active_soon', 'at_risk_of_inactivity', 'return_after_first_use'), the target_event is auto-resolved from your event schema — review resolved_activity_event and activity_event_alternatives, then re-resolve with a target_event override if the chosen event is wrong. For 'feature_adoption' and 'repeat_key_behavior', supply target_event (required). After resolving: (1) call autoresearch-validate-create with the resolved target_event, horizon_days, training_lookback_days, training_population and inference_population, so validation counts the same window the pipeline will use; (2) if can_proceed is true, call autoresearch-create with name set to suggested_name and the same five fields plus output_person_property. For an action target, pass the same target_definition to both calls; target_event then only labels it, and both calls need the action:read scope.",
"category": "Autoresearch",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 939b30103759..88defa157b28 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14130,6 +14130,8 @@ export namespace Schemas {
* @maxLength 255
*/
output_person_property?: string;
+ /** Whether live scoring writes the champion's score to output_person_property on each scored person. Feature flags, cohorts, workflows and insights that target people by score need it on. */
+ readonly write_person_property: boolean;
/** Pipeline lifecycle status: draft, bootstrapping, running, converged, paused, or archived.
*
* * `draft` - Draft
@@ -14286,6 +14288,8 @@ export namespace Schemas {
* @maxLength 255
*/
output_person_property?: string;
+ /** Write the champion's score to output_person_property on each scored person at every live scoring run. Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. Prediction events, validation and segments work without it. Turning it off, or archiving or deleting the pipeline while it is on, removes the property from the people it scored. */
+ write_person_property?: boolean;
}
/**
@@ -14296,6 +14300,7 @@ export namespace Schemas {
/**
* * `inference` - Inference
* * `validation` - Validation
+ * * `property_cleanup` - Property cleanup
*/
export type AutoresearchRunRunTypeEnum = typeof AutoresearchRunRunTypeEnum[keyof typeof AutoresearchRunRunTypeEnum];
@@ -14303,6 +14308,7 @@ export namespace Schemas {
export const AutoresearchRunRunTypeEnum = {
Inference: 'inference',
Validation: 'validation',
+ PropertyCleanup: 'property_cleanup',
} as const;
/**
@@ -14334,7 +14340,8 @@ export namespace Schemas {
/** Type of run: 'inference' (daily scoring) or 'validation' (outcome evaluation).
*
* * `inference` - Inference
- * * `validation` - Validation */
+ * * `validation` - Validation
+ * * `property_cleanup` - Property cleanup */
run_type: AutoresearchRunRunTypeEnum;
/** Run status: pending, running, completed, or failed.
*
@@ -78334,6 +78341,8 @@ export namespace Schemas {
* @maxLength 255
*/
output_person_property?: string;
+ /** Write the champion's score to output_person_property on each scored person at every live scoring run. Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. Prediction events, validation and segments work without it. Turning it off, or archiving or deleting the pipeline while it is on, removes the property from the people it scored. */
+ write_person_property?: boolean;
}
/**
diff --git a/services/mcp/src/generated/autoresearch/api.ts b/services/mcp/src/generated/autoresearch/api.ts
index 39de830dc5a8..5d3acca9d311 100644
--- a/services/mcp/src/generated/autoresearch/api.ts
+++ b/services/mcp/src/generated/autoresearch/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 23 enabled ops
+ * PostHog API - MCP 24 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -146,6 +146,12 @@ export const AutoresearchCreateBody = () => zod.object({
.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."
),
+ write_person_property: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Write the champion's score to output_person_property on each scored person at every live scoring run. Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. Prediction events, validation and segments work without it. Turning it off, or archiving or deleting the pipeline while it is on, removes the property from the people it scored."
+ ),
})
/**
@@ -706,6 +712,133 @@ export const AutoresearchRetrieveParams = () => zod.object({
),
})
+/**
+ * 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 AutoresearchPartialUpdateParams = () => zod.object({
+ id: zod.string().describe('A UUID string identifying this autoresearch pipeline.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+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 = () => 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."
+ ),
+ write_person_property: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Write the champion's score to output_person_property on each scored person at every live scoring run. Default: false. Needed to target people by score in feature flags, cohorts, workflows and insights. Prediction events, validation and segments work without it. Turning it off, or archiving or deleting the pipeline while it is on, removes the property from the people it scored."
+ ),
+})
+
/**
* Return the realized metrics online validation recorded for each model on each validated prediction date, newest date first. Each row has realized AUC with a 95% interval, Brier score, calibration error, quantile calibration bins, mean predicted probability against the base rate, lift, and the model's role when it emitted and now. The rows come from the validation runs, so a former champion that a promotion archived keeps its history. Read-only; it runs no queries.
* @summary Read realized performance history
diff --git a/services/mcp/src/tools/generated/autoresearch.ts b/services/mcp/src/tools/generated/autoresearch.ts
index 707129815e1d..db1202108e9d 100644
--- a/services/mcp/src/tools/generated/autoresearch.ts
+++ b/services/mcp/src/tools/generated/autoresearch.ts
@@ -59,6 +59,9 @@ const autoresearchCreate = (): ToolBase<
if (params.output_person_property !== undefined) {
body['output_person_property'] = params.output_person_property
}
+ if (params.write_person_property !== undefined) {
+ body['write_person_property'] = params.write_person_property
+ }
const result = await context.api.request<Schemas.AutoresearchPipeline>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/`,
@@ -239,6 +242,72 @@ const autoresearchOnlinePerformanceRetrieve = (): ToolBase<
},
})
+const AutoresearchPartialUpdateSchema = () => {
+ const AutoresearchPartialUpdateBody = orvalSchemas.AutoresearchPartialUpdateBody()
+ const AutoresearchPartialUpdateParams = orvalSchemas.AutoresearchPartialUpdateParams()
+ return AutoresearchPartialUpdateParams.omit({ project_id: true }).extend(AutoresearchPartialUpdateBody.shape)
+}
+
+const autoresearchPartialUpdate = (): ToolBase<
+ ReturnType<typeof AutoresearchPartialUpdateSchema>,
+ WithPostHogUrl<Schemas.AutoresearchPipeline>
+> => ({
+ name: 'autoresearch-partial-update',
+ schema: AutoresearchPartialUpdateSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchPartialUpdateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.description !== undefined) {
+ body['description'] = params.description
+ }
+ if (params.target_event !== undefined) {
+ body['target_event'] = params.target_event
+ }
+ if (params.target_definition !== undefined) {
+ body['target_definition'] = params.target_definition
+ }
+ if (params.horizon_days !== undefined) {
+ body['horizon_days'] = params.horizon_days
+ }
+ if (params.training_lookback_days !== undefined) {
+ body['training_lookback_days'] = params.training_lookback_days
+ }
+ if (params.training_population !== undefined) {
+ body['training_population'] = params.training_population
+ }
+ if (params.inference_population !== undefined) {
+ body['inference_population'] = params.inference_population
+ }
+ if (params.cadence_days !== undefined) {
+ body['cadence_days'] = params.cadence_days
+ }
+ if (params.iteration_budget !== undefined) {
+ body['iteration_budget'] = params.iteration_budget
+ }
+ if (params.success_auc !== undefined) {
+ body['success_auc'] = params.success_auc
+ }
+ if (params.plateau_iterations !== undefined) {
+ body['plateau_iterations'] = params.plateau_iterations
+ }
+ if (params.output_person_property !== undefined) {
+ body['output_person_property'] = params.output_person_property
+ }
+ if (params.write_person_property !== undefined) {
+ body['write_person_property'] = params.write_person_property
+ }
+ const result = await context.api.request<Schemas.AutoresearchPipeline>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return await withPostHogUrl(context, result, `/autoresearch/${result.id}`)
+ },
+})
+
const AutoresearchResolveTemplateCreateSchema = () => {
const AutoresearchResolveTemplateCreateBody = orvalSchemas.AutoresearchResolveTemplateCreateBody()
return AutoresearchResolveTemplateCreateBody
@@ -873,6 +942,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'autoresearch-models-list': autoresearchModelsList,
'autoresearch-models-retrieve': autoresearchModelsRetrieve,
'autoresearch-online-performance-retrieve': autoresearchOnlinePerformanceRetrieve,
+ 'autoresearch-partial-update': autoresearchPartialUpdate,
'autoresearch-resolve-template-create': autoresearchResolveTemplateCreate,
'autoresearch-retrieve': autoresearchRetrieve,
'autoresearch-runs-list': autoresearchRunsList,