: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(bigquery-batch-export): New storage stream API consumer (#65854)
Tomás Farías Santanaaa2f59857bd4
diff --git a/posthog/settings/batch_exports.py b/posthog/settings/batch_exports.pyindex a656e22c8c5d..2cb2c49929e7 100644--- a/posthog/settings/batch_exports.py+++ b/posthog/settings/batch_exports.py@@ -26,6 +26,10 @@ BATCH_EXPORT_BIGQUERY_RECORD_BATCH_QUEUE_MAX_SIZE_BYTES: int = get_from_env(BATCH_EXPORT_BIGQUERY_USE_MULTIPLE_CONSUMERS_TEAM_IDS: list[str] = get_list(os.getenv("BATCH_EXPORT_BIGQUERY_USE_MULTIPLE_CONSUMERS_TEAM_IDS", ""))+BATCH_EXPORT_BIGQUERY_USE_STORAGE_STREAM_API_TEAM_IDS: list[str] = get_list(+ os.getenv("BATCH_EXPORT_BIGQUERY_USE_STORAGE_STREAM_API_TEAM_IDS", "")+)+BATCH_EXPORT_BIGQUERY_MAX_CONSUMERS: int = get_from_env("BATCH_EXPORT_BIGQUERY_MAX_CONSUMERS", 5, type_cast=int)BATCH_EXPORT_BIGQUERY_SERVICE_ACCOUNT: str = get_from_env("BATCH_EXPORT_BIGQUERY_SERVICE_ACCOUNT", "")BATCH_EXPORT_BIGQUERY_STS_AUDIENCE_FIELD: str = get_from_env("BATCH_EXPORT_BIGQUERY_STS_AUDIENCE_FIELD", "")diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.pyindex b2cc5aa37969..04bb17c43896 100644--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py@@ -4,12 +4,14 @@ import timeimport typingimport asyncioimport datetime as dt+import functoolsimport contextlibimport dataclassesimport collections.abcfrom django.conf import settings+import grpcimport boto3import pyarrow as paimport requests@@ -29,8 +31,11 @@ from google.api_core.exceptions import (ServiceUnavailable,TooManyRequests,)-from google.cloud import bigquery, iam_admin_v1+from google.cloud import bigquery, bigquery_storage_v1, iam_admin_v1from google.cloud.bigquery.table import RowIterator, _EmptyRowIterator+from google.cloud.bigquery_storage_v1 import types+from google.cloud.bigquery_storage_v1.services.big_query_write.transports import BigQueryWriteGrpcTransport+from google.cloud.bigquery_storage_v1.writer import AppendRowsStreamfrom google.oauth2 import service_accountfrom structlog.contextvars import bind_contextvarsfrom temporalio import activity, workflow@@ -66,6 +71,7 @@ from products.batch_exports.backend.temporal.pipeline.transformer import (ParquetStreamTransformer,PipelineTransformer,SchemaTransformer,+ SerializedStreamTransformer,)from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult, reduce_batch_export_resultsfrom products.batch_exports.backend.temporal.spmc import (@@ -108,6 +114,17 @@ NON_RETRYABLE_ERROR_TYPES = (LOGGER = get_write_only_logger(__name__)EXTERNAL_LOGGER = get_logger("EXTERNAL")++def _cast_to_lossless_timestamp(arr: pa.Array, *, unit: typing.Literal["s", "us", "ms", "ns"]) -> pa.Array:+ """Create a new timestamp array with an adjusted unit if the conversion is lossless."""+ return arr.cast(pa.timestamp(unit, tz="UTC"), safe=True)+++def _cast_as_type(arr: pa.Array, *, type: pa.DataType) -> pa.Array:+ """Wrapper around an array's cast."""+ return arr.cast(type, safe=True)++FileFormat = typing.Literal["Parquet", "JSONLines"]BigQueryTypeName = typing.Literal["JSON",@@ -1140,6 +1157,97 @@ class BigQueryConsumer(Consumer):self.current_buffer = io.BytesIO()+class BigQueryStorageConsumer(Consumer):+ """Consume serialized record batch bytes to a BigQuery storage stream."""++ def __init__(+ self,+ client: BigQueryClient,+ table: BigQueryTable,+ transformer: SerializedStreamTransformer,+ model: str = "events",+ ):+ super().__init__(model=model)+ channel = BigQueryWriteGrpcTransport.create_channel(+ compression=grpc.Compression.Gzip,+ )+ transport = BigQueryWriteGrpcTransport(channel=channel)+ self.write_client = bigquery_storage_v1.BigQueryWriteClient(+ credentials=client.sync_client._credentials,+ transport=transport,+ )+ self.stream: AppendRowsStream | None = None++ self.transformer = transformer+ self.table = table+ self.logger = self.logger.bind(table=self.table)++ async def consume_chunk(self, data: bytes) -> None:+ """Directly consume chunk by sending it on the stream."""+ if not data:+ return++ self.logger.debug(+ "Send to stream starting",+ )+ try:+ await asyncio.to_thread(self.send_data, data)+ except Exception:+ self.logger.exception("Send to stream failed")+ await self.close_stream()+ raise++ self.logger.debug(+ "Send to stream finished",+ )++ def send_data(self, data: bytes) -> None:+ """Actually send the data, this is blocking."""+ req = types.AppendRowsRequest()+ req.arrow_rows.rows.serialized_record_batch = data++ stream = self.stream or self.start_stream()++ send = stream.send(req)+ return send.result()++ def start_stream(self) -> AppendRowsStream:+ """Start an append rows stream."""+ stream_name = (+ f"projects/{self.table.project_id}/datasets/{self.table.dataset_id}/tables/{self.table.name}/_default"+ )+ template = types.AppendRowsRequest()+ template.write_stream = stream_name+ template.arrow_rows.writer_schema.serialized_schema = self.transformer.schema.serialize().to_pybytes()+ self.stream = AppendRowsStream(self.write_client, template)+ return self.stream++ async def close_stream(self) -> None:+ """Close open stream, if any."""+ if not self.stream:+ return++ try:+ await asyncio.to_thread(self.stream.close)+ self.stream = None+ except bigquery_storage_v1.exceptions.StreamClosedError:+ # Stream was already closed, so nothing to do here.+ self.stream = None+ except Exception:+ self.logger.exception("Stream close failed")+ raise++ async def finalize_file(self) -> None:+ """No files here, just serialized bytes."""+ # TODO: Make consumer a protocol so we don't need this.+ pass++ async def finalize(self) -> None:+ """Finalize by closing the stream and underlying client."""+ await self.close_stream()+ await asyncio.to_thread(self.write_client.transport.close)++async def run_consumers(client: BigQueryClient,table: BigQueryTable,@@ -1149,42 +1257,69 @@ async def run_consumers(can_perform_merge: bool,max_consumers: int,model: str = "events",+ use_storage_stream: bool = False,) -> BatchExportResult:tasks = []max_file_size_bytes_per_consumer = settings.BATCH_EXPORT_BIGQUERY_UPLOAD_CHUNK_SIZE_BYTES // max_consumersasync with asyncio.TaskGroup() as tg:for _ in range(max_consumers):- consumer = BigQueryConsumer(- client=client,- table=table,- file_format=file_format,- model=model,- )-- if can_perform_merge:+ if use_storage_stream:+ serialized = SerializedStreamTransformer()transformer: ChunkTransformerProtocol = PipelineTransformer(transformers=(SchemaTransformer(table=table,+ extra_compatible_types={+ # BigQuery Storage requires INTEGER columns be signed+ # Cast is safe and will throw on overflow.+ (pa.uint64(), pa.int64()): functools.partial(_cast_as_type, type=pa.int64()),+ (pa.uint8(), pa.int64()): functools.partial(_cast_as_type, type=pa.int64()),+ # BigQuery Storage requires that TIMESTAMP columns be 'us'+ (pa.timestamp("ms", tz="UTC"), pa.timestamp("us", tz="UTC")): functools.partial(+ _cast_to_lossless_timestamp, unit="us"+ ),+ },),- ParquetStreamTransformer(- compression="zstd",- max_file_size_bytes=max_file_size_bytes_per_consumer,- ),+ serialized,))+ consumer: Consumer = BigQueryStorageConsumer(+ client=client,+ table=table,+ transformer=serialized,+ model=model,+ )else:- transformer = PipelineTransformer(- transformers=(- SchemaTransformer(- table=table,- ),- JSONLStreamTransformer(- max_file_size_bytes=max_file_size_bytes_per_consumer,- ),- )+ consumer = BigQueryConsumer(+ client=client,+ table=table,+ file_format=file_format,+ model=model,)+ if can_perform_merge:+ transformer = PipelineTransformer(+ transformers=(+ SchemaTransformer(+ table=table,+ ),+ ParquetStreamTransformer(+ compression="zstd",+ max_file_size_bytes=max_file_size_bytes_per_consumer,+ ),+ )+ )+ else:+ transformer = PipelineTransformer(+ transformers=(+ SchemaTransformer(+ table=table,+ ),+ JSONLStreamTransformer(+ max_file_size_bytes=max_file_size_bytes_per_consumer,+ ),+ )+ )tasks.append(tg.create_task(@@ -1437,41 +1572,73 @@ async def insert_into_bigquery_activity_from_stage(inputs: BigQueryInsertInputs)) as bigquery_consumer_table:file_format: typing.Literal["Parquet", "JSONLines"] = "Parquet" if can_perform_merge else "JSONLines"+ use_storage_stream = (+ str(inputs.team_id) in settings.BATCH_EXPORT_BIGQUERY_USE_STORAGE_STREAM_API_TEAM_IDS+ )+if str(inputs.team_id) not in settings.BATCH_EXPORT_BIGQUERY_USE_MULTIPLE_CONSUMERS_TEAM_IDS:# This just repeats what's in `run_consumers` to preserve backwards compatibility# while testing.# TODO: Remove this or the else block after we have tested out whether multiple# consumers are viable.- consumer = BigQueryConsumer(+ consumer: Consumer = BigQueryConsumer(client=bq_client,table=bigquery_consumer_table,file_format=file_format,model=model.name if isinstance(model, BatchExportModel) else "events",)- if can_perform_merge:+ if use_storage_stream:+ serialized = SerializedStreamTransformer()transformer: ChunkTransformerProtocol = PipelineTransformer(transformers=(SchemaTransformer(table=bigquery_consumer_table,+ extra_compatible_types={+ # BigQuery Storage requires INTEGER columns be signed+ # Cast is safe and will throw on overflow.+ (pa.uint64(), pa.int64()): functools.partial(_cast_as_type, type=pa.int64()),+ (pa.uint8(), pa.int64()): functools.partial(_cast_as_type, type=pa.int64()),+ # BigQuery Storage requires that TIMESTAMP columns be 'us'+ (pa.timestamp("ms", tz="UTC"), pa.timestamp("us", tz="UTC")): functools.partial(+ _cast_to_lossless_timestamp, unit="us"+ ),+ },),- ParquetStreamTransformer(- compression="zstd",- max_file_size_bytes=settings.BATCH_EXPORT_BIGQUERY_UPLOAD_CHUNK_SIZE_BYTES,- ),+ serialized,))++ consumer = BigQueryStorageConsumer(+ client=bq_client,+ table=bigquery_consumer_table,+ transformer=serialized,+ model=model.name if isinstance(model, BatchExportModel) else "events",+ )else:- transformer = PipelineTransformer(- transformers=(- SchemaTransformer(- table=bigquery_consumer_table,- ),- JSONLStreamTransformer(- max_file_size_bytes=settings.BATCH_EXPORT_BIGQUERY_UPLOAD_CHUNK_SIZE_BYTES,- ),+ if can_perform_merge:+ transformer = PipelineTransformer(+ transformers=(+ SchemaTransformer(+ table=bigquery_consumer_table,+ ),+ ParquetStreamTransformer(+ compression="zstd",+ max_file_size_bytes=settings.BATCH_EXPORT_BIGQUERY_UPLOAD_CHUNK_SIZE_BYTES,+ ),+ )+ )+ else:+ transformer = PipelineTransformer(+ transformers=(+ SchemaTransformer(+ table=bigquery_consumer_table,+ ),+ JSONLStreamTransformer(+ max_file_size_bytes=settings.BATCH_EXPORT_BIGQUERY_UPLOAD_CHUNK_SIZE_BYTES,+ ),+ ))- )result = await run_consumer_from_stage(queue=queue,@@ -1492,6 +1659,7 @@ async def insert_into_bigquery_activity_from_stage(inputs: BigQueryInsertInputs)can_perform_merge=can_perform_merge,max_consumers=settings.BATCH_EXPORT_BIGQUERY_MAX_CONSUMERS,model=model.name if isinstance(model, BatchExportModel) else "events",+ use_storage_stream=use_storage_stream,)if can_perform_merge:diff --git a/products/batch_exports/backend/temporal/pipeline/transformer.py b/products/batch_exports/backend/temporal/pipeline/transformer.pyindex f0092d75c5f6..35ac356370ca 100644--- a/products/batch_exports/backend/temporal/pipeline/transformer.py+++ b/products/batch_exports/backend/temporal/pipeline/transformer.py@@ -722,6 +722,74 @@ class CSVStreamTransformer:return buffer.getvalue()+class SerializedStreamTransformer:+ """A transformer to serialize record batches into Arrow IPC format."""++ def __init__(+ self,+ include_inserted_at: bool = False,+ max_file_size_bytes: int = 0,+ ):+ self.include_inserted_at = include_inserted_at+ self.max_file_size_bytes = max_file_size_bytes+ self._schema: pa.Schema | None = None++ async def iter(+ self, record_batches: collections.abc.AsyncIterable[pa.RecordBatch]+ ) -> collections.abc.AsyncIterator[Chunk]:+ """Iterate over record batches transforming them into chunks."""+ current_file_size = 0++ async for record_batch in record_batches:+ self.schema = record_batch.schema++ with ExecutionTimeRecorder(+ "serialized_transformer_record_batch_transform_duration",+ description="Duration to serialize a record batch.",+ log_message=(+ "Serialized record batch with %(num_records)d records."+ " Record batch size: %(mb_processed).2f MB, process time:"+ " %(duration_seconds)d seconds, speed: %(mb_per_second).2f MB/s"+ ),+ log_attributes={"num_records": record_batch.num_rows},+ ) as recorder:+ recorder.add_bytes_processed(record_batch.nbytes)+ # The entire Arrow C++ call is not GIL-free, but enough of it+ # seems to be for it to be worth to spawn a thread here, based+ # on tests with 64MiB batches.+ buf = await asyncio.to_thread(record_batch.select(self.schema.names).serialize)+ chunk = buf.to_pybytes() # We need bytes downstream+ del buf # Free buf on the next gc run++ yield Chunk(chunk, False)++ if self.max_file_size_bytes and current_file_size + len(chunk) > self.max_file_size_bytes:+ yield Chunk(b"", True)+ current_file_size = 0++ else:+ current_file_size += len(chunk)++ yield Chunk(b"", True)++ @property+ def schema(self) -> pa.Schema:+ if not self._schema:+ raise ValueError("Schema not set, is the transformer running?")+ return self._schema++ @schema.setter+ def schema(self, schema: pa.Schema) -> None:+ if self._schema is not None:+ return++ if not self.include_inserted_at:+ if (index := schema.get_field_index("_inserted_at")) >= 0:+ schema = schema.remove(index)++ self._schema = schema++class IncompatibleTypesError(TypeError):"""Exception for incompatible types between source and destination.diff --git a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_activity.py b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_activity.pyindex cea274868c4c..e0c24f664fc4 100644--- a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_activity.py+++ b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_activity.py@@ -2,6 +2,7 @@import uuidimport datetime as dt+import dataclassesimport collections.abcimport pytest@@ -498,6 +499,9 @@ async def test_insert_into_bigquery_activity_from_stage_merges_persons_data_in_ftimestamp=old_person["_timestamp"],)+ activity_environment.info = dataclasses.replace(+ activity_environment.info, attempt=activity_environment.info.attempt + 1+ )await _run_activity(activity_environment,bigquery_client=bigquery_client,@@ -574,6 +578,9 @@ async def test_insert_into_bigquery_activity_from_stage_merges_sessions_data_in_insert_sessions=True,)+ activity_environment.info = dataclasses.replace(+ activity_environment.info, attempt=activity_environment.info.attempt + 1+ )result = await _run_activity(activity_environment,bigquery_client=bigquery_client,@@ -679,6 +686,9 @@ async def test_insert_into_bigquery_activity_from_stage_handles_person_new_columtimestamp=old_person["_timestamp"],)+ activity_environment.info = dataclasses.replace(+ activity_environment.info, attempt=activity_environment.info.attempt + 1+ )# this time we don't expected there to be a created_at columnexpected_fields = [field for field in EXPECTED_PERSONS_BATCH_EXPORT_FIELDS if field != "created_at"]await _run_activity(@@ -756,6 +766,9 @@ async def test_insert_into_bigquery_activity_from_stage_handles_datetime_to_int()_ = query_job.result()+ activity_environment.info = dataclasses.replace(+ activity_environment.info, attempt=activity_environment.info.attempt + 1+ )await _run_activity(activity_environment,bigquery_client=bigquery_client,