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(managed-migrations): add trial run API and UI (#71874)

José Sequeira04a53369d4c1
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 7cedc16e45d0..453454ff03bc 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -369,6 +369,7 @@ export const FEATURE_FLAGS = {
LOGS_SPARKLINE_SERVICE_BREAKDOWN: 'logs-sparkline-service-breakdown', // owner: #team-logs
LOGS_SQL_VIEW: 'logs-sql-view', // owner: #team-logs
LOGS_TABBED_VIEW: 'logs-tabbed-view', // owner: #team-logs
+ MANAGED_MIGRATIONS_TRIAL_RUNS: 'managed-migrations-trial-runs', // owner: #team-ingestion, gates trial runs for managed migrations
MANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analytics
MARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_COSTS_PRECOMPUTATION: 'marketing-analytics-costs-precomputation', // owner: @jabahamondes #team-web-analytics — gates reading the native cost precompute table
diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.py
index cf5f9420a08c..4fb106872f56 100644
--- a/posthog/settings/__init__.py
+++ b/posthog/settings/__init__.py
@@ -45,6 +45,7 @@ from posthog.settings.object_storage import *
from posthog.settings.temporal import *
from posthog.settings.web import *
from posthog.settings.data_warehouse import *
+from posthog.settings.managed_migrations import *
from posthog.settings.session_replay import *
from posthog.settings.session_replay_v2 import *
from posthog.settings.integrations import *
diff --git a/posthog/settings/managed_migrations.py b/posthog/settings/managed_migrations.py
new file mode 100644
index 000000000000..78eeaa592e1d
--- /dev/null
+++ b/posthog/settings/managed_migrations.py
@@ -0,0 +1,32 @@
+import os
+from typing import Optional
+
+from posthog.settings.base_variables import DEBUG, TEST
+from posthog.settings.object_storage import OBJECT_STORAGE_REGION
+
+# S3-compatible store holding managed-migration trial run output (browsable
+# JSONL pages + summary), written by the batch-import worker (its TRIAL_BUCKET_*
+# config must point at the same bucket/prefix) and read back by the API. Retention
+# is enforced by an S3 lifecycle rule on the prefix, not by the application.
+if TEST or DEBUG:
+ MANAGED_MIGRATIONS_TRIAL_S3_ENDPOINT = os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_ENDPOINT", "http://seaweedfs:8333")
+ MANAGED_MIGRATIONS_TRIAL_S3_ACCESS_KEY_ID: Optional[str] = os.getenv(
+ "MANAGED_MIGRATIONS_TRIAL_S3_ACCESS_KEY_ID", "any"
+ )
+ MANAGED_MIGRATIONS_TRIAL_S3_SECRET_ACCESS_KEY: Optional[str] = os.getenv(
+ "MANAGED_MIGRATIONS_TRIAL_S3_SECRET_ACCESS_KEY", "any"
+ )
+else:
+ MANAGED_MIGRATIONS_TRIAL_S3_ENDPOINT = os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_ENDPOINT", "")
+ # Default to None (not "") so boto falls back to the ambient AWS credentials
+ # (IRSA / instance role) in production.
+ MANAGED_MIGRATIONS_TRIAL_S3_ACCESS_KEY_ID = os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_ACCESS_KEY_ID", "") or None
+ MANAGED_MIGRATIONS_TRIAL_S3_SECRET_ACCESS_KEY = (
+ os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_SECRET_ACCESS_KEY", "") or None
+ )
+
+MANAGED_MIGRATIONS_TRIAL_S3_REGION = os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_REGION") or OBJECT_STORAGE_REGION
+# Empty bucket outside DEBUG/TEST means trial results are unavailable (the API
+# responds accordingly); set it wherever the worker fleet has a trial bucket.
+MANAGED_MIGRATIONS_TRIAL_S3_BUCKET = os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_BUCKET", "posthog" if TEST or DEBUG else "")
+MANAGED_MIGRATIONS_TRIAL_S3_PREFIX = os.getenv("MANAGED_MIGRATIONS_TRIAL_S3_PREFIX", "trial_runs")
diff --git a/products/managed_migrations/backend/api/batch_imports.py b/products/managed_migrations/backend/api/batch_imports.py
index 3dcf5b162bc8..fccb57556ec9 100644
--- a/products/managed_migrations/backend/api/batch_imports.py
+++ b/products/managed_migrations/backend/api/batch_imports.py
@@ -1,9 +1,13 @@
import uuid
+from copy import deepcopy
from datetime import timedelta
+from typing import cast
+
+from django.db import transaction
import posthoganalytics
from django_filters.rest_framework import DjangoFilterBackend
-from drf_spectacular.utils import extend_schema_field
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field
from rest_framework import filters, serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
@@ -14,7 +18,45 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.models.user import User
-from products.managed_migrations.backend.models.batch_imports import BatchImport, ContentType, DateRangeExportSource
+from products.managed_migrations.backend import trial_storage
+from products.managed_migrations.backend.models.batch_imports import (
+ BatchImport,
+ BatchImportConfigBuilder,
+ ContentType,
+ DateRangeExportSource,
+)
+
+TRIAL_RECORD_LIMIT_DEFAULT = 1_000
+TRIAL_RECORD_LIMIT_MAX = 50_000
+
+
+class BatchImportTrialOptionsMixin(serializers.Serializer):
+ """Write-only trial options shared by every create serializer."""
+
+ is_trial = serializers.BooleanField(
+ write_only=True,
+ required=False,
+ default=False,
+ help_text="Run a trial instead of a real import: parse and transform up to trial_record_limit source records and store browsable results, without ingesting any events.",
+ )
+ trial_record_limit = serializers.IntegerField(
+ write_only=True,
+ required=False,
+ default=TRIAL_RECORD_LIMIT_DEFAULT,
+ min_value=1,
+ max_value=TRIAL_RECORD_LIMIT_MAX,
+ help_text=f"Maximum number of source records to process in a trial run (1 to {TRIAL_RECORD_LIMIT_MAX}). Ignored unless is_trial is set.",
+ )
+
+
+def _apply_output_sink(config_builder: BatchImportConfigBuilder, validated_data: dict) -> None:
+ """Point the job at its output: the trial results bucket for trial runs, capture otherwise."""
+ if validated_data.get("is_trial"):
+ config_builder.to_trial_output(
+ record_limit=validated_data.get("trial_record_limit", TRIAL_RECORD_LIMIT_DEFAULT)
+ )
+ else:
+ config_builder.to_capture(send_rate=1000)
class BatchImportSerializer(serializers.ModelSerializer):
@@ -78,7 +120,7 @@ class BatchImportSerializer(serializers.ModelSerializer):
return None
-class BatchImportS3SourceCreateSerializer(BatchImportSerializer):
+class BatchImportS3SourceCreateSerializer(BatchImportTrialOptionsMixin, BatchImportSerializer):
"""Serializer for creating BatchImports with config builder methods"""
content_type = serializers.ChoiceField(
@@ -129,6 +171,8 @@ class BatchImportS3SourceCreateSerializer(BatchImportSerializer):
"import_events",
"generate_identify_events",
"generate_group_identify_events",
+ "is_trial",
+ "trial_record_limit",
]
read_only_fields = [
"id",
@@ -172,13 +216,13 @@ class BatchImportS3SourceCreateSerializer(BatchImportSerializer):
.with_generate_group_identify_events(validated_data.get("generate_group_identify_events", False))
)
- config_builder.to_capture(send_rate=1000)
+ _apply_output_sink(config_builder, validated_data)
batch_import.save()
return batch_import
-class BatchImportS3GzipSourceCreateSerializer(BatchImportSerializer):
+class BatchImportS3GzipSourceCreateSerializer(BatchImportTrialOptionsMixin, BatchImportSerializer):
"""Serializer for creating BatchImports with S3 gzipped JSONL source"""
content_type = serializers.ChoiceField(
@@ -229,6 +273,8 @@ class BatchImportS3GzipSourceCreateSerializer(BatchImportSerializer):
"import_events",
"generate_identify_events",
"generate_group_identify_events",
+ "is_trial",
+ "trial_record_limit",
]
read_only_fields = [
"id",
@@ -272,13 +318,13 @@ class BatchImportS3GzipSourceCreateSerializer(BatchImportSerializer):
.with_generate_group_identify_events(validated_data.get("generate_group_identify_events", False))
)
- config_builder.to_capture(send_rate=1000)
+ _apply_output_sink(config_builder, validated_data)
batch_import.save()
return batch_import
-class BatchImportDateRangeSourceCreateSerializer(BatchImportSerializer):
+class BatchImportDateRangeSourceCreateSerializer(BatchImportTrialOptionsMixin, BatchImportSerializer):
"""Serializer for creating BatchImports with date range source (mixpanel, amplitude, etc.)"""
start_date = serializers.DateTimeField(write_only=True, required=True)
@@ -331,6 +377,8 @@ class BatchImportDateRangeSourceCreateSerializer(BatchImportSerializer):
"import_events",
"generate_identify_events",
"generate_group_identify_events",
+ "is_trial",
+ "trial_record_limit",
]
read_only_fields = [
"id",
@@ -410,7 +458,7 @@ class BatchImportDateRangeSourceCreateSerializer(BatchImportSerializer):
.with_generate_group_identify_events(validated_data.get("generate_group_identify_events", True))
)
- config_builder.to_capture(send_rate=1000)
+ _apply_output_sink(config_builder, validated_data)
batch_import.save()
return batch_import
@@ -428,6 +476,11 @@ class BatchImportResponseSerializer(serializers.ModelSerializer):
content_type = serializers.SerializerMethodField()
status_message = serializers.CharField(source="display_status_message", allow_null=True)
display_status = serializers.SerializerMethodField()
+ is_trial = serializers.BooleanField(
+ read_only=True, help_text="Whether this job is a trial run (stores browsable results instead of ingesting)."
+ )
+ trial_record_limit = serializers.SerializerMethodField()
+ promoted_from_trial_id = serializers.SerializerMethodField()
class Meta:
model = BatchImport
@@ -443,29 +496,42 @@ class BatchImportResponseSerializer(serializers.ModelSerializer):
"created_at",
"status_message",
"state",
+ "is_trial",
+ "trial_record_limit",
+ "promoted_from_trial_id",
]
+ @extend_schema_field({"type": "string"})
def get_source_type(self, obj):
"""Extract source type from import_config"""
source = obj.import_config.get("source", {})
return source.get("type", "s3")
+ @extend_schema_field({"type": "string", "nullable": True})
def get_start_date(self, obj):
"""Extract start date from import_config"""
source = obj.import_config.get("source", {})
return source.get("start")
+ @extend_schema_field({"type": "string", "nullable": True})
def get_end_date(self, obj):
"""Extract end date from import_config"""
source = obj.import_config.get("source", {})
return source.get("end")
+ @extend_schema_field({"type": "string"})
def get_content_type(self, obj):
"""Extract content type from import_config"""
data_format = obj.import_config.get("data_format", {})
content = data_format.get("content", {})
return content.get("type", "captured")
+ @extend_schema_field({"type": "string", "nullable": True})
+ def get_promoted_from_trial_id(self, obj):
+ """Id of the trial run this real import was promoted from, if any."""
+ return obj.import_config.get("promoted_from_trial_id")
+
+ @extend_schema_field({"type": "object", "nullable": True})
def get_created_by(self, obj):
if obj.created_by_id:
try:
@@ -475,11 +541,35 @@ class BatchImportResponseSerializer(serializers.ModelSerializer):
return None
return None
+ @extend_schema_field({"type": "string"})
def get_display_status(self, obj):
if obj.status == BatchImport.Status.RUNNING and obj.lease_id is None:
return "waiting_to_start"
return obj.status
+ @extend_schema_field({"type": "integer", "nullable": True})
+ def get_trial_record_limit(self, obj):
+ """The trial's source-record cap from the sink config; null for real imports."""
+ if not obj.is_trial:
+ return None
+ return obj.import_config.get("sink", {}).get("record_limit")
+
+
+class TrialRecordsResponseSerializer(serializers.Serializer):
+ """One page of trial-run results, proxied from the trial output store."""
+
+ records = serializers.ListField(
+ child=serializers.JSONField(),
+ help_text="Trial records in source order: each has seq (global index), source (the original source event), outputs (the event(s) it would produce), and error (why it would be dropped, if it would be).",
+ )
+ page = serializers.IntegerField(help_text="Zero-based index of this page.")
+ total_pages = serializers.IntegerField(help_text="Number of result pages written so far.")
+ total_records = serializers.IntegerField(help_text="Number of source records processed so far.")
+ summary = serializers.JSONField(
+ allow_null=True,
+ help_text="Running aggregates: output event name counts, error counts, dropped/skipped totals, timestamp range.",
+ )
+
class BatchImportViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""Viewset for BatchImport model"""
@@ -529,43 +619,70 @@ class BatchImportViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer = BatchImportResponseSerializer(queryset, many=True)
return Response({"results": serializer.data})
- def create(self, request: Request, **kwargs) -> Response:
- """Create a new managed migration/batch import."""
- existing_running_import = BatchImport.objects.filter(
- team_id=self.team_id, status=BatchImport.Status.RUNNING
- ).first()
-
- if existing_running_import:
+ def _running_import_conflict(self, is_trial: bool) -> Response | None:
+ """One running job per team and per kind: a trial only conflicts with
+ another running trial, a real import only with another real import, so
+ users can trial their next migration while one is ingesting.
+
+ The kind check runs in Python (a team has at most a handful of running
+ rows): a JSON-path exclude() would silently drop rows whose config has
+ no sink key at all, letting a running legacy-shaped import go unnoticed.
+ """
+ running = BatchImport.objects.filter(team_id=self.team_id, status=BatchImport.Status.RUNNING)
+ conflict = next((job for job in running if job.is_trial == is_trial), None)
+ if conflict is None:
+ return None
+ if is_trial:
return Response(
{
- "error": "Cannot create a new batch import while another import is already running for this organization.",
- "detail": f"Please wait for the current import (ID: {existing_running_import.id}) to complete or pause it before starting a new one.",
+ "error": "Cannot create a new trial run while another trial is already running for this project.",
+ "detail": f"Please wait for the current trial (ID: {conflict.id}) to complete before starting a new one.",
},
status=status.HTTP_400_BAD_REQUEST,
)
+ return Response(
+ {
+ "error": "Cannot create a new batch import while another import is already running for this organization.",
+ "detail": f"Please wait for the current import (ID: {conflict.id}) to complete or pause it before starting a new one.",
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
- serializer = self.get_serializer(data=request.data)
- serializer.is_valid(raise_exception=True)
- migration = serializer.save()
-
- source_type = request.data.get("source_type", "unknown")
- content_type = request.data.get("content_type", "unknown")
-
+ def _capture_batch_import_created(self, request: Request, migration: BatchImport, properties: dict) -> None:
distinct_id = (
request.user.distinct_id
if request.user.is_authenticated and request.user.distinct_id
else str(uuid.uuid4())
)
-
posthoganalytics.capture(
"batch import created",
distinct_id=distinct_id,
properties={
"batch_import_id": migration.id,
- "source_type": source_type,
- "content_type": content_type,
"team_id": self.team_id,
+ "is_trial": migration.is_trial,
"$process_person_profile": False,
+ **properties,
+ },
+ )
+
+ def create(self, request: Request, **kwargs) -> Response:
+ """Create a new managed migration/batch import."""
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ conflict = self._running_import_conflict(is_trial=serializer.validated_data.get("is_trial", False))
+ if conflict:
+ return conflict
+
+ migration = serializer.save()
+
+ self._capture_batch_import_created(
+ request,
+ migration,
+ {
+ "source_type": request.data.get("source_type", "unknown"),
+ "content_type": request.data.get("content_type", "unknown"),
},
)
@@ -616,3 +733,121 @@ class BatchImportViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
return Response({"status": "resumed"})
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "page", int, description="Zero-based results page index (see total_pages in the response)."
+ )
+ ],
+ responses={200: TrialRecordsResponseSerializer},
+ )
+ @action(methods=["GET"], detail=True)
+ def trial_records(self, request: Request, **kwargs) -> Response:
+ """Fetch one page of a trial run's results (source event paired with its would-be output events)."""
+ batch_import = self.get_object()
+
+ if not batch_import.is_trial:
+ return Response({"error": "This import is not a trial run"}, status=status.HTTP_400_BAD_REQUEST)
+
+ try:
+ page = int(request.query_params.get("page", "0"))
+ except ValueError:
+ return Response({"error": "page must be an integer"}, status=status.HTTP_400_BAD_REQUEST)
+ if page < 0:
+ return Response({"error": "page must be non-negative"}, status=status.HTTP_400_BAD_REQUEST)
+
+ trial = batch_import.trial_progress() or {}
+ total_pages = trial.get("pages_written", 0)
+ if total_pages == 0:
+ # A trial that emitted no records has no pages — show an empty state, not an error.
+ return Response(
+ {
+ "records": [],
+ "page": 0,
+ "total_pages": 0,
+ "total_records": trial.get("records_emitted", 0),
+ "summary": trial.get("summary"),
+ }
+ )
+ if page >= total_pages:
+ return Response(
+ {"error": f"Page {page} does not exist", "total_pages": total_pages},
+ status=status.HTTP_404_NOT_FOUND,
+ )
+
+ try:
+ records = trial_storage.read_trial_page(batch_import.team_id, str(batch_import.id), page)
+ except trial_storage.TrialResultsUnavailable:
+ return Response(
+ {"error": "Trial results have expired and are no longer available"},
+ status=status.HTTP_410_GONE,
+ )
+
+ return Response(
+ {
+ "records": records,
+ "page": page,
+ "total_pages": total_pages,
+ "total_records": trial.get("records_emitted", 0),
+ "summary": trial.get("summary"),
+ }
+ )
+
+ @extend_schema(request=None, responses={201: BatchImportResponseSerializer})
+ @action(methods=["POST"], detail=True)
+ def promote(self, request: Request, **kwargs) -> Response:
+ """Start the real import from a completed trial run, reusing its source config and credentials."""
+ trial = self.get_object()
+
+ if not trial.is_trial:
+ return Response({"error": "Only trial runs can be promoted"}, status=status.HTTP_400_BAD_REQUEST)
+ if trial.status != BatchImport.Status.COMPLETED:
+ return Response({"error": "Only completed trial runs can be promoted"}, status=status.HTTP_400_BAD_REQUEST)
+
+ with transaction.atomic():
+ # Lock the trial row so concurrent promotes of the same trial serialize
+ # behind the already-promoted check below.
+ trial = BatchImport.objects.select_for_update().get(pk=trial.pk)
+
+ promoted = BatchImport.objects.filter(
+ team_id=self.team_id, import_config__promoted_from_trial_id=str(trial.id)
+ ).first()
+ if promoted is not None:
+ return Response(
+ {
+ "error": "This trial has already been promoted to a full import.",
+ "detail": f"The import created from this trial is {promoted.id}.",
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ conflict = self._running_import_conflict(is_trial=False)
+ if conflict:
+ return conflict
+
+ import_config = deepcopy(trial.import_config)
+ import_config["sink"] = {"type": "capture", "send_rate": 1000}
+ # The worker ignores unknown config keys and never writes import_config
+ # back, so this link doubles as the promotion single-use marker.
+ import_config["promoted_from_trial_id"] = str(trial.id)
+
+ migration = BatchImport.objects.create(
+ team_id=self.team_id,
+ created_by_id=cast(User, request.user).pk,
+ import_config=import_config,
+ secrets=trial.secrets,
+ )
+
+ response_data = BatchImportResponseSerializer(migration).data
+ self._capture_batch_import_created(
+ request,
+ migration,
+ {
+ "promoted_from_trial_id": str(trial.id),
+ "source_type": response_data["source_type"],
+ "content_type": response_data["content_type"],
+ },
+ )
+
+ return Response(response_data, status=status.HTTP_201_CREATED)
diff --git a/products/managed_migrations/backend/api/test/test_batch_imports.py b/products/managed_migrations/backend/api/test/test_batch_imports.py
index 542b8714b1b9..09ac125a8393 100644
--- a/products/managed_migrations/backend/api/test/test_batch_imports.py
+++ b/products/managed_migrations/backend/api/test/test_batch_imports.py
@@ -1,6 +1,7 @@
from datetime import UTC, datetime, timedelta
from posthog.test.base import APIBaseTest, BaseTest
+from unittest.mock import patch
from django.contrib.admin.sites import AdminSite
from django.contrib.messages import get_messages
@@ -11,6 +12,7 @@ from django.test import RequestFactory
from parameterized import parameterized
+from products.managed_migrations.backend import trial_storage
from products.managed_migrations.backend.admin.batch_imports import BatchImportAdmin
from products.managed_migrations.backend.models.batch_imports import BatchImport, BatchImportConfigBuilder, ContentType
@@ -966,3 +968,222 @@ class TestBatchImportAPI(APIBaseTest):
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["attr"], "endpoint_url")
+
+
+class TestBatchImportTrialAPI(APIBaseTest):
+ S3_PAYLOAD = {
+ "source_type": "s3",
+ "content_type": "captured",
+ "s3_bucket": "test-bucket",
+ "s3_region": "us-east-1",
+ "s3_prefix": "data/",
+ "access_key": "test-key",
+ "secret_key": "test-secret",
+ }
+
+ def _create_import(self, status=BatchImport.Status.RUNNING, is_trial=False, state=None) -> BatchImport:
+ sink = {"type": "trial_s3", "record_limit": 100} if is_trial else {"type": "capture", "send_rate": 1000}
+ return BatchImport.objects.create(
+ team=self.team,
+ created_by_id=self.user.id,
+ import_config={"source": {"type": "s3"}, "sink": sink},
+ secrets={"access_key": "k", "secret_key": "s"},
+ status=status,
+ state=state,
+ )
+
+ def test_create_trial_sets_trial_sink_and_limit(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/managed_migrations",
+ {**self.S3_PAYLOAD, "is_trial": True, "trial_record_limit": 500},
+ )
+
+ self.assertEqual(response.status_code, 201, response.json())
+ batch_import = BatchImport.objects.get(id=response.json()["id"])
+ self.assertEqual(batch_import.import_config["sink"], {"type": "trial_s3", "record_limit": 500})
+ self.assertTrue(response.json()["is_trial"])
+ self.assertEqual(response.json()["trial_record_limit"], 500)
+
+ @parameterized.expand([("zero", 0), ("above_max", 50_001)])
+ def test_trial_record_limit_out_of_bounds_is_rejected(self, _name, limit):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/managed_migrations",
+ {**self.S3_PAYLOAD, "is_trial": True, "trial_record_limit": limit},
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.json()["attr"], "trial_record_limit")
+
+ def test_trial_allowed_while_real_import_is_running(self):
+ self._create_import(is_trial=False)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/managed_migrations",
+ {**self.S3_PAYLOAD, "is_trial": True},
+ )
+
+ self.assertEqual(response.status_code, 201, response.json())
+
+ def test_real_import_allowed_while_trial_is_running(self):
+ self._create_import(is_trial=True)
+
+ response = self.client.post(f"/api/projects/{self.team.id}/managed_migrations", self.S3_PAYLOAD)
+
+ self.assertEqual(response.status_code, 201, response.json())
+
+ def test_second_trial_is_blocked_while_one_is_running(self):
+ existing = self._create_import(is_trial=True)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/managed_migrations",
+ {**self.S3_PAYLOAD, "is_trial": True},
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("trial", response.json()["error"])
+ self.assertIn(str(existing.id), response.json()["detail"])
+
+ def test_trial_records_rejects_non_trial_imports(self):
+ batch_import = self._create_import(is_trial=False)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/managed_migrations/{batch_import.id}/trial_records")
+
+ self.assertEqual(response.status_code, 400)
+
+ def test_trial_records_returns_page_with_progress_metadata(self):
+ trial_state = {
+ "parts": [],
+ "trial": {
+ "records_emitted": 4,
+ "pages_written": 2,
+ "summary": {"source_records": 4, "dropped_records": 1},
+ },
+ }
+ batch_import = self._create_import(status=BatchImport.Status.COMPLETED, is_trial=True, state=trial_state)
+ records = [{"seq": 2, "source": {"event": "a"}, "outputs": [], "error": None}]
+
+ with patch(
+ "products.managed_migrations.backend.api.batch_imports.trial_storage.read_trial_page",
+ return_value=records,
+ ) as mock_read:
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/managed_migrations/{batch_import.id}/trial_records?page=1"
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.json(),
+ {
+ "records": records,
+ "page": 1,
+ "total_pages": 2,
+ "total_records": 4,
+ "summary": {"source_records": 4, "dropped_records": 1},
+ },
+ )
+ mock_read.assert_called_once_with(self.team.id, str(batch_import.id), 1)
+
+ def test_trial_records_with_no_pages_returns_empty_state(self):
+ batch_import = self._create_import(
+ status=BatchImport.Status.COMPLETED,
+ is_trial=True,
+ state={"parts": [], "trial": {"records_emitted": 0, "pages_written": 0, "summary": {"source_records": 0}}},
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/managed_migrations/{batch_import.id}/trial_records")
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.json(),
+ {
+ "records": [],
+ "page": 0,
+ "total_pages": 0,
+ "total_records": 0,
+ "summary": {"source_records": 0},
+ },
+ )
+
+ def test_trial_records_page_out_of_range_is_404(self):
+ batch_import = self._create_import(
+ status=BatchImport.Status.COMPLETED,
+ is_trial=True,
+ state={"parts": [], "trial": {"records_emitted": 4, "pages_written": 2, "summary": {}}},
+ )
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/managed_migrations/{batch_import.id}/trial_records?page=2"
+ )
+
+ self.assertEqual(response.status_code, 404)
+ self.assertEqual(response.json()["total_pages"], 2)
+
+ def test_trial_records_expired_results_are_410(self):
+ batch_import = self._create_import(
+ status=BatchImport.Status.COMPLETED,
+ is_trial=True,
+ state={"parts": [], "trial": {"records_emitted": 4, "pages_written": 2, "summary": {}}},
+ )
+
+ with patch(
+ "products.managed_migrations.backend.api.batch_imports.trial_storage.read_trial_page",
+ side_effect=trial_storage.TrialResultsUnavailable("gone"),
+ ):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/managed_migrations/{batch_import.id}/trial_records"
+ )
+
+ self.assertEqual(response.status_code, 410)
+
+ def test_promote_creates_real_import_with_capture_sink_and_copied_secrets(self):
+ trial = self._create_import(status=BatchImport.Status.COMPLETED, is_trial=True)
+
+ response = self.client.post(f"/api/projects/{self.team.id}/managed_migrations/{trial.id}/promote")
+
+ self.assertEqual(response.status_code, 201, response.json())
+ promoted = BatchImport.objects.get(id=response.json()["id"])
+ self.assertNotEqual(promoted.id, trial.id)
+ self.assertEqual(promoted.import_config["sink"], {"type": "capture", "send_rate": 1000})
+ self.assertEqual(promoted.import_config["source"], trial.import_config["source"])
+ self.assertEqual(promoted.secrets, trial.secrets)
+ self.assertEqual(promoted.status, BatchImport.Status.RUNNING)
+ self.assertFalse(response.json()["is_trial"])
+ self.assertEqual(response.json()["promoted_from_trial_id"], str(trial.id))
+
+ def test_promote_is_single_use(self):
+ trial = self._create_import(status=BatchImport.Status.COMPLETED, is_trial=True)
+
+ first = self.client.post(f"/api/projects/{self.team.id}/managed_migrations/{trial.id}/promote")
+ self.assertEqual(first.status_code, 201, first.json())
+
+ # Once the promoted import is no longer running, the RUNNING-conflict
+ # check no longer applies — re-promotion must still be rejected.
+ BatchImport.objects.filter(id=first.json()["id"]).update(status=BatchImport.Status.COMPLETED)
+
+ second = self.client.post(f"/api/projects/{self.team.id}/managed_migrations/{trial.id}/promote")
+
+ self.assertEqual(second.status_code, 400)
+ self.assertIn("already been promoted", second.json()["error"])
+ self.assertEqual(BatchImport.objects.filter(team_id=self.team.id).exclude(id=trial.id).count(), 1)
+
+ @parameterized.expand(
+ [
+ ("not_a_trial", False, BatchImport.Status.COMPLETED),
+ ("not_completed", True, BatchImport.Status.RUNNING),
+ ]
+ )
+ def test_promote_rejects_ineligible_jobs(self, _name, is_trial, job_status):
+ batch_import = self._create_import(status=job_status, is_trial=is_trial)
+
+ response = self.client.post(f"/api/projects/{self.team.id}/managed_migrations/{batch_import.id}/promote")
+
+ self.assertEqual(response.status_code, 400)
+
+ def test_promote_blocked_while_real_import_is_running(self):
+ trial = self._create_import(status=BatchImport.Status.COMPLETED, is_trial=True)
+ self._create_import(is_trial=False)
+
+ response = self.client.post(f"/api/projects/{self.team.id}/managed_migrations/{trial.id}/promote")
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("Cannot create a new batch import", response.json()["error"])
diff --git a/products/managed_migrations/backend/models/batch_imports.py b/products/managed_migrations/backend/models/batch_imports.py
index dc6aaf0c7985..f54d75b89588 100644
--- a/products/managed_migrations/backend/models/batch_imports.py
+++ b/products/managed_migrations/backend/models/batch_imports.py
@@ -1,6 +1,7 @@
from enum import Enum
from typing import Self
+from django.conf import settings
from django.db import models
from posthog.helpers.encrypted_fields import EncryptedJSONStringField
@@ -61,6 +62,19 @@ class BatchImport(ModelActivityMixin, UUIDTModel):
def config(self) -> "BatchImportConfigBuilder":
return self._config_builder
+ @property
+ def is_trial(self) -> bool:
+ """Whether this job is a trial run (parses and stores browsable results
+ instead of capturing events). Derived from the sink type — trials have
+ no dedicated column."""
+ return ((self.import_config or {}).get("sink") or {}).get("type") == "trial_s3"
+
+ def trial_progress(self) -> dict | None:
+ """The worker-owned trial progress (records_emitted, pages_written,
+ running summary) from the state JSON, or None before the worker has
+ flushed any."""
+ return (self.state or {}).get("trial")
+
def parts_progress(self) -> tuple[int, int, dict | None]:
"""Summarize worker part state: (done_count, total_count, first_unfinished_part).
@@ -204,6 +218,11 @@ class BatchImportConfigBuilder:
}
if endpoint_url:
source["endpoint_url"] = endpoint_url
+ if settings.DEBUG:
+ # Local dev: let custom endpoints point at the dev stack
+ # (SeaweedFS on localhost) — the worker's SSRF guard blocks
+ # non-public IPs otherwise. Never set outside DEBUG.
+ source["allow_internal_ips"] = True
self.batch_import.import_config["source"] = source
self.batch_import.secrets[access_key_id_key] = access_key_id
self.batch_import.secrets[secret_access_key_key] = secret_access_key
@@ -230,6 +249,11 @@ class BatchImportConfigBuilder:
}
if endpoint_url:
source["endpoint_url"] = endpoint_url
+ if settings.DEBUG:
+ # Local dev: let custom endpoints point at the dev stack
+ # (SeaweedFS on localhost) — the worker's SSRF guard blocks
+ # non-public IPs otherwise. Never set outside DEBUG.
+ source["allow_internal_ips"] = True
self.batch_import.import_config["source"] = source
self.batch_import.secrets[access_key_id_key] = access_key_id
self.batch_import.secrets[secret_access_key_key] = secret_access_key
@@ -337,6 +361,13 @@ class BatchImportConfigBuilder:
self.batch_import.import_config["sink"] = {"type": "noop"}
return self
+ def to_trial_output(self, record_limit: int) -> Self:
+ """Trial run: parse and transform only, writing browsable results to the
+ worker-configured trial bucket instead of capturing events. Stops after
+ record_limit source records (the worker clamps it again)."""
+ self.batch_import.import_config["sink"] = {"type": "trial_s3", "record_limit": record_limit}
+ return self
+
def with_import_events(self, import_events: bool = True) -> Self:
"""Set whether to import events from the source"""
self.batch_import.import_config["import_events"] = import_events
diff --git a/products/managed_migrations/backend/trial_storage.py b/products/managed_migrations/backend/trial_storage.py
new file mode 100644
index 000000000000..3586acb274c9
--- /dev/null
+++ b/products/managed_migrations/backend/trial_storage.py
@@ -0,0 +1,73 @@
+"""Read access to trial-run output written by the batch-import worker.
+
+The worker lays results out as `{prefix}/team_{team_id}/job_{job_id}/pages/{page:05}.jsonl`
+plus a `summary.json`; this module only reads them back for the API. Objects
+expire via an S3 lifecycle rule on the prefix, so a missing object for a known
+page means the results are gone, not that the path is wrong.
+"""
+
+import json
+
+from django.conf import settings
+
+import structlog
+from boto3 import client as boto3_client
+from botocore.client import Config
+from botocore.exceptions import BotoCoreError, ClientError
+
+logger = structlog.get_logger(__name__)
+
+
+class TrialResultsUnavailable(Exception):
+ """The requested trial object no longer exists (expired) or storage is not configured."""
+
+
+def is_configured() -> bool:
+ return bool(settings.MANAGED_MIGRATIONS_TRIAL_S3_BUCKET)
+
+
+def _client():
+ return boto3_client(
+ "s3",
+ endpoint_url=settings.MANAGED_MIGRATIONS_TRIAL_S3_ENDPOINT or None,
+ aws_access_key_id=settings.MANAGED_MIGRATIONS_TRIAL_S3_ACCESS_KEY_ID,
+ aws_secret_access_key=settings.MANAGED_MIGRATIONS_TRIAL_S3_SECRET_ACCESS_KEY,
+ region_name=settings.MANAGED_MIGRATIONS_TRIAL_S3_REGION,
+ config=Config(signature_version="s3v4", connect_timeout=5, retries={"max_attempts": 2}),
+ )
+
+
+def _job_prefix(team_id: int, job_id: str) -> str:
+ prefix = settings.MANAGED_MIGRATIONS_TRIAL_S3_PREFIX.strip("/")
+ return f"{prefix}/team_{team_id}/job_{job_id}"
+
+
+def _read_object(key: str) -> bytes:
+ if not is_configured():
+ raise TrialResultsUnavailable("trial storage is not configured")
+ try:
+ response = _client().get_object(Bucket=settings.MANAGED_MIGRATIONS_TRIAL_S3_BUCKET, Key=key)
+ return response["Body"].read()
+ except ClientError as exc:
+ code = exc.response.get("Error", {}).get("Code", "")
+ if code in ("NoSuchKey", "404"):
+ raise TrialResultsUnavailable(f"trial object {key} not found") from exc
+ # Anything else (NoSuchBucket, auth failures, …) is a storage misconfiguration,
+ # not expired results — surface it as an error instead of "expired".
+ logger.exception("managed_migrations.trial_storage.read_failed", key=key)
+ raise
+ except BotoCoreError:
+ # Connection-level failures (endpoint unreachable, timeouts) — log and surface.
+ logger.exception("managed_migrations.trial_storage.read_failed", key=key)
+ raise
+
+
+def read_trial_page(team_id: int, job_id: str, page: int) -> list[dict]:
+ """Return one page of trial records (source event, outputs, error), in order.
+
+ Raises TrialResultsUnavailable when the page object is gone (lifecycle
+ expiry) or storage is not configured.
+ """
+ key = f"{_job_prefix(team_id, job_id)}/pages/{page:05}.jsonl"
+ body = _read_object(key)
+ return [json.loads(line) for line in body.decode("utf-8").splitlines() if line.strip()]
diff --git a/products/managed_migrations/frontend/ManagedMigration.tsx b/products/managed_migrations/frontend/ManagedMigration.tsx
index 833a5bc795af..6ac4b6fc6b82 100644
--- a/products/managed_migrations/frontend/ManagedMigration.tsx
+++ b/products/managed_migrations/frontend/ManagedMigration.tsx
@@ -22,7 +22,8 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { type ManagedMigrationForm, managedMigrationLogic } from './managedMigrationLogic'
+import { TRIAL_RECORD_LIMIT_MAX, type ManagedMigrationForm, managedMigrationLogic } from './managedMigrationLogic'
+import { TrialResultsModal } from './TrialResultsModal'
import { type ManagedMigration as ManagedMigrationData } from './types'
const STATUS_COLORS = {
@@ -78,7 +79,7 @@ function AmplitudeImportOptions({
}
export function ManagedMigration(): JSX.Element {
- const { managedMigration } = useValues(managedMigrationLogic)
+ const { managedMigration, isManagedMigrationSubmitting } = useValues(managedMigrationLogic)
const { setManagedMigrationValue } = useActions(managedMigrationLogic)
return (
@@ -89,7 +90,7 @@ export function ManagedMigration(): JSX.Element {
resourceType={{ type: 'managed_migration', forceIcon: <IconSort /> }}
actions={
<LemonButton type="primary" htmlType="submit" size="small">
- Import Data
+ {managedMigration.is_trial ? 'Start trial run' : 'Import Data'}
</LemonButton>
}
forceBackTo={{
@@ -269,9 +270,37 @@ export function ManagedMigration(): JSX.Element {
</div>
)}
+ <FlaggedFeature flag={FEATURE_FLAGS.MANAGED_MIGRATIONS_TRIAL_RUNS}>
+ <LemonField name="is_trial">
+ <LemonCheckbox
+ checked={managedMigration.is_trial === true}
+ onChange={(checked) => setManagedMigrationValue('is_trial', checked)}
+ label="Run as a trial first"
+ />
+ </LemonField>
+ {managedMigration.is_trial && (
+ <>
+ <div className="text-muted text-sm -mt-2">
+ A trial parses and transforms a sample of your data and shows the exact events a real
+ import would create, without ingesting anything. Trials still call the source API, so
+ they consume its export quota.
+ </div>
+ <LemonField name="trial_record_limit" label="Number of records to test">
+ <LemonInput
+ type="number"
+ min={1}
+ max={TRIAL_RECORD_LIMIT_MAX}
+ value={managedMigration.trial_record_limit}
+ onChange={(value) => setManagedMigrationValue('trial_record_limit', value)}
+ />
+ </LemonField>
+ </>
+ )}
+ </FlaggedFeature>
+
<div className="flex justify-end">
- <LemonButton type="primary" htmlType="submit">
- Import Data
+ <LemonButton type="primary" htmlType="submit" loading={isManagedMigrationSubmitting}>
+ {managedMigration.is_trial ? 'Start trial run' : 'Import Data'}
</LemonButton>
</div>
</SceneContent>
@@ -280,8 +309,8 @@ export function ManagedMigration(): JSX.Element {
}
export function ManagedMigrations(): JSX.Element {
- const { managedMigrationId, migrations, migrationsLoading } = useValues(managedMigrationLogic)
- const { pauseMigration, resumeMigration } = useActions(managedMigrationLogic)
+ const { managedMigrationId, migrations, migrationsLoading, promotingMigrationId } = useValues(managedMigrationLogic)
+ const { pauseMigration, resumeMigration, promoteTrial, viewTrialResults } = useActions(managedMigrationLogic)
const calculateProgress = (
migration: ManagedMigrationData
@@ -374,6 +403,7 @@ export function ManagedMigrations(): JSX.Element {
<div className="flex items-center gap-2">
<img src={config.icon} alt={config.alt} className="w-4 h-4" />
{config.label}
+ {migration.is_trial && <LemonTag type="highlight">Trial</LemonTag>}
</div>
)
},
@@ -481,6 +511,37 @@ export function ManagedMigrations(): JSX.Element {
title: 'Actions',
key: 'actions',
render: (_: any, migration: ManagedMigrationData) => {
+ if (migration.is_trial && migration.display_status === 'completed') {
+ const alreadyPromoted = migrations.some(
+ (other) => other.promoted_from_trial_id === migration.id
+ )
+ return (
+ <div className="flex gap-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => viewTrialResults(migration.id)}
+ >
+ View results
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={() => promoteTrial(migration.id)}
+ loading={promotingMigrationId === migration.id}
+ disabledReason={
+ alreadyPromoted
+ ? 'This trial already started a full import'
+ : promotingMigrationId
+ ? 'Starting import…'
+ : undefined
+ }
+ >
+ Run full import
+ </LemonButton>
+ </div>
+ )
+ }
if (migration.display_status === 'running') {
return (
<LemonButton
@@ -510,6 +571,7 @@ export function ManagedMigrations(): JSX.Element {
]}
emptyState="No migrations found. Create a new migration to get started."
/>
+ <TrialResultsModal />
</>
)}
</SceneContent>
diff --git a/products/managed_migrations/frontend/TrialResultsModal.tsx b/products/managed_migrations/frontend/TrialResultsModal.tsx
new file mode 100644
index 000000000000..9d65294803bd
--- /dev/null
+++ b/products/managed_migrations/frontend/TrialResultsModal.tsx
@@ -0,0 +1,163 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonModal, LemonTable, LemonTag } from '@posthog/lemon-ui'
+
+import { managedMigrationLogic } from './managedMigrationLogic'
+import type { TrialRecord, TrialSummary } from './types'
+
+function SummaryStat({ label, value }: { label: string; value: number }): JSX.Element {
+ return (
+ <div className="flex flex-col">
+ <span className="text-xs text-muted">{label}</span>
+ <span className="text-lg font-semibold">{value.toLocaleString()}</span>
+ </div>
+ )
+}
+
+function JsonBlock({ title, value }: { title: string; value: unknown }): JSX.Element {
+ return (
+ <div className="flex-1 min-w-0">
+ <div className="text-xs font-semibold text-muted mb-1">{title}</div>
+ <pre className="text-xs bg-bg-light border rounded p-2 overflow-auto max-h-80">
+ {JSON.stringify(value, null, 2)}
+ </pre>
+ </div>
+ )
+}
+
+function recordEventName(record: TrialRecord): string {
+ if (record.outputs.length > 0) {
+ return record.outputs.map((output) => output.event).join(', ')
+ }
+ const source = record.source as Record<string, unknown> | null
+ const name = source?.['event'] ?? source?.['event_type']
+ return typeof name === 'string' ? name : '—'
+}
+
+export function TrialResultsModal(): JSX.Element {
+ const { trialResultsId, trialRecords, trialRecordsLoading } = useValues(managedMigrationLogic)
+ const { closeTrialResults, loadTrialRecordsPage } = useActions(managedMigrationLogic)
+
+ const summary = (trialRecords?.summary ?? null) as TrialSummary | null
+ const records = (trialRecords?.records ?? []) as TrialRecord[]
+ const page = trialRecords?.page ?? 0
+ const totalPages = trialRecords?.total_pages ?? 0
+ const errorEntries = Object.entries(summary?.error_counts ?? {})
+
+ return (
+ <LemonModal
+ isOpen={!!trialResultsId}
+ onClose={closeTrialResults}
+ title="Trial run results"
+ description="Each source record is shown with the event(s) it would produce on a real import, or the reason it failed. No events were ingested."
+ width={960}
+ >
+ <div className="space-y-4">
+ {summary && (
+ <div className="flex gap-8">
+ <SummaryStat label="Records processed" value={trialRecords?.total_records ?? 0} />
+ <SummaryStat label="Events to import" value={summary.output_events} />
+ <SummaryStat label="Failed" value={summary.dropped_records} />
+ <SummaryStat label="Skipped" value={summary.skipped_records} />
+ </div>
+ )}
+
+ {errorEntries.length > 0 && (
+ <LemonBanner type="warning">
+ <div className="font-semibold mb-1">Some records can't be imported</div>
+ <div className="mb-1">
+ These errors are not retriable. A full import will pause when it reaches the first failing
+ record, and stay paused until the source data is fixed.
+ </div>
+ <ul className="list-disc pl-4">
+ {errorEntries.map(([message, count]) => (
+ <li key={message}>
+ {message} <span className="text-muted">({count.toLocaleString()})</span>
+ </li>
+ ))}
+ </ul>
+ </LemonBanner>
+ )}
+
+ <LemonTable
+ dataSource={records}
+ loading={trialRecordsLoading}
+ rowKey="seq"
+ columns={[
+ {
+ title: '#',
+ key: 'seq',
+ width: 60,
+ render: (_: any, record: TrialRecord) => <span className="text-muted">{record.seq}</span>,
+ },
+ {
+ title: 'Event',
+ key: 'event',
+ render: (_: any, record: TrialRecord) => recordEventName(record),
+ },
+ {
+ title: 'Result',
+ key: 'result',
+ render: (_: any, record: TrialRecord) => {
+ if (record.error) {
+ return <LemonTag type="danger">Failed</LemonTag>
+ }
+ if (record.outputs.length === 0) {
+ return <LemonTag type="muted">Skipped</LemonTag>
+ }
+ return (
+ <LemonTag type="success">
+ {record.outputs.length === 1 ? '1 event' : `${record.outputs.length} events`}
+ </LemonTag>
+ )
+ },
+ },
+ {
+ title: 'Details',
+ key: 'details',
+ render: (_: any, record: TrialRecord) => record.error ?? null,
+ },
+ ]}
+ expandable={{
+ expandedRowRender: (record: TrialRecord) => (
+ <div className="flex gap-4 p-2">
+ <JsonBlock title="Source event" value={record.source} />
+ <JsonBlock
+ title={record.error ? 'Error' : 'Imported event(s)'}
+ value={record.error ?? record.outputs}
+ />
+ </div>
+ ),
+ }}
+ emptyState="No records in this trial run."
+ />
+
+ {totalPages > 1 && (
+ <div className="flex items-center justify-end gap-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ disabledReason={page === 0 ? 'Already on the first page' : undefined}
+ loading={trialRecordsLoading}
+ onClick={() => loadTrialRecordsPage({ page: page - 1 })}
+ >
+ Previous
+ </LemonButton>
+ <span className="text-muted text-sm">
+ Page {page + 1} of {totalPages}
+ </span>
+ <LemonButton
+ type="secondary"
+ size="small"
+ disabledReason={page >= totalPages - 1 ? 'Already on the last page' : undefined}
+ loading={trialRecordsLoading}
+ onClick={() => loadTrialRecordsPage({ page: page + 1 })}
+ >
+ Next
+ </LemonButton>
+ </div>
+ )}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/managed_migrations/frontend/generated/api.schemas.ts b/products/managed_migrations/frontend/generated/api.schemas.ts
index 8f437a00d6b5..c66ee9e344ac 100644
--- a/products/managed_migrations/frontend/generated/api.schemas.ts
+++ b/products/managed_migrations/frontend/generated/api.schemas.ts
@@ -331,6 +331,54 @@ export interface PatchedBatchImportApi {
readonly import_config?: unknown
}
+/**
+ * @nullable
+ */
+export type BatchImportResponseApiCreatedBy = { [key: string]: unknown } | null
+
+/**
+ * Serializer for BatchImport responses that matches frontend expectations
+ */
+export interface BatchImportResponseApi {
+ readonly id: string
+ readonly source_type: string
+ readonly content_type: string
+ status?: BatchImportStatusEnumApi
+ readonly display_status: string
+ /** @nullable */
+ readonly start_date: string | null
+ /** @nullable */
+ readonly end_date: string | null
+ /** @nullable */
+ readonly created_by: BatchImportResponseApiCreatedBy
+ readonly created_at: string
+ /** @nullable */
+ status_message: string | null
+ state?: unknown
+ /** Whether this job is a trial run (stores browsable results instead of ingesting). */
+ readonly is_trial: boolean
+ /** @nullable */
+ readonly trial_record_limit: number | null
+ /** @nullable */
+ readonly promoted_from_trial_id: string | null
+}
+
+/**
+ * One page of trial-run results, proxied from the trial output store.
+ */
+export interface TrialRecordsResponseApi {
+ /** Trial records in source order: each has seq (global index), source (the original source event), outputs (the event(s) it would produce), and error (why it would be dropped, if it would be). */
+ records: unknown[]
+ /** Zero-based index of this page. */
+ page: number
+ /** Number of result pages written so far. */
+ total_pages: number
+ /** Number of source records processed so far. */
+ total_records: number
+ /** Running aggregates: output event name counts, error counts, dropped/skipped totals, timestamp range. */
+ summary: unknown
+}
+
export type ManagedMigrationsSupportListParams = {
/**
* Number of results to return per page.
@@ -402,3 +450,10 @@ export const ManagedMigrationsListStatus = {
Paused: 'paused',
Running: 'running',
} as const
+
+export type ManagedMigrationsTrialRecordsRetrieveParams = {
+ /**
+ * Zero-based results page index (see total_pages in the response).
+ */
+ page?: number
+}
diff --git a/products/managed_migrations/frontend/generated/api.ts b/products/managed_migrations/frontend/generated/api.ts
index 5242933fdbfe..989fe4b60d3f 100644
--- a/products/managed_migrations/frontend/generated/api.ts
+++ b/products/managed_migrations/frontend/generated/api.ts
@@ -10,12 +10,15 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
BatchImportApi,
+ BatchImportResponseApi,
BatchImportSupportDetailApi,
ManagedMigrationsListParams,
ManagedMigrationsSupportListParams,
+ ManagedMigrationsTrialRecordsRetrieveParams,
PaginatedBatchImportListApi,
PaginatedBatchImportSupportListListApi,
PatchedBatchImportApi,
+ TrialRecordsResponseApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -226,6 +229,24 @@ export const managedMigrationsPauseCreate = async (
})
}
+export const getManagedMigrationsPromoteCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/managed_migrations/${id}/promote/`
+}
+
+/**
+ * Start the real import from a completed trial run, reusing its source config and credentials.
+ */
+export const managedMigrationsPromoteCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<BatchImportResponseApi> => {
+ return apiMutator<BatchImportResponseApi>(getManagedMigrationsPromoteCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getManagedMigrationsResumeCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/managed_migrations/${id}/resume/`
}
@@ -246,3 +267,38 @@ export const managedMigrationsResumeCreate = async (
body: JSON.stringify(batchImportApi),
})
}
+
+export const getManagedMigrationsTrialRecordsRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params?: ManagedMigrationsTrialRecordsRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/managed_migrations/${id}/trial_records/?${stringifiedParams}`
+ : `/api/projects/${projectId}/managed_migrations/${id}/trial_records/`
+}
+
+/**
+ * Fetch one page of a trial run's results (source event paired with its would-be output events).
+ */
+export const managedMigrationsTrialRecordsRetrieve = async (
+ projectId: string,
+ id: string,
+ params?: ManagedMigrationsTrialRecordsRetrieveParams,
+ options?: RequestInit
+): Promise<TrialRecordsResponseApi> => {
+ return apiMutator<TrialRecordsResponseApi>(getManagedMigrationsTrialRecordsRetrieveUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/managed_migrations/frontend/managedMigrationLogic.ts b/products/managed_migrations/frontend/managedMigrationLogic.ts
index deddb86cf8f4..396a540a7a01 100644
--- a/products/managed_migrations/frontend/managedMigrationLogic.ts
+++ b/products/managed_migrations/frontend/managedMigrationLogic.ts
@@ -17,12 +17,15 @@ import { router, urlToAction } from 'kea-router'
import api, { ApiConfig } from 'lib/api'
import { dayjs } from 'lib/dayjs'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { urls } from 'scenes/urls'
import { FileSystemIconType } from '~/queries/schema/schema-general'
import { Breadcrumb, ProjectTreeRef } from '~/types'
+import { managedMigrationsPromoteCreate, managedMigrationsTrialRecordsRetrieve } from './generated/api'
+import type { TrialRecordsResponseApi } from './generated/api.schemas'
import { ManagedMigration } from './types'
export interface ManagedMigrationForm {
@@ -44,8 +47,14 @@ export interface ManagedMigrationForm {
import_events?: boolean
generate_identify_events?: boolean
generate_group_identify_events?: boolean
+ // Trial run options
+ is_trial?: boolean
+ trial_record_limit?: number
}
+export const TRIAL_RECORD_LIMIT_DEFAULT = 1000
+export const TRIAL_RECORD_LIMIT_MAX = 50000
+
const NEW_MANAGED_MIGRATION: ManagedMigrationForm = {
source_type: 's3',
access_key: '',
@@ -61,6 +70,8 @@ const NEW_MANAGED_MIGRATION: ManagedMigrationForm = {
import_events: true,
generate_identify_events: true,
generate_group_identify_events: true,
+ is_trial: false,
+ trial_record_limit: TRIAL_RECORD_LIMIT_DEFAULT,
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -82,11 +93,39 @@ export interface managedMigrationLogicValues {
migrations: ManagedMigration[]
migrationsLoading: boolean
projectTreeRef: ProjectTreeRef
+ promotingMigrationId: string | null
showManagedMigrationErrors: boolean
+ trialRecords: TrialRecordsResponseApi | null
+ trialRecordsLoading: boolean
+ trialResultsId: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface managedMigrationLogicActions {
+ closeTrialResults: () => {
+ value: true
+ }
+ closeTrialResultsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ closeTrialResultsSuccess: (
+ trialRecords: null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ trialRecords: null
+ payload?: {
+ value: true
+ }
+ }
+ confirmPromoteTrial: (id: string) => {
+ id: string
+ }
editManagedMigration: (id: string | null) => {
id: string | null
}
@@ -105,9 +144,36 @@ export interface managedMigrationLogicActions {
migrations: ManagedMigration[]
payload?: any
}
+ loadTrialRecordsPage: ({ page }: { page: number }) => {
+ page: number
+ }
+ loadTrialRecordsPageFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTrialRecordsPageSuccess: (
+ trialRecords: TrialRecordsResponseApi | null,
+ payload?: {
+ page: number
+ }
+ ) => {
+ trialRecords: TrialRecordsResponseApi | null
+ payload?: {
+ page: number
+ }
+ }
pauseMigration: (id: string) => {
id: string
}
+ promoteTrial: (id: string) => {
+ id: string
+ }
+ promoteTrialFinished: () => {
+ value: true
+ }
resetManagedMigration: (values?: ManagedMigrationForm) => {
values?: ManagedMigrationForm
}
@@ -152,6 +218,9 @@ export interface managedMigrationLogicActions {
touchManagedMigrationField: (key: string) => {
key: string
}
+ viewTrialResults: (id: string) => {
+ id: string
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -183,14 +252,24 @@ export const managedMigrationLogic = kea<managedMigrationLogicType>([
editManagedMigration: (id: string | null) => ({ id }),
pauseMigration: (id: string) => ({ id }),
resumeMigration: (id: string) => ({ id }),
+ promoteTrial: (id: string) => ({ id }),
+ confirmPromoteTrial: (id: string) => ({ id }),
+ promoteTrialFinished: true,
+ viewTrialResults: (id: string) => ({ id }),
+ closeTrialResults: true,
startPolling: true,
stopPolling: true,
}),
reducers({
managedMigrationId: [null as string | null, { editManagedMigration: (_, { id }) => id }],
isPolling: [false, { startPolling: () => true, stopPolling: () => false }],
+ trialResultsId: [null as string | null, { viewTrialResults: (_, { id }) => id, closeTrialResults: () => null }],
+ promotingMigrationId: [
+ null as string | null,
+ { confirmPromoteTrial: (_, { id }) => id, promoteTrialFinished: () => null },
+ ],
}),
- loaders(() => ({
+ loaders(({ values }) => ({
migrations: [
[] as ManagedMigration[],
{
@@ -202,6 +281,25 @@ export const managedMigrationLogic = kea<managedMigrationLogicType>([
},
},
],
+ trialRecords: [
+ null as TrialRecordsResponseApi | null,
+ {
+ loadTrialRecordsPage: async ({ page }: { page: number }, breakpoint) => {
+ if (!values.trialResultsId) {
+ return null
+ }
+ await breakpoint(100)
+ const projectId = String(ApiConfig.getCurrentProjectId())
+ const response = await managedMigrationsTrialRecordsRetrieve(projectId, values.trialResultsId, {
+ page,
+ })
+ // Drop out-of-order responses so stale pages can't overwrite newer state.
+ breakpoint()
+ return response
+ },
+ closeTrialResults: () => null,
+ },
+ ],
})),
forms({
managedMigration: {
@@ -218,6 +316,8 @@ export const managedMigrationLogic = kea<managedMigrationLogicType>([
import_events,
generate_identify_events,
generate_group_identify_events,
+ is_trial,
+ trial_record_limit,
}: ManagedMigrationForm) => {
const errors: Record<string, string | null> = {
secret_key: !secret_key
@@ -227,6 +327,13 @@ export const managedMigrationLogic = kea<managedMigrationLogicType>([
: null,
}
+ if (is_trial) {
+ errors.trial_record_limit =
+ !trial_record_limit || trial_record_limit < 1 || trial_record_limit > TRIAL_RECORD_LIMIT_MAX
+ ? `Number of records must be between 1 and ${TRIAL_RECORD_LIMIT_MAX}`
+ : null
+ }
+
// Mixpanel authenticates with the project secret alone — no access key.
if (source_type !== 'mixpanel') {
errors.access_key = !access_key ? 'Access key is required' : null
@@ -280,6 +387,7 @@ export const managedMigrationLogic = kea<managedMigrationLogicType>([
access_key: values.access_key,
secret_key: values.secret_key,
content_type: values.content_type,
+ ...(values.is_trial ? { is_trial: true, trial_record_limit: values.trial_record_limit } : {}),
}
if (values.source_type === 's3' || values.source_type === 's3_gzip') {
payload = {
@@ -324,7 +432,10 @@ export const managedMigrationLogic = kea<managedMigrationLogicType>([
},
}),
listeners(({ actions, values, cache }) => ({
- submitManagedMigrationSuccess: async () => {
+ submitManagedMigrationSuccess: async ({ managedMigration }) => {
+ if (managedMigration?.is_trial) {
+ lemonToast.success('Trial run started — results will appear here when it completes')
+ }
actions.loadMigrations()
router.actions.push(urls.managedMigration())
},
@@ -357,6 +468,52 @@ export const managedMigrationLogic = kea<managedMigrationLogicType>([
lemonToast.error(error?.message || 'Failed to resume migration')
}
},
+ viewTrialResults: () => {
+ actions.loadTrialRecordsPage({ page: 0 })
+ },
+ loadTrialRecordsPageFailure: async ({ errorObject }) => {
+ if (errorObject?.status === 410) {
+ lemonToast.error('Trial results have expired and are no longer available')
+ } else {
+ lemonToast.error('Failed to load trial results')
+ }
+ actions.closeTrialResults()
+ },
+ promoteTrial: ({ id }) => {
+ if (values.promotingMigrationId) {
+ return
+ }
+ const trial = values.migrations.find((migration: ManagedMigration) => migration.id === id)
+ const failedRecords = trial?.state?.trial?.summary?.dropped_records ?? 0
+ if (failedRecords === 0) {
+ actions.confirmPromoteTrial(id)
+ return
+ }
+ LemonDialog.open({
+ title: 'Start the full import?',
+ description: `This trial found ${failedRecords} record${
+ failedRecords === 1 ? '' : 's'
+ } that can't be imported. These errors are not retriable: the import will pause when it reaches the first failing record, and stay paused until the source data is fixed.`,
+ primaryButton: {
+ children: 'Start import anyway',
+ type: 'primary',
+ onClick: () => actions.confirmPromoteTrial(id),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ },
+ confirmPromoteTrial: async ({ id }) => {
+ try {
+ const projectId = String(ApiConfig.getCurrentProjectId())
+ await managedMigrationsPromoteCreate(projectId, id)
+ lemonToast.success('Import started from trial run')
+ actions.loadMigrations()
+ } catch (error: any) {
+ lemonToast.error(error?.data?.error || error?.message || 'Failed to start import from trial')
+ } finally {
+ actions.promoteTrialFinished()
+ }
+ },
loadMigrationsSuccess: () => {
const hasActiveMigrations = values.migrations.some(
(migration: ManagedMigration) =>
diff --git a/products/managed_migrations/frontend/types.ts b/products/managed_migrations/frontend/types.ts
index 8b5e27d400f8..bf38806d8210 100644
--- a/products/managed_migrations/frontend/types.ts
+++ b/products/managed_migrations/frontend/types.ts
@@ -1,5 +1,37 @@
export type ManagedMigrationStatus = 'paused' | 'completed' | 'running' | 'failed' | 'waiting_to_start'
+export interface TrialSummary {
+ source_records: number
+ output_events: number
+ dropped_records: number
+ skipped_records: number
+ event_name_counts: Record<string, number>
+ error_counts: Record<string, number>
+ first_timestamp?: string
+ last_timestamp?: string
+}
+
+export interface TrialProgress {
+ records_emitted: number
+ pages_written: number
+ summary: TrialSummary
+}
+
+export interface TrialOutputEvent {
+ uuid: string
+ distinct_id: string
+ event: string
+ timestamp?: string
+ payload: unknown
+}
+
+export interface TrialRecord {
+ seq: number
+ source: unknown
+ outputs: TrialOutputEvent[]
+ error?: string | null
+}
+
export interface BaseManagedMigration {
id: string
access_key: string
@@ -7,6 +39,9 @@ export interface BaseManagedMigration {
content_type: 'captured' | 'mixpanel' | 'amplitude'
status: ManagedMigrationStatus
display_status: ManagedMigrationStatus
+ is_trial: boolean
+ trial_record_limit: number | null
+ promoted_from_trial_id: string | null
created_by: {
id: number
uuid: string
@@ -22,6 +57,7 @@ export interface BaseManagedMigration {
total_size: number | null
current_offset: number
}>
+ trial?: TrialProgress
}
}
diff --git a/products/managed_migrations/mcp/tools.yaml b/products/managed_migrations/mcp/tools.yaml
index 2b810b360c6a..2c228ab2d606 100644
--- a/products/managed_migrations/mcp/tools.yaml
+++ b/products/managed_migrations/mcp/tools.yaml
@@ -24,6 +24,9 @@ tools:
managed-migrations-pause-create:
operation: managed_migrations_pause_create
enabled: false
+ managed-migrations-promote-create:
+ operation: managed_migrations_promote_create
+ enabled: false
managed-migrations-resume-create:
operation: managed_migrations_resume_create
enabled: false
@@ -53,6 +56,9 @@ tools:
list: true
title: List batch import jobs across all teams (PostHog staff only)
description_file: ./prompts/managed-migrations-support-list.md
+ managed-migrations-trial-records-retrieve:
+ operation: managed_migrations_trial_records_retrieve
+ enabled: false
managed-migrations-update:
operation: managed_migrations_update
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 46818870a65c..e68d2f434e88 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12538,6 +12538,38 @@ export namespace Schemas {
inflight_total_size: number | null;
}
+ /**
+ * @nullable
+ */
+ export type BatchImportResponseCreatedBy = { [key: string]: unknown } | null;
+
+ /**
+ * Serializer for BatchImport responses that matches frontend expectations
+ */
+ export interface BatchImportResponse {
+ readonly id: string;
+ readonly source_type: string;
+ readonly content_type: string;
+ status?: BatchImportStatusEnum;
+ readonly display_status: string;
+ /** @nullable */
+ readonly start_date: string | null;
+ /** @nullable */
+ readonly end_date: string | null;
+ /** @nullable */
+ readonly created_by: BatchImportResponseCreatedBy;
+ readonly created_at: string;
+ /** @nullable */
+ status_message: string | null;
+ state?: unknown;
+ /** Whether this job is a trial run (stores browsable results instead of ingesting). */
+ readonly is_trial: boolean;
+ /** @nullable */
+ readonly trial_record_limit: number | null;
+ /** @nullable */
+ readonly promoted_from_trial_id: string | null;
+ }
+
/**
* Raw worker progress blob: {'parts': [{'key', 'current_offset', 'total_size'}]}. A part is done when current_offset >= total_size; parts are processed in order. URL part keys (url_list sources) have their query string and userinfo redacted, since those can carry presigned tokens or credentials.
* @nullable
@@ -68293,6 +68325,22 @@ export namespace Schemas {
target_language?: string;
}
+ /**
+ * One page of trial-run results, proxied from the trial output store.
+ */
+ export interface TrialRecordsResponse {
+ /** Trial records in source order: each has seq (global index), source (the original source event), outputs (the event(s) it would produce), and error (why it would be dropped, if it would be). */
+ records: unknown[];
+ /** Zero-based index of this page. */
+ page: number;
+ /** Number of result pages written so far. */
+ total_pages: number;
+ /** Number of source records processed so far. */
+ total_records: number;
+ /** Running aggregates: output event name counts, error counts, dropped/skipped totals, timestamp range. */
+ summary: unknown;
+ }
+
export interface UpdateAppInput {
/** New name for the app. */
name?: string;
@@ -77486,6 +77534,13 @@ export namespace Schemas {
Running: 'running',
} as const;
+ export type ManagedMigrationsTrialRecordsRetrieveParams = {
+ /**
+ * Zero-based results page index (see total_pages in the response).
+ */
+ page?: number;
+ };
+
export type MarketingAnalyticsDataSourcesRetrieveParams = {
/**
* Optional. Restrict to one integration (e.g. 'GoogleAds').