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(data-warehouse): resolve duckgres data-import schema from team table_suffix (#65323)

Eric Duong639606418372
diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.py
index 0082bfc7e2e9..5f94501c3c72 100644
--- a/posthog/ducklake/common.py
+++ b/posthog/ducklake/common.py
@@ -550,6 +550,43 @@ def sanitize_ducklake_identifier(raw: str, *, default_prefix: str) -> str:
return cleaned[:63]
+def validate_duckgres_identifier(identifier: str) -> None:
+ """Fail-closed check that an identifier is safe for SQL interpolation.
+
+ Only alphanumeric characters and underscores are allowed. Mirrors the
+ events/persons duckling DAG's ``_validate_identifier`` so a user-supplied
+ ``DuckLakeBackfill.table_suffix`` is validated identically wherever it is
+ interpolated into DuckDB DDL.
+ """
+ if not identifier or not identifier.replace("_", "").isalnum():
+ raise ValueError(f"Invalid SQL identifier: {identifier!r}")
+
+
+def duckgres_data_imports_schema(team_id: int) -> str:
+ """Resolve the duckgres schema the v3 data-import sink writes a team into.
+
+ A DuckgresServer is org-scoped and hosts many teams, so each team needs its
+ own schema. Historically that was ``posthog_data_imports_team_{team_id}``.
+ When a team sets ``DuckLakeBackfill.table_suffix`` (the same field that
+ governs its events/persons tables), the data-import schema uses that suffix
+ so one user-chosen identifier names all of a team's warehouse tables.
+
+ Backward-compatible: a NULL/empty suffix keeps the team-id schema, so
+ existing teams are unaffected until a suffix is explicitly set.
+
+ NOTE: a suffix CHANGE moves the schema and orphans the old one — callers
+ that have already written a team's tables must trigger a re-prime (handled
+ by the backfill state machine), not silently switch.
+ """
+ from posthog.ducklake.models import DuckLakeBackfill
+
+ suffix = DuckLakeBackfill.objects.filter(team_id=team_id).values_list("table_suffix", flat=True).first()
+ if not suffix:
+ return f"posthog_data_imports_team_{team_id}"
+ validate_duckgres_identifier(suffix)
+ return f"posthog_data_imports_{suffix}"
+
+
TABLE_SUFFIX_MAX_LENGTH = 63
# The table name the user supplies is used verbatim as the suffix in `events_<suffix>` /
# `persons_<suffix>`, so it must already be a safe SQL identifier — lowercase letters,
@@ -652,6 +689,7 @@ def get_team_backfill_state(team_id: int) -> dict[str, object]:
__all__ = [
"DucklingBackfillEnableError",
"attach_catalog",
+ "duckgres_data_imports_schema",
"enable_team_backfill",
"escape",
"get_config",
@@ -675,5 +713,6 @@ __all__ = [
"reset_ducklake_catalog",
"run_smoke_check",
"sanitize_ducklake_identifier",
+ "validate_duckgres_identifier",
"validate_table_suffix",
]
diff --git a/posthog/ducklake/test_common.py b/posthog/ducklake/test_common.py
index 50f6cba75ad3..0c4e1508007f 100644
--- a/posthog/ducklake/test_common.py
+++ b/posthog/ducklake/test_common.py
@@ -332,3 +332,60 @@ class TestInitializeDucklake:
assert result is True
mock_reset.assert_called_once_with(TEST_CONFIG)
+
+
+class TestValidateDuckgresIdentifier:
+ @parameterized.expand(["prod", "us_prod", "team_42", "abc123"])
+ def test_accepts_safe_identifiers(self, ident):
+ from posthog.ducklake.common import validate_duckgres_identifier
+
+ validate_duckgres_identifier(ident) # no raise
+
+ @parameterized.expand(["", "a-b", "a b", "a;drop", "a.b", "a$b", '"x"'])
+ def test_rejects_unsafe_identifiers(self, ident):
+ from posthog.ducklake.common import validate_duckgres_identifier
+
+ with pytest.raises(ValueError):
+ validate_duckgres_identifier(ident)
+
+
+class TestDuckgresDataImportsSchema:
+ def _team(self):
+ from posthog.models import Organization, Team
+
+ org = Organization.objects.create(name="o")
+ return Team.objects.create(organization=org, name="t")
+
+ def test_falls_back_to_team_id_when_no_backfill_row(self):
+ from posthog.ducklake.common import duckgres_data_imports_schema
+
+ team = self._team()
+ assert duckgres_data_imports_schema(team.id) == f"posthog_data_imports_team_{team.id}"
+
+ def test_falls_back_to_team_id_when_suffix_null_or_empty(self):
+ from posthog.ducklake.common import duckgres_data_imports_schema
+ from posthog.ducklake.models import DuckLakeBackfill
+
+ team = self._team()
+ DuckLakeBackfill.objects.create(team=team, table_suffix=None)
+ assert duckgres_data_imports_schema(team.id) == f"posthog_data_imports_team_{team.id}"
+ DuckLakeBackfill.objects.filter(team=team).update(table_suffix="")
+ assert duckgres_data_imports_schema(team.id) == f"posthog_data_imports_team_{team.id}"
+
+ def test_uses_suffix_when_set(self):
+ from posthog.ducklake.common import duckgres_data_imports_schema
+ from posthog.ducklake.models import DuckLakeBackfill
+
+ team = self._team()
+ DuckLakeBackfill.objects.create(team=team, table_suffix="us_prod")
+ assert duckgres_data_imports_schema(team.id) == "posthog_data_imports_us_prod"
+
+ def test_rejects_unsafe_suffix(self):
+ from posthog.ducklake.common import duckgres_data_imports_schema
+ from posthog.ducklake.models import DuckLakeBackfill
+
+ team = self._team()
+ DuckLakeBackfill.objects.create(team=team, table_suffix="a;drop")
+ with pytest.raises(ValueError):
+ duckgres_data_imports_schema(team.id)
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
index 7abb16446b45..eb800804dcfb 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
@@ -10,7 +10,7 @@ import psycopg
import structlog
from psycopg import sql
-from posthog.ducklake.common import get_duckgres_config_for_org
+from posthog.ducklake.common import duckgres_data_imports_schema, get_duckgres_config_for_org
from posthog.ducklake.storage import setup_duckgres_session
from posthog.models import Team
from posthog.temporal.data_imports.naming_convention import NamingConvention
@@ -212,7 +212,10 @@ def _process_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: E
def _duckgres_schema_name(team_id: int) -> str:
- return f"posthog_data_imports_team_{team_id}"
+ # Resolves to posthog_data_imports_<table_suffix> when the team has set one
+ # (DuckLakeBackfill.table_suffix — the same suffix that names its
+ # events/persons tables), else the legacy posthog_data_imports_team_<id>.
+ return duckgres_data_imports_schema(team_id)
def _duckgres_table_name(schema: ExternalDataSchema) -> str:
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py
index 0836b4231044..7172232e58c1 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py
@@ -1,5 +1,6 @@
from typing import Any
+import pytest
from unittest.mock import MagicMock, Mock, patch
from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor import (
@@ -12,6 +13,17 @@ from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor impo
from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatch
[email protected](autouse=True)
+def _stub_schema_resolver():
+ # _duckgres_schema_name now resolves the team's table_suffix via the ORM;
+ # these are no-DB unit tests, so pin a deterministic schema name.
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor.duckgres_data_imports_schema",
+ return_value="posthog_data_imports_team_1",
+ ):
+ yield
+
+
def _make_batch(**overrides: Any) -> PendingBatch:
defaults: dict[str, Any] = {
"id": "00000000-0000-0000-0000-000000000001",
diff --git a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
index e1476d0cd29b..591324536887 100644
--- a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
+++ b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
@@ -17,6 +17,7 @@ from temporalio.exceptions import ApplicationError
from posthog.ducklake.common import (
_get_org_id_for_team,
attach_catalog,
+ duckgres_data_imports_schema,
get_config,
get_duckgres_server_for_organization,
get_ducklake_catalog_by_team_org,
@@ -218,6 +219,11 @@ async def prepare_data_imports_ducklake_metadata_activity(
await logger.ainfo("DuckLake copy requested but no schema_ids were provided - skipping")
return []
+ # Resolve the same per-team schema the v3 sink uses (table_suffix-aware), so the
+ # historical copy and the live sink never diverge on schema name. All schemas in the
+ # batch belong to one team, so this is loop-invariant — resolve it once.
+ ducklake_schema_name = await database_sync_to_async(duckgres_data_imports_schema)(inputs.team_id)
+
model_list: list[DuckLakeCopyDataImportsMetadata] = []
for schema_id in inputs.schema_ids:
@@ -244,7 +250,7 @@ async def prepare_data_imports_ducklake_metadata_activity(
source_schema_name=schema.name,
source_normalized_name=normalized_name,
source_table_uri=source_table_uri,
- ducklake_schema_name=f"posthog_data_imports_team_{inputs.team_id}",
+ ducklake_schema_name=ducklake_schema_name,
ducklake_table_name=sanitize_ducklake_identifier(
f"{source_type}_{schema.source.prefix}_{normalized_name}"
if schema.source.prefix