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.

fix(data-warehouse): use inclusive cursor on date-typed incremental sync (#59033)

Tom Owersa81a147aac5a
diff --git a/posthog/temporal/data_imports/pipelines/helpers.py b/posthog/temporal/data_imports/pipelines/helpers.py
index 222b14fd835a..8e47d441385a 100644
--- a/posthog/temporal/data_imports/pipelines/helpers.py
+++ b/posthog/temporal/data_imports/pipelines/helpers.py
@@ -45,6 +45,17 @@ def incremental_type_to_initial_value(field_type: IncrementalFieldType) -> int |
raise ValueError(f"Unsupported incremental field type: {field_type}")
+def incremental_type_to_operator(field_type: IncrementalFieldType) -> str:
+ # Date cursors lose all rows that land on the boundary day after the previous sync's
+ # cursor advance, because the cursor only carries day-granularity and `>` skips
+ # everything equal to that day. `>=` re-fetches the boundary day so primary-key dedup
+ # (or append acceptance) can close the gap. Every other field type carries enough
+ # resolution that `>` is safe and avoids re-shipping the boundary row on every sync.
+ if field_type == IncrementalFieldType.Date:
+ return ">="
+ return ">"
+
+
def build_table_name(source: ExternalDataSource, schema_name: str):
return f"{source.prefix or ''}{source.source_type}_{schema_name}".lower()
diff --git a/posthog/temporal/data_imports/pipelines/test_helpers.py b/posthog/temporal/data_imports/pipelines/test_helpers.py
index 3f96b4e1c54d..21b5ce5ae052 100644
--- a/posthog/temporal/data_imports/pipelines/test_helpers.py
+++ b/posthog/temporal/data_imports/pipelines/test_helpers.py
@@ -1,9 +1,10 @@
+import pytest
from posthog.test.base import BaseTest
from unittest.mock import patch
import structlog
-from posthog.temporal.data_imports.pipelines.helpers import sync_revenue_analytics_views
+from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_operator, sync_revenue_analytics_views
from posthog.temporal.data_imports.sources.stripe.constants import CHARGE_RESOURCE_NAME as STRIPE_CHARGE_RESOURCE_NAME
from products.data_warehouse.backend.models import (
@@ -12,11 +13,32 @@ from products.data_warehouse.backend.models import (
ExternalDataSchema,
ExternalDataSource,
)
-from products.data_warehouse.backend.types import DataWarehouseManagedViewSetKind, ExternalDataSourceType
+from products.data_warehouse.backend.types import (
+ DataWarehouseManagedViewSetKind,
+ ExternalDataSourceType,
+ IncrementalFieldType,
+)
PATH = "products.data_warehouse.backend.models.datawarehouse_saved_query"
+ "field_type,expected",
+ [
+ # Date is the only inclusive case — day-granularity cursors otherwise lose any
+ # rows landed on the boundary day after the cursor is saved.
+ (IncrementalFieldType.Date, ">="),
+ (IncrementalFieldType.DateTime, ">"),
+ (IncrementalFieldType.Timestamp, ">"),
+ (IncrementalFieldType.Integer, ">"),
+ (IncrementalFieldType.Numeric, ">"),
+ (IncrementalFieldType.ObjectID, ">"),
+ ],
+)
+def test_incremental_type_to_operator(field_type: IncrementalFieldType, expected: str) -> None:
+ assert incremental_type_to_operator(field_type) == expected
+
+
class TestSyncRevenueAnalyticsViews(BaseTest):
"""Tests for the sync_revenue_analytics_views function
that should be called after run_post_load_operations completes.
diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
index 9d1f32e7cd5e..76168ece9e5a 100644
--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
@@ -16,7 +16,10 @@ from structlog.types import FilteringBoundLogger
from posthog.exceptions_capture import capture_exception
from posthog.temporal.data_imports.naming_convention import NamingConvention
-from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
+from posthog.temporal.data_imports.pipelines.helpers import (
+ incremental_type_to_initial_value,
+ incremental_type_to_operator,
+)
from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_TABLE_SIZE_BYTES
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.pipelines.pipeline.utils import DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES
@@ -509,9 +512,10 @@ def _get_query(
if isinstance(last_value, datetime) or isinstance(last_value, date):
last_value = f"'{last_value.isoformat()}'"
+ operator = incremental_type_to_operator(incremental_field_type)
return f"""
SELECT * FROM `{bq_table.dataset_id}`.`{bq_table.table_id}`
- WHERE `{incremental_field}` > {last_value}
+ WHERE `{incremental_field}` {operator} {last_value}
ORDER BY `{incremental_field}` ASC
"""
diff --git a/posthog/temporal/data_imports/sources/mssql/mssql.py b/posthog/temporal/data_imports/sources/mssql/mssql.py
index 7d1d6a7310aa..bf11df0c3ac2 100644
--- a/posthog/temporal/data_imports/sources/mssql/mssql.py
+++ b/posthog/temporal/data_imports/sources/mssql/mssql.py
@@ -13,7 +13,10 @@ from structlog.types import FilteringBoundLogger
from posthog.exceptions_capture import capture_exception
from posthog.temporal.data_imports.naming_convention import NamingConvention
-from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
+from posthog.temporal.data_imports.pipelines.helpers import (
+ incremental_type_to_initial_value,
+ incremental_type_to_operator,
+)
from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_CHUNK_SIZE, DEFAULT_TABLE_SIZE_BYTES
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.pipelines.pipeline.utils import (
@@ -110,8 +113,9 @@ def _build_query(
if db_incremental_field_last_value is None:
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
+ operator = incremental_type_to_operator(incremental_field_type)
query = base_query.format(top="TOP 100" if add_limit else "", schema=schema, table_name=table_name)
- query = f"{query} WHERE [{incremental_field}] > %(incremental_value)s"
+ query = f"{query} WHERE [{incremental_field}] {operator} %(incremental_value)s"
# it is only safe to have this order by nested in a CTE if TOP is also specified
# ordering for incremental sync purposes where TOP is not specified is handled in get_rows()
if add_limit:
diff --git a/posthog/temporal/data_imports/sources/mysql/mysql.py b/posthog/temporal/data_imports/sources/mysql/mysql.py
index 75f936d5b718..30b86173dd5a 100644
--- a/posthog/temporal/data_imports/sources/mysql/mysql.py
+++ b/posthog/temporal/data_imports/sources/mysql/mysql.py
@@ -20,7 +20,10 @@ from structlog.types import FilteringBoundLogger
from posthog.exceptions_capture import capture_exception
from posthog.temporal.data_imports.naming_convention import NamingConvention
-from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
+from posthog.temporal.data_imports.pipelines.helpers import (
+ incremental_type_to_initial_value,
+ incremental_type_to_operator,
+)
from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_CHUNK_SIZE, DEFAULT_TABLE_SIZE_BYTES
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.pipelines.pipeline.utils import (
@@ -190,9 +193,10 @@ def _build_query(
if db_incremental_field_last_value is None:
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
+ operator = incremental_type_to_operator(incremental_field_type)
query = (
f"SELECT * FROM {table}{hint}"
- f" WHERE {_sanitize_identifier(incremental_field)} > %(incremental_value)s"
+ f" WHERE {_sanitize_identifier(incremental_field)} {operator} %(incremental_value)s"
f" ORDER BY {_sanitize_identifier(incremental_field)} ASC"
)
diff --git a/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py b/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py
index bcf97832667c..493e12c5e8a5 100644
--- a/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py
+++ b/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py
@@ -12,7 +12,10 @@ import pyarrow as pa
from psycopg import sql
from structlog.types import FilteringBoundLogger
-from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
+from posthog.temporal.data_imports.pipelines.helpers import (
+ incremental_type_to_initial_value,
+ incremental_type_to_operator,
+)
from posthog.temporal.data_imports.pipelines.pipeline.utils import (
DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,
QueryTimeoutException,
@@ -514,10 +517,12 @@ def build_partition_query(
if db_incremental_field_last_value is None:
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
- return sql.SQL("SELECT * FROM {schema}.{table} WHERE {field} > {last_value} ORDER BY {field} ASC").format(
+ operator = sql.SQL(incremental_type_to_operator(incremental_field_type))
+ return sql.SQL("SELECT * FROM {schema}.{table} WHERE {field} {op} {last_value} ORDER BY {field} ASC").format(
schema=sql.Identifier(child_schema),
table=sql.Identifier(child_name),
field=sql.Identifier(incremental_field),
+ op=operator,
last_value=sql.Literal(db_incremental_field_last_value),
)
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index a243ddfebd2f..197facbc2336 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -24,7 +24,10 @@ from structlog.types import FilteringBoundLogger
from posthog.exceptions_capture import capture_exception
from posthog.temporal.data_imports.naming_convention import NamingConvention
-from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
+from posthog.temporal.data_imports.pipelines.helpers import (
+ incremental_type_to_initial_value,
+ incremental_type_to_operator,
+)
from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_CHUNK_SIZE, DEFAULT_TABLE_SIZE_BYTES
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.pipelines.pipeline.utils import (
@@ -795,30 +798,41 @@ def _build_query(
if db_incremental_field_last_value is None:
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
+ # Use the type-aware operator (`>=` for Date) only for single-shot scans. Windowed
+ # scans (upper_bound_inclusive set) must keep `>` because consecutive windows use the
+ # previous window's hi as the next window's lo — `>=` would re-fetch every row at the
+ # boundary value, duplicating each window's hi inside a single run.
+ operator = (
+ sql.SQL(incremental_type_to_operator(incremental_field_type)) if upper_bound_inclusive is None else sql.SQL(">")
+ )
+
if add_sampling:
if table_type == "view":
query = sql.SQL(
- "SELECT * FROM {schema}.{table} WHERE {incremental_field} > {last_value} AND random() < 0.01"
+ "SELECT * FROM {schema}.{table} WHERE {incremental_field} {op} {last_value} AND random() < 0.01"
).format(
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
incremental_field=sql.Identifier(incremental_field),
+ op=operator,
last_value=sql.Literal(db_incremental_field_last_value),
)
else:
query = sql.SQL(
- "SELECT * FROM {schema}.{table} TABLESAMPLE SYSTEM (1) WHERE {incremental_field} > {last_value}"
+ "SELECT * FROM {schema}.{table} TABLESAMPLE SYSTEM (1) WHERE {incremental_field} {op} {last_value}"
).format(
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
incremental_field=sql.Identifier(incremental_field),
+ op=operator,
last_value=sql.Literal(db_incremental_field_last_value),
)
else:
- query = sql.SQL("SELECT * FROM {schema}.{table} WHERE {incremental_field} > {last_value}").format(
+ query = sql.SQL("SELECT * FROM {schema}.{table} WHERE {incremental_field} {op} {last_value}").format(
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
incremental_field=sql.Identifier(incremental_field),
+ op=operator,
last_value=sql.Literal(db_incremental_field_last_value),
)
@@ -857,10 +871,12 @@ def _build_count_query(
if db_incremental_field_last_value is None:
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
- return sql.SQL("SELECT COUNT(*) FROM {schema}.{table} WHERE {incremental_field} > {last_value}").format(
+ operator = sql.SQL(incremental_type_to_operator(incremental_field_type))
+ return sql.SQL("SELECT COUNT(*) FROM {schema}.{table} WHERE {incremental_field} {op} {last_value}").format(
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
incremental_field=sql.Identifier(incremental_field),
+ op=operator,
last_value=sql.Literal(db_incremental_field_last_value),
)
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 114cefa85ca0..490094f2ee29 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -492,6 +492,55 @@ class TestBuildQuery:
assert '"id"' in rendered
assert "LIMIT 1000" in rendered
+ @pytest.mark.parametrize(
+ "field_type,last_value,expected_operator",
+ [
+ # Date cursors must be inclusive — saving cursor='2026-05-13' and re-querying with
+ # `>` skips every row that lands on 2026-05-13 after the cursor advanced.
+ (IncrementalFieldType.Date, date(2026, 5, 13), ">="),
+ (IncrementalFieldType.DateTime, datetime(2026, 5, 13, 1, 36, tzinfo=UTC), ">"),
+ (IncrementalFieldType.Timestamp, datetime(2026, 5, 13, 1, 36, tzinfo=UTC), ">"),
+ (IncrementalFieldType.Integer, 100, ">"),
+ ],
+ )
+ def test_operator_matches_field_type(self, field_type, last_value, expected_operator):
+ query = _build_query("public", "events", True, "table", "cursor", field_type, last_value)
+ rendered = self._render(query)
+ assert f'"cursor" {expected_operator} ' in rendered
+ # The other operator never appears for the cursor column.
+ wrong = ">" if expected_operator == ">=" else ">="
+ assert f'"cursor" {wrong} ' not in rendered
+
+ @pytest.mark.parametrize(
+ "field_type,last_value,expected_operator",
+ [
+ (IncrementalFieldType.Date, date(2026, 5, 13), ">="),
+ (IncrementalFieldType.DateTime, datetime(2026, 5, 13, 1, 36, tzinfo=UTC), ">"),
+ (IncrementalFieldType.Integer, 100, ">"),
+ ],
+ )
+ def test_count_query_operator_matches_field_type(self, field_type, last_value, expected_operator):
+ query = _build_count_query("public", "events", True, "cursor", field_type, last_value)
+ rendered = self._render(query)
+ assert f'"cursor" {expected_operator} ' in rendered
+
+ def test_windowed_mode_keeps_exclusive_lower_bound_for_date(self):
+ # iterate_date_windows feeds previous_hi as next_lo; `>=` would re-fetch every
+ # boundary date inside one run, so the upper_bound_inclusive path must stay `>`.
+ query = _build_query(
+ "public",
+ "events",
+ True,
+ "table",
+ "cursor",
+ IncrementalFieldType.Date,
+ date(2026, 5, 13),
+ upper_bound_inclusive=date(2026, 5, 14),
+ )
+ rendered = self._render(query)
+ assert '"cursor" > ' in rendered
+ assert '"cursor" >= ' not in rendered
+
class TestBuildPartitionQuery:
def _render(self, composed: sql.Composed) -> str:
@@ -536,6 +585,26 @@ class TestBuildPartitionQuery:
db_incremental_field_last_value=None,
)
+ @pytest.mark.parametrize(
+ "field_type,last_value,expected_operator",
+ [
+ (IncrementalFieldType.Date, date(2026, 5, 13), ">="),
+ (IncrementalFieldType.DateTime, datetime(2026, 5, 13, 1, 36, tzinfo=UTC), ">"),
+ (IncrementalFieldType.Integer, 100, ">"),
+ ],
+ )
+ def test_operator_matches_field_type(self, field_type, last_value, expected_operator):
+ query = build_partition_query(
+ "public",
+ "events_2026_01",
+ should_use_incremental_field=True,
+ incremental_field="cursor",
+ incremental_field_type=field_type,
+ db_incremental_field_last_value=last_value,
+ )
+ rendered = self._render(query)
+ assert f'"cursor" {expected_operator} ' in rendered
+
class TestBuildCountQuery:
def _render(self, composed: sql.Composed) -> str:
diff --git a/posthog/temporal/data_imports/sources/redshift/redshift.py b/posthog/temporal/data_imports/sources/redshift/redshift.py
index 4f62d5712de7..e9a74237994c 100644
--- a/posthog/temporal/data_imports/sources/redshift/redshift.py
+++ b/posthog/temporal/data_imports/sources/redshift/redshift.py
@@ -15,7 +15,10 @@ from structlog.types import FilteringBoundLogger
from posthog.exceptions_capture import capture_exception
from posthog.temporal.data_imports.naming_convention import NamingConvention
-from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
+from posthog.temporal.data_imports.pipelines.helpers import (
+ incremental_type_to_initial_value,
+ incremental_type_to_operator,
+)
from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_CHUNK_SIZE, DEFAULT_TABLE_SIZE_BYTES
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.pipelines.pipeline.utils import (
@@ -203,21 +206,25 @@ def _build_query(
if db_incremental_field_last_value is None:
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
+ operator = sql.SQL(incremental_type_to_operator(incremental_field_type))
+
if add_sampling:
# Redshift doesn't support TABLESAMPLE SYSTEM
query = sql.SQL(
- "SELECT * FROM {schema}.{table} WHERE {incremental_field} > {last_value} AND random() < 0.01"
+ "SELECT * FROM {schema}.{table} WHERE {incremental_field} {op} {last_value} AND random() < 0.01"
).format(
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
incremental_field=sql.Identifier(incremental_field),
+ op=operator,
last_value=sql.Literal(db_incremental_field_last_value),
)
else:
- query = sql.SQL("SELECT * FROM {schema}.{table} WHERE {incremental_field} > {last_value}").format(
+ query = sql.SQL("SELECT * FROM {schema}.{table} WHERE {incremental_field} {op} {last_value}").format(
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
incremental_field=sql.Identifier(incremental_field),
+ op=operator,
last_value=sql.Literal(db_incremental_field_last_value),
)
diff --git a/posthog/temporal/data_imports/sources/snowflake/snowflake.py b/posthog/temporal/data_imports/sources/snowflake/snowflake.py
index 748372f96977..448e4d63ecf3 100644
--- a/posthog/temporal/data_imports/sources/snowflake/snowflake.py
+++ b/posthog/temporal/data_imports/sources/snowflake/snowflake.py
@@ -13,7 +13,10 @@ from structlog.types import FilteringBoundLogger
from posthog.exceptions_capture import capture_exception
from posthog.temporal.data_imports.naming_convention import NamingConvention
-from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value
+from posthog.temporal.data_imports.pipelines.helpers import (
+ incremental_type_to_initial_value,
+ incremental_type_to_operator,
+)
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig
@@ -161,7 +164,8 @@ def _build_query(
if db_incremental_field_last_value is None:
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
- return "SELECT * FROM IDENTIFIER(%s) WHERE IDENTIFIER(%s) > %s ORDER BY IDENTIFIER(%s) ASC", (
+ operator = incremental_type_to_operator(incremental_field_type)
+ return f"SELECT * FROM IDENTIFIER(%s) WHERE IDENTIFIER(%s) {operator} %s ORDER BY IDENTIFIER(%s) ASC", (
f"{database}.{schema}.{table_name}",
incremental_field,
db_incremental_field_last_value,