: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
feat(batch-exports): export created_at to Databricks (#89666)
Luke Baber62d369719c5a
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/destinations/databricks.tsx b/frontend/src/scenes/data-pipelines/batch-exports/destinations/databricks.tsxindex edd8fb92c445..2e5b5e19fc8c 100644--- a/frontend/src/scenes/data-pipelines/batch-exports/destinations/databricks.tsx+++ b/frontend/src/scenes/data-pipelines/batch-exports/destinations/databricks.tsx@@ -25,6 +25,12 @@ export const databricksDefinition: DestinationDefinition = {schema_valid: true,},...PERSON_PROPERTIES_EVENT_FIELD,+ created_at: {+ name: 'created_at',+ hogql_value: 'created_at',+ type: 'datetime',+ schema_valid: true,+ },databricks_ingested_timestamp: {name: 'databricks_ingested_timestamp',hogql_value: 'NOW64()',diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.pyindex 194a37422a88..aab73795a19c 100644--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py@@ -938,6 +938,9 @@ def databricks_default_fields() -> list[BatchExportField]:concerned about supporting legacy fields for backwards compatibility."""batch_export_fields = events_model_default_fields()+ # `timestamp` comes from the client, whereas `created_at` is set server-side at ingestion, so+ # users get an event time they can rely on.+ batch_export_fields.append({"expression": "created_at", "alias": "created_at"})# add a metadata field for the ingested timestamp to aid with debugging# (this is not strictly the time the data is ingested into Databricks but rather the time we query it from ClickHouse)batch_export_fields.append({"expression": "NOW64()", "alias": "databricks_ingested_timestamp"})@@ -1005,6 +1008,25 @@ def _get_databricks_fields_from_record_schema(return databricks_schema+def _events_table_fields(json_type: str) -> list[DatabricksField]:+ """Return the Databricks columns for the events model with the default schema.++ Must stay in sync with the fields `databricks_default_fields` queries, minus `_inserted_at`,+ which only tracks progress and is never exported.+ """+ return [+ ("uuid", "STRING"),+ ("event", "STRING"),+ ("properties", json_type),+ ("person_properties", json_type),+ ("distinct_id", "STRING"),+ ("team_id", "BIGINT"),+ ("timestamp", "TIMESTAMP"),+ ("created_at", "TIMESTAMP"),+ ("databricks_ingested_timestamp", "TIMESTAMP"),+ ]++class TableSettings(t.NamedTuple):table_fields: list[DatabricksField]record_batch_schema: pa.Schema@@ -1035,17 +1057,22 @@ def _get_databricks_table_settings(json_type = "STRING"known_variant_columns = []- if model is None or (isinstance(model, BatchExportModel) and model.name == "events"):- table_fields = [- ("uuid", "STRING"),- ("event", "STRING"),- ("properties", json_type),- ("person_properties", json_type),- ("distinct_id", "STRING"),- ("team_id", "BIGINT"),- ("timestamp", "TIMESTAMP"),- ("databricks_ingested_timestamp", "TIMESTAMP"),- ]+ if model is None or (isinstance(model, BatchExportModel) and model.name == "events" and model.schema is None):+ table_fields = _events_table_fields(json_type)++ # Staging and copying are two activities, so a deploy of a schema change between them could+ # leave the staged files a version behind this list. Outside that window the two lists+ # always match, because the staging query is built from the same+ # `databricks_default_fields`.+ staged_columns = set(record_batch_schema.names)+ missing_columns = [name for name, _ in table_fields if name not in staged_columns]+ if missing_columns:+ LOGGER.warning("Skipping columns absent from the staged data: %s", missing_columns)+ staged_fields = [field for field in table_fields if field[0] in staged_columns]+ # Keeping the full list is better than a `CREATE TABLE` with no columns, which cannot+ # run at all. Sharing no column with the staged data means something else is wrong.+ if staged_fields:+ table_fields = staged_fieldselse:table_fields = _get_databricks_fields_from_record_schema(record_batch_schema,diff --git a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_utils.py b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_utils.pyindex 93198e872745..cbf6d39e389f 100644--- a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_utils.py@@ -2,7 +2,15 @@ import datetime as dtimport pytest-from products.batch_exports.backend.temporal.destinations.databricks_batch_export import _get_long_running_query_timeout+import pyarrow as pa++from products.batch_exports.backend.service import BatchExportModel, BatchExportSchema+from products.batch_exports.backend.temporal.destinations.databricks_batch_export import (+ _events_table_fields,+ _get_databricks_table_settings,+ _get_long_running_query_timeout,+ databricks_default_fields,+)@pytest.mark.parametrize(@@ -20,3 +28,50 @@ from products.batch_exports.backend.temporal.destinations.databricks_batch_expor)def test_get_long_running_query_timeout(data_interval_start, data_interval_end, expected_timeout):assert _get_long_running_query_timeout(data_interval_start, data_interval_end) == expected_timeout+++def _staged_events_schema(column_names: list[str]) -> pa.Schema:+ # Only the column names are asserted on below, so the types here are arbitrary.+ return pa.schema([pa.field(name, pa.string()) for name in column_names])+++def _events_table_field_names(staged_column_names: list[str], schema: BatchExportSchema | None) -> list[str]:+ table_fields, _, _ = _get_databricks_table_settings(+ model=BatchExportModel(name="events", schema=schema),+ record_batch_schema=_staged_events_schema(staged_column_names),+ use_variant_type=True,+ )+ return [name for name, _ in table_fields]+++def test_events_table_fields_match_the_exported_fields():+ # The fields we query and the table columns we create are two separate literals. Adding to the+ # first alone drops the column from the user's table; adding to the second alone builds a+ # CREATE TABLE and a COPY INTO naming a column the staged data has no value for.+ # `_inserted_at` only tracks progress and is never exported.+ exported = sorted(field["alias"] for field in databricks_default_fields() if field["alias"] != "_inserted_at")++ assert sorted(name for name, _ in _events_table_fields("VARIANT")) == exported+++def test_events_table_fields_drop_columns_missing_from_staged_data():+ # A run that staged its data before `created_at` was added has no such column to copy, so+ # dropping it keeps the copy working instead of wedging the run on a retry loop.+ staged = [field["alias"] for field in databricks_default_fields() if field["alias"] != "created_at"]++ assert "created_at" not in _events_table_field_names(staged, schema=None)+++def test_events_table_fields_follow_a_custom_schema():+ # A custom schema stages only the columns it selects, so the table has to follow the staged+ # data. Starting from the default events columns instead loses every column outside them, such+ # as `browser` here, and names columns the staged files have no value for.+ schema: BatchExportSchema = {+ "fields": [+ {"expression": "event", "alias": "event"},+ {"expression": "nullIf(JSONExtractString(properties, %(hogql_val_0)s), '')", "alias": "browser"},+ ],+ "values": {"hogql_val_0": "$browser"},+ }++ assert _events_table_field_names(["event", "browser"], schema=schema) == ["event", "browser"]diff --git a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_workflow.pyindex ee938debfb6e..0de4f6a2cc96 100644--- a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_workflow.py+++ b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_workflow.py@@ -388,6 +388,7 @@ class TestDatabricksBatchExportWorkflow(CommonWorkflowTests):("distinct_id", "STRING"),("team_id", "BIGINT"),("timestamp", "TIMESTAMP"),+ ("created_at", "TIMESTAMP"),("databricks_ingested_timestamp", "TIMESTAMP"),],id="events-missing-person_properties",diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambrindex 17d46f5c097e..017f23c3892b 100644--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr@@ -34,7 +34,7 @@e.`$window_id` AS `$window_id`,if(equals(e.event, 'user signed up'), 1, 0) AS step_0,if(equals(e.event, 'user did things'), 1, 0) AS step_1,- ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,+ ([e__person.properties___fish] AS value) AS prop_basic,prop_basic AS propFROM events AS eLEFT OUTER JOIN@@ -44,6 +44,16 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))GROUP BY aggregation_targetHAVING ifNull(greaterOrEquals(step_reached, 0), 0))@@ -111,7 +121,17 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))GROUP BY aggregation_targetHAVING ifNull(greaterOrEquals(step_reached, 0), 0))GROUP BY breakdown@@ -168,8 +188,8 @@e.uuid AS uuid,e.`$session_id` AS `$session_id`,e.`$window_id` AS `$window_id`,- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1+ if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_0,+ if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_1FROM events AS eLEFT OUTER JOIN(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,@@ -178,6 +198,16 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))GROUP BY aggregation_targetHAVING ifNull(greaterOrEquals(step_reached, 0), 0))@@ -294,7 +324,24 @@(SELECT count() AS total,toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)@@ -326,7 +373,24 @@(SELECT count() AS total,toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)