Skip to content

: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.

fix(batch-exports): cancel the staging query when we stop waiting for it (#83260)

Rosse29ae05481de
diff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
index 693481582e2c..86f3451b707c 100644
--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py
+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py
@@ -701,22 +701,53 @@ async def _execute_query(
query_id = str(uuid.uuid4())
logger = LOGGER.bind(query_id=query_id)
with log_query_duration(logger=logger, query_id=query_id, query_type="insert_into_internal_stage"):
- try:
- summary = await client.execute_query_with_summary(
- query, query_parameters=query_parameters, query_id=query_id, timeout=300, settings=query_settings
- )
- except ClickHouseClientTimeoutError:
- logger.warning(
- "Timed-out waiting for insert into S3. Will attempt to check query status and wait for completion",
- timeout=300,
- )
- await _wait_for_query_completion(client, query_id)
- # The summary is gone with the timed-out response, but the query has finished, so
- # recover the written-row count from its query log entry.
- return await client.aget_written_rows_from_query_log(query_id)
+ async with _kill_query_on_cancellation(client, query_id):
+ try:
+ summary = await client.execute_query_with_summary(
+ query, query_parameters=query_parameters, query_id=query_id, timeout=300, settings=query_settings
+ )
+ except ClickHouseClientTimeoutError:
+ logger.warning(
+ "Timed-out waiting for insert into S3. Will attempt to check query status and wait for completion",
+ timeout=300,
+ )
+ await _wait_for_query_completion(client, query_id)
+ # The summary is gone with the timed-out response, but the query has finished, so
+ # recover the written-row count from its query log entry.
+ return await client.aget_written_rows_from_query_log(query_id)
return _written_rows_from_summary(summary)
+@asynccontextmanager
+async def _kill_query_on_cancellation(client: ClickHouseClient, query_id: str) -> typing.AsyncIterator[None]:
+ """Kill `query_id` if we are cancelled while waiting on it.
+
+ Dropping the connection does not stop an INSERT: `cancel_http_readonly_queries_on_client_close`
+ is enabled on our cluster but covers only reads, and ClickHouse currently offers no INSERT
+ equivalent. Without an explicit kill the query keeps writing to the stage until its own
+ execution time limit, despite us no longer waiting on it.
+
+ The kill is best-effort. It is timeout-bounded so a slow ClickHouse cannot hold up our exit, and
+ a kill that fails is logged rather than raised so it cannot replace the `CancelledError` we are
+ handling — a cancelled run must still be recorded as cancelled, not as a failure. Being cancelled
+ again abandons the attempt, which is deliberate: the kill cannot outlive the client.
+ """
+ logger = LOGGER.bind(query_id=query_id)
+ try:
+ yield
+ except asyncio.CancelledError:
+ logger.warning("Cancelled while waiting for insert into S3. Attempting to cancel the query")
+ try:
+ await asyncio.wait_for(client.acancel_query(query_id), timeout=30)
+ except asyncio.CancelledError:
+ logger.warning("Cancelled again while cancelling query")
+ except TimeoutError:
+ logger.warning("Timed out cancelling query", timeout=30)
+ except Exception:
+ logger.warning("Failed to cancel query after cancellation", exc_info=True)
+ raise
+
+
async def _wait_for_query_completion(client: ClickHouseClient, query_id: str) -> None:
"""Wait for the query to complete by checking the query log and process list.
diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
index e7a9e9c37ab9..528c65aeeb0f 100644
--- a/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
@@ -384,6 +384,68 @@ async def test_execute_query_recovers_written_rows_from_query_log_on_timeout(que
client.aget_written_rows_from_query_log.assert_awaited_once()
[email protected]("timed_out_first", [False, True], ids=["while_awaiting_query", "while_waiting_for_completion"])
+async def test_execute_query_cancels_the_query_when_cancelled(timed_out_first: bool):
+ """Test that on cancellation, we cancel the insert instead of leaving it running.
+
+ Dropping the connection does not stop an INSERT: `cancel_http_readonly_queries_on_client_close`
+ is enabled on our cluster but covers only reads, and ClickHouse currently offers no INSERT
+ equivalent. Without an explicit kill the query keeps writing to the stage until its own
+ execution time limit, despite us no longer waiting on it.
+
+ Covers cancellation both while awaiting the query's response and while polling for it to
+ finish after the response timed out.
+ """
+ started = asyncio.Event()
+
+ async def block_forever(*args, **kwargs):
+ started.set()
+ await asyncio.Event().wait()
+
+ client = AsyncMock()
+ if timed_out_first:
+ client.execute_query_with_summary.side_effect = ClickHouseClientTimeoutError("INSERT ...", "test-query-id")
+ client.acheck_query.side_effect = block_forever
+ else:
+ client.execute_query_with_summary.side_effect = block_forever
+
+ task = asyncio.create_task(_execute_query(client, "INSERT INTO FUNCTION s3(...) SELECT ...", {}))
+ await started.wait()
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ client.acancel_query.assert_awaited_once()
+ # The kill has to target the query we started, which is the id the insert was sent with.
+ query_id = client.execute_query_with_summary.await_args.kwargs["query_id"]
+ assert client.acancel_query.await_args.args == (query_id,)
+
+
+async def test_execute_query_still_cancels_when_the_kill_fails():
+ """If our attempt to cancel the query fails, we still need to ensure we propagate the
+ CancelledError.
+ """
+ started = asyncio.Event()
+
+ async def block_forever(*args, **kwargs):
+ started.set()
+ await asyncio.Event().wait()
+
+ client = AsyncMock()
+ client.execute_query_with_summary.side_effect = block_forever
+ client.acancel_query.side_effect = ClickHouseClientTimeoutError("KILL ...", "test-query-id")
+
+ task = asyncio.create_task(_execute_query(client, "INSERT INTO FUNCTION s3(...) SELECT ...", {}))
+ await started.wait()
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ client.acancel_query.assert_awaited_once()
+
+
class PersonToExport(t.TypedDict):
team_id: int
person_id: str