: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(web-analytics): narrow the session range read by dimensional inserts (#117872)
Lucas Ricoye8511e75e287
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex cba0ec296bd9..76b389c80cf9 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -30411,6 +30411,10 @@"enum": ["auto", "v1", "v2", "v3"],"type": "string"},+ "sessionTimestampBufferMinutes": {+ "$ref": "#/definitions/integer",+ "description": "Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range."+ },"sessionsV2JoinMode": {"enum": ["string", "uuid"],"type": "string"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 843fca339ff4..c507ccc6b2fb 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -525,6 +525,8 @@ export interface HogQLQueryModifiers {optimizeJoinedFilters?: boolean/** Push a `session_id_v7 IN (SELECT … FROM events WHERE …)` predicate into the raw_sessions subquery to limit aggregation to sessions that participate in the outer events filter. */sessionIdPushdown?: boolean+ /** Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range. */+ sessionTimestampBufferMinutes?: integer/** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */sessionPropertyPreAggregation?: boolean/** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */diff --git a/posthog/hogql/database/schema/util/test/test_session_v2_where_clause_extractor.py b/posthog/hogql/database/schema/util/test/test_session_v2_where_clause_extractor.pyindex 1f7c1f73bc06..5f874780636e 100644--- a/posthog/hogql/database/schema/util/test/test_session_v2_where_clause_extractor.py+++ b/posthog/hogql/database/schema/util/test/test_session_v2_where_clause_extractor.py@@ -54,9 +54,13 @@ class TestSessionWhereClauseExtractorV2(ClickhouseTestMixin, APIBaseTest):@propertydef inliner(self):+ return self._inliner()++ def _inliner(self, session_timestamp_buffer_minutes: Optional[int] = None):team = self.teammodifiers = create_default_modifiers_for_team(team)modifiers.sessionTableVersion = SessionTableVersion.V2+ modifiers.sessionTimestampBufferMinutes = session_timestamp_buffer_minutescontext = HogQLContext(team_id=team.pk,team=team,@@ -124,10 +128,22 @@ class TestSessionWhereClauseExtractorV2(ClickhouseTestMixin, APIBaseTest):actual = self.inliner.get_inner_where(parse("SELECT event, count() FROM sessions GROUP BY event LIMIT 10"))assert actual is None- def test_handles_select_with_eq(self):- actual = f(self.inliner.get_inner_where(parse("SELECT * FROM sessions WHERE $start_timestamp = '2021-01-01'")))+ @parameterized.expand(+ [+ ("default_buffer", None, "toIntervalDay(3)"),+ ("modifier_buffer", 60, "toIntervalMinute(60)"),+ ("modifier_cannot_widen", 10_000_000, "toIntervalDay(3)"),+ ("negative_modifier_clamped", -60, "toIntervalMinute(0)"),+ ]+ )+ def test_handles_select_with_eq(self, _name, buffer_minutes, interval):+ actual = f(+ self._inliner(buffer_minutes).get_inner_where(+ parse("SELECT * FROM sessions WHERE $start_timestamp = '2021-01-01'")+ )+ )expected = f(- "fromUnixTimestamp(intDiv(_toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)) >= ('2021-01-01' - toIntervalDay(3)) AND fromUnixTimestamp(intDiv(_toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)) <= ('2021-01-01' + toIntervalDay(3))"+ f"fromUnixTimestamp(intDiv(_toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)) >= ('2021-01-01' - {interval}) AND fromUnixTimestamp(intDiv(_toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)) <= ('2021-01-01' + {interval})")assert expected == actualdiff --git a/posthog/hogql/database/schema/util/where_clause_extractor.py b/posthog/hogql/database/schema/util/where_clause_extractor.pyindex 4c53284270e3..510e048815b1 100644--- a/posthog/hogql/database/schema/util/where_clause_extractor.py+++ b/posthog/hogql/database/schema/util/where_clause_extractor.py@@ -282,6 +282,11 @@ class SessionMinTimestampWhereClauseExtractor(WhereClauseExtractor):def __init__(self, context: HogQLContext):super().__init__(context)+ buffer_minutes = context.modifiers.sessionTimestampBufferMinutes if context.modifiers else None+ # Any client can set this modifier, so it may only narrow the default buffer. A wider buffer+ # would let one query scan the whole sessions table.+ if buffer_minutes is not None and buffer_minutes < SESSION_BUFFER_DAYS * 24 * 60:+ self.time_buffer = ast.Call(name="toIntervalMinute", args=[ast.Constant(value=max(buffer_minutes, 0))])def should_apply_default_limit_bound(self, select_query: ast.SelectQuery) -> bool:if (diff --git a/posthog/schema.py b/posthog/schema.pyindex 4f003ab1830a..b7fa79d969ad 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -6325,6 +6325,16 @@ class HogQLQueryModifiers(BaseModel):),)sessionTableVersion: SessionTableVersion | None = None+ sessionTimestampBufferMinutes: int | None = Field(+ default=None,+ description=(+ "Padding, in minutes, on each side of the event time range when it filters"+ " the sessions table by session start. Defaults to 3 days. It can only"+ " narrow the range: values above the default are ignored. Lower it only for"+ " a query that keeps just the sessions that start inside its own time"+ " range."+ ),+ )sessionsV2JoinMode: SessionsV2JoinMode | None = Nonetimings: bool | None = NonetypeAwareCastSimplification: bool | None = Field(diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex 119da89c0f7b..79e4bb218361 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -854,6 +854,8 @@ export interface HogQLQueryModifiersApi {/** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */sessionPropertyPreAggregation?: boolean | nullsessionTableVersion?: SessionTableVersionApi | null+ /** Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range. */+ sessionTimestampBufferMinutes?: number | nullsessionsV2JoinMode?: SessionsV2JoinModeApi | nulltimings?: boolean | null/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.tsindex 0a5482befcab..1274aaf05c6d 100644--- a/products/batch_exports/frontend/generated/api.zod.ts+++ b/products/batch_exports/frontend/generated/api.zod.ts@@ -654,6 +654,12 @@ export const BatchExportsCreateBody = /* @__PURE__ */ zod'Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zod@@ -1617,6 +1623,12 @@ export const BatchExportsUpdateBody = /* @__PURE__ */ zod'Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zod@@ -2339,6 +2351,12 @@ export const BatchExportsPartialUpdateBody = /* @__PURE__ */ zod'Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zod@@ -3046,6 +3064,12 @@ export const BatchExportsRunTestStepCreateBody = /* @__PURE__ */ zod'Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zod@@ -3772,6 +3796,12 @@ export const BatchExportsRunTestStepNewCreateBody = /* @__PURE__ */ zod'Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zod@@ -4215,6 +4245,12 @@ export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union(['Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zod@@ -4479,6 +4515,12 @@ export const FileDownloadBatchExportsCountRowsCreateBody = /* @__PURE__ */ zod'Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zoddiff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 6bd5a71cc443..f9494ce4a055 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1784,6 +1784,8 @@ export interface HogQLQueryModifiersApi {/** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */sessionPropertyPreAggregation?: boolean | nullsessionTableVersion?: SessionTableVersionApi | null+ /** Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range. */+ sessionTimestampBufferMinutes?: number | nullsessionsV2JoinMode?: SessionsV2JoinModeApi | nulltimings?: boolean | null/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 08253d2ae65d..f572a556c931 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -1804,6 +1804,8 @@ export interface HogQLQueryModifiersApi {/** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */sessionPropertyPreAggregation?: boolean | nullsessionTableVersion?: SessionTableVersionApi | null+ /** Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range. */+ sessionTimestampBufferMinutes?: number | nullsessionsV2JoinMode?: SessionsV2JoinModeApi | nulltimings?: boolean | null/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex d21c4c432f22..4c833575fa87 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -224,6 +224,7 @@ export namespace Schemas {sessionIdPushdown: boolean | null;sessionPropertyPreAggregation: boolean | null;sessionTableVersion: SessionTableVersion | null;+ sessionTimestampBufferMinutes: number | null;sessionsV2JoinMode: SessionsV2JoinMode | null;timings: boolean | null;typeAwareCastSimplification: boolean | null;diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.tsindex 8e9311e5ec6d..2e8086faec66 100644--- a/products/marketing_analytics/frontend/generated/api.schemas.ts+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts@@ -1641,6 +1641,8 @@ export interface HogQLQueryModifiersApi {/** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */sessionPropertyPreAggregation?: boolean | nullsessionTableVersion?: SessionTableVersionApi | null+ /** Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range. */+ sessionTimestampBufferMinutes?: number | nullsessionsV2JoinMode?: SessionsV2JoinModeApi | nulltimings?: boolean | null/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 4ad3fa270222..4f2a5375de6d 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -668,6 +668,8 @@ export interface HogQLQueryModifiersApi {/** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */sessionPropertyPreAggregation?: boolean | nullsessionTableVersion?: SessionTableVersionApi | null+ /** Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range. */+ sessionTimestampBufferMinutes?: number | nullsessionsV2JoinMode?: SessionsV2JoinModeApi | nulltimings?: boolean | null/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.py b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.pyindex 7a7fa423a4f5..cd7fb13b7adc 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.py@@ -67,7 +67,10 @@ class TestWebDimensionalPrecomputeParity(WebAnalyticsPreAggregatedTestBase):)def _setup_test_data(self):- sa, sb, sc = (str(uuid7(DATE_START)) for _ in range(3))+ sa, sb = (str(uuid7(DATE_START)) for _ in range(2))+ # user_c's device clock runs two hours slow: capture corrects the event timestamp, but the+ # session id keeps the device time, which falls on the previous day.+ sc = str(uuid7("2023-12-31T22:30:00+00:00"))with time_machine.travel("2024-01-01T09:00:00Z", tick=False):# Create persons so events resolve to a stable person_id per distinct_id# (without this, _create_event assigns a fresh random person_id per row).@@ -109,7 +112,7 @@ class TestWebDimensionalPrecomputeParity(WebAnalyticsPreAggregatedTestBase):self._pageview("user_c",sc,- "2024-01-01T12:00:00Z",+ "2024-01-01T00:30:00Z",**{"$host": "blog.example.com","$device_type": "Desktop",diff --git a/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.pyindex a4dbabc05941..c02f324dcc83 100644--- a/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py@@ -24,7 +24,10 @@ Parity with v2 is intentional, with two deliberate deviations:from datetime import datetime+from posthog.schema import HogQLQueryModifiers+from posthog.hogql import ast+from posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_exprfrom posthog.models.team import Team@@ -310,8 +313,24 @@ DIMENSIONAL_INSERT_SETTINGS: dict[str, int | str] = {"max_bytes_before_external_group_by": 70 * 1024**3,"distributed_aggregation_memory_efficient": 1,"max_execution_time": 2200,+ # Spread the sessions-table reads over every replica, like the legacy job. `in_order` sends every+ # one of these heavy reads to the first replica.+ "load_balancing": "random",}+# HogQL filters the sessions table by the time in the session id, which comes from the device+# clock, while event timestamps are corrected at capture. A device clock that runs slow gives a+# session id earlier than the session's real start, so the buffer is the clock skew we tolerate.+# 25 hours matches the legacy pre-aggregation job and avoids the default 3 days on each side,+# which makes these inserts read about twice as many sessions.+DIMENSIONAL_SESSION_BUFFER_MINUTES = 25 * 60+++def _insert_modifiers(team: Team) -> HogQLQueryModifiers:+ return create_default_modifiers_for_team(+ team, HogQLQueryModifiers(sessionTimestampBufferMinutes=DIMENSIONAL_SESSION_BUFFER_MINUTES)+ )+def ensure_web_stats_dimensional_precomputed(team: Team,@@ -329,6 +348,7 @@ def ensure_web_stats_dimensional_precomputed(query_type="web_stats_dimensional_insert",read_after_write=False,insert_settings=DIMENSIONAL_INSERT_SETTINGS,+ modifiers=_insert_modifiers(team),)@@ -348,4 +368,5 @@ def ensure_web_bounces_dimensional_precomputed(query_type="web_bounces_dimensional_insert",read_after_write=False,insert_settings=DIMENSIONAL_INSERT_SETTINGS,+ modifiers=_insert_modifiers(team),)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5747fca17d3d..edcac3c08523 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2684,6 +2684,8 @@ export namespace Schemas {/** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */sessionPropertyPreAggregation?: boolean | null;sessionTableVersion?: SessionTableVersion | null;+ /** Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range. */+ sessionTimestampBufferMinutes?: number | null;sessionsV2JoinMode?: SessionsV2JoinMode | null;timings?: boolean | null;/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */diff --git a/services/mcp/src/generated/batch_exports/api.ts b/services/mcp/src/generated/batch_exports/api.tsindex 45525ea9de04..5993dfee36db 100644--- a/services/mcp/src/generated/batch_exports/api.ts+++ b/services/mcp/src/generated/batch_exports/api.ts@@ -666,6 +666,12 @@ export const BatchExportsCreateBody = () => zod'Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zod@@ -1392,6 +1398,12 @@ export const BatchExportsPartialUpdateBody = () => zod'Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zod@@ -1849,6 +1861,12 @@ export const FileDownloadBatchExportsCreateBody = () => zod.union(['Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zod@@ -2149,6 +2167,12 @@ export const FileDownloadBatchExportsCountRowsCreateBody = () => zod'Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown\/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`).'),sessionTableVersion: zod.union([zod.enum(['auto', 'v1', 'v2', 'v3']), zod.null()]).optional(),+ sessionTimestampBufferMinutes: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range.'+ ),sessionsV2JoinMode: zod.union([zod.enum(['string', 'uuid']), zod.null()]).optional(),timings: zod.union([zod.boolean(), zod.null()]).optional(),typeAwareCastSimplification: zoddiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.jsonindex f563bad29615..700b3f33f961 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json@@ -1034,6 +1034,17 @@}]},+ "sessionTimestampBufferMinutes": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range."+ },"timings": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.jsonindex 398b7864e56a..58e7429d417c 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json@@ -1033,6 +1033,17 @@}]},+ "sessionTimestampBufferMinutes": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range."+ },"timings": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.jsonindex 59565947db9a..778b5c021315 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json@@ -509,6 +509,17 @@}]},+ "sessionTimestampBufferMinutes": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range."+ },"timings": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.jsonindex 848e81446813..eb97d37b5660 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json@@ -738,6 +738,17 @@}]},+ "sessionTimestampBufferMinutes": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range."+ },"timings": {"anyOf": [{