:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(logs): retry a cut-short logs alert query with its full time (#118165)
Jimmy Zhu2f95fe00a540
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex 6c865c34db97..a9c9885bfb04 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -29,6 +29,7 @@ import structlogfrom posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.dataclasses import frozen+from posthog.exceptions import ClickHouseEstimatedQueryExecutionTimeTooLong, ClickHouseQueryTimeOutfrom posthog.models import Teamfrom posthog.temporal.alerts.admission import hold_evaluation_slot, release_evaluation_slotfrom posthog.utils import absolute_uri@@ -126,6 +127,8 @@ MIN_QUERY_SECONDS = 2# With the cohort budget this keeps every query of a batch inside `BATCH_SLOT_LEASE_SECONDS`, so a# query never runs after its slot frees for another batch.CHECKPOINT_QUERY_SECONDS = 10+# The errors ClickHouse raises when a query exceeds, or is estimated to exceed, its time limit.+_OUT_OF_TIME_ERRORS: Final = (ClickHouseQueryTimeOut, ClickHouseEstimatedQueryExecutionTimeTooLong)INFLIGHT_KEY = "alerts:platform:logs:batches:inflight"# A workflow takes the slot before its evaluation activity starts, and the activity holds it again@@ -565,8 +568,10 @@ def _evaluate_cohort(*,now: datetime,query_seconds: int,+ cut_short: bool,muted_ids: frozenset[UUID],-) -> list[Decision]:+) -> list[Decision] | None:+ """The cohort's decisions, or None when it ran out of time that earlier queries spent."""window_minutes, evaluation_periods, cadence_minutes, projection_eligible, date_to = keylookback = rolling_check_lookback_minutes(window_minutes, cadence_minutes, evaluation_periods)@@ -581,6 +586,8 @@ def _evaluate_cohort(ch_user=ClickHouseUser.ALERTS_PLATFORM_LOGS,).execute_rolling_checks(date_to, window_minutes, cadence_minutes, evaluation_periods)except Exception as error:+ if cut_short and isinstance(error, _OUT_OF_TIME_ERRORS):+ return None# One cohort's query must not end the batch, which is how the production cohort runner# contains the same failure.logger.exception(@@ -748,8 +755,9 @@ def _evaluate_grouped(checkpoint: datetime | None,now: datetime,query_seconds: int,+ cut_short: bool,muted: bool,-) -> Decision:+) -> Decision | None:"""One grouped alert: its own query, then the platform's per-group decision.An open group the query did not return had no matching log, so it is checked against a zero@@ -779,6 +787,8 @@ def _evaluate_grouped(date_to, condition.window_minutes, check.check_interval_minutes, check.evaluation_periods)except Exception as error:+ if cut_short and isinstance(error, _OUT_OF_TIME_ERRORS):+ return Nonelogger.exception("Grouped logs alert query failed", check_id=str(check.id), error=str(error))return _delivery(check, _failed(check, error, now=now, muted=muted), window_end=date_to, now=now, failed=True)@@ -1042,6 +1052,11 @@ def _evaluate_admitted(deadline = started_at + BATCH_QUERY_BUDGET_SECONDSunqueried = 0+ # A query that runs out of time the queries before it spent records nothing, so its checks keep+ # their due time. Discovery then hands their slot back alone, and the first query of that batch+ # has the full time, so a query too slow even with it counts toward BROKEN rather than retrying+ # forever. The first query of a batch has nothing before it to blame, so its timeout counts.+ queried = False# Capped the way the production cohort query requires: one batched query carries one countIf# column per alert, so an uncapped cohort is an unbounded query.chunks = [@@ -1056,26 +1071,39 @@ def _evaluate_admitted(# advancing their schedule would drop a real check. They keep their due time.unqueried += len(chunk)continue- decided.extend(- _evaluate_cohort(- team, chunk, cohort_key, now=cutoff, query_seconds=query_seconds, muted_ids=triage.muted_ids- )+ cohort_decided = _evaluate_cohort(+ team,+ chunk,+ cohort_key,+ now=cutoff,+ query_seconds=query_seconds,+ cut_short=queried and query_seconds < MAX_QUERY_SECONDS,+ muted_ids=triage.muted_ids,)+ queried = True+ if cohort_decided is None:+ unqueried += len(chunk)+ continue+ decided.extend(cohort_decided)for check in grouped:query_seconds = min(MAX_QUERY_SECONDS, int(deadline - time.monotonic()))if query_seconds < MIN_QUERY_SECONDS:unqueried += 1continue- decided.append(- _evaluate_grouped(- team,- check,- checkpoint=checkpoint,- now=cutoff,- query_seconds=query_seconds,- muted=check.id in triage.muted_ids,- )+ grouped_decided = _evaluate_grouped(+ team,+ check,+ checkpoint=checkpoint,+ now=cutoff,+ query_seconds=query_seconds,+ cut_short=queried and query_seconds < MAX_QUERY_SECONDS,+ muted=check.id in triage.muted_ids,)+ queried = True+ if grouped_decided is None:+ unqueried += 1+ continue+ decided.append(grouped_decided)if unqueried:logger.warning(diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.pyindex 15888f2bc005..9398c1400d5c 100644--- a/products/logs/backend/test/test_alert_evaluate.py+++ b/products/logs/backend/test/test_alert_evaluate.py@@ -14,6 +14,7 @@ from parameterized import parameterizedfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog import redis+from posthog.exceptions import ClickHouseQueryTimeOutfrom posthog.models.scoping import team_scopefrom posthog.temporal.alerts.admission import admit_evaluation_slots@@ -70,6 +71,9 @@ _LOGS_OWNED_FIELDS = ("state", "consecutive_failures", "next_check_at", "last_no_LEGACY_ALERT_FIELDS = ("evaluation_periods", "datapoints_to_alarm", "cooldown_minutes", "schedule_restriction")+_BY_SERVICE = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("service_name",))++class TestLogsAlertEvaluation(APIBaseTest):def setUp(self) -> None:super().setUp()@@ -474,6 +478,61 @@ class TestLogsAlertEvaluation(APIBaseTest):assert configuration.next_check_at is not Noneassert configuration.next_check_at > self.cutoff+ @parameterized.expand(+ [+ ("cohort_cut_short_by_an_earlier_query", Grouping(), True, 10, None),+ ("cohort_with_its_full_time_after_another", Grouping(), True, 0, 5),+ ("cohort_first_in_its_batch", Grouping(), False, 0, 5),+ ("grouped_cut_short_by_an_earlier_query", _BY_SERVICE, True, 10, None),+ ("grouped_with_its_full_time_after_another", _BY_SERVICE, True, 0, 5),+ ]+ )+ def test_a_query_out_of_time_counts_only_when_no_earlier_query_spent_its_time(+ self,+ _name: str,+ grouping: Grouping,+ after_another: bool,+ earlier_query_seconds: int,+ expected_failures: int | None,+ ) -> None:+ if after_another:+ self._configuration()+ slow = self._configuration(+ consecutive_failures=4,+ grouping=grouping.to_stored(),+ source_config={"condition": {**CONDITION, "window_minutes": 10}},+ )+ clock = [1000.0]+ cohort_calls: list[int] = []++ def cohort_query_run(*_args: Any, **_kwargs: Any) -> BatchedBucketedResult:+ # The first cohort is the earlier query when one runs; any later cohort is the slow one.+ cohort_calls.append(1)+ if after_another and grouping.mode == GroupingMode.SINGLE and len(cohort_calls) > 1:+ raise ClickHouseQueryTimeOut()+ if not after_another:+ raise ClickHouseQueryTimeOut()+ clock[0] += earlier_query_seconds+ return BatchedBucketedResult(per_alert={}, query_duration_ms=1)++ with (+ patch(f"{_MODULE}.time") as fake_time,+ patch(f"{_MODULE}.fetch_live_logs_checkpoint", return_value=None),+ patch(f"{_MODULE}.BatchedAlertCheckQuery") as cohort_query,+ patch(f"{_MODULE}.GroupedAlertCheckQuery") as grouped_query,+ ):+ fake_time.monotonic.side_effect = lambda: clock[0]+ cohort_query.return_value.execute_rolling_checks.side_effect = cohort_query_run+ grouped_query.return_value.execute_rolling_checks.side_effect = ClickHouseQueryTimeOut()+ evaluation = evaluate_logs_batch(self.team.id, self._slot(), self.cutoff)+ self._record(evaluation)++ failures = [o.consecutive_failures for o in evaluation.outcomes if o.configuration_id == slow.id]+ with team_scope(self.team.id):+ still_due = platform_testing.count_still_due([slow.id], at=self.cutoff)+ # A query cut short by an earlier one leaves its check due, so its slot comes back alone.+ assert (failures, still_due) == (([], 1) if expected_failures is None else ([expected_failures], 0))+def test_a_failure_the_batch_cannot_record_leaves_the_whole_batch_due(self) -> None:configuration = self._configuration(consecutive_failures=4)