: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
refactor(batch-exports): split temporal/sql.py into per-model modules (#75928)
Ross0753cfbfa99d
diff --git a/products/batch_exports/backend/debug/debugger.py b/products/batch_exports/backend/debug/debugger.pyindex 634fd0304760..69fc0c5900ea 100644--- a/products/batch_exports/backend/debug/debugger.py+++ b/products/batch_exports/backend/debug/debugger.py@@ -45,15 +45,14 @@ from products.batch_exports.backend.temporal.spmc import (compose_filters_clause,use_distributed_events_recent_table,)-from products.batch_exports.backend.temporal.sql import (+from products.batch_exports.backend.temporal.sql.events import (SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,SELECT_FROM_EVENTS_VIEW,SELECT_FROM_EVENTS_VIEW_BACKFILL,SELECT_FROM_EVENTS_VIEW_RECENT,SELECT_FROM_EVENTS_VIEW_UNBOUNDED,- SELECT_FROM_PERSONS,- SELECT_FROM_PERSONS_BACKFILL,)+from products.batch_exports.backend.temporal.sql.persons import SELECT_FROM_PERSONS, SELECT_FROM_PERSONS_BACKFILLconsole = Console()diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.pyindex 1ab633e0699b..c1b3b8efa736 100644--- a/products/batch_exports/backend/temporal/batch_exports.py+++ b/products/batch_exports/backend/temporal/batch_exports.py@@ -40,7 +40,7 @@ from products.batch_exports.backend.service import (from products.batch_exports.backend.temporal.metrics import get_export_finished_metric, get_export_started_metricfrom products.batch_exports.backend.temporal.pipeline.types import BatchExportResultfrom products.batch_exports.backend.temporal.spmc import use_distributed_events_recent_table-from products.batch_exports.backend.temporal.sql import (+from products.batch_exports.backend.temporal.sql.events import (SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,SELECT_FROM_EVENTS_VIEW,SELECT_FROM_EVENTS_VIEW_BACKFILL,diff --git a/products/batch_exports/backend/temporal/monitoring.py b/products/batch_exports/backend/temporal/monitoring.pyindex c5da8ffbc021..e38d28080c2f 100644--- a/products/batch_exports/backend/temporal/monitoring.py+++ b/products/batch_exports/backend/temporal/monitoring.py@@ -14,7 +14,7 @@ from posthog.temporal.common.logger import get_loggerfrom products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRunfrom products.batch_exports.backend.service import afetch_batch_export_runs_in_range, aupdate_records_total_count-from products.batch_exports.backend.temporal.sql import EVENT_COUNT_BY_INTERVAL+from products.batch_exports.backend.temporal.sql.events import EVENT_COUNT_BY_INTERVALLOGGER = get_logger(__name__)diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex 3aecd27edb5c..10acd10b1a7e 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -58,16 +58,18 @@ from products.batch_exports.backend.temporal.spmc import (use_distributed_events_recent_table,wait_for_delta_past_data_interval_end,)-from products.batch_exports.backend.temporal.sql import (+from products.batch_exports.backend.temporal.sql.common import get_s3_function_call+from products.batch_exports.backend.temporal.sql.events import (EXPORT_TO_S3_FROM_DISTRIBUTED_EVENTS_RECENT,EXPORT_TO_S3_FROM_EVENTS,EXPORT_TO_S3_FROM_EVENTS_BACKFILL,EXPORT_TO_S3_FROM_EVENTS_RECENT,EXPORT_TO_S3_FROM_EVENTS_UNBOUNDED,EXPORT_TO_S3_FROM_EVENTS_WORKFLOWS,+)+from products.batch_exports.backend.temporal.sql.persons import (EXPORT_TO_S3_FROM_PERSONS,EXPORT_TO_S3_FROM_PERSONS_BACKFILL,- get_s3_function_call,)from products.batch_exports.backend.temporal.utils import set_status_to_running_taskdiff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.pyindex 8e02350eeb52..bff5c56d61a1 100644--- a/products/batch_exports/backend/temporal/record_batch_model.py+++ b/products/batch_exports/backend/temporal/record_batch_model.py@@ -24,8 +24,9 @@ from products.batch_exports.backend.hogql_source import (parse_hogql_select_for_batch_export,)from products.batch_exports.backend.service import BatchExportModel, BatchExportSchema-from products.batch_exports.backend.temporal import sqlfrom products.batch_exports.backend.temporal.metrics import log_query_duration+from 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_HOGQLLOGGER = get_write_only_logger()@@ -139,7 +140,7 @@ class RecordBatchModel(abc.ABC):) -> tuple[Query, QueryParameters]:"""Produce an `INSERT INTO FUNCTION s3(...)` query and its ClickHouse parameters."""printed, parameters = await self._print_query(data_interval_start, data_interval_end, output_format=None)- s3_function = sql.get_s3_function_call(s3_folder, credentials, num_partitions)+ s3_function = get_s3_function_call(s3_folder, credentials, num_partitions)insert_query = f"""INSERT INTO FUNCTION {s3_function}{printed}@@ -154,7 +155,7 @@ class SessionsRecordBatchModel(RecordBatchModel):self, data_interval_start: dt.datetime | None, data_interval_end: dt.datetime) -> ast.SelectQuery:"""Return the HogQLQuery used for the sessions model."""- hogql_query = clone_expr(sql.SELECT_FROM_SESSIONS_HOGQL)+ hogql_query = clone_expr(SELECT_FROM_SESSIONS_HOGQL)where_and = ast.And(exprs=[@@ -242,7 +243,7 @@ class SessionsRecordBatchModel(RecordBatchModel):],select_from=ast.JoinExpr(table=ast.Field(chain=["sessions"])),where=where_and,- settings=sql.HogQLQueryBatchExportSettings(),+ settings=HogQLQueryBatchExportSettings(),)async def get_backfill_info(@@ -339,7 +340,7 @@ class HogQLQueryRecordBatchModel(RecordBatchModel):# Sent with the request instead of set on the query AST, because the user query may# not parse to a simple `ast.SelectQuery` (e.g. a UNION parses to an# `ast.SelectSetQuery`, which has no `settings` field to attach these to).- return _as_clickhouse_request_settings(sql.HogQLQueryBatchExportSettings())+ return _as_clickhouse_request_settings(HogQLQueryBatchExportSettings())def resolve_batch_exports_model(diff --git a/products/batch_exports/backend/temporal/spmc.py b/products/batch_exports/backend/temporal/spmc.pyindex de880521bd14..9716e225e7a8 100644--- a/products/batch_exports/backend/temporal/spmc.py+++ b/products/batch_exports/backend/temporal/spmc.py@@ -31,16 +31,15 @@ from posthog.temporal.common.logger import get_write_only_loggerfrom products.batch_exports.backend.service import SUPPORTED_FILTER_TYPES, BackfillDetailsfrom products.batch_exports.backend.temporal.metrics import get_metric_meterfrom products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel-from products.batch_exports.backend.temporal.sql import (+from products.batch_exports.backend.temporal.sql.events import (SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,SELECT_FROM_EVENTS_VIEW,SELECT_FROM_EVENTS_VIEW_BACKFILL,SELECT_FROM_EVENTS_VIEW_RECENT,SELECT_FROM_EVENTS_VIEW_UNBOUNDED,SELECT_FROM_EVENTS_WORKFLOWS,- SELECT_FROM_PERSONS,- SELECT_FROM_PERSONS_BACKFILL,)+from products.batch_exports.backend.temporal.sql.persons import SELECT_FROM_PERSONS, SELECT_FROM_PERSONS_BACKFILLLOGGER = get_write_only_logger(__name__)diff --git a/products/batch_exports/backend/temporal/sql/__init__.py b/products/batch_exports/backend/temporal/sql/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/batch_exports/backend/temporal/sql/common.py b/products/batch_exports/backend/temporal/sql/common.pynew file mode 100644index 000000000000..3b0d96f42c5e--- /dev/null+++ b/products/batch_exports/backend/temporal/sql/common.py@@ -0,0 +1,31 @@+from posthog.hogql.constants import HogQLQuerySettings++from posthog.credentials import AWSKeyPair+++def get_s3_function_call(s3_folder: str, credentials: AWSKeyPair | None, num_partitions: int) -> str:+ """Generate the s3() function call for ClickHouse INSERT queries.++ When using keyless S3 auth (IAM roles), we omit credentials and ClickHouse uses the+ default credential provider chain. Otherwise, we pass the access key and secret.++ Note: We use %% for the modulo operator because the ClickHouse client uses % for+ parameter substitution, so %% produces a literal % in the final query.+ """+ s3_url = f"{s3_folder}/export_{{{{_partition_id}}}}.arrow"+ if credentials is not None:+ # Escape single quotes by doubling them (ClickHouse SQL escaping)+ escaped_key = credentials.access_key_id.replace("'", "''")+ escaped_secret = credentials.secret_access_key.replace("'", "''")+ s3_call = f"s3('{s3_url}', '{escaped_key}', '{escaped_secret}', 'ArrowStream')"+ else:+ s3_call = f"s3('{s3_url}', 'ArrowStream')"++ return f"""{s3_call}+ PARTITION BY rand() %% {num_partitions}"""+++class HogQLQueryBatchExportSettings(HogQLQuerySettings):+ optimize_aggregation_in_order: bool | None = True+ max_bytes_before_external_sort: int | None = 50000000000+ max_bytes_before_external_group_by: int | None = 50000000000diff --git a/products/batch_exports/backend/temporal/sql.py b/products/batch_exports/backend/temporal/sql/events.pysimilarity index 50%rename from products/batch_exports/backend/temporal/sql.pyrename to products/batch_exports/backend/temporal/sql/events.pyindex b8cb0160cfa8..e110eb27de15 100644--- a/products/batch_exports/backend/temporal/sql.py+++ b/products/batch_exports/backend/temporal/sql/events.py@@ -1,253 +1,52 @@-from string import Template--from posthog.hogql import ast-from posthog.hogql.constants import HogQLQuerySettings-from posthog.hogql.parser import parse_expr--from posthog.credentials import AWSKeyPair---def get_s3_function_call(s3_folder: str, credentials: AWSKeyPair | None, num_partitions: int) -> str:- """Generate the s3() function call for ClickHouse INSERT queries.+"""SQL for the events batch export model."""- When using keyless S3 auth (IAM roles), we omit credentials and ClickHouse uses the- default credential provider chain. Otherwise, we pass the access key and secret.+from string import Template- Note: We use %% for the modulo operator because the ClickHouse client uses % for- parameter substitution, so %% produces a literal % in the final query.+SELECT_FROM_EVENTS_VIEW = Template("""- s3_url = f"{s3_folder}/export_{{{{_partition_id}}}}.arrow"- if credentials is not None:- # Escape single quotes by doubling them (ClickHouse SQL escaping)- escaped_key = credentials.access_key_id.replace("'", "''")- escaped_secret = credentials.secret_access_key.replace("'", "''")- s3_call = f"s3('{s3_url}', '{escaped_key}', '{escaped_secret}', 'ArrowStream')"- else:- s3_call = f"s3('{s3_url}', 'ArrowStream')"-- return f"""{s3_call}- PARTITION BY rand() %% {num_partitions}"""---SELECT_FROM_PERSONS = """SELECT- persons.team_id AS team_id,- persons.distinct_id AS distinct_id,- persons.person_id AS person_id,- persons.properties AS properties,- persons.person_distinct_id_version AS person_distinct_id_version,- persons.person_version AS person_version,- persons.created_at AS created_at,- persons._inserted_at AS _inserted_at,- persons.is_deleted AS is_deleted+ $fieldsFROM (- WITH new_persons AS (- SELECT- id- FROM- person- WHERE- team_id = {team_id}::Int64- AND id in (- SELECT- id- FROM- person- WHERE- team_id = {team_id}::Int64- AND _timestamp >= {interval_start}::DateTime64- AND _timestamp < {interval_end}::DateTime64- )- GROUP BY- id- HAVING- argMax(_timestamp, person.version) >= {interval_start}::DateTime64- AND argMax(_timestamp, person.version) < {interval_end}::DateTime64- ),- distinct_ids AS (- -- new distinct_ids- SELECT- distinct_id- FROM- person_distinct_id2- WHERE- team_id = {team_id}::Int64- AND distinct_id in (- SELECT- distinct_id- FROM- person_distinct_id2- WHERE- team_id = {team_id}::Int64- AND _timestamp >= {interval_start}::DateTime64- AND _timestamp < {interval_end}::DateTime64- )- GROUP BY- distinct_id- HAVING- argMax(_timestamp, person_distinct_id2.version) >= {interval_start}::DateTime64- AND argMax(_timestamp, person_distinct_id2.version) < {interval_end}::DateTime64-- UNION DISTINCT-- -- existing distinct_ids for new/updated persons- SELECT- DISTINCT distinct_id- FROM- person_distinct_id2- WHERE- team_id = {team_id}::Int64- AND person_id IN new_persons- ),- latest_distinct_ids AS (- SELECT- distinct_id,- argMax(person_id, person_distinct_id2.version) AS person_id2,- max(version) AS version,- argMax(_timestamp, person_distinct_id2.version) AS _timestamp- FROM- person_distinct_id2- WHERE- team_id = {team_id}::Int64- AND distinct_id IN distinct_ids- GROUP BY- distinct_id- ),- latest_person_versions AS (- SELECT- id,- max(version) AS version,- max(_timestamp) AS _timestamp- FROM- person- WHERE- team_id = {team_id}::Int64- AND- id IN (- SELECT- DISTINCT person_id2- FROM- latest_distinct_ids- )- GROUP BY- id- )- SELECT- p.team_id AS team_id,- pd.distinct_id AS distinct_id,- toString(pd.person_id2) AS person_id,- p.version AS person_version,- pd.version AS person_distinct_id_version,- p.properties AS properties,- p.created_at AS created_at,- toBool(p.is_deleted) AS is_deleted,- multiIf(- (- pd._timestamp >= {interval_start}::DateTime64- AND pd._timestamp < {interval_end}::DateTime64- )- AND NOT (- p._timestamp >= {interval_start}::DateTime64- AND p._timestamp < {interval_end}::DateTime64- ),- pd._timestamp,- (- p._timestamp >= {interval_start}::DateTime64- AND p._timestamp < {interval_end}::DateTime64- )- AND NOT (- pd._timestamp >= {interval_start}::DateTime64- AND pd._timestamp < {interval_end}::DateTime64- ),- p._timestamp,- least(p._timestamp, pd._timestamp)- ) AS _inserted_at+ SELECT DISTINCT ON (team_id, event, cityHash64(events.distinct_id), cityHash64(events.uuid))+ team_id AS team_id,+ timestamp AS timestamp,+ event AS event,+ distinct_id AS distinct_id,+ toString(uuid) AS uuid,+ COALESCE(inserted_at, _timestamp) AS _inserted_at,+ created_at AS created_at,+ elements_chain AS elements_chain,+ toString(person_id) AS person_id,+ nullIf(properties, '') AS properties,+ nullIf(person_properties, '') AS person_properties,+ nullIf(JSONExtractString(properties, '$set'), '') AS set,+ nullIf(JSONExtractString(properties, '$set_once'), '') AS set_onceFROM- person p- INNER JOIN latest_distinct_ids pd- ON p.id = pd.person_id2+ events+ PREWHERE+ COALESCE(events.inserted_at, events._timestamp) >= {{interval_start:DateTime64}}+ AND COALESCE(events.inserted_at, events._timestamp) < {{interval_end:DateTime64}}WHERE- p.team_id = {team_id}::Int64- AND (p.id, p.version, p._timestamp) in latest_person_versions- ORDER BY- _inserted_at-) AS persons+ team_id = {{team_id:Int64}}+ AND events.timestamp >= {{interval_start:DateTime64}} - INTERVAL {{lookback_days:Int32}} DAY+ AND events.timestamp < {{interval_end:DateTime64}} + INTERVAL 1 DAY+ AND (length({{include_events:Array(String)}}) = 0 OR event IN {{include_events:Array(String)}})+ AND (length({{exclude_events:Array(String)}}) = 0 OR event NOT IN {{exclude_events:Array(String)}})+ $filters+ $order+) AS eventsFORMAT ArrowStreamSETTINGS- max_bytes_before_external_group_by=50000000000,+ -- This is half of configured MAX_MEMORY_USAGE for batch exports.max_bytes_before_external_sort=50000000000,optimize_aggregation_in_order=1"""+)-SELECT_FROM_PERSONS_BACKFILL = """-SELECT- pd.team_id AS team_id,- pd.distinct_id AS distinct_id,- toString(p.id) AS person_id,- p.properties AS properties,- pd.version AS person_distinct_id_version,- p.version AS person_version,- p.created_at AS created_at,- toBool(p.is_deleted) AS is_deleted,- multiIf(- pd._timestamp < {interval_end}::DateTime64- AND NOT p._timestamp < {interval_end}::DateTime64,- pd._timestamp,- p._timestamp < {interval_end}::DateTime64- AND NOT pd._timestamp < {interval_end}::DateTime64,- p._timestamp,- least(p._timestamp, pd._timestamp)- ) AS _inserted_at-FROM (- SELECT- team_id,- distinct_id,- max(version) AS version,- argMax(person_id, person_distinct_id2.version) AS person_id,- argMax(_timestamp, person_distinct_id2.version) AS _timestamp- FROM- person_distinct_id2- PREWHERE- team_id = {team_id}::Int64- GROUP BY- team_id,- distinct_id-) AS pd-INNER JOIN (- SELECT- team_id,- id,- max(version) AS version,- argMax(properties, person.version) AS properties,- argMax(created_at, person.version) AS created_at,- argMax(_timestamp, person.version) AS _timestamp,- argMax(is_deleted, person.version) AS is_deleted- FROM- person- PREWHERE- team_id = {team_id}::Int64- GROUP BY- team_id,- id-) AS p ON p.id = pd.person_id AND p.team_id = pd.team_id-WHERE- pd.team_id = {team_id}::Int64- AND p.team_id = {team_id}::Int64- AND (- pd._timestamp < {interval_end}::DateTime64- OR p._timestamp < {interval_end}::DateTime64- )-ORDER BY- _inserted_at-FORMAT ArrowStream-SETTINGS- max_bytes_before_external_group_by=50000000000,- max_bytes_before_external_sort=50000000000,- optimize_aggregation_in_order=1-"""-SELECT_FROM_EVENTS_VIEW = Template(+EXPORT_TO_S3_FROM_EVENTS = Template("""+INSERT INTO FUNCTION $s3_functionSELECT$fieldsFROM (@@ -277,16 +76,16 @@ FROM (AND (length({{include_events:Array(String)}}) = 0 OR event IN {{include_events:Array(String)}})AND (length({{exclude_events:Array(String)}}) = 0 OR event NOT IN {{exclude_events:Array(String)}})$filters- $order) AS events-FORMAT ArrowStreamSETTINGS-- This is half of configured MAX_MEMORY_USAGE for batch exports.max_bytes_before_external_sort=50000000000,- optimize_aggregation_in_order=1+ optimize_aggregation_in_order=1,+ log_comment={log_comment}""")+SELECT_FROM_EVENTS_WORKFLOWS = Template("""SELECT@@ -308,6 +107,30 @@ SETTINGS""")++EXPORT_TO_S3_FROM_EVENTS_WORKFLOWS = Template(+ """+INSERT INTO FUNCTION $s3_function+SELECT+ $fields+FROM+ events+WHERE+ team_id = {{team_id:Int64}}+ AND events.timestamp >= {{interval_start:DateTime64}}+ AND events.timestamp < {{interval_end:DateTime64}}+ AND (length({{include_events:Array(String)}}) = 0 OR event IN {{include_events:Array(String)}})+ AND (length({{exclude_events:Array(String)}}) = 0 OR event NOT IN {{exclude_events:Array(String)}})+ $filters+SETTINGS+ -- This is half of configured MAX_MEMORY_USAGE for batch exports.+ max_bytes_before_external_sort=50000000000,+ optimize_aggregation_in_order=1,+ log_comment={log_comment}+"""+)++SELECT_FROM_EVENTS_VIEW_RECENT = Template("""SELECT@@ -348,60 +171,20 @@ SETTINGS""")-SELECT_FROM_DISTRIBUTED_EVENTS_RECENT = Template(- """-SELECT- $fields-FROM (- SELECT DISTINCT ON (team_id, event, cityHash64(distributed_events_recent.distinct_id), cityHash64(distributed_events_recent.uuid))- team_id AS team_id,- timestamp AS timestamp,- event AS event,- distinct_id AS distinct_id,- toString(uuid) AS uuid,- inserted_at AS _inserted_at,- created_at AS created_at,- elements_chain AS elements_chain,- toString(person_id) AS person_id,- nullIf(properties, '') AS properties,- nullIf(person_properties, '') AS person_properties,- nullIf(JSONExtractString(properties, '$$set'), '') AS set,- nullIf(JSONExtractString(properties, '$$set_once'), '') AS set_once- FROM- distributed_events_recent AS events- PREWHERE- distributed_events_recent.inserted_at >= {interval_start}::DateTime64- AND distributed_events_recent.inserted_at < {interval_end}::DateTime64- WHERE- team_id = {team_id}::Int64- AND (length({include_events}::Array(String)) = 0 OR event IN {include_events}::Array(String))- AND (length({exclude_events}::Array(String)) = 0 OR event NOT IN {exclude_events}::Array(String))- $filters- $order-) AS events-FORMAT ArrowStream-SETTINGS- -- This is half of configured MAX_MEMORY_USAGE for batch exports.- max_bytes_before_external_sort=50000000000,- max_replica_delay_for_distributed_queries=60,- fallback_to_stale_replicas_for_distributed_queries=0,- optimize_aggregation_in_order=1-"""-)--SELECT_FROM_EVENTS_VIEW_UNBOUNDED = Template(+EXPORT_TO_S3_FROM_EVENTS_RECENT = Template("""+INSERT INTO FUNCTION $s3_functionSELECT$fieldsFROM (- SELECT DISTINCT ON (team_id, event, cityHash64(events.distinct_id), cityHash64(events.uuid))+ SELECT DISTINCT ON (team_id, event, cityHash64(events_recent.distinct_id), cityHash64(events_recent.uuid))team_id AS team_id,timestamp AS timestamp,event AS event,distinct_id AS distinct_id,toString(uuid) AS uuid,- COALESCE(inserted_at, _timestamp) AS _inserted_at,+ inserted_at AS _inserted_at,created_at AS created_at,elements_chain AS elements_chain,toString(person_id) AS person_id,@@ -410,125 +193,68 @@ FROM (nullIf(JSONExtractString(properties, '$set'), '') AS set,nullIf(JSONExtractString(properties, '$set_once'), '') AS set_onceFROM- events+ events_recent AS eventsPREWHERE- COALESCE(events.inserted_at, events._timestamp) >= {{interval_start:DateTime64}}- AND COALESCE(events.inserted_at, events._timestamp) < {{interval_end:DateTime64}}+ events_recent.inserted_at >= {{interval_start:DateTime64}}+ AND events_recent.inserted_at < {{interval_end:DateTime64}}WHEREteam_id = {{team_id:Int64}}AND (length({{include_events:Array(String)}}) = 0 OR event IN {{include_events:Array(String)}})AND (length({{exclude_events:Array(String)}}) = 0 OR event NOT IN {{exclude_events:Array(String)}})$filters- $order) AS events-FORMAT ArrowStreamSETTINGS-- This is half of configured MAX_MEMORY_USAGE for batch exports.max_bytes_before_external_sort=50000000000,- optimize_aggregation_in_order=1+ max_replica_delay_for_distributed_queries=1,+ optimize_aggregation_in_order=1,+ log_comment={log_comment}""")-SELECT_FROM_EVENTS_VIEW_BACKFILL = Template(++SELECT_FROM_DISTRIBUTED_EVENTS_RECENT = Template("""SELECT$fieldsFROM (- SELECT DISTINCT ON (team_id, event, cityHash64(events.distinct_id), cityHash64(events.uuid))+ SELECT DISTINCT ON (team_id, event, cityHash64(distributed_events_recent.distinct_id), cityHash64(distributed_events_recent.uuid))team_id AS team_id,timestamp AS timestamp,event AS event,distinct_id AS distinct_id,toString(uuid) AS uuid,- timestamp AS _inserted_at,+ inserted_at AS _inserted_at,created_at AS created_at,elements_chain AS elements_chain,toString(person_id) AS person_id,nullIf(properties, '') AS properties,nullIf(person_properties, '') AS person_properties,- nullIf(JSONExtractString(properties, '$set'), '') AS set,- nullIf(JSONExtractString(properties, '$set_once'), '') AS set_once+ nullIf(JSONExtractString(properties, '$$set'), '') AS set,+ nullIf(JSONExtractString(properties, '$$set_once'), '') AS set_onceFROM- events+ distributed_events_recent AS events+ PREWHERE+ distributed_events_recent.inserted_at >= {interval_start}::DateTime64+ AND distributed_events_recent.inserted_at < {interval_end}::DateTime64WHERE- team_id = {{team_id:Int64}}- AND events.timestamp >= {{interval_start:DateTime64}}- AND events.timestamp < {{interval_end:DateTime64}}- AND (length({{include_events:Array(String)}}) = 0 OR event IN {{include_events:Array(String)}})- AND (length({{exclude_events:Array(String)}}) = 0 OR event NOT IN {{exclude_events:Array(String)}})+ team_id = {team_id}::Int64+ AND (length({include_events}::Array(String)) = 0 OR event IN {include_events}::Array(String))+ AND (length({exclude_events}::Array(String)) = 0 OR event NOT IN {exclude_events}::Array(String))$filters$order-) as events+) AS eventsFORMAT ArrowStreamSETTINGS-- This is half of configured MAX_MEMORY_USAGE for batch exports.max_bytes_before_external_sort=50000000000,+ max_replica_delay_for_distributed_queries=60,+ fallback_to_stale_replicas_for_distributed_queries=0,optimize_aggregation_in_order=1""")-class HogQLQueryBatchExportSettings(HogQLQuerySettings):- optimize_aggregation_in_order: bool | None = True- max_bytes_before_external_sort: int | None = 50000000000- max_bytes_before_external_group_by: int | None = 50000000000---SELECT_FROM_SESSIONS_HOGQL = ast.SelectQuery(- select=[- parse_expr("session_id as session_id"),- parse_expr("toString(session_id_v7) as session_id_v7"),- parse_expr("team_id"),- parse_expr("distinct_id as distinct_id"),- parse_expr("$start_timestamp as start_timestamp"),- parse_expr("$end_timestamp as end_timestamp"),- parse_expr("$urls as urls"),- parse_expr("$num_uniq_urls as num_uniq_urls"),- parse_expr("$entry_current_url as entry_current_url"),- parse_expr("$entry_pathname as entry_pathname"),- parse_expr("$entry_hostname as entry_hostname"),- parse_expr("$end_current_url as end_current_url"),- parse_expr("$end_pathname as end_pathname"),- parse_expr("$end_hostname as end_hostname"),- parse_expr("$entry_utm_source as entry_utm_source"),- parse_expr("$entry_utm_campaign as entry_utm_campaign"),- parse_expr("$entry_utm_medium as entry_utm_medium"),- parse_expr("$entry_utm_term as entry_utm_term"),- parse_expr("$entry_utm_content as entry_utm_content"),- parse_expr("$entry_referring_domain as entry_referring_domain"),- parse_expr("$entry_gclid as entry_gclid"),- parse_expr("$entry_fbclid as entry_fbclid"),- parse_expr("$entry_gad_source as entry_gad_source"),- parse_expr("$pageview_count as pageview_count"),- parse_expr("$autocapture_count as autocapture_count"),- parse_expr("$screen_count as screen_count"),- parse_expr("$channel_type as channel_type"),- parse_expr("$session_duration as session_duration"),- parse_expr("duration as duration"),- parse_expr("$is_bounce as is_bounce"),- parse_expr("$last_external_click_url as last_external_click_url"),- parse_expr("$page_screen_autocapture_count_up_to as page_screen_autocapture_count_up_to"),- 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"),- parse_expr("$entry_gclsrc as entry_gclsrc"),- parse_expr("$entry_dclid as entry_dclid"),- parse_expr("$entry_gbraid as entry_gbraid"),- parse_expr("$entry_wbraid as entry_wbraid"),- parse_expr("$entry_msclkid as entry_msclkid"),- parse_expr("$entry_twclid as entry_twclid"),- parse_expr("$entry_li_fat_id as entry_li_fat_id"),- parse_expr("$entry_mc_cid as entry_mc_cid"),- parse_expr("$entry_igshid as entry_igshid"),- parse_expr("$entry_ttclid as entry_ttclid"),- parse_expr("$entry__kx as entry__kx"),- parse_expr("$entry_irclid as entry_irclid"),- ],- select_from=ast.JoinExpr(table=ast.Field(chain=["sessions"])),- settings=HogQLQueryBatchExportSettings(),-)-EXPORT_TO_S3_FROM_DISTRIBUTED_EVENTS_RECENT = Template("""INSERT INTO FUNCTION $s3_function@@ -570,19 +296,19 @@ SETTINGS""")-EXPORT_TO_S3_FROM_EVENTS_RECENT = Template(++SELECT_FROM_EVENTS_VIEW_UNBOUNDED = Template("""-INSERT INTO FUNCTION $s3_functionSELECT$fieldsFROM (- SELECT DISTINCT ON (team_id, event, cityHash64(events_recent.distinct_id), cityHash64(events_recent.uuid))+ SELECT DISTINCT ON (team_id, event, cityHash64(events.distinct_id), cityHash64(events.uuid))team_id AS team_id,timestamp AS timestamp,event AS event,distinct_id AS distinct_id,toString(uuid) AS uuid,- inserted_at AS _inserted_at,+ COALESCE(inserted_at, _timestamp) AS _inserted_at,created_at AS created_at,elements_chain AS elements_chain,toString(person_id) AS person_id,@@ -591,25 +317,26 @@ FROM (nullIf(JSONExtractString(properties, '$set'), '') AS set,nullIf(JSONExtractString(properties, '$set_once'), '') AS set_onceFROM- events_recent AS events+ eventsPREWHERE- events_recent.inserted_at >= {{interval_start:DateTime64}}- AND events_recent.inserted_at < {{interval_end:DateTime64}}+ COALESCE(events.inserted_at, events._timestamp) >= {{interval_start:DateTime64}}+ AND COALESCE(events.inserted_at, events._timestamp) < {{interval_end:DateTime64}}WHEREteam_id = {{team_id:Int64}}AND (length({{include_events:Array(String)}}) = 0 OR event IN {{include_events:Array(String)}})AND (length({{exclude_events:Array(String)}}) = 0 OR event NOT IN {{exclude_events:Array(String)}})$filters+ $order) AS events+FORMAT ArrowStreamSETTINGS-- This is half of configured MAX_MEMORY_USAGE for batch exports.max_bytes_before_external_sort=50000000000,- max_replica_delay_for_distributed_queries=1,- optimize_aggregation_in_order=1,- log_comment={log_comment}+ optimize_aggregation_in_order=1""")+EXPORT_TO_S3_FROM_EVENTS_UNBOUNDED = Template("""INSERT INTO FUNCTION $s3_function@@ -649,9 +376,9 @@ SETTINGS""")-EXPORT_TO_S3_FROM_EVENTS_BACKFILL = Template(++SELECT_FROM_EVENTS_VIEW_BACKFILL = Template("""-INSERT INTO FUNCTION $s3_functionSELECT$fieldsFROM (@@ -678,37 +405,18 @@ FROM (AND (length({{include_events:Array(String)}}) = 0 OR event IN {{include_events:Array(String)}})AND (length({{exclude_events:Array(String)}}) = 0 OR event NOT IN {{exclude_events:Array(String)}})$filters+ $order) as events+FORMAT ArrowStreamSETTINGS-- This is half of configured MAX_MEMORY_USAGE for batch exports.max_bytes_before_external_sort=50000000000,- optimize_aggregation_in_order=1,- log_comment={log_comment}+ optimize_aggregation_in_order=1""")-EXPORT_TO_S3_FROM_EVENTS_WORKFLOWS = Template(- """-INSERT INTO FUNCTION $s3_function-SELECT- $fields-FROM- events-WHERE- team_id = {{team_id:Int64}}- AND events.timestamp >= {{interval_start:DateTime64}}- AND events.timestamp < {{interval_end:DateTime64}}- AND (length({{include_events:Array(String)}}) = 0 OR event IN {{include_events:Array(String)}})- AND (length({{exclude_events:Array(String)}}) = 0 OR event NOT IN {{exclude_events:Array(String)}})- $filters-SETTINGS- -- This is half of configured MAX_MEMORY_USAGE for batch exports.- max_bytes_before_external_sort=50000000000,- optimize_aggregation_in_order=1,- log_comment={log_comment}-"""-)-EXPORT_TO_S3_FROM_EVENTS = Template(++EXPORT_TO_S3_FROM_EVENTS_BACKFILL = Template("""INSERT INTO FUNCTION $s3_functionSELECT@@ -720,7 +428,7 @@ FROM (event AS event,distinct_id AS distinct_id,toString(uuid) AS uuid,- COALESCE(inserted_at, _timestamp) AS _inserted_at,+ timestamp AS _inserted_at,created_at AS created_at,elements_chain AS elements_chain,toString(person_id) AS person_id,@@ -730,17 +438,14 @@ FROM (nullIf(JSONExtractString(properties, '$set_once'), '') AS set_onceFROMevents- PREWHERE- COALESCE(events.inserted_at, events._timestamp) >= {{interval_start:DateTime64}}- AND COALESCE(events.inserted_at, events._timestamp) < {{interval_end:DateTime64}}WHEREteam_id = {{team_id:Int64}}- AND events.timestamp >= {{interval_start:DateTime64}} - INTERVAL {{lookback_days:Int32}} DAY- AND events.timestamp < {{interval_end:DateTime64}} + INTERVAL 1 DAY+ AND events.timestamp >= {{interval_start:DateTime64}}+ AND events.timestamp < {{interval_end:DateTime64}}AND (length({{include_events:Array(String)}}) = 0 OR event IN {{include_events:Array(String)}})AND (length({{exclude_events:Array(String)}}) = 0 OR event NOT IN {{exclude_events:Array(String)}})$filters-) AS events+) as eventsSETTINGS-- This is half of configured MAX_MEMORY_USAGE for batch exports.max_bytes_before_external_sort=50000000000,@@ -749,223 +454,6 @@ SETTINGS""")-EXPORT_TO_S3_FROM_PERSONS_BACKFILL = Template("""-INSERT INTO FUNCTION $s3_function-SELECT- pd.team_id AS team_id,- pd.distinct_id AS distinct_id,- toString(p.id) AS person_id,- p.properties AS properties,- pd.version AS person_distinct_id_version,- p.version AS person_version,- p.created_at AS created_at,- toBool(p.is_deleted) AS is_deleted,- multiIf(- pd._timestamp < {interval_end}::DateTime64- AND NOT p._timestamp < {interval_end}::DateTime64,- pd._timestamp,- p._timestamp < {interval_end}::DateTime64- AND NOT pd._timestamp < {interval_end}::DateTime64,- p._timestamp,- least(p._timestamp, pd._timestamp)- ) AS _inserted_at-FROM (- SELECT- team_id,- distinct_id,- max(version) AS version,- argMax(person_id, person_distinct_id2.version) AS person_id,- argMax(_timestamp, person_distinct_id2.version) AS _timestamp- FROM- person_distinct_id2- PREWHERE- team_id = {team_id}::Int64- GROUP BY- team_id,- distinct_id-) AS pd-INNER JOIN (- SELECT- team_id,- id,- max(version) AS version,- argMax(properties, person.version) AS properties,- argMax(created_at, person.version) AS created_at,- argMax(_timestamp, person.version) AS _timestamp,- argMax(is_deleted, person.version) AS is_deleted- FROM- person- PREWHERE- team_id = {team_id}::Int64- GROUP BY- team_id,- id-) AS p ON p.id = pd.person_id AND p.team_id = pd.team_id-WHERE- pd.team_id = {team_id}::Int64- AND p.team_id = {team_id}::Int64- AND (- pd._timestamp < {interval_end}::DateTime64- OR p._timestamp < {interval_end}::DateTime64- )-SETTINGS- max_bytes_before_external_group_by=50000000000,- max_bytes_before_external_sort=50000000000,- optimize_aggregation_in_order=1,- log_comment={log_comment}-""")---EXPORT_TO_S3_FROM_PERSONS = Template("""-INSERT INTO FUNCTION $s3_function-SELECT- persons.team_id AS team_id,- persons.distinct_id AS distinct_id,- persons.person_id AS person_id,- persons.properties AS properties,- persons.person_distinct_id_version AS person_distinct_id_version,- persons.person_version AS person_version,- persons.created_at AS created_at,- persons._inserted_at AS _inserted_at,- persons.is_deleted AS is_deleted-FROM (- WITH new_persons AS (- SELECT- id- FROM- person- WHERE- team_id = {team_id}::Int64- AND id in (- SELECT- id- FROM- person- WHERE- team_id = {team_id}::Int64- AND _timestamp >= {interval_start}::DateTime64- AND _timestamp < {interval_end}::DateTime64- )- GROUP BY- id- HAVING- argMax(_timestamp, person.version) >= {interval_start}::DateTime64- AND argMax(_timestamp, person.version) < {interval_end}::DateTime64- ),- distinct_ids AS (- -- new distinct_ids- SELECT- distinct_id- FROM- person_distinct_id2- WHERE- team_id = {team_id}::Int64- AND distinct_id in (- SELECT- distinct_id- FROM- person_distinct_id2- WHERE- team_id = {team_id}::Int64- AND _timestamp >= {interval_start}::DateTime64- AND _timestamp < {interval_end}::DateTime64- )- GROUP BY- distinct_id- HAVING- argMax(_timestamp, person_distinct_id2.version) >= {interval_start}::DateTime64- AND argMax(_timestamp, person_distinct_id2.version) < {interval_end}::DateTime64-- UNION DISTINCT-- -- existing distinct_ids for new/updated persons- SELECT- DISTINCT distinct_id- FROM- person_distinct_id2- WHERE- team_id = {team_id}::Int64- AND person_id IN new_persons- ),- latest_distinct_ids AS (- SELECT- distinct_id,- argMax(person_id, person_distinct_id2.version) AS person_id2,- max(version) AS version,- argMax(_timestamp, person_distinct_id2.version) AS _timestamp- FROM- person_distinct_id2- WHERE- team_id = {team_id}::Int64- AND distinct_id IN distinct_ids- GROUP BY- distinct_id- $filter_distinct_ids- ),- latest_person_versions AS (- SELECT- id,- max(version) AS version,- max(_timestamp) AS _timestamp- FROM- person- WHERE- team_id = {team_id}::Int64- AND- id IN (- SELECT- DISTINCT person_id2- FROM- latest_distinct_ids- )- GROUP BY- id- )- SELECT- p.team_id AS team_id,- pd.distinct_id AS distinct_id,- toString(pd.person_id2) AS person_id,- p.version AS person_version,- pd.version AS person_distinct_id_version,- p.properties AS properties,- p.created_at AS created_at,- toBool(p.is_deleted) AS is_deleted,- multiIf(- (- pd._timestamp >= {interval_start}::DateTime64- AND pd._timestamp < {interval_end}::DateTime64- )- AND NOT (- p._timestamp >= {interval_start}::DateTime64- AND p._timestamp < {interval_end}::DateTime64- ),- pd._timestamp,- (- p._timestamp >= {interval_start}::DateTime64- AND p._timestamp < {interval_end}::DateTime64- )- AND NOT (- pd._timestamp >= {interval_start}::DateTime64- AND pd._timestamp < {interval_end}::DateTime64- ),- p._timestamp,- least(p._timestamp, pd._timestamp)- ) AS _inserted_at- FROM- person p- INNER JOIN latest_distinct_ids pd- ON p.id = pd.person_id2- WHERE- p.team_id = {team_id}::Int64- AND (p.id, p.version, p._timestamp) in latest_person_versions-) AS persons-SETTINGS- max_bytes_before_external_group_by=50000000000,- max_bytes_before_external_sort=50000000000,- optimize_aggregation_in_order=1,- log_comment={log_comment}-""")-EVENT_COUNT_BY_INTERVAL = """SELECTdiff --git a/products/batch_exports/backend/temporal/sql/persons.py b/products/batch_exports/backend/temporal/sql/persons.pynew file mode 100644index 000000000000..15db3d6c385f--- /dev/null+++ b/products/batch_exports/backend/temporal/sql/persons.py@@ -0,0 +1,439 @@+"""SQL for the persons batch export model."""++from string import Template++SELECT_FROM_PERSONS = """+SELECT+ persons.team_id AS team_id,+ persons.distinct_id AS distinct_id,+ persons.person_id AS person_id,+ persons.properties AS properties,+ persons.person_distinct_id_version AS person_distinct_id_version,+ persons.person_version AS person_version,+ persons.created_at AS created_at,+ persons._inserted_at AS _inserted_at,+ persons.is_deleted AS is_deleted+FROM (+ WITH new_persons AS (+ SELECT+ id+ FROM+ person+ WHERE+ team_id = {team_id}::Int64+ AND id in (+ SELECT+ id+ FROM+ person+ WHERE+ team_id = {team_id}::Int64+ AND _timestamp >= {interval_start}::DateTime64+ AND _timestamp < {interval_end}::DateTime64+ )+ GROUP BY+ id+ HAVING+ argMax(_timestamp, person.version) >= {interval_start}::DateTime64+ AND argMax(_timestamp, person.version) < {interval_end}::DateTime64+ ),+ distinct_ids AS (+ -- new distinct_ids+ SELECT+ distinct_id+ FROM+ person_distinct_id2+ WHERE+ team_id = {team_id}::Int64+ AND distinct_id in (+ SELECT+ distinct_id+ FROM+ person_distinct_id2+ WHERE+ team_id = {team_id}::Int64+ AND _timestamp >= {interval_start}::DateTime64+ AND _timestamp < {interval_end}::DateTime64+ )+ GROUP BY+ distinct_id+ HAVING+ argMax(_timestamp, person_distinct_id2.version) >= {interval_start}::DateTime64+ AND argMax(_timestamp, person_distinct_id2.version) < {interval_end}::DateTime64++ UNION DISTINCT++ -- existing distinct_ids for new/updated persons+ SELECT+ DISTINCT distinct_id+ FROM+ person_distinct_id2+ WHERE+ team_id = {team_id}::Int64+ AND person_id IN new_persons+ ),+ latest_distinct_ids AS (+ SELECT+ distinct_id,+ argMax(person_id, person_distinct_id2.version) AS person_id2,+ max(version) AS version,+ argMax(_timestamp, person_distinct_id2.version) AS _timestamp+ FROM+ person_distinct_id2+ WHERE+ team_id = {team_id}::Int64+ AND distinct_id IN distinct_ids+ GROUP BY+ distinct_id+ ),+ latest_person_versions AS (+ SELECT+ id,+ max(version) AS version,+ max(_timestamp) AS _timestamp+ FROM+ person+ WHERE+ team_id = {team_id}::Int64+ AND+ id IN (+ SELECT+ DISTINCT person_id2+ FROM+ latest_distinct_ids+ )+ GROUP BY+ id+ )+ SELECT+ p.team_id AS team_id,+ pd.distinct_id AS distinct_id,+ toString(pd.person_id2) AS person_id,+ p.version AS person_version,+ pd.version AS person_distinct_id_version,+ p.properties AS properties,+ p.created_at AS created_at,+ toBool(p.is_deleted) AS is_deleted,+ multiIf(+ (+ pd._timestamp >= {interval_start}::DateTime64+ AND pd._timestamp < {interval_end}::DateTime64+ )+ AND NOT (+ p._timestamp >= {interval_start}::DateTime64+ AND p._timestamp < {interval_end}::DateTime64+ ),+ pd._timestamp,+ (+ p._timestamp >= {interval_start}::DateTime64+ AND p._timestamp < {interval_end}::DateTime64+ )+ AND NOT (+ pd._timestamp >= {interval_start}::DateTime64+ AND pd._timestamp < {interval_end}::DateTime64+ ),+ p._timestamp,+ least(p._timestamp, pd._timestamp)+ ) AS _inserted_at+ FROM+ person p+ INNER JOIN latest_distinct_ids pd+ ON p.id = pd.person_id2+ WHERE+ p.team_id = {team_id}::Int64+ AND (p.id, p.version, p._timestamp) in latest_person_versions+ ORDER BY+ _inserted_at+) AS persons+FORMAT ArrowStream+SETTINGS+ max_bytes_before_external_group_by=50000000000,+ max_bytes_before_external_sort=50000000000,+ optimize_aggregation_in_order=1+"""+++EXPORT_TO_S3_FROM_PERSONS = Template("""+INSERT INTO FUNCTION $s3_function+SELECT+ persons.team_id AS team_id,+ persons.distinct_id AS distinct_id,+ persons.person_id AS person_id,+ persons.properties AS properties,+ persons.person_distinct_id_version AS person_distinct_id_version,+ persons.person_version AS person_version,+ persons.created_at AS created_at,+ persons._inserted_at AS _inserted_at,+ persons.is_deleted AS is_deleted+FROM (+ WITH new_persons AS (+ SELECT+ id+ FROM+ person+ WHERE+ team_id = {team_id}::Int64+ AND id in (+ SELECT+ id+ FROM+ person+ WHERE+ team_id = {team_id}::Int64+ AND _timestamp >= {interval_start}::DateTime64+ AND _timestamp < {interval_end}::DateTime64+ )+ GROUP BY+ id+ HAVING+ argMax(_timestamp, person.version) >= {interval_start}::DateTime64+ AND argMax(_timestamp, person.version) < {interval_end}::DateTime64+ ),+ distinct_ids AS (+ -- new distinct_ids+ SELECT+ distinct_id+ FROM+ person_distinct_id2+ WHERE+ team_id = {team_id}::Int64+ AND distinct_id in (+ SELECT+ distinct_id+ FROM+ person_distinct_id2+ WHERE+ team_id = {team_id}::Int64+ AND _timestamp >= {interval_start}::DateTime64+ AND _timestamp < {interval_end}::DateTime64+ )+ GROUP BY+ distinct_id+ HAVING+ argMax(_timestamp, person_distinct_id2.version) >= {interval_start}::DateTime64+ AND argMax(_timestamp, person_distinct_id2.version) < {interval_end}::DateTime64++ UNION DISTINCT++ -- existing distinct_ids for new/updated persons+ SELECT+ DISTINCT distinct_id+ FROM+ person_distinct_id2+ WHERE+ team_id = {team_id}::Int64+ AND person_id IN new_persons+ ),+ latest_distinct_ids AS (+ SELECT+ distinct_id,+ argMax(person_id, person_distinct_id2.version) AS person_id2,+ max(version) AS version,+ argMax(_timestamp, person_distinct_id2.version) AS _timestamp+ FROM+ person_distinct_id2+ WHERE+ team_id = {team_id}::Int64+ AND distinct_id IN distinct_ids+ GROUP BY+ distinct_id+ $filter_distinct_ids+ ),+ latest_person_versions AS (+ SELECT+ id,+ max(version) AS version,+ max(_timestamp) AS _timestamp+ FROM+ person+ WHERE+ team_id = {team_id}::Int64+ AND+ id IN (+ SELECT+ DISTINCT person_id2+ FROM+ latest_distinct_ids+ )+ GROUP BY+ id+ )+ SELECT+ p.team_id AS team_id,+ pd.distinct_id AS distinct_id,+ toString(pd.person_id2) AS person_id,+ p.version AS person_version,+ pd.version AS person_distinct_id_version,+ p.properties AS properties,+ p.created_at AS created_at,+ toBool(p.is_deleted) AS is_deleted,+ multiIf(+ (+ pd._timestamp >= {interval_start}::DateTime64+ AND pd._timestamp < {interval_end}::DateTime64+ )+ AND NOT (+ p._timestamp >= {interval_start}::DateTime64+ AND p._timestamp < {interval_end}::DateTime64+ ),+ pd._timestamp,+ (+ p._timestamp >= {interval_start}::DateTime64+ AND p._timestamp < {interval_end}::DateTime64+ )+ AND NOT (+ pd._timestamp >= {interval_start}::DateTime64+ AND pd._timestamp < {interval_end}::DateTime64+ ),+ p._timestamp,+ least(p._timestamp, pd._timestamp)+ ) AS _inserted_at+ FROM+ person p+ INNER JOIN latest_distinct_ids pd+ ON p.id = pd.person_id2+ WHERE+ p.team_id = {team_id}::Int64+ AND (p.id, p.version, p._timestamp) in latest_person_versions+) AS persons+SETTINGS+ max_bytes_before_external_group_by=50000000000,+ max_bytes_before_external_sort=50000000000,+ optimize_aggregation_in_order=1,+ log_comment={log_comment}+""")+++SELECT_FROM_PERSONS_BACKFILL = """+SELECT+ pd.team_id AS team_id,+ pd.distinct_id AS distinct_id,+ toString(p.id) AS person_id,+ p.properties AS properties,+ pd.version AS person_distinct_id_version,+ p.version AS person_version,+ p.created_at AS created_at,+ toBool(p.is_deleted) AS is_deleted,+ multiIf(+ pd._timestamp < {interval_end}::DateTime64+ AND NOT p._timestamp < {interval_end}::DateTime64,+ pd._timestamp,+ p._timestamp < {interval_end}::DateTime64+ AND NOT pd._timestamp < {interval_end}::DateTime64,+ p._timestamp,+ least(p._timestamp, pd._timestamp)+ ) AS _inserted_at+FROM (+ SELECT+ team_id,+ distinct_id,+ max(version) AS version,+ argMax(person_id, person_distinct_id2.version) AS person_id,+ argMax(_timestamp, person_distinct_id2.version) AS _timestamp+ FROM+ person_distinct_id2+ PREWHERE+ team_id = {team_id}::Int64+ GROUP BY+ team_id,+ distinct_id+) AS pd+INNER JOIN (+ SELECT+ team_id,+ id,+ max(version) AS version,+ argMax(properties, person.version) AS properties,+ argMax(created_at, person.version) AS created_at,+ argMax(_timestamp, person.version) AS _timestamp,+ argMax(is_deleted, person.version) AS is_deleted+ FROM+ person+ PREWHERE+ team_id = {team_id}::Int64+ GROUP BY+ team_id,+ id+) AS p ON p.id = pd.person_id AND p.team_id = pd.team_id+WHERE+ pd.team_id = {team_id}::Int64+ AND p.team_id = {team_id}::Int64+ AND (+ pd._timestamp < {interval_end}::DateTime64+ OR p._timestamp < {interval_end}::DateTime64+ )+ORDER BY+ _inserted_at+FORMAT ArrowStream+SETTINGS+ max_bytes_before_external_group_by=50000000000,+ max_bytes_before_external_sort=50000000000,+ optimize_aggregation_in_order=1+"""+++EXPORT_TO_S3_FROM_PERSONS_BACKFILL = Template("""+INSERT INTO FUNCTION $s3_function+SELECT+ pd.team_id AS team_id,+ pd.distinct_id AS distinct_id,+ toString(p.id) AS person_id,+ p.properties AS properties,+ pd.version AS person_distinct_id_version,+ p.version AS person_version,+ p.created_at AS created_at,+ toBool(p.is_deleted) AS is_deleted,+ multiIf(+ pd._timestamp < {interval_end}::DateTime64+ AND NOT p._timestamp < {interval_end}::DateTime64,+ pd._timestamp,+ p._timestamp < {interval_end}::DateTime64+ AND NOT pd._timestamp < {interval_end}::DateTime64,+ p._timestamp,+ least(p._timestamp, pd._timestamp)+ ) AS _inserted_at+FROM (+ SELECT+ team_id,+ distinct_id,+ max(version) AS version,+ argMax(person_id, person_distinct_id2.version) AS person_id,+ argMax(_timestamp, person_distinct_id2.version) AS _timestamp+ FROM+ person_distinct_id2+ PREWHERE+ team_id = {team_id}::Int64+ GROUP BY+ team_id,+ distinct_id+) AS pd+INNER JOIN (+ SELECT+ team_id,+ id,+ max(version) AS version,+ argMax(properties, person.version) AS properties,+ argMax(created_at, person.version) AS created_at,+ argMax(_timestamp, person.version) AS _timestamp,+ argMax(is_deleted, person.version) AS is_deleted+ FROM+ person+ PREWHERE+ team_id = {team_id}::Int64+ GROUP BY+ team_id,+ id+) AS p ON p.id = pd.person_id AND p.team_id = pd.team_id+WHERE+ pd.team_id = {team_id}::Int64+ AND p.team_id = {team_id}::Int64+ AND (+ pd._timestamp < {interval_end}::DateTime64+ OR p._timestamp < {interval_end}::DateTime64+ )+SETTINGS+ max_bytes_before_external_group_by=50000000000,+ max_bytes_before_external_sort=50000000000,+ optimize_aggregation_in_order=1,+ log_comment={log_comment}+""")diff --git a/products/batch_exports/backend/temporal/sql/sessions.py b/products/batch_exports/backend/temporal/sql/sessions.pynew file mode 100644index 000000000000..81f3e4e275dd--- /dev/null+++ b/products/batch_exports/backend/temporal/sql/sessions.py@@ -0,0 +1,61 @@+"""SQL for the sessions batch export model."""++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr++from products.batch_exports.backend.temporal.sql.common import HogQLQueryBatchExportSettings++SELECT_FROM_SESSIONS_HOGQL = ast.SelectQuery(+ select=[+ parse_expr("session_id as session_id"),+ parse_expr("toString(session_id_v7) as session_id_v7"),+ parse_expr("team_id"),+ parse_expr("distinct_id as distinct_id"),+ parse_expr("$start_timestamp as start_timestamp"),+ parse_expr("$end_timestamp as end_timestamp"),+ parse_expr("$urls as urls"),+ parse_expr("$num_uniq_urls as num_uniq_urls"),+ parse_expr("$entry_current_url as entry_current_url"),+ parse_expr("$entry_pathname as entry_pathname"),+ parse_expr("$entry_hostname as entry_hostname"),+ parse_expr("$end_current_url as end_current_url"),+ parse_expr("$end_pathname as end_pathname"),+ parse_expr("$end_hostname as end_hostname"),+ parse_expr("$entry_utm_source as entry_utm_source"),+ parse_expr("$entry_utm_campaign as entry_utm_campaign"),+ parse_expr("$entry_utm_medium as entry_utm_medium"),+ parse_expr("$entry_utm_term as entry_utm_term"),+ parse_expr("$entry_utm_content as entry_utm_content"),+ parse_expr("$entry_referring_domain as entry_referring_domain"),+ parse_expr("$entry_gclid as entry_gclid"),+ parse_expr("$entry_fbclid as entry_fbclid"),+ parse_expr("$entry_gad_source as entry_gad_source"),+ parse_expr("$pageview_count as pageview_count"),+ parse_expr("$autocapture_count as autocapture_count"),+ parse_expr("$screen_count as screen_count"),+ parse_expr("$channel_type as channel_type"),+ parse_expr("$session_duration as session_duration"),+ parse_expr("duration as duration"),+ parse_expr("$is_bounce as is_bounce"),+ parse_expr("$last_external_click_url as last_external_click_url"),+ parse_expr("$page_screen_autocapture_count_up_to as page_screen_autocapture_count_up_to"),+ 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"),+ parse_expr("$entry_gclsrc as entry_gclsrc"),+ parse_expr("$entry_dclid as entry_dclid"),+ parse_expr("$entry_gbraid as entry_gbraid"),+ parse_expr("$entry_wbraid as entry_wbraid"),+ parse_expr("$entry_msclkid as entry_msclkid"),+ parse_expr("$entry_twclid as entry_twclid"),+ parse_expr("$entry_li_fat_id as entry_li_fat_id"),+ parse_expr("$entry_mc_cid as entry_mc_cid"),+ parse_expr("$entry_igshid as entry_igshid"),+ parse_expr("$entry_ttclid as entry_ttclid"),+ parse_expr("$entry__kx as entry__kx"),+ parse_expr("$entry_irclid as entry_irclid"),+ ],+ select_from=ast.JoinExpr(table=ast.Field(chain=["sessions"])),+ settings=HogQLQueryBatchExportSettings(),+)