: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): add per-query resource limits to HogQL batch exports (#83261)
Ross06528282bdba
diff --git a/posthog/settings/batch_exports.py b/posthog/settings/batch_exports.pyindex f5c46ab94441..0beeeff02b93 100644--- a/posthog/settings/batch_exports.py+++ b/posthog/settings/batch_exports.py@@ -141,3 +141,16 @@ BATCH_EXPORTS_FILE_DOWNLOAD_REGION: str = os.getenv("BATCH_EXPORTS_FILE_DOWNLOADBATCH_EXPORTS_FILE_DOWNLOAD_EXPIRATION_SECONDS: int = get_from_env("BATCH_EXPORTS_FILE_DOWNLOAD_EXPIRATION_SECONDS", 3600, type_cast=int)++# Per-query ClickHouse resource limits for HogQL-powered batch exports.+# Since we accept arbitrary user-supplied queries, we need to set conservative limits to avoid+# monopolising the offline cluster.+BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME: int = get_from_env(+ "BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME", 900, type_cast=int+) # 15 minutes (deliberately under the file-download stage timeout of 20 minutes)+BATCH_EXPORT_HOGQL_MAX_MEMORY_USAGE: int = get_from_env(+ "BATCH_EXPORT_HOGQL_MAX_MEMORY_USAGE", 50 * 1000 * 1000 * 1000, type_cast=int+) # 50GB (rather arbitrary for now, can always increase later)+BATCH_EXPORT_HOGQL_MAX_BYTES_TO_READ: int = get_from_env(+ "BATCH_EXPORT_HOGQL_MAX_BYTES_TO_READ", 200 * 1000 * 1000 * 1000, type_cast=int+) # 200GB (again, rather arbitrary for now)diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.pyindex fb8efa5e1d09..37a7b47291af 100644--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py@@ -73,6 +73,7 @@ DEFAULT_MAX_STAGE_RETRY_INTERVAL_SECONDS = 600STAGE_NON_RETRYABLE_ERROR_TYPES = ("InvalidFilterError","DataIntervalEndInFutureError",+ "HogQLQueryResourceLimitExceededError",)@@ -146,6 +147,14 @@ def _get_status_for_activity_error(error: exceptions.ActivityError) -> BatchExpoif isinstance(error.cause, exceptions.CancelledError):return BatchExportRun.Status.CANCELLED+ if isinstance(error.cause, exceptions.ApplicationError) and error.cause.type in STAGE_NON_RETRYABLE_ERROR_TYPES:+ return BatchExportRun.Status.FAILED++ # Reaching this outside tests means one of two assumptions broke, so `finish_batch_export_run`+ # logs it. Callers pass `maximum_attempts=0` with no schedule-to-close or run timeout, so a+ # retryable error (or activity timeout) retries forever and never surfaces here; and a terminal+ # error from the destination activity comes back as a `BatchExportResult` with `error_repr`+ # rather than raising. That leaves `TEST`, which forces `maximum_attempts=1`.return BatchExportRun.Status.FAILED_RETRYABLEdiff --git a/products/batch_exports/backend/temporal/pipeline/internal_stage.py b/products/batch_exports/backend/temporal/pipeline/internal_stage.pyindex 86f3451b707c..ae650621c842 100644--- a/products/batch_exports/backend/temporal/pipeline/internal_stage.py+++ b/products/batch_exports/backend/temporal/pipeline/internal_stage.py@@ -33,13 +33,17 @@ from posthog.temporal.common.clickhouse import (ClickHouseClient,ClickHouseClientTimeoutError,ClickHouseError,+ ClickHouseMemoryLimitExceededError,ClickHouseQueryNotFound,ClickHouseQueryStatus,+ ClickHouseQueryTimeoutError,+ ClickHouseTooManyBytesError,get_client,)from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_write_only_logger+from products.batch_exports.backend.models.batch_export import BatchExportfrom products.batch_exports.backend.service import (BackfillDetails,BatchExportField,@@ -83,6 +87,58 @@ class DataIntervalEndInFutureError(Exception):super().__init__(f"The provided 'data_interval_end' ({data_interval_end.isoformat()}) is in the future")+class HogQLQueryResourceLimitExceededError(Exception):+ """A user's HogQL batch export query exceeded a per-query ClickHouse resource limit.++ Raised in place of the ClickHouse error so the workflow treats it as non-retryable (see the+ stage activity's `non_retryable_error_types`): re-running the query unchanged would fail again.++ Only raised for the `hogql` model. The fixed models keep their ClickHouse errors and stay+ retryable, since their queries are ours and any failures are our responsibility to address.+ """+++def _raise_on_hogql_resource_limit_error(exc: ClickHouseError, model_name: str) -> None:+ """Re-raise a per-query resource limit breach as an error the workflow will not retry.++ Returns for anything else, leaving the caller to re-raise the original and stay retryable.++ The message we raise replaces the ClickHouse error rather than adding to it: the real one may+ contain internal details that we should not expose to the user, plus we want to ensure we return+ a user-friendly error.++ Raises:+ HogQLQueryResourceLimitExceededError: If a `hogql` export's query exceeded a per-query limit.+ """+ if model_name != BatchExport.Model.HOGQL:+ return++ if isinstance(exc, ClickHouseQueryTimeoutError):+ limit_message = (+ "The batch export query took too long to run. Simplifying it, or exporting a shorter date range may help."+ )+ elif isinstance(exc, ClickHouseTooManyBytesError):+ limit_message = (+ "The batch export query read too much data. Selecting fewer columns, or exporting a shorter date "+ "range may help."+ )+ # The memory class also covers the shared ClickHouse user's budget and the whole server's, neither of which+ # is this query's fault. Therefore, we only consider query memory limit errors as non-retryable.+ # Since we're matching based on strings, this is rather fragile. We have an automated test in+ # products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py which runs+ # against a real ClickHouse server in order to help catch any regressions.+ elif isinstance(exc, ClickHouseMemoryLimitExceededError) and "query memory limit exceeded" in str(exc).lower():+ limit_message = (+ "The batch export query needed too much memory to run. Aggregating over fewer rows, or exporting a "+ "shorter date range may help."+ )+ else:+ return++ LOGGER.warning("HogQL query exceeded a per-query resource limit", error=str(exc))+ raise HogQLQueryResourceLimitExceededError(limit_message) from exc++def _is_local_dev_or_test() -> bool:return settings.DEBUG or settings.TEST@@ -251,6 +307,7 @@ async def insert_into_internal_stage_activity("""bind_contextvars(team_id=inputs.team_id,+ batch_export_id=inputs.batch_export_id,data_interval_start=inputs.data_interval_start,data_interval_end=inputs.data_interval_end,)@@ -314,17 +371,21 @@ async def insert_into_internal_stage_activity()query_or_model = query- records_total = await _write_batch_export_record_batches_to_internal_stage(- query_or_model=query_or_model,- full_range=full_range,- query_parameters=query_parameters,- team_id=inputs.team_id,- batch_export_id=inputs.batch_export_id,- data_interval_start=inputs.data_interval_start,- data_interval_end=inputs.data_interval_end,- s3_staging_folder_url=s3_staging_folder.url,- num_partitions=num_partitions,- )+ try:+ records_total = await _write_batch_export_record_batches_to_internal_stage(+ query_or_model=query_or_model,+ full_range=full_range,+ query_parameters=query_parameters,+ team_id=inputs.team_id,+ batch_export_id=inputs.batch_export_id,+ data_interval_start=inputs.data_interval_start,+ data_interval_end=inputs.data_interval_end,+ s3_staging_folder_url=s3_staging_folder.url,+ num_partitions=num_partitions,+ )+ except ClickHouseError as e:+ _raise_on_hogql_resource_limit_error(e, model_name)+ raiselogger.info("Staging data completed successfully", records_total=records_total)return InternalStageResult(stage_folder=s3_staging_folder.folder, records_total=records_total)@@ -759,12 +820,13 @@ async def _wait_for_query_completion(client: ClickHouseClient, query_id: str) ->ClickHouseError: If the query were are trying to check has failed."""logger = LOGGER.bind(query_id=query_id)- num_attempts = 5- # Sometimes this check can fail, especially when ClickHouse is under heavy load, so we retry a few times+ num_attempts = 10+ # This check can fail while ClickHouse is under heavy load, plus it can also take a while for+ # queries to be flushed to the query_log, so we retry a few times, over a period of time.check_query = make_retryable_with_exponential_backoff(client.acheck_query,max_attempts=num_attempts,- max_retry_delay=1,+ max_retry_delay=5,retryable_exceptions=(ClickHouseQueryNotFound, ClickHouseCheckQueryStatusError),)diff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.pyindex 2739df9edeac..e5ccc8f74837 100644--- a/products/batch_exports/backend/temporal/record_batch_model.py+++ b/products/batch_exports/backend/temporal/record_batch_model.py@@ -25,7 +25,11 @@ from products.batch_exports.backend.hogql_source import ()from products.batch_exports.backend.service import BatchExportModel, BatchExportSchemafrom products.batch_exports.backend.temporal.metrics import log_query_duration-from products.batch_exports.backend.temporal.sql.common import HogQLQueryBatchExportSettings, get_s3_function_call+from products.batch_exports.backend.temporal.sql.common import (+ BatchExportQuerySettings,+ get_s3_function_call,+ get_user_hogql_batch_export_query_settings,+)from products.batch_exports.backend.temporal.sql.sessions import SELECT_FROM_SESSIONS_HOGQL, SESSIONS_LOOKBACK_DAYSLOGGER = get_write_only_logger()@@ -279,7 +283,7 @@ class SessionsRecordBatchModel(RecordBatchModel):],select_from=ast.JoinExpr(table=ast.Field(chain=["sessions"])),where=where_and,- settings=HogQLQueryBatchExportSettings(),+ settings=BatchExportQuerySettings(),)async def get_backfill_info(@@ -376,7 +380,7 @@ class HogQLQueryRecordBatchModel(RecordBatchModel):# Sent with the request instead of set on the query AST, because the user query may# not parse to a simple `ast.SelectQuery` (e.g. a UNION parses to an# `ast.SelectSetQuery`, which has no `settings` field to attach these to).- return _as_clickhouse_request_settings(HogQLQueryBatchExportSettings())+ return _as_clickhouse_request_settings(get_user_hogql_batch_export_query_settings())def resolve_batch_exports_model(diff --git a/products/batch_exports/backend/temporal/sql/common.py b/products/batch_exports/backend/temporal/sql/common.pyindex 3b0d96f42c5e..8498ac80f4d3 100644--- a/products/batch_exports/backend/temporal/sql/common.py+++ b/products/batch_exports/backend/temporal/sql/common.py@@ -1,3 +1,7 @@+import typing++from django.conf import settings+from posthog.hogql.constants import HogQLQuerySettingsfrom posthog.credentials import AWSKeyPair@@ -25,7 +29,44 @@ def get_s3_function_call(s3_folder: str, credentials: AWSKeyPair | None, num_parPARTITION BY rand() %% {num_partitions}"""-class HogQLQueryBatchExportSettings(HogQLQuerySettings):+class BatchExportQuerySettings(HogQLQuerySettings):optimize_aggregation_in_order: bool | None = Truemax_bytes_before_external_sort: int | None = 50000000000max_bytes_before_external_group_by: int | None = 50000000000+++class UserHogQLBatchExportQuerySettings(BatchExportQuerySettings):+ """Settings for a batch export powered by an arbitrary user-supplied HogQL query.++ User-supplied queries are a lot more unpredictable than our own queries for+ events/persons/sessions, so we need to set some resource limits to prevent them consuming all+ available resources, which could negatively impact other batch exports.+ """++ max_execution_time: int | None = None+ max_memory_usage: int | None = None++ # These are ClickHouse's own defaults but we pin them here just to be sure (setting them to+ # 'break' for example would allow for queries to return partial data on failure).+ read_overflow_mode: typing.Literal["throw", "break"] | None = "throw"+ timeout_overflow_mode: typing.Literal["throw", "break"] | None = "throw"+ # Must be 0 or the absolute `max_bytes_before_external_*` thresholds do nothing: a non-zero ratio+ # (0.5 by default) measures against *available server* memory instead, which on a large node sits+ # far above any per-query cap.+ max_bytes_ratio_before_external_sort: float | None = 0.0+ max_bytes_ratio_before_external_group_by: float | None = 0.0+++def get_user_hogql_batch_export_query_settings() -> UserHogQLBatchExportQuerySettings:+ """Build the user-query settings, reading Django settings at call time so `@override_settings` works."""+ max_memory_usage = settings.BATCH_EXPORT_HOGQL_MAX_MEMORY_USAGE+ # Spill sorts and aggregations to disk at this share of the query's memory cap. Halfway leaves room+ # to finish the spilled work within the cap.+ spill_after_bytes = int(max_memory_usage * 0.5)+ return UserHogQLBatchExportQuerySettings(+ max_execution_time=settings.BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME,+ max_memory_usage=max_memory_usage,+ max_bytes_before_external_sort=spill_after_bytes,+ max_bytes_before_external_group_by=spill_after_bytes,+ max_bytes_to_read=settings.BATCH_EXPORT_HOGQL_MAX_BYTES_TO_READ,+ )diff --git a/products/batch_exports/backend/temporal/sql/sessions.py b/products/batch_exports/backend/temporal/sql/sessions.pyindex 51a6e9ead8d1..673329ae52f4 100644--- a/products/batch_exports/backend/temporal/sql/sessions.py+++ b/products/batch_exports/backend/temporal/sql/sessions.py@@ -5,7 +5,7 @@ import datetime as dtfrom posthog.hogql import astfrom posthog.hogql.parser import parse_expr-from products.batch_exports.backend.temporal.sql.common import HogQLQueryBatchExportSettings+from products.batch_exports.backend.temporal.sql.common import BatchExportQuerySettings# max_inserted_at is only available since around end of 2025. Before# that, it is the zero value (unix epoch). We use greatest to pick@@ -72,5 +72,5 @@ SELECT_FROM_SESSIONS_HOGQL = ast.SelectQuery(parse_expr("$entry_irclid as entry_irclid"),],select_from=ast.JoinExpr(table=ast.Field(chain=["sessions"])),- settings=HogQLQueryBatchExportSettings(),+ settings=BatchExportQuerySettings(),)diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py b/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.pyindex 6c7a38629856..514aaae80950 100644--- a/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_entrypoint.py@@ -4,6 +4,7 @@ import datetime as dtfrom dataclasses import dataclassimport pytest+from unittest.mock import AsyncMock, patchfrom django.conf import settings@@ -15,6 +16,7 @@ from temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.clickhouse import ClickHouseMemoryLimitExceededErrorfrom posthog.temporal.tests.utils.models import afetch_batch_export_runsfrom products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination@@ -265,6 +267,54 @@ class TestErrorHandling:assert run.status == "FailedRetryable"assert run.latest_error == "DummyRetryableError: This is an unexpected internal error"+ # A real per-query memory-limit failure, in the form the ClickHouse client raises it+ _QUERY_MEMORY_ERROR = ClickHouseMemoryLimitExceededError(+ "Code: 241. DB::Exception: Query memory limit exceeded: would use 30.01 GiB "+ "(attempt to allocate chunk of 4.00 MiB), maximum: 30.00 GiB. (MEMORY_LIMIT_EXCEEDED)"+ )++ async def test_hogql_queries_fail_terminally_if_per_query_resource_limit_reached(self, batch_export):+ """A user-supplied HogQL query that hits a per-query ClickHouse resource limit should be+ fail as a non-retryable error (re-running it would not produce a different result).+ """+ inputs = DummyExportInputs(+ team_id=batch_export.team_id,+ batch_export_id=str(batch_export.id),+ interval="hour",+ data_interval_end=dt.datetime(2025, 7, 21, 13, 0, 0, tzinfo=dt.UTC).isoformat(),+ batch_export_model=BatchExportModel(+ name="hogql", schema=None, hogql_query="SELECT event AS event FROM events"+ ),+ )+ with patch(+ "products.batch_exports.backend.temporal.pipeline.internal_stage._write_batch_export_record_batches_to_internal_stage",+ new=AsyncMock(side_effect=self._QUERY_MEMORY_ERROR),+ ):+ run = await self._run_workflow(inputs, expect_workflow_failure=True)++ assert run.status == "Failed"+ assert run.latest_error is not None+ assert "The batch export query needed too much memory to run" in run.latest_error++ async def test_per_query_resource_limit_only_applies_to_hogql(self, batch_export):+ """The identical ClickHouse error under a fixed model stays retryable, unchanged."""+ inputs = DummyExportInputs(+ team_id=batch_export.team_id,+ batch_export_id=str(batch_export.id),+ interval="hour",+ data_interval_end=dt.datetime(2025, 7, 21, 13, 0, 0, tzinfo=dt.UTC).isoformat(),+ batch_export_model=BatchExportModel(name="events", schema=None),+ )+ with patch(+ "products.batch_exports.backend.temporal.pipeline.internal_stage._write_batch_export_record_batches_to_internal_stage",+ new=AsyncMock(side_effect=self._QUERY_MEMORY_ERROR),+ ):+ run = await self._run_workflow(inputs, expect_workflow_failure=True)++ # In reality, we would never set the status to FailedRetryable as the activity has no retry+ # limit; our tests run with RetryPolicy(maximum_attempts=1) however.+ assert run.status == "FailedRetryable"+async def test_successful_run(self, batch_export_by_interval, interval):inputs = DummyExportInputs(team_id=batch_export_by_interval.team_id,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.pyindex 528c65aeeb0f..cc588d41641d 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@@ -1,3 +1,4 @@+import reimport jsonimport uuidimport random@@ -20,7 +21,13 @@ from temporalio.testing import ActivityEnvironmentfrom posthog.models.scoping import team_scopefrom posthog.models.utils import uuid7from posthog.sync import database_sync_to_async-from posthog.temporal.common.clickhouse import ClickHouseClient, ClickHouseClientTimeoutError, ClickHouseQueryStatus+from posthog.temporal.common.clickhouse import (+ ClickHouseClient,+ ClickHouseClientTimeoutError,+ ClickHouseError,+ ClickHouseQueryStatus,+ get_client,+)from posthog.temporal.tests.utils.events import (generate_test_events,insert_event_values_in_clickhouse,@@ -37,7 +44,9 @@ from products.batch_exports.backend.service import BackfillDetails, BatchExportMfrom products.batch_exports.backend.temporal.pipeline.internal_stage import (BatchExportInsertIntoInternalStageInputs,DataIntervalEndInFutureError,+ HogQLQueryResourceLimitExceededError,_execute_query,+ _raise_on_hogql_resource_limit_error,_write_batch_export_record_batches_to_internal_stage,compute_num_partitions,insert_into_internal_stage_activity,@@ -446,6 +455,116 @@ async def test_execute_query_still_cancels_when_the_kill_fails():client.acancel_query.assert_awaited_once()+def _as_clickhouse_error(message: str) -> ClickHouseError:+ """Build the exception the ClickHouse client would raise for this error message."""+ try:+ ClickHouseClient.raise_clickhouse_error(message)+ except ClickHouseError as e:+ return e+++def _limit_message_for(exc: ClickHouseError) -> str | None:+ """The message a hogql export would fail with for `exc`, or None if it is left retryable."""+ try:+ _raise_on_hogql_resource_limit_error(exc, "hogql")+ except HogQLQueryResourceLimitExceededError as e:+ return str(e)+ return None+++ "message,expected",+ [+ # A query's own memory budget: this query alone was too big, so it cannot succeed on retry.+ (+ "Code: 241. DB::Exception: Query memory limit exceeded: would use 30.01 GiB "+ "(attempt to allocate chunk of 4.00 MiB), maximum: 30.00 GiB. (MEMORY_LIMIT_EXCEEDED)",+ "needed too much memory",+ ),+ # A shared user's budget or the whole server's: not this query's fault, so leave it retryable.+ (+ "Code: 241. DB::Exception: User memory limit exceeded: would use 5.02 MiB, "+ "maximum: 976.56 KiB. (MEMORY_LIMIT_EXCEEDED)",+ None,+ ),+ (+ "Code: 241. DB::Exception: (total) memory limit exceeded: would use 99.97 GiB, "+ "maximum: 111.19 GiB. (MEMORY_LIMIT_EXCEEDED)",+ None,+ ),+ # Query timeout and bytes-read need no scope check: their error class is enough.+ (+ "Code: 159. DB::Exception: Timeout exceeded: elapsed 900.372 seconds, maximum: 900. (TIMEOUT_EXCEEDED)",+ "took too long",+ ),+ (+ "Code: 307. DB::Exception: Limit for rows or bytes to read exceeded, max bytes: 1.00 TiB. (TOO_MANY_BYTES)",+ "read too much data",+ ),+ # A result-size limit (a different code we don't impose) must not be mistaken for bytes-read.+ (+ "Code: 396. DB::Exception: Limit for result exceeded, max rows: 10.00, "+ "current rows: 10.00 thousand. (TOO_MANY_ROWS_OR_BYTES)",+ None,+ ),+ # An unrelated failure is not a resource limit, so it stays retryable.+ ("Code: 60. DB::Exception: Table default.nope does not exist. (UNKNOWN_TABLE)", None),+ ],+ ids=[+ "query_memory",+ "user_memory",+ "total_memory",+ "timeout",+ "too_many_bytes",+ "result_rows_or_bytes",+ "unrelated",+ ],+)+def test_raise_on_hogql_resource_limit_error(message: str, expected: str | None):+ """Each per-query resource limit gets its own message; everything else is left retryable."""+ limit_message = _limit_message_for(_as_clickhouse_error(message))++ if expected is None:+ assert limit_message is None+ else:+ assert limit_message is not None+ assert expected in limit_message+++def test_raise_on_hogql_resource_limit_error_ignores_other_models():+ """A fixed model's query keeps its ClickHouse error, however that error was classified."""+ exc = _as_clickhouse_error(+ "Code: 241. DB::Exception: Query memory limit exceeded: would use 30.01 GiB, "+ "maximum: 30.00 GiB. (MEMORY_LIMIT_EXCEEDED)"+ )++ _raise_on_hogql_resource_limit_error(exc, "events")+++async def test_raise_on_hogql_resource_limit_error_matches_real_clickhouse_memory_limit():+ """The per-query memory wording the detector relies on is real, checked against a live server.++ Memory scope is the one limit matched by strings, and ClickHouse has reworded it before. Asking+ the server means an upgrade that changes the wording fails here, rather than silently letting a+ query that can never fit retry until it times out.+ """+ async with get_client() as client:+ with pytest.raises(ClickHouseError) as exc_info:+ await client.execute_query_with_summary(+ "SELECT groupArray(toString(number)) FROM numbers(10000000)",+ query_id=f"test-hogql-memory-limit-{uuid.uuid4()}",+ settings={"max_memory_usage": "1000000"},+ )++ limit_message = _limit_message_for(exc_info.value)+ assert limit_message is not None+ assert "needed too much memory" in limit_message+ # And a demonstration of why the raw error is not what we hand back: this real one reports the+ # cap we configured and the exact server build.+ assert re.search(r"maximum: [\d.]+ KiB", str(exc_info.value))+ assert re.search(r"version \d+\.\d+", str(exc_info.value))++class PersonToExport(t.TypedDict):team_id: intperson_id: str@@ -1120,8 +1239,14 @@ async def test_insert_into_stage_activity_uses_static_default_without_previous_rasync def _assert_staging_query_settings(clickhouse_client: ClickHouseClient, batch_export_id: str) -> None:- """Currently every model's staging query should run with the same batch export settings applied."""- actual_settings = await _fetch_staging_query_settings(clickhouse_client, batch_export_id)+ """The fixed models (events/persons/sessions) run their staging query with the shared settings.++ The hogql model diverges — it applies the tighter per-query user-query limits — so it asserts its+ own settings separately rather than going through this helper.+ """+ actual_settings = await _fetch_staging_query_settings(+ clickhouse_client, batch_export_id, ["max_bytes_before_external_sort", "optimize_aggregation_in_order"]+ )# one staging query, with max_bytes_before_external_sort and optimize_aggregation_in_order setassert actual_settings == [["50000000000", "1"]]@@ -1129,10 +1254,11 @@ async def _assert_staging_query_settings(clickhouse_client: ClickHouseClient, baasync def _fetch_staging_query_settings(clickhouse_client: ClickHouseClient,batch_export_id: str,+ setting_names: list[str],max_wait_time: float = 10.0,poll_interval: float = 0.5,) -> list[list[str]]:- """Return the settings ClickHouse recorded for this export's staging queries.+ """Return the given settings ClickHouse recorded for this export's staging queries.Looking the queries up by their log comment means a result is also proof the logcomment was attached.@@ -1144,11 +1270,12 @@ async def _fetch_staging_query_settings(Matching on `query_kind` rather than the query text keeps this query from findingitself: it runs with the same log comment as the export it is looking up."""+ selected = ", ".join(f"Settings['{name}']" for name in setting_names)elapsed_time = 0.0while True:await clickhouse_client.execute_query("SYSTEM FLUSH LOGS")rows = await clickhouse_client.read_query(- "SELECT Settings['max_bytes_before_external_sort'], Settings['optimize_aggregation_in_order'] "+ f"SELECT {selected} ""FROM system.query_log "f"WHERE JSONExtractString(log_comment, 'batch_export_id') = '{batch_export_id}' ""AND JSONExtractString(log_comment, 'product') = 'batch_export' "@@ -1426,6 +1553,11 @@ class TestHogQLModel:(e["uuid"], e["event"], e["distinct_id"]) for e in events)+ @override_settings(+ BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME=900,+ BATCH_EXPORT_HOGQL_MAX_MEMORY_USAGE=30_000_000_000,+ BATCH_EXPORT_HOGQL_MAX_BYTES_TO_READ=200_000_000_000,+ )async def test_applies_settings_and_log_comment(self,hogql_model_test_data,@@ -1436,10 +1568,12 @@ class TestHogQLModel:data_interval_start,data_interval_end,):- """The batch export settings and log comment reach the query ClickHouse actually runs.+ """The per-query resource limits and log comment reach the query ClickHouse actually runs.- Neither is written into the query text; they are both sent as query paramaters, so this- asserts against ClickHouse's own record of the query rather than the SQL we generated.+ Neither is written into the query text; they are both sent as query parameters, so this+ asserts against ClickHouse's own record of the query rather than the SQL we generated. This+ also proves the settings names are ones ClickHouse accepts — it rejects unknown settings, so+ a typo would fail the export rather than being silently dropped."""batch_export_id = str(uuid.uuid4())@@ -1453,4 +1587,19 @@ class TestHogQLModel:batch_export_id=batch_export_id,)- await _assert_staging_query_settings(clickhouse_client, batch_export_id)+ # `Settings` in `system.query_log` records only settings changed from their default, so the+ # overflow modes are absent here (`throw` is already ClickHouse's default, and we pin it only+ # to avoid inheriting a `break` from a cluster profile). That we send them is covered by+ # `test_get_clickhouse_request_settings`.+ actual_settings = await _fetch_staging_query_settings(+ clickhouse_client,+ batch_export_id,+ [+ "max_execution_time",+ "max_memory_usage",+ "max_bytes_before_external_sort",+ "max_bytes_ratio_before_external_sort",+ "max_bytes_to_read",+ ],+ )+ assert actual_settings == [["900", "30000000000", "15000000000", "0", "200000000000"]]diff --git a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py b/products/batch_exports/backend/tests/temporal/test_record_batch_model.pyindex f51dc11fc6ff..fbf26633d8c1 100644--- a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py+++ b/products/batch_exports/backend/tests/temporal/test_record_batch_model.py@@ -2,6 +2,8 @@ import datetime as dtimport pytest+from django.test import override_settings+from posthog.hogql.hogql import astfrom posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast@@ -358,19 +360,37 @@ class TestHogQLQueryRecordBatchModel:# SETTINGS clause into the queryassert "SETTINGS" not in printed_query+ @override_settings(+ BATCH_EXPORT_HOGQL_MAX_EXECUTION_TIME=900,+ BATCH_EXPORT_HOGQL_MAX_MEMORY_USAGE=30_000_000_000,+ BATCH_EXPORT_HOGQL_MAX_BYTES_TO_READ=200_000_000_000,+ )async def test_get_clickhouse_request_settings(self):"""Batch export settings are sent as query parameters rather than a SETTINGS clause.- Values are rendered the way the HogQL printer renders them (bools as 1/0), so a- setting reads the same in query_log however it was applied. ClickHouse rejects- unknown setting names outright, so a typo here fails the export.+ Values are rendered the way the HogQL printer renders them (bools as 1/0), so a setting+ reads the same in query_log however it was applied. ClickHouse rejects unknown setting names+ outright, so a typo here fails the export. The per-query resource limits are read from Django+ settings at call time, hence the `override_settings` above pins them for the assertion.++ `read_overflow_mode`/`timeout_overflow_mode` are `throw` on purpose: without them a query+ that hits the time or read limit could return a truncated result as a success. The spill+ thresholds are half the memory cap, and the `max_bytes_ratio_before_external_*` settings are+ 0 so that those thresholds are what ClickHouse actually spills on."""model = HogQLQueryRecordBatchModel(team_id=1, hogql_query="SELECT event AS event FROM events")assert model.get_clickhouse_request_settings() == {"optimize_aggregation_in_order": "1",- "max_bytes_before_external_sort": "50000000000",- "max_bytes_before_external_group_by": "50000000000",+ "max_bytes_before_external_sort": "15000000000",+ "max_bytes_before_external_group_by": "15000000000",+ "max_bytes_ratio_before_external_sort": "0.0",+ "max_bytes_ratio_before_external_group_by": "0.0",+ "max_execution_time": "900",+ "max_memory_usage": "30000000000",+ "max_bytes_to_read": "200000000000",+ "read_overflow_mode": "throw",+ "timeout_overflow_mode": "throw",}@pytest.mark.parametrize(@@ -392,6 +412,28 @@ class TestHogQLQueryRecordBatchModel:with pytest.raises(UnsupportedHogQLQueryError, match=expected_message):model.get_hogql_query(data_interval_start, data_interval_end)+ @pytest.mark.parametrize(+ "hogql_query",+ [+ "SELECT event AS event FROM events SETTINGS max_bytes_to_read=0",+ "SELECT event AS event FROM events UNION ALL SELECT event AS event FROM events SETTINGS max_bytes_to_read=0",+ "WITH x AS (SELECT event FROM events SETTINGS max_bytes_to_read=0) SELECT event AS event FROM x",+ ],+ ids=["top-level", "after-union", "in-cte"],+ )+ async def test_get_hogql_query_rejects_a_settings_clause(self, hogql_query, data_interval_start, data_interval_end):+ """A user query carrying its own SETTINGS is rejected, wherever that clause appears.++ The per-query resource limits are sent as request settings, and a query-level SETTINGS clause+ takes precedence over those, so a query able to smuggle one through could lift its own memory,+ time and bytes-read caps. The parser refusing these is what the limits rest on, and nothing+ else asserts it.+ """+ model = HogQLQueryRecordBatchModel(team_id=1, hogql_query=hogql_query)++ with pytest.raises(UnsupportedHogQLQueryError, match="settingsClause"):+ model.get_hogql_query(data_interval_start, data_interval_end)+async def test_resolve_batch_exports_model_returns_hogql_model(self):batch_export_model = BatchExportModel(name="hogql", schema=None, hogql_query="SELECT event AS event FROM events"