Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: Wire up SLOs in query service (#52895)

Vasco de Krijgerb2ae576eacb9
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index de1191dcec5d..790c5884a766 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -92,7 +92,7 @@ from posthog.clickhouse.client.limit import (
get_org_app_concurrency_limit,
)
from posthog.clickhouse.query_tagging import get_query_tag_value, tag_queries
-from posthog.errors import classify_query_error, clickhouse_error_type
+from posthog.errors import QueryErrorCategory, classify_query_error, clickhouse_error_type
from posthog.event_usage import AnalyticsProps, groups, report_user_or_team_action
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.insights.utils.breakdowns import has_multi_breakdown, has_single_breakdown
@@ -112,6 +112,8 @@ from posthog.models import Team, User
from posthog.models.team import WeekStartDay
from posthog.rbac.user_access_control import UserAccessControlError
from posthog.schema_helpers import to_dict
+from posthog.slo.context import JsonValue, SloSpec, slo_operation
+from posthog.slo.types import SloArea, SloOperation, SloOutcome
from posthog.utils import generate_cache_key, get_from_dict_or_attr, to_json
logger = structlog.get_logger(__name__)
@@ -220,6 +222,32 @@ def _is_force_blocking_eligible_for_shared(last_refresh: datetime | None) -> boo
return datetime.now(UTC) - last_refresh >= SHARED_FORCE_BLOCKING_MIN_AGE
+def _classify_error_for_slo(exc: Exception) -> tuple[QueryErrorCategory, SloOutcome]:
+ """Classify a query exception for SLO emission.
+
+ Returns the QueryErrorCategory plus the SloOutcome that should be reported:
+
+ - USER_ERROR / RATE_LIMITED / CANCELLED → SUCCESS. They reflect user input,
+ abuse, or normal interaction (cancel-on-navigate-away), not platform
+ reliability. The completed event still fires with the error_category tag
+ so dashboards can slice by it.
+ - QUERY_PERFORMANCE_ERROR and unclassified exceptions → FAILURE. Timeouts
+ and OOM dominate that category at scale; the user-input limits inside it
+ (EstimatedQueryExecutionTimeTooLong, QuerySizeExceeded) are a minority
+ worth living with for now.
+
+ UserAccessControlError is folded into USER_ERROR locally since
+ classify_query_error doesn't recognise it but a 403 is the user's input,
+ not a service failure.
+ """
+ if isinstance(exc, UserAccessControlError):
+ return QueryErrorCategory.USER_ERROR, SloOutcome.SUCCESS
+ category = classify_query_error(exc)
+ if category in (QueryErrorCategory.USER_ERROR, QueryErrorCategory.RATE_LIMITED, QueryErrorCategory.CANCELLED):
+ return category, SloOutcome.SUCCESS
+ return category, SloOutcome.FAILURE
+
+
def shared_insights_execution_mode(
execution_mode: ExecutionMode,
*,
@@ -1327,21 +1355,30 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
self.user = user
start_time = perf_counter()
cache_key = self.get_cache_key()
+ # Resolve per-call state before observability so SLO + analytics agree on the values.
+ self.query_id = query_id or self.query_id
+ self._cache_age_override = cache_age_seconds
with posthoganalytics.new_context():
+ query_type = getattr(self.query, "kind", "Other")
+ distinct_id = str(user.distinct_id) if user else str(self.team.uuid)
+
posthoganalytics.tag("cache_key", cache_key)
- posthoganalytics.tag("query_type", getattr(self.query, "kind", "Other"))
+ posthoganalytics.tag("query_type", query_type)
if insight_id:
posthoganalytics.tag("insight_id", str(insight_id))
if dashboard_id:
posthoganalytics.tag("dashboard_id", str(dashboard_id))
+
+ product_key: str | None = None
if tags := getattr(self.query, "tags", None):
if tags.name:
posthoganalytics.tag("query_name", tags.name)
tag_queries(name=tags.name)
if tags.productKey:
- posthoganalytics.tag("product_key", tags.productKey)
+ product_key = tags.productKey
+ posthoganalytics.tag("product_key", product_key)
tag_queries(product=tags.productKey)
if tags.scene:
posthoganalytics.tag("scene", tags.scene)
@@ -1350,117 +1387,158 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
tag_queries(execution_mode=execution_mode.value)
tag_queries(cache_key=cache_key)
- # Abort early if the user doesn't have access to the query runner
- # We'll proceed as usual if there's no user connected to this request
- # We're capturing the error for analytics purposes, but we reraise the same one
- if user is not None:
+ slo_properties: dict[str, JsonValue] = {
+ "query_type": query_type,
+ "execution_mode": execution_mode.value,
+ }
+ if insight_id is not None:
+ slo_properties["insight_id"] = insight_id
+ if dashboard_id is not None:
+ slo_properties["dashboard_id"] = dashboard_id
+ if product_key is not None:
+ slo_properties["product_key"] = product_key
+
+ with slo_operation(
+ spec=SloSpec(
+ distinct_id=distinct_id,
+ area=SloArea.ANALYTIC_PLATFORM,
+ operation=SloOperation.QUERY_SERVICE,
+ team_id=self.team.id,
+ resource_id=self.query_id,
+ sample_rate=settings.QUERY_SERVICE_SLO_SAMPLE_RATE,
+ ),
+ properties=slo_properties,
+ ) as slo:
try:
- self.validate_query_runner_access(user)
- except UserAccessControlError as error:
- posthoganalytics.capture(
- distinct_id=user.distinct_id,
- event="query access control error",
- properties={
- "query_runner": self.__class__.__name__,
- "query_id": self.query_id,
- "insight_id": insight_id,
- "dashboard_id": dashboard_id,
- "execution_mode": execution_mode.value,
- "query_type": getattr(self.query, "kind", "Other"),
- "resource": error.resource,
- "required_level": error.required_level,
- "resource_id": error.resource_id,
- "cache_key": cache_key,
- },
- )
-
- raise
+ # Abort early if the user doesn't have access to the query runner
+ # We'll proceed as usual if there's no user connected to this request
+ # We're capturing the error for analytics purposes, but we reraise the same one
+ if user is not None:
+ try:
+ self.validate_query_runner_access(user)
+ except UserAccessControlError as error:
+ posthoganalytics.capture(
+ distinct_id=user.distinct_id,
+ event="query access control error",
+ properties={
+ "query_runner": self.__class__.__name__,
+ "query_id": self.query_id,
+ "insight_id": insight_id,
+ "dashboard_id": dashboard_id,
+ "execution_mode": execution_mode.value,
+ "query_type": query_type,
+ "resource": error.resource,
+ "required_level": error.required_level,
+ "resource_id": error.resource_id,
+ "cache_key": cache_key,
+ },
+ )
- trigger: str | None = get_query_tag_value("trigger")
+ raise
- self.query_id = query_id or self.query_id
- self._cache_age_override = cache_age_seconds
- CachedResponse: type[CR] = self.cached_response_type
- cache_manager = get_query_cache_manager(
- team=self.team,
- cache_key=cache_key,
- insight_id=insight_id,
- dashboard_id=dashboard_id,
- )
+ trigger: str | None = get_query_tag_value("trigger")
- if execution_mode == ExecutionMode.CALCULATE_ASYNC_ALWAYS:
- # We should always kick off async calculation and disregard the cache
- return QueryStatusResponse(
- query_status=self.enqueue_async_calculation(
- refresh_requested=True,
- cache_manager=cache_manager,
- user=user,
- analytics_props=analytics_props,
+ CachedResponse: type[CR] = self.cached_response_type
+ cache_manager = get_query_cache_manager(
+ team=self.team,
+ cache_key=cache_key,
+ insight_id=insight_id,
+ dashboard_id=dashboard_id,
)
- )
- elif execution_mode != ExecutionMode.CALCULATE_BLOCKING_ALWAYS:
- # Let's look in the cache first
- results = self.handle_cache_and_async_logic(
- execution_mode=execution_mode,
- cache_manager=cache_manager,
- user=user,
- analytics_props=analytics_props,
- )
- if results:
- cache_tracking_props = {}
- if isinstance(results, CachedResponse):
- if (not trigger or not trigger.startswith("warming")) and results.query_metadata:
- log_event_usage_from_query_metadata(
- results.query_metadata,
- team_id=self.team.id,
- user_id=user.id if user else None,
+
+ if execution_mode == ExecutionMode.CALCULATE_ASYNC_ALWAYS:
+ # We should always kick off async calculation and disregard the cache.
+ # cache_hit is left unset on this path because the cache wasn't consulted.
+ slo.tag(execution_path="async_dispatched")
+ return QueryStatusResponse(
+ query_status=self.enqueue_async_calculation(
+ refresh_requested=True,
+ cache_manager=cache_manager,
+ user=user,
+ analytics_props=analytics_props,
+ )
+ )
+ elif execution_mode != ExecutionMode.CALCULATE_BLOCKING_ALWAYS:
+ # Let's look in the cache first
+ results = self.handle_cache_and_async_logic(
+ execution_mode=execution_mode,
+ cache_manager=cache_manager,
+ user=user,
+ analytics_props=analytics_props,
+ )
+ if results:
+ cache_tracking_props = {}
+ if isinstance(results, CachedResponse):
+ if (not trigger or not trigger.startswith("warming")) and results.query_metadata:
+ log_event_usage_from_query_metadata(
+ results.query_metadata,
+ team_id=self.team.id,
+ user_id=user.id if user else None,
+ )
+
+ last_refresh = last_refresh_from_cached_result(results)
+ cache_tracking_props = {
+ "is_cache_stale": self._is_stale(last_refresh=last_refresh),
+ "calculation_trigger": results.calculation_trigger,
+ "cache_age_seconds": round((datetime.now(UTC) - last_refresh).total_seconds(), 2)
+ if last_refresh
+ else None,
+ "last_refresh": last_refresh.isoformat() if last_refresh else None,
+ }
+ slo.tag(
+ execution_path="cache_hit",
+ cache_hit=True,
+ **cache_tracking_props,
+ )
+ else:
+ slo.tag(execution_path="cache_miss", cache_hit=False)
+
+ query_executed_props = {
+ "insight_id": insight_id,
+ "dashboard_id": dashboard_id,
+ "execution_mode": execution_mode.value,
+ "query_type": query_type,
+ "cache_key": cache_key,
+ "cache_hit": isinstance(results, CachedResponse),
+ "response_time_ms": round((perf_counter() - start_time) * 1000, 2),
+ **cache_tracking_props,
+ }
+ report_user_or_team_action(
+ "query executed",
+ query_executed_props,
+ user=user,
+ team=self.team,
+ organization=self.team.organization,
+ analytics_props=analytics_props,
)
- last_refresh = last_refresh_from_cached_result(results)
- cache_tracking_props = {
- "is_cache_stale": self._is_stale(last_refresh=last_refresh),
- "calculation_trigger": results.calculation_trigger,
- "cache_age_seconds": round((datetime.now(UTC) - last_refresh).total_seconds(), 2)
- if last_refresh
- else None,
- "last_refresh": last_refresh.isoformat() if last_refresh else None,
- }
-
- query_executed_props = {
- "insight_id": insight_id,
- "dashboard_id": dashboard_id,
- "execution_mode": execution_mode.value,
- "query_type": getattr(self.query, "kind", "Other"),
- "cache_key": cache_key,
- "cache_hit": True if isinstance(results, CachedResponse) else False,
- "response_time_ms": round((perf_counter() - start_time) * 1000, 2),
- **cache_tracking_props,
- }
- report_user_or_team_action(
- "query executed",
- query_executed_props,
+ return results
+
+ # cache_hit is left unset on this path: either the caller passed
+ # CALCULATE_BLOCKING_ALWAYS (cache skipped) or the cache returned nothing.
+ slo.tag(execution_path="blocking", calculation_trigger=trigger)
+ return self._execute_and_cache_blocking(
+ cache_key=cache_key,
+ cache_manager=cache_manager,
+ execution_mode=execution_mode,
+ insight_id=insight_id,
+ dashboard_id=dashboard_id,
+ trigger=trigger,
user=user,
- team=self.team,
- organization=self.team.organization,
+ start_time=start_time,
analytics_props=analytics_props,
)
-
- return results
-
- def execute_blocking():
- return self._execute_and_cache_blocking(
- cache_key=cache_key,
- cache_manager=cache_manager,
- execution_mode=execution_mode,
- insight_id=insight_id,
- dashboard_id=dashboard_id,
- trigger=trigger,
- user=user,
- start_time=start_time,
- analytics_props=analytics_props,
- )
-
- return execute_blocking()
+ except Exception as exc:
+ # Don't pass execution_path here: whichever branch tag was set before the raise
+ # (cache_hit / cache_miss / blocking / async_dispatched) stays intact so
+ # dashboards can attribute errors to the path they happened in. Errors that fire
+ # before any branch tag is set leave execution_path unset, which is honest.
+ category, outcome = _classify_error_for_slo(exc)
+ if outcome == SloOutcome.SUCCESS:
+ slo.succeed(error_category=category.value)
+ else:
+ slo.fail(error_category=category.value)
+ raise
def _execute_and_cache_blocking(
self,
diff --git a/posthog/hogql_queries/test/test_property_values_query_runner.py b/posthog/hogql_queries/test/test_property_values_query_runner.py
index 3fe9f9d0c1f9..0aa4e40d5b54 100644
--- a/posthog/hogql_queries/test/test_property_values_query_runner.py
+++ b/posthog/hogql_queries/test/test_property_values_query_runner.py
@@ -233,7 +233,7 @@ class TestPropertyValuesQueryRunner(ClickhouseTestMixin, APIBaseTest):
("poll", ExecutionMode.CACHE_ONLY_NEVER_CALCULATE, "force_cache"),
]
)
- def test_execution_mode_recorded_in_query_executed_event(self, _name, execution_mode, expected_value):
+ def test_execution_mode_recorded_in_slo_started_event(self, _name, execution_mode, expected_value):
_create_event(event="$pageview", distinct_id="u1", team=self.team, properties={"browser": "Chrome"})
flush_persons_and_events()
@@ -247,6 +247,8 @@ class TestPropertyValuesQueryRunner(ClickhouseTestMixin, APIBaseTest):
with patch("posthog.hogql_queries.query_runner.posthoganalytics.capture") as mock_capture:
runner.run(execution_mode)
- mock_capture.assert_called_once()
- captured_props = mock_capture.call_args.kwargs["properties"]
+ mock_capture.assert_called()
+ slo_started_calls = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "slo_operation_started"]
+ assert len(slo_started_calls) == 1
+ captured_props = slo_started_calls[0].kwargs["properties"]
assert captured_props["execution_mode"] == expected_value
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 7ed1cb0bb144..a2f910bb9c36 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -39,6 +39,7 @@ from posthog.schema import (
from posthog.hogql.constants import LimitContext
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
from posthog.hogql_queries.query_runner import (
ExecutionMode,
@@ -48,6 +49,8 @@ from posthog.hogql_queries.query_runner import (
)
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.team.team import Team, WeekStartDay
+from posthog.rbac.user_access_control import UserAccessControlError
+from posthog.slo.types import SloOutcome
from products.customer_analytics.backend.constants import DEFAULT_ACTIVITY_EVENT
from products.revenue_analytics.backend.hogql_queries.test.data.structure import REVENUE_ANALYTICS_CONFIG_SAMPLE_EVENT
@@ -523,6 +526,39 @@ class TestQueryRunner(BaseTest):
)
assert QUERY_EXECUTION_DURATION.labels(query_type="TestQuery")._sum.get() > before_duration_sum
+ @parameterized.expand(
+ [
+ (
+ "user_access_control_error",
+ lambda: UserAccessControlError("query", "viewer", None),
+ SloOutcome.SUCCESS,
+ "user_error",
+ ),
+ ("concurrency_limit_exceeded", ConcurrencyLimitExceeded, SloOutcome.SUCCESS, "rate_limited"),
+ ("unclassified_value_error", ValueError, SloOutcome.FAILURE, "error"),
+ ]
+ )
+ def test_run_classifies_slo_error_at_except_boundary(
+ self, _name, exception_factory, expected_outcome, expected_error_category
+ ):
+ TestQueryRunner = self.setup_test_query_runner_class()
+ raised_exc = exception_factory()
+
+ def calculate_raises(self):
+ raise raised_exc
+
+ TestQueryRunner.calculate = calculate_raises
+ runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)
+
+ with mock.patch("posthog.slo.context.emit_slo_completed") as mock_emit_slo_completed:
+ with pytest.raises(type(raised_exc)):
+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+
+ mock_emit_slo_completed.assert_called_once()
+ completed_kwargs = mock_emit_slo_completed.call_args.kwargs
+ assert completed_kwargs["properties"].outcome == expected_outcome
+ assert completed_kwargs["extra_properties"]["error_category"] == expected_error_category
+
def test_query_execution_metrics_not_recorded_on_cache_hit(self):
from posthog.hogql_queries.query_runner import QUERY_EXECUTION_DURATION, QUERY_EXECUTION_TOTAL
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index e8401006d385..67d6368886c3 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -625,6 +625,14 @@ KAFKA_PRODUCE_ACK_TIMEOUT_SECONDS = int(os.getenv("KAFKA_PRODUCE_ACK_TIMEOUT_SEC
# if `true` we highly increase the rate limit on /query endpoint and limit the number of concurrent queries
API_QUERIES_ENABLED = get_from_env("API_QUERIES_ENABLED", False, type_cast=str_to_bool)
+# Query service SLO sampling rate. Each QueryRunner.run() call emits two events
+# (slo_operation_started + slo_operation_completed); unsampled, that's many millions of
+# events per day. The chosen rate is stamped on each event as `properties.sample_rate`
+# so dashboards can weight by 1/sample_rate to reconstruct true counts. Tunable via env
+# var without redeploy. 1.0 = emit every operation, 0.01 = 1% sample.
+# Defaults to 1.0 under TEST so assertions on emitted SLO events are deterministic.
+QUERY_SERVICE_SLO_SAMPLE_RATE = get_from_env("QUERY_SERVICE_SLO_SAMPLE_RATE", 1.0 if TEST else 0.01, type_cast=float)
+
####
# Livestream
diff --git a/posthog/slo/context.py b/posthog/slo/context.py
index aeed675ee381..377edeefb0f1 100644
--- a/posthog/slo/context.py
+++ b/posthog/slo/context.py
@@ -19,6 +19,7 @@ Intended usage patterns:
tag_current_slo(cache_hit=True)
"""
+import random
import traceback
import dataclasses
from collections.abc import Callable, Iterator, Mapping
@@ -47,6 +48,11 @@ class SloSpec:
operation: SloOperation
team_id: int
resource_id: str | None = None
+ # 1.0 = emit every operation. <1.0 = randomly drop both started+completed in
+ # tandem (the coin flip happens once per operation so the event pair is preserved).
+ # The chosen rate is stamped on the events as `properties.sample_rate` so dashboards
+ # can weight each event by 1/sample_rate to reconstruct the true rate.
+ sample_rate: float = 1.0
@dataclasses.dataclass
@@ -117,46 +123,60 @@ def slo_operation(
handle = SloHandle()
base_properties = dict(properties or {})
base_properties["correlation_id"] = str(uuid4())
+ # One coin flip per operation: started+completed share fate, so a sampled
+ # operation never emits a half-pair.
+ should_emit = spec.sample_rate >= 1.0 or random.random() < spec.sample_rate
started_at = monotonic()
token = _current_slo.set(handle)
try:
- emit_slo_started(
- distinct_id=spec.distinct_id,
- properties=SloStartedProperties(
- area=spec.area,
- operation=spec.operation,
- team_id=spec.team_id,
- resource_id=spec.resource_id,
- ),
- extra_properties=base_properties or None,
- capture=capture,
- )
-
- outcome = SloOutcome.SUCCESS
- try:
- yield handle
- outcome = handle.outcome_override or SloOutcome.SUCCESS
- except Exception as exc:
- handle.completion_properties.setdefault("error_type", type(exc).__name__)
- handle.completion_properties.setdefault("error_message", str(exc))
- handle.completion_properties.setdefault("error_origin", _build_error_origin(exc))
- outcome = SloOutcome.FAILURE
- raise
- finally:
- completion_properties = {**base_properties, **handle.completion_properties} or None
- emit_slo_completed(
+ if should_emit:
+ emit_slo_started(
distinct_id=spec.distinct_id,
- properties=SloCompletedProperties(
+ properties=SloStartedProperties(
area=spec.area,
operation=spec.operation,
team_id=spec.team_id,
- outcome=outcome,
resource_id=spec.resource_id,
- duration_ms=(monotonic() - started_at) * 1000,
),
- extra_properties=completion_properties,
+ extra_properties=base_properties or None,
capture=capture,
+ sample_rate=spec.sample_rate,
)
+
+ outcome = SloOutcome.SUCCESS
+ try:
+ yield handle
+ # outcome_override wins both ways: succeed-then-no-raise stays SUCCESS,
+ # fail-then-no-raise reports FAILURE, succeed-then-raise reports SUCCESS,
+ # fail-then-raise reports FAILURE. Lets callers express "this was actually a
+ # success, we just need to propagate the exception" or vice versa.
+ outcome = handle.outcome_override or SloOutcome.SUCCESS
+ except Exception as exc:
+ # Skip the dict mutations + traceback walk on the sampled-out path —
+ # nothing downstream consumes completion_properties when we don't emit.
+ if should_emit:
+ handle.completion_properties.setdefault("error_type", type(exc).__name__)
+ handle.completion_properties.setdefault("error_message", str(exc))
+ handle.completion_properties.setdefault("error_origin", _build_error_origin(exc))
+ outcome = handle.outcome_override or SloOutcome.FAILURE
+ raise
+ finally:
+ if should_emit:
+ completion_properties = {**base_properties, **handle.completion_properties} or None
+ emit_slo_completed(
+ distinct_id=spec.distinct_id,
+ properties=SloCompletedProperties(
+ area=spec.area,
+ operation=spec.operation,
+ team_id=spec.team_id,
+ outcome=outcome,
+ resource_id=spec.resource_id,
+ duration_ms=(monotonic() - started_at) * 1000,
+ ),
+ extra_properties=completion_properties,
+ capture=capture,
+ sample_rate=spec.sample_rate,
+ )
finally:
_current_slo.reset(token)
diff --git a/posthog/slo/events.py b/posthog/slo/events.py
index acd9ce082c6e..b81332c8231e 100644
--- a/posthog/slo/events.py
+++ b/posthog/slo/events.py
@@ -10,17 +10,17 @@ from posthog.slo.types import SloCompletedProperties, SloStartedProperties
OPERATION_STARTED_COUNTER = Counter(
"slo_operation_started",
"A counter keeping track of when a slo-measured operation has started.",
- labelnames=["area", "operation"],
+ labelnames=["area", "operation", "sample_rate"],
)
OPERATION_COMPLETED_COUNTER = Counter(
"slo_operation_completed",
"A counter keeping track of when a slo-measured operation has completed.",
- labelnames=["area", "operation", "outcome"],
+ labelnames=["area", "operation", "outcome", "sample_rate"],
)
OPERATION_DURATION = Histogram(
"slo_operation_duration_seconds",
"Time spent for a slo-measured operation",
- labelnames=["area", "operation", "outcome"],
+ labelnames=["area", "operation", "outcome", "sample_rate"],
buckets=(
0.005,
0.01,
@@ -75,12 +75,16 @@ def emit_slo_started(
properties: SloStartedProperties,
extra_properties: dict | None = None,
capture: Callable | None = None,
+ sample_rate: float = 1.0,
) -> None:
try:
all_properties = properties.to_dict()
all_properties["deploy_sha"] = get_git_commit_short()
if extra_properties:
all_properties.update(extra_properties)
+ # Only stamp sample_rate when sampling is on; dashboards coalesce missing values to 1.0.
+ if sample_rate < 1.0:
+ all_properties["sample_rate"] = sample_rate
_capture = capture or posthoganalytics.capture
_capture(
@@ -91,6 +95,7 @@ def emit_slo_started(
OPERATION_STARTED_COUNTER.labels(
area=properties.area,
operation=properties.operation,
+ sample_rate=sample_rate,
).inc()
except Exception as exc:
_capture_emit_exception(
@@ -106,12 +111,16 @@ def emit_slo_completed(
properties: SloCompletedProperties,
extra_properties: dict | None = None,
capture: Callable | None = None,
+ sample_rate: float = 1.0,
) -> None:
try:
all_properties = properties.to_dict()
all_properties["deploy_sha"] = get_git_commit_short()
if extra_properties:
all_properties.update(extra_properties)
+ # Only stamp sample_rate when sampling is on; dashboards coalesce missing values to 1.0.
+ if sample_rate < 1.0:
+ all_properties["sample_rate"] = sample_rate
_capture = capture or posthoganalytics.capture
_capture(
@@ -123,6 +132,7 @@ def emit_slo_completed(
area=properties.area,
operation=properties.operation,
outcome=properties.outcome,
+ sample_rate=sample_rate,
).inc()
if properties.duration_ms is not None:
@@ -130,6 +140,7 @@ def emit_slo_completed(
area=properties.area,
operation=properties.operation,
outcome=properties.outcome,
+ sample_rate=sample_rate,
).observe(properties.duration_ms / 1000)
except Exception as exc:
_capture_emit_exception(
diff --git a/posthog/slo/test/test_slo_context.py b/posthog/slo/test/test_slo_context.py
index 0f7424fcdc9c..af4948699d5a 100644
--- a/posthog/slo/test/test_slo_context.py
+++ b/posthog/slo/test/test_slo_context.py
@@ -1,6 +1,9 @@
import asyncio
import inspect
import traceback
+import dataclasses
+from collections.abc import Callable
+from contextlib import nullcontext
from pathlib import Path
from typing import Any
@@ -171,54 +174,82 @@ def test_build_error_origin_prefers_deepest_repo_frame() -> None:
@pytest.mark.parametrize(
- "overrides,expected_outcome,expected_extra_properties",
+ "overrides, raise_via, expected_outcome, expected_extra_properties",
[
+ # No raise: fail() -> FAILURE
(
[("fail", {"reason": "partial_failure", "failed_checks": 1})],
+ None,
SloOutcome.FAILURE,
- {
- "calculation_interval": "weekly",
- "reason": "partial_failure",
- "failed_checks": 1,
- },
+ {"reason": "partial_failure", "failed_checks": 1},
),
+ # No raise: fail() then succeed() -> SUCCESS (last override wins)
(
[
("fail", {"reason": "partial_failure", "failed_checks": 1}),
("succeed", {"recovered": True}),
],
+ None,
SloOutcome.SUCCESS,
- {
- "calculation_interval": "weekly",
- "reason": "partial_failure",
- "failed_checks": 1,
- "recovered": True,
- },
+ {"reason": "partial_failure", "failed_checks": 1, "recovered": True},
+ ),
+ # Raise: succeed() then raise -> SUCCESS, override + branch tags preserved
+ (
+ [("succeed", {"execution_path": "error", "error_category": "user_error"})],
+ _raise_runtime_error,
+ SloOutcome.SUCCESS,
+ {"execution_path": "error", "error_category": "user_error"},
+ ),
+ # Raise: tag() then raise (no override) -> FAILURE, branch tag preserved
+ (
+ [("tag", {"execution_path": "blocking"})],
+ _raise_runtime_error,
+ SloOutcome.FAILURE,
+ {"execution_path": "blocking"},
),
],
)
@patch("posthog.slo.context.emit_slo_completed")
@patch("posthog.slo.context.emit_slo_started")
-def test_slo_operation_allows_no_exception_outcome_override(
+def test_slo_operation_outcome_override(
mock_emit_slo_started: MagicMock,
mock_emit_slo_completed: MagicMock,
overrides: list[tuple[str, dict[str, object]]],
+ raise_via: Callable[..., None] | None,
expected_outcome: SloOutcome,
expected_extra_properties: dict[str, object],
) -> None:
spec = _build_spec()
- with slo_operation(spec=spec, properties={"calculation_interval": "weekly"}) as slo:
- for method_name, props in overrides:
- getattr(slo, method_name)(**props)
+ with pytest.raises(RuntimeError, match="boom") if raise_via else nullcontext():
+ with slo_operation(spec=spec, properties={"calculation_interval": "weekly"}) as slo:
+ for method_name, props in overrides:
+ getattr(slo, method_name)(**props)
+ if raise_via:
+ raise_via()
mock_emit_slo_started.assert_called_once()
mock_emit_slo_completed.assert_called_once()
- started_kwargs = mock_emit_slo_started.call_args.kwargs
completed_kwargs = mock_emit_slo_completed.call_args.kwargs
assert completed_kwargs["properties"].outcome == expected_outcome
- correlation_id = started_kwargs["extra_properties"]["correlation_id"]
- assert completed_kwargs["extra_properties"] == {**expected_extra_properties, "correlation_id": correlation_id}
+
+ # The context manager auto-populates these on the raise path.
+ auto_error_props = (
+ {
+ "error_type": "RuntimeError",
+ "error_message": "boom",
+ "error_origin": _expected_origin_for(raise_via),
+ }
+ if raise_via
+ else {}
+ )
+ correlation_id = completed_kwargs["extra_properties"]["correlation_id"]
+ assert completed_kwargs["extra_properties"] == {
+ "calculation_interval": "weekly",
+ **expected_extra_properties,
+ **auto_error_props,
+ "correlation_id": correlation_id,
+ }
@patch("posthog.slo.context.emit_slo_completed")
@@ -267,3 +298,64 @@ async def test_slo_operation_contextvar_survives_await(
completed_extra = mock_emit_slo_completed.call_args.kwargs["extra_properties"]
correlation_id = started_extra["correlation_id"]
assert completed_extra == {"async_stage": "after_await", "correlation_id": correlation_id}
+
+
+ "sample_rate, random_value, expect_emit",
+ [
+ (1.0, None, True),
+ (0.0, 0.99, False),
+ (0.01, 0.005, True),
+ (0.01, 0.5, False),
+ (0.5, 0.49, True),
+ (0.5, 0.51, False),
+ ],
+)
+@patch("posthog.slo.context.emit_slo_completed")
+@patch("posthog.slo.context.emit_slo_started")
+@patch("posthog.slo.context.random.random")
+def test_slo_operation_respects_sample_rate(
+ mock_random: MagicMock,
+ mock_emit_slo_started: MagicMock,
+ mock_emit_slo_completed: MagicMock,
+ sample_rate: float,
+ random_value: float | None,
+ expect_emit: bool,
+) -> None:
+ if random_value is not None:
+ mock_random.return_value = random_value
+
+ spec = dataclasses.replace(_build_spec(), sample_rate=sample_rate)
+
+ with slo_operation(spec=spec):
+ pass
+
+ if sample_rate >= 1.0:
+ mock_random.assert_not_called()
+
+ if expect_emit:
+ mock_emit_slo_started.assert_called_once()
+ mock_emit_slo_completed.assert_called_once()
+ assert mock_emit_slo_started.call_args.kwargs["sample_rate"] == sample_rate
+ assert mock_emit_slo_completed.call_args.kwargs["sample_rate"] == sample_rate
+ else:
+ mock_emit_slo_started.assert_not_called()
+ mock_emit_slo_completed.assert_not_called()
+
+
+@patch("posthog.slo.context.emit_slo_completed")
+@patch("posthog.slo.context.emit_slo_started")
+@patch("posthog.slo.context.random.random", return_value=0.99)
+def test_slo_operation_sampled_out_still_propagates_exception(
+ _mock_random: MagicMock,
+ mock_emit_slo_started: MagicMock,
+ mock_emit_slo_completed: MagicMock,
+) -> None:
+ spec = dataclasses.replace(_build_spec(), sample_rate=0.01)
+
+ with pytest.raises(RuntimeError, match="boom"):
+ with slo_operation(spec=spec):
+ raise RuntimeError("boom")
+
+ mock_emit_slo_started.assert_not_called()
+ mock_emit_slo_completed.assert_not_called()
diff --git a/posthog/slo/types.py b/posthog/slo/types.py
index fd95caa9a0af..7cddf265b094 100644
--- a/posthog/slo/types.py
+++ b/posthog/slo/types.py
@@ -13,6 +13,7 @@ class SloOperation(StrEnum):
SUBSCRIPTION_CREATE = "subscription_create"
SUBSCRIPTION_DELETE = "subscription_delete"
ALERT_CHECK = "alert_check"
+ QUERY_SERVICE = "query_service"
class SloOutcome(StrEnum):
diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.py
index b583592f4e8c..6704d4fed85c 100644
--- a/posthog/temporal/tests/test_subscriptions_workflows.py
+++ b/posthog/temporal/tests/test_subscriptions_workflows.py
@@ -312,12 +312,18 @@ async def test_handle_subscription_value_change_email(
# SLO events emitted exactly once (child only, not parent)
started_calls = [
- c for c in mock_analytics.capture.call_args_list if c.kwargs.get("event") == "slo_operation_started"
+ c
+ for c in mock_analytics.capture.call_args_list
+ if c.kwargs.get("event") == "slo_operation_started"
+ and c.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY
]
assert len(started_calls) == 1
completed_calls = [
- c for c in mock_analytics.capture.call_args_list if c.kwargs.get("event") == "slo_operation_completed"
+ c
+ for c in mock_analytics.capture.call_args_list
+ if c.kwargs.get("event") == "slo_operation_completed"
+ and c.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY
]
assert len(completed_calls) == 1
assert completed_calls[0].kwargs["properties"]["outcome"] == SloOutcome.SUCCESS
@@ -863,8 +869,18 @@ async def test_create_export_assets_creates_exported_assets(
assert asset.insight_id == insight.id
assert asset.export_format == "image/png"
- # SLO started is emitted by the interceptor, not this activity
- mock_analytics.capture.assert_not_called()
+ # SLO started is emitted by the interceptor, not this activity. Internal QueryRunner.run()
+ # calls during snapshot build emit query_service SLO events — those are unrelated.
+ subscription_slo_calls = [
+ c
+ for c in mock_analytics.capture.call_args_list
+ if c.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY
+ ]
+ assert subscription_slo_calls == []
+ assert any(
+ c.kwargs.get("properties", {}).get("operation") == SloOperation.QUERY_SERVICE
+ for c in mock_analytics.capture.call_args_list
+ )
@patch("posthog.temporal.subscriptions.activities.build_insight_delivery_snapshot")
@@ -1166,8 +1182,18 @@ async def test_create_export_assets_dashboard_with_multiple_insights(
)
assert len(result.exported_asset_ids) == 3
- # SLO started is emitted by the interceptor, not this activity
- mock_analytics.capture.assert_not_called()
+ # SLO started is emitted by the interceptor, not this activity. Internal QueryRunner.run()
+ # calls during snapshot build emit query_service SLO events — those are unrelated.
+ subscription_slo_calls = [
+ c
+ for c in mock_analytics.capture.call_args_list
+ if c.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY
+ ]
+ assert subscription_slo_calls == []
+ assert any(
+ c.kwargs.get("properties", {}).get("operation") == SloOperation.QUERY_SERVICE
+ for c in mock_analytics.capture.call_args_list
+ )
@freeze_time("2022-02-02T08:55:00.000Z")
@@ -1333,12 +1359,18 @@ async def test_deliver_subscription_workflow_end_to_end(
# Both started and completed events flow through posthog.slo.events
started_calls = [
- c for c in mock_slo_analytics.capture.call_args_list if c.kwargs.get("event") == "slo_operation_started"
+ c
+ for c in mock_slo_analytics.capture.call_args_list
+ if c.kwargs.get("event") == "slo_operation_started"
+ and c.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY
]
assert len(started_calls) == 1
completed_calls = [
- c for c in mock_slo_analytics.capture.call_args_list if c.kwargs.get("event") == "slo_operation_completed"
+ c
+ for c in mock_slo_analytics.capture.call_args_list
+ if c.kwargs.get("event") == "slo_operation_completed"
+ and c.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY
]
assert len(completed_calls) == 1
assert completed_calls[0].kwargs["properties"]["outcome"] == SloOutcome.SUCCESS
@@ -1613,7 +1645,10 @@ async def test_export_error_slo_outcome(
assert state["calls"] == expected_calls
completed_calls = [
- c for c in mock_slo_analytics.capture.call_args_list if c.kwargs.get("event") == "slo_operation_completed"
+ c
+ for c in mock_slo_analytics.capture.call_args_list
+ if c.kwargs.get("event") == "slo_operation_completed"
+ and c.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY
]
assert len(completed_calls) == 1
assert completed_calls[0].kwargs["properties"]["outcome"] == expected_outcome
@@ -1712,7 +1747,10 @@ async def test_partial_export_failure_delivers_successful_assets(
assert len(delivered_assets) == 3
completed_calls = [
- c for c in mock_slo_analytics.capture.call_args_list if c.kwargs.get("event") == "slo_operation_completed"
+ c
+ for c in mock_slo_analytics.capture.call_args_list
+ if c.kwargs.get("event") == "slo_operation_completed"
+ and c.kwargs.get("properties", {}).get("operation") == SloOperation.SUBSCRIPTION_DELIVERY
]
assert len(completed_calls) == 1
props = completed_calls[0].kwargs["properties"]
diff --git a/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf b/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf
index c49b0b0eb84c..d3c256f745c7 100644
--- a/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf
+++ b/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf
@@ -30,6 +30,17 @@ locals {
slo = 99.95 # error budget = 0.05%
regions = ["US", "EU"]
}
+ query_service = {
+ name = "Query service"
+ slo = 99.95 # error budget = 0.05%
+ regions = ["US", "EU"]
+ # Sampled at 1% to keep ingestion volume sane (unsampled would be many millions
+ # of events per day). Match this to QUERY_SERVICE_SLO_SAMPLE_RATE in
+ # posthog/settings/web.py. Documentation only; the dashboard SQL reads
+ # `properties.sample_rate` from each event and weights by 1/sample_rate, so a
+ # mismatch here doesn't break math.
+ sample_rate = 0.01
+ }
}
# ---------------------------------------------------------------------------
@@ -64,38 +75,54 @@ locals {
-- Single scan: GROUP BY (cid, hour) extracts correlation_id once per row.
-- Correlated events (cid != '') are paired by cid then attributed to start hour.
-- Uncorrelated events (cid = '') use bucket-based counting with clamp.
- WITH per_cid_hour AS (
+ -- Sampled operations (properties.sample_rate < 1.0) are reweighted by 1/sample_rate
+ -- so the dashboard reflects true volume; events without the property coalesce to 1.0.
+ WITH weighted_events AS (
SELECT
- coalesce(nullIf(properties.correlation_id, ''), '') AS cid,
- toStartOfHour(timestamp) AS event_hour,
- countIf(event = 'slo_operation_started') AS starts,
- countIf(event = 'slo_operation_completed' AND properties.outcome = 'success') AS successes,
- min(if(event = 'slo_operation_started', timestamp, NULL)) AS first_start
+ event,
+ timestamp,
+ coalesce(nullIf(properties.correlation_id, ''), '') AS correlation_id,
+ properties.outcome AS outcome,
+ coalesce(toFloat(properties.sample_rate), 1.0) AS sample_rate,
+ 1.0 / coalesce(toFloat(properties.sample_rate), 1.0) AS weight
FROM events
WHERE event IN ('slo_operation_started', 'slo_operation_completed')
AND properties.operation = '{{OPERATION}}'
AND properties.region = '{{REGION}}'
AND timestamp >= now() - INTERVAL 35 DAY
+ ),
+ per_cid_hour AS (
+ SELECT
+ correlation_id AS cid,
+ toStartOfHour(timestamp) AS event_hour,
+ sumIf(weight, event = 'slo_operation_started') AS starts,
+ sumIf(weight, event = 'slo_operation_completed' AND outcome = 'success') AS successes,
+ -- Per-cid sample_rate for the correlated-path collapse. All events in a pair
+ -- share the same rate (coin flip is per-operation) so max() is unambiguous.
+ max(sample_rate) AS cid_sample_rate,
+ min(if(event = 'slo_operation_started', timestamp, NULL)) AS first_start
+ FROM weighted_events
GROUP BY cid, event_hour
),
hourly AS (
SELECT hour, sum(total) AS total, sum(failures) AS failures
FROM (
- -- Uncorrelated: each row is one hour bucket, clamp failures to 0
+ -- Uncorrelated: starts/successes already weighted; 1 row per hour.
SELECT
event_hour AS hour,
starts AS total,
- greatest(starts - successes, 0) AS failures
+ greatest(starts - successes, 0.0) AS failures
FROM per_cid_hour
WHERE cid = ''
UNION ALL
- -- Correlated: collapse across hours per cid, attribute to start hour
+ -- Correlated: collapse across hours per cid, attribute to start hour.
+ -- Each cid = one operation, weighted by 1/sample_rate of its events.
SELECT
toStartOfHour(min(first_start)) AS hour,
- 1 AS total,
- if(max(successes) > 0, 0, 1) AS failures
+ 1.0 / max(cid_sample_rate) AS total,
+ if(max(successes) > 0, 0.0, 1.0 / max(cid_sample_rate)) AS failures
FROM per_cid_hour
WHERE cid != ''
GROUP BY cid
@@ -305,20 +332,31 @@ resource "posthog_insight" "slo_success_rate" {
kind = "HogQLQuery"
query = <<-SQL
-- No correlation_id needed: daily buckets have negligible cross-bucket issues.
- WITH daily AS (
+ -- Sampled operations are reweighted by 1/sample_rate so the rate reflects
+ -- true volume; events without the property coalesce to 1.0 (no sampling).
+ WITH weighted_events AS (
SELECT
- toDate(timestamp) AS date,
+ event,
+ timestamp,
properties.operation AS operation,
- countIf(event = 'slo_operation_started') AS total,
- greatest(
- countIf(event = 'slo_operation_started')
- - countIf(event = 'slo_operation_completed' AND properties.outcome = 'success'),
- 0
- ) AS failures
+ properties.outcome AS outcome,
+ 1.0 / coalesce(toFloat(properties.sample_rate), 1.0) AS weight
FROM events
WHERE event IN ('slo_operation_started', 'slo_operation_completed')
AND properties.operation IN (${local.slo_operation_list})
AND timestamp >= now() - INTERVAL 56 DAY
+ ),
+ daily AS (
+ SELECT
+ toDate(timestamp) AS date,
+ operation,
+ sumIf(weight, event = 'slo_operation_started') AS total,
+ greatest(
+ sumIf(weight, event = 'slo_operation_started')
+ - sumIf(weight, event = 'slo_operation_completed' AND outcome = 'success'),
+ 0.0
+ ) AS failures
+ FROM weighted_events
GROUP BY date, operation
),
date_range AS (
@@ -391,31 +429,42 @@ resource "posthog_insight" "slo_volume" {
kind = "HogQLQuery"
query = <<-SQL
-- No correlation_id needed: single 28-day bucket has no cross-bucket issue.
+ -- Counts reconstructed to true volume by weighting each event by 1/sample_rate;
+ -- events without the property coalesce to 1.0 (no sampling).
+ WITH weighted_events AS (
+ SELECT
+ event,
+ properties.operation AS operation,
+ properties.region AS raw_region,
+ properties.outcome AS outcome,
+ 1.0 / coalesce(toFloat(properties.sample_rate), 1.0) AS weight
+ FROM events
+ WHERE event IN ('slo_operation_started', 'slo_operation_completed')
+ AND timestamp >= now() - INTERVAL 28 DAY
+ )
SELECT
- properties.operation AS operation,
+ operation,
if(
- count(properties.region) OVER (PARTITION BY properties.operation) = 1,
+ count(raw_region) OVER (PARTITION BY operation) = 1,
'all*',
- properties.region
+ raw_region
) AS region,
- countIf(event = 'slo_operation_started') AS started,
- countIf(event = 'slo_operation_completed' AND properties.outcome = 'success') AS successes,
- countIf(event = 'slo_operation_completed' AND properties.outcome = 'failure') AS failures,
+ sumIf(weight, event = 'slo_operation_started') AS started,
+ sumIf(weight, event = 'slo_operation_completed' AND outcome = 'success') AS successes,
+ sumIf(weight, event = 'slo_operation_completed' AND outcome = 'failure') AS failures,
greatest(
- countIf(event = 'slo_operation_started')
- - countIf(event = 'slo_operation_completed'),
- 0
+ sumIf(weight, event = 'slo_operation_started')
+ - sumIf(weight, event = 'slo_operation_completed'),
+ 0.0
) AS never_completed,
if(
- countIf(event = 'slo_operation_started') > 0,
- round(countIf(event = 'slo_operation_completed' AND properties.outcome = 'success')
- / countIf(event = 'slo_operation_started') * 100, 2),
+ sumIf(weight, event = 'slo_operation_started') > 0,
+ round(sumIf(weight, event = 'slo_operation_completed' AND outcome = 'success')
+ / sumIf(weight, event = 'slo_operation_started') * 100, 2),
NULL
) AS success_rate
- FROM events
- WHERE event IN ('slo_operation_started', 'slo_operation_completed')
- AND timestamp >= now() - INTERVAL 28 DAY
- GROUP BY operation, properties.region
+ FROM weighted_events
+ GROUP BY operation, raw_region
ORDER BY operation, region
SQL
}