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.

refactor(batch-exports): move the record batch queue out of spmc, delete it (#76703)

Rossf4251bcf217f
diff --git a/products/batch_exports/backend/debug/debugger.py b/products/batch_exports/backend/debug/debugger.py
index c2b97484d6b0..31171dc774f3 100644
--- a/products/batch_exports/backend/debug/debugger.py
+++ b/products/batch_exports/backend/debug/debugger.py
@@ -23,6 +23,7 @@ from products.batch_exports.backend.models.batch_export import BatchExport, Batc
from products.batch_exports.backend.service import (
DESTINATION_WORKFLOWS,
BaseBatchExportInputs,
+ BatchExportField,
BatchExportModel,
BigQueryBatchExportInputs,
DatabricksBatchExportInputs,
@@ -42,7 +43,6 @@ from products.batch_exports.backend.temporal.destinations.snowflake_batch_export
from products.batch_exports.backend.temporal.filters import compose_filters_clause
from products.batch_exports.backend.temporal.pipeline.internal_stage import get_base_s3_staging_folder
from products.batch_exports.backend.temporal.pipeline.query_ranges import use_distributed_events_recent_table
-from products.batch_exports.backend.temporal.spmc import BatchExportField
from products.batch_exports.backend.temporal.sql.events import (
SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,
SELECT_FROM_EVENTS_VIEW,
diff --git a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py
index bc3f7e609afb..87472029d2c3 100644
--- a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py
@@ -41,7 +41,7 @@ from products.batch_exports.backend.temporal.pipeline.transformer import (
get_json_stream_transformer,
)
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producer
from products.batch_exports.backend.temporal.utils import handle_non_retryable_errors
NON_RETRYABLE_ERROR_TYPES = (
diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
index 424223b56803..5423ad21b7e2 100644
--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py
@@ -67,7 +67,7 @@ from products.batch_exports.backend.temporal.pipeline.transformer import (
SchemaTransformer,
)
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult, reduce_batch_export_results
-from products.batch_exports.backend.temporal.spmc import (
+from products.batch_exports.backend.temporal.queue import (
RecordBatchQueue,
raise_on_task_failure,
wait_for_schema_or_producer,
diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
index 1fc04a348e60..fcb59aa35971 100644
--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
@@ -51,7 +51,7 @@ from products.batch_exports.backend.temporal.pipeline.transformer import (
ParquetStreamTransformer,
)
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producer
from products.batch_exports.backend.temporal.utils import (
JsonType,
handle_non_retryable_errors,
diff --git a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py
index 768425a09f35..50a0d76695f4 100644
--- a/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/postgres_batch_export.py
@@ -53,7 +53,7 @@ from products.batch_exports.backend.temporal.pipeline.entrypoint import execute_
from products.batch_exports.backend.temporal.pipeline.producer import Producer
from products.batch_exports.backend.temporal.pipeline.transformer import CSVStreamTransformer
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producer
from products.batch_exports.backend.temporal.utils import (
JsonType,
handle_non_retryable_errors,
diff --git a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
index 66947db52f87..5a486199ccba 100644
--- a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py
@@ -60,7 +60,7 @@ from products.batch_exports.backend.temporal.pipeline.transformer import (
RedshiftQueryStreamTransformer,
)
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producer
from products.batch_exports.backend.temporal.utils import JsonType, handle_non_retryable_errors
LOGGER = get_write_only_logger(__name__)
diff --git a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
index 904c7cac4e4e..9ab167a91139 100644
--- a/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/s3_batch_export.py
@@ -66,7 +66,7 @@ from products.batch_exports.backend.temporal.pipeline.transformer import (
get_json_stream_transformer,
)
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producer
from products.batch_exports.backend.temporal.utils import handle_non_retryable_errors
NON_RETRYABLE_ERROR_TYPES = (
diff --git a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
index f50c390dab8c..abf5c88d2fa5 100644
--- a/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/snowflake_batch_export.py
@@ -54,7 +54,7 @@ from products.batch_exports.backend.temporal.pipeline.transformer import (
SchemaTransformer,
)
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producer
from products.batch_exports.backend.temporal.temporary_file import BatchExportTemporaryFile
from products.batch_exports.backend.temporal.utils import (
JsonType,
diff --git a/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py b/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py
index a34c773ea138..6d9f2fee1f8c 100644
--- a/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/workflows_batch_export.py
@@ -29,7 +29,7 @@ from products.batch_exports.backend.temporal.pipeline.entrypoint import execute_
from products.batch_exports.backend.temporal.pipeline.producer import Producer
from products.batch_exports.backend.temporal.pipeline.transformer import JSONLStreamTransformer
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producer
from products.batch_exports.backend.temporal.utils import (
handle_non_retryable_errors,
make_retryable_with_exponential_backoff,
diff --git a/products/batch_exports/backend/temporal/pipeline/consumer.py b/products/batch_exports/backend/temporal/pipeline/consumer.py
index 85380373e279..0c0fe9e2ecc6 100644
--- a/products/batch_exports/backend/temporal/pipeline/consumer.py
+++ b/products/batch_exports/backend/temporal/pipeline/consumer.py
@@ -19,7 +19,7 @@ from products.batch_exports.backend.temporal.metrics import (
)
from products.batch_exports.backend.temporal.pipeline.transformer import ChunkTransformerProtocol
from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, raise_on_task_failure
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, raise_on_task_failure
from products.batch_exports.backend.temporal.utils import cast_record_batch_json_columns
LOGGER = get_write_only_logger(__name__)
@@ -41,7 +41,7 @@ class _WaitResult(enum.Enum):
class Consumer:
"""Consumer for batch exports.
- This is an alternative implementation of the `spmc.Consumer` class that consumes data from a producer which is in
+ This is an alternative implementation of the legacy SPMC consumer that consumes data from a producer which is in
turn reading data from the internal S3 staging area.
"""
diff --git a/products/batch_exports/backend/temporal/pipeline/producer.py b/products/batch_exports/backend/temporal/pipeline/producer.py
index d66abda3712d..3b5d08c452ea 100644
--- a/products/batch_exports/backend/temporal/pipeline/producer.py
+++ b/products/batch_exports/backend/temporal/pipeline/producer.py
@@ -14,7 +14,7 @@ from posthog.temporal.common.logger import get_write_only_logger
from products.batch_exports.backend.temporal.metrics import CumulativeTimer
from products.batch_exports.backend.temporal.pipeline.internal_stage import get_base_s3_staging_folder, get_s3_client
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.utils import make_retryable_with_exponential_backoff
if typing.TYPE_CHECKING:
diff --git a/products/batch_exports/backend/temporal/spmc.py b/products/batch_exports/backend/temporal/queue.py
similarity index 93%
rename from products/batch_exports/backend/temporal/spmc.py
rename to products/batch_exports/backend/temporal/queue.py
index ce3d907b4cdd..fc1b151537c3 100644
--- a/products/batch_exports/backend/temporal/spmc.py
+++ b/products/batch_exports/backend/temporal/queue.py
@@ -1,3 +1,11 @@
+"""The bounded queue that carries record batches from a producer to a consumer.
+
+Batch exports move data by having a producer read record batches and a consumer write them to
+the destination. This is the handoff between them: a queue bounded by bytes rather than item
+count, since record batch sizes vary enormously, plus the helpers for waiting on the producer
+and surfacing its failures.
+"""
+
import time
import typing
import asyncio
@@ -161,15 +169,3 @@ async def wait_for_schema_or_producer(queue: RecordBatchQueue, producer_task: as
await raise_on_task_failure(producer_task)
return record_batch_schema
-
-
-class BatchExportField(typing.TypedDict):
- """A field to be queried from ClickHouse.
-
- Attributes:
- expression: A ClickHouse SQL expression that declares the field required.
- alias: An alias to apply to the expression (after an 'AS' keyword).
- """
-
- expression: str
- alias: str
diff --git a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/utils.py b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/utils.py
index 61a978f27cf8..e4b31e28271b 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/utils.py
@@ -26,8 +26,8 @@ from products.batch_exports.backend.temporal.destinations.azure_blob_batch_expor
insert_into_azure_blob_activity_from_stage,
)
from products.batch_exports.backend.temporal.pipeline.internal_stage import insert_into_internal_stage_activity
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducer
from products.batch_exports.backend.tests.temporal.utils.records import get_record_batch_from_queue
diff --git a/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py b/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py
index 8abf51407448..0f9c11a9f285 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/base_destination_tests.py
@@ -39,8 +39,8 @@ from products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWS
from products.batch_exports.backend.temporal.batch_exports import finish_batch_export_run, start_batch_export_run
from products.batch_exports.backend.temporal.metrics import BATCH_EXPORT_ACTIVITY_TYPES, BATCH_EXPORT_WORKFLOW_TYPES
from products.batch_exports.backend.temporal.pipeline.internal_stage import insert_into_internal_stage_activity
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducer
from products.batch_exports.backend.tests.temporal.utils.records import (
get_record_batch_from_queue,
diff --git a/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py b/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py
index afb4dd2bb074..79825907de90 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/bigquery/utils.py
@@ -17,8 +17,8 @@ from products.batch_exports.backend.temporal.destinations.bigquery_batch_export
bigquery_default_fields,
get_our_google_cloud_credentials,
)
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducer
from products.batch_exports.backend.tests.temporal.utils.records import get_record_batch_from_queue
diff --git a/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py b/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py
index 13d3cdfa2d5d..50af3035cfaa 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/postgres/utils.py
@@ -11,8 +11,8 @@ from posthog.temporal.common.clickhouse import ClickHouseClient
from products.batch_exports.backend.service import BackfillDetails, BatchExportModel, BatchExportSchema
from products.batch_exports.backend.temporal.destinations.postgres_batch_export import postgres_default_fields
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducer
from products.batch_exports.backend.tests.temporal.utils.records import (
get_record_batch_from_queue,
diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py
index 75bc52284cd7..1ffd9dcbbca1 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/utils.py
@@ -10,8 +10,8 @@ from posthog.temporal.common.clickhouse import ClickHouseClient
from products.batch_exports.backend.service import BackfillDetails, BatchExportModel, BatchExportSchema
from products.batch_exports.backend.temporal.destinations.redshift_batch_export import redshift_default_fields
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.temporal.temporary_file import remove_escaped_whitespace_recursive
from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducer
from products.batch_exports.backend.tests.temporal.utils.records import (
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py
index ef1e2f3545b4..f592a9257590 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/utils.py
@@ -41,8 +41,8 @@ from products.batch_exports.backend.temporal.pipeline.internal_stage import (
BatchExportInsertIntoInternalStageInputs,
insert_into_internal_stage_activity,
)
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducer
from products.batch_exports.backend.tests.temporal.utils.records import get_record_batch_from_queue
from products.batch_exports.backend.tests.temporal.utils.s3 import assert_file_in_s3, assert_no_files_in_s3
diff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py
index 69141afa3cde..86a767f2de0f 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/utils.py
@@ -20,8 +20,8 @@ from posthog.temporal.common.clickhouse import ClickHouseClient
from products.batch_exports.backend.service import BackfillDetails, BatchExportModel, BatchExportSchema
from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import snowflake_default_fields
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducer
from products.batch_exports.backend.tests.temporal.utils.records import (
get_record_batch_from_queue,
diff --git a/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py b/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py
index 88ae36f69d0b..2f4c7e8a00e6 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/workflows/utils.py
@@ -7,8 +7,8 @@ from posthog.temporal.common.clickhouse import ClickHouseClient
from products.batch_exports.backend.service import BackfillDetails, BatchExportModel, BatchExportSchema
from products.batch_exports.backend.temporal.destinations.workflows_batch_export import workflows_default_fields
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModel
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.tests.temporal.utils.clickhouse_test_producer import ClickHouseTestProducer
from products.batch_exports.backend.tests.temporal.utils.records import get_record_batch_from_queue
diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_consumer.py b/products/batch_exports/backend/tests/temporal/pipeline/test_consumer.py
index c9ded7e83373..e75cd20c117b 100644
--- a/products/batch_exports/backend/tests/temporal/pipeline/test_consumer.py
+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_consumer.py
@@ -8,7 +8,7 @@ from structlog.testing import capture_logs
from products.batch_exports.backend.temporal.pipeline.consumer import Consumer, run_consumer_from_stage
from products.batch_exports.backend.temporal.pipeline.transformer import Chunk
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
pytestmark = [pytest.mark.asyncio]
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 e950c055e70c..e7a9e9c37ab9 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
@@ -43,7 +43,7 @@ from products.batch_exports.backend.temporal.pipeline.internal_stage import (
insert_into_internal_stage_activity,
)
from products.batch_exports.backend.temporal.pipeline.producer import Producer
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producer
from products.batch_exports.backend.tests.temporal.utils.mock_clickhouse import MockClickHouseClient
from products.batch_exports.backend.tests.temporal.utils.persons import (
generate_test_person_distinct_id2_in_clickhouse,
diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_producer.py b/products/batch_exports/backend/tests/temporal/pipeline/test_producer.py
index 579317ed83fa..4478c1a96d15 100644
--- a/products/batch_exports/backend/tests/temporal/pipeline/test_producer.py
+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_producer.py
@@ -26,8 +26,8 @@ from products.batch_exports.backend.temporal.pipeline.internal_stage import (
BatchExportInsertIntoInternalStageInputs,
insert_into_internal_stage_activity,
)
-from products.batch_exports.backend.temporal.pipeline.producer import Producer, S3FileResumeState
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue, wait_for_schema_or_producer
+from products.batch_exports.backend.temporal.pipeline.producer import Producer, S3FileResumeState, slice_record_batch
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue, wait_for_schema_or_producer
from products.batch_exports.backend.temporal.utils import make_retryable_with_exponential_backoff
from products.batch_exports.backend.tests.temporal.utils.s3 import assert_files_in_s3
@@ -404,3 +404,69 @@ async def test_producer_resumes_from_offset_after_mid_file_failure(
assert resume_call.get("Range", "").startswith("bytes=")
assert int(resume_call["Range"].removeprefix("bytes=").removesuffix("-")) > 0
assert resume_call.get("IfMatch")
+
+
+def test_slice_record_batch_into_single_record_slices():
+ """Test we slice a record batch into slices with a single record."""
+ n_legs = pa.array([2, 2, 4, 4, 5, 100])
+ animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
+ arrays: collections.abc.Collection[pa.Array[typing.Any]] = [n_legs, animals]
+ batch = pa.RecordBatch.from_arrays(arrays, names=["n_legs", "animals"])
+
+ slices = list(slice_record_batch(batch, max_record_batch_size_bytes=1, min_records_per_batch=1))
+ assert len(slices) == 6
+ assert all(slice.num_rows == 1 for slice in slices)
+
+
+def test_slice_record_batch_into_one_batch():
+ """Test we do not slice a record batch without a bytes limit."""
+ n_legs = pa.array([2, 2, 4, 4, 5, 100])
+ animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
+ batch = pa.RecordBatch.from_arrays([n_legs, animals], names=["n_legs", "animals"])
+
+ slices = list(slice_record_batch(batch, max_record_batch_size_bytes=0))
+ assert len(slices) == 1
+ assert all(slice.num_rows == 6 for slice in slices)
+
+
+def test_slice_record_batch_in_half():
+ """Test we can slice a record batch into half size."""
+ n_legs = pa.array([4] * 6)
+ animals = pa.array(["Dog"] * 6)
+ batch = pa.RecordBatch.from_arrays([n_legs, animals], names=["n_legs", "animals"])
+
+ slices = list(slice_record_batch(batch, max_record_batch_size_bytes=batch.nbytes // 2, min_records_per_batch=1))
+ assert len(slices) == 2
+ assert all(slice.num_rows == 3 for slice in slices)
+
+
+def test_slice_large_record_batch():
+ """Test we can slice a record batch with plenty of elements and data.
+
+ We construct an array with a large payload and attempt to slice it evenly.
+ We assert that the count of rows matches expected, all ids are accounted
+ for, the number of slices matches what we expect, and that each slice
+ has the same number of rows.
+ """
+ size = 1_000_000
+ one_tenth = size / 10
+
+ payload = pa.array([b"0" * (1024)] * size, type=pa.large_binary())
+ id = pa.array(list(range(size)))
+ batch = pa.RecordBatch.from_arrays([id, payload], names=["id", "payload"])
+
+ # Large binary allocates additional 8 bytes per row.
+ # Id array is int64, and takes up 8 bytes per row.
+ # So, we add 16 bytes per row (16 * 1000 total) to get evenly split record
+ # batches of 1k rows each.
+ slices = list(
+ slice_record_batch(batch, max_record_batch_size_bytes=int(one_tenth * (1024 + 16)), min_records_per_batch=1)
+ )
+ expected_len = 10
+ result_len = len(slices)
+ concatenated = pa.concat_arrays(s.column("id") for s in slices)
+
+ assert sum(slice.num_rows for slice in slices) == size
+ assert concatenated.to_pylist() == list(range(size))
+ assert result_len == expected_len, f"Have {result_len} slices, expected {expected_len}"
+ assert all(slice.num_rows == one_tenth for slice in slices)
diff --git a/products/batch_exports/backend/tests/temporal/pipeline/test_query_ranges.py b/products/batch_exports/backend/tests/temporal/pipeline/test_query_ranges.py
new file mode 100644
index 000000000000..deae6835d5e7
--- /dev/null
+++ b/products/batch_exports/backend/tests/temporal/pipeline/test_query_ranges.py
@@ -0,0 +1,55 @@
+"""Tests for choosing which ranges and tables a batch export run queries."""
+
+import typing
+import datetime as dt
+
+import pytest
+
+from products.batch_exports.backend.service import BackfillDetails
+from products.batch_exports.backend.temporal.pipeline.query_ranges import use_distributed_events_recent_table
+
+pytestmark = [pytest.mark.django_db]
+
+
+ "test_data",
+ [
+ # isn't a backfill so should use distributed_events_recent table
+ {
+ "is_backfill": False,
+ "data_interval_start": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=1),
+ "use_distributed_events_recent_table": True,
+ },
+ # is a backfill within the last 6 days so should use distributed_events_recent table
+ {
+ "is_backfill": True,
+ "backfill_start_at": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=1),
+ "data_interval_start": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=1),
+ "use_distributed_events_recent_table": True,
+ },
+ # is a backfill outside the last 6 days so shouldn't use distributed_events_recent table
+ {
+ "is_backfill": True,
+ "backfill_start_at": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=7),
+ "data_interval_start": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=1),
+ "use_distributed_events_recent_table": False,
+ },
+ ],
+)
+def test_use_distributed_events_recent_table(test_data: dict[str, typing.Any]):
+ backfill_details = (
+ BackfillDetails(
+ backfill_id=None,
+ start_at=test_data["backfill_start_at"].isoformat(),
+ end_at=(test_data["backfill_start_at"] + dt.timedelta(days=1)).isoformat(),
+ is_earliest_backfill=False,
+ )
+ if test_data["is_backfill"]
+ else None
+ )
+ assert (
+ use_distributed_events_recent_table(
+ test_data["is_backfill"], backfill_details, data_interval_start=test_data["data_interval_start"]
+ )
+ == test_data["use_distributed_events_recent_table"]
+ )
diff --git a/products/batch_exports/backend/tests/temporal/test_filters.py b/products/batch_exports/backend/tests/temporal/test_filters.py
new file mode 100644
index 000000000000..e04ea0460a54
--- /dev/null
+++ b/products/batch_exports/backend/tests/temporal/test_filters.py
@@ -0,0 +1,142 @@
+"""Tests for composing HogQL property filters into ClickHouse clauses."""
+
+import typing
+
+import pytest
+
+from products.batch_exports.backend.temporal.filters import InvalidFilterError, compose_filters_clause
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
+
+
+ "filters,expected_clause,expected_values",
+ [
+ # Events
+ (
+ [
+ {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]},
+ ],
+ """ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), 0)""",
+ {"hogql_val_0": "$browser", "hogql_val_1": "Firefox"},
+ ),
+ (
+ [
+ {"key": "$current_url", "operator": "icontains", "type": "event", "value": "https://posthog.com"},
+ ],
+ """ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', '')), %(hogql_val_1)s), 0)""",
+ {"hogql_val_0": "$current_url", "hogql_val_1": "%https://posthog.com%"},
+ ),
+ (
+ [
+ {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]},
+ {"key": "test", "operator": "exact", "type": "event", "value": ["Test"]},
+ ],
+ """and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), 0), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), ''), 'null'), '^"|"$', ''), %(hogql_val_3)s), 0))""",
+ {"hogql_val_0": "$browser", "hogql_val_1": "Firefox", "hogql_val_2": "test", "hogql_val_3": "Test"},
+ ),
+ # Feature (subset of event)
+ (
+ [
+ {"key": "$feature/some-feature", "type": "event", "operator": "exact", "value": ["true"]},
+ ],
+ """ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_1)s), 0)""",
+ {"hogql_val_0": "$feature/some-feature", "hogql_val_1": "true"},
+ ),
+ # Person
+ (
+ [
+ {"key": "$initial_current_url", "type": "person", "operator": "exact", "value": ["http://localhost"]},
+ ],
+ """ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), 0)""",
+ {"hogql_val_0": "$initial_current_url", "hogql_val_1": "http://localhost"},
+ ),
+ (
+ [
+ {"key": "$initial_current_url", "type": "person", "operator": "is_set", "value": None},
+ ],
+ """isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\'))""",
+ {"hogql_val_0": "$initial_current_url"},
+ ),
+ (
+ [
+ {"key": "$initial_current_url", "type": "person", "operator": "regex", "value": ["^http://.*$"]},
+ ],
+ """ifNull(match(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\')), %(hogql_val_1)s), 0)""",
+ {"hogql_val_0": "$initial_current_url", "hogql_val_1": "^http://.*$"},
+ ),
+ (
+ [
+ {"key": "$created_at", "type": "person", "operator": "between", "value": [0, 1]},
+ ],
+ """and(ifNull(greaterOrEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\'), 0.0), 0), ifNull(lessOrEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_1)s), \'\'), \'null\'), \'^"|"$\', \'\'), 1.0), 0))""",
+ {"hogql_val_0": "$created_at", "hogql_val_1": "$created_at"},
+ ),
+ # HogQL
+ (
+ [
+ {"key": "toInt(properties.$browser_version) * 10 = 1", "type": "hogql", "value": None},
+ ],
+ """ifNull(equals(multiply(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_1)s), 10), 1), 0)""",
+ {"hogql_val_0": "$browser_version", "hogql_val_1": "Int64"},
+ ),
+ ],
+ ids=[
+ "events0",
+ "events1",
+ "events2",
+ "feature0",
+ "person0",
+ "person1",
+ "person2",
+ "person3",
+ "hogql0",
+ ],
+)
+def test_compose_filters_clause(
+ filters: list[dict[str, typing.Any]],
+ expected_clause: str,
+ expected_values: dict[str, str],
+ ateam,
+):
+ result_clause, result_values = compose_filters_clause(filters, team_id=ateam.id)
+ assert result_clause == expected_clause
+ assert result_values == expected_values
+
+
+def test_compose_filters_clause_uses_legacy_events_schema(settings, ateam):
+ settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA = True
+
+ result_clause, result_values = compose_filters_clause(
+ [{"key": "$browser", "type": "event", "operator": "exact", "value": ["Chrome"]}],
+ team_id=ateam.id,
+ )
+
+ assert (
+ result_clause
+ == """ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), 0)"""
+ )
+ assert result_values == {"hogql_val_0": "$browser", "hogql_val_1": "Chrome"}
+
+
+ "filters",
+ (
+ [
+ {"key": "event in (select * from events)", "type": "hogql", "value": None},
+ ],
+ [
+ {"key": "event =", "type": "hogql", "value": None},
+ ],
+ ),
+ ids=[
+ "hogql0",
+ "hogql1",
+ ],
+)
+def test_compose_filters_clause_raises(
+ filters: list[dict[str, typing.Any]],
+ ateam,
+):
+ with pytest.raises(InvalidFilterError):
+ result_clause, result_values = compose_filters_clause(filters, team_id=ateam.id)
diff --git a/products/batch_exports/backend/tests/temporal/test_queue.py b/products/batch_exports/backend/tests/temporal/test_queue.py
new file mode 100644
index 000000000000..6ddc87be8ef1
--- /dev/null
+++ b/products/batch_exports/backend/tests/temporal/test_queue.py
@@ -0,0 +1,75 @@
+"""Tests for the record batch queue that carries data from producer to consumer."""
+
+import asyncio
+
+import pytest
+
+import pyarrow as pa
+
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
+
+
+async def test_record_batch_queue_tracks_bytes():
+ """Test `RecordBatchQueue` tracks bytes from `RecordBatch`."""
+ records = [{"test": 1}, {"test": 2}, {"test": 3}]
+ record_batch = pa.RecordBatch.from_pylist(records)
+
+ queue = RecordBatchQueue()
+
+ await queue.put(record_batch)
+ assert record_batch.get_total_buffer_size() == queue.qsize()
+
+ item = await queue.get()
+
+ assert item == record_batch
+ assert queue.qsize() == 0
+
+
+async def test_record_batch_queue_raises_queue_full():
+ """Test `QueueFull` is raised when we put too many bytes."""
+ records = [{"test": 1}, {"test": 2}, {"test": 3}]
+ record_batch = pa.RecordBatch.from_pylist(records)
+ record_batch_size = record_batch.get_total_buffer_size()
+
+ queue = RecordBatchQueue(max_size_bytes=record_batch_size)
+
+ await queue.put(record_batch)
+ assert record_batch.get_total_buffer_size() == queue.qsize()
+
+ with pytest.raises(asyncio.QueueFull):
+ queue.put_nowait(record_batch)
+
+ item = await queue.get()
+
+ assert item == record_batch
+ assert queue.qsize() == 0
+
+
+async def test_record_batch_queue_sets_schema():
+ """Test `RecordBatchQueue` sets a schema from first `RecordBatch`."""
+ records = [{"test": 1}, {"test": 2}, {"test": 3}]
+ record_batch = pa.RecordBatch.from_pylist(records)
+
+ queue = RecordBatchQueue()
+
+ await queue.put(record_batch)
+
+ assert queue._schema_set.is_set()
+
+ schema = await queue.get_schema()
+ assert schema == record_batch.schema
+
+
+async def test_record_batch_queue_str_and_repr():
+ """Test `RecordBatchQueue` returns sensible output for str and repr"""
+ records = [{"test": 1}, {"test": 2}, {"test": 3}]
+ record_batch = pa.RecordBatch.from_pylist(records)
+
+ queue = RecordBatchQueue()
+
+ await queue.put(record_batch)
+
+ assert str(queue) == "<RecordBatchQueue record_batches=1 bytes=24 schema='test: int64'>"
+ assert "record_batches=1 bytes=24 schema='test: int64'" in repr(queue)
diff --git a/products/batch_exports/backend/tests/temporal/test_spmc.py b/products/batch_exports/backend/tests/temporal/test_spmc.py
deleted file mode 100644
index 2abf45477b95..000000000000
--- a/products/batch_exports/backend/tests/temporal/test_spmc.py
+++ /dev/null
@@ -1,323 +0,0 @@
-import typing
-import asyncio
-import datetime as dt
-from collections.abc import Collection
-
-import pytest
-
-import pyarrow as pa
-
-from products.batch_exports.backend.service import BackfillDetails
-from products.batch_exports.backend.temporal.filters import InvalidFilterError, compose_filters_clause
-from products.batch_exports.backend.temporal.pipeline.producer import slice_record_batch
-from products.batch_exports.backend.temporal.pipeline.query_ranges import use_distributed_events_recent_table
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
-
-pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
-
-
-async def test_record_batch_queue_tracks_bytes():
- """Test `RecordBatchQueue` tracks bytes from `RecordBatch`."""
- records = [{"test": 1}, {"test": 2}, {"test": 3}]
- record_batch = pa.RecordBatch.from_pylist(records)
-
- queue = RecordBatchQueue()
-
- await queue.put(record_batch)
- assert record_batch.get_total_buffer_size() == queue.qsize()
-
- item = await queue.get()
-
- assert item == record_batch
- assert queue.qsize() == 0
-
-
-async def test_record_batch_queue_raises_queue_full():
- """Test `QueueFull` is raised when we put too many bytes."""
- records = [{"test": 1}, {"test": 2}, {"test": 3}]
- record_batch = pa.RecordBatch.from_pylist(records)
- record_batch_size = record_batch.get_total_buffer_size()
-
- queue = RecordBatchQueue(max_size_bytes=record_batch_size)
-
- await queue.put(record_batch)
- assert record_batch.get_total_buffer_size() == queue.qsize()
-
- with pytest.raises(asyncio.QueueFull):
- queue.put_nowait(record_batch)
-
- item = await queue.get()
-
- assert item == record_batch
- assert queue.qsize() == 0
-
-
-async def test_record_batch_queue_sets_schema():
- """Test `RecordBatchQueue` sets a schema from first `RecordBatch`."""
- records = [{"test": 1}, {"test": 2}, {"test": 3}]
- record_batch = pa.RecordBatch.from_pylist(records)
-
- queue = RecordBatchQueue()
-
- await queue.put(record_batch)
-
- assert queue._schema_set.is_set()
-
- schema = await queue.get_schema()
- assert schema == record_batch.schema
-
-
-async def test_record_batch_queue_str_and_repr():
- """Test `RecordBatchQueue` returns sensible output for str and repr"""
- records = [{"test": 1}, {"test": 2}, {"test": 3}]
- record_batch = pa.RecordBatch.from_pylist(records)
-
- queue = RecordBatchQueue()
-
- await queue.put(record_batch)
-
- assert str(queue) == "<RecordBatchQueue record_batches=1 bytes=24 schema='test: int64'>"
- assert "record_batches=1 bytes=24 schema='test: int64'" in repr(queue)
-
-
-def test_slice_record_batch_into_single_record_slices():
- """Test we slice a record batch into slices with a single record."""
- n_legs = pa.array([2, 2, 4, 4, 5, 100])
- animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
- arrays: Collection[pa.Array[typing.Any]] = [n_legs, animals]
- batch = pa.RecordBatch.from_arrays(arrays, names=["n_legs", "animals"])
-
- slices = list(slice_record_batch(batch, max_record_batch_size_bytes=1, min_records_per_batch=1))
- assert len(slices) == 6
- assert all(slice.num_rows == 1 for slice in slices)
-
-
-def test_slice_record_batch_into_one_batch():
- """Test we do not slice a record batch without a bytes limit."""
- n_legs = pa.array([2, 2, 4, 4, 5, 100])
- animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"])
- batch = pa.RecordBatch.from_arrays([n_legs, animals], names=["n_legs", "animals"])
-
- slices = list(slice_record_batch(batch, max_record_batch_size_bytes=0))
- assert len(slices) == 1
- assert all(slice.num_rows == 6 for slice in slices)
-
-
-def test_slice_record_batch_in_half():
- """Test we can slice a record batch into half size."""
- n_legs = pa.array([4] * 6)
- animals = pa.array(["Dog"] * 6)
- batch = pa.RecordBatch.from_arrays([n_legs, animals], names=["n_legs", "animals"])
-
- slices = list(slice_record_batch(batch, max_record_batch_size_bytes=batch.nbytes // 2, min_records_per_batch=1))
- assert len(slices) == 2
- assert all(slice.num_rows == 3 for slice in slices)
-
-
-def test_slice_large_record_batch():
- """Test we can slice a record batch with plenty of elements and data.
-
- We construct an array with a large payload and attempt to slice it evenly.
- We assert that the count of rows matches expected, all ids are accounted
- for, the number of slices matches what we expect, and that each slice
- has the same number of rows.
- """
- size = 1_000_000
- one_tenth = size / 10
-
- payload = pa.array([b"0" * (1024)] * size, type=pa.large_binary())
- id = pa.array(list(range(size)))
- batch = pa.RecordBatch.from_arrays([id, payload], names=["id", "payload"])
-
- # Large binary allocates additional 8 bytes per row.
- # Id array is int64, and takes up 8 bytes per row.
- # So, we add 16 bytes per row (16 * 1000 total) to get evenly split record
- # batches of 1k rows each.
- slices = list(
- slice_record_batch(batch, max_record_batch_size_bytes=int(one_tenth * (1024 + 16)), min_records_per_batch=1)
- )
- expected_len = 10
- result_len = len(slices)
- concatenated = pa.concat_arrays(s.column("id") for s in slices)
-
- assert sum(slice.num_rows for slice in slices) == size
- assert concatenated.to_pylist() == list(range(size))
- assert result_len == expected_len, f"Have {result_len} slices, expected {expected_len}"
- assert all(slice.num_rows == one_tenth for slice in slices)
-
-
- "test_data",
- [
- # isn't a backfill so should use distributed_events_recent table
- {
- "is_backfill": False,
- "data_interval_start": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=1),
- "use_distributed_events_recent_table": True,
- },
- # is a backfill within the last 6 days so should use distributed_events_recent table
- {
- "is_backfill": True,
- "backfill_start_at": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=1),
- "data_interval_start": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=1),
- "use_distributed_events_recent_table": True,
- },
- # is a backfill outside the last 6 days so shouldn't use distributed_events_recent table
- {
- "is_backfill": True,
- "backfill_start_at": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=7),
- "data_interval_start": dt.datetime.now(tz=dt.UTC) - dt.timedelta(days=1),
- "use_distributed_events_recent_table": False,
- },
- ],
-)
-def test_use_distributed_events_recent_table(test_data: dict[str, typing.Any]):
- backfill_details = (
- BackfillDetails(
- backfill_id=None,
- start_at=test_data["backfill_start_at"].isoformat(),
- end_at=(test_data["backfill_start_at"] + dt.timedelta(days=1)).isoformat(),
- is_earliest_backfill=False,
- )
- if test_data["is_backfill"]
- else None
- )
- assert (
- use_distributed_events_recent_table(
- test_data["is_backfill"], backfill_details, data_interval_start=test_data["data_interval_start"]
- )
- == test_data["use_distributed_events_recent_table"]
- )
-
-
- "filters,expected_clause,expected_values",
- [
- # Events
- (
- [
- {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]},
- ],
- """ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), 0)""",
- {"hogql_val_0": "$browser", "hogql_val_1": "Firefox"},
- ),
- (
- [
- {"key": "$current_url", "operator": "icontains", "type": "event", "value": "https://posthog.com"},
- ],
- """ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', '')), %(hogql_val_1)s), 0)""",
- {"hogql_val_0": "$current_url", "hogql_val_1": "%https://posthog.com%"},
- ),
- (
- [
- {"key": "$browser", "operator": "exact", "type": "event", "value": ["Firefox"]},
- {"key": "test", "operator": "exact", "type": "event", "value": ["Test"]},
- ],
- """and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), 0), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), ''), 'null'), '^"|"$', ''), %(hogql_val_3)s), 0))""",
- {"hogql_val_0": "$browser", "hogql_val_1": "Firefox", "hogql_val_2": "test", "hogql_val_3": "Test"},
- ),
- # Feature (subset of event)
- (
- [
- {"key": "$feature/some-feature", "type": "event", "operator": "exact", "value": ["true"]},
- ],
- """ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_1)s), 0)""",
- {"hogql_val_0": "$feature/some-feature", "hogql_val_1": "true"},
- ),
- # Person
- (
- [
- {"key": "$initial_current_url", "type": "person", "operator": "exact", "value": ["http://localhost"]},
- ],
- """ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), 0)""",
- {"hogql_val_0": "$initial_current_url", "hogql_val_1": "http://localhost"},
- ),
- (
- [
- {"key": "$initial_current_url", "type": "person", "operator": "is_set", "value": None},
- ],
- """isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\'))""",
- {"hogql_val_0": "$initial_current_url"},
- ),
- (
- [
- {"key": "$initial_current_url", "type": "person", "operator": "regex", "value": ["^http://.*$"]},
- ],
- """ifNull(match(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\')), %(hogql_val_1)s), 0)""",
- {"hogql_val_0": "$initial_current_url", "hogql_val_1": "^http://.*$"},
- ),
- (
- [
- {"key": "$created_at", "type": "person", "operator": "between", "value": [0, 1]},
- ],
- """and(ifNull(greaterOrEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\'), 0.0), 0), ifNull(lessOrEquals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, %(hogql_val_1)s), \'\'), \'null\'), \'^"|"$\', \'\'), 1.0), 0))""",
- {"hogql_val_0": "$created_at", "hogql_val_1": "$created_at"},
- ),
- # HogQL
- (
- [
- {"key": "toInt(properties.$browser_version) * 10 = 1", "type": "hogql", "value": None},
- ],
- """ifNull(equals(multiply(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_1)s), 10), 1), 0)""",
- {"hogql_val_0": "$browser_version", "hogql_val_1": "Int64"},
- ),
- ],
- ids=[
- "events0",
- "events1",
- "events2",
- "feature0",
- "person0",
- "person1",
- "person2",
- "person3",
- "hogql0",
- ],
-)
-def test_compose_filters_clause(
- filters: list[dict[str, typing.Any]],
- expected_clause: str,
- expected_values: dict[str, str],
- ateam,
-):
- result_clause, result_values = compose_filters_clause(filters, team_id=ateam.id)
- assert result_clause == expected_clause
- assert result_values == expected_values
-
-
-def test_compose_filters_clause_uses_legacy_events_schema(settings, ateam):
- settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA = True
-
- result_clause, result_values = compose_filters_clause(
- [{"key": "$browser", "type": "event", "operator": "exact", "value": ["Chrome"]}],
- team_id=ateam.id,
- )
-
- assert (
- result_clause
- == """ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), 0)"""
- )
- assert result_values == {"hogql_val_0": "$browser", "hogql_val_1": "Chrome"}
-
-
- "filters",
- (
- [
- {"key": "event in (select * from events)", "type": "hogql", "value": None},
- ],
- [
- {"key": "event =", "type": "hogql", "value": None},
- ],
- ),
- ids=[
- "hogql0",
- "hogql1",
- ],
-)
-def test_compose_filters_clause_raises(
- filters: list[dict[str, typing.Any]],
- ateam,
-):
- with pytest.raises(InvalidFilterError):
- result_clause, result_values = compose_filters_clause(filters, team_id=ateam.id)
diff --git a/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py b/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py
index 6880e8428eb1..1dd6a058f9fc 100644
--- a/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py
+++ b/products/batch_exports/backend/tests/temporal/utils/clickhouse_test_producer.py
@@ -27,8 +27,8 @@ from products.batch_exports.backend.temporal.pipeline.query_ranges import (
use_distributed_events_recent_table,
wait_for_delta_past_data_interval_end,
)
+from products.batch_exports.backend.temporal.queue import RecordBatchQueue
from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel
-from products.batch_exports.backend.temporal.spmc import RecordBatchQueue
from products.batch_exports.backend.temporal.sql.events import (
SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,
SELECT_FROM_EVENTS_VIEW,