: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(batch-exports): Close async write client in BigQuery (#66947)
Tomás Farías Santanadc8603aa953b
diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.pyindex 24c9fc784735..e81c5f41c504 100644--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py@@ -1167,7 +1167,8 @@ _RETRYABLE_STATUS = {_RETRYABLE_CODES = {s.value[0] for s in _RETRYABLE_STATUS}-def get_bigquery_write_async_client(credentials) -> BigQueryWriteAsyncClient:+async def bigquery_write_async_client(credentials) -> collections.abc.AsyncIterator[BigQueryWriteAsyncClient]:"""Create a new BigQuery storage write async client."""channel = BigQueryWriteGrpcAsyncIOTransport.create_channel(credentials=credentials,@@ -1177,7 +1178,11 @@ def get_bigquery_write_async_client(credentials) -> BigQueryWriteAsyncClient:client = BigQueryWriteAsyncClient(transport=transport,)- return client++ try:+ yield client+ finally:+ await transport.close()class BigQueryStorageConsumer(Consumer):@@ -1681,13 +1686,6 @@ async def insert_into_bigquery_activity_from_stage(inputs: BigQueryInsertInputs)# while testing.# TODO: Remove this or the else block after we have tested out whether multiple# consumers are viable.- consumer: Consumer = BigQueryConsumer(- client=bq_client,- table=bigquery_consumer_table,- file_format=file_format,- model=model.name if isinstance(model, BatchExportModel) else "events",- )-if use_storage_stream:serialized = SerializedStreamTransformer()transformer: ChunkTransformerProtocol = PipelineTransformer(@@ -1713,14 +1711,31 @@ async def insert_into_bigquery_activity_from_stage(inputs: BigQueryInsertInputs)))- write_client = get_bigquery_write_async_client(bq_client.sync_client._credentials)- consumer = BigQueryStorageConsumer(- client=write_client,+ async with bigquery_write_async_client(bq_client.sync_client._credentials) as write_client:+ consumer: Consumer = BigQueryStorageConsumer(+ client=write_client,+ table=bigquery_consumer_table,+ transformer=serialized,+ model=model.name if isinstance(model, BatchExportModel) else "events",+ )++ result = await run_consumer_from_stage(+ queue=queue,+ producer_task=producer_task,+ consumer=consumer,+ transformer=transformer,+ json_columns=(),+ records_total=inputs.records_total,+ )++ else:+ consumer = BigQueryConsumer(+ client=bq_client,table=bigquery_consumer_table,- transformer=serialized,+ file_format=file_format,model=model.name if isinstance(model, BatchExportModel) else "events",)- else:+if can_perform_merge:transformer = PipelineTransformer(transformers=(@@ -1745,26 +1760,26 @@ async def insert_into_bigquery_activity_from_stage(inputs: BigQueryInsertInputs)))- result = await run_consumer_from_stage(- queue=queue,- producer_task=producer_task,- consumer=consumer,- transformer=transformer,- json_columns=(),- records_total=inputs.records_total,- )+ result = await run_consumer_from_stage(+ queue=queue,+ producer_task=producer_task,+ consumer=consumer,+ transformer=transformer,+ json_columns=(),+ records_total=inputs.records_total,+ )else:if use_storage_stream:- write_client = get_bigquery_write_async_client(bq_client.sync_client._credentials)- result = await run_storage_stream_consumers(- client=write_client,- table=bigquery_consumer_table,- producer_task=producer_task,- queue=queue,- max_consumers=settings.BATCH_EXPORT_BIGQUERY_MAX_CONSUMERS,- model=model.name if isinstance(model, BatchExportModel) else "events",- )+ async with bigquery_write_async_client(bq_client.sync_client._credentials) as write_client:+ result = await run_storage_stream_consumers(+ client=write_client,+ table=bigquery_consumer_table,+ producer_task=producer_task,+ queue=queue,+ max_consumers=settings.BATCH_EXPORT_BIGQUERY_MAX_CONSUMERS,+ model=model.name if isinstance(model, BatchExportModel) else "events",+ )else:result = await run_consumers(client=bq_client,diff --git a/products/batch_exports/backend/temporal/pipeline/transformer.py b/products/batch_exports/backend/temporal/pipeline/transformer.pyindex 35ac356370ca..0b02e8405a65 100644--- a/products/batch_exports/backend/temporal/pipeline/transformer.py+++ b/products/batch_exports/backend/temporal/pipeline/transformer.py@@ -754,10 +754,8 @@ class SerializedStreamTransformer: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)++ buf = record_batch.select(self.schema.names).serialize()chunk = buf.to_pybytes() # We need bytes downstreamdel buf # Free buf on the next gc run