: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
fix(sessions): Use max_inserted_at for Sessions model (#78919)
Tomás Farías Santana9de6e86a45ff
diff --git a/products/batch_exports/backend/temporal/backfill_batch_export.py b/products/batch_exports/backend/temporal/backfill_batch_export.pyindex 26640fd5b8f6..203689fd8eb6 100644--- a/products/batch_exports/backend/temporal/backfill_batch_export.py+++ b/products/batch_exports/backend/temporal/backfill_batch_export.py@@ -451,8 +451,9 @@ async def _get_backfill_info_for_sessions() -> tuple[dt.datetime | None, int | None]:"""Get earliest timestamp and estimated record count for sessions model.- Queries the sessions table via HogQL, filtering by $end_timestamp- (this logic is the same as the actual export query, which aliases `$end_timestamp` as `_inserted_at`).+ Queries the sessions table via HogQL, filtering by $end_timestamp. This matches+ the event-time semantics of backfill export queries (see+ `SessionsRecordBatchModel.get_hogql_query` with `is_backfill=True`).Returns:A tuple of (min_timestamp, estimated_records_count).diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex 5b9e92fd3d55..693481582e2c 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -263,7 +263,11 @@ async def insert_into_internal_stage_activity(set_status_to_running_task(run_id=inputs.run_id),):_, record_batch_model, model_name, fields, filters, extra_query_parameters = resolve_batch_exports_model(- inputs.team_id, inputs.batch_export_model, inputs.batch_export_schema, inputs.batch_export_id+ inputs.team_id,+ inputs.batch_export_model,+ inputs.batch_export_schema,+ inputs.batch_export_id,+ is_backfill=inputs.backfill_details is not None,)data_interval_start = (dt.datetime.fromisoformat(inputs.data_interval_start) if inputs.data_interval_start else Nonediff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.pyindex bff5c56d61a1..2739df9edeac 100644--- a/products/batch_exports/backend/temporal/record_batch_model.py+++ b/products/batch_exports/backend/temporal/record_batch_model.py@@ -26,7 +26,7 @@ from products.batch_exports.backend.hogql_source import (from products.batch_exports.backend.service import BatchExportModel, BatchExportSchemafrom products.batch_exports.backend.temporal.metrics import log_query_durationfrom products.batch_exports.backend.temporal.sql.common import HogQLQueryBatchExportSettings, get_s3_function_call-from products.batch_exports.backend.temporal.sql.sessions import SELECT_FROM_SESSIONS_HOGQL+from products.batch_exports.backend.temporal.sql.sessions import SELECT_FROM_SESSIONS_HOGQL, SESSIONS_LOOKBACK_DAYSLOGGER = get_write_only_logger()@@ -149,7 +149,18 @@ INSERT INTO FUNCTION {s3_function}class SessionsRecordBatchModel(RecordBatchModel):- """A model to produce record batches from the sessions table."""+ """A model to produce record batches from the sessions table.++ Attributes:+ is_backfill: Whether this model serves a backfill run. Incremental runs select+ sessions using `_inserted_at` (when the session's events were ingested), so+ sessions receiving late events are re-exported so that they can be updated.+ Backfill runs select instead by `$end_timestamp`.+ """++ def __init__(self, team_id: int, batch_export_id: str | None = None, is_backfill: bool = False):+ super().__init__(team_id=team_id, batch_export_id=batch_export_id)+ self.is_backfill = is_backfilldef get_hogql_query(self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime@@ -157,42 +168,66 @@ class SessionsRecordBatchModel(RecordBatchModel):"""Return the HogQLQuery used for the sessions model."""hogql_query = clone_expr(SELECT_FROM_SESSIONS_HOGQL)- where_and = ast.And(- exprs=[- ast.CompareOperation(- op=ast.CompareOperationOp.Eq,- left=ast.Field(chain=["sessions", "team_id"]),- right=ast.Constant(value=self.team_id),- ),- ast.CompareOperation(- op=ast.CompareOperationOp.Lt,- left=ast.Field(chain=["_inserted_at"]),- right=ast.Constant(value=data_interval_end),- ),- # include $end_timestamp because hogql uses this to add a where clause to the inner query- ast.CompareOperation(- op=ast.CompareOperationOp.Lt,- left=ast.Field(chain=["$end_timestamp"]),- right=ast.Constant(value=data_interval_end),- ),- ]+ team_id_filter = ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["sessions", "team_id"]),+ right=ast.Constant(value=self.team_id),)- if data_interval_start is not None:- where_and.exprs.extend(- [++ if self.is_backfill:+ where_and = ast.And(+ exprs=[+ team_id_filter,+ ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=ast.Field(chain=["$end_timestamp"]),+ right=ast.Constant(value=data_interval_end),+ ),+ ]+ )+ if data_interval_start is not None:+ where_and.exprs.append(ast.CompareOperation(op=ast.CompareOperationOp.GtEq,- left=ast.Field(chain=["_inserted_at"]),+ left=ast.Field(chain=["$end_timestamp"]),right=ast.Constant(value=data_interval_start),),+ )+ else:+ where_and = ast.And(+ exprs=[+ team_id_filter,+ ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=ast.Field(chain=["_inserted_at"]),+ right=ast.Constant(value=data_interval_end),+ ),# include $end_timestamp because hogql uses this to add a where clause to the inner queryast.CompareOperation(- op=ast.CompareOperationOp.GtEq,+ op=ast.CompareOperationOp.Lt,left=ast.Field(chain=["$end_timestamp"]),- right=ast.Constant(value=data_interval_start),+ right=ast.Constant(value=data_interval_end),),])+ if data_interval_start is not None:+ where_and.exprs.extend(+ [+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["_inserted_at"]),+ right=ast.Constant(value=data_interval_start),+ ),+ # Sessions whose events are ingested more than SESSIONS_LOOKBACK_DAYS+ # after the session ended are not picked up by incremental runs. This+ # is a trade-off to avoid a full table scan.+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["$end_timestamp"]),+ right=ast.Constant(value=data_interval_start - SESSIONS_LOOKBACK_DAYS),+ ),+ ]+ )hogql_query.where = where_and@@ -218,6 +253,7 @@ class SessionsRecordBatchModel(RecordBatchModel):])+ # The estimate mirrors backfill runs, which $end_timestamp semantics.if end_at is not None:where_and.exprs.append(ast.CompareOperation(@@ -348,6 +384,7 @@ def resolve_batch_exports_model(batch_export_model: BatchExportModel | None = None,batch_export_schema: BatchExportSchema | None = None,batch_export_id: str | None = None,+ is_backfill: bool = False,):"""Resolve which model and model parameters to use for a batch export.@@ -366,7 +403,9 @@ def resolve_batch_exports_model(filters = model.filtersif model_name == "sessions":- record_batch_model = SessionsRecordBatchModel(team_id=team_id, batch_export_id=batch_export_id)+ record_batch_model = SessionsRecordBatchModel(+ team_id=team_id, batch_export_id=batch_export_id, is_backfill=is_backfill+ )elif model_name == "hogql":if model.hogql_query is None:raise UnsupportedHogQLQueryError("Batch export model is 'hogql' but no HogQL query was provided")diff --git a/products/batch_exports/backend/temporal/sql/sessions.py b/products/batch_exports/backend/temporal/sql/sessions.pyindex 81f3e4e275dd..51a6e9ead8d1 100644--- a/products/batch_exports/backend/temporal/sql/sessions.py+++ b/products/batch_exports/backend/temporal/sql/sessions.py@@ -1,10 +1,24 @@"""SQL for the sessions batch export model."""+import datetime as dt+from posthog.hogql import astfrom posthog.hogql.parser import parse_exprfrom products.batch_exports.backend.temporal.sql.common import HogQLQueryBatchExportSettings+# max_inserted_at is only available since around end of 2025. Before+# that, it is the zero value (unix epoch). We use greatest to pick+# $end_timestamp for backfills from before max_inserted_at was available.+SESSIONS_INSERTED_AT_SQL = "greatest(max_inserted_at, $end_timestamp)"++# Lookback days based on the timestamp field of the events that make up a session.+# Sessions is an aggregate table which is not sorted by inserted_at. So, we need+# a filter on $end_timestamp to avoid a full scan of the table. Backfills use+# $end_timestamp rather than max_inserted_at, so this lookback period only applies+# to regular runs. While testing, 3 days catched almost all sessions.+SESSIONS_LOOKBACK_DAYS = dt.timedelta(days=3)+SELECT_FROM_SESSIONS_HOGQL = ast.SelectQuery(select=[parse_expr("session_id as session_id"),@@ -42,7 +56,8 @@ SELECT_FROM_SESSIONS_HOGQL = ast.SelectQuery(parse_expr("$exit_current_url as exit_current_url"),parse_expr("$exit_pathname as exit_pathname"),parse_expr("$vitals_lcp as vitals_lcp"),- parse_expr("$end_timestamp as _inserted_at"),+ # nosemgrep: semgrep.rules.security.hogql-fstring-audit+ parse_expr(f"{SESSIONS_INSERTED_AT_SQL} as _inserted_at"),parse_expr("$entry_gclsrc as entry_gclsrc"),parse_expr("$entry_dclid as entry_dclid"),parse_expr("$entry_gbraid as entry_gbraid"),diff --git a/products/batch_exports/backend/tests/temporal/backfills/test_get_backfill_info.py b/products/batch_exports/backend/tests/temporal/backfills/test_get_backfill_info.pyindex 7b6e30a3017b..faf43ff2bd0d 100644--- a/products/batch_exports/backend/tests/temporal/backfills/test_get_backfill_info.py+++ b/products/batch_exports/backend/tests/temporal/backfills/test_get_backfill_info.py@@ -725,10 +725,12 @@ class TestGetBackfillInfoForSessions:end_time: dt.datetime | None = None,count: int = 10,count_other_team: int = 0,+ inserted_at: dt.datetime | None = None,):"""Generate events with unique session IDs and derive sessions from them.Each event gets a unique $session_id, so the number of sessions equals count.+ Events are ingested at their event time unless `inserted_at` says otherwise."""for i in range(count):event_time = start_time + dt.timedelta(seconds=i)@@ -739,7 +741,7 @@ class TestGetBackfillInfoForSessions:start_time=event_time,end_time=(end_time or event_time + dt.timedelta(minutes=2)),count=1,- inserted_at=event_time,+ inserted_at=inserted_at or event_time,table="sharded_events",event_name="test-event",count_outside_range=0,@@ -816,6 +818,32 @@ class TestGetBackfillInfoForSessions:assert result.adjusted_start_at == dt.datetime(2021, 1, 20, 0, 0, 0, tzinfo=dt.UTC).isoformat()assert result.total_records_count == 8+ async def test_counts_late_ingested_sessions_by_event_time(+ self, generate_sessions, create_batch_export, run_get_backfill_info+ ):+ """The estimate must mirror backfill runs, which select sessions by event time: a+ session whose events were ingested late counts towards the backfill range covering+ its $end_timestamp, not the one covering its ingestion time."""+ event_time = dt.datetime(2021, 1, 10, 12, 0, 0, tzinfo=dt.UTC)+ ingested_time = dt.datetime(2021, 1, 20, 6, 30, 0, tzinfo=dt.UTC)+ await generate_sessions(start_time=event_time, count=3, inserted_at=ingested_time)++ batch_export = await create_batch_export()+ result_event_range = await run_get_backfill_info(+ batch_export,+ start_at=dt.datetime(2021, 1, 10, 0, 0, 0, tzinfo=dt.UTC),+ end_at=dt.datetime(2021, 1, 11, 0, 0, 0, tzinfo=dt.UTC),+ )+ result_ingestion_range = await run_get_backfill_info(+ batch_export,+ start_at=dt.datetime(2021, 1, 20, 0, 0, 0, tzinfo=dt.UTC),+ end_at=dt.datetime(2021, 1, 21, 0, 0, 0, tzinfo=dt.UTC),+ )++ assert result_event_range.adjusted_start_at == dt.datetime(2021, 1, 10, 12, 0, 0, tzinfo=dt.UTC).isoformat()+ assert result_event_range.total_records_count == 3+ assert result_ingestion_range.total_records_count == 0+async def test_counts_only_sessions_before_end_at(self, generate_sessions, create_batch_export, run_get_backfill_info):diff --git a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py b/products/batch_exports/backend/tests/temporal/test_record_batch_model.pyindex 71a9da6d98db..f51dc11fc6ff 100644--- a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py+++ b/products/batch_exports/backend/tests/temporal/test_record_batch_model.py@@ -1,10 +1,14 @@+import datetime as dt+import pytestfrom posthog.hogql.hogql import astfrom posthog.hogql.printer import prepare_ast_for_printing, print_prepared_astfrom posthog.credentials import AWSKeyPair+from posthog.models.utils import uuid7from posthog.sync import database_sync_to_async+from posthog.temporal.tests.utils.events import generate_test_events_in_clickhousefrom products.batch_exports.backend.hogql_source import UnsupportedHogQLQueryErrorfrom products.batch_exports.backend.service import BatchExportModel@@ -13,6 +17,8 @@ from products.batch_exports.backend.temporal.record_batch_model import (SessionsRecordBatchModel,resolve_batch_exports_model,)+from products.batch_exports.backend.temporal.sql.sessions import SESSIONS_LOOKBACK_DAYS+from products.batch_exports.backend.tests.temporal.utils.clickhouse import truncate_events, truncate_sessionspytestmark = [pytest.mark.asyncio, pytest.mark.django_db]@@ -28,10 +34,48 @@ class TestSessionsRecordBatchModel:left=ast.Field(chain=["sessions", "team_id"]),right=ast.Constant(value=ateam.id),)+ # the $end_timestamp lower bound is what lets hogql prune raw_sessions partitions,+ # shifted back to still catch sessions ingested up to SESSIONS_MAX_LATENESS late+ lateness_filter = ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["$end_timestamp"]),+ right=ast.Constant(value=data_interval_start - SESSIONS_LOOKBACK_DAYS),+ )assert hogql_query.where is not Noneassert isinstance(hogql_query.where, ast.And)assert team_id_filter in hogql_query.where.exprs+ assert lateness_filter in hogql_query.where.exprs++ async def test_get_hogql_query_for_backfill(self, ateam, data_interval_start, data_interval_end):+ """Backfill runs select sessions by event time ($end_timestamp), not by the+ _inserted_at watermark, so sessions ingested beyond SESSIONS_MAX_LATENESS can+ still be exported by backfilling their $end_timestamp range."""+ model = SessionsRecordBatchModel(team_id=ateam.id, is_backfill=True)+ hogql_query = model.get_hogql_query(data_interval_start, data_interval_end)++ lower_bound = ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["$end_timestamp"]),+ right=ast.Constant(value=data_interval_start),+ )+ upper_bound = ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=ast.Field(chain=["$end_timestamp"]),+ right=ast.Constant(value=data_interval_end),+ )++ assert hogql_query.where is not None+ assert isinstance(hogql_query.where, ast.And)+ assert lower_bound in hogql_query.where.exprs+ assert upper_bound in hogql_query.where.exprs+ # no _inserted_at bounds: backfill selection is purely by event time+ assert not any(+ isinstance(expr, ast.CompareOperation)+ and isinstance(expr.left, ast.Field)+ and expr.left.chain == ["_inserted_at"]+ for expr in hogql_query.where.exprs+ )async def test_as_query_with_parameters(self, ateam, data_interval_start, data_interval_end):model = SessionsRecordBatchModel(@@ -46,6 +90,11 @@ class TestSessionsRecordBatchModel:in printed_query)assert f"less(_inserted_at, toDateTime64('{data_interval_end:%Y-%m-%d %H:%M:%S.%f}', 6, 'UTC')" in printed_query+ # the $end_timestamp lower bound is shifted back by lookback days+ assert (+ f"toDateTime64('{data_interval_start - SESSIONS_LOOKBACK_DAYS:%Y-%m-%d %H:%M:%S.%f}', 6, 'UTC')"+ in printed_query+ )# check that we have a date range set on the inner query using the session IDassert (@@ -118,6 +167,11 @@ class TestSessionsRecordBatchModel:in printed_query)assert f"less(_inserted_at, toDateTime64('{data_interval_end:%Y-%m-%d %H:%M:%S.%f}', 6, 'UTC')" in printed_query+ # the $end_timestamp lower bound is shifted back by the lateness horizon+ assert (+ f"toDateTime64('{data_interval_start - SESSIONS_LOOKBACK_DAYS:%Y-%m-%d %H:%M:%S.%f}', 6, 'UTC')"+ in printed_query+ )# check that we have a date range set on the inner query using the session IDassert (@@ -159,6 +213,119 @@ class TestSessionsRecordBatchModel:assert "PARTITION BY rand() %% 5" in printed_query+class TestSessionsRecordBatchModelSelection:+ """Run the sessions model query against ClickHouse to verify which intervals select a session."""++ @pytest.fixture(autouse=True)+ async def truncate_tables(self, clickhouse_client):+ await truncate_events(clickhouse_client)+ await truncate_sessions(clickhouse_client)++ async def _generate_session(+ self,+ clickhouse_client,+ team_id: int,+ event_time: dt.datetime,+ inserted_at: dt.datetime,+ ) -> str:+ session_id = str(uuid7(unix_ms_time=int(event_time.timestamp() * 1000)))+ await generate_test_events_in_clickhouse(+ client=clickhouse_client,+ team_id=team_id,+ start_time=event_time,+ end_time=event_time + dt.timedelta(minutes=2),+ count=1,+ count_outside_range=0,+ count_other_team=0,+ inserted_at=inserted_at,+ table="sharded_events",+ event_name="test-event",+ properties={"$session_id": session_id},+ insert_sessions=True,+ )+ return session_id++ async def _select_session_ids(+ self,+ clickhouse_client,+ model: SessionsRecordBatchModel,+ interval_start: dt.datetime,+ interval_end: dt.datetime,+ ) -> list[str]:+ printed_query, parameters = await model._print_query(interval_start, interval_end, output_format="JSONEachRow")+ rows = await clickhouse_client.read_query_as_jsonl(printed_query, query_parameters=parameters)+ return [row["session_id"] for row in rows]++ async def test_selects_late_session_by_interval_covering_its_ingestion(self, clickhouse_client, ateam):+ """A session whose events are ingested late (within SESSIONS_LOOKBACK_DAYS) is selected+ by the interval covering its ingestion time, not the one covering its event timestamps."""+ event_time = dt.datetime(2021, 1, 18, 12, 0, 0, tzinfo=dt.UTC)+ ingested_at = dt.datetime(2021, 1, 20, 6, 30, 0, tzinfo=dt.UTC)+ session_id = await self._generate_session(clickhouse_client, ateam.pk, event_time, ingested_at)+ model = SessionsRecordBatchModel(team_id=ateam.pk)++ selected_by_event_interval = await self._select_session_ids(+ clickhouse_client,+ model,+ dt.datetime(2021, 1, 18, 12, 0, 0, tzinfo=dt.UTC),+ dt.datetime(2021, 1, 18, 13, 0, 0, tzinfo=dt.UTC),+ )+ selected_by_ingestion_interval = await self._select_session_ids(+ clickhouse_client,+ model,+ dt.datetime(2021, 1, 20, 6, 0, 0, tzinfo=dt.UTC),+ dt.datetime(2021, 1, 20, 7, 0, 0, tzinfo=dt.UTC),+ )++ assert selected_by_event_interval == []+ assert selected_by_ingestion_interval == [session_id]++ async def test_session_ingested_beyond_lateness_horizon_requires_backfill(self, clickhouse_client, ateam):+ """A session ingested more than SESSIONS_LOOKBACK_DAYS after it ended is skipped by+ incremental runs (the prunable $end_timestamp bound excludes it), but a backfill of+ its event-time range picks it up."""+ event_time = dt.datetime(2021, 1, 10, 12, 0, 0, tzinfo=dt.UTC)+ ingested_at = dt.datetime(2021, 1, 20, 6, 30, 0, tzinfo=dt.UTC)+ session_id = await self._generate_session(clickhouse_client, ateam.pk, event_time, ingested_at)++ incremental_model = SessionsRecordBatchModel(team_id=ateam.pk)+ selected_by_ingestion_interval = await self._select_session_ids(+ clickhouse_client,+ incremental_model,+ dt.datetime(2021, 1, 20, 6, 0, 0, tzinfo=dt.UTC),+ dt.datetime(2021, 1, 20, 7, 0, 0, tzinfo=dt.UTC),+ )++ backfill_model = SessionsRecordBatchModel(team_id=ateam.pk, is_backfill=True)+ selected_by_backfill_of_event_range = await self._select_session_ids(+ clickhouse_client,+ backfill_model,+ dt.datetime(2021, 1, 10, 0, 0, 0, tzinfo=dt.UTC),+ dt.datetime(2021, 1, 11, 0, 0, 0, tzinfo=dt.UTC),+ )++ assert selected_by_ingestion_interval == []+ assert selected_by_backfill_of_event_range == [session_id]++ async def test_sessions_without_max_inserted_at_fall_back_to_end_timestamp(self, clickhouse_client, ateam):+ """Sessions from before raw_sessions had max_inserted_at carry the epoch value; the+ watermark falls back to $end_timestamp, so they are still selected by their event-time+ interval."""+ event_time = dt.datetime(2021, 1, 15, 10, 30, 0, tzinfo=dt.UTC)+ epoch = dt.datetime(1970, 1, 1, 0, 0, 0, tzinfo=dt.UTC)+ session_id = await self._generate_session(clickhouse_client, ateam.pk, event_time, epoch)+ model = SessionsRecordBatchModel(team_id=ateam.pk)++ selected = await self._select_session_ids(+ clickhouse_client,+ model,+ dt.datetime(2021, 1, 15, 10, 0, 0, tzinfo=dt.UTC),+ dt.datetime(2021, 1, 15, 11, 0, 0, tzinfo=dt.UTC),+ )++ assert selected == [session_id]++class TestHogQLQueryRecordBatchModel:async def test_as_query_with_parameters(self, ateam, data_interval_start, data_interval_end):model = HogQLQueryRecordBatchModel(