: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): free bigquery load buffers after each load job (#117168)
Tom Owersd8e899158950
diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.pyindex 36c91eed386a..7e4c671f30f6 100644--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py@@ -19,6 +19,7 @@ import google.auth.exceptionsimport google.auth.transport.requestsimport google.auth.impersonated_credentialsfrom google.api_core.exceptions import (+ BadGateway,BadRequest,DeadlineExceeded,Forbidden,@@ -27,6 +28,7 @@ from google.api_core.exceptions import (InternalServerError,NotFound,PermissionDenied,+ RetryError,ServiceUnavailable,TooManyRequests,)@@ -109,6 +111,23 @@ NON_RETRYABLE_ERROR_TYPES = ("BigQueryIncompatibleSchemaError",)+# Errors that only mean we could not read a load job's state. `RetryError` is raised when the+# client's own retries for these errors run out.+LOAD_JOB_POLL_RETRYABLE_EXCEPTIONS = (+ RetryError,+ TooManyRequests,+ InternalServerError,+ BadGateway,+ ServiceUnavailable,+ GatewayTimeout,+ DeadlineExceeded,+ ConnectionError,+ requests.exceptions.ConnectionError,+ requests.exceptions.Timeout,+ requests.exceptions.ChunkedEncodingError,+ google.auth.exceptions.TransportError,+)+LOGGER = get_write_only_logger(__name__)EXTERNAL_LOGGER = get_logger("EXTERNAL")@@ -1037,7 +1056,7 @@ class BigQueryClient:)return await query_job(merge_query)- async def load_file(self, file, format: FileFormat, table: BigQueryTable):+ async def load_file(self, file, format: FileFormat, table: BigQueryTable, poll_interval: float = 1.0):"""Load a file into BigQuery table."""schema = tuple(field.to_destination_field() for field in table.fields)if format == "Parquet":@@ -1070,7 +1089,7 @@ class BigQueryClient:while True:try:- result = await asyncio.to_thread(self._run_load_job, file, bq_table, job_config=job_config)+ result = await self._run_load_job(file, bq_table, job_config=job_config, poll_interval=poll_interval)except (TooManyRequests,ServiceUnavailable,@@ -1166,14 +1185,57 @@ class BigQueryClient:else:return result- def _run_load_job(self, file, bq_table, job_config):+ async def _run_load_job(self, file, bq_table, job_config, poll_interval: float):"""Run a BigQuery LoadJob and return its result.- This method blocks and should only be run on an executor.+ We poll the job ourselves and only call `LoadJob.result()` once the job is done.+ While a job runs, `result()` polls through google-api-core's retry loop, which raises+ an exception on every poll and keeps each one in a list. The exception tracebacks and+ that list form a reference cycle that keeps the calling frames, and so `file`, alive+ until the cyclic garbage collector runs. With large files, this holds gigabytes of+ memory that the activity does not use.+ """+ load_job = await asyncio.to_thread(+ self.sync_client.load_table_from_file, file, bq_table, job_config=job_config, rewind=True+ )++ await self._wait_for_load_job(load_job, poll_interval=poll_interval)++ return load_job.result() # Non-blocking: Job is done.++ async def _wait_for_load_job(self, load_job: bigquery.LoadJob, poll_interval: float) -> None:+ """Poll a LoadJob until it is done.++ A transient error while polling does not mean that the job failed, so we retry it forever.+ If the error reached `load_file`, it would upload the file again and start a second load+ job, which can load the same rows twice."""- load_job = self.sync_client.load_table_from_file(file, bq_table, job_config=job_config, rewind=True)- result = load_job.result()- return result+ initial_retry = 1+ backoff_factor = 2+ max_retry = 32+ attempt = 0++ while True:+ try:+ done = await asyncio.to_thread(load_job.done)+ except LOAD_JOB_POLL_RETRYABLE_EXCEPTIONS:+ backoff = min(max_retry, initial_retry * (backoff_factor**attempt))+ self.logger.warning(+ "Transient error while polling LoadJob",+ job_id=load_job.job_id,+ attempt=attempt,+ backoff=backoff,+ exc_info=True,+ )+ await asyncio.sleep(backoff)+ attempt += 1+ continue++ if done:+ return++ attempt = 0+ await asyncio.sleep(poll_interval)class MissingRequiredPermissionsError(Exception):@@ -1260,6 +1322,8 @@ class BigQueryConsumer(Consumer):buffer_size=buffer_size,)+ # Release buffer in case a reference is kept by anybody else+ self.current_buffer.close()self.current_buffer = io.BytesIO()diff --git a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_client.py b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_client.pyindex d608cdf5224f..c6ff294e7ecb 100644--- a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_client.py+++ b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_client.py@@ -1,9 +1,26 @@+import gc+import ioimport randomimport string+import asyncio+import weakref+import collections.abcimport pytest-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patch+import pyarrow as pa+import requests+import google.auth.exceptions+from google.api_core.exceptions import (+ Forbidden,+ GatewayTimeout,+ InternalServerError,+ NotFound,+ RetryError,+ ServiceUnavailable,+ TooManyRequests,+)from google.cloud import bigqueryfrom posthog.models.integration.google_cloud import InvalidGoogleTokenUriError@@ -75,6 +92,100 @@ async def test_execute_query_pending_timeout(states_sequence: list[str], should_assert result == mock_result+def _make_load_test_client(+ reload_outcomes: collections.abc.Sequence[str | Exception],+) -> tuple[BigQueryClient, BigQueryTable, list[int]]:+ mock_sync_client = MagicMock()+ mock_sync_client.project = "test-project"++ load_job = bigquery.LoadJob(+ "test-job-id", None, bigquery.TableReference.from_string("test-project.dataset.table"), mock_sync_client+ )+ load_job._properties["status"] = {"state": "RUNNING"}+ outcomes = iter(reload_outcomes)++ def reload(*args, **kwargs):+ outcome = next(outcomes)+ if isinstance(outcome, Exception):+ raise outcome+ load_job._set_properties({**load_job._properties, "status": {"state": outcome}})++ load_job.reload = reload # type: ignore+ uploads: list[int] = []++ # A plain function rather than a MagicMock, because a mock keeps the file alive in `call_args`.+ def load_table_from_file(file, *args, **kwargs):+ uploads.append(len(file.read()))+ return load_job++ mock_sync_client.load_table_from_file = load_table_from_file++ table = BigQueryTable.from_arrow_schema(+ pa.schema([pa.field("event", pa.string())]),+ project_id="test-project",+ dataset_id="dataset",+ table_id="table",+ primary_key=(),+ version_key=(),+ )+ return BigQueryClient(mock_sync_client), table, uploads++[email protected]("reloads_until_done", [1, 3])+async def test_load_file_does_not_keep_file_alive_after_load(reloads_until_done: int):+ client, table, _ = _make_load_test_client(["RUNNING"] * (reloads_until_done - 1) + ["DONE"])+ file = io.BytesIO(b"x" * 1024)+ file_ref = weakref.ref(file)++ gc.disable()+ try:+ await client.load_file(file, format="Parquet", table=table, poll_interval=0.01)+ del file++ assert file_ref() is None+ finally:+ gc.enable()+++ "reload_outcomes,expected_exception",+ [+ ([ServiceUnavailable("unavailable"), "RUNNING", "DONE"], None),+ ([GatewayTimeout("timeout"), TooManyRequests("slow down"), "DONE"], None),+ ([RetryError("deadline exceeded", cause=InternalServerError("internal")), "DONE"], None),+ ([requests.exceptions.ConnectionError("reset"), requests.exceptions.Timeout("timeout"), "DONE"], None),+ ([google.auth.exceptions.TransportError("token refresh failed"), "DONE"], None),+ ([NotFound("job not found")], NotFound),+ (["RUNNING", Forbidden("forbidden")], Forbidden),+ ],+ ids=[+ "service_unavailable",+ "gateway_timeout_then_too_many_requests",+ "client_retries_exhausted",+ "requests_connection_errors",+ "auth_transport_error",+ "not_found_raises",+ "forbidden_raises",+ ],+)+async def test_load_file_retries_transient_poll_errors_without_uploading_again(+ reload_outcomes: list[str | Exception], expected_exception: type[Exception] | None+):+ client, table, uploads = _make_load_test_client(reload_outcomes)+ real_sleep = asyncio.sleep++ with patch("asyncio.sleep", side_effect=lambda delay: real_sleep(0)):+ if expected_exception is None:+ await client.load_file(io.BytesIO(b"x"), format="Parquet", table=table, poll_interval=0.01)+ else:+ with pytest.raises(expected_exception):+ await client.load_file(io.BytesIO(b"x"), format="Parquet", table=table, poll_interval=0.01)++ assert len(uploads) == 1++@SKIP_IF_MISSING_GOOGLE_APPLICATION_CREDENTIALS@pytest.mark.asyncio@pytest.mark.parametrize(