: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(cohorts): bound seeder clickhouse load and push down event filters (#109474)
Matheus Batista91c4cf29237f
diff --git a/docs/internal/realtime-cohorts/backfill-coordination.md b/docs/internal/realtime-cohorts/backfill-coordination.mdindex 656dae204277..86511361d620 100644--- a/docs/internal/realtime-cohorts/backfill-coordination.md+++ b/docs/internal/realtime-cohorts/backfill-coordination.md@@ -2,7 +2,7 @@Django decides when a backfill is owed, freezes what it must replay, and at the end decides whether the finished run may open the cohort to feature flags.It never turns history into seeds, never produces to Kafka and never reconciles.-Its one ClickHouse query is the size estimate for person runs.+Its only ClickHouse queries are the size estimate for person runs and the operator command's event count for behavioral team runs.This page covers the run tables, the save path that triggers runs, pinning, supersession, the gates, and what happens when things go wrong.The last step, finalization and readiness stamps, is in [completion and readiness](completion-and-readiness.md).[Backfill overview](backfill-overview.md) explains what a run does and its lifecycle.@@ -158,6 +158,7 @@ Missing one of them fails quietly, so they are worth knowing.| `COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST` | Teams whose saves create runs automatically. Unset or empty means **no** teams || Operator attestations | Settings an operator sets to declare that prerequisites hold. They are declarations, not live checks. Behavioral runs need `BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED` and `BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED`. Person runs also need the person TTL and sizing attestations and a positive seed-bytes budget || Person sizing budget | A cohort-scoped person run is refused when the team's active person-run estimates plus its own would exceed the budget. The check reads the active estimates before the run exists and reserves nothing, so two cohorts sized at the same time can together exceed the budget. A team run checks only its own estimate. Hitting the size estimate's scan cap, or the cap on pinned conditions, also refuses |+| Behavioral scan limit | `create_cohort_backfill_run` refuses a behavioral team run when its pinned event names had more events than `BEHAVIORAL_BACKFILL_MAX_SCAN_EVENTS_PER_DAY` on the busiest of the last 7 complete UTC days. `--max-scan-events-per-day` overrides it for one invocation, and 0 skips the count and the check. The save path does not check it |The Rust services have their own switches, and Django cannot see them.Two of them gate person runs, and they must open in order.@@ -181,6 +182,11 @@ Two management commands cover operator work.- `create_cohort_backfill_run` creates team-scoped runs, behavioral or person, including disaster-recovery runs with a pinned boundary.It can narrow the run to chosen cohorts, which is how an operator re-drives one cohort whose trigger was lost.It refuses when an attestation is missing or when a target cohort already has an open participation, and it supports a dry run.+ For a behavioral run it first counts the team's events on the pinned event names over the last 7 complete UTC days, through the `events` primary key on the offline cluster.+ It prints the busiest day and its largest events, refuses above the behavioral scan limit, and records the count in the run's `preconditions`.+ The count is a recent sample, not a bound: an older day, or a day in the run's timezone, can hold more events.+ The seeder reads fewer rows when every condition on an event name filters on event property values.+ The person size estimate also runs on the offline cluster, and aggregates in primary-key order so its memory does not grow with the team.- `manage_cohort_backfill_runs inventory` lists and classifies active runs.`manage_cohort_backfill_runs terminalize` cancels chosen runs.It is a dry run unless told otherwise, and it never cancels a run that already stamped.diff --git a/docs/internal/realtime-cohorts/seeder.md b/docs/internal/realtime-cohorts/seeder.mdindex cde854ce3178..b64dc37c475f 100644--- a/docs/internal/realtime-cohorts/seeder.md+++ b/docs/internal/realtime-cohorts/seeder.md@@ -116,6 +116,7 @@ WHERE team_id = <team>AND timestamp in [start of day, start of next day) in the run's timezoneAND event IN (<event names of the conditions whose window still covers this day>)AND coalesce(inserted_at, _timestamp) < S_chunk+ [AND <row filter>][AND hash(person) % bands = band]```@@ -124,6 +125,8 @@ WHERE team_id = <team>- **Arrival bound.** Only events that reached ClickHouse before `S_chunk` count.- **Active conditions.** Conditions whose window has slid past this day by scan time are left out.If none remain, the chunk is done without a query.+- **Row filter.** When every active condition on an event name compares event properties to string values, only rows that can match one of them leave ClickHouse.+ See [Row filter](#row-filter).### Evaluating and producing@@ -176,6 +179,29 @@ A reclaimed chunk is scanned and produced again from scratch.The duplicate tiles are absorbed by max-merge.A graceful shutdown before a chunk is marked produced returns it to `pending`, even if some of its tiles already reached Kafka.+### Resource breaker++The retry backoff delays one failed chunk, while the run's other pending chunks stay claimable at once.+So a run whose scans do not fit ClickHouse would refill every freed slot with a new scan that fails the same way, and each of those scans takes memory from the other tenants of the cluster until it fails.++The seeder classifies each chunk failure by the ClickHouse error behind it.+Codes 241 (memory limit), 159 (timeout), 160 (too slow) and 202 (too many simultaneous queries) are resource errors.+So is a response that ClickHouse cuts after it has started it, labelled `response_cut`.+The client reads no error code then, and a scan that the memory or time limit stops mid-stream fails this way.+Per run:++1. After `SEEDER_CH_BREAKER_THRESHOLD` resource failures in a row (default 3), the seeder stops claiming the run's chunks for a cooldown (`SEEDER_CH_BREAKER_COOLDOWN_BASE_SECS`, default 300 s).+ Chunks already running finish, and their results do not count, whether they fail or confirm.+2. After the cooldown, once none of the run's chunks is still running, the seeder scans one chunk of the run.+ A confirmed chunk closes the breaker and resets its count.+ A resource failure opens it again for twice as long, up to `SEEDER_CH_BREAKER_COOLDOWN_CAP_SECS` (default 1800 s).+3. The opening that reaches `SEEDER_CH_BREAKER_MAX_TRIPS` (default 4) without a confirmed chunk in between fails the run, with the last error in its `error`.+ If that write does not apply, the next probe decides again.++Any other failure leaves the breaker as it is.+The breaker lives in the seeder process, so each replica keeps its own and a restart closes them.+`seeder_clickhouse_resource_errors_total`, `seeder_run_breaker_trips_total`, `seeder_runs_failed_breaker_total` and `seeder_run_breakers_open` report it.+## Person-property runsA person run seeds the person record instead of behavioral leaves.@@ -187,6 +213,10 @@ Planning a person run needs a scan, so it runs off the poll loop, one at a timeThe seeder streams the ids of the team's persons that changed within the horizon, keeps every Nth id as a boundary, and inserts chunks that tile the whole id space.The insert is all or nothing.+The boundaries only size the chunks, because the chunks tile the whole id space and each chunk's scan applies the exact person predicate.+So the boundary scan filters person versions by `_timestamp` and does not collapse them: deleted persons count toward the stride, which only makes some chunks smaller.+It builds no set of ids, so its memory does not grow with the team.+Person chunks have their own claim slots, so they run alongside behavioral work.If a person run has no surviving condition at all while a participation is active, the seeder fails it.@@ -266,6 +296,8 @@ Then each participation is marked complete, retryable, or superseded, and the ruIt is on by default in code, adds a full-width query per chunk and roughly doubles scan memory, so it is meant to be turned off once projection is proven.- **Scan-time window gate.**A chunk whose day has slid out of every active window issues no query.+- **Row filter.**+ See [Row filter](#row-filter).- **Bands.**Splitting a day by person hash bounds one chunk's memory, at the cost of reading the day once per band.- **Pacing.**@@ -310,6 +342,46 @@ p-1 hashes to partition 26.7. **Completion.**When the other six chunks confirm, the seeder moves R to `reconciling` and sends 64 reconcile requests for cohort 42.+### Row filter++A behavioral chunk's scan can leave rows in ClickHouse that no active condition can match.+The accumulator evaluates a row only against the active conditions of the row's event name, and a row no condition matches adds nothing to any tile, so dropping such a row changes no tile.++1. **Recognizing a condition.**+ A static pass over each condition's bytecode recognizes one exact shape: `event == '<name>'` in an `AND` with equalities of event properties to string literals, alone or in an `OR` of such equalities.+ This is what the compiler emits for an event filter with the `exact` operator.+ Any other opcode leaves the condition without a filter.+ Another comparison in the same `AND`, such as a person property, is allowed and ignored.+2. **Deriving the chunk's filter.**+ An event name is filtered only when every active condition on it has a filter whose event is that name.+ One condition without a filter keeps every row of the event.+3. **Rendering it.**+ The filter is one more `WHERE` conjunct: every unfiltered event passes, and a row of a filtered event passes when some condition's property test holds.+ Conditions that each test one key render as one test per key over the union of their values, which keeps many flag cohorts under the length limit below.++HogVM equality coerces across types, so the property test is a superset of it.+The test reads `replaceRegexpAll(JSONExtractRaw(properties, key), '^"|"$', '')`, the value's raw JSON text without its outer quotes.+It admits the value itself, `true` and `false` (the VM equates a JSON boolean with a string), text holding a backslash (an escaped string), and text starting with `{` (the VM compares a temporal object by epoch).+A value that parses as a number is never filtered on, because the VM also equates it with a JSON number.+The test also admits a blob that ClickHouse cannot parse, such as one holding an integer past 64 bits: ClickHouse then extracts '' for every key, while `serde_json` reads the blob.+Ingestion writes event properties with `JSON.stringify` of a parsed object, so a key appears once and the first-value and last-value readings of ClickHouse and `serde_json` agree.+`tests/ch_event_row_filter.rs` checks all of this against a live ClickHouse, with the VM as the oracle.++Where possible, the test reads a materialized column instead of the blob.+Before each filtered chunk, the seeder looks in `system.columns` for a `String` column of `sharded_events` whose default expression is exactly that extraction for the key, and that also exists on `events`.+Only such a column is used, because a column with another expression, such as a typed `JSONExtract`, reads different values for the same row.+The column holds '' for a blob ClickHouse cannot parse, so the test admits '' there instead of reading the blob.+Without one, the test extracts from the blob: ClickHouse still decompresses the blob for the event's rows, but only the matching rows are transferred and evaluated.+The filter is dropped when the query would grow past the 8192 bytes the client sends by GET, since the `cohort_seeder` profile refuses the POST form.+`seeder_scan_row_filter_total{outcome}` reports per chunk whether the filter read materialized columns, read the blob, did not apply, or was dropped for length.++### ClickHouse settings++The client sends `max_execution_time`, the two external-spill byte thresholds, `max_bytes_in_set` and `join_algorithm` with every query.+It also sends `max_threads` (`SEEDER_CH_MAX_THREADS`), `max_memory_usage` (`SEEDER_CH_MAX_MEMORY_USAGE`) and `distributed_replica_max_ignored_errors` (`SEEDER_CH_DISTRIBUTED_REPLICA_MAX_IGNORED_ERRORS`), but only when set.+These three have no default because the `cohort_seeder` profile can constrain them, and ClickHouse fails a query that sends a value above a constraint's maximum or a disallowed value.+Set them only to go below the profile.+## Things that surprise people- `B` is the moment the seeder first saw the run, not when the run was created, except for disaster-recovery runs, whose `B` Django pins.diff --git a/posthog/settings/cohorts.py b/posthog/settings/cohorts.pyindex c5917bfd1841..8be611a89873 100644--- a/posthog/settings/cohorts.py+++ b/posthog/settings/cohorts.py@@ -34,8 +34,8 @@ BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET: int = get_from_env("BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET", 0, type_cast=int)# Bounds the ClickHouse sizing scan that runs before a person-property run is created. The scan-# reads the team's whole person history on the user-facing cluster, so it carries its own limits-# rather than the query defaults. `read_overflow_mode: throw` turns either limit into a refusal to+# reads the team's whole person history on the offline cluster, so it carries its own limits rather+# than the query defaults. `read_overflow_mode: throw` turns either limit into a refusal to# create the run, instead of a run sized off a partial scan.## Do not set either to 0. ClickHouse reads 0 as "no limit" for both, so a cleared value removes the@@ -46,6 +46,12 @@ BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_BYTES: int = get_from_env(BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_SECONDS: int = get_from_env("BEHAVIORAL_BACKFILL_PERSON_SIZING_MAX_SECONDS", 30, type_cast=int)+# Refuses a behavioral team run whose pinned event names had more events than this on the busiest+# of the last 7 complete UTC days, as a proxy for one seeder chunk's scan. Older days can hold more.+# `--max-scan-events-per-day` overrides it per invocation; 0 skips the count and the check.+BEHAVIORAL_BACKFILL_MAX_SCAN_EVENTS_PER_DAY: int = get_from_env(+ "BEHAVIORAL_BACKFILL_MAX_SCAN_EVENTS_PER_DAY", 50_000_000, type_cast=int+)BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED: bool = get_from_env("BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED", False, type_cast=str_to_bool)diff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.pyindex 44cf10a95aed..37800ee04a72 100644--- a/products/cohorts/backend/backfill/runs.py+++ b/products/cohorts/backend/backfill/runs.py@@ -22,6 +22,7 @@ from products.cohorts.backend.backfill.pinning import ()from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hashfrom products.cohorts.backend.backfill.sizing import (+ BehavioralScanEstimate,PersonSeedEstimate,PersonSeedEstimateScanCapExceeded,estimate_person_seed_topic_bytes,@@ -374,6 +375,7 @@ def create_team_backfill_run(cohort_ids: Iterable[int] | None = None,created_by_id: int | None = None,boundary_at: datetime | None = None,+ scan_estimate: BehavioralScanEstimate | None = None,) -> CohortBackfillRun:if not is_realtime_cohort_team(team_id):raise ValueError(f"Team {team_id} is not in the realtime cohort allowlist")@@ -413,6 +415,8 @@ def create_team_backfill_run(hashes[cohort.id] = ensure_filters_shape_hash(cohort)behavioral_hashes[cohort.id] = cohort.behavioral_filters_shape_hash or ""preconditions, missing = check_run_preconditions()+ if scan_estimate is not None:+ preconditions = {**preconditions, **scan_estimate.as_preconditions()}status, blocked_reason = _run_status(missing)run = CohortBackfillRun.objects.for_team(team_id).create(team_id=team_id,diff --git a/products/cohorts/backend/backfill/sizing.py b/products/cohorts/backend/backfill/sizing.pyindex a0408887cff2..2bd8c8115591 100644--- a/products/cohorts/backend/backfill/sizing.py+++ b/products/cohorts/backend/backfill/sizing.py@@ -1,10 +1,14 @@+from collections.abc import Sequencefrom dataclasses import dataclass-from datetime import datetime+from datetime import UTC, date, datetime, timedeltafrom typing import Anyfrom django.conf import settings+from django.utils import timezone as django_timezonefrom posthog.clickhouse.client import sync_execute+from posthog.clickhouse.workload import Workload+from posthog.dataclasses import frozenfrom posthog.errors import InternalCHQueryErrorfrom posthog.exceptions import ClickHouseQueryTimeOut@@ -20,6 +24,10 @@ PERSON_SEED_PER_HASH_BYTES = 38# failure._READ_CAP_ERROR_CODES = (158, 307)+# A week, so a weekend day never stands in for the weekday peak.+BEHAVIORAL_SCAN_ESTIMATE_DAYS = 7+_BEHAVIORAL_SCAN_ESTIMATE_MAX_SECONDS = 60+class PersonSeedEstimateScanCapExceeded(Exception):"""The sizing scan hit one of its own caps: the team's person history exceeds what the estimate@@ -64,6 +72,10 @@ def estimate_person_seed_topic_bytes(# Collapsing versions per id before counting keeps persons whose latest in-window row is a# deletion out of the estimate — counting them inflates the topic-byte figure and biases the# budget gate toward refusing runs that would have fit.+ #+ # `person` is sorted by (team_id, id), so in-order aggregation streams the GROUP BY instead of+ # holding every id in a hash table. No `readonly=True`: a configured readonly user takes+ # precedence over the offline host.try:rows = sync_execute("""@@ -82,15 +94,16 @@ def estimate_person_seed_topic_bytes("max_execution_time": max_execution_time,"max_bytes_to_read": max_bytes_to_read,"read_overflow_mode": "throw",+ "optimize_aggregation_in_order": 1,},+ workload=Workload.OFFLINE,team_id=team_id,- readonly=True,)except ClickHouseQueryTimeOut as error:# `max_execution_time` is this gate's own cap, so a timeout means the same thing as the byte# cap: the team's person history does not fit, and a retry pays the whole scan again for the# same answer. `trigger_cohort_backfill_run_task` retries every other exception three times,- # which at a 300 s cap is 20 minutes of scans on the user-facing cluster per cohort save.+ # which at a 300 s cap is 20 minutes of scans per cohort save.raise PersonSeedEstimateScanCapExceeded(f"Person sizing scan for team {team_id} exceeded its {max_execution_time}s time cap") from error@@ -109,3 +122,73 @@ def estimate_person_seed_topic_bytes(estimated_topic_bytes=estimated_persons * bytes_per_seed,budget_bytes=settings.BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET,)+++@frozen+class BehavioralScanEstimate:+ """A recent sample, not a bound: an older day, or a day in the run's timezone, can hold more events. The+ seeder reads fewer rows where every condition on an event name has a row filter."""++ days_sampled: int+ peak_day: date | None+ peak_day_events: int+ peak_day_events_by_name: dict[str, int]+ max_events_per_day: int++ @property+ def over_limit(self) -> bool:+ return self.max_events_per_day > 0 and self.peak_day_events > self.max_events_per_day++ def largest_events(self, count: int) -> list[tuple[str, int]]:+ return sorted(self.peak_day_events_by_name.items(), key=lambda item: (-item[1], item[0]))[:count]++ def as_preconditions(self) -> dict[str, Any]:+ return {+ "behavioral_scan_days_sampled": self.days_sampled,+ "behavioral_scan_peak_day": self.peak_day.isoformat() if self.peak_day else None,+ "behavioral_scan_peak_day_events": self.peak_day_events,+ "behavioral_scan_max_events_per_day": self.max_events_per_day,+ }+++def estimate_behavioral_scan_events(+ team_id: int,+ event_names: Sequence[str],+ *,+ max_events_per_day: int,+) -> BehavioralScanEstimate:+ """Reads `events` because that is the table the seeder scans."""+ by_day: dict[date, dict[str, int]] = {}+ if event_names:+ until = django_timezone.now().astimezone(UTC).replace(hour=0, minute=0, second=0, microsecond=0)+ rows = sync_execute(+ """+ SELECT toDate(timestamp) AS day, event, count() AS events+ FROM events+ WHERE team_id = %(team_id)s+ AND timestamp >= %(since)s+ AND timestamp < %(until)s+ AND event IN %(event_names)s+ GROUP BY day, event+ """,+ {+ "team_id": team_id,+ "since": until - timedelta(days=BEHAVIORAL_SCAN_ESTIMATE_DAYS),+ "until": until,+ "event_names": list(event_names),+ },+ settings={"max_execution_time": _BEHAVIORAL_SCAN_ESTIMATE_MAX_SECONDS},+ workload=Workload.OFFLINE,+ team_id=team_id,+ )+ for day, event, count in rows:+ by_day.setdefault(day, {})[event] = int(count)+ peak_day = max(by_day, key=lambda day: (sum(by_day[day].values()), day), default=None)+ peak_day_events_by_name = by_day[peak_day] if peak_day is not None else {}+ return BehavioralScanEstimate(+ days_sampled=BEHAVIORAL_SCAN_ESTIMATE_DAYS,+ peak_day=peak_day,+ peak_day_events=sum(peak_day_events_by_name.values()),+ peak_day_events_by_name=peak_day_events_by_name,+ max_events_per_day=max_events_per_day,+ )diff --git a/products/cohorts/backend/backfill/test/test_management_command.py b/products/cohorts/backend/backfill/test/test_management_command.pyindex 4942f47763d5..74dbb42cc9ab 100644--- a/products/cohorts/backend/backfill/test/test_management_command.py+++ b/products/cohorts/backend/backfill/test/test_management_command.py@@ -1,4 +1,4 @@-from datetime import UTC, datetime+from datetime import UTC, date, datetimefrom io import StringIOfrom posthog.test.base import BaseTest@@ -10,7 +10,19 @@ from django.test import override_settingsfrom parameterized import parameterized-from products.cohorts.backend.backfill.sizing import PersonSeedEstimate+from posthog.errors import InternalCHQueryError+from posthog.exceptions import (+ ClickHouseAtCapacity,+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQueryTimeOut,+)++from products.cohorts.backend.backfill.sizing import (+ BehavioralScanEstimate,+ PersonSeedEstimate,+ PersonSeedEstimateScanCapExceeded,+)from products.cohorts.backend.models.backfill import (CohortBackfillKind,CohortBackfillRun,@@ -34,6 +46,26 @@ _BYTECODE = ["_H", 1, 32, "matched", 32, "event", 1, 1, 11]BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET=1_000_000,)class TestCreateCohortBackfillRunCommand(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ patcher = mock.patch(+ "products.cohorts.backend.management.commands.create_cohort_backfill_run.estimate_behavioral_scan_events",+ side_effect=self._scan_estimate,+ )+ self.scan_estimate = patcher.start()+ self.addCleanup(patcher.stop)++ def _scan_estimate(+ self, team_id: int, event_names: list[str], *, max_events_per_day: int+ ) -> BehavioralScanEstimate:+ return BehavioralScanEstimate(+ days_sampled=7,+ peak_day=date(2026, 9, 28),+ peak_day_events=1_000,+ peak_day_events_by_name={"$pageview": 1_000},+ max_events_per_day=max_events_per_day,+ )+def _cohort(self, event: str) -> Cohort:return Cohort.objects.create(team=self.team,@@ -115,6 +147,7 @@ class TestCreateCohortBackfillRunCommand(BaseTest):run = CohortBackfillRun.objects.for_team(self.team.id).get()self.assertIn(str(run.id), stdout.getvalue())+ self.assertEqual(run.preconditions["behavioral_scan_peak_day_events"], 1_000)self.assertEqual(set(CohortBackfillRunCohort.objects.for_team(self.team.id)@@ -135,6 +168,7 @@ class TestCreateCohortBackfillRunCommand(BaseTest):cohort_ids=[selected.id],)+ self.assertEqual(self.scan_estimate.call_args.args[1], ["$pageview"])run = CohortBackfillRun.objects.for_team(self.team.id).get()self.assertEqual(list(@@ -226,6 +260,49 @@ class TestCreateCohortBackfillRunCommand(BaseTest):)self.assertIn("Dry run", stdout.getvalue())+ self.assertIn("Scan estimate: 1000 events", stdout.getvalue())+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)++ @parameterized.expand(+ [+ ("the_setting_refuses", {}, True),+ ("an_override_above_the_volume", {"max_scan_events_per_day": 2_000}, False),+ ("a_disabled_check", {"max_scan_events_per_day": 0}, False),+ ]+ )+ @override_settings(BEHAVIORAL_BACKFILL_MAX_SCAN_EVENTS_PER_DAY=500)+ def test_a_run_over_the_scan_limit_needs_the_operator_to_raise_it(+ self, _name: str, options: dict[str, int], refused: bool+ ) -> None:+ self._cohort("$pageview")++ if refused:+ with self.assertRaisesMessage(CommandError, "above the limit of 500"):+ call_command("create_cohort_backfill_run", team_id=self.team.id, trigger="team_enablement", **options)+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)+ else:+ call_command("create_cohort_backfill_run", team_id=self.team.id, trigger="team_enablement", **options)+ run = CohortBackfillRun.objects.for_team(self.team.id).get()+ self.assertEqual(+ run.preconditions.get("behavioral_scan_max_events_per_day"),+ options["max_scan_events_per_day"] or None,+ )++ @parameterized.expand(+ [+ ("timeout", ClickHouseQueryTimeOut()),+ ("too_slow", ClickHouseEstimatedQueryExecutionTimeTooLong()),+ ("memory", ClickHouseQueryMemoryLimitExceeded()),+ ("at_capacity", ClickHouseAtCapacity()),+ ("other", InternalCHQueryError("boom", code=60)),+ ]+ )+ def test_a_failed_scan_estimate_names_the_way_around_it(self, _name: str, raised: Exception) -> None:+ self._cohort("$pageview")+ self.scan_estimate.side_effect = raised++ with self.assertRaisesMessage(CommandError, "Pass --max-scan-events-per-day 0"):+ call_command("create_cohort_backfill_run", team_id=self.team.id, trigger="team_enablement")self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)def test_behavioral_dry_run_names_every_refusal(self) -> None:@@ -363,15 +440,28 @@ class TestCreateCohortBackfillRunCommand(BaseTest):self.assertIn("would refuse: no", stdout.getvalue())self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)+ @parameterized.expand(+ [+ ("over_budget", None, "exceed budget"),+ (+ "sizing_scan_capped",+ PersonSeedEstimateScanCapExceeded("Person sizing scan for team 1 exceeded its 30s time cap"),+ "exceeded its 30s time cap",+ ),+ ]+ )@mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")- def test_person_over_budget_returns_clean_command_error(self, estimate: mock.Mock) -> None:+ def test_person_sizing_refusal_returns_clean_command_error(+ self, _name: str, raised: Exception | None, message: str, estimate: mock.Mock+ ) -> None:self._person_cohort()estimate.return_value = self._estimate(estimated_topic_bytes=1_000_001,budget_bytes=1_000_000,)+ estimate.side_effect = raised- with self.assertRaisesMessage(CommandError, "exceed budget"):+ with self.assertRaisesMessage(CommandError, message):call_command("create_cohort_backfill_run",team_id=self.team.id,diff --git a/products/cohorts/backend/backfill/test/test_sizing.py b/products/cohorts/backend/backfill/test/test_sizing.pyindex cf423bc4374b..17a6010c404c 100644--- a/products/cohorts/backend/backfill/test/test_sizing.py+++ b/products/cohorts/backend/backfill/test/test_sizing.py@@ -1,15 +1,21 @@-from datetime import UTC, datetime+from datetime import UTC, date, datetime+import time_machinefrom unittest import mockfrom django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized+from posthog.clickhouse.workload import Workloadfrom posthog.errors import InternalCHQueryErrorfrom posthog.exceptions import ClickHouseQueryTimeOut-from products.cohorts.backend.backfill.sizing import PersonSeedEstimateScanCapExceeded, estimate_person_seed_topic_bytes+from products.cohorts.backend.backfill.sizing import (+ PersonSeedEstimateScanCapExceeded,+ estimate_behavioral_scan_events,+ estimate_person_seed_topic_bytes,+)@override_settings(@@ -53,10 +59,17 @@ class TestPersonBackfillSizing(SimpleTestCase):# scan that can finish rather than a run that always refuses.self.assertEqual(sync_execute.call_args.kwargs["settings"],- {"max_execution_time": 300, "max_bytes_to_read": 20_000_000_000, "read_overflow_mode": "throw"},+ {+ "max_execution_time": 300,+ "max_bytes_to_read": 20_000_000_000,+ "read_overflow_mode": "throw",+ "optimize_aggregation_in_order": 1,+ },)self.assertEqual(sync_execute.call_args.kwargs["team_id"], 7)- self.assertTrue(sync_execute.call_args.kwargs["readonly"])+ # A configured readonly user would take precedence over the offline host.+ self.assertEqual(sync_execute.call_args.kwargs["workload"], Workload.OFFLINE)+ self.assertNotIn("readonly", sync_execute.call_args.kwargs)@parameterized.expand([@@ -78,3 +91,42 @@ class TestPersonBackfillSizing(SimpleTestCase):with mock.patch("products.cohorts.backend.backfill.sizing.sync_execute", side_effect=raised):with self.assertRaises(InternalCHQueryError):estimate_person_seed_topic_bytes(7, datetime(2026, 5, 1, tzinfo=UTC), 2)+++class TestBehavioralScanEstimate(SimpleTestCase):+ @time_machine.travel(datetime(2026, 9, 29, 15, 30, tzinfo=UTC), tick=False)+ @mock.patch("products.cohorts.backend.backfill.sizing.sync_execute")+ def test_the_estimate_is_the_busiest_day_across_every_pinned_event(self, sync_execute: mock.Mock) -> None:+ # The largest single count falls on the other day.+ sync_execute.return_value = [+ (date(2026, 9, 27), "$pageview", 40),+ (date(2026, 9, 27), "signup", 5),+ (date(2026, 9, 28), "$pageview", 30),+ (date(2026, 9, 28), "signup", 30),+ ]++ estimate = estimate_behavioral_scan_events(7, ["$pageview", "signup"], max_events_per_day=50)++ self.assertEqual(estimate.peak_day, date(2026, 9, 28))+ self.assertEqual(estimate.peak_day_events, 60)+ self.assertTrue(estimate.over_limit)+ self.assertEqual(estimate.largest_events(1), [("$pageview", 30)])+ # Seven complete UTC days, so today's partial day never reads as a quiet one.+ self.assertEqual(+ sync_execute.call_args.args[1],+ {+ "team_id": 7,+ "since": datetime(2026, 9, 22, tzinfo=UTC),+ "until": datetime(2026, 9, 29, tzinfo=UTC),+ "event_names": ["$pageview", "signup"],+ },+ )+ self.assertEqual(sync_execute.call_args.kwargs["workload"], Workload.OFFLINE)++ @mock.patch("products.cohorts.backend.backfill.sizing.sync_execute")+ def test_no_event_names_skip_the_query(self, sync_execute: mock.Mock) -> None:+ estimate = estimate_behavioral_scan_events(7, [], max_events_per_day=50)++ sync_execute.assert_not_called()+ self.assertIsNone(estimate.peak_day)+ self.assertFalse(estimate.over_limit)diff --git a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py b/products/cohorts/backend/management/commands/create_cohort_backfill_run.pyindex d12e88f3f9cb..1edd958577ee 100644--- a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py+++ b/products/cohorts/backend/management/commands/create_cohort_backfill_run.py@@ -8,6 +8,13 @@ from django.db import IntegrityErrorfrom django.utils import timezone as django_timezonefrom django.utils.dateparse import parse_datetime+from posthog.errors import InternalCHQueryError+from posthog.exceptions import (+ ClickHouseAtCapacity,+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQueryTimeOut,+)from posthog.models.team.team import Teamfrom products.cohorts.backend.backfill.pinning import (@@ -25,7 +32,12 @@ from products.cohorts.backend.backfill.runs import (judge_team_cohorts,person_backfill_ineligibility_reason,)-from products.cohorts.backend.backfill.sizing import estimate_person_seed_topic_bytes+from products.cohorts.backend.backfill.sizing import (+ BehavioralScanEstimate,+ PersonSeedEstimateScanCapExceeded,+ estimate_behavioral_scan_events,+ estimate_person_seed_topic_bytes,+)from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillRunCohort, CohortBackfillTriggerfrom products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.leaf_shape import walk_filter_leaves@@ -64,6 +76,15 @@ class Command(BaseCommand):parser.add_argument("--cohort-ids", type=int, nargs="+")parser.add_argument("--boundary-at", help="ISO 8601 disaster recovery boundary with a UTC offset")parser.add_argument("--person-horizon-days", type=int)+ parser.add_argument(+ "--max-scan-events-per-day",+ type=int,+ help=(+ "Behavioral runs only: refuse the run when its pinned event names had more events than this on "+ "any of the last 7 complete UTC days. Overrides BEHAVIORAL_BACKFILL_MAX_SCAN_EVENTS_PER_DAY; "+ "0 disables it."+ ),+ )parser.add_argument("--dry-run", action="store_true")def handle(self, *args: Any, **options: Any) -> None:@@ -78,6 +99,13 @@ class Command(BaseCommand):raise CommandError("--person-horizon-days is required with --kind person_property")if kind == CohortBackfillKind.BEHAVIORAL and person_horizon_days is not None:raise CommandError("--person-horizon-days is only valid with --kind person_property")+ max_scan_events_per_day: int | None = options.get("max_scan_events_per_day")+ if kind == CohortBackfillKind.PERSON_PROPERTY and max_scan_events_per_day is not None:+ raise CommandError("--max-scan-events-per-day is only valid with --kind behavioral")+ if max_scan_events_per_day is None:+ max_scan_events_per_day = settings.BEHAVIORAL_BACKFILL_MAX_SCAN_EVENTS_PER_DAY+ if max_scan_events_per_day < 0:+ raise CommandError("--max-scan-events-per-day must be 0 or more")if not is_realtime_cohort_team(team_id):raise CommandError(f"Team {team_id} is not in the realtime cohort allowlist")@@ -106,10 +134,37 @@ class Command(BaseCommand):f"Dry run: {len(cohorts)} cohorts, {len(pinned['conditions'])} conditions, "f"{len(event_names)} event names")+ if max_scan_events_per_day:+ self._write_scan_estimate(+ self._scan_estimate(team_id, event_names, max_scan_events_per_day), len(event_names)+ )+ else:+ self.stdout.write("Scan estimate: skipped, because the limit is 0")return+ scan_estimate: BehavioralScanEstimate | None = None+ if max_scan_events_per_day:+ # Estimated before the creator locks the cohorts, so an edit in between can shift the names.+ # The limit is a preflight, not a guarantee: the save path creates runs without it.+ eligible = [+ cohort+ for cohort, reason in judge_team_cohorts(team_id, cohort_ids, behavioral_backfill_ineligibility_reason)+ if reason is None+ ]+ _, event_names = pin_conditions_for_cohorts(eligible)+ scan_estimate = self._scan_estimate(team_id, event_names, max_scan_events_per_day)+ self._write_scan_estimate(scan_estimate, len(event_names))+ if scan_estimate.over_limit:+ raise CommandError(+ f"The run would scan {scan_estimate.peak_day_events} events on its busiest day "+ f"({scan_estimate.peak_day}), above the limit of {scan_estimate.max_events_per_day}. "+ "Narrow it with --cohort-ids, or pass --max-scan-events-per-day to accept the volume."+ )+try:- run = create_team_backfill_run(team_id, trigger, cohort_ids, boundary_at=boundary_at)+ run = create_team_backfill_run(+ team_id, trigger, cohort_ids, boundary_at=boundary_at, scan_estimate=scan_estimate+ )except (Team.DoesNotExist, ValueError) as error:raise CommandError(str(error)) from errorexcept IntegrityError as error:@@ -156,7 +211,7 @@ class Command(BaseCommand):cohort_ids,boundary_at=boundary_at,)- except (Team.DoesNotExist, ValueError) as error:+ except (Team.DoesNotExist, ValueError, PersonSeedEstimateScanCapExceeded) as error:raise CommandError(str(error)) from errorexcept IntegrityError as error:raise CommandError(f"Team {team_id} already has an active person-property team backfill run") from error@@ -200,11 +255,14 @@ class Command(BaseCommand):person_scan_since = (normalized_boundary or django_timezone.now()) - timedelta(days=person_horizon_days)except (OverflowError, ValueError) as error:raise CommandError(str(error)) from error- estimate = estimate_person_seed_topic_bytes(- team_id,- person_scan_since,- len(pinned["conditions"]),- )+ try:+ estimate = estimate_person_seed_topic_bytes(+ team_id,+ person_scan_since,+ len(pinned["conditions"]),+ )+ except PersonSeedEstimateScanCapExceeded as error:+ raise CommandError(str(error)) from errorverdict = "yes" if estimate.over_budget else "no"self.stdout.write(f"Dry run: {len(cohorts)} cohorts, {len(pinned['conditions'])} conditions, "@@ -213,6 +271,29 @@ class Command(BaseCommand):f"would refuse: {verdict}")+ def _scan_estimate(self, team_id: int, event_names: list[str], max_events_per_day: int) -> BehavioralScanEstimate:+ try:+ return estimate_behavioral_scan_events(team_id, event_names, max_events_per_day=max_events_per_day)+ except (+ ClickHouseQueryTimeOut,+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseAtCapacity,+ InternalCHQueryError,+ ) as error:+ raise CommandError(+ f"The scan estimate failed: {error}. Pass --max-scan-events-per-day 0 to create the run without it."+ ) from error++ def _write_scan_estimate(self, estimate: BehavioralScanEstimate, event_name_count: int) -> None:+ largest = ", ".join(f"{name} {count}" for name, count in estimate.largest_events(5)) or "none"+ verdict = "yes" if estimate.over_limit else "no"+ self.stdout.write(+ f"Scan estimate: {estimate.peak_day_events} events on the busiest of the last {estimate.days_sampled} "+ f"complete UTC days ({estimate.peak_day or 'no events'}) across {event_name_count} event names, "+ f"limit {estimate.max_events_per_day}, would refuse: {verdict}. Largest on that day: {largest}"+ )+def _dry_run_cohorts(self,team_id: int,diff --git a/rust/cohort-core/src/hogvm/analysis/mod.rs b/rust/cohort-core/src/hogvm/analysis/mod.rsindex 6856ad6a3d20..4a9968c5bab9 100644--- a/rust/cohort-core/src/hogvm/analysis/mod.rs+++ b/rust/cohort-core/src/hogvm/analysis/mod.rs@@ -40,6 +40,7 @@ mod decode;mod event_only;mod plan;mod projection;+mod row_filter;use std::collections::BTreeSet;@@ -49,6 +50,7 @@ use serde_json::Value;pub use decode::DecodeError;pub use plan::{GlobalsBuild, GlobalsPlan};pub use projection::AnalysisBudget;+pub use row_filter::{event_row_filter, EventRowFilter, PropertyAlternatives};/// What a static pass could establish about one condition's bytecode.#[derive(Debug, Clone, PartialEq, Eq)]diff --git a/rust/cohort-core/src/hogvm/analysis/row_filter.rs b/rust/cohort-core/src/hogvm/analysis/row_filter.rsnew file mode 100644index 000000000000..d329d29d87e4--- /dev/null+++ b/rust/cohort-core/src/hogvm/analysis/row_filter.rs@@ -0,0 +1,538 @@+//! Derives the event property values a row must carry for a condition's program to return true.+//!+//! A filter that drops a row the program matches loses membership, so the grammar is exact: string+//! literals, reads of `event` and `properties.<key>`, `==`, `AND` and `OR`. Any other opcode yields+//! no filter. An unrecognized `==` may still stand as an `AND` operand and is ignored, because the+//! VM's `AND` evaluates every operand and requires all of them to be truthy.++use std::collections::{BTreeMap, BTreeSet};+use std::str::FromStr;+use std::sync::Arc;++use hogvm::{Num, Operation};+use serde_json::Value;++use super::decode::{decode, InstrKind};++/// A necessary condition for the program to return true: the row's `event` is [`Self::event`], and+/// every conjunct has some `(key, value)` with `properties[key] == value` under HogVM equality.+///+/// HogVM equality coerces, so besides the string `value` it also holds for any JSON boolean+/// (compared with `value.to_lowercase() == "true"`) and for an object carrying a temporal marker+/// (compared by epoch). A value that parses as a number is never kept, because it would also equal a+/// JSON number. A consumer that renders a row filter must admit all of these.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct EventRowFilter {+ pub event: String,+ /// Never empty.+ pub conjuncts: Vec<PropertyAlternatives>,+}++/// A disjunction of `properties[key] == value`, grouped by key.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PropertyAlternatives(BTreeMap<String, BTreeSet<String>>);++impl PropertyAlternatives {+ pub fn iter(&self) -> impl Iterator<Item = (&str, &BTreeSet<String>)> {+ self.0.iter().map(|(key, values)| (key.as_str(), values))+ }+}++#[derive(Debug, Clone)]+enum Node {+ Literal(Arc<str>),+ /// A `GET_GLOBAL` chain, root first.+ Global(Vec<Arc<str>>),+ EventIs(Arc<str>),+ PropertyIs {+ key: Arc<str>,+ value: Arc<str>,+ },+ OtherEquality,+ And(Vec<Node>),+ Or(Vec<Node>),+}++impl Node {+ const fn is_boolean(&self) -> bool {+ !matches!(self, Self::Literal(_) | Self::Global(_))+ }+}++pub fn event_row_filter(bytecode: &[Value]) -> Option<EventRowFilter> {+ let root = parse(bytecode)?;+ let mut conjuncts = Vec::new();+ flatten_and(root, &mut conjuncts);++ let mut event: Option<Arc<str>> = None;+ let mut filters = Vec::new();+ for conjunct in conjuncts {+ match conjunct {+ Node::EventIs(name) => match &event {+ Some(existing) if *existing != name => return None,+ Some(_) => {}+ None => event = Some(name),+ },+ other => filters.extend(alternatives(other)),+ }+ }+ let event = event?;+ if filters.is_empty() {+ return None;+ }+ Some(EventRowFilter {+ event: event.to_string(),+ conjuncts: filters,+ })+}++fn parse(bytecode: &[Value]) -> Option<Node> {+ let decoded = decode(bytecode).ok()?;+ let mut stack: Vec<Node> = Vec::new();+ let mut returned: Option<Node> = None;+ for instr in &decoded.instrs {+ // The loader appends a `RETURN` to programs that may already end in one.+ if returned.is_some() {+ if matches!(instr.kind, InstrKind::Bare(Operation::Return)) {+ continue;+ }+ return None;+ }+ match &instr.kind {+ InstrKind::String(literal) => stack.push(Node::Literal(literal.clone())),+ InstrKind::Counted(Operation::GetGlobal, count) => {+ if *count == 0 {+ return None;+ }+ let mut chain = Vec::with_capacity(*count);+ for _ in 0..*count {+ match stack.pop()? {+ Node::Literal(segment) => chain.push(segment),+ _ => return None,+ }+ }+ stack.push(Node::Global(chain));+ }+ InstrKind::Bare(Operation::Eq) => {+ let top = stack.pop()?;+ let below = stack.pop()?;+ stack.push(equality(top, below));+ }+ InstrKind::Counted(op @ (Operation::And | Operation::Or), count) => {+ if *count == 0 || *count > stack.len() {+ return None;+ }+ let operands = stack.split_off(stack.len() - count);+ if !operands.iter().all(Node::is_boolean) {+ return None;+ }+ stack.push(if *op == Operation::And {+ Node::And(operands)+ } else {+ Node::Or(operands)+ });+ }+ InstrKind::Bare(Operation::Return) => {+ if stack.len() != 1 {+ return None;+ }+ returned = stack.pop();+ }+ _ => return None,+ }+ }+ returned.filter(Node::is_boolean)+}++fn equality(left: Node, right: Node) -> Node {+ let (literal, chain) = match (left, right) {+ (Node::Literal(literal), Node::Global(chain))+ | (Node::Global(chain), Node::Literal(literal)) => (literal, chain),+ _ => return Node::OtherEquality,+ };+ match chain.as_slice() {+ [root] if &**root == "event" => Node::EventIs(literal),+ [root, key] if &**root == "properties" => Node::PropertyIs {+ key: key.clone(),+ value: literal,+ },+ _ => Node::OtherEquality,+ }+}++fn flatten_and(node: Node, out: &mut Vec<Node>) {+ match node {+ Node::And(operands) => {+ for operand in operands {+ flatten_and(operand, out);+ }+ }+ other => out.push(other),+ }+}++fn flatten_or(node: Node, out: &mut Vec<Node>) {+ match node {+ Node::Or(operands) => {+ for operand in operands {+ flatten_or(operand, out);+ }+ }+ other => out.push(other),+ }+}++fn alternatives(conjunct: Node) -> Option<PropertyAlternatives> {+ let mut disjuncts = Vec::new();+ flatten_or(conjunct, &mut disjuncts);+ let mut by_key: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+ for disjunct in disjuncts {+ let Node::PropertyIs { key, value } = disjunct else {+ return None;+ };+ if Num::from_str(&value).is_ok() {+ return None;+ }+ by_key+ .entry(key.to_string())+ .or_default()+ .insert(value.to_string());+ }+ (!by_key.is_empty()).then_some(PropertyAlternatives(by_key))+}++#[cfg(test)]+mod tests {+ use proptest::prelude::*;+ use serde_json::json;++ use super::*;+ use crate::hogvm::{evaluate_detailed, EvalOutcome};++ const STRING: u64 = Operation::String as u64;+ const GET_GLOBAL: u64 = Operation::GetGlobal as u64;+ const EQ: u64 = Operation::Eq as u64;+ const AND: u64 = Operation::And as u64;+ const OR: u64 = Operation::Or as u64;+ const RETURN: u64 = Operation::Return as u64;++ fn event_is(name: &str) -> Vec<Value> {+ vec![+ json!(STRING),+ json!(name),+ json!(STRING),+ json!("event"),+ json!(GET_GLOBAL),+ json!(1),+ json!(EQ),+ ]+ }++ fn property_is(key: &str, value: &str) -> Vec<Value> {+ vec![+ json!(STRING),+ json!(value),+ json!(STRING),+ json!(key),+ json!(STRING),+ json!("properties"),+ json!(GET_GLOBAL),+ json!(2),+ json!(EQ),+ ]+ }++ fn person_property_is(key: &str, value: &str) -> Vec<Value> {+ vec![+ json!(STRING),+ json!(value),+ json!(STRING),+ json!(key),+ json!(STRING),+ json!("properties"),+ json!(STRING),+ json!("person"),+ json!(GET_GLOBAL),+ json!(3),+ json!(EQ),+ ]+ }++ fn fold(op: u64, operands: Vec<Vec<Value>>) -> Vec<Value> {+ let count = operands.len();+ let mut tokens: Vec<Value> = operands.into_iter().flatten().collect();+ tokens.push(json!(op));+ tokens.push(json!(count));+ tokens+ }++ fn program(body: Vec<Value>) -> Vec<Value> {+ let mut tokens = vec![json!("_H"), json!(1)];+ tokens.extend(body);+ tokens.push(json!(RETURN));+ tokens+ }++ fn filter(event: &str, conjuncts: &[&[(&str, &[&str])]]) -> EventRowFilter {+ EventRowFilter {+ event: event.to_owned(),+ conjuncts: conjuncts+ .iter()+ .map(|alternatives| {+ PropertyAlternatives(+ alternatives+ .iter()+ .map(|(key, values)| {+ (+ (*key).to_owned(),+ values.iter().map(|value| (*value).to_owned()).collect(),+ )+ })+ .collect(),+ )+ })+ .collect(),+ }+ }++ #[test]+ fn compiled_event_filters_yield_their_row_filters() {+ let cases: Vec<(&str, Vec<Value>, EventRowFilter)> = vec![+ (+ "one exact value",+ fold(+ AND,+ vec![+ event_is("$feature_flag_called"),+ property_is("$feature_flag", "my-flag"),+ ],+ ),+ filter(+ "$feature_flag_called",+ &[&[("$feature_flag", &["my-flag"])]],+ ),+ ),+ (+ "a value list",+ fold(+ AND,+ vec![+ event_is("$feature_flag_called"),+ fold(+ OR,+ vec![+ property_is("$feature_flag", "a"),+ property_is("$feature_flag", "b"),+ ],+ ),+ ],+ ),+ filter("$feature_flag_called", &[&[("$feature_flag", &["a", "b"])]]),+ ),+ (+ "two filters, one of them on the person",+ fold(+ AND,+ vec![+ event_is("purchase"),+ fold(+ AND,+ vec![+ person_property_is("plan", "pro"),+ property_is("currency", "EUR"),+ ],+ ),+ ],+ ),+ filter("purchase", &[&[("currency", &["EUR"])]]),+ ),+ (+ "two event properties",+ fold(+ AND,+ vec![+ event_is("purchase"),+ fold(+ AND,+ vec![property_is("currency", "EUR"), property_is("plan", "pro")],+ ),+ ],+ ),+ filter(+ "purchase",+ &[&[("currency", &["EUR"])], &[("plan", &["pro"])]],+ ),+ ),+ (+ "a disjunction across keys",+ fold(+ AND,+ vec![+ event_is("purchase"),+ fold(OR, vec![property_is("a", "x"), property_is("b", "y")]),+ ],+ ),+ filter("purchase", &[&[("a", &["x"]), ("b", &["y"])]]),+ ),+ ];+ for (label, body, expected) in cases {+ assert_eq!(event_row_filter(&program(body)), Some(expected), "{label}");+ }+ }++ #[test]+ fn programs_outside_the_grammar_yield_no_filter() {+ let not_equal = {+ let mut tokens = property_is("$feature_flag", "my-flag");+ *tokens.last_mut().unwrap() = json!(Operation::NotEq as u64);+ fold(AND, vec![event_is("e"), tokens])+ };+ let case_insensitive = {+ let mut tokens = property_is("$current_url", "%pricing%");+ *tokens.last_mut().unwrap() = json!(Operation::Ilike as u64);+ fold(AND, vec![event_is("e"), tokens])+ };+ let cases: Vec<(&str, Vec<Value>)> = vec![+ ("the event alone", event_is("e")),+ ("a property alone", property_is("k", "v")),+ ("a negated equality", not_equal),+ ("a pattern match", case_insensitive),+ (+ "a numeric value",+ fold(AND, vec![event_is("e"), property_is("k", "42")]),+ ),+ (+ "a value that parses as a float",+ fold(AND, vec![event_is("e"), property_is("k", "1e3")]),+ ),+ (+ "only a nested property path",+ fold(+ AND,+ vec![+ event_is("e"),+ vec![+ json!(STRING),+ json!("v"),+ json!(STRING),+ json!("b"),+ json!(STRING),+ json!("a"),+ json!(STRING),+ json!("properties"),+ json!(GET_GLOBAL),+ json!(3),+ json!(EQ),+ ],+ ],+ ),+ ),+ (+ "an OR that also admits the event itself",+ fold(+ AND,+ vec![+ event_is("e"),+ fold(OR, vec![property_is("k", "v"), event_is("f")]),+ ],+ ),+ ),+ (+ "the event under an OR",+ fold(OR, vec![event_is("e"), property_is("k", "v")]),+ ),+ (+ "two different events",+ fold(+ AND,+ vec![event_is("e"), event_is("f"), property_is("k", "v")],+ ),+ ),+ (+ "a string operand of AND",+ fold(AND, vec![event_is("e"), vec![json!(STRING), json!("v")]]),+ ),+ ];+ for (label, body) in cases {+ assert_eq!(event_row_filter(&program(body)), None, "{label}");+ }++ let mut unterminated = program(fold(AND, vec![event_is("e"), property_is("k", "v")]));+ unterminated.pop();+ assert_eq!(event_row_filter(&unterminated), None, "no RETURN");+ let mut trailing = program(fold(AND, vec![event_is("e"), property_is("k", "v")]));+ trailing.push(json!(Operation::True as u64));+ assert_eq!(event_row_filter(&trailing), None, "code after RETURN");+ }++ fn property_value() -> impl Strategy<Value = Value> {+ let leaf = prop_oneof![+ Just(Value::Null),+ any::<bool>().prop_map(Value::Bool),+ any::<i64>().prop_map(|number| json!(number)),+ (-1e6f64..1e6).prop_map(|number| json!(number)),+ prop_oneof![+ Just("my-flag".to_owned()),+ Just("true".to_owned()),+ Just("TRUE".to_owned()),+ Just("false".to_owned()),+ Just(String::new()),+ Just("2024-01-01".to_owned()),+ Just("a\"b\\c\n".to_owned()),+ "\\PC{0,6}",+ ]+ .prop_map(Value::String),+ ];+ leaf.prop_recursive(2, 6, 3, |inner| {+ prop_oneof![+ prop::collection::vec(inner.clone(), 0..3).prop_map(Value::Array),+ Just(json!({"__hogDateTime__": true, "dt": 1_704_067_200.0, "zone": "UTC"})),+ Just(json!({"__hogDate__": true, "year": 2024, "month": 1, "day": 1})),+ inner.prop_map(|value| json!({ "nested": value })),+ ]+ })+ }++ fn filter_value() -> impl Strategy<Value = String> {+ prop_oneof![+ Just("my-flag".to_owned()),+ Just("true".to_owned()),+ Just("True".to_owned()),+ Just("false".to_owned()),+ Just(String::new()),+ Just("2024-01-01".to_owned()),+ Just("2024-01-01T00:00:00Z".to_owned()),+ Just("a\"b\\c\n".to_owned()),+ "\\PC{0,6}",+ ]+ }++ proptest! {+ /// Checks the [`EventRowFilter`] contract against the VM, so a change to HogVM equality that+ /// matches a string against another JSON type fails here.+ #[test]+ fn a_program_match_implies_a_value_the_filter_admits(+ actual in property_value(),+ expected in filter_value(),+ ) {+ let bytecode = program(fold(+ AND,+ vec![event_is("e"), property_is("k", &expected)],+ ));+ let Some(row_filter) = event_row_filter(&bytecode) else {+ prop_assert!(Num::from_str(&expected).is_ok());+ return Ok(());+ };+ prop_assert_eq!(&row_filter.event, "e");+ let globals = json!({"event": "e", "properties": {"k": actual.clone()}});+ if let EvalOutcome::Matched(true) = evaluate_detailed(&bytecode, globals) {+ let admitted = match &actual {+ Value::String(value) => *value == expected,+ Value::Bool(_) | Value::Object(_) => true,+ Value::Null | Value::Number(_) | Value::Array(_) => false,+ };+ prop_assert!(admitted, "the VM matched {actual} against {expected:?}");+ }+ }+ }+}diff --git a/rust/cohort-seeder/src/app/breaker.rs b/rust/cohort-seeder/src/app/breaker.rsnew file mode 100644index 000000000000..5cd104f9aabd--- /dev/null+++ b/rust/cohort-seeder/src/app/breaker.rs@@ -0,0 +1,360 @@+//! App layer: the per-run breaker that stops claiming a run's chunks while ClickHouse keeps refusing+//! its scans for lack of resources.+//!+//! The chunk retry backoff delays only the failed chunk, so without this a run's pending chunks+//! refill every freed slot with a scan that fails the same way. The state is process-local, so a+//! restart closes every breaker.++use std::collections::HashMap;+use std::num::NonZeroU32;+use std::time::{Duration, Instant};++use crate::domain::backoff::MAX_RETRY_BACKOFF_CAP;+use crate::domain::{AttemptCount, BackoffPolicyError, RetryBackoffPolicy, RunId};++/// Not shorter than any cooldown, so an open breaker is never dropped before it would close.+const IDLE_EXPIRY: Duration = MAX_RETRY_BACKOFF_CAP;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct BreakerPolicy {+ threshold: NonZeroU32,+ cooldown: RetryBackoffPolicy,+ max_trips: NonZeroU32,+}++impl BreakerPolicy {+ /// `threshold` resource failures in a row open the breaker for `cooldown_base × 2^(trip - 1)`,+ /// capped at `cooldown_cap`. The `max_trips`-th opening without a confirmed chunk fails the run.+ pub fn new(+ threshold: u32,+ cooldown_base: Duration,+ cooldown_cap: Duration,+ max_trips: u32,+ ) -> Result<Self, BreakerPolicyError> {+ Ok(Self {+ threshold: NonZeroU32::new(threshold).ok_or(BreakerPolicyError::ZeroThreshold)?,+ cooldown: RetryBackoffPolicy::new(cooldown_base, cooldown_cap)+ .map_err(BreakerPolicyError::Cooldown)?,+ max_trips: NonZeroU32::new(max_trips).ok_or(BreakerPolicyError::ZeroMaxTrips)?,+ })+ }++ fn cooldown(self, trip: u32) -> Duration {+ self.cooldown.ceiling(AttemptCount::new(trip))+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum BreakerPolicyError {+ #[error("the breaker failure threshold must be greater than zero")]+ ZeroThreshold,+ #[error("the breaker trip limit must be greater than zero")]+ ZeroMaxTrips,+ #[error("invalid breaker cooldown: {0}")]+ Cooldown(BackoffPolicyError),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum State {+ Closed {+ consecutive: u32,+ },+ /// A failure that arrives while open came from a chunk claimed before the trip, so it does not+ /// count.+ Open {+ until: Instant,+ trips: u32,+ },+ HalfOpen {+ trips: u32,+ },+ /// The caller fails the run. [`RunBreakers::retry_exhausted`] admits one more probe when that+ /// write does not apply.+ Exhausted,+}++#[derive(Debug, Clone, Copy)]+struct Entry {+ state: State,+ touched: Instant,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BreakerEvent {+ Unchanged,+ Tripped {+ trips: u32,+ cooldown: Duration,+ },+ /// The caller fails the run.+ Exhausted {+ trips: u32,+ },+}++#[derive(Debug)]+pub struct RunBreakers {+ policy: BreakerPolicy,+ entries: HashMap<RunId, Entry>,+}++impl RunBreakers {+ pub fn new(policy: BreakerPolicy) -> Self {+ Self {+ policy,+ entries: HashMap::new(),+ }+ }++ /// The breaker turns half-open only once none of the run's chunks is in flight, so the one+ /// probe it then admits is the only chunk whose result the half-open state counts.+ pub fn admits(&mut self, run_id: RunId, now: Instant, run_in_flight: bool) -> bool {+ let Some(entry) = self.entries.get_mut(&run_id) else {+ return true;+ };+ match entry.state {+ State::Closed { .. } => true,+ State::Open { until, trips } if now >= until && !run_in_flight => {+ entry.state = State::HalfOpen { trips };+ true+ }+ State::Open { .. } | State::Exhausted => false,+ State::HalfOpen { .. } => !run_in_flight,+ }+ }++ /// While open or exhausted, every chunk in flight was claimed before the breaker opened, so its+ /// confirmation says nothing about whether ClickHouse has recovered.+ pub fn record_success(&mut self, run_id: RunId) {+ if self.entries.get(&run_id).is_some_and(|entry| {+ matches!(entry.state, State::Closed { .. } | State::HalfOpen { .. })+ }) {+ self.entries.remove(&run_id);+ }+ }++ /// Failing the run did not apply. The next probe's resource failure exhausts the breaker again,+ /// so the caller retries the write, and a confirmed probe closes it.+ pub fn retry_exhausted(&mut self, run_id: RunId) {+ let retry = State::HalfOpen {+ trips: self.policy.max_trips.get() - 1,+ };+ if let Some(entry) = self+ .entries+ .get_mut(&run_id)+ .filter(|entry| entry.state == State::Exhausted)+ {+ entry.state = retry;+ }+ }++ pub fn record_resource_failure(&mut self, run_id: RunId, now: Instant) -> BreakerEvent {+ let entry = self.entries.entry(run_id).or_insert(Entry {+ state: State::Closed { consecutive: 0 },+ touched: now,+ });+ entry.touched = now;+ let trips_before = match entry.state {+ State::Closed { consecutive } => {+ let consecutive = consecutive.saturating_add(1);+ if consecutive < self.policy.threshold.get() {+ entry.state = State::Closed { consecutive };+ return BreakerEvent::Unchanged;+ }+ 0+ }+ State::Open { .. } | State::Exhausted => return BreakerEvent::Unchanged,+ State::HalfOpen { trips } => trips,+ };+ let trips = trips_before.saturating_add(1);+ if trips >= self.policy.max_trips.get() {+ entry.state = State::Exhausted;+ return BreakerEvent::Exhausted { trips };+ }+ let cooldown = self.policy.cooldown(trips);+ entry.state = State::Open {+ until: now + cooldown,+ trips,+ };+ BreakerEvent::Tripped { trips, cooldown }+ }++ pub fn is_open(&self, run_id: RunId) -> bool {+ self.entries+ .get(&run_id)+ .is_some_and(|entry| !matches!(entry.state, State::Closed { .. }))+ }++ /// Keyed on age rather than on the eligible-run set, because a discovery error yields an empty+ /// set and would reset every breaker.+ pub fn expire_idle(&mut self, now: Instant) {+ self.entries.retain(|_, entry| {+ let open_until_future = matches!(entry.state, State::Open { until, .. } if until > now);+ open_until_future || now.duration_since(entry.touched) < IDLE_EXPIRY+ });+ }+}++#[cfg(test)]+mod tests {+ use uuid::Uuid;++ use super::*;++ const BASE: Duration = Duration::from_secs(300);++ fn breakers(threshold: u32, max_trips: u32) -> RunBreakers {+ RunBreakers::new(+ BreakerPolicy::new(threshold, BASE, Duration::from_secs(1800), max_trips).unwrap(),+ )+ }++ fn run() -> RunId {+ RunId(Uuid::from_u128(1))+ }++ #[test]+ fn consecutive_resource_failures_trip_then_probe_then_exhaust() {+ let mut breakers = breakers(3, 3);+ let start = Instant::now();++ assert_eq!(+ breakers.record_resource_failure(run(), start),+ BreakerEvent::Unchanged+ );+ assert_eq!(+ breakers.record_resource_failure(run(), start),+ BreakerEvent::Unchanged+ );+ assert!(breakers.admits(run(), start, true));+ assert_eq!(+ breakers.record_resource_failure(run(), start),+ BreakerEvent::Tripped {+ trips: 1,+ cooldown: BASE+ }+ );+ assert_eq!(+ breakers.record_resource_failure(run(), start),+ BreakerEvent::Unchanged,+ "a straggler claimed before the trip counted as new evidence"+ );+ assert!(!breakers.admits(run(), start + BASE / 2, false));++ assert!(breakers.admits(run(), start + BASE, false));+ assert!(+ !breakers.admits(run(), start + BASE, true),+ "a second probe was admitted beside the first"+ );+ assert_eq!(+ breakers.record_resource_failure(run(), start + BASE),+ BreakerEvent::Tripped {+ trips: 2,+ cooldown: BASE * 2+ },+ "a failed probe waited for the threshold again"+ );+ assert!(!breakers.admits(run(), start + BASE * 2, false));++ assert!(breakers.admits(run(), start + BASE * 3, false));+ assert_eq!(+ breakers.record_resource_failure(run(), start + BASE * 3),+ BreakerEvent::Exhausted { trips: 3 }+ );+ assert!(+ !breakers.admits(run(), start + BASE * 100, false),+ "an exhausted run went back to full concurrency"+ );++ breakers.retry_exhausted(run());+ assert!(+ breakers.admits(run(), start + BASE * 100, false),+ "a run whose failure did not apply stayed refused for good"+ );+ assert_eq!(+ breakers.record_resource_failure(run(), start + BASE * 100),+ BreakerEvent::Exhausted { trips: 3 }+ );+ }++ #[test]+ fn chunks_claimed_before_the_trip_neither_count_nor_close_it() {+ let mut breakers = breakers(1, 2);+ let start = Instant::now();+ breakers.record_resource_failure(run(), start);++ assert!(+ !breakers.admits(run(), start + BASE, true),+ "a probe was admitted beside a chunk claimed before the trip"+ );+ assert_eq!(+ breakers.record_resource_failure(run(), start + BASE),+ BreakerEvent::Unchanged,+ "a chunk claimed before the trip counted as a failed probe"+ );+ breakers.record_success(run());+ assert!(+ breakers.is_open(run()),+ "a chunk claimed before the trip closed the breaker"+ );++ assert!(breakers.admits(run(), start + BASE, false));+ assert_eq!(+ breakers.record_resource_failure(run(), start + BASE),+ BreakerEvent::Exhausted { trips: 2 }+ );+ }++ #[test]+ fn a_confirmed_chunk_resets_the_failures_in_a_row() {+ let mut breakers = breakers(3, 4);+ let start = Instant::now();+ breakers.record_resource_failure(run(), start);+ breakers.record_resource_failure(run(), start);+ breakers.record_success(run());++ assert_eq!(+ breakers.record_resource_failure(run(), start),+ BreakerEvent::Unchanged+ );+ assert_eq!(+ breakers.record_resource_failure(run(), start),+ BreakerEvent::Unchanged+ );+ assert!(!breakers.is_open(run()));+ }++ #[test]+ fn a_confirmed_chunk_closes_the_breaker_and_resets_the_trip_count() {+ let mut breakers = breakers(1, 2);+ let start = Instant::now();+ assert!(matches!(+ breakers.record_resource_failure(run(), start),+ BreakerEvent::Tripped { trips: 1, .. }+ ));+ assert!(breakers.admits(run(), start + BASE, false));++ breakers.record_success(run());++ assert!(breakers.admits(run(), start + BASE, true));+ assert!(matches!(+ breakers.record_resource_failure(run(), start + BASE),+ BreakerEvent::Tripped { trips: 1, .. }+ ));+ }++ #[test]+ fn an_open_breaker_outlives_the_idle_expiry_until_its_cooldown_ends() {+ let mut breakers = RunBreakers::new(+ BreakerPolicy::new(1, MAX_RETRY_BACKOFF_CAP, MAX_RETRY_BACKOFF_CAP, 2).unwrap(),+ );+ let start = Instant::now();+ breakers.record_resource_failure(run(), start);++ breakers.expire_idle(start + IDLE_EXPIRY - Duration::from_secs(1));+ assert!(breakers.is_open(run()));++ breakers.expire_idle(start + IDLE_EXPIRY + Duration::from_secs(1));+ assert!(!breakers.is_open(run()));+ }+}diff --git a/rust/cohort-seeder/src/app/execute.rs b/rust/cohort-seeder/src/app/execute.rsindex 479ec59e5809..f855774ba563 100644--- a/rust/cohort-seeder/src/app/execute.rs+++ b/rust/cohort-seeder/src/app/execute.rs@@ -14,13 +14,16 @@ use tokio_util::sync::CancellationToken;use tracing::{info, warn};use crate::clickhouse::scanner::ChunkScanner;+use crate::clickhouse::ResourceError;use crate::domain::{ChunkLease, ChunkSpec, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, ProducedChunk,RetryBackoffPolicy, ScannedChunk, StreamedChunk,};use crate::kafka::pacing::TilePacer;use crate::kafka::producer::SeedTileProducer;-use crate::observability::metrics::{CHUNKS_CONFIRMED, CHUNKS_FAILED, TILES_PRODUCED};+use crate::observability::metrics::{+ CHUNKS_CONFIRMED, CHUNKS_FAILED, CLICKHOUSE_RESOURCE_ERRORS, TILES_PRODUCED,+};use crate::store::chunks::{ChunkStoreError, PgChunkStore};use crate::store::lease::LeaseHandle;use crate::store::runs::RunKind;@@ -193,7 +196,7 @@ impl FailureDisposition {/// The retry wait is drawn from the chunk's own attempt count, so a chunk failing repeatedly waits/// longer each time while a first failure retries almost immediately. An unclaim draws none: it/// refunds the attempt and is not a failure.-pub(super) async fn resolve_halt<S: ChunkState, E: std::error::Error>(+pub(super) async fn resolve_halt<S: ChunkState, E: std::error::Error + 'static>(store: &PgChunkStore,halt: Halted<S, E>,shutdown: &CancellationToken,@@ -202,12 +205,17 @@ pub(super) async fn resolve_halt<S: ChunkState, E: std::error::Error>(let spec = halt.state.spec();let lease = spec.lease;let detail = render_reason(&halt.reason);+ let resource = match &halt.reason {+ HaltReason::Failed(error) => ResourceError::classify(error),+ HaltReason::Cancelled(_) => None,+ };match FailureDisposition::resolve(S::STAGE, shutdown.is_cancelled()) {FailureDisposition::Unclaim => match store.unclaim(lease).await {Ok(()) => ChunkOutcome::Unclaimed { lease },Err(recovery) => ChunkOutcome::RecoveryFailed {lease,detail: detail.as_str().to_string(),+ resource,recovery,},},@@ -217,11 +225,13 @@ pub(super) async fn resolve_halt<S: ChunkState, E: std::error::Error>(Ok(()) => ChunkOutcome::Failed {lease,detail: detail.as_str().to_string(),+ resource,retry_delay,},Err(recovery) => ChunkOutcome::RecoveryFailed {lease,detail: detail.as_str().to_string(),+ resource,recovery,},}@@ -265,20 +275,60 @@ pub(super) enum ChunkOutcome {Failed {lease: ChunkLease,detail: String,+ resource: Option<ResourceError>,retry_delay: Duration,},Unclaimed {lease: ChunkLease,},+ /// The failure still counts toward the breaker like `Failed`.RecoveryFailed {lease: ChunkLease,detail: String,+ resource: Option<ResourceError>,recovery: ChunkStoreError,},}+/// What a settled chunk tells its run's breaker.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum BreakerSignal {+ Success,+ ResourceFailure(ResourceError),+ /// An unclaim refunds the attempt, and any other failure says nothing about ClickHouse load.+ Ignore,+}++impl ChunkOutcome {+ pub(super) fn run_id(&self) -> crate::domain::RunId {+ match self {+ Self::Confirmed { lease, .. }+ | Self::Failed { lease, .. }+ | Self::Unclaimed { lease }+ | Self::RecoveryFailed { lease, .. } => lease.run_id(),+ }+ }++ pub(super) fn breaker_signal(&self) -> BreakerSignal {+ match self {+ Self::Confirmed { .. } => BreakerSignal::Success,+ Self::Failed {+ resource: Some(resource),+ ..+ }+ | Self::RecoveryFailed {+ resource: Some(resource),+ ..+ } => BreakerSignal::ResourceFailure(*resource),+ Self::Failed { resource: None, .. }+ | Self::RecoveryFailed { resource: None, .. }+ | Self::Unclaimed { .. } => BreakerSignal::Ignore,+ }+ }+}+pub(super) fn record_task_result(- result: Result<ChunkOutcome, tokio::task::JoinError>,+ result: &Result<ChunkOutcome, tokio::task::JoinError>,kind: RunKind,) {match result {@@ -304,12 +354,15 @@ pub(super) fn record_task_result(Ok(ChunkOutcome::Failed {lease,detail,+ resource,retry_delay,}) => {counter!(CHUNKS_FAILED, "kind" => kind.as_str()).increment(1);+ record_resource_error(kind, *resource);warn!(?lease,error = %detail,+ clickhouse_code = resource.map(ResourceError::as_str),retry_delay_secs = retry_delay.as_secs_f64(),"chunk failed and was released for retry");@@ -320,10 +373,18 @@ pub(super) fn record_task_result(Ok(ChunkOutcome::RecoveryFailed {lease,detail,+ resource,recovery,}) => {counter!(CHUNKS_FAILED, "kind" => kind.as_str()).increment(1);- warn!(?lease, error = %detail, recovery_error = %recovery, "chunk recovery update did not apply");+ record_resource_error(kind, *resource);+ warn!(+ ?lease,+ error = %detail,+ clickhouse_code = resource.map(ResourceError::as_str),+ recovery_error = %recovery,+ "chunk recovery update did not apply"+ );}Err(error) => {counter!(CHUNKS_FAILED, "kind" => kind.as_str()).increment(1);@@ -332,6 +393,17 @@ pub(super) fn record_task_result(}}+fn record_resource_error(kind: RunKind, resource: Option<ResourceError>) {+ if let Some(resource) = resource {+ counter!(+ CLICKHOUSE_RESOURCE_ERRORS,+ "kind" => kind.as_str(),+ "code" => resource.as_str(),+ )+ .increment(1);+ }+}+#[cfg(test)]mod tests {use super::*;@@ -348,6 +420,48 @@ mod tests {assert_eq!(<ProducedChunk as ChunkState>::STAGE, FailureStage::PostMark);}+ #[test]+ fn only_a_confirmed_chunk_or_a_resource_failure_reaches_the_breaker() {+ let lease = ChunkLease::new(+ crate::domain::ChunkId(uuid::Uuid::from_u128(1)),+ crate::domain::RunId(uuid::Uuid::from_u128(2)),+ crate::domain::ClaimEpoch(1),+ );+ let memory = ResourceError::MemoryLimitExceeded;+ let failed = |resource| ChunkOutcome::Failed {+ lease,+ detail: String::new(),+ resource,+ retry_delay: Duration::ZERO,+ };+ let recovery_failed = |resource| ChunkOutcome::RecoveryFailed {+ lease,+ detail: String::new(),+ resource,+ recovery: ChunkStoreError::TilesProducedOutOfRange(0),+ };+ for (outcome, expected) in [+ (+ ChunkOutcome::Confirmed {+ lease,+ tiles_produced: 0,+ detail: ConfirmedDetail::Behavioral,+ },+ BreakerSignal::Success,+ ),+ (failed(Some(memory)), BreakerSignal::ResourceFailure(memory)),+ (+ recovery_failed(Some(memory)),+ BreakerSignal::ResourceFailure(memory),+ ),+ (failed(None), BreakerSignal::Ignore),+ (recovery_failed(None), BreakerSignal::Ignore),+ (ChunkOutcome::Unclaimed { lease }, BreakerSignal::Ignore),+ ] {+ assert_eq!(outcome.breaker_signal(), expected, "{outcome:?}");+ }+ }+#[test]fn failure_disposition_encodes_the_recovery_matrix() {assert_eq!(diff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rsindex 6c04c242dd6a..62cea176bd8d 100644--- a/rust/cohort-seeder/src/app/mod.rs+++ b/rust/cohort-seeder/src/app/mod.rs@@ -1,6 +1,7 @@//! Application layer: wires `store`, `clickhouse`, `kafka`, and `config` into the seeder's poll loop.//! Depends on every lower layer; nothing below depends on it, so this is where the arrows terminate.+mod breaker;pub mod completion;mod deliver;mod execute;diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rsindex 3eb73fbc8678..5d2d40f75af2 100644--- a/rust/cohort-seeder/src/app/orchestrator.rs+++ b/rust/cohort-seeder/src/app/orchestrator.rs@@ -8,9 +8,9 @@ use std::time::{Duration, Instant};use common_types::cohort::TeamAllowlist;use lifecycle::Handle;-use metrics::counter;+use metrics::{counter, gauge};use sqlx::PgPool;-use tokio::task::JoinSet;+use tokio::task::{JoinError, JoinSet};use tokio_util::sync::CancellationToken;use tracing::{info, warn};@@ -20,14 +20,18 @@ use crate::domain::{ClaimKind, RunId};use crate::kafka::pacing::TilePacer;use crate::kafka::producer::SeedTileProducer;use crate::observability::metrics::{- CHUNKS_CLAIMED, CHUNKS_POISONED, CHUNKS_RECLAIMED, RUNS_FAILED_EXHAUSTED_CHUNKS,+ CHUNKS_CLAIMED, CHUNKS_POISONED, CHUNKS_RECLAIMED, RUNS_FAILED_BREAKER,+ RUNS_FAILED_EXHAUSTED_CHUNKS, RUN_BREAKERS_OPEN, RUN_BREAKER_TRIPS,};use crate::store::chunks::{Claim, PgChunkStore};use crate::store::runs::{complete_trailing_runs, fail_run, RunError, RunKind};use crate::store::{Claimant, MaxAttempts, RenderedError};+use super::breaker::{BreakerEvent, RunBreakers};use super::completion::CompletionDriver;-use super::execute::{execute_chunk, record_task_result, ChunkOutcome, ChunkTaskContext};+use super::execute::{+ execute_chunk, record_task_result, BreakerSignal, ChunkOutcome, ChunkTaskContext,+};use super::person_execute::{execute_person_chunk, PersonChunkTaskContext};use super::person_plan::{plan_person_run, PersonPlanAttempt, PersonPlanRequest};use super::prepare::{refresh_runs, run_ids_of_kind, PreparedRun, RefreshOutcome};@@ -50,19 +54,34 @@ pub struct PersonComponents {pub pacer: TilePacer,}-/// The planning slot's bookkeeping: which runs a spawned task covers (keyed by task id, so a-/// panicked task un-tracks only itself) and when each run's last attempt failed.+/// Which run each spawned task works for. Keyed by task id, so a panicked task, whose result carries+/// no run, still leaves the map, and un-tracks only itself.+#[derive(Default)]+struct InflightTasks(HashMap<tokio::task::Id, RunId>);++impl InflightTasks {+ fn insert(&mut self, task_id: tokio::task::Id, run_id: RunId) {+ self.0.insert(task_id, run_id);+ }++ fn remove(&mut self, task_id: tokio::task::Id) {+ self.0.remove(&task_id);+ }++ fn has_run(&self, run_id: RunId) -> bool {+ self.0.values().any(|inflight| *inflight == run_id)+ }+}++/// The planning slot's bookkeeping: which runs a spawned task covers and when each run's last+/// attempt failed.#[derive(Default)]struct PlanningState {- inflight: HashMap<tokio::task::Id, RunId>,+ inflight: InflightTasks,failed_at: HashMap<RunId, Instant>,}impl PlanningState {- fn is_inflight(&self, run_id: RunId) -> bool {- self.inflight.values().any(|inflight| *inflight == run_id)- }-fn in_backoff(&self, run_id: RunId) -> bool {self.failed_at.get(&run_id)@@ -79,6 +98,11 @@ impl PlanningState {}}+struct ClaimState {+ inflight: InflightTasks,+ breakers: RunBreakers,+}+pub struct SeederOrchestrator {pool: PgPool,store: PgChunkStore,@@ -133,6 +157,10 @@ impl SeederOrchestrator {let mut person_tasks = JoinSet::new();let mut planning: JoinSet<(RunId, PersonPlanAttempt)> = JoinSet::new();let mut planning_state = PlanningState::default();+ let mut claims = ClaimState {+ inflight: InflightTasks::default(),+ breakers: RunBreakers::new(self.settings.breaker),+ };let mut eligible_runs = HashMap::new();let mut reported_runs = HashSet::new();self.handle.report_healthy();@@ -142,28 +170,40 @@ impl SeederOrchestrator {tokio::select! {biased;_ = shutdown.cancelled() => break,- Some(result) = tasks.join_next(), if !tasks.is_empty() => {- record_task_result(result, RunKind::Behavioral);- self.fill_claim_slots(&eligible_runs, &mut tasks, &mut person_tasks, &shutdown)- .await;+ Some(result) = tasks.join_next_with_id(), if !tasks.is_empty() => {+ self.settle_chunk(result, RunKind::Behavioral, &mut claims).await;+ self.fill_claim_slots(+ &eligible_runs,+ &mut tasks,+ &mut person_tasks,+ &mut claims,+ &shutdown,+ )+ .await;self.handle.report_healthy();}- Some(result) = person_tasks.join_next(), if !person_tasks.is_empty() => {- record_task_result(result, RunKind::PersonProperty);- self.fill_claim_slots(&eligible_runs, &mut tasks, &mut person_tasks, &shutdown)- .await;+ Some(result) = person_tasks.join_next_with_id(), if !person_tasks.is_empty() => {+ self.settle_chunk(result, RunKind::PersonProperty, &mut claims).await;+ self.fill_claim_slots(+ &eligible_runs,+ &mut tasks,+ &mut person_tasks,+ &mut claims,+ &shutdown,+ )+ .await;self.handle.report_healthy();}Some(result) = planning.join_next_with_id(), if !planning.is_empty() => {match result {Ok((task_id, (run_id, attempt))) => {- planning_state.inflight.remove(&task_id);+ planning_state.inflight.remove(task_id);if attempt == PersonPlanAttempt::Failed {planning_state.failed_at.insert(run_id, Instant::now());}}Err(error) => {- planning_state.inflight.remove(&error.id());+ planning_state.inflight.remove(error.id());warn!(error = %error, "person planning task failed unexpectedly");}}@@ -192,8 +232,16 @@ impl SeederOrchestrator {// CAS'd to `reconciling` in the same pass.self.fail_exhausted_runs(&eligible_runs).await;self.complete_trailing_runs(&eligible_runs).await;- self.fill_claim_slots(&eligible_runs, &mut tasks, &mut person_tasks, &shutdown)- .await;+ claims.breakers.expire_idle(Instant::now());+ publish_open_breakers(&eligible_runs, &claims.breakers);+ self.fill_claim_slots(+ &eligible_runs,+ &mut tasks,+ &mut person_tasks,+ &mut claims,+ &shutdown,+ )+ .await;if let Some(driver) = &self.completion_driver {// Dispatch work is spawned off this tick, but observation runs inline: a few// DB reads per reconciling run, plus at most one OffsetFetch and one@@ -215,10 +263,10 @@ impl SeederOrchestrator {"stopping claims and draining active chunks");while let Some(result) = tasks.join_next().await {- record_task_result(result, RunKind::Behavioral);+ record_task_result(&result, RunKind::Behavioral);}while let Some(result) = person_tasks.join_next().await {- record_task_result(result, RunKind::PersonProperty);+ record_task_result(&result, RunKind::PersonProperty);}let producer = self.producer.clone();@@ -230,6 +278,79 @@ impl SeederOrchestrator {info!("cohort seeder orchestrator stopped");}+ async fn settle_chunk(+ &self,+ result: Result<(tokio::task::Id, ChunkOutcome), JoinError>,+ kind: RunKind,+ claims: &mut ClaimState,+ ) {+ let task_id = match &result {+ Ok((task_id, _)) => *task_id,+ Err(error) => error.id(),+ };+ claims.inflight.remove(task_id);+ let result = result.map(|(_, outcome)| outcome);+ record_task_result(&result, kind);+ let Ok(outcome) = result else {+ return;+ };+ let run_id = outcome.run_id();+ let resource = match outcome.breaker_signal() {+ BreakerSignal::Success => {+ claims.breakers.record_success(run_id);+ return;+ }+ BreakerSignal::ResourceFailure(resource) => resource,+ BreakerSignal::Ignore => return,+ };+ match claims+ .breakers+ .record_resource_failure(run_id, Instant::now())+ {+ BreakerEvent::Unchanged => {}+ BreakerEvent::Tripped { trips, cooldown } => {+ counter!(RUN_BREAKER_TRIPS, "kind" => kind.as_str()).increment(1);+ warn!(+ ?run_id,+ kind = kind.as_str(),+ trips,+ cooldown_secs = cooldown.as_secs(),+ clickhouse_code = resource.as_str(),+ "run breaker opened: ClickHouse keeps refusing this run's scans for lack of resources"+ );+ }+ BreakerEvent::Exhausted { trips } => {+ let error = RenderedError::from_message(format!(+ "the ClickHouse resource breaker opened {trips} times with no confirmed chunk in \+ between; last error: {}. The run's scans do not fit the ClickHouse limits: make \+ them smaller or raise the limits, then create a new run",+ resource.as_str(),+ ));+ match fail_run(&self.pool, run_id, &error).await {+ Ok(()) => {+ counter!(RUNS_FAILED_BREAKER, "kind" => kind.as_str()).increment(1);+ warn!(+ ?run_id,+ kind = kind.as_str(),+ trips,+ clickhouse_code = resource.as_str(),+ "failing run: its ClickHouse resource breaker reached the trip limit"+ );+ }+ Err(RunError::NotActive(_)) => {}+ Err(error) => {+ claims.breakers.retry_exhausted(run_id);+ warn!(+ ?run_id,+ error = %error,+ "failing the run at its breaker trip limit did not apply; its next probe retries it"+ );+ }+ }+ }+ }+ }+fn spawn_person_planning(&self,requests: Vec<PersonPlanRequest>,@@ -246,7 +367,7 @@ impl SeederOrchestrator {return;}let run_id = request.run.run_id;- if state.is_inflight(run_id) || state.in_backoff(run_id) {+ if state.inflight.has_run(run_id) || state.in_backoff(run_id) {continue;}let handle = planning.spawn(plan_person_run(@@ -335,6 +456,7 @@ impl SeederOrchestrator {eligible_runs: &HashMap<RunId, PreparedRun>,tasks: &mut JoinSet<ChunkOutcome>,person_tasks: &mut JoinSet<ChunkOutcome>,+ claims: &mut ClaimState,shutdown: &CancellationToken,) {loop {@@ -345,12 +467,17 @@ impl SeederOrchestrator {let person_room = self.settings.person.is_some_and(|person_settings| {person_tasks.len() < person_settings.max_concurrent_chunks.get()});+ let now = Instant::now();let mut run_ids = Vec::with_capacity(eligible_runs.len());for (run_id, prepared) in eligible_runs {- let admitted = match prepared {+ let has_room = match prepared {PreparedRun::Behavioral(_) => behavioral_room,PreparedRun::Person(_) => person_room,};+ let admitted = has_room+ && claims+ .breakers+ .admits(*run_id, now, claims.inflight.has_run(*run_id));if admitted {run_ids.push(*run_id);}@@ -399,7 +526,8 @@ impl SeederOrchestrator {retry_backoff: self.settings.retry_backoff,};let shutdown = shutdown.clone();- tasks.spawn(async move { execute_chunk(ctx, shutdown).await });+ let task = tasks.spawn(async move { execute_chunk(ctx, shutdown).await });+ claims.inflight.insert(task.id(), chunk_lease.run_id());}PreparedRun::Person(run) => {// Unreachable while the gate is off: discovery never yields person runs then.@@ -425,7 +553,9 @@ impl SeederOrchestrator {retry_backoff: self.settings.retry_backoff,};let shutdown = shutdown.clone();- person_tasks.spawn(async move { execute_person_chunk(ctx, shutdown).await });+ let task = person_tasks+ .spawn(async move { execute_person_chunk(ctx, shutdown).await });+ claims.inflight.insert(task.id(), chunk_lease.run_id());}}}@@ -486,6 +616,17 @@ pub async fn fail_exhausted_runs_of_kind(failed}+/// Counted over the eligible set, so a run that finished with an open breaker stops counting.+fn publish_open_breakers(eligible_runs: &HashMap<RunId, PreparedRun>, breakers: &RunBreakers) {+ for kind in [RunKind::Behavioral, RunKind::PersonProperty] {+ let open = run_ids_of_kind(eligible_runs, kind)+ .into_iter()+ .filter(|run_id| breakers.is_open(*run_id))+ .count();+ gauge!(RUN_BREAKERS_OPEN, "kind" => kind.as_str()).set(open as f64);+ }+}+fn record_claim(claim_kind: ClaimKind, run_kind: RunKind) {counter!(CHUNKS_CLAIMED, "kind" => run_kind.as_str()).increment(1);if claim_kind == ClaimKind::Reclaim {diff --git a/rust/cohort-seeder/src/app/person_execute.rs b/rust/cohort-seeder/src/app/person_execute.rsindex 603f7227d7bd..0b5b82e17218 100644--- a/rust/cohort-seeder/src/app/person_execute.rs+++ b/rust/cohort-seeder/src/app/person_execute.rs@@ -304,3 +304,31 @@ enum PersonChunkError {#[error(transparent)]Produce(ProduceError),}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::clickhouse::ResourceError;++ /// `Scan` is transparent, so its source chain skips `PersonScanError` and must still reach the+ /// ClickHouse error, or the person breaker never sees a resource error.+ #[test]+ fn person_scan_resource_errors_reach_the_breaker() {+ let memory = || {+ clickhouse::error::Error::BadResponse(+ "Code: 241. DB::Exception: Memory limit (for query) exceeded. (MEMORY_LIMIT_EXCEEDED)"+ .to_owned(),+ )+ };+ for error in [+ PersonChunkError::Scan(PersonScanError::Cursor(memory())),+ PersonChunkError::Cursor(memory()),+ ] {+ assert_eq!(+ ResourceError::classify(&error),+ Some(ResourceError::MemoryLimitExceeded),+ "{error:?}"+ );+ }+ }+}diff --git a/rust/cohort-seeder/src/app/prepare.rs b/rust/cohort-seeder/src/app/prepare.rsindex 159e9c6ee2ed..317b12c64978 100644--- a/rust/cohort-seeder/src/app/prepare.rs+++ b/rust/cohort-seeder/src/app/prepare.rs@@ -486,6 +486,7 @@ fn record_condition_census(property_projectable_fraction = census.property_projectable_fraction(),eligible_events = census.projection_eligible_event_names().len(),blocked_events = %census.render_blocked_events(),+ row_filtered_conditions = analyses.row_filtered_conditions(),"condition bytecode analysis census",);// The read sets and the uncapped blocked list carry customer-defined event names and propertydiff --git a/rust/cohort-seeder/src/app/prime.rs b/rust/cohort-seeder/src/app/prime.rsindex 4cb1853ef950..08599614c21f 100644--- a/rust/cohort-seeder/src/app/prime.rs+++ b/rust/cohort-seeder/src/app/prime.rs@@ -24,10 +24,11 @@ use cohort_core::hogvm::VmErrorClass;use metrics::counter;use crate::clickhouse::person_sql::ScanFilterOutcome;-use crate::clickhouse::ScanSkipReason;+use crate::clickhouse::{ResourceError, ScanSkipReason};use crate::observability::metrics::{- CHUNKS_POISONED, EVENTS_SKIPPED, HOGVM_ERRORS, PERSON_CONDITIONS_SHORTCUT, PERSON_ROWS_PRUNED,- PERSON_SCAN_FILTER, PRUNE_REASON_IRRELEVANT,+ CHUNKS_POISONED, CLICKHOUSE_RESOURCE_ERRORS, EVENTS_SKIPPED, HOGVM_ERRORS,+ PERSON_CONDITIONS_SHORTCUT, PERSON_ROWS_PRUNED, PERSON_SCAN_FILTER, PRUNE_REASON_IRRELEVANT,+ RUN_BREAKER_TRIPS,};use crate::store::runs::RunKind;@@ -42,6 +43,15 @@ pub fn prime_zero_series() {}for kind in RunKind::ALL {counter!(CHUNKS_POISONED, "kind" => kind.as_str()).increment(0);+ counter!(RUN_BREAKER_TRIPS, "kind" => kind.as_str()).increment(0);+ for resource in ResourceError::ALL {+ counter!(+ CLICKHOUSE_RESOURCE_ERRORS,+ "kind" => kind.as_str(),+ "code" => resource.as_str(),+ )+ .increment(0);+ }}// The person canary is read against these two: a run that pruned nothing and a run whose filter// never rendered have to look different from an exporter that dropped the family.@@ -73,6 +83,8 @@ mod tests {format!("{EVENTS_SKIPPED}{{reason=\"globals_parse_error\"}} 0"),format!("{HOGVM_ERRORS}{{class=\"unknown_ref\"}} 0"),format!("{CHUNKS_POISONED}{{kind=\"behavioral\"}} 0"),+ format!("{CLICKHOUSE_RESOURCE_ERRORS}{{kind=\"behavioral\",code=\"241\"}} 0"),+ format!("{RUN_BREAKER_TRIPS}{{kind=\"behavioral\"}} 0"),format!("{PERSON_ROWS_PRUNED}{{reason=\"irrelevant\"}} 0"),format!("{PERSON_SCAN_FILTER}{{outcome=\"key_presence\"}} 0"),format!("{PERSON_SCAN_FILTER}{{outcome=\"none\"}} 0"),diff --git a/rust/cohort-seeder/src/app/settings.rs b/rust/cohort-seeder/src/app/settings.rsindex 9ce9afd364c0..4d23d2b09296 100644--- a/rust/cohort-seeder/src/app/settings.rs+++ b/rust/cohort-seeder/src/app/settings.rs@@ -10,6 +10,7 @@ use crate::domain::{BackoffPolicyError, PersonEmissionPolicy, PlanCaps, RetryBacuse crate::store::runs::RunKind;use crate::store::{LeaseDuration, LeaseDurationError, MaxAttempts, MaxAttemptsError};+use super::breaker::{BreakerPolicy, BreakerPolicyError};use super::deliver::QUEUE_FULL_BACKOFF_CAP;use super::orchestrator::ORCHESTRATOR_LIVENESS_DEADLINE;@@ -62,6 +63,7 @@ pub struct OrchestratorSettings {pub(super) chunk_lease: LeaseDuration,pub(super) max_chunk_attempts: MaxAttempts,pub(super) retry_backoff: RetryBackoffPolicy,+ pub(super) breaker: BreakerPolicy,pub(super) plan_caps: PlanCaps,pub(super) producer: ProducerSettings,pub(super) person: Option<PersonSettings>,@@ -75,6 +77,7 @@ impl OrchestratorSettings {chunk_lease: Duration,max_chunk_attempts: u32,retry_backoff: RetryBackoffPolicy,+ breaker: BreakerPolicy,max_lookback_days: u32,bands_per_day: u16,live_tracking_lag: Duration,@@ -109,6 +112,7 @@ impl OrchestratorSettings {chunk_lease,max_chunk_attempts,retry_backoff,+ breaker,plan_caps: PlanCaps {max_lookback_days,bands_per_day,@@ -179,12 +183,20 @@ impl TryFrom<&Config> for OrchestratorSettings {Duration::from_secs(config.seeder_retry_backoff_cap_secs),).map_err(OrchestratorSettingsError::RetryBackoff)?;+ let breaker = BreakerPolicy::new(+ config.seeder_ch_breaker_threshold,+ Duration::from_secs(config.seeder_ch_breaker_cooldown_base_secs),+ Duration::from_secs(config.seeder_ch_breaker_cooldown_cap_secs),+ config.seeder_ch_breaker_max_trips,+ )+ .map_err(OrchestratorSettingsError::Breaker)?;Ok(Self::new(Duration::from_secs(config.seeder_run_poll_secs),config.seeder_max_concurrent_chunks,Duration::from_secs(config.seeder_chunk_lease_secs),config.seeder_max_chunk_attempts,retry_backoff,+ breaker,config.seeder_max_lookback_days,config.seeder_bands_per_day,Duration::from_secs(config.seeder_live_tracking_lag_secs),@@ -215,6 +227,8 @@ pub enum OrchestratorSettingsError {BandsPerDayOutOfRange,#[error(transparent)]RetryBackoff(#[from] BackoffPolicyError),+ #[error(transparent)]+ Breaker(#[from] BreakerPolicyError),#[error("person seeds per second must be greater than zero")]ZeroPersonSeedRate,#[error("persons per chunk must be greater than zero")]@@ -291,6 +305,10 @@ mod tests {RetryBackoffPolicy::new(Duration::from_secs(30), Duration::from_secs(1800)).unwrap()}+ fn breaker() -> BreakerPolicy {+ BreakerPolicy::new(3, Duration::from_secs(300), Duration::from_secs(1800), 4).unwrap()+ }+#[test]fn producer_settings_reject_unbounded_bounds() {assert_eq!(@@ -319,6 +337,7 @@ mod tests {Duration::from_secs(3),1,backoff(),+ breaker(),400,1,Duration::ZERO,@@ -335,6 +354,7 @@ mod tests {Duration::from_secs(3),1,backoff(),+ breaker(),400,1,Duration::ZERO,@@ -351,6 +371,7 @@ mod tests {Duration::from_secs(3),1,backoff(),+ breaker(),400,1,Duration::ZERO,@@ -367,6 +388,7 @@ mod tests {Duration::from_secs(2),1,backoff(),+ breaker(),400,1,Duration::ZERO,@@ -383,6 +405,7 @@ mod tests {Duration::from_secs(3),0,backoff(),+ breaker(),400,1,Duration::ZERO,@@ -399,6 +422,7 @@ mod tests {Duration::from_secs(3),1,backoff(),+ breaker(),400,0,Duration::ZERO,@@ -415,6 +439,7 @@ mod tests {Duration::from_secs(3),1,backoff(),+ breaker(),400,u16::MAX,Duration::ZERO,@@ -522,6 +547,25 @@ mod tests {));}+ #[test]+ fn breaker_is_parsed_from_config_and_rejected_when_it_cannot_trip() {+ let config = Config::init_from_hashmap(&HashMap::new()).unwrap();+ let settings = OrchestratorSettings::try_from(&config).unwrap();+ assert_eq!(+ settings.breaker,+ BreakerPolicy::new(3, Duration::from_secs(300), Duration::from_secs(1800), 4).unwrap()+ );++ let mut zero_threshold = config.clone();+ zero_threshold.seeder_ch_breaker_threshold = 0;+ assert!(matches!(+ OrchestratorSettings::try_from(&zero_threshold),+ Err(SettingsError::Orchestrator(+ OrchestratorSettingsError::Breaker(BreakerPolicyError::ZeroThreshold)+ ))+ ));+ }+/// A backoff pair that cannot space retries must fail at startup. Accepting it would leave the/// claim gate stamping a zero or shrinking wait, which is the reclaim storm the policy exists/// to stop, and nothing downstream would report it.diff --git a/rust/cohort-seeder/src/clickhouse/client.rs b/rust/cohort-seeder/src/clickhouse/client.rsindex da77aa93cc41..a3a79c1db9fe 100644--- a/rust/cohort-seeder/src/clickhouse/client.rs+++ b/rust/cohort-seeder/src/clickhouse/client.rs@@ -4,6 +4,7 @@//! Depends on `config` for the raw env strings; every value that shapes a ClickHouse query option is//! parsed here so a misconfiguration fails startup instead of silently degrading query behavior.+use std::num::NonZeroU64;use std::str::FromStr;use std::sync::Arc;use std::time::Duration;@@ -327,12 +328,37 @@ pub fn build_client(config: &Config) -> Result<ClickHouseClient, ClickHouseClienconfig.seeder_ch_max_bytes_in_set.to_string(),).with_option("join_algorithm", join_algorithm.as_str());+ let client = optional_settings(config)+ .into_iter()+ .fold(client, |client, (name, value)| {+ client.with_option(name, value.to_string())+ });Ok(ClickHouseClient::new(client,ClickHouseCredential::from_config(config),))}+fn optional_settings(config: &Config) -> Vec<(&'static str, u64)> {+ [+ (+ "max_threads",+ config.seeder_ch_max_threads.map(NonZeroU64::get),+ ),+ (+ "max_memory_usage",+ config.seeder_ch_max_memory_usage.map(NonZeroU64::get),+ ),+ (+ "distributed_replica_max_ignored_errors",+ config.seeder_ch_distributed_replica_max_ignored_errors,+ ),+ ]+ .into_iter()+ .filter_map(|(name, value)| value.map(|value| (name, value)))+ .collect()+}+#[cfg(test)]mod tests {use std::collections::HashMap;@@ -434,6 +460,41 @@ LaIcbwSaQpbb1SSltcQ0krF2y351IH79a2fmV57qw3VZ5u17KbO4}}+ #[test]+ fn profile_constrained_settings_are_sent_only_when_configured() {+ assert_eq!(optional_settings(&default_config()), Vec::new());++ // Parsed from env names, so a renamed field fails here.+ let config = Config::init_from_hashmap(&HashMap::from([+ ("SEEDER_CH_MAX_THREADS".to_string(), "4".to_string()),+ (+ "SEEDER_CH_MAX_MEMORY_USAGE".to_string(),+ "8589934592".to_string(),+ ),+ (+ "SEEDER_CH_DISTRIBUTED_REPLICA_MAX_IGNORED_ERRORS".to_string(),+ "1000".to_string(),+ ),+ ]))+ .unwrap();+ assert_eq!(+ optional_settings(&config),+ vec![+ ("max_threads", 4),+ ("max_memory_usage", 8_589_934_592),+ ("distributed_replica_max_ignored_errors", 1000),+ ]+ );++ for name in ["SEEDER_CH_MAX_THREADS", "SEEDER_CH_MAX_MEMORY_USAGE"] {+ assert!(+ Config::init_from_hashmap(&HashMap::from([(name.to_string(), "0".to_string())]))+ .is_err(),+ "{name}=0 lifts the bound instead of failing startup"+ );+ }+ }+#[test]fn build_client_rejects_a_join_algorithm_typo_at_startup() {let mut config = default_config();diff --git a/rust/cohort-seeder/src/clickhouse/materialized.rs b/rust/cohort-seeder/src/clickhouse/materialized.rsnew file mode 100644index 000000000000..bc61560a1248--- /dev/null+++ b/rust/cohort-seeder/src/clickhouse/materialized.rs@@ -0,0 +1,103 @@+//! Finds the materialized columns a behavioral scan's row filter can read instead of the+//! `properties` blob.+//!+//! A column qualifies only when its stored default expression on the data table is exactly the+//! trim-quotes extraction the filter would otherwise evaluate. A typed `JSONExtract` column reads+//! different values for the same row, such as an empty value for a boolean that HogVM equality can+//! match. The column must also exist on the distributed `events` table the scan reads.++use std::collections::{BTreeSet, HashMap};++use clickhouse::Row;+use serde::Deserialize;++use super::client::ClickHouseClient;+use super::sql::clickhouse_string_literal;++/// Only the data table's columns carry the default expressions.+const EVENTS_DATA_TABLE: &str = "sharded_events";++/// Property key to verified column name.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct MaterializedColumns(HashMap<String, String>);++impl MaterializedColumns {+ pub fn column_for(&self, key: &str) -> Option<&str> {+ self.0.get(key).map(String::as_str)+ }++ pub async fn lookup(+ client: &ClickHouseClient,+ keys: &BTreeSet<&str>,+ ) -> Result<Self, clickhouse::error::Error> {+ if keys.is_empty() {+ return Ok(Self::default());+ }+ let expected: HashMap<String, &str> = keys+ .iter()+ .map(|key| (trim_quotes_extraction(key), *key))+ .collect();+ let rows = client+ .query(&lookup_sql(expected.keys()))+ .fetch_all::<ColumnRow>()+ .await?;+ let mut columns = HashMap::new();+ for row in rows {+ // Rows are sorted by name, so every chunk picks the same column for a key.+ if let Some(key) = expected.get(&row.expression) {+ columns+ .entry((*key).to_owned())+ .or_insert_with(|| row.name.clone());+ }+ }+ Ok(Self(columns))+ }+}++impl FromIterator<(String, String)> for MaterializedColumns {+ fn from_iter<I: IntoIterator<Item = (String, String)>>(pairs: I) -> Self {+ Self(pairs.into_iter().collect())+ }+}++#[derive(Debug, Row, Deserialize)]+struct ColumnRow {+ name: String,+ expression: String,+}++/// The materializer's default expression for a non-nullable property column, as ClickHouse stores+/// it. Only `'` and `\` are escaped, so a key holding another character ClickHouse escapes finds no+/// column and the filter reads the blob.+fn trim_quotes_extraction(key: &str) -> String {+ let escaped = key.replace('\\', "\\\\").replace('\'', "\\'");+ format!("replaceRegexpAll(JSONExtractRaw(properties, '{escaped}'), '^\"|\"$', '')")+}++fn lookup_sql<'a>(expressions: impl Iterator<Item = &'a String>) -> String {+ let mut expressions = expressions+ .map(|expression| clickhouse_string_literal(expression))+ .collect::<Vec<_>>();+ expressions.sort();+ format!(+ "SELECT name, default_expression AS expression\nFROM system.columns\nWHERE database = currentDatabase() AND table = '{EVENTS_DATA_TABLE}'\n AND type = 'String' AND default_kind IN ('DEFAULT', 'MATERIALIZED')\n AND default_expression IN ({})\n AND name IN (SELECT name FROM system.columns WHERE database = currentDatabase() AND table = 'events' AND type = 'String')\nORDER BY name",+ expressions.join(", "),+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_expected_expression_is_the_stored_materializer_text() {+ assert_eq!(+ trim_quotes_extraction("$feature_flag"),+ r#"replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag'), '^"|"$', '')"#+ );+ assert_eq!(+ trim_quotes_extraction(r"it's\here"),+ r#"replaceRegexpAll(JSONExtractRaw(properties, 'it\'s\\here'), '^"|"$', '')"#+ );+ }+}diff --git a/rust/cohort-seeder/src/clickhouse/mod.rs b/rust/cohort-seeder/src/clickhouse/mod.rsindex 7c9e8cdd5055..6986b3ea38f8 100644--- a/rust/cohort-seeder/src/clickhouse/mod.rs+++ b/rust/cohort-seeder/src/clickhouse/mod.rs@@ -5,8 +5,10 @@pub mod client;pub mod credential;pub mod log_comment;+pub mod materialized;pub mod person_scanner;pub mod person_sql;+pub mod resource;pub mod row;pub mod scan_volume;pub mod scanner;@@ -20,5 +22,6 @@ pub use credential::ClickHouseCredential;pub use log_comment::{ScanLogComment, LOG_COMMENT_OPTION};pub use person_scanner::{PersonRow, PersonScanError, PersonScanner};pub use person_sql::PersonScanSpec;+pub use resource::ResourceError;pub use scan_volume::ScanKind;pub use scanner::{ChunkScanner, ScanError, ScanSkipReason};diff --git a/rust/cohort-seeder/src/clickhouse/person_scanner.rs b/rust/cohort-seeder/src/clickhouse/person_scanner.rsindex ccefd96b8ff5..c5828b784f05 100644--- a/rust/cohort-seeder/src/clickhouse/person_scanner.rs+++ b/rust/cohort-seeder/src/clickhouse/person_scanner.rs@@ -40,7 +40,7 @@ impl PersonScanner {Self { client }}- /// Stream the run's live person ids in ClickHouse order, keeping the first id of every new+ /// Stream the run's person ids in ClickHouse order, keeping the first id of every new/// chunk as a range boundary — memory is bounded by the chunk-count ceiling, never the table/// size. When the ceiling saturates, the final unbounded range absorbs the remainder and the/// scan stops early rather than failing a run over a column-width constraint.diff --git a/rust/cohort-seeder/src/clickhouse/person_sql.rs b/rust/cohort-seeder/src/clickhouse/person_sql.rsindex a79dbbad60f5..90c8176957a1 100644--- a/rust/cohort-seeder/src/clickhouse/person_sql.rs+++ b/rust/cohort-seeder/src/clickhouse/person_sql.rs@@ -1,21 +1,27 @@//! ClickHouse person-scan SQL: the byte-frozen renderers for the boundary and range scans over the//! `person` table. Depends on `domain`; never on `store`.//!-//! Both queries read the ReplacingMergeTree's latest row per person (`GROUP BY p.id` + `argMax(…,-//! version)`) with `team_id` equality-fixed. Range predicates are defined in ClickHouse's UUID-//! order. Every column reference is table-qualified because the output alias is itself named `id`:-//! ClickHouse binds a bare `id` in `WHERE`, `GROUP BY`, or `ORDER BY` to that alias rather than to-//! the column, so an unqualified `id >= toUUID(…)` compares `String` against `UUID` (no supertype,-//! so the query cannot execute) and an unqualified `ORDER BY id` streams boundaries in text order-//! while the range predicates read them back in UUID order. The horizon appears twice on purpose:-//! the `p.id IN (…)` prefilter keeps the `_timestamp` minmax skip index usable (a bare `HAVING`-//! would decompress every historical version of every person), while the `HAVING` clause states the-//! update-recency semantics against the group — `argMax` still sees all versions of the surviving-//! ids. That prefilter is the one unbounded structure here: the boundary query's set spans a whole-//! team, so the client caps it with `max_bytes_in_set`. `optimize_aggregation_in_order = 1` keeps-//! the streaming aggregation bounded; the client's external-group-by spill guard backstops a silent-//! optimizer fallback. Only the boundary query orders its output — the range scan's fold is-//! order-independent, and an unneeded `ORDER BY` would materialize the whole chunk result.+//! Both queries group by person with `team_id` equality-fixed, and range predicates are defined in+//! ClickHouse's UUID order. Every column reference is table-qualified because the output alias is+//! itself named `id`: ClickHouse binds a bare `id` in `WHERE`, `GROUP BY`, or `ORDER BY` to that+//! alias rather than to the column, so an unqualified `id >= toUUID(…)` compares `String` against+//! `UUID` (no supertype, so the query cannot execute) and an unqualified `ORDER BY id` streams+//! boundaries in text order while the range predicates read them back in UUID order.+//! `optimize_aggregation_in_order = 1` keeps both aggregations streaming; the client's+//! external-group-by spill guard backstops a silent optimizer fallback.+//!+//! The range scan reads the ReplacingMergeTree's latest row per person (`argMax(…, version)`). Its+//! horizon appears twice on purpose: the `p.id IN (…)` prefilter keeps the `_timestamp` minmax skip+//! index usable (a bare `HAVING` would decompress every historical version of every person), while+//! the `HAVING` clause states the update-recency semantics against the group, so `argMax` still sees+//! all versions of the surviving ids. The prefilter's set holds one chunk's range of ids, and the+//! client caps it with `max_bytes_in_set`.+//!+//! The boundary query only sizes the chunks, since the ranges tile the whole UUID space and each+//! range scan applies the exact predicate. So it filters versions by `_timestamp` without collapsing+//! them, counting deleted persons toward the stride, and builds no whole-team id set. Only the+//! boundary query orders its output; the range scan's fold is order-independent, and an unneeded+//! `ORDER BY` would materialize the whole chunk result.//!//! The range scan may also carry a key-presence filter, which drops a person whose latest blob is a//! JSON object holding none of the keys the run's conditions read — a person the fold would prune@@ -24,19 +30,16 @@use cohort_core::filters::TeamId;-use crate::clickhouse::sql::key_list;+use crate::clickhouse::sql::{key_list, MAX_GET_QUERY_BYTES};use crate::domain::{PersonRange, ProjectedKeys, UtcMillis};-/// The rendered ceiling one scan may reach, leaving about 2 KB of margin.+/// The rendered ceiling one scan may reach, leaving 2 KB of margin below the GET limit.///-/// The `cohort_seeder` ClickHouse profile runs `readonly=2`, under which a query over 8192 bytes is-/// POSTed as `readonly=1` and fails with code 164. The profile lives in the infrastructure-/// repository, not here, so this constant cannot be derived — re-check it against the profile-/// rather than against this comment. Conservative in the safe direction: the `?` → `??` escaping in+/// Conservative in the safe direction: the `?` → `??` escaping in/// [`clickhouse_string_literal`](super::sql::clickhouse_string_literal) is undone by the client's/// template parser, so the query that reaches the server is never longer than the text measured/// here.-const MAX_RENDERED_SCAN_BYTES: usize = 6144;+const MAX_RENDERED_SCAN_BYTES: usize = MAX_GET_QUERY_BYTES - 2048;/// What became of a run's key filter on one chunk, as a bounded metric label.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -112,7 +115,7 @@ impl PersonScanSpec {pub fn person_boundaries_sql(team_id: TeamId, scan_since: UtcMillis) -> String {format!(- "SELECT toString(p.id) AS id\nFROM person AS p\nWHERE p.team_id = {team} AND p.id IN (\n SELECT recent.id FROM person AS recent\n WHERE recent.team_id = {team} AND recent._timestamp >= fromUnixTimestamp64Milli({since})\n)\nGROUP BY p.id\nHAVING argMax(p.is_deleted, p.version) = 0 AND max(p._timestamp) >= fromUnixTimestamp64Milli({since})\nORDER BY p.id\nSETTINGS optimize_aggregation_in_order = 1",+ "SELECT toString(p.id) AS id\nFROM person AS p\nWHERE p.team_id = {team} AND p._timestamp >= fromUnixTimestamp64Milli({since})\nGROUP BY p.id\nORDER BY p.id\nSETTINGS optimize_aggregation_in_order = 1",team = team_id.0,since = scan_since.as_i64(),)@@ -194,11 +197,12 @@ mod tests {.expect("the test key sets are non-empty")}+ /// The boundary query spans a whole team, so it must not build an `IN (SELECT …)` set.#[test]fn boundaries_sql_is_byte_frozen() {assert_eq!(person_boundaries_sql(TeamId(2), SINCE),- "SELECT toString(p.id) AS id\nFROM person AS p\nWHERE p.team_id = 2 AND p.id IN (\n SELECT recent.id FROM person AS recent\n WHERE recent.team_id = 2 AND recent._timestamp >= fromUnixTimestamp64Milli(1780000000000)\n)\nGROUP BY p.id\nHAVING argMax(p.is_deleted, p.version) = 0 AND max(p._timestamp) >= fromUnixTimestamp64Milli(1780000000000)\nORDER BY p.id\nSETTINGS optimize_aggregation_in_order = 1"+ "SELECT toString(p.id) AS id\nFROM person AS p\nWHERE p.team_id = 2 AND p._timestamp >= fromUnixTimestamp64Milli(1780000000000)\nGROUP BY p.id\nORDER BY p.id\nSETTINGS optimize_aggregation_in_order = 1");}diff --git a/rust/cohort-seeder/src/clickhouse/resource.rs b/rust/cohort-seeder/src/clickhouse/resource.rsnew file mode 100644index 000000000000..e5fa3226844c--- /dev/null+++ b/rust/cohort-seeder/src/clickhouse/resource.rs@@ -0,0 +1,177 @@+//! Classifies a failed scan by the ClickHouse error behind it, for the run breaker.++use std::error::Error;+use std::io;++/// What the crate reports for a `500` whose body mixes buffered rows with the exception, which is+/// how ClickHouse answers a query that fails after its first rows but before it sends the headers.+const UNREADABLE_SERVER_ERROR: &str = "500 Internal Server Error";++/// A ClickHouse error meaning the query did not fit the server's resources.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ResourceError {+ /// Also raised when the overcommit tracker stops the query to free memory for others.+ MemoryLimitExceeded,+ TimeoutExceeded,+ TooSlow,+ TooManySimultaneousQueries,+ /// The query failed after ClickHouse started the response, so the client never reads the error+ /// code. It counts, because the memory and time limits stop a scan mid-stream and the client+ /// cannot tell them from another server error there.+ ResponseCut,+}++impl ResourceError {+ pub const ALL: [Self; 5] = [+ Self::MemoryLimitExceeded,+ Self::TimeoutExceeded,+ Self::TooSlow,+ Self::TooManySimultaneousQueries,+ Self::ResponseCut,+ ];++ pub const fn as_str(self) -> &'static str {+ match self {+ Self::MemoryLimitExceeded => "241",+ Self::TimeoutExceeded => "159",+ Self::TooSlow => "160",+ Self::TooManySimultaneousQueries => "202",+ Self::ResponseCut => "response_cut",+ }+ }++ fn from_code(code: u32) -> Option<Self> {+ match code {+ 241 => Some(Self::MemoryLimitExceeded),+ 159 => Some(Self::TimeoutExceeded),+ 160 => Some(Self::TooSlow),+ 202 => Some(Self::TooManySimultaneousQueries),+ _ => None,+ }+ }++ /// Walks the source chain, because the chunk pipeline wraps the `clickhouse` crate's error.+ pub fn classify(error: &(dyn Error + 'static)) -> Option<Self> {+ let mut current = Some(error);+ while let Some(error) = current {+ if let Some(error) = error.downcast_ref::<clickhouse::error::Error>() {+ return Self::from_clickhouse(error);+ }+ current = error.source();+ }+ None+ }++ fn from_clickhouse(error: &clickhouse::error::Error) -> Option<Self> {+ match error {+ clickhouse::error::Error::BadResponse(message)+ if message == UNREADABLE_SERVER_ERROR =>+ {+ Some(Self::ResponseCut)+ }+ clickhouse::error::Error::BadResponse(message) => {+ server_error_code(message).and_then(Self::from_code)+ }+ // Once the headers are out, ClickHouse ends the body early instead.+ clickhouse::error::Error::Network(source) => {+ ends_early(source.as_ref()).then_some(Self::ResponseCut)+ }+ _ => None,+ }+ }+}++/// The crate reports a server exception raised before the response starts as `BadResponse` text+/// starting `Code: <n>.`.+fn server_error_code(message: &str) -> Option<u32> {+ let rest = message.trim_start().strip_prefix("Code:")?.trim_start();+ let digits = rest+ .find(|character: char| !character.is_ascii_digit())+ .map_or(rest, |end| &rest[..end]);+ digits.parse().ok()+}++/// A refused or reset connection is not a cut response, so only an early end of the body counts.+fn ends_early(error: &(dyn Error + 'static)) -> bool {+ let mut current = Some(error);+ while let Some(error) = current {+ if error+ .downcast_ref::<io::Error>()+ .is_some_and(|error| error.kind() == io::ErrorKind::UnexpectedEof)+ {+ return true;+ }+ current = error.source();+ }+ false+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::clickhouse::ScanError;++ fn bad_response(message: &str) -> ScanError {+ ScanError::Cursor(clickhouse::error::Error::BadResponse(message.to_owned()))+ }++ #[test]+ fn resource_codes_are_read_through_the_source_chain() {+ for (message, expected) in [+ (+ "Code: 241. DB::Exception: Memory limit (for query) exceeded: would use 16.00 GiB. (MEMORY_LIMIT_EXCEEDED) (version 26.6.2.158)",+ Some(ResourceError::MemoryLimitExceeded),+ ),+ (+ "Code: 241. DB::Exception: Memory limit (total) exceeded. OvercommitTracker decision: Query was selected to stop by OvercommitTracker. (MEMORY_LIMIT_EXCEEDED)",+ Some(ResourceError::MemoryLimitExceeded),+ ),+ (+ "Code: 159. DB::Exception: Timeout exceeded: elapsed 14400.1 seconds, maximum: 14400. (TIMEOUT_EXCEEDED)",+ Some(ResourceError::TimeoutExceeded),+ ),+ (+ "Code: 160. DB::Exception: Estimated query execution time is too long. (TOO_SLOW)",+ Some(ResourceError::TooSlow),+ ),+ (+ "Code: 202. DB::Exception: Too many simultaneous queries for user cohort_seeder. (TOO_MANY_SIMULTANEOUS_QUERIES)",+ Some(ResourceError::TooManySimultaneousQueries),+ ),+ (+ "Code: 47. DB::Exception: Unknown expression identifier `mat_x`. (UNKNOWN_IDENTIFIER)",+ None,+ ),+ (+ "Code: 452. DB::Exception: Setting max_threads shouldn't be greater than 8. (SETTING_CONSTRAINT_VIOLATION)",+ None,+ ),+ ("500 Internal Server Error", Some(ResourceError::ResponseCut)),+ ("503 Service Unavailable", None),+ ] {+ assert_eq!(+ ResourceError::classify(&bad_response(message)),+ expected,+ "{message}"+ );+ }+ assert_eq!(+ ResourceError::classify(&ScanError::Cursor(clickhouse::error::Error::TimedOut)),+ None+ );+ for (kind, expected) in [+ (+ io::ErrorKind::UnexpectedEof,+ Some(ResourceError::ResponseCut),+ ),+ (io::ErrorKind::ConnectionRefused, None),+ ] {+ let network = clickhouse::error::Error::Network(Box::new(io::Error::new(kind, "body")));+ assert_eq!(+ ResourceError::classify(&ScanError::Cursor(network)),+ expected,+ "{kind:?}"+ );+ }+ }+}diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rsindex 7d39578cb363..cb5a0cd500bc 100644--- a/rust/cohort-seeder/src/clickhouse/scanner.rs+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs@@ -3,6 +3,7 @@//! `sql`/`row` modules; never on `store` or `kafka`.use std::sync::Arc;+use std::time::Duration;use chrono::Utc;use chrono_tz::Tz;@@ -19,22 +20,26 @@ use tracing::{info, warn};use super::client::ClickHouseClient;use super::log_comment::{ScanLogComment, LOG_COMMENT_OPTION};+use super::materialized::MaterializedColumns;use super::row::{row_to_event, EventRow};use super::scan_volume::{self, ScanKind};-use super::sql::{plan_scan, scan_sql, ScanPlan, ScanSpec};+use super::sql::{fits_client_get, plan_scan, row_filter_sql, scan_sql, ScanPlan, ScanSpec};use crate::domain::{conditions_active_on, diff_tiles, ActiveConditions, AggregateError, BlobSource, CancelCause,ChunkAccumulator, ChunkDomainError, ChunkProjection, ChunkSpec, ClaimedChunk,ConditionAnalyses, DayIdx, EventNameSet, Halted, PinnedCondition, PinnedRun, RecordOutcome,- RecordStats, ScanVolume, ScannedChunk, SeedDomain, SeedTile, TileDiff, UtcMillis,+ RecordStats, ScanRowFilter, ScanVolume, ScannedChunk, SeedDomain, SeedTile, TileDiff,+ UtcMillis,};use crate::observability::metrics::{team_label, MetricTimer, AGGREGATE_ENTRIES, CHUNKS_PROJECTED, CHUNKS_VACUOUS,CHUNK_SCAN_DURATION_SECONDS, CONDITIONS_EVALUATED, EVENTS_SKIPPED, HOGVM_ERRORS,- PROJECTION_KEYS, ROWS_SCANNED, SHADOW_COMPARE, SHADOW_COMPARE_DURATION_SECONDS,- SHADOW_COMPARE_LEGACY_SKIPPED,+ PROJECTION_KEYS, ROWS_SCANNED, SCAN_ROW_FILTER, SHADOW_COMPARE,+ SHADOW_COMPARE_DURATION_SECONDS, SHADOW_COMPARE_LEGACY_SKIPPED,};+const MATERIALIZED_LOOKUP_TIMEOUT: Duration = Duration::from_secs(30);+#[derive(Clone)]pub struct ChunkScanner {client: ClickHouseClient,@@ -133,6 +138,10 @@ impl ChunkScanner {};let projection = analyses.projection(&active);self.record_projection(run.team_id, &projection);+ let row_filter = analyses.row_filter(&event_names, &run.filters, &active);+ let scan_spec = self+ .filter_rows(run.team_id, scan_spec, &row_filter, &projection)+ .await;let (tiles, volume, projected_fold) = self.scan_once(@@ -333,6 +342,57 @@ impl ChunkScanner {Ok(())}+ /// Drops the filter when the query would be too long to send, since every attempt would fail.+ async fn filter_rows(+ &self,+ team_id: TeamId,+ spec: ScanSpec,+ row_filter: &ScanRowFilter,+ projection: &ChunkProjection,+ ) -> ScanSpec {+ let (spec, outcome) = if row_filter.is_empty() {+ (spec, RowFilterOutcome::None)+ } else {+ let keys = row_filter.keys();+ let columns = match tokio::time::timeout(+ MATERIALIZED_LOOKUP_TIMEOUT,+ MaterializedColumns::lookup(&self.client, &keys),+ )+ .await+ {+ Ok(Ok(columns)) => columns,+ Ok(Err(error)) => {+ warn!(error = ?error, "materialized column lookup failed; the row filter reads the properties blob");+ MaterializedColumns::default()+ }+ Err(_) => {+ warn!("materialized column lookup timed out; the row filter reads the properties blob");+ MaterializedColumns::default()+ }+ };+ let outcome = if keys.iter().all(|key| columns.column_for(key).is_some()) {+ RowFilterOutcome::Materialized+ } else {+ RowFilterOutcome::PropertiesBlob+ };+ let filtered = spec+ .clone()+ .with_row_filter(row_filter_sql(row_filter, &columns));+ // Both renderings, because the shadow compare sends the wide one with the same filter.+ let fits = [projection, &ChunkProjection::FullColumns]+ .into_iter()+ .all(|projection| fits_client_get(&scan_sql(&filtered, projection)));+ if fits {+ (filtered, outcome)+ } else {+ (spec, RowFilterOutcome::TooLong)+ }+ };+ let team = team_label(&self.allowlist, team_id);+ counter!(SCAN_ROW_FILTER, "outcome" => outcome.as_str(), "team_id" => team).increment(1);+ spec+ }+/// Publish what this chunk's scan narrowed to, so a team that stops projecting is visible/// before its scan cost is.fn record_projection(&self, team_id: TeamId, projection: &ChunkProjection) {@@ -366,6 +426,25 @@ fn record_projected_keys(blob: &'static str, source: &BlobSource, team: Arc<str>histogram!(PROJECTION_KEYS, "blob" => blob, "team_id" => team).record(keys as f64);}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum RowFilterOutcome {+ None,+ Materialized,+ PropertiesBlob,+ TooLong,+}++impl RowFilterOutcome {+ const fn as_str(self) -> &'static str {+ match self {+ Self::None => "none",+ Self::Materialized => "materialized",+ Self::PropertiesBlob => "properties_blob",+ Self::TooLong => "too_long",+ }+ }+}+/// Why a chunk's compare is not worth issuing, when it is not. Each case would spend a second/// full-width ClickHouse query on a diff that can only agree, and the second query's right side is/// an unbounded `person_distinct_id_overrides` aggregate over the whole team.diff --git a/rust/cohort-seeder/src/clickhouse/sql.rs b/rust/cohort-seeder/src/clickhouse/sql.rsindex b7f235c57c2a..fe2c39573249 100644--- a/rust/cohort-seeder/src/clickhouse/sql.rs+++ b/rust/cohort-seeder/src/clickhouse/sql.rs@@ -1,15 +1,27 @@//! ClickHouse scan planning: the `Vacuous`-vs-`Scan` parse and the byte-frozen SQL renderer. Depends//! on `domain` (the proven range/band/event-name inputs) and `cohort-core`; never on `store`.+use std::collections::{BTreeMap, BTreeSet};use std::num::NonZeroU32;use cohort_core::filters::TeamId;+use cohort_core::hogvm::analysis::PropertyAlternatives;+use super::materialized::MaterializedColumns;use crate::domain::{BandSpec, BlobSource, ChunkProjection, ColumnPlan, EventNameSet, ProjectedKeys, ScalarColumn,- SeedDomain,+ ScanRowFilter, SeedDomain,};+/// The crate sends a longer query by POST with `readonly=1`, which the `cohort_seeder` profile's+/// `readonly=2` refuses with code 164, because the seeder sends settings with every query. The+/// profile lives in the infrastructure repository, so re-check this against the profile rather than+/// against this comment.+pub(crate) const MAX_GET_QUERY_BYTES: usize = 8192;++/// Appended by the crate's `fetch` before it measures the query.+const FETCH_FORMAT_CLAUSE: &str = " FORMAT RowBinary";+/// The rendered scan's inputs, proven complete: constructed only by [`plan_scan`] from already-proven/// types, so [`scan_sql`] never re-validates. Fields stay private — the SQL text is the only output.#[derive(Debug, Clone, PartialEq, Eq)]@@ -21,6 +33,22 @@ pub struct ScanSpec {event_names: Vec<String>,band: u32,num_bands: NonZeroU32,+ row_filter: Option<String>,+}++impl ScanSpec {+ /// On the spec rather than the projection, so both shadow-compare arms read the same rows.+ pub fn with_row_filter(self, row_filter: String) -> Self {+ Self {+ row_filter: Some(row_filter),+ ..self+ }+ }+}++/// Measured before the client collapses `??` to `?`, so the sent query is never longer.+pub fn fits_client_get(sql: &str) -> bool {+ sql.len() + FETCH_FORMAT_CLAUSE.len() <= MAX_GET_QUERY_BYTES}/// Whether a chunk has anything to scan. `plan_scan` collapses the empty-domain and empty-event-name@@ -51,6 +79,7 @@ pub fn plan_scan(event_names: event_names.as_slice().to_vec(),band: band.band(),num_bands: band.num_bands(),+ row_filter: None,})}@@ -74,6 +103,11 @@ pub fn scan_sql(spec: &ScanSpec, projection: &ChunkProjection) -> String {.map(|name| clickhouse_string_literal(name)).collect::<Vec<_>>().join(", ");+ let row_filter = spec+ .row_filter+ .as_ref()+ .map(|row_filter| format!("\n AND {row_filter}"))+ .unwrap_or_default();let band_predicate = if spec.num_bands.get() > 1 {format!("\n AND cityHash64(toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)))\n % {} = {}",@@ -84,7 +118,7 @@ pub fn scan_sql(spec: &ScanSpec, projection: &ChunkProjection) -> String {};format!(- "SELECT {}\nFROM events AS e\nLEFT JOIN (\n SELECT distinct_id, argMax(person_id, version) AS person_id\n FROM person_distinct_id_overrides\n WHERE team_id = {}\n GROUP BY distinct_id\n HAVING argMax(is_deleted, version) = 0\n) AS ov ON e.distinct_id = ov.distinct_id\nWHERE e.team_id = {}\n AND e.timestamp >= fromUnixTimestamp64Milli({})\n AND e.timestamp < fromUnixTimestamp64Milli({})\n AND e.event IN ({})\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli({}){}",+ "SELECT {}\nFROM events AS e\nLEFT JOIN (\n SELECT distinct_id, argMax(person_id, version) AS person_id\n FROM person_distinct_id_overrides\n WHERE team_id = {}\n GROUP BY distinct_id\n HAVING argMax(is_deleted, version) = 0\n) AS ov ON e.distinct_id = ov.distinct_id\nWHERE e.team_id = {}\n AND e.timestamp >= fromUnixTimestamp64Milli({})\n AND e.timestamp < fromUnixTimestamp64Milli({})\n AND e.event IN ({})\n AND coalesce(e.inserted_at, e._timestamp) < fromUnixTimestamp64Milli({}){}{}",select_list,spec.team_id.0,spec.team_id.0,@@ -92,10 +126,125 @@ pub fn scan_sql(spec: &ScanSpec, projection: &ChunkProjection) -> String {spec.day_end_ms,event_names,spec.s_chunk_ms,+ row_filter,band_predicate,)}+/// Renders a superset of HogVM equality (see [`cohort_core::hogvm::analysis::EventRowFilter`]) over+/// the value's raw JSON text without its outer quotes. The string `value` reads as itself, or holds a+/// backslash when JSON escapes one of its characters; a boolean reads as `true` or `false`; an object+/// starts with `{`. Assumes a blob holds each key once, since ClickHouse reads the first value and+/// `serde_json` the last.+pub fn row_filter_sql(filter: &ScanRowFilter, columns: &MaterializedColumns) -> String {+ let filtered_events = filter+ .events()+ .map(|(event, _)| clickhouse_string_literal(event))+ .collect::<Vec<_>>()+ .join(", ");+ let mut terms = vec![format!("e.event NOT IN ({filtered_events})")];+ for (event, conditions) in filter.events() {+ // A one-conjunct condition is a disjunction of key tests, so together they are one test per+ // key over the union of their values. This keeps many flag cohorts under the GET limit.+ let mut single_conjunct: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();+ let mut rendered = BTreeSet::new();+ for conjuncts in conditions {+ if let [alternatives] = conjuncts.as_slice() {+ for (key, values) in alternatives.iter() {+ single_conjunct+ .entry(key)+ .or_default()+ .extend(values.iter().map(String::as_str));+ }+ } else {+ rendered.insert(join_terms(+ conjuncts+ .iter()+ .map(|alternatives| alternatives_sql(alternatives, columns)),+ "AND",+ ));+ }+ }+ rendered.extend(+ single_conjunct+ .into_iter()+ .map(|(key, values)| property_value_sql(key, values, columns)),+ );+ terms.push(format!(+ "(e.event = {} AND {})",+ clickhouse_string_literal(event),+ join_terms(rendered.into_iter(), "OR"),+ ));+ }+ format!("({})", terms.join(" OR "))+}++fn alternatives_sql(alternatives: &PropertyAlternatives, columns: &MaterializedColumns) -> String {+ join_terms(+ alternatives.iter().map(|(key, values)| {+ property_value_sql(key, values.iter().map(String::as_str), columns)+ }),+ "OR",+ )+}++fn property_value_sql<'a>(+ key: &str,+ values: impl IntoIterator<Item = &'a str>,+ columns: &MaterializedColumns,+) -> String {+ // ClickHouse extracts '' for every key of a blob it cannot parse, such as one holding an integer+ // past 64 bits, which `serde_json` reads. A materialized column stores that '', so admitting ''+ // there keeps the test off the blob.+ let (value, unparsed) = match columns.column_for(key) {+ Some(column) => (format!("e.{}", clickhouse_identifier(column)), "v = ''"),+ None => (+ format!(+ "replaceRegexpAll(JSONExtractRaw(e.properties, {}), '^\"|\"$', '')",+ clickhouse_string_literal(key)+ ),+ "JSONType(e.properties) != 'Object'",+ ),+ };+ let literals = values+ .into_iter()+ .chain(["true", "false"])+ .collect::<BTreeSet<_>>()+ .into_iter()+ .map(clickhouse_string_literal)+ .collect::<Vec<_>>()+ .join(", ");+ // The lambda binds the extraction once. Written inline, ClickHouse computes each copy of it+ // separately inside the lazily evaluated branch, which parses the blob once per copy.+ format!(+ "arrayExists(v -> v IN ({literals}) OR position(v, '\\\\') > 0 OR startsWith(v, '{{') OR {unparsed}, [{value}])"+ )+}++fn join_terms(terms: impl Iterator<Item = String>, operator: &str) -> String {+ let terms = terms.collect::<Vec<_>>();+ match terms.as_slice() {+ [single] => single.clone(),+ _ => format!("({})", terms.join(&format!(" {operator} "))),+ }+}++/// Escaped for the server and for the client's template parser, which reads a bare `?` as a bind.+fn clickhouse_identifier(name: &str) -> String {+ let mut escaped = String::with_capacity(name.len() + 2);+ escaped.push('`');+ for character in name.chars() {+ match character {+ '\\' => escaped.push_str("\\\\"),+ '`' => escaped.push_str("\\`"),+ '?' => escaped.push_str("??"),+ character => escaped.push(character),+ }+ }+ escaped.push('`');+ escaped+}+/// The eight-column select list. `event`, `timestamp`, `distinct_id`, and the override-resolved/// `person_id` are always selected: the fold places the row in its day by timestamp, the accumulator/// keys on the person, and the event name decides which conditions run.@@ -397,6 +546,77 @@ mod tests {assert!(select_list_of(&sql).ends_with("e.elements_chain"), "{sql}");}+ #[test]+ fn the_row_filter_passes_other_events_and_reads_materialized_columns() {+ use crate::domain::row_filter::test_catalog::{catalog, event_and_property, hash, Leaf};+ use crate::domain::{ActiveConditions, ConditionAnalyses, Lookback, PinnedCondition};+ use cohort_core::filters::CohortId;++ let leaves = [+ Leaf {+ cohort: 1,+ key: "$feature_flag_called",+ hash: "aaaaaaaaaaaaaaaa",+ body: event_and_property("$feature_flag_called", "$feature_flag", "a"),+ },+ Leaf {+ cohort: 3,+ key: "$feature_flag_called",+ hash: "bbbbbbbbbbbbbbbb",+ body: event_and_property("$feature_flag_called", "$feature_flag", "b"),+ },+ Leaf {+ cohort: 2,+ key: "$pageview",+ hash: "cccccccccccccccc",+ body: event_and_property("$pageview", "$current_url", "https://example.com/"),+ },+ ];+ let filters = catalog(&leaves);+ let conditions = leaves+ .iter()+ .map(|leaf| PinnedCondition {+ cohort_id: CohortId(leaf.cohort),+ hash: hash(leaf.hash),+ event_name: leaf.key.to_owned(),+ lookback: Lookback::SlidingDays(7),+ })+ .collect::<Vec<_>>();+ let event_names =+ EventNameSet::new(["$feature_flag_called", "$pageview", "purchase"].map(str::to_owned));+ let row_filter = ConditionAnalyses::build(&conditions, &filters).row_filter(+ &event_names,+ &filters,+ &ActiveConditions::new(leaves.iter().map(|leaf| hash(leaf.hash))),+ );+ let columns = MaterializedColumns::from_iter([(+ "$feature_flag".to_owned(),+ "mat_$feature_flag".to_owned(),+ )]);+ let rendered = row_filter_sql(&row_filter, &columns);+ assert_eq!(+ rendered,+ "(e.event NOT IN ('$feature_flag_called', '$pageview') OR (e.event = '$feature_flag_called' AND arrayExists(v -> v IN ('a', 'b', 'false', 'true') OR position(v, '\\\\') > 0 OR startsWith(v, '{') OR v = '', [e.`mat_$feature_flag`])) OR (e.event = '$pageview' AND arrayExists(v -> v IN ('false', 'https://example.com/', 'true') OR position(v, '\\\\') > 0 OR startsWith(v, '{') OR JSONType(e.properties) != 'Object', [replaceRegexpAll(JSONExtractRaw(e.properties, '$current_url'), '^\"|\"$', '')])))"+ );++ let banded = spec(event_names.into_vec(), BandSpec::new(1, 2).unwrap());+ let unfiltered = full_sql(&banded);+ assert_eq!(+ full_sql(&banded.with_row_filter(rendered.clone())),+ unfiltered.replace(+ "\n AND cityHash64",+ &format!("\n AND {rendered}\n AND cityHash64")+ )+ );+ }++ #[test]+ fn a_query_fits_the_client_get_only_with_room_for_the_format_clause() {+ // The crate POSTs a query longer than 8192 bytes once ` FORMAT RowBinary` is appended.+ assert!(fits_client_get(&"x".repeat(8175)));+ assert!(!fits_client_get(&"x".repeat(8176)));+ }+/// The wide arm and the plan that keeps every column render the same text, which is what makes/// the frozen strings above a contract over both. Without this, the fallback could drift into a/// second, untested spelling of today's scan.diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rsindex ee9bb6d31980..35b59c026ce6 100644--- a/rust/cohort-seeder/src/config.rs+++ b/rust/cohort-seeder/src/config.rs@@ -3,7 +3,7 @@//! never away.use std::fmt;-use std::num::NonZeroU32;+use std::num::{NonZeroU32, NonZeroU64};use std::str::FromStr;use std::time::Duration;@@ -192,6 +192,21 @@ pub struct Config {#[envconfig(default = "1800")]pub seeder_retry_backoff_cap_secs: u64,+ /// ClickHouse resource errors in a row on one run before the seeder stops claiming its chunks.+ #[envconfig(default = "3")]+ pub seeder_ch_breaker_threshold: u32,++ /// The first opening's length. Each later opening doubles it, up to the cap.+ #[envconfig(default = "300")]+ pub seeder_ch_breaker_cooldown_base_secs: u64,++ #[envconfig(default = "1800")]+ pub seeder_ch_breaker_cooldown_cap_secs: u64,++ /// The opening, counted since the last confirmed chunk, that fails the run instead.+ #[envconfig(default = "4")]+ pub seeder_ch_breaker_max_trips: u32,+#[envconfig(default = "3000")]pub seeder_tiles_per_sec: u32,@@ -202,9 +217,11 @@ pub struct Config {pub seeder_max_lookback_days: u32,/// Person-hash bands each planned day is split into, bounding one chunk's in-memory aggregate- /// to roughly `uniq(person, condition) / bands`. Safe to raise mid-run: planning is idempotent- /// per (run, day, band) and tile application is max-merge idempotent, so a re-planned day only- /// adds narrower re-scans.+ /// to roughly `uniq(person, condition) / bands`.+ ///+ /// Never change it while a behavioral run is seeding. A claim takes its divisor from the day's+ /// band count at claim time and confirmed bands are not rescanned, so some persons fall in no+ /// scanned band while the run still stamps readiness.#[envconfig(default = "1")]pub seeder_bands_per_day: u16,@@ -302,16 +319,27 @@ pub struct Config {#[envconfig(default = "20000000000")]pub seeder_ch_max_bytes_before_external_sort: u64,- /// Runaway guard on sets built from `IN (SELECT …)` subqueries, which nothing else bounds — the- /// person boundary scan's horizon prefilter builds one id set covering a whole team, unchunked.- /// Exceeding it throws a set-size error naming the limit rather than pushing the server toward- /// an OOM that takes unrelated queries down with it.+ /// Runaway guard on sets built from `IN (SELECT …)` subqueries. Exceeding it throws a set-size+ /// error rather than pushing the server toward an OOM that takes unrelated queries down.#[envconfig(default = "20000000000")]pub seeder_ch_max_bytes_in_set: u64,#[envconfig(default = "grace_hash")]pub seeder_ch_join_algorithm: String,+ /// This and the next two settings are sent only when set. The `cohort_seeder` profile constrains+ /// them, and ClickHouse rejects a query that sends a value above a constraint, so a default could+ /// fail every scan. Not 0, which ClickHouse reads as one thread per core.+ pub seeder_ch_max_threads: Option<NonZeroU64>,++ /// Not 0, which ClickHouse reads as unlimited.+ pub seeder_ch_max_memory_usage: Option<NonZeroU64>,++ /// ClickHouse ranks a shard's replicas by recent error count before `<priority>`. A high value+ /// treats a replica with up to that many recent errors as healthy, so a shard's read stays on its+ /// offline replica instead of moving to an online one.+ pub seeder_ch_distributed_replica_max_ignored_errors: Option<u64>,+#[envconfig(default = "100")]pub seeder_queue_full_backoff_ms: u64,diff --git a/rust/cohort-seeder/src/domain/backoff.rs b/rust/cohort-seeder/src/domain/backoff.rsindex 82099e021c7f..1883b6b60c2a 100644--- a/rust/cohort-seeder/src/domain/backoff.rs+++ b/rust/cohort-seeder/src/domain/backoff.rs@@ -28,6 +28,12 @@ impl AttemptCount {Self(u32::try_from(attempts).map_or(1, |count| count.max(1)))}+ /// A count kept in memory rather than read from a row, such as a run breaker's openings. Zero+ /// reads as one, for the same reason as in [`Self::from_row`].+ pub fn new(count: u32) -> Self {+ Self(count.max(1))+ }+pub const fn get(self) -> u32 {self.0}diff --git a/rust/cohort-seeder/src/domain/condition_analysis.rs b/rust/cohort-seeder/src/domain/condition_analysis.rsindex 3ebeb1376061..652d6204e085 100644--- a/rust/cohort-seeder/src/domain/condition_analysis.rs+++ b/rust/cohort-seeder/src/domain/condition_analysis.rs@@ -22,14 +22,15 @@ use std::sync::Arc;use cohort_core::filters::TeamFilters;use cohort_core::hogvm::analysis::{- analyze_condition_within, AnalysisBudget, ConditionAnalysis, EvaluationClass,- FullColumnsReason, Projection, ReadPath,+ analyze_condition_within, event_row_filter, AnalysisBudget, ConditionAnalysis, EvaluationClass,+ EventRowFilter, FullColumnsReason, Projection, ReadPath,};-use super::condition::PinnedCondition;+use super::condition::{EventNameSet, PinnedCondition};use super::ids::ConditionHash;use super::plan::ActiveConditions;use super::projection::ChunkProjection;+use super::row_filter::ScanRowFilter;/// What one condition turned out to need. Ordered so a census renders the same way every time.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]@@ -118,6 +119,8 @@ const CENSUS_WORST_CASE_CONDITIONS: usize = 8;#[derive(Debug, Default)]pub struct ConditionAnalyses {by_hash: HashMap<ConditionHash, ConditionAnalysis>,+ /// Not budgeted, because matching is linear in the program.+ row_filters: HashMap<ConditionHash, EventRowFilter>,}impl ConditionAnalyses {@@ -129,6 +132,7 @@ impl ConditionAnalyses {pub fn build(conditions: &[PinnedCondition], filters: &TeamFilters) -> Self {let mut budget = AnalysisBudget::for_conditions(CENSUS_WORST_CASE_CONDITIONS);let mut by_hash = HashMap::new();+ let mut row_filters = HashMap::new();for condition in conditions {if by_hash.contains_key(&condition.hash) {continue;@@ -143,8 +147,27 @@ impl ConditionAnalyses {condition.hash,analyze_condition_within(program.tokens(), &mut budget),);+ if let Some(row_filter) = event_row_filter(program.tokens()) {+ row_filters.insert(condition.hash, row_filter);+ }+ }+ Self {+ by_hash,+ row_filters,}- Self { by_hash }+ }++ pub fn row_filter(+ &self,+ event_names: &EventNameSet,+ filters: &TeamFilters,+ active: &ActiveConditions,+ ) -> ScanRowFilter {+ ScanRowFilter::derive(event_names, filters, active, &self.row_filters)+ }++ pub fn row_filtered_conditions(&self) -> usize {+ self.row_filters.len()}/// What a scan over the conditions active on one chunk has to select.diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rsindex a193a180fd25..bb923f502709 100644--- a/rust/cohort-seeder/src/domain/mod.rs+++ b/rust/cohort-seeder/src/domain/mod.rs@@ -24,6 +24,7 @@ pub mod person_relevance;pub mod pinned;pub mod plan;pub mod projection;+pub mod row_filter;pub mod window;pub use aggregate::{@@ -73,4 +74,5 @@ pub use pinned::{};pub use plan::{bands_for_day, conditions_active_on, plan_days, ActiveConditions};pub use projection::{BlobSource, ChunkProjection, ColumnPlan, ProjectedKeys, ScalarColumn};+pub use row_filter::{ConditionConjuncts, ScanRowFilter};pub use window::{Boundary, DaySchedule, DomainError, PlanCaps, PlannedDay, SeedDomain};diff --git a/rust/cohort-seeder/src/domain/row_filter.rs b/rust/cohort-seeder/src/domain/row_filter.rsnew file mode 100644index 000000000000..1df4610315c1--- /dev/null+++ b/rust/cohort-seeder/src/domain/row_filter.rs@@ -0,0 +1,255 @@+//! Domain layer: which rows of each event a chunk's scan may leave in ClickHouse.+//!+//! A row is evaluated only against the active conditions of its event, and a row no condition+//! matches adds nothing to any tile. So an event can be filtered only when every active condition on+//! it has a row filter.++use std::collections::{BTreeMap, BTreeSet, HashMap};++use cohort_core::filters::TeamFilters;+use cohort_core::hogvm::analysis::{EventRowFilter, PropertyAlternatives};++use super::condition::EventNameSet;+use super::ids::ConditionHash;+use super::plan::ActiveConditions;++pub type ConditionConjuncts = Vec<PropertyAlternatives>;++/// Per filtered event, the conditions a row must satisfy one of. Other events are scanned whole.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ScanRowFilter {+ by_event: BTreeMap<String, Vec<ConditionConjuncts>>,+}++impl ScanRowFilter {+ /// A condition's filter counts for an event only when its program tests that event, because the+ /// reverse index buckets conditions by the leaf's key, not by the bytecode.+ pub fn derive(+ event_names: &EventNameSet,+ filters: &TeamFilters,+ active: &ActiveConditions,+ row_filters: &HashMap<ConditionHash, EventRowFilter>,+ ) -> Self {+ let mut by_event = BTreeMap::new();+ for event in event_names.iter() {+ let Some(bucket) = filters.behavioral_by_event_name.get(event) else {+ continue;+ };+ let mut conditions: Vec<ConditionConjuncts> = Vec::new();+ let mut every_condition_filtered = true;+ for candidate in &bucket.conditions {+ let Some(hash) = active.get(candidate) else {+ continue;+ };+ match row_filters.get(&hash) {+ Some(row_filter) if row_filter.event == *event => {+ if !conditions.contains(&row_filter.conjuncts) {+ conditions.push(row_filter.conjuncts.clone());+ }+ }+ Some(_) | None => {+ every_condition_filtered = false;+ break;+ }+ }+ }+ if every_condition_filtered && !conditions.is_empty() {+ by_event.insert(event.clone(), conditions);+ }+ }+ Self { by_event }+ }++ pub fn is_empty(&self) -> bool {+ self.by_event.is_empty()+ }++ pub fn events(&self) -> impl Iterator<Item = (&str, &[ConditionConjuncts])> {+ self.by_event+ .iter()+ .map(|(event, conditions)| (event.as_str(), conditions.as_slice()))+ }++ pub fn keys(&self) -> BTreeSet<&str> {+ self.by_event+ .values()+ .flatten()+ .flatten()+ .flat_map(|alternatives| alternatives.iter().map(|(key, _)| key))+ .collect()+ }+}++#[cfg(test)]+pub(crate) mod test_catalog {+ use chrono_tz::UTC;+ use cohort_core::filters::{CohortId, TeamFilters, TeamFiltersBuilder, TeamId};+ use serde_json::{json, Value};++ use crate::domain::ConditionHash;++ pub(crate) struct Leaf {+ pub(crate) cohort: i32,+ pub(crate) key: &'static str,+ pub(crate) hash: &'static str,+ pub(crate) body: Vec<Value>,+ }++ pub(crate) fn event_is(name: &str) -> Vec<Value> {+ vec![+ json!(32),+ json!(name),+ json!(32),+ json!("event"),+ json!(1),+ json!(1),+ json!(11),+ ]+ }++ pub(crate) fn event_and_property(event: &str, key: &str, value: &str) -> Vec<Value> {+ let mut body = event_is(event);+ body.extend([+ json!(32),+ json!(value),+ json!(32),+ json!(key),+ json!(32),+ json!("properties"),+ json!(1),+ json!(2),+ json!(11),+ json!(3),+ json!(2),+ ]);+ body+ }++ pub(crate) fn catalog(leaves: &[Leaf]) -> TeamFilters {+ let mut builder = TeamFiltersBuilder::default();+ for leaf in leaves {+ let mut bytecode = vec![json!("_H"), json!(1)];+ bytecode.extend(leaf.body.iter().cloned());+ builder+ .add_cohort(+ CohortId(leaf.cohort),+ TeamId(2),+ &json!({+ "properties": { "type": "AND", "values": [{+ "type": "behavioral",+ "value": "performed_event",+ "key": leaf.key,+ "conditionHash": leaf.hash,+ "time_value": 7,+ "time_interval": "day",+ "bytecode": bytecode,+ }]}+ }),+ )+ .unwrap();+ }+ builder.freeze(UTC)+ }++ pub(crate) fn hash(value: &str) -> ConditionHash {+ ConditionHash::parse(value).unwrap()+ }+}++#[cfg(test)]+mod tests {+ use cohort_core::filters::CohortId;++ use super::test_catalog::{catalog, event_and_property, event_is, hash, Leaf};+ use super::*;+ use crate::domain::{ConditionAnalyses, Lookback, PinnedCondition};++ const FLAG_A: &str = "aaaaaaaaaaaaaaaa";+ const FLAG_B: &str = "bbbbbbbbbbbbbbbb";+ const PAGE_URL: &str = "cccccccccccccccc";+ const PAGE_ANY: &str = "dddddddddddddddd";+ const MISFILED: &str = "eeeeeeeeeeeeeeee";++ fn leaves() -> Vec<Leaf> {+ vec![+ Leaf {+ cohort: 1,+ key: "$feature_flag_called",+ hash: FLAG_A,+ body: event_and_property("$feature_flag_called", "$feature_flag", "a"),+ },+ Leaf {+ cohort: 2,+ key: "$feature_flag_called",+ hash: FLAG_B,+ body: event_and_property("$feature_flag_called", "$feature_flag", "b"),+ },+ Leaf {+ cohort: 3,+ key: "$pageview",+ hash: PAGE_URL,+ body: event_and_property("$pageview", "$current_url", "https://example.com/"),+ },+ Leaf {+ cohort: 4,+ key: "$pageview",+ hash: PAGE_ANY,+ body: event_is("$pageview"),+ },+ // Filed under a key that differs from the event its program tests.+ Leaf {+ cohort: 5,+ key: "purchase",+ hash: MISFILED,+ body: event_and_property("refund", "currency", "EUR"),+ },+ ]+ }++ fn row_filter(active: &[&str]) -> ScanRowFilter {+ let leaves = leaves();+ let filters = catalog(&leaves);+ let conditions = leaves+ .iter()+ .map(|leaf| PinnedCondition {+ cohort_id: CohortId(leaf.cohort),+ hash: hash(leaf.hash),+ event_name: leaf.key.to_owned(),+ lookback: Lookback::SlidingDays(7),+ })+ .collect::<Vec<_>>();+ let analyses = ConditionAnalyses::build(&conditions, &filters);+ analyses.row_filter(+ &EventNameSet::new(leaves.iter().map(|leaf| leaf.key.to_owned())),+ &filters,+ &ActiveConditions::new(active.iter().map(|value| hash(value))),+ )+ }++ fn filtered_events(filter: &ScanRowFilter) -> Vec<&str> {+ filter.events().map(|(event, _)| event).collect()+ }++ #[test]+ fn an_event_is_filtered_only_when_every_active_condition_on_it_is() {+ let all = row_filter(&[FLAG_A, FLAG_B, PAGE_URL, PAGE_ANY, MISFILED]);+ assert_eq!(filtered_events(&all), vec!["$feature_flag_called"]);+ let (_, conditions) = all.events().next().unwrap();+ assert_eq!(conditions.len(), 2, "one entry per flag condition");++ let without_any = row_filter(&[FLAG_A, PAGE_URL]);+ assert_eq!(+ filtered_events(&without_any),+ vec!["$feature_flag_called", "$pageview"]+ );+ assert_eq!(+ without_any.keys(),+ BTreeSet::from(["$current_url", "$feature_flag"])+ );+ }++ #[test]+ fn a_condition_filed_under_another_event_keeps_that_event_whole() {+ assert!(row_filter(&[MISFILED]).is_empty());+ }+}diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rsindex 38417eacf3c4..0930df0250b0 100644--- a/rust/cohort-seeder/src/main.rs+++ b/rust/cohort-seeder/src/main.rs@@ -329,6 +329,11 @@ fn log_startup(config: &Config) {).as_str(),scan_shadow_compare = config.seeder_scan_shadow_compare,+ ch_max_threads = ?config.seeder_ch_max_threads,+ ch_max_memory_usage = ?config.seeder_ch_max_memory_usage,+ ch_distributed_replica_max_ignored_errors =+ ?config.seeder_ch_distributed_replica_max_ignored_errors,+ ch_max_bytes_in_set = config.seeder_ch_max_bytes_in_set,reconcile_auto_dispatch_enabled = config.seeder_reconcile_auto_dispatch_enabled,confirm_register_backfilled = config.seeder_confirm_register_backfilled,reconcile_max_concurrent_dispatches = config.seeder_reconcile_max_concurrent_dispatches,diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rsindex 8c1821095263..b95a9c29f005 100644--- a/rust/cohort-seeder/src/observability/metrics.rs+++ b/rust/cohort-seeder/src/observability/metrics.rs@@ -89,6 +89,10 @@ pub const SHADOW_COMPARE_LEGACY_SKIPPED: &str = "seeder_shadow_compare_legacy_sk/// sentinel would be indistinguishable from a real reading. Those show up as decoded bytes that do/// not fall — read this against `seeder_scan_decoded_bytes_total{kind="behavioral"}`.pub const PROJECTION_KEYS: &str = "seeder_projection_keys";+/// Behavioral chunks by row filter `outcome` (`none`/`materialized`/`properties_blob`/`too_long`)+/// and `team_id` (counter). Only `materialized` saves ClickHouse reads; `properties_blob` saves the+/// transfer and evaluation of rows no condition matches.+pub const SCAN_ROW_FILTER: &str = "seeder_scan_row_filter_total";pub const CHUNKS_PLANNED: &str = "seeder_chunks_planned_total";pub const CHUNKS_CLAIMED: &str = "seeder_chunks_claimed_total";pub const CHUNKS_RECLAIMED: &str = "seeder_chunks_reclaimed_total";@@ -101,6 +105,15 @@ pub const CHUNKS_POISONED: &str = "seeder_chunks_poisoned_total";/// blocking every future run for that cohort. The paired `warn!` carries the chunk and its error,/// which is what an operator reads once this counter points them at a run.pub const RUNS_FAILED_EXHAUSTED_CHUNKS: &str = "seeder_runs_failed_exhausted_chunks_total";+/// Failed chunks ClickHouse refused for lack of resources, by `kind` and `code` (counter). A+/// response ClickHouse cut mid-stream carries no code and counts as `code="response_cut"`.+pub const CLICKHOUSE_RESOURCE_ERRORS: &str = "seeder_clickhouse_resource_errors_total";+/// Run breaker openings, by `kind` (counter).+pub const RUN_BREAKER_TRIPS: &str = "seeder_run_breaker_trips_total";+/// Runs failed at the breaker trip limit, by `kind` (counter).+pub const RUNS_FAILED_BREAKER: &str = "seeder_runs_failed_breaker_total";+/// Eligible runs whose breaker is not closed, by `kind` (gauge).+pub const RUN_BREAKERS_OPEN: &str = "seeder_run_breakers_open";pub const CHUNK_SCAN_DURATION_SECONDS: &str = "seeder_chunk_scan_duration_seconds";/// Compressed bytes a scan cursor read off the wire, labelled by `kind` (counter). Paired with/// [`SCAN_DECODED_BYTES`], it tells a slow scan that moved a lot of data apart from one that moveddiff --git a/rust/cohort-seeder/tests/ch_event_row_filter.rs b/rust/cohort-seeder/tests/ch_event_row_filter.rsnew file mode 100644index 000000000000..7b987877210c--- /dev/null+++ b/rust/cohort-seeder/tests/ch_event_row_filter.rs@@ -0,0 +1,356 @@+//! Checks against a live ClickHouse that a behavioral scan's row filter admits every row the+//! condition's program matches, with the VM as the oracle, and that the materialized-column lookup+//! accepts only columns holding the same values.++#![cfg(feature = "ch-test-support")]++use std::collections::BTreeSet;++use chrono_tz::UTC;+use clickhouse::Row;+use cohort_core::events::CohortStreamEvent;+use cohort_core::filters::{CohortId, TeamFilters, TeamFiltersBuilder, TeamId};+use cohort_core::hogvm::analysis::GlobalsPlan;+use cohort_core::hogvm::{build_behavioral_globals, evaluate_detailed, EvalOutcome, GlobalsBuild};+use cohort_seeder::clickhouse::client::build_client;+use cohort_seeder::clickhouse::materialized::MaterializedColumns;+use cohort_seeder::clickhouse::sql::row_filter_sql;+use cohort_seeder::clickhouse::ClickHouseClient;+use cohort_seeder::config::Config;+use cohort_seeder::domain::{+ ActiveConditions, ConditionAnalyses, ConditionHash, EventNameSet, Lookback, PinnedCondition,+};+use envconfig::Envconfig;+use serde::Deserialize;+use serde_json::{json, Value};++const HASH: &str = "aaaaaaaaaaaaaaaa";+const EVENT: &str = "$feature_flag_called";+const KEY: &str = "$feature_flag";+/// A second event property, for the condition whose filter holds two conjuncts.+const SECOND_KEY: &str = "plan";+const MATERIALIZED: &str = "mat_$feature_flag";++const VALUES: &[&str] = &[+ "my-flag",+ "true",+ "TRUE",+ "false",+ "",+ "2024-01-01",+ "2024-01-01T00:00:00Z",+ "a\"b",+ "a\\b",+ "tab\there",+ "é😀",+ "quote' OR 1 = 1 --",+ "why?fields",+ "{not json",+];++/// No blob repeats a key: ClickHouse reads the first value and `serde_json` the last, and stored+/// event properties never repeat one.+const FIXED_BLOBS: &[&str] = &[+ r#"{}"#,+ r#"{"other":"my-flag"}"#,+ r#"{"$feature_flag":"another-flag"}"#,+ r#"{"$feature_flag":"MY-FLAG"}"#,+ r#"{"$feature_flag":null}"#,+ r#"{"$feature_flag":true}"#,+ r#"{"$feature_flag":false}"#,+ r#"{"$feature_flag":5}"#,+ r#"{"$feature_flag":5.0}"#,+ r#"{"$feature_flag":["my-flag"]}"#,+ r#"{"$feature_flag":{"my-flag":1}}"#,+ r#"{"$feature_flag":{"__hogDateTime__":true,"dt":1704067200,"zone":"UTC"}}"#,+ r#"{"$feature_flag":{"__hogDate__":true,"year":2024,"month":1,"day":1}}"#,+ r#"{ "$feature_flag" : "my-flag" , "other" : 1 }"#,+ r#"{"nested":{"$feature_flag":"my-flag"}}"#,+ r#"["my-flag"]"#,+ r#""my-flag""#,+ r#"null"#,+ r#""#,+ r#"{not json"#,+ // ClickHouse cannot parse an integer past 64 bits, which `serde_json` reads as a float.+ r#"{"$feature_flag":"my-flag","n":18446744073709551616}"#,+ r#"{"n":18446744073709552000,"$feature_flag":"my-flag"}"#,+ r#"{"$feature_flag":"my-flag","n":-9223372036854775809}"#,+];++#[derive(Row, Deserialize)]+struct Admitted {+ index: u32,+ admitted: bool,+}++#[tokio::test]+async fn the_row_filter_admits_every_row_the_program_matches() {+ let client = connect(None);+ let materialized = MaterializedColumns::from_iter([(KEY.to_owned(), MATERIALIZED.to_owned())]);+ for keys in [&[KEY][..], &[KEY, SECOND_KEY]] {+ for value in VALUES {+ let (filters, program) = condition(value, keys);+ let blobs = blobs_for(value);+ let plain = Value::Object(+ keys.iter()+ .map(|key| ((*key).to_owned(), json!(value)))+ .collect(),+ );+ assert!(+ program_matches(&program, &plain.to_string()),+ "value {value:?}: the program matches no blob, so nothing below is checked"+ );+ for columns in [&MaterializedColumns::default(), &materialized] {+ let predicate = rendered_predicate(&filters, columns);+ let admitted = admit_all(&client, &predicate, &blobs).await;+ for (blob, admitted) in blobs.iter().zip(admitted) {+ if program_matches(&program, blob) {+ assert!(+ admitted,+ "value {value:?}: the program matches {blob:?} but the filter dropped it\n{predicate}"+ );+ }+ }+ }+ }+ }+}++#[tokio::test]+async fn the_row_filter_drops_rows_no_program_can_match() {+ let client = connect(None);+ let (filters, _) = condition("my-flag", &[KEY]);+ let predicate = rendered_predicate(&filters, &MaterializedColumns::default());+ let dropped = [+ r#"{}"#,+ r#"{"other":"my-flag"}"#,+ r#"{"$feature_flag":"another-flag"}"#,+ r#"{"$feature_flag":"MY-FLAG"}"#,+ r#"{"$feature_flag":null}"#,+ r#"{"$feature_flag":5}"#,+ r#"{"$feature_flag":["my-flag"]}"#,+ r#"{"nested":{"$feature_flag":"my-flag"}}"#,+ ];+ let admitted = admit_all(&client, &predicate, &dropped).await;+ assert_eq!(admitted, vec![false; dropped.len()], "{predicate}");+}++/// Only a live server shows how ClickHouse formats the stored default expression.+#[tokio::test]+async fn the_lookup_accepts_only_trim_quotes_columns_on_both_tables() {+ const DATABASE: &str = "seeder_materialized_lookup";+ let admin = connect(None);+ for statement in [+ format!("DROP DATABASE IF EXISTS {DATABASE}"),+ format!("CREATE DATABASE {DATABASE}"),+ format!(+ "CREATE TABLE {DATABASE}.sharded_events (\+ properties String, \+ `mat_$feature_flag` String DEFAULT replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag'), '^\"|\"$', ''), \+ mat_typed String DEFAULT JSONExtract(properties, 'typed', 'String'), \+ mat_nullable Nullable(String) DEFAULT JSONExtract(properties, 'nullable', 'Nullable(String)'), \+ `mat_$data_only` String DEFAULT replaceRegexpAll(JSONExtractRaw(properties, '$data_only'), '^\"|\"$', '')\+ ) ENGINE = MergeTree ORDER BY tuple()"+ ),+ format!(+ "CREATE TABLE {DATABASE}.events (\+ properties String, \+ `mat_$feature_flag` String COMMENT 'column_materializer::properties::$feature_flag', \+ mat_typed String, \+ mat_nullable Nullable(String)\+ ) ENGINE = Memory"+ ),+ ] {+ admin+ .query(&statement)+ .execute()+ .await+ .unwrap_or_else(|error| panic!("{error}\n{statement}"));+ }++ let client = connect(Some(DATABASE));+ let keys = BTreeSet::from(["$feature_flag", "typed", "nullable", "$data_only", "absent"]);+ let columns = MaterializedColumns::lookup(&client, &keys)+ .await+ .expect("the lookup reads only system.columns");+ assert_eq!(+ columns.column_for("$feature_flag"),+ Some("mat_$feature_flag")+ );+ for refused in ["typed", "nullable", "$data_only", "absent"] {+ assert_eq!(columns.column_for(refused), None, "{refused}");+ }+}++fn connect(database: Option<&str>) -> ClickHouseClient {+ let mut config = Config::init_from_env().expect("the seeder config falls back to its defaults");+ if let Some(database) = database {+ config.clickhouse_database = database.to_owned();+ }+ build_client(&config).expect("the default ClickHouse client builds")+}++/// `event == EVENT` and `properties[key] == value` for every key, the bytecode the compiler emits for+/// exact event property filters.+fn condition(value: &str, keys: &[&str]) -> (TeamFilters, Vec<Value>) {+ let mut bytecode = vec![+ json!("_H"),+ json!(1),+ json!(32),+ json!(EVENT),+ json!(32),+ json!("event"),+ json!(1),+ json!(1),+ json!(11),+ ];+ for key in keys {+ bytecode.extend([+ json!(32),+ json!(value),+ json!(32),+ json!(key),+ json!(32),+ json!("properties"),+ json!(1),+ json!(2),+ json!(11),+ ]);+ }+ bytecode.extend([json!(3), json!(keys.len() + 1)]);+ let mut builder = TeamFiltersBuilder::default();+ builder+ .add_cohort(+ CohortId(1),+ TeamId(2),+ &json!({+ "properties": { "type": "AND", "values": [{+ "type": "behavioral",+ "value": "performed_event",+ "key": EVENT,+ "conditionHash": HASH,+ "time_value": 7,+ "time_interval": "day",+ "bytecode": bytecode+ }]}+ }),+ )+ .unwrap();+ let filters = builder.freeze(UTC);+ let hash = ConditionHash::parse(HASH).unwrap();+ let program = filters+ .by_condition_to_program+ .get(&hash.as_bytes())+ .expect("the catalog loads the condition's program")+ .tokens()+ .to_vec();+ (filters, program)+}++fn rendered_predicate(filters: &TeamFilters, columns: &MaterializedColumns) -> String {+ let hash = ConditionHash::parse(HASH).unwrap();+ let conditions = [PinnedCondition {+ cohort_id: CohortId(1),+ hash,+ event_name: EVENT.to_owned(),+ lookback: Lookback::SlidingDays(7),+ }];+ let analyses = ConditionAnalyses::build(&conditions, filters);+ let row_filter = analyses.row_filter(+ &EventNameSet::new([EVENT.to_owned()]),+ filters,+ &ActiveConditions::new([hash]),+ );+ assert!(+ !row_filter.is_empty(),+ "the condition carries no row filter"+ );+ let predicate = row_filter_sql(&row_filter, columns);+ assert_eq!(+ predicate.contains("e.properties"),+ row_filter+ .keys()+ .iter()+ .any(|key| columns.column_for(key).is_none()),+ "a materialized column must keep the filter off the blob: {predicate}"+ );+ // The materializer's default expression, so the column holds what it holds in `events`.+ predicate+ .replace(+ &format!("e.`{MATERIALIZED}`"),+ &format!("replaceRegexpAll(JSONExtractRaw(blob, '{KEY}'), '^\"|\"$', '')"),+ )+ .replace("e.properties", "blob")+ .replace("e.event", "'$feature_flag_called'")+}++fn blobs_for(value: &str) -> Vec<String> {+ let escaped = value+ .encode_utf16()+ .map(|unit| format!("\\u{unit:04x}"))+ .collect::<String>();+ let mut blobs: Vec<String> = FIXED_BLOBS.iter().map(|blob| (*blob).to_owned()).collect();+ blobs.push(json!({ KEY: value }).to_string());+ blobs.push(format!(r#"{{"{KEY}":"{escaped}"}}"#));+ blobs.push(json!({ KEY: value, SECOND_KEY: value }).to_string());+ blobs.push(format!(+ r#"{{"{KEY}":"{escaped}","{SECOND_KEY}":"{escaped}"}}"#+ ));+ blobs.push(json!({ SECOND_KEY: value }).to_string());+ blobs+}++fn program_matches(program: &[Value], blob: &str) -> bool {+ let event = CohortStreamEvent {+ team_id: 2,+ person_id: "0190c3a5-0000-7000-8000-000000000001".to_owned(),+ distinct_id: "distinct".to_owned(),+ uuid: "0190c3a5-0000-7000-8000-000000000002".to_owned(),+ event: EVENT.to_owned(),+ timestamp: "2024-01-01 00:00:00.000000".to_owned(),+ properties: (!blob.is_empty()).then(|| blob.to_owned()),+ person_properties: None,+ elements_chain: None,+ source_offset: 0,+ source_partition: -1,+ redirected_from: None,+ redirect_hops: 0,+ };+ let Ok(globals) = build_behavioral_globals(&event, GlobalsBuild::whole(GlobalsPlan::FULL))+ else {+ return false;+ };+ matches!(+ evaluate_detailed(program, globals),+ EvalOutcome::Matched(true)+ )+}++async fn admit_all(+ client: &ClickHouseClient,+ predicate: &str,+ blobs: &[impl AsRef<str>],+) -> Vec<bool> {+ let sql = format!(+ "WITH ? AS blobs\nSELECT index, {predicate} AS admitted\nFROM (SELECT arrayJoin(arrayEnumerate(blobs)) AS index, blobs[index] AS blob)\nORDER BY index",+ );+ let owned = blobs+ .iter()+ .map(|blob| blob.as_ref().to_owned())+ .collect::<Vec<_>>();+ let rows = client+ .query(&sql)+ .bind(owned)+ .fetch_all::<Admitted>()+ .await+ .unwrap_or_else(|error| panic!("the row-filter query failed: {error}\n{sql}"));+ assert_eq!(rows.len(), blobs.len(), "a blob went missing: {sql}");+ for (position, row) in rows.iter().enumerate() {+ assert_eq!(+ row.index as usize,+ position + 1,+ "rows arrived out of order: {sql}"+ );+ }+ rows.into_iter().map(|row| row.admitted).collect()+}diff --git a/rust/cohort-seeder/tests/ch_resource_errors.rs b/rust/cohort-seeder/tests/ch_resource_errors.rsnew file mode 100644index 000000000000..2c1e7000155b--- /dev/null+++ b/rust/cohort-seeder/tests/ch_resource_errors.rs@@ -0,0 +1,55 @@+//! Checks against a live ClickHouse that the run breaker classifies a scan the server stops after+//! rows have flowed. The client reads no error code then, so only a real response shows the shape.++#![cfg(feature = "ch-test-support")]++use cohort_seeder::clickhouse::client::build_client;+use cohort_seeder::clickhouse::ResourceError;+use cohort_seeder::config::Config;+use envconfig::Envconfig;++#[tokio::test]+async fn a_resource_error_raised_mid_stream_reaches_the_breaker() {+ let client = build_client(&Config::init_from_env().expect("the seeder config has defaults"))+ .expect("the default ClickHouse client builds");+ let memory = "SELECT number FROM numbers(10000000) WHERE throwIf(number = 5000000, 'test', toInt32(241)) = 0";+ for (sql, settings, expected) in [+ (+ memory,+ [+ ("allow_custom_error_code_in_throwif", "1"),+ ("max_threads", "1"),+ ],+ ResourceError::MemoryLimitExceeded,+ ),+ (+ "SELECT number FROM system.numbers",+ [("max_execution_time", "1"), ("max_threads", "1")],+ ResourceError::TimeoutExceeded,+ ),+ ] {+ let query = settings+ .into_iter()+ .fold(client.query(sql), |query, (name, value)| {+ query.with_option(name, value)+ });+ let mut cursor = query.fetch::<u64>().expect("the query builds");+ let mut rows = 0_u64;+ let error = loop {+ match cursor.next().await {+ Ok(Some(_)) => rows += 1,+ Ok(None) => panic!("{sql}: finished without an error"),+ Err(error) => break error,+ }+ };+ assert!(+ rows > 0,+ "{sql}: failed before any row, so nothing was streamed"+ );+ let classified = ResourceError::classify(&error);+ assert!(+ classified == Some(expected) || classified == Some(ResourceError::ResponseCut),+ "{sql}: {error:?} classified as {classified:?}"+ );+ }+}