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-modeling): run incremental models incrementally in the trino shadow (#113990)

Jovan Sakovic8d46f2282aca
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index e0384ac070e8..5ba6b54d1cab 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -32,7 +32,6 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queries, tags
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
-from posthog.ph_client import feature_enabled_or_false
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.settings.base_variables import TEST
from posthog.sync import database_sync_to_async_pool
@@ -57,16 +56,13 @@ from posthog.temporal.data_modeling.activities.incremental_write import (
from posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_context
from products.data_modeling.backend.facade.api import (
- IncrementalConfig,
IncrementalFilterError,
+ WritePlan,
clear_incremental_state,
- definition_fingerprint,
- get_incremental_config,
- get_incremental_state,
inject_incremental_filter,
record_incremental_history,
+ resolve_write_plan,
set_incremental_state,
- window_start,
)
from products.data_modeling.backend.facade.modeling import bounded_resolver_factory_for_view
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery, Node, NodeType
@@ -197,10 +193,6 @@ def _reject_duplicate_output_columns(columns: list[_DescribedColumn]) -> None:
CLICKHOUSE_MAX_BLOCK_SIZE_ROWS = 50 * 1000
DELTA_TABLE_RETENTION_HOURS = 24
-# The only gate. Incremental is also the only path that writes through deltalite, so turning this
-# off falls back to full refresh on delta-rs and takes the engine with it.
-INCREMENTAL_FLAG = "data-modeling-incremental-views"
-
# Above this many files, the per-run compaction is worth its full-table rewrite. Below it, skipping
# keeps an incremental run's cost proportional to the rows it changed rather than the table's size.
INCREMENTAL_COMPACT_FILE_THRESHOLD = 200
@@ -247,72 +239,6 @@ class DuplicateOutputColumnError(NonReportableError):
self.duplicates = duplicates
-def _incremental_enabled(team_id: int) -> bool:
- """Fails closed: a flag-service outage produces a full refresh, which costs money but is
- never wrong."""
- try:
- team = Team.objects.only("organization_id").get(id=team_id)
- return feature_enabled_or_false(
- INCREMENTAL_FLAG,
- str(team_id),
- groups={"organization": str(team.organization_id), "project": str(team_id)},
- group_properties={
- "organization": {"id": str(team.organization_id)},
- "project": {"id": str(team_id)},
- },
- only_evaluate_locally=True,
- send_feature_flag_events=False,
- )
- except Exception:
- LOGGER.warning("Failed to evaluate incremental flag; falling back to full refresh", team_id=team_id)
- return False
-
-
[email protected](frozen=True, kw_only=True, slots=True)
-class WritePlan:
- """Whether this run rebuilds the table or updates it, and why. The reason is surfaced on the
- job so an unexpectedly expensive run explains itself."""
-
- incremental: bool
- reason: str
- since: typing.Any = None
- fingerprint: str | None = None
- config: IncrementalConfig | None = None
-
-
-@database_sync_to_async_pool
-def _resolve_write_plan(saved_query: DataWarehouseSavedQuery, team_id: int) -> WritePlan:
- config = get_incremental_config(saved_query)
- if config is None:
- return WritePlan(incremental=False, reason="not configured for incremental materialization")
-
- if not _incremental_enabled(team_id):
- return WritePlan(incremental=False, reason="incremental materialization is not enabled")
-
- fingerprint = definition_fingerprint(typing.cast(dict, saved_query.query), config)
- state = get_incremental_state(saved_query)
-
- if state.watermark is None:
- return WritePlan(incremental=False, reason="first run", fingerprint=fingerprint, config=config)
-
- if fingerprint is None or fingerprint != state.definition_fingerprint:
- # The query or its config changed, so existing rows were computed by a definition that no
- # longer applies. Rebuilding is the only way the table still matches the SQL the user sees.
- return WritePlan(incremental=False, reason="definition changed", fingerprint=fingerprint, config=config)
-
- since = window_start(state, config)
- if since is None:
- return WritePlan(incremental=False, reason="no usable watermark", fingerprint=fingerprint, config=config)
-
- return WritePlan(
- incremental=True,
- reason="incremental",
- since=since,
- fingerprint=fingerprint,
- config=config,
- )
-
-
def _is_s3_permission_denied(error: BaseException) -> bool:
"""True for an S3 access-denied error on our own bucket, from either client this pipeline uses.
@@ -1133,7 +1059,7 @@ async def _materialize_incrementally(
publish to copy incrementally would break that, so the two decisions are linked.
"""
config = plan.config
- assert config is not None # _resolve_write_plan only sets incremental with a config
+ assert config is not None # resolve_write_plan only sets incremental with a config
delta_table = deltalake.DeltaTable(table_uri, storage_options=storage_options)
# Wrapped in pa.schema() because delta-rs hands back an arro3 schema, whose DataType does not
@@ -1280,7 +1206,7 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
await logger.adebug(f"Delta table URI = {table_uri}")
storage_options = get_aws_storage_options()
- plan = await _resolve_write_plan(objects.saved_query, inputs.team_id)
+ plan = await database_sync_to_async_pool(resolve_write_plan)(inputs.team_id, objects.saved_query.id)
if plan.incremental and not await asyncio.to_thread(table_exists, table_uri, storage_options):
# deltalite can only open a table, never create one, so a missing table has to rebuild.
plan = dataclasses.replace(plan, incremental=False, reason="table missing")
diff --git a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py
index c3f2277ad6dd..09bc2b426f65 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py
@@ -15,6 +15,13 @@ from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
+from products.data_modeling.backend.facade.api import (
+ TRINO_INCREMENTAL_SCOPE,
+ WritePlan,
+ clear_incremental_state,
+ resolve_write_plan,
+ set_incremental_state,
+)
from products.data_modeling.backend.facade.models import (
DataModelingJob,
DataModelingJobStatus,
@@ -31,7 +38,11 @@ from products.managed_warehouse.backend.facade.api import (
is_data_modeling_shadow_ready,
is_dev_mode,
)
-from products.managed_warehouse.backend.facade.contracts import DuckLakeCompiledQuery, DuckLakeS3Secret
+from products.managed_warehouse.backend.facade.contracts import (
+ DuckLakeCompiledQuery,
+ DuckLakeS3Secret,
+ TrinoIncrementalWrite,
+)
from products.managed_warehouse.backend.facade.feature_flags import DATA_MODELING_SHADOW_FLAG
from ..metrics import get_node_suspended_metric
@@ -228,6 +239,7 @@ async def _materialize_view_managed_warehouse(
sql: str = ""
values: dict[str, object] = {}
s3_secrets: tuple[DuckLakeS3Secret, ...] = ()
+ plan: WritePlan | None = None
try:
from products.managed_warehouse.backend.facade.client import execute_ducklake_create_table, execute_trino_model
@@ -240,12 +252,26 @@ async def _materialize_view_managed_warehouse(
table_name=table_name,
)
if inputs.use_trino:
+ plan = await database_sync_to_async_pool(resolve_write_plan)(
+ team.pk, saved_query.id, scope=TRINO_INCREMENTAL_SCOPE
+ )
+ await logger.ainfo("Trino write plan", incremental=plan.incremental, reason=plan.reason)
result = await execute_trino_model(
organization_id=str(team.organization_id),
team_id=team.pk,
saved_query_id=saved_query.id,
source_query=saved_query.query,
+ incremental=_trino_incremental_write(plan),
)
+ if plan.config is not None:
+ # A quiet window writes nothing, so it records the run without moving the watermark.
+ await database_sync_to_async_pool(set_incremental_state)(
+ saved_query,
+ watermark=result.watermark,
+ fingerprint=plan.fingerprint,
+ mode="incremental" if result.merged else "full_refresh",
+ scope=TRINO_INCREMENTAL_SCOPE,
+ )
from products.managed_warehouse.backend.facade.client import request_model_alias_reconciliation
try:
@@ -312,6 +338,13 @@ async def _materialize_view_managed_warehouse(
table_name=table_name,
error=str(e),
)
+ if plan is not None and plan.incremental:
+ # The merge may have stopped partway or failed on a schema change. Rebuilding next run
+ # is the only state that is certainly correct.
+ try:
+ await database_sync_to_async_pool(clear_incremental_state)(saved_query, scope=TRINO_INCREMENTAL_SCOPE)
+ except Exception as clear_error:
+ capture_exception(clear_error)
job_engine = await _resolve_managed_warehouse_job(inputs.job_id, shadow_result)
suspended = await maybe_suspend_node_for_engine(
node_id=inputs.node_id,
@@ -330,6 +363,16 @@ async def _materialize_view_managed_warehouse(
return shadow_result
+def _trino_incremental_write(plan: WritePlan) -> TrinoIncrementalWrite | None:
+ if plan.config is None:
+ return None
+ return TrinoIncrementalWrite(
+ incremental_key=plan.config.incremental_key,
+ unique_key=tuple(plan.config.unique_key),
+ since=plan.since if plan.incremental else None,
+ )
+
+
@activity.defn
async def materialize_view_managed_warehouse_activity(
inputs: ManagedWarehouseShadowInputs,
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index f3d0fbe97dc7..48d746269105 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -59,7 +59,14 @@ from posthog.temporal.data_modeling.activities.notify_materialization_failure im
from products.customer_analytics.backend.facade.temporal import stage_warehouse_account_property_files_activity
from products.customer_analytics.backend.facade.temporal_contracts import StageAccountPropertySyncInput
-from products.data_modeling.backend.facade.api import compute_enrichment_hash
+from products.data_modeling.backend.facade.api import (
+ TRINO_INCREMENTAL_SCOPE,
+ compute_enrichment_hash,
+ definition_fingerprint,
+ get_incremental_config,
+ get_incremental_state,
+ set_incremental_state,
+)
from products.data_modeling.backend.facade.modeling import ResolutionCycleError, bounded_resolver_factory_for_view
from products.data_modeling.backend.facade.models import (
DataModelingJob,
@@ -79,7 +86,7 @@ from products.data_quality.backend.facade.enums import (
)
from products.data_quality.backend.facade.models import DataQualityCheckRun, DataQualitySuiteRun
from products.data_warehouse.backend.facade.api import CreateTableResult
-from products.managed_warehouse.backend.facade.contracts import DuckLakeTableResult
+from products.managed_warehouse.backend.facade.contracts import DuckLakeTableResult, TrinoIncrementalWrite
from products.notifications.backend.facade.api import NotificationType, Priority, TargetType
from products.warehouse_sources.backend.facade.hooks import (
AccountPropertySourceProjection,
@@ -195,6 +202,7 @@ class TestMaterializeViewManagedWarehouseActivity:
team_id=ateam.pk,
saved_query_id=asaved_query.id,
source_query=executable_query,
+ incremental=None,
)
legacy_execute.assert_not_called()
await database_sync_to_async(ajob.refresh_from_db)()
@@ -209,6 +217,57 @@ class TestMaterializeViewManagedWarehouseActivity:
assert ajob.status == DataModelingJobStatus.COMPLETED
assert ajob.rows_materialized == 12
+ @pytest.mark.parametrize("merge_fails", [False, True])
+ async def test_trino_shadow_keeps_its_own_incremental_watermark(
+ self, activity_environment, ateam, anode, ajob, adag, asaved_query, merge_fails: bool
+ ) -> None:
+ clickhouse_mark = dt.datetime(2026, 10, 5, tzinfo=dt.UTC)
+ trino_mark = dt.datetime(2026, 10, 3, tzinfo=dt.UTC)
+ written_mark = dt.datetime(2026, 10, 7, tzinfo=dt.UTC)
+
+ def seed() -> None:
+ asaved_query.incremental_config = {"enabled": True, "incremental_key": "ts", "unique_key": ["id"]}
+ asaved_query.save(update_fields=["incremental_config"])
+ fingerprint = definition_fingerprint(asaved_query.query, get_incremental_config(asaved_query))
+ set_incremental_state(asaved_query, watermark=clickhouse_mark, fingerprint=fingerprint, mode="incremental")
+ set_incremental_state(
+ asaved_query,
+ watermark=trino_mark,
+ fingerprint=fingerprint,
+ mode="incremental",
+ scope=TRINO_INCREMENTAL_SCOPE,
+ )
+
+ await database_sync_to_async(seed)()
+ inputs = ManagedWarehouseShadowInputs(
+ team_id=ateam.pk, node_id=str(anode.id), dag_id=str(adag.id), job_id=str(ajob.id), use_trino=True
+ )
+ with (
+ unittest.mock.patch(
+ "products.data_modeling.backend.logic.incremental_plan.incremental_enabled", return_value=True
+ ),
+ unittest.mock.patch(
+ "products.managed_warehouse.backend.facade.client.request_model_alias_reconciliation",
+ ),
+ unittest.mock.patch(
+ "products.managed_warehouse.backend.facade.client.execute_trino_model",
+ return_value=DuckLakeTableResult(
+ schema_name="s", table_name="t", row_count=4, watermark=written_mark, merged=True
+ ),
+ side_effect=RuntimeError("MERGE failed") if merge_fails else None,
+ ) as execute,
+ ):
+ await activity_environment.run(materialize_view_managed_warehouse_activity, inputs)
+
+ assert execute.call_args.kwargs["incremental"] == TrinoIncrementalWrite(
+ incremental_key="ts", unique_key=("id",), since=trino_mark
+ )
+ await database_sync_to_async(asaved_query.refresh_from_db)()
+ trino_state = get_incremental_state(asaved_query, scope=TRINO_INCREMENTAL_SCOPE)
+ assert trino_state.watermark == (None if merge_fails else written_mark.isoformat())
+ # ClickHouse progress is never moved by the shadow.
+ assert get_incremental_state(asaved_query).watermark == clickhouse_mark.isoformat()
+
async def test_records_failure_against_the_job_engine(self, activity_environment, ateam, anode, ajob, adag):
ajob.engine = DataModelingJobEngine.LEGACY_DUCKGRES
await database_sync_to_async(ajob.save)(update_fields=["engine"])
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
index 0195b61f529c..b99afce85981 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
@@ -124,7 +124,7 @@ async def _run(
_mock_hogql_table(*batches, value_column=value_column, windows=windows, column_types=column_types),
),
unittest.mock.patch(
- "posthog.temporal.data_modeling.activities.materialize_view._incremental_enabled",
+ "products.data_modeling.backend.logic.incremental_plan.incremental_enabled",
return_value=enabled,
),
):
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index 3049c0562989..7dba507d7977 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -83,6 +83,7 @@ _LAZY = {
"enrichment_gates_pass": "logic.enrich_view_semantics",
"enrich_view_semantics_sync": "logic.enrich_view_semantics",
"MAX_LOOKBACK_SECONDS": "logic.incremental",
+ "TRINO_INCREMENTAL_SCOPE": "logic.incremental",
"IncrementalConfig": "logic.incremental",
"IncrementalState": "logic.incremental",
"clear_incremental_state": "logic.incremental",
@@ -94,8 +95,13 @@ _LAZY = {
"record_incremental_history": "logic.incremental",
"set_incremental_state": "logic.incremental",
"window_start": "logic.incremental",
+ "INCREMENTAL_FLAG": "logic.incremental_plan",
+ "WritePlan": "logic.incremental_plan",
+ "incremental_enabled": "logic.incremental_plan",
+ "resolve_write_plan": "logic.incremental_plan",
"IncrementalFilterError": "logic.incremental_filter",
"inject_incremental_filter": "logic.incremental_filter",
+ "apply_incremental_filter": "logic.incremental_filter",
"EligibilityResult": "logic.incremental_eligibility",
"check_incremental_eligibility": "logic.incremental_eligibility",
}
diff --git a/products/data_modeling/backend/logic/incremental.py b/products/data_modeling/backend/logic/incremental.py
index 005f493d7370..2a6b15981a7b 100644
--- a/products/data_modeling/backend/logic/incremental.py
+++ b/products/data_modeling/backend/logic/incremental.py
@@ -30,6 +30,9 @@ DEFAULT_LOOKBACK_SECONDS = 0
# is better served by a full refresh, which at least produces a table with no stale rows.
MAX_LOOKBACK_SECONDS = 60 * 60 * 24 * 30
+# The incremental_state key under which the managed warehouse's Trino shadow keeps its own progress.
+TRINO_INCREMENTAL_SCOPE = "trino"
+
@dataclass(frozen=True, kw_only=True, slots=True)
class IncrementalConfig:
@@ -92,8 +95,16 @@ def get_incremental_config(saved_query) -> Optional[IncrementalConfig]:
)
-def get_incremental_state(saved_query) -> IncrementalState:
- raw = saved_query.incremental_state
+def _scoped(state: Any, scope: Optional[str]) -> Any:
+ """The state blob for one engine. ClickHouse owns the top level; other engines keep their own
+ watermark under a key, because a failed or lagging engine must not move another's progress."""
+ if scope is None or not isinstance(state, dict):
+ return state
+ return state.get(scope)
+
+
+def get_incremental_state(saved_query, *, scope: Optional[str] = None) -> IncrementalState:
+ raw = _scoped(saved_query.incremental_state, scope)
if not isinstance(raw, dict):
return IncrementalState()
return IncrementalState(
@@ -194,7 +205,9 @@ def window_start(state: IncrementalState, config: IncrementalConfig) -> Any:
return watermark
-def set_incremental_state(saved_query, *, watermark: Any, fingerprint: Optional[str], mode: str) -> None:
+def set_incremental_state(
+ saved_query, *, watermark: Any, fingerprint: Optional[str], mode: str, scope: Optional[str] = None
+) -> None:
"""Row-locked read-modify-write of the state blob.
Locked and re-read because the API can be writing ``incremental_config`` on the same row while
@@ -205,13 +218,14 @@ def set_incremental_state(saved_query, *, watermark: Any, fingerprint: Optional[
with transaction.atomic():
locked = model.objects.select_for_update().get(pk=saved_query.pk)
state = dict(locked.incremental_state or {})
- state["last_run_mode"] = mode
+ target = _writable_scope(state, scope)
+ target["last_run_mode"] = mode
if mode == "full_refresh":
- state["last_full_refresh_at"] = _isoformat(watermark_now())
+ target["last_full_refresh_at"] = _isoformat(watermark_now())
if watermark is not None:
- state["watermark"] = _serialize_watermark(watermark)
- state["watermark_type"] = _watermark_type(watermark)
- state["definition_fingerprint"] = fingerprint
+ target["watermark"] = _serialize_watermark(watermark)
+ target["watermark_type"] = _watermark_type(watermark)
+ target["definition_fingerprint"] = fingerprint
locked.incremental_state = state
locked.save(update_fields=["incremental_state"])
saved_query.incremental_state = state
@@ -233,21 +247,30 @@ def _clamp_temporal_watermark(watermark: Any) -> Any:
return watermark
-def clear_incremental_state(saved_query) -> None:
+def clear_incremental_state(saved_query, *, scope: Optional[str] = None) -> None:
"""Drop the watermark so the next run rebuilds from scratch. Used by a definition change, by
an explicit full refresh, and by any engine failure we do not want to retry incrementally."""
model = type(saved_query)
with transaction.atomic():
locked = model.objects.select_for_update().get(pk=saved_query.pk)
state = dict(locked.incremental_state or {})
- state.pop("watermark", None)
- state.pop("watermark_type", None)
- state.pop("definition_fingerprint", None)
+ target = _writable_scope(state, scope)
+ target.pop("watermark", None)
+ target.pop("watermark_type", None)
+ target.pop("definition_fingerprint", None)
locked.incremental_state = state
locked.save(update_fields=["incremental_state"])
saved_query.incremental_state = state
+def _writable_scope(state: dict[str, Any], scope: Optional[str]) -> dict[str, Any]:
+ if scope is None:
+ return state
+ nested = state.get(scope)
+ state[scope] = dict(nested) if isinstance(nested, dict) else {}
+ return state[scope]
+
+
def watermark_now() -> datetime:
from django.utils import timezone
diff --git a/products/data_modeling/backend/logic/incremental_filter.py b/products/data_modeling/backend/logic/incremental_filter.py
index ff5b0410db54..0a3e64572d64 100644
--- a/products/data_modeling/backend/logic/incremental_filter.py
+++ b/products/data_modeling/backend/logic/incremental_filter.py
@@ -36,7 +36,11 @@ class IncrementalFilterError(ValueError):
def inject_incremental_filter(query: str, *, incremental_key: str, since: Any) -> SelectLike:
"""Parse ``query`` and return it filtered to rows at or after ``since``."""
- node = parse_select(query)
+ return apply_incremental_filter(parse_select(query), incremental_key=incremental_key, since=since)
+
+
+def apply_incremental_filter(node: SelectLike, *, incremental_key: str, since: Any) -> SelectLike:
+ """Filter an already-parsed query, for callers that replace placeholders before filtering."""
filtered = _push_predicate(node, incremental_key=incremental_key, since=since)
return _wrap_with_guard(filtered, incremental_key=incremental_key, since=since)
diff --git a/products/data_modeling/backend/logic/incremental_plan.py b/products/data_modeling/backend/logic/incremental_plan.py
new file mode 100644
index 000000000000..a7e486de95c0
--- /dev/null
+++ b/products/data_modeling/backend/logic/incremental_plan.py
@@ -0,0 +1,97 @@
+"""Decide whether one materialization run rebuilds its table or updates it.
+
+Each engine keeps its own watermark, so the same decision runs once per engine with that engine's
+``scope``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, cast
+from uuid import UUID
+
+import structlog
+
+from posthog.models import Team
+from posthog.ph_client import feature_enabled_or_false
+
+from products.data_modeling.backend.logic.incremental import (
+ IncrementalConfig,
+ definition_fingerprint,
+ get_incremental_config,
+ get_incremental_state,
+ window_start,
+)
+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+
+LOGGER = structlog.get_logger(__name__)
+
+# The only gate. Incremental is also the only path that writes through deltalite, so turning this
+# off falls back to full refresh on delta-rs and takes the engine with it.
+INCREMENTAL_FLAG = "data-modeling-incremental-views"
+
+
+def incremental_enabled(team_id: int) -> bool:
+ """Fails closed: a flag-service outage produces a full refresh, which costs money but is
+ never wrong."""
+ try:
+ team = Team.objects.only("organization_id").get(id=team_id)
+ return feature_enabled_or_false(
+ INCREMENTAL_FLAG,
+ str(team_id),
+ groups={"organization": str(team.organization_id), "project": str(team_id)},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team_id)},
+ },
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ LOGGER.warning("Failed to evaluate incremental flag; falling back to full refresh", team_id=team_id)
+ return False
+
+
+@dataclass(frozen=True, kw_only=True, slots=True)
+class WritePlan:
+ """Whether this run rebuilds the table or updates it, and why. The reason is surfaced on the
+ job so an unexpectedly expensive run explains itself."""
+
+ incremental: bool
+ reason: str
+ since: Any = None
+ fingerprint: str | None = None
+ config: IncrementalConfig | None = None
+
+
+def resolve_write_plan(team_id: int, saved_query_id: UUID | str, *, scope: str | None = None) -> WritePlan:
+ saved_query = DataWarehouseSavedQuery.objects.get(team_id=team_id, id=saved_query_id)
+ config = get_incremental_config(saved_query)
+ if config is None:
+ return WritePlan(incremental=False, reason="not configured for incremental materialization")
+
+ if not incremental_enabled(team_id):
+ return WritePlan(incremental=False, reason="incremental materialization is not enabled")
+
+ fingerprint = definition_fingerprint(cast(dict, saved_query.query), config)
+ state = get_incremental_state(saved_query, scope=scope)
+
+ if state.watermark is None:
+ return WritePlan(incremental=False, reason="first run", fingerprint=fingerprint, config=config)
+
+ if fingerprint is None or fingerprint != state.definition_fingerprint:
+ # The query or its config changed, so existing rows were computed by a definition that no
+ # longer applies. Rebuilding is the only way the table still matches the SQL the user sees.
+ return WritePlan(incremental=False, reason="definition changed", fingerprint=fingerprint, config=config)
+
+ since = window_start(state, config)
+ if since is None:
+ return WritePlan(incremental=False, reason="no usable watermark", fingerprint=fingerprint, config=config)
+
+ return WritePlan(
+ incremental=True,
+ reason="incremental",
+ since=since,
+ fingerprint=fingerprint,
+ config=config,
+ )
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
index ed93c02404c7..62f6d982aae7 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
@@ -278,6 +278,7 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
def run(self, request: request.Request, *args, **kwargs) -> response.Response:
"""Run this saved query."""
from products.data_modeling.backend.facade.api import (
+ TRINO_INCREMENTAL_SCOPE,
MissingDagNodeError,
clear_incremental_state,
materialize_saved_query,
@@ -294,6 +295,7 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
# dispatch could roll back, or the worker reads the old watermark and runs
# incrementally instead.
clear_incremental_state(saved_query)
+ clear_incremental_state(saved_query, scope=TRINO_INCREMENTAL_SCOPE)
try:
materialize_saved_query(saved_query, triggered_by_id=request.user.pk)
diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.py
index 54d09b2c1467..263737bfb0a8 100644
--- a/products/managed_warehouse/backend/facade/client.py
+++ b/products/managed_warehouse/backend/facade/client.py
@@ -46,6 +46,7 @@ if TYPE_CHECKING:
DuckLakeTableResult,
ManagedWarehouseTrinoConnection,
TrinoCompiledQuery,
+ TrinoIncrementalWrite,
)
from products.managed_warehouse.backend.service_credentials import ServiceCredential
from products.managed_warehouse.backend.trino_compiler import PreparedTrinoCompiler
@@ -92,6 +93,7 @@ def execute_trino_shadow_materialization(
team_id: int,
saved_query_id: str | UUID,
source_query: object,
+ incremental: TrinoIncrementalWrite | None = None,
) -> DuckLakeTableResult:
from products.managed_warehouse.backend.trino_materialization import ( # noqa: PLC0415 -- keeps the optional Trino driver off startup paths
execute_trino_shadow_materialization as execute_shadow,
@@ -102,6 +104,7 @@ def execute_trino_shadow_materialization(
team_id=team_id,
saved_query_id=saved_query_id,
source_query=source_query,
+ incremental=incremental,
)
@@ -230,7 +233,12 @@ async def request_model_alias_reconciliation(team_id: int, saved_query_id: str |
async def execute_trino_model(
- *, organization_id: str, team_id: int, saved_query_id: str | UUID, source_query: object
+ *,
+ organization_id: str,
+ team_id: int,
+ saved_query_id: str | UUID,
+ source_query: object,
+ incremental: TrinoIncrementalWrite | None = None,
) -> DuckLakeTableResult:
from products.managed_warehouse.backend.trino_execution import ( # noqa: PLC0415 -- keeps executor creation off startup paths
run_trino_model,
@@ -245,6 +253,7 @@ async def execute_trino_model(
team_id=team_id,
saved_query_id=saved_query_id,
source_query=source_query,
+ incremental=incremental,
control=control,
),
)
diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.py
index d1b58a7826e7..a1004a175606 100644
--- a/products/managed_warehouse/backend/facade/contracts.py
+++ b/products/managed_warehouse/backend/facade/contracts.py
@@ -324,6 +324,20 @@ class TrinoCompiledQuery:
hogql: str | None = None
+@frozen
+class TrinoIncrementalWrite:
+ """How a Trino model build tracks an incremental view.
+
+ With ``since`` set, the build reads only rows at or after it and merges them into the existing
+ table on ``unique_key``. Without it, the build replaces the table. Both report the highest
+ ``incremental_key`` written, so a full build seeds the next incremental one.
+ """
+
+ incremental_key: str
+ unique_key: tuple[str, ...]
+ since: Any = None
+
+
class TrinoExpansionMode(StrEnum):
PURE = "pure"
DJANGO = "django"
@@ -341,10 +355,13 @@ class DuckLakeQueryResult:
query_ms: float | None = None
-@dataclass
+@frozen
class DuckLakeTableResult:
schema_name: str
table_name: str
row_count: int
file_size_bytes: int = 0
file_size_delta_bytes: int = 0
+ # Highest incremental key written, for builds that track one. None when no rows were written.
+ watermark: Any = None
+ merged: bool = False
diff --git a/products/managed_warehouse/backend/tests/test_trino_materialization.py b/products/managed_warehouse/backend/tests/test_trino_materialization.py
index c1fd04a3f56d..5ac6150079f7 100644
--- a/products/managed_warehouse/backend/tests/test_trino_materialization.py
+++ b/products/managed_warehouse/backend/tests/test_trino_materialization.py
@@ -1,3 +1,5 @@
+import datetime as dt
+from typing import Any
from uuid import UUID, uuid4
from posthog.test.base import BaseTest
@@ -18,12 +20,14 @@ from products.managed_warehouse.backend.facade.contracts import (
ManagedWarehouseTeamMembership,
TrinoCompiledQuery,
TrinoExpansionMode,
+ TrinoIncrementalWrite,
)
from products.managed_warehouse.backend.models import (
ManagedWarehouseViewTranslationJob,
ManagedWarehouseViewTranslationResult,
)
from products.managed_warehouse.backend.table_binding import build_trino_table_locators
+from products.managed_warehouse.backend.trino_materialization import DuplicateUniqueKeyError
from products.managed_warehouse.backend.view_translation_status import source_query_hash
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -81,6 +85,7 @@ class TestTrinoShadowMaterialization(BaseTest):
team=self.team,
bypass_warehouse_access_control=True,
expansion_mode=TrinoExpansionMode.DJANGO,
+ select_transform=None,
)
connect.assert_called_once_with(
str(self.organization.pk),
@@ -227,3 +232,128 @@ class TestTrinoShadowMaterialization(BaseTest):
)
assert locators["orders"] == (self.connection.catalog, written.schema_name, written.table_name)
assert written.table_name == (model_label or f"model_{self.saved_query_id.hex}")
+
+
+class _ScriptedCursor:
+ """Answers each statement by its leading words, and records every statement it ran."""
+
+ def __init__(self, *, table_exists: bool, staged: int, duplicate: bool = False, max_key: Any = None) -> None:
+ self.table_exists = table_exists
+ self.staged = staged
+ self.duplicate = duplicate
+ self.max_key = max_key
+ self.statements: list[tuple[str, Any]] = []
+ self.rowcount = -1
+ self.description: list[tuple[str]] | None = None
+ self._rows: list[tuple[Any, ...]] = []
+
+ def execute(self, statement: str, parameters: Any = None) -> None:
+ self.statements.append((statement, parameters))
+ self.rowcount, self._rows = -1, []
+ if "information_schema.tables" in statement:
+ self._rows = [(1,)] if self.table_exists else []
+ elif statement.startswith("CREATE OR REPLACE TABLE"):
+ self.rowcount = self.staged
+ elif "HAVING count(*) > 1" in statement:
+ self._rows = [(1,)] if self.duplicate else []
+ elif statement.endswith("LIMIT 0"):
+ self.description = [("id",), ("ts",)]
+ elif statement.startswith("MERGE"):
+ self.rowcount = self.staged
+ elif statement.startswith("SELECT max("):
+ self._rows = [(self.max_key,)]
+
+ def fetchall(self) -> list[tuple[Any, ...]]:
+ return self._rows
+
+ def close(self) -> None:
+ pass
+
+
+class TestTrinoIncrementalMaterialization(BaseTest):
+ saved_query_id = UUID("12345678-1234-5678-1234-567812345678")
+ query = {"kind": "HogQLQuery", "query": "SELECT id, ts FROM orders"}
+ since = dt.datetime(2026, 10, 1, tzinfo=dt.UTC)
+
+ def run_build(
+ self, cursor: _ScriptedCursor, since: Any
+ ) -> tuple[DuckLakeTableResult | Exception, list[str], list[Any]]:
+ compiled = TrinoCompiledQuery(sql="SELECT id, ts FROM orders", values={})
+ connection = MagicMock(catalog="cat")
+ connection.cursor.return_value = cursor
+ with (
+ patch(
+ "products.managed_warehouse.backend.trino_materialization.compile_hogql_to_trino_sql",
+ return_value=compiled,
+ ) as compile_query,
+ patch(
+ "products.managed_warehouse.backend.trino_materialization.connect_managed_warehouse_trino"
+ ) as connect,
+ ):
+ connect.return_value.__enter__.return_value = connection
+ try:
+ result: DuckLakeTableResult | Exception = execute_trino_shadow_materialization(
+ organization_id=str(self.organization.pk),
+ team_id=self.team.pk,
+ saved_query_id=self.saved_query_id,
+ source_query=self.query,
+ incremental=TrinoIncrementalWrite(incremental_key="ts", unique_key=("id",), since=since),
+ )
+ except Exception as error:
+ result = error
+ transforms = [call.kwargs["select_transform"] for call in compile_query.call_args_list]
+ return result, [statement for statement, _ in cursor.statements], transforms
+
+ def test_merges_staged_rows_and_reports_their_watermark(self) -> None:
+ latest = dt.datetime(2026, 10, 7, tzinfo=dt.UTC)
+ result, statements, transforms = self.run_build(
+ _ScriptedCursor(table_exists=True, staged=3, max_key=latest), self.since
+ )
+
+ assert isinstance(result, DuckLakeTableResult)
+ assert (result.row_count, result.watermark, result.merged) == (3, latest, True)
+ assert len(transforms) == 1 and transforms[0] is not None
+ table = f'"cat"."posthog_data_modeling_team_{self.team.pk}"."model_{self.saved_query_id.hex}"'
+ stage = table[:-1] + '__ph_incremental_stage"'
+ assert f"CREATE OR REPLACE TABLE {stage} AS SELECT id, ts FROM orders" in statements
+ assert not any(statement.startswith(f"CREATE OR REPLACE TABLE {table} ") for statement in statements)
+ assert (
+ f'MERGE INTO {table} t USING {stage} s ON t."id" = s."id" '
+ 'WHEN MATCHED THEN UPDATE SET "id" = s."id", "ts" = s."ts" '
+ 'WHEN NOT MATCHED THEN INSERT ("id", "ts") VALUES (s."id", s."ts")'
+ ) in statements
+ assert f'SELECT max("ts") FROM {stage}' in statements
+ assert statements[-1] == f"DROP TABLE IF EXISTS {stage}"
+
+ @parameterized.expand(
+ [
+ ("quiet_window", _ScriptedCursor(table_exists=True, staged=0), None),
+ ("duplicate_keys", _ScriptedCursor(table_exists=True, staged=3, duplicate=True), DuplicateUniqueKeyError),
+ ]
+ )
+ def test_leaves_the_table_untouched(self, _name: str, cursor: _ScriptedCursor, error: type | None) -> None:
+ result, statements, _ = self.run_build(cursor, self.since)
+
+ if error is None:
+ assert isinstance(result, DuckLakeTableResult)
+ assert (result.row_count, result.watermark, result.merged) == (0, None, True)
+ else:
+ assert isinstance(result, error)
+ assert not any(statement.startswith("MERGE") for statement in statements)
+ assert statements[-1].startswith("DROP TABLE IF EXISTS") and "__ph_incremental_stage" in statements[-1]
+
+ @parameterized.expand([("first_run", None, True), ("table_missing", since, False)])
+ def test_builds_the_whole_table_and_seeds_the_watermark(self, _name: str, since: Any, exists: bool) -> None:
+ latest = dt.datetime(2026, 10, 7, tzinfo=dt.UTC)
+ result, statements, transforms = self.run_build(
+ _ScriptedCursor(table_exists=exists, staged=9, max_key=latest), since
+ )
+
+ assert isinstance(result, DuckLakeTableResult)
+ assert (result.row_count, result.watermark, result.merged) == (9, latest, False)
+ # The table is rebuilt from the unfiltered query.
+ assert transforms[-1] is None
+ table = f'"cat"."posthog_data_modeling_team_{self.team.pk}"."model_{self.saved_query_id.hex}"'
+ assert f"CREATE OR REPLACE TABLE {table} AS SELECT id, ts FROM orders" in statements
+ assert not any("__ph_incremental_stage" in statement for statement in statements)
+ assert statements[-1] == f'SELECT max("ts") FROM {table}'
diff --git a/products/managed_warehouse/backend/trino_compiler.py b/products/managed_warehouse/backend/trino_compiler.py
index c75c0449df2d..886b32f311b9 100644
--- a/products/managed_warehouse/backend/trino_compiler.py
+++ b/products/managed_warehouse/backend/trino_compiler.py
@@ -14,8 +14,11 @@ from products.managed_warehouse.backend.facade.cp_teams import get_org_team_memb
from products.managed_warehouse.backend.table_binding import build_trino_table_locators
if TYPE_CHECKING:
+ from collections.abc import Callable
+
from posthog.schema import HogQLQuery
+ from posthog.hogql import ast
from posthog.hogql.transforms.trino.manifest import PreparedTrinoCatalog, TrinoCatalogManifest
from posthog.models import Team, User
@@ -210,6 +213,8 @@ def compile_hogql_to_trino_sql(
include_hogql: bool = False,
expansion_mode: TrinoExpansionMode = TrinoExpansionMode.PURE,
catalog_manifest: TrinoCatalogManifest | None = None,
+ select_transform: Callable[[ast.SelectQuery | ast.SelectSetQuery], ast.SelectQuery | ast.SelectSetQuery]
+ | None = None,
) -> TrinoCompiledQuery:
"""Compile HogQL for the ready Trino catalog that serves the team's DuckLake data.
@@ -218,8 +223,12 @@ def compile_hogql_to_trino_sql(
Set ``include_hogql`` to render normalized HogQL for diagnostics. Pure manifest-backed
compilation is the default; select ``TrinoExpansionMode.DJANGO`` only when the query needs
actions, cohorts, saved queries, variables, filters, or other Django-backed semantics.
+ ``select_transform`` rewrites the parsed query after placeholders are replaced, so it sees the
+ same AST the printer does. It needs ``TrinoExpansionMode.DJANGO``.
"""
if expansion_mode == TrinoExpansionMode.PURE:
+ if select_transform is not None:
+ raise ValueError("A select transform needs Django expansion")
return prepare_hogql_to_trino_compiler(
team_id,
team=team,
@@ -288,6 +297,8 @@ def compile_hogql_to_trino_sql(
for variable in query.variables.values():
variables[variable.code_name] = variable.value
parsed = cast("ast.SelectQuery | ast.SelectSetQuery", replace_placeholders(parsed, replacements))
+ if select_transform is not None:
+ parsed = select_transform(parsed)
trino_table_locators = build_trino_table_locators(
database,
diff --git a/products/managed_warehouse/backend/trino_materialization.py b/products/managed_warehouse/backend/trino_materialization.py
index af96c1f07211..b5bc9310ba35 100644
--- a/products/managed_warehouse/backend/trino_materialization.py
+++ b/products/managed_warehouse/backend/trino_materialization.py
@@ -1,8 +1,10 @@
from __future__ import annotations
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from uuid import UUID
+import structlog
+
from posthog.schema import HogQLQuery
from posthog.hogql.escape_sql import escape_trino_identifier
@@ -11,14 +13,30 @@ from posthog.hogql.trino_parameters import convert_pyformat_placeholders
from posthog.models import Team
from products.managed_warehouse.backend.common import ducklake_data_modeling_schema
-from products.managed_warehouse.backend.facade.contracts import DuckLakeTableResult, TrinoExpansionMode
+from products.managed_warehouse.backend.facade.contracts import (
+ DuckLakeTableResult,
+ TrinoExpansionMode,
+ TrinoIncrementalWrite,
+)
from products.managed_warehouse.backend.table_binding import get_data_modeling_table_names
from products.managed_warehouse.backend.trino_compiler import compile_hogql_to_trino_sql
from products.managed_warehouse.backend.trino_connection import connect_managed_warehouse_trino
if TYPE_CHECKING:
+ from trino.dbapi import Cursor
+
+ from posthog.hogql import ast
+
from products.managed_warehouse.backend.trino_execution import TrinoQueryControl
+STAGE_SUFFIX = "__ph_incremental_stage"
+
+logger = structlog.get_logger(__name__)
+
+
+class DuplicateUniqueKeyError(ValueError):
+ """The incremental rows hold more than one row per unique key, so a merge cannot place them."""
+
def execute_trino_shadow_materialization(
*,
@@ -26,22 +44,18 @@ def execute_trino_shadow_materialization(
team_id: int,
saved_query_id: str | UUID,
source_query: object,
+ incremental: TrinoIncrementalWrite | None = None,
control: TrinoQueryControl | None = None,
) -> DuckLakeTableResult:
if control:
control.checkpoint()
team = Team.objects.get(pk=team_id, organization_id=organization_id)
- compiled = compile_hogql_to_trino_sql(
- team_id,
- HogQLQuery.model_validate(source_query),
- team=team,
- bypass_warehouse_access_control=True,
- expansion_mode=TrinoExpansionMode.DJANGO,
- )
+ hogql_query = HogQLQuery.model_validate(source_query)
+ merge = incremental is not None and incremental.since is not None
+ compiled = _compile(team, hogql_query, incremental if merge else None)
if control:
control.checkpoint()
- sql, parameters = convert_pyformat_placeholders(compiled.sql, compiled.values)
schema_name = ducklake_data_modeling_schema(team_id)
query_id = UUID(str(saved_query_id))
table_name = get_data_modeling_table_names(team_id, [query_id])[query_id]
@@ -54,19 +68,154 @@ def execute_trino_shadow_materialization(
if control:
control.attach(cursor)
try:
- if control:
- control.checkpoint()
- cursor.execute(f"CREATE SCHEMA IF NOT EXISTS {schema}")
- cursor.fetchall()
- if control:
- control.checkpoint()
+ _run(cursor, control, f"CREATE SCHEMA IF NOT EXISTS {schema}")
+ if merge and not _table_exists(cursor, control, connection.catalog, schema_name, table_name):
+ # Nothing to merge into, so build the whole table from the unfiltered query.
+ merge = False
+ compiled = _compile(team, hogql_query, None)
+ sql, parameters = convert_pyformat_placeholders(compiled.sql, compiled.values)
+ if merge:
+ assert incremental is not None
+ stage = f"{schema}.{escape_trino_identifier(table_name + STAGE_SUFFIX)}"
+ try:
+ row_count, watermark = _merge(cursor, control, table, stage, sql, parameters, incremental)
+ finally:
+ _drop_stage(cursor, stage)
+ return DuckLakeTableResult(
+ schema_name=schema_name,
+ table_name=table_name,
+ row_count=row_count,
+ watermark=watermark,
+ merged=True,
+ )
+
# The connector replaces the table atomically, so a failed write preserves the previous shadow.
- cursor.execute(f"CREATE OR REPLACE TABLE {table} AS {sql}", parameters or None)
- cursor.fetchall()
- row_count = cursor.rowcount
- if row_count < 0:
- raise RuntimeError("Trino did not report the materialized row count")
+ row_count = _run(cursor, control, f"CREATE OR REPLACE TABLE {table} AS {sql}", parameters)
+ watermark = (
+ _max_key(cursor, control, table, incremental.incremental_key) if incremental is not None else None
+ )
finally:
cursor.close()
- return DuckLakeTableResult(schema_name=schema_name, table_name=table_name, row_count=row_count)
+ return DuckLakeTableResult(schema_name=schema_name, table_name=table_name, row_count=row_count, watermark=watermark)
+
+
+def _compile(team: Team, query: HogQLQuery, incremental: TrinoIncrementalWrite | None) -> Any:
+ select_transform = None
+ if incremental is not None:
+ from products.data_modeling.backend.facade.api import ( # noqa: PLC0415 -- the facade loads lazily
+ apply_incremental_filter,
+ )
+
+ def select_transform(node: ast.SelectQuery | ast.SelectSetQuery) -> ast.SelectQuery | ast.SelectSetQuery:
+ return apply_incremental_filter(node, incremental_key=incremental.incremental_key, since=incremental.since)
+
+ return compile_hogql_to_trino_sql(
+ team.pk,
+ query,
+ team=team,
+ bypass_warehouse_access_control=True,
+ expansion_mode=TrinoExpansionMode.DJANGO,
+ select_transform=select_transform,
+ )
+
+
+def _merge(
+ cursor: Cursor,
+ control: TrinoQueryControl | None,
+ table: str,
+ stage: str,
+ sql: str,
+ parameters: list[object],
+ incremental: TrinoIncrementalWrite,
+) -> tuple[int, Any]:
+ """Stage the new rows, then merge them into ``table`` on the unique key in one statement.
+
+ Staging first lets the duplicate check and the watermark read the same rows the merge writes,
+ and keeps the target untouched until the single MERGE commits.
+ """
+ staged = _run(cursor, control, f"CREATE OR REPLACE TABLE {stage} AS {sql}", parameters)
+ if staged == 0:
+ return 0, None
+
+ keys = [escape_trino_identifier(key) for key in incremental.unique_key]
+ _run(
+ cursor,
+ control,
+ f"SELECT 1 FROM {stage} GROUP BY {', '.join(keys)} HAVING count(*) > 1 LIMIT 1",
+ fetch=False,
+ )
+ if cursor.fetchall():
+ raise DuplicateUniqueKeyError(
+ f"The incremental rows hold more than one row per unique key ({', '.join(incremental.unique_key)})"
+ )
+
+ _run(cursor, control, f"SELECT * FROM {stage} LIMIT 0")
+ columns = [escape_trino_identifier(column[0]) for column in cursor.description or []]
+ on = " AND ".join(f"t.{key} = s.{key}" for key in keys)
+ updates = ", ".join(f"{column} = s.{column}" for column in columns)
+ inserted = ", ".join(columns)
+ values = ", ".join(f"s.{column}" for column in columns)
+ _run(
+ cursor,
+ control,
+ f"MERGE INTO {table} t USING {stage} s ON {on} "
+ f"WHEN MATCHED THEN UPDATE SET {updates} "
+ f"WHEN NOT MATCHED THEN INSERT ({inserted}) VALUES ({values})",
+ )
+ return staged, _max_key(cursor, control, stage, incremental.incremental_key)
+
+
+def _drop_stage(cursor: Cursor, stage: str) -> None:
+ # A leftover stage costs storage only; the next run replaces it. Never mask the build's own error.
+ try:
+ _run(cursor, None, f"DROP TABLE IF EXISTS {stage}")
+ except Exception:
+ logger.warning("trino_incremental_stage_drop_failed", stage=stage, exc_info=True)
+
+
+def _table_exists(
+ cursor: Cursor, control: TrinoQueryControl | None, catalog: str, schema_name: str, table_name: str
+) -> bool:
+ _run(
+ cursor,
+ control,
+ f"SELECT 1 FROM {escape_trino_identifier(catalog)}.information_schema.tables "
+ "WHERE table_schema = ? AND table_name = ? AND table_type = 'BASE TABLE'",
+ [schema_name, table_name],
+ fetch=False,
+ )
+ return bool(cursor.fetchall())
+
+
+def _max_key(cursor: Cursor, control: TrinoQueryControl | None, table: str, incremental_key: str) -> Any:
+ _run(cursor, control, f"SELECT max({escape_trino_identifier(incremental_key)}) FROM {table}", fetch=False)
+ rows = cursor.fetchall()
+ return rows[0][0] if rows else None
+
+
+def _run(
+ cursor: Cursor,
+ control: TrinoQueryControl | None,
+ statement: str,
+ parameters: list[object] | None = None,
+ *,
+ fetch: bool = True,
+) -> int:
+ """Run one statement and return the row count Trino reports for a write.
+
+ ``fetch=False`` leaves the result for the caller to read.
+ """
+ if control:
+ control.checkpoint()
+ if parameters:
+ cursor.execute(statement, parameters)
+ else:
+ cursor.execute(statement)
+ if not fetch:
+ return -1
+ cursor.fetchall()
+ row_count = cursor.rowcount
+ if statement.startswith(("CREATE OR REPLACE TABLE", "MERGE")) and row_count < 0:
+ raise RuntimeError("Trino did not report the materialized row count")
+ return row_count