: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): services tab respects filter_group when listing active rules (#59537)
Daniel Visca6bc627b28f77
diff --git a/products/logs/backend/services_query_runner.py b/products/logs/backend/services_query_runner.pyindex 7fa1f9ee1740..35217254b2fa 100644--- a/products/logs/backend/services_query_runner.py+++ b/products/logs/backend/services_query_runner.py@@ -1,3 +1,7 @@+from typing import Any++import re2+from posthog.schema import CachedLogsQueryResponse, LogsQueryfrom posthog.hogql import ast@@ -10,6 +14,132 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom products.logs.backend.logs_query_runner import LogsQueryResponse, LogsQueryRunnerMixinfrom products.logs.backend.models import LogsExclusionRule+# Three-valued logic for evaluating a rule's filter_group against a partial record+# at query time. We only know the row's `service_name`; everything else (severity,+# attributes) varies per log line. A leaf returning INDETERMINATE means we can't+# decide without seeing the full row, so the answer at the group level depends on+# how children combine: AND × INDETERMINATE → INDETERMINATE, OR × INDETERMINATE+# → INDETERMINATE (unless another child resolves it). The Services page treats+# INDETERMINATE as "rule might apply, show it" and only excludes when the result+# is provably FALSE — i.e. the rule cannot match any row from this service.+_FALSE, _INDETERMINATE, _TRUE = -1, 0, 1+_SERVICE_NAME_KEYS = {"service_name", "service.name"}+++def rule_could_apply_to_service(filter_group: Any, service_name: str) -> bool:+ """+ Return True iff the rule's `config.filter_group` could match some log line+ with this `service_name`. Returns True for an absent/empty filter_group+ (no scoping → applies to everything). Returns False only when the filter+ group provably cannot match — e.g. an `AND` containing+ `service.name exact "other"` against `service_name == "api"`.++ Operates on three-valued logic so non-service-name predicates (severity,+ arbitrary attributes) remain INDETERMINATE and conservatively keep the rule+ visible in the Services tab. The Node ingestion worker remains the source+ of truth for per-record drop decisions; this helper only filters the+ display list of "rules active on each service".+ """+ if filter_group is None or not isinstance(filter_group, dict):+ return True+ return _evaluate_node(filter_group, service_name) != _FALSE+++def _evaluate_node(node: Any, service_name: str) -> int:+ if not isinstance(node, dict):+ return _INDETERMINATE+ if _is_group(node):+ children = node.get("values") or []+ if not children:+ # Empty group: conservative — keep the rule visible (mirrors the+ # ingestion worker's "empty group → no match → don't drop" logic;+ # for display, "might apply" is the safer default).+ return _INDETERMINATE+ results = [_evaluate_node(child, service_name) for child in children]+ if str(node.get("type", "")).upper() == "OR":+ if _TRUE in results:+ return _TRUE+ if _INDETERMINATE in results:+ return _INDETERMINATE+ return _FALSE+ # AND (default for any unrecognised operator).+ if _FALSE in results:+ return _FALSE+ if _INDETERMINATE in results:+ return _INDETERMINATE+ return _TRUE+ # Property-filter leaf.+ key = str(node.get("key") or "").lower()+ if key not in _SERVICE_NAME_KEYS:+ # Any other key depends on per-row data we don't have at services-tab time.+ return _INDETERMINATE+ return _evaluate_service_leaf(node, service_name)+++def _is_group(node: dict) -> bool:+ type_ = str(node.get("type", "")).upper()+ return type_ in ("AND", "OR") and isinstance(node.get("values"), list)+++def _evaluate_service_leaf(leaf: dict, service_name: str) -> int:+ operator = str(leaf.get("operator") or "exact").lower()+ value = leaf.get("value")+ sn = service_name or ""++ if operator == "is_set":+ return _TRUE if sn else _FALSE+ if operator == "is_not_set":+ return _TRUE if not sn else _FALSE+ # Every remaining operator requires both an override and a filter value.++ if value is None:+ return _INDETERMINATE+ if not sn:+ # For negation operators, empty string doesn't match non-empty values+ if operator in ("is_not", "not_in", "not_icontains", "not_regex"):+ return _TRUE+ # For positive match operators, empty string can't match+ return _FALSE++ if operator in ("exact", "in"):+ return _TRUE if _matches_any(value, sn) else _FALSE+ if operator in ("is_not", "not_in"):+ return _FALSE if _matches_any(value, sn) else _TRUE+ if operator == "icontains":+ return _TRUE if str(value).lower() in sn.lower() else _FALSE+ if operator == "not_icontains":+ return _FALSE if str(value).lower() in sn.lower() else _TRUE+ if operator in ("regex", "not_regex"):+ # RE2 (linear-time, no catastrophic backtracking) — same engine the Node+ # ingestion worker uses via `tracked-re2`. A project member can pick the+ # regex operator on the drop-rule form, so a pathological pattern run+ # through Python's backtracking `re` engine here would be a ReDoS vector+ # on every Services-tab request.+ try:+ # `(?is)` inline flags = case-insensitive + DOTALL, matching the worker's+ # `re.IGNORECASE | re.DOTALL` and `compileLeafRegex`'s `is` flags.+ matched = re2.compile(f"(?is){str(value)}").search(sn) is not None+ except re2.error:+ # Invalid regex: for `regex` it can never match → FALSE.+ # For `not_regex` it trivially never matches → the "not" condition is+ # always satisfied → INDETERMINATE (shown on every service row), which+ # is the conservative choice and consistent with the PR's invariant that+ # only a provably-FALSE result hides the rule.+ return _FALSE if operator == "regex" else _INDETERMINATE+ if operator == "regex":+ return _TRUE if matched else _FALSE+ return _FALSE if matched else _TRUE+ # Numeric / semver / date operators don't apply to service_name strings —+ # unknown for our purposes, so be conservative and keep the rule visible.+ return _INDETERMINATE+++def _matches_any(value: Any, sn: str) -> bool:+ sn_lower = sn.lower()+ if isinstance(value, list):+ return any(str(v).lower() == sn_lower for v in value)+ return str(value).lower() == sn_lower+def _sampling_rule_summary(rule: LogsExclusionRule) -> str:if rule.rule_type == LogsExclusionRule.RuleType.PATH_DROP:@@ -69,8 +199,16 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerror_rate = error_count / log_count if log_count > 0 else 0.0active_rules = []for rule in enabled_rules:+ # Legacy scope_service column (still honored for rules that predate+ # the universal filter_group).if rule.scope_service and rule.scope_service != service_name:continue+ # Modern: scope via `config.filter_group`. Three-valued evaluation+ # against the partial record (we only know service_name at this+ # point); INDETERMINATE keeps the rule visible.+ filter_group = (rule.config or {}).get("filter_group")+ if not rule_could_apply_to_service(filter_group, service_name):+ continueactive_rules.append({"rule_id": str(rule.id),diff --git a/products/logs/backend/test/test_services_query_runner.py b/products/logs/backend/test/test_services_query_runner.pynew file mode 100644index 000000000000..56aaba84b0c4--- /dev/null+++ b/products/logs/backend/test/test_services_query_runner.py@@ -0,0 +1,157 @@+from typing import Any++import pytest++from parameterized import parameterized++from products.logs.backend.services_query_runner import rule_could_apply_to_service+++def _wrap(inner: dict) -> dict:+ """Mirror the outer-AND envelope the drop-rules UI emits."""+ return {"type": "AND", "values": [inner]}+++def _leaf(key: str, operator: str, value: Any) -> dict:+ return {"key": key, "operator": operator, "value": value, "type": "log_resource_attribute"}+++class TestRuleCouldApplyToService:+ """+ Unit tests for the three-valued evaluator that backs the Services tab's+ `active_rules` list. The Node ingestion worker remains the source of truth+ for actual per-record drop decisions; this helper only filters the display+ list so a rule scoped via `filter_group` to one service doesn't appear on+ every service's row.+ """++ def test_empty_or_missing_filter_group_applies_to_every_service(self) -> None:+ assert rule_could_apply_to_service(None, "api") is True+ assert rule_could_apply_to_service({}, "api") is True+ assert rule_could_apply_to_service({"type": "AND", "values": []}, "api") is True++ def test_exact_service_name_match(self) -> None:+ rule = _wrap({"type": "AND", "values": [_leaf("service.name", "exact", "api")]})+ assert rule_could_apply_to_service(rule, "api") is True+ assert rule_could_apply_to_service(rule, "other") is False++ def test_underscore_key_matches_dotted_key(self) -> None:+ # The Node consumer treats `service_name` and `service.name` as aliases;+ # services-page evaluation should too, so the UI's choice of key doesn't+ # silently change the display semantics.+ rule = _wrap({"type": "AND", "values": [_leaf("service_name", "exact", "api")]})+ assert rule_could_apply_to_service(rule, "api") is True+ assert rule_could_apply_to_service(rule, "other") is False++ @parameterized.expand(+ [+ ("icontains_match", "icontains", "ap", "api", True),+ ("icontains_no_match", "icontains", "redis", "api", False),+ ("not_icontains_match", "not_icontains", "redis", "api", True),+ ("not_icontains_excludes", "not_icontains", "ap", "api", False),+ ("regex_anchor_match", "regex", "^api$", "api", True),+ ("regex_prefix_match", "regex", "^api", "api-v2", True),+ ("regex_no_match", "regex", "^kafka", "api", False),+ ("not_regex_match", "not_regex", "^kafka", "api", True),+ ("in_list_match", "in", ["api", "kafka"], "api", True),+ ("in_list_no_match", "in", ["redis", "kafka"], "api", False),+ ("not_in_match", "not_in", ["redis", "kafka"], "api", True),+ ("not_in_excludes", "not_in", ["api", "kafka"], "api", False),+ ("is_set_with_value", "is_set", None, "api", True),+ ("is_set_blank", "is_set", None, "", False),+ ("is_not_set_with_value", "is_not_set", None, "api", False),+ ("is_not_set_blank", "is_not_set", None, "", True),+ ("invalid_regex_never_matches", "regex", "[unclosed", "api", False),+ ("invalid_not_regex_is_indeterminate", "not_regex", "[unclosed", "api", True),+ ]+ )+ def test_service_leaf_operators(+ self, _label: str, operator: str, value: Any, service_name: str, expected: bool+ ) -> None:+ rule = _wrap({"type": "AND", "values": [_leaf("service.name", operator, value)]})+ assert rule_could_apply_to_service(rule, service_name) is expected++ def test_non_service_leaf_is_indeterminate(self) -> None:+ # A rule scoped only by attributes can match some logs on any service —+ # we can't know without seeing the row. Keep the rule visible.+ rule = _wrap({"type": "AND", "values": [_leaf("severity_text", "exact", "error")]})+ assert rule_could_apply_to_service(rule, "api") is True+ assert rule_could_apply_to_service(rule, "anything") is True++ def test_and_excludes_when_service_predicate_fails(self) -> None:+ # `service.name = api AND severity = error` → for `other` the service+ # predicate is FALSE, so the AND is FALSE regardless of severity.+ rule = _wrap(+ {+ "type": "AND",+ "values": [+ _leaf("service.name", "exact", "api"),+ _leaf("severity_text", "exact", "error"),+ ],+ }+ )+ assert rule_could_apply_to_service(rule, "api") is True # might apply (error subset)+ assert rule_could_apply_to_service(rule, "other") is False # cannot apply++ def test_or_keeps_rule_visible_when_one_branch_indeterminate(self) -> None:+ # `service.name = api OR severity = error` → on `other`, service branch+ # is FALSE but severity branch is INDETERMINATE → INDETERMINATE → keep.+ rule = _wrap(+ {+ "type": "OR",+ "values": [+ _leaf("service.name", "exact", "api"),+ _leaf("severity_text", "exact", "error"),+ ],+ }+ )+ assert rule_could_apply_to_service(rule, "api") is True+ assert rule_could_apply_to_service(rule, "other") is True # error logs of `other` would match++ def test_or_all_service_predicates_resolve_negatively(self) -> None:+ # `service.name = api OR service.name = kafka` → on `redis`, both branches+ # FALSE, OR = FALSE, rule excluded.+ rule = _wrap(+ {+ "type": "OR",+ "values": [+ _leaf("service.name", "exact", "api"),+ _leaf("service.name", "exact", "kafka"),+ ],+ }+ )+ assert rule_could_apply_to_service(rule, "api") is True+ assert rule_could_apply_to_service(rule, "kafka") is True+ assert rule_could_apply_to_service(rule, "redis") is False++ def test_nested_groups(self) -> None:+ # `service.name = api AND (severity = error OR severity = fatal)` —+ # the inner OR is INDETERMINATE (severity unknown), AND with TRUE service+ # match yields INDETERMINATE → keep on `api`. On `other`, the outer AND+ # short-circuits to FALSE.+ rule = _wrap(+ {+ "type": "AND",+ "values": [+ _leaf("service.name", "exact", "api"),+ {+ "type": "OR",+ "values": [+ _leaf("severity_text", "exact", "error"),+ _leaf("severity_text", "exact", "fatal"),+ ],+ },+ ],+ }+ )+ assert rule_could_apply_to_service(rule, "api") is True+ assert rule_could_apply_to_service(rule, "other") is False++ def test_malformed_node_falls_back_to_indeterminate(self) -> None:+ # Conservative default: anything we can't parse keeps the rule visible.+ assert rule_could_apply_to_service({"type": "AND", "values": ["oops"]}, "api") is True+ assert rule_could_apply_to_service({"not_a_group": True}, "api") is True+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])