:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse_sources): support langfuse api version v3 (#113237)
Tom Owersdf72fabf9830
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.mdindex 9456ba7abb54..5204e25b1f4f 100644--- a/.agents/skills/warehouse-source-new-version/SKILL.md+++ b/.agents/skills/warehouse-source-new-version/SKILL.md@@ -69,11 +69,11 @@ The opposite gap also occurs: a reference rendered from one version-blind OpenAP## Deprecating a version1. Implement the newer version first (steps above) if not already supported. When the version being sunset is the vendor's **terminal** version (the whole product is discontinued and there is no successor to add), per-version deprecation cannot apply — the framework never deprecates a source's sole/default version, and there is no version to repin to. Don't fabricate a successor or relax the invariant to force the metadata: leave `supported_versions`/`default_version` unchanged, document the vendor sunset and the customer off-ramp (move off the source entirely before shutdown) in the PR, and surface whether a source-level whole-product deprecation surface is warranted for a human to decide.-2. Add the old version to `deprecated_versions` with the vendor's announced sunset date (or `sunset_at=None` if none). When the vendor gives only a month ("supported until January 2027"), use the first day of that month: it is the earliest day the version can stop working, so the warning never comes after the vendor stops serving the version. Never deprecate `default_version` — flip the default to the new version in the same PR.+2. Add the old version to `deprecated_versions` with the vendor's announced sunset date (or `sunset_at=None` if none). When the vendor gives only a month ("supported until January 2027"), use the first day of that month: it is the earliest day the version can stop working, so the warning never comes after the vendor stops serving the version. Never deprecate `default_version` — flip the default to the new version in the same PR. Every other supported label that resolves to the same retiring wire (an alias added by an earlier relabel) shares that sunset: deprecate and repin it too, or its pins hit the shutdown with no warning.The version to deprecate is the source label whose wire reads the retired path, which can differ from the vendor label in the request. A source on the unversioned `v1` label that reads a vendor `/v2/...` endpoint deprecates and repins `v1`. Never declare the vendor's old label just to deprecate it: no row is pinned to it, and the repin would match nothing.3. The in-product warning banner and API fields light up automatically from the metadata — zero per-source UI work.4. **Deprecated is not migrated.** Existing pins move only when the vendor has announced the version will stop being served (a sunset/removal date). A deprecation without a sunset date is advisory: mark it, leave every existing pin on it fully supported, and write no migration — repinning working customers off a version the vendor still serves is exactly the silent version move the pinning framework exists to prevent. Two narrow cases still repin under an advisory (`sunset_at=None`) deprecation: the deprecated label resolves to a byte-identical request as the new default (a pure alias — no per-version dispatch — so the repin is not a move), or the vendor already errors on the old version (e.g. `410`/`406`) so leaving pins is worse than moving them. A source that sends a per-version header/URL for a version the vendor still serves is neither — stay advisory. A published fixed support window ("each dated version is supported for N months after release") is an announced sunset: compute `sunset_at` from it, even when that date has already passed, and repin. If the docs do not say how the API answers an expired version, add no rejection signature to `get_non_retryable_errors`. Before concluding a vendor publishes no sunset date, find its per-version status table (often on an upgrade-guide page, not the versioning-policy page): a policy page that only describes a generic phase-out timeline is not evidence that no date exists.-5. Only for a sunsetting version: include a **written-not-run** migration script that repins affected `ExternalDataSource` rows (`api_version` column) from the deprecated version to the new one, plus any safe data/schema transforms. It must be idempotent and reviewable, and its reverse must be a no-op — repinned rows are indistinguishable from natively-created ones, so a blanket downgrade would clobber legitimate native pins. Repin only rows explicitly on the deprecated version: when the default is already the target (you are deprecating an old label without flipping the default in this PR), do not also repin NULL pins — they already resolve to the current default, so touching them is redundant churn — and leave other still-served deprecated versions alone. Where migration is lossy or unsafe — including when the new version needs credentials that can't be derived from the stored ones — do not script it: document the manual path in the PR. When only a subset of rows is unsafe (the version diverges for one endpoint that needs a credential others don't), split the cohort: script the repin for the safe rows and exclude the unsafe ones by querying their schemas, documenting only that cohort as manual — don't drop the whole migration to manual because one endpoint can't move. Whether a column whose _type_ changes across the versions needs a transform is decided by the schema's sync type, not by the type change: a full-refresh schema drops its table before every sync, so the next run rebuilds it under the newly inferred types and the repin alone is enough, while a merge-based schema carries the old type forward and needs a `reset_pipeline` stamp (delta-rs cannot widen in place, and the automatic resync covers only safe numeric widenings). A repin that lands after the sunset does not resume syncs on its own: the vendor's rejection was non-retryable and auto-disabled the affected schemas, so say in the PR that they need re-enabling. Do not execute migrations or backfills; humans review and run them.+5. Only for a sunsetting version: include a **written-not-run** migration script that repins affected `ExternalDataSource` rows (`api_version` column) from the deprecated version to the new one, plus any safe data/schema transforms. It must be idempotent and reviewable, and its reverse must be a no-op — repinned rows are indistinguishable from natively-created ones, so a blanket downgrade would clobber legitimate native pins. Repin only rows explicitly on the deprecated version: when the default is already the target (you are deprecating an old label without flipping the default in this PR), do not also repin NULL pins — they already resolve to the current default, so touching them is redundant churn — and leave other still-served deprecated versions alone. Where migration is lossy or unsafe — including when the new version needs credentials that can't be derived from the stored ones — do not script it: document the manual path in the PR. When only a subset of rows is unsafe (the version diverges for one endpoint that needs a credential others don't), split the cohort: script the repin for the safe rows and exclude the unsafe ones by querying their schemas, documenting only that cohort as manual — don't drop the whole migration to manual because one endpoint can't move. `ExternalDataSchema.deleted` is nullable and NULL means live, so a cohort query excludes `deleted=True` rather than filtering `deleted=False`, which would misread live rows as safe. Whether a column whose _type_ changes across the versions needs a transform is decided by the schema's sync type, not by the type change: a full-refresh schema drops its table before every sync, so the next run rebuilds it under the newly inferred types and the repin alone is enough, while a merge-based schema carries the old type forward and needs a `reset_pipeline` stamp (delta-rs cannot widen in place, and the automatic resync covers only safe numeric widenings). A repin that lands after the sunset does not resume syncs on its own: the vendor's rejection was non-retryable and auto-disabled the affected schemas, so say in the PR that they need re-enabling. Do not execute migrations or backfills; humans review and run them.6. **Never touch `ExternalDataSchema.api_version` overrides** in migration scripts — they are user-managed by design. The schema-level deprecation warning covers them; the user migrates them from the schema's configuration page.## Pinning semantics (do not break these)diff --git a/products/warehouse_sources/backend/migrations/0184_repin_langfuse_api_version_v3.py b/products/warehouse_sources/backend/migrations/0184_repin_langfuse_api_version_v3.pynew file mode 100644index 000000000000..2141fbec21b5--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0184_repin_langfuse_api_version_v3.py@@ -0,0 +1,48 @@+from django.db import migrations++# Langfuse Cloud stops serving the legacy `/traces` and `/sessions` read routes on 2026-11-16.+# The source's v1 and v2 labels both read them, and send identical requests for every other table.+# v3 keeps that wire for every other table and drops `traces` and `sessions`, because their+# replacement returns observation rows, not trace or session objects.+#+# A source that syncs neither table loses nothing on v3, so this repins it. A source that syncs+# either table would lose that table on repin, so it stays on its pin. The PR documents the manual+# path for those sources.+LANGFUSE_SOURCE_TYPE = "Langfuse"+OLD_VERSIONS = ("v1", "v2")+NEW_VERSION = "v3"+LEGACY_ONLY_TABLES = ("traces", "sessions")+++def repin_langfuse_to_v3(apps, schema_editor):+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")++ # `deleted` is nullable, and a NULL row is live, so exclude only rows marked deleted.+ sources_syncing_legacy_tables = (+ ExternalDataSchema.objects.filter(+ source__source_type=LANGFUSE_SOURCE_TYPE,+ source__api_version__in=OLD_VERSIONS,+ name__in=LEGACY_ONLY_TABLES,+ should_sync=True,+ )+ .exclude(deleted=True)+ .values("source_id")+ )++ # Only the source-level pin moves. Schema-level `ExternalDataSchema.api_version` overrides are+ # user-managed and stay as they are. NULL pins already resolve to the new default. Matching only+ # the old labels keeps this idempotent: a second run matches only the excluded sources.+ ExternalDataSource.objects.filter(source_type=LANGFUSE_SOURCE_TYPE, api_version__in=OLD_VERSIONS).exclude(+ id__in=sources_syncing_legacy_tables+ ).update(api_version=NEW_VERSION)+++class Migration(migrations.Migration):+ dependencies = [("warehouse_sources", "0183_repin_gusto_api_version")]++ operations = [+ # Reverse is a no-op: repinned rows are indistinguishable from natively created v3 rows, so a+ # blanket downgrade would clobber legitimate v3 pins.+ migrations.RunPython(repin_langfuse_to_v3, migrations.RunPython.noop, elidable=False),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 1680a5fc534a..39a8ff3efba1 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0183_repin_gusto_api_version+0184_repin_langfuse_api_version_v3diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.pyindex 6669c25ec9c5..bc2fe9942d54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.py@@ -58,6 +58,7 @@ HTTP_NOT_ALLOWED_ERROR = "Langfuse host must use HTTPS"RESPONSE_LIMIT_ERROR = "Langfuse response exceeded a transfer limit"PAGE_LIMIT_ERROR = "Langfuse pagination page limit reached"REPEATED_CURSOR_ERROR = "Langfuse API returned the same pagination cursor twice"+TABLE_NOT_IN_VERSION_ERROR = "Langfuse table is not available on this API version"class LangfuseRetryableError(Exception):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.pyindex cc6a84f49415..cb699d01ce65 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/settings.py@@ -1,20 +1,21 @@from dataclasses import dataclass, field-from datetime import timedelta+from datetime import date, timedeltafrom typing import Literal, Optionalfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSIONfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# Source-level vendor API version labels. Distinct from the per-endpoint URL versions baked into-# LANGFUSE_ENDPOINTS below (Langfuse versions each resource route independently). The source already-# reads Langfuse's current route for every resource that has one (`/v2/observations`, `/v3/scores`,-# `/v2/prompts`, `/v2/datasets`), so both labels resolve to the same wire — the bump is a declaration-# plus deprecation with no request-layer branching. v1 keeps the pre-versioning UNVERSIONED default-# so already-pinned rows resolve unchanged.+# LANGFUSE_ENDPOINTS below (Langfuse versions each resource route independently). v1 and v2 resolve+# to the same wire: v1 keeps the pre-versioning UNVERSIONED default so already-pinned rows resolve+# unchanged. Both read the `/traces` and `/sessions` routes Langfuse Cloud stops serving on+# 2026-11-16; v3 drops those tables, as `observations` already carries traceId and sessionId.LANGFUSE_API_VERSION_V1 = UNVERSIONED_API_VERSIONLANGFUSE_API_VERSION_V2 = "v2"-SUPPORTED_VERSIONS = (LANGFUSE_API_VERSION_V1, LANGFUSE_API_VERSION_V2)-DEFAULT_VERSION = LANGFUSE_API_VERSION_V2+LANGFUSE_API_VERSION_V3 = "v3"+SUPPORTED_VERSIONS = (LANGFUSE_API_VERSION_V1, LANGFUSE_API_VERSION_V2, LANGFUSE_API_VERSION_V3)+DEFAULT_VERSION = LANGFUSE_API_VERSION_V3+LANGFUSE_LEGACY_SUNSET = date(2026, 11, 16)def _datetime_incremental_field(name: str) -> IncrementalField:@@ -203,6 +204,22 @@ LANGFUSE_ENDPOINTS: dict[str, LangfuseEndpointConfig] = {ENDPOINTS = tuple(LANGFUSE_ENDPOINTS.keys())+LEGACY_ONLY_ENDPOINTS = frozenset({"traces", "sessions"})++ENDPOINTS_BY_VERSION: dict[str, tuple[str, ...]] = {+ LANGFUSE_API_VERSION_V1: ENDPOINTS,+ LANGFUSE_API_VERSION_V2: ENDPOINTS,+ LANGFUSE_API_VERSION_V3: tuple(name for name in ENDPOINTS if name not in LEGACY_ONLY_ENDPOINTS),+}+++def endpoints_for_version(api_version: str) -> tuple[str, ...]:+ try:+ return ENDPOINTS_BY_VERSION[api_version]+ except KeyError as e:+ raise ValueError(f"Unsupported Langfuse API version: {api_version!r}") from e++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in LANGFUSE_ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.pyindex dd7d98fc4dd3..b7e6a3497e2e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/source.py@@ -27,16 +27,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.lHTTP_NOT_ALLOWED_ERROR,REPEATED_CURSOR_ERROR,RESPONSE_LIMIT_ERROR,+ TABLE_NOT_IN_VERSION_ERROR,LangfuseResumeConfig,langfuse_source,validate_credentials as validate_langfuse_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.settings import (DEFAULT_VERSION,- ENDPOINTS,INCREMENTAL_FIELDS,LANGFUSE_API_VERSION_V1,+ LANGFUSE_API_VERSION_V2,+ LANGFUSE_LEGACY_SUNSET,SUPPORTED_VERSIONS,+ endpoints_for_version,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -48,12 +51,12 @@ class LangfuseSource(ResumableSource[LangfuseSourceConfig, LangfuseResumeConfig]supported_versions = SUPPORTED_VERSIONSdefault_version = DEFAULT_VERSION- # Langfuse is retiring its v1 public read endpoints at the (undated) v4 cutover. The source- # already reads Langfuse's current route for every resource that has one, so both labels share- # one wire and v1-pinned rows keep working — v1 is deprecated advisory-only (no vendor sunset- # date). `traces`/`sessions` have no lossless v2 replacement (v2 returns observation rows, not- # trace/session objects), so their cutover is a documented manual migration, not an auto repin.- deprecated_versions = (VersionDeprecation(version=LANGFUSE_API_VERSION_V1),)+ # The replacement for `/traces` and `/sessions` returns observation rows, not trace or session+ # objects, so v3 drops both tables and sources that sync them need a manual move.+ deprecated_versions = (+ VersionDeprecation(version=LANGFUSE_API_VERSION_V1, sunset_at=LANGFUSE_LEGACY_SUNSET),+ VersionDeprecation(version=LANGFUSE_API_VERSION_V2, sunset_at=LANGFUSE_LEGACY_SUNSET),+ )@propertydef source_type(self) -> ExternalDataSourceType:@@ -125,6 +128,7 @@ Find your project API keys in your Langfuse **Project settings > API Keys**. Set# PAGE_LIMIT_ERROR is intentionally absent: it is retryable, so a huge sync resumes# from its checkpoint on the next attempt instead of failing permanently.REPEATED_CURSOR_ERROR: "The Langfuse host repeated a pagination cursor, so the sync was stopped to avoid looping. Check that the host points at a real Langfuse instance.",+ TABLE_NOT_IN_VERSION_ERROR: "Langfuse retired the API for this table. Trace and session data is in the observations table: group its rows by traceId or sessionId.",}def get_retryable_errors(self) -> set[str]:@@ -157,7 +161,7 @@ Find your project API keys in your Langfuse **Project settings > API Keys**. Setsupports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),)- for endpoint in ENDPOINTS+ for endpoint in endpoints_for_version(self.resolve_api_version(api_version))]if names is not None:names_set = set(names)@@ -182,6 +186,12 @@ Find your project API keys in your Langfuse **Project settings > API Keys**. Setresumable_source_manager: ResumableSourceManager[LangfuseResumeConfig],inputs: SourceInputs,) -> SourceResponse:+ api_version = self.resolve_api_version(inputs.api_version)+ if inputs.schema_name not in endpoints_for_version(api_version):+ raise ValueError(+ f"{TABLE_NOT_IN_VERSION_ERROR}: '{inputs.schema_name}' is not available on API version {api_version}"+ )+return langfuse_source(host=config.host,public_key=config.public_key,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse_source.pyindex 5404e1c44637..ce9786b2a528 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/tests/test_langfuse_source.py@@ -1,5 +1,12 @@+from datetime import date++import pytestfrom unittest import mock+from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.settings import (+ ENDPOINTS,+ endpoints_for_version,+)from products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.source import LangfuseSource@@ -12,6 +19,20 @@ class TestLangfuseSource:self.config.public_key = "pk-lf-key"self.config.secret_key = "sk-lf-key"+ def test_legacy_versions_carry_the_vendor_sunset_and_default_is_v3(self):+ assert self.source.default_version == "v3"+ assert self.source.supported_versions == ("v1", "v2", "v3")++ for legacy in ("v1", "v2"):+ deprecation = self.source.get_version_deprecation(legacy)+ assert deprecation is not None+ assert deprecation.sunset_at == date(2026, 11, 16)+ assert self.source.get_version_deprecation("v3") is None++ def test_endpoints_for_version_rejects_an_unknown_pin(self):+ with pytest.raises(ValueError, match="Unsupported Langfuse API version"):+ endpoints_for_version("v4")+def test_exhausted_connection_pool_error_is_classified_retryable(self):# Matches the message urllib3 raises once `get_rows`'s tenacity retry (which covers read# timeouts and connection failures, not just 429/422/5xx) exhausts its budget — keeps this@@ -25,7 +46,43 @@ class TestLangfuseSource:)assert any(pattern in observed_error for pattern in self.source.get_retryable_errors())+ @pytest.mark.parametrize(+ "api_version, expected",+ [+ ("v1", set(ENDPOINTS)),+ ("v2", set(ENDPOINTS)),+ ("v3", set(ENDPOINTS) - {"traces", "sessions"}),+ (None, set(ENDPOINTS) - {"traces", "sessions"}),+ ],+ )+ def test_get_schemas_discovers_the_pinned_version_catalog(self, api_version, expected):+ schemas = self.source.get_schemas(self.config, self.team_id, api_version=api_version)+ assert {s.name for s in schemas} == expected++ @pytest.mark.parametrize(+ "api_version, endpoint",+ [("v1", "traces"), ("v2", "sessions"), ("v3", "observations")],+ )+ def test_source_for_pipeline_reads_tables_served_by_the_pin(self, api_version, endpoint):+ inputs = mock.MagicMock(api_version=api_version, schema_name=endpoint, should_use_incremental_field=False)+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.source.langfuse_source"+ ) as langfuse_source:+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)+ assert langfuse_source.call_args.kwargs["endpoint"] == endpoint++ @pytest.mark.parametrize("endpoint", ["traces", "sessions"])+ def test_v3_refuses_retired_tables_with_a_non_retryable_error(self, endpoint):+ inputs = mock.MagicMock(api_version="v3", schema_name=endpoint)+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.langfuse.source.langfuse_source"+ ) as langfuse_source:+ with pytest.raises(ValueError) as exc_info:+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)+ langfuse_source.assert_not_called()+ assert any(pattern in str(exc_info.value) for pattern in self.source.get_non_retryable_errors())+def test_get_schemas_filtered_by_names(self):- schemas = self.source.get_schemas(self.config, self.team_id, names=["traces"])+ schemas = self.source.get_schemas(self.config, self.team_id, names=["observations"])assert len(schemas) == 1- assert schemas[0].name == "traces"+ assert schemas[0].name == "observations"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.pyindex 03fa42a095c6..411d3bb763ce 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py@@ -32,6 +32,7 @@ DESCRIPTIONS_NOT_IN_SCHEMAS = {"EZOfficeInventory","Giphy","GoogleSearchConsole",+ "Langfuse","Lovable","Omnisend","OpenWeather",diff --git a/products/warehouse_sources/backend/tests/test_migration_repin_langfuse_api_version_v3.py b/products/warehouse_sources/backend/tests/test_migration_repin_langfuse_api_version_v3.pynew file mode 100644index 000000000000..56fd168b3b80--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_migration_repin_langfuse_api_version_v3.py@@ -0,0 +1,52 @@+from typing import Any++from posthog.test.base import TestMigrations+++class TestRepinLangfuseApiVersionV3(TestMigrations):+ migrate_from = "0183_repin_gusto_api_version"+ migrate_to = "0184_repin_langfuse_api_version_v3"++ def setUpBeforeMigration(self, apps: Any) -> None:+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")++ def source(source_type: str, api_version: str | None, schemas: list[tuple[str, bool, bool | None]]) -> str:+ created = ExternalDataSource.objects.create(+ team_id=self.team.id,+ source_id="source-id",+ connection_id="connection-id",+ status="Completed",+ source_type=source_type,+ api_version=api_version,+ )+ for name, should_sync, deleted in schemas:+ ExternalDataSchema.objects.create(+ team_id=self.team.id,+ source=created,+ name=name,+ should_sync=should_sync,+ deleted=deleted,+ api_version="v1" if name == "scores" else None,+ )+ return str(created.id)++ self.expected = {+ source("Langfuse", "v1", [("observations", True, False), ("traces", False, False)]): "v3",+ source("Langfuse", "v2", [("scores", True, False), ("sessions", True, True)]): "v3",+ source("Langfuse", "v2", [("observations", True, False), ("traces", True, False)]): "v2",+ source("Langfuse", "v1", [("sessions", True, False)]): "v1",+ source("Langfuse", "v1", [("traces", True, None)]): "v1",+ source("Langfuse", None, [("traces", False, False)]): None,+ source("Langfuse", "v3", []): "v3",+ source("Ably", "v1", []): "v1",+ }++ def test_repins_only_sources_that_lose_no_synced_table(self) -> None:+ assert self.apps is not None+ ExternalDataSource = self.apps.get_model("warehouse_sources", "ExternalDataSource")+ ExternalDataSchema = self.apps.get_model("warehouse_sources", "ExternalDataSchema")++ pins = dict(ExternalDataSource.objects.filter(id__in=self.expected).values_list("id", "api_version"))+ assert {str(source_id): pin for source_id, pin in pins.items()} == self.expected+ assert ExternalDataSchema.objects.get(name="scores").api_version == "v1"