: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(actions): compile CSS selectors that match zero events (#80653)
posthog[bot]eb917c997e75
diff --git a/nodejs/src/cdp/legacy-webhooks/action-matcher.test.ts b/nodejs/src/cdp/legacy-webhooks/action-matcher.test.tsindex 589c97776d9c..81546bccf2b7 100644--- a/nodejs/src/cdp/legacy-webhooks/action-matcher.test.ts+++ b/nodejs/src/cdp/legacy-webhooks/action-matcher.test.ts@@ -1104,6 +1104,7 @@ describe('ActionMatcher', () => {expect(checkElementsAgainstSelector(elements, ".top [data-attr='xyz']")).toBeTruthy()expect(checkElementsAgainstSelector(elements, "[data-attr='foo']")).toBeFalsy()+ expect(checkElementsAgainstSelector(elements, "[data-attr='foo'][data-attr='xyz']")).toBeFalsy()expect(checkElementsAgainstSelector(elements, "main[data-attr='xyz']")).toBeFalsy()expect(checkElementsAgainstSelector(elements, "div[data-attr='xyz']")).toBeFalsy()expect(checkElementsAgainstSelector(elements, "div[data-attr='xyz']")).toBeFalsy()@@ -1193,6 +1194,7 @@ describe('ActionMatcher', () => {expect(checkElementsAgainstSelector(elements, 'section > span:nth-child(2):nth-of-type(1)')).toBeTruthy()expect(checkElementsAgainstSelector(elements, 'section > span:nth-child(1):nth-of-type(1)')).toBeFalsy()expect(checkElementsAgainstSelector(elements, 'section > span:nth-child(2):nth-of-type(3)')).toBeFalsy()+ expect(checkElementsAgainstSelector(elements, 'section > span:nth-child(1):nth-child(2)')).toBeFalsy()})})})diff --git a/nodejs/src/cdp/legacy-webhooks/action-matcher.ts b/nodejs/src/cdp/legacy-webhooks/action-matcher.tsindex f046ea0d14d6..5cade0c9a738 100644--- a/nodejs/src/cdp/legacy-webhooks/action-matcher.ts+++ b/nodejs/src/cdp/legacy-webhooks/action-matcher.ts@@ -468,6 +468,9 @@ export class ActionMatcher {part.uniqueOrder = parts.filter((p) => equal(p.requirements, part.requirements)).lengthparts.push(part)}+ if (parts.some((part) => part.unsatisfiable)) {+ return false+ }// Matching elements against selector parts// Initial base element is the imaginary parent of the outermost known elementlet baseElementIndex = elements.length@@ -554,15 +557,19 @@ class SelectorPart {directDescendant: booleanuniqueOrder: numberrequirements: Partial<Element>+ unsatisfiable: booleanconstructor(tag: string, directDescendant: boolean, escapeSlashes: boolean) {- const ATTRIBUTE_SELECTOR_REGEX = /\[(.*)=[\'|\"](.*)[\'|\"]\]/+ // Non-greedy and quote-balanced, so two attribute selectors on one element are+ // read as two attributes instead of collapsing into one nonsense key.+ const ATTRIBUTE_SELECTOR_REGEX = /\[\s*([^\]\s=]+)\s*=\s*(['"])(.*?)\2\s*\]/const COLON_SELECTOR_REGEX = /:([A-Za-z-]+)\((\d+)\)/const FINAL_TAG_REGEX = /^([A-Za-z0-9]+)/this.directDescendant = directDescendantthis.uniqueOrder = 0this.requirements = {}+ this.unsatisfiable = falselet attributeSelector = tag.match(ATTRIBUTE_SELECTOR_REGEX)while (attributeSelector) {@@ -570,24 +577,33 @@ class SelectorPart {tag.slice(0, attributeSelector.index) +tag.slice(attributeSelector.index! + attributeSelector[0].length)const attribute = attributeSelector[1].toLowerCase()+ const attributeValue = attributeSelector[3]switch (attribute) {case 'id':- this.requirements.attr_id = attributeSelector[2].toLowerCase()+ this.noteConflict(this.requirements.attr_id, attributeValue.toLowerCase())+ this.requirements.attr_id = attributeValue.toLowerCase()breakcase 'href':- this.requirements.href = attributeSelector[2]+ this.noteConflict(this.requirements.href, attributeValue)+ this.requirements.href = attributeValuebreakdefault:if (!this.requirements.attributes) {this.requirements.attributes = {}}- this.requirements.attributes[attribute] = attributeSelector[2]+ this.noteConflict(this.requirements.attributes[attribute], attributeValue)+ this.requirements.attributes[attribute] = attributeValuebreak}attributeSelector = tag.match(ATTRIBUTE_SELECTOR_REGEX)}- let colonSelector = tag.match(COLON_SELECTOR_REGEX)- while (colonSelector) {+ // The re-match has to sit in the update expression: the `continue`s below would+ // otherwise skip it, leaving colonSelector truthy while tag shrinks to "".+ for (+ let colonSelector = tag.match(COLON_SELECTOR_REGEX);+ colonSelector;+ colonSelector = tag.match(COLON_SELECTOR_REGEX)+ ) {tag = tag.slice(0, colonSelector.index) + tag.slice(colonSelector.index! + colonSelector[0].length)const parsedArgument = parseInt(colonSelector[2])if (!parsedArgument) {@@ -595,15 +611,16 @@ class SelectorPart {}switch (colonSelector[1]) {case 'nth-child':+ this.noteConflict(this.requirements.nth_child, parsedArgument)this.requirements.nth_child = parsedArgumentbreakcase 'nth-of-type':+ this.noteConflict(this.requirements.nth_of_type, parsedArgument)this.requirements.nth_of_type = parsedArgumentbreakdefault:continue // unsupported selector}- colonSelector = tag.match(COLON_SELECTOR_REGEX)}if (tag.includes('.')) {const classParts = tag.split('.')@@ -620,6 +637,13 @@ class SelectorPart {}}+ /** No element carries two values for one key, so [type="button"][type="submit"] matches nothing. */+ private noteConflict(current: string | number | undefined, next: string | number): void {+ if (current !== undefined && current !== next) {+ this.unsatisfiable = true+ }+ }+/** Separate all double slashes "\\" (replace them with "\") and remove all single slashes between them. */private unescapeClassName(className: string): string {return classNamediff --git a/posthog/hogql/property.py b/posthog/hogql/property.pyindex 16ddc97984f1..b24b7c397238 100644--- a/posthog/hogql/property.py+++ b/posthog/hogql/property.py@@ -1999,6 +1999,10 @@ def element_property_key_to_breakdown_expr(key: str) -> ast.Expr:def selector_to_expr(selector_string: str):selector = Selector(selector_string, escape_slashes=False)+ if selector.is_unsatisfiable():+ # The id-only shortcut below skips the regex, so [id="a"][id="b"] would match every+ # element with id "b". A selector that no element can satisfy matches no event.+ return ast.Constant(value=False)exprs = []regex = build_selector_regex(selector)exprs.append(parse_expr("elements_chain =~ {regex}", {"regex": ast.Constant(value=regex)}))diff --git a/posthog/hogql/test/test_action_to_expr.py b/posthog/hogql/test/test_action_to_expr.pyindex c46579cf819a..3afaaba063e4 100644--- a/posthog/hogql/test/test_action_to_expr.py+++ b/posthog/hogql/test/test_action_to_expr.py@@ -42,7 +42,7 @@ class TestActionToExpr(BaseTest):"elements_chain =~ {regex}",{"regex": ast.Constant(- value="(^|;)a.*?\\.active\\..*?nav\\-link[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))"+ value='(^|;)a(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.active\\.(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?nav\\-link(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))')},),diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.pyindex f46868fe5809..f0efd2491889 100644--- a/posthog/hogql/test/test_property.py+++ b/posthog/hogql/test/test_property.py@@ -959,12 +959,16 @@ class TestProperty(BaseTest):def test_selector_to_expr(self):self.assertEqual(self._selector_to_expr("div"),- clear_locations(elements_chain_match("(^|;)div[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))")),+ clear_locations(+ elements_chain_match('(^|;)div(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))')+ ),)self.assertEqual(self._selector_to_expr("div > div"),clear_locations(- elements_chain_match("(^|;)div[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))div[^;]*?($|;|:([^;^\\s]*(;|$|\\s))).*")+ elements_chain_match(+ '(^|;)div(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))div(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s))).*'+ )),)self.assertEqual(@@ -972,20 +976,32 @@ class TestProperty(BaseTest):clear_locations(parse_expr("{regex} and arrayCount(x -> x IN ['a'], elements_chain_elements) > 0",- {"regex": elements_chain_match('(^|;)a.*?href="boo".*?[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))')},+ {+ "regex": elements_chain_match(+ '(^|;)a(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?href="boo"(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'+ )+ },)),)self.assertEqual(self._selector_to_expr(".class"),- clear_locations(elements_chain_match("(^|;).*?\\.class[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))")),+ clear_locations(+ elements_chain_match(+ '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.class(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'+ )+ ),)self.assertEqual(self._selector_to_expr("a#withid"),clear_locations(parse_expr("""{regex} and indexOf(elements_chain_ids, 'withid') > 0 and arrayCount(x -> x IN ['a'], elements_chain_elements) > 0""",- {"regex": elements_chain_match('(^|;)a.*?attr_id="withid".*?[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))')},+ {+ "regex": elements_chain_match(+ '(^|;)a(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?attr_id="withid"(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'+ )+ },)),)@@ -997,7 +1013,7 @@ class TestProperty(BaseTest):"""{regex} and indexOf(elements_chain_ids, 'with-dashed-id') > 0 and arrayCount(x -> x IN ['a'], elements_chain_elements) > 0""",{"regex": elements_chain_match(- '(^|;)a.*?attr_id="with\\-dashed\\-id".*?[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'+ '(^|;)a(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?attr_id="with\\-dashed\\-id"(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))')},)@@ -1012,6 +1028,7 @@ class TestProperty(BaseTest):self._selector_to_expr("#with-dashed-id"),self._selector_to_expr("[id='with-dashed-id']"),)+ self.assertEqual(self._selector_to_expr("#a[id='b']"), ast.Constant(value=False))self.assertEqual(self._selector_to_expr("#with\\slashed\\id"),clear_locations(@@ -1027,7 +1044,9 @@ class TestProperty(BaseTest):self.assertEqual(self._selector_to_expr(".sm:[max-width:640px]"),clear_locations(- elements_chain_match("(^|;).*?\\.sm:\\[max\\-width:640px\\][^;]*?($|;|:([^;^\\s]*(;|$|\\s)))")+ elements_chain_match(+ '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.sm:\\[max\\-width:640px\\](?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'+ )),)@@ -1035,7 +1054,9 @@ class TestProperty(BaseTest):self.assertEqual(self._selector_to_expr(".w-[calc(100%-2rem)]"),clear_locations(- elements_chain_match("(^|;).*?\\.w\\-\\[calc\\(100%\\-2rem\\)\\][^;]*?($|;|:([^;^\\s]*(;|$|\\s)))")+ elements_chain_match(+ '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.w\\-\\[calc\\(100%\\-2rem\\)\\](?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'+ )),)@@ -1044,7 +1065,7 @@ class TestProperty(BaseTest):self._selector_to_expr(".shadow-[0_4px_6px_rgba(0,0,0,0.1)]"),clear_locations(elements_chain_match(- "(^|;).*?\\.shadow\\-\\[0_4px_6px_rgba\\(0,0,0,0\\.1\\)\\][^;]*?($|;|:([^;^\\s]*(;|$|\\s)))"+ '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.shadow\\-\\[0_4px_6px_rgba\\(0,0,0,0\\.1\\)\\](?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))')),)@@ -1052,7 +1073,11 @@ class TestProperty(BaseTest):# Test Tailwind fraction/opacity class with a slashself.assertEqual(self._selector_to_expr(".bg-yellow/50"),- clear_locations(elements_chain_match("(^|;).*?\\.bg\\-yellow/50[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))")),+ clear_locations(+ elements_chain_match(+ '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.bg\\-yellow/50(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'+ )+ ),)def test_cohort_filter_static(self):diff --git a/posthog/models/event/event.py b/posthog/models/event/event.pyindex 784503319850..cf0d58cae23a 100644--- a/posthog/models/event/event.py+++ b/posthog/models/event/event.py@@ -11,8 +11,46 @@ from dateutil.relativedelta import relativedeltafrom posthog.models.team import Team-SELECTOR_ATTRIBUTE_REGEX = r"([a-zA-Z]*)\[(.*)=[\'|\"](.*)[\'|\"]\]"-ATTRIBUTE_PAIR_REGEX = r"\[\s*([^\]\s=\"']+)\s*=\s*(['\"])((?:\\.|(?!\\|\2).)*)\2\s*\]"+SELECTOR_ATTRIBUTE_REGEX = r"\[\s*([^\]\s=]+)\s*=\s*(['\"])(.*?)\2\s*\]"+# The chain records an element's position as nth-child and nth-of-type, and a selector+# can carry either or both. Matching each one lets a selector keep the rest of itself.+POSITIONAL_PSEUDO_CLASS_REGEX = r":(nth-child|nth-of-type)\((\d+)\)"+# A real element tag in the chain is alphanumeric. Anything else left in a parsed+# tag name is unsupported CSS the parser could not peel off.+VALID_TAG_NAME_REGEX = re.compile(r"[a-zA-Z][a-zA-Z0-9-]*")+# An attribute operator (^=, *=, $=, ~=, |=) ends up inside the parsed key, and no+# element chain contains an attribute named that.+VALID_ATTRIBUTE_KEY_REGEX = re.compile(r"[a-zA-Z_:][a-zA-Z0-9_:.-]*")+# A pseudo-class written after a class is folded into the class name, and no element+# carries a class called that. A Tailwind variant puts the same word first instead+# (hover:bg-blue), so only the segment after the last colon can be a pseudo-class.+UNSUPPORTED_PSEUDO_CLASSES = frozenset(+ {+ "active",+ "after",+ "before",+ "checked",+ "disabled",+ "empty",+ "enabled",+ "first-child",+ "first-of-type",+ "focus",+ "focus-visible",+ "focus-within",+ "hover",+ "invalid",+ "last-child",+ "last-of-type",+ "only-child",+ "optional",+ "required",+ "root",+ "target",+ "valid",+ "visited",+ }+)LAST_UPDATED_TEAM_ACTION: dict[int, datetime.datetime] = {}@@ -30,28 +68,41 @@ class SelectorPart:self.direct_descendant = direct_descendantself.data: dict[str, Union[str, list]] = {}self.ch_attributes: dict[str, Union[str, list]] = {} # attributes for CH-- result = re.search(SELECTOR_ATTRIBUTE_REGEX, tag)- pairs = self._attribute_pairs(tag, result)- self.confine_to_element = bool(pairs)- if result and pairs:- for key, value in pairs.items():- self.data[f"attributes__attr__{key}"] = value- self.ch_attributes[key] = value- tag = result[1]- if result and "[id=" in tag:- self.data["attr_id"] = result[3]- self.ch_attributes["attr_id"] = result[3]- tag = result[1]- if result and "[" in tag:- self.data[f"attributes__attr__{result[2]}"] = result[3]- self.ch_attributes[result[2]] = result[3]- tag = result[1]- if ":nth-child(" in tag:- parts = tag.split(":nth-child(")- self.data["nth_child"] = parts[1].replace(")", "")- self.ch_attributes["nth-child"] = self.data["nth_child"]- tag = parts[0]+ self.unsatisfiable = False++ attribute_matches = list(re.finditer(SELECTOR_ATTRIBUTE_REGEX, tag))+ # Saved actions count on the loose reading of a single attribute: its bare key+ # also matches the end of a longer key (label inside aria-label), and its value+ # keeps backslashes such as the hex escape in \31. Two or more attributes without+ # an id never matched under the earlier parser, so no saved count depends on+ # their reading, and they take the strict one: unescaped values and the full+ # chain key.+ self.strict_attributes = len(attribute_matches) >= 2 and all(+ match.group(1) != "id" for match in attribute_matches+ )+ if attribute_matches:+ for match in attribute_matches:+ key = match.group(1)+ value = match.group(3)+ if self.strict_attributes:+ value = re.sub(r"\\(.)", r"\1", value)+ if key == "id":+ self.data["attr_id"] = value+ self._require("attr_id", value)+ else:+ self.data[f"attributes__attr__{key}"] = value+ self._require(key, value)+ # Excise the attribute spans and keep the rest, so a class, id or+ # nth-child written after an attribute selector is not discarded.+ for match in reversed(attribute_matches):+ tag = tag[: match.start()] + tag[match.end() :]+ positional_matches = list(re.finditer(POSITIONAL_PSEUDO_CLASS_REGEX, tag))+ for match in positional_matches:+ pseudo_class, position = match.group(1), match.group(2)+ self.data["nth_child" if pseudo_class == "nth-child" else "nth_of_type"] = position+ self._require(pseudo_class, position)+ for match in reversed(positional_matches):+ tag = tag[: match.start()] + tag[match.end() :]if "." in tag:# Regex pattern that matches dots that are NOT inside square brackets# Uses negative lookahead to ensure the dot is not followed by content ending with ]@@ -67,8 +118,9 @@ class SelectorPart:if "#" in tag:parts = tag.split("#")if len(parts) > 1:- self.data["attr_id"] = self._unescape_class(parts[1]) if escape_slashes else parts[1]- self.ch_attributes["attr_id"] = self.data["attr_id"]+ attr_id = self._unescape_class(parts[1]) if escape_slashes else parts[1]+ self.data["attr_id"] = attr_id+ self._require("attr_id", attr_id)tag = parts[0]if tag:self.data["tag_name"] = tag@@ -88,23 +140,12 @@ class SelectorPart:params.append(value)return {"where": where, "params": params}- @staticmethod- def _attribute_pairs(tag: str, result: Optional[re.Match[str]]) -> dict[str, str]:- # The greedy SELECTOR_ATTRIBUTE_REGEX folds [a="1"][b="2"], or a value with a nested- # quote, into one key that contains a quote. The chain escapes quotes inside keys and- # values, so that key can never match. Only those parts are parsed again, which means- # a selector that matches events today compiles exactly as before.- # A prefix like .btn or :nth-child(2) before the tag letters is not parsed here.- if not result or tag[: result.start(1)] or "[id=" in tag or not re.search(r"[\"']", result[2]):- return {}- # Fall back unless the pairs run to the end of the part, so a trailing .class or a- # repeated key never turns into a match that ignores it.- brackets = tag[result.end(1) :]- matches = re.findall(ATTRIBUTE_PAIR_REGEX, brackets)- pairs = {key: re.sub(r"\\(.)", r"\1", value) for key, _quote, value in matches}- if re.sub(ATTRIBUTE_PAIR_REGEX, "", brackets) or len(pairs) != len(matches):- return {}- return pairs+ def _require(self, key: str, value: str) -> None:+ # No element carries two values for one key, so a selector such as+ # [type="button"][type="submit"] or :nth-child(1):nth-child(2) matches nothing.+ if self.ch_attributes.get(key, value) != value:+ self.unsatisfiable = True+ self.ch_attributes[key] = valuedef _unescape_class(self, class_name):r"""Separate all double slashes "\\" (replace them with "\") and remove all single slashes between them."""@@ -153,6 +194,35 @@ class Selector:yield "".join(part)+ def is_unsatisfiable(self) -> bool:+ # For example [type="button"][type="submit"], which no element can satisfy.+ return any(part.unsatisfiable for part in self.parts)++ def has_unsupported_syntax(self) -> bool:+ # A part keeps unsupported CSS (a pseudo-class, an unsupported combinator, ...)+ # as its tag name, so the compiled regex looks for a tag no real element has and+ # matches nothing.+ for part in self.parts:+ tag = part.data.get("tag_name")+ # "*" is the universal selector, which build_selector_regex supports by+ # skipping the tag name entirely.+ if isinstance(tag, str) and tag != "*" and not VALID_TAG_NAME_REGEX.fullmatch(tag):+ return True+ if any(not VALID_ATTRIBUTE_KEY_REGEX.fullmatch(key) for key in part.ch_attributes):+ return True+ classes = part.data.get("attr_class__contains")+ if isinstance(classes, list) and any(self._class_carries_pseudo_class(name) for name in classes):+ return True+ return False++ @staticmethod+ def _class_carries_pseudo_class(class_name: str) -> bool:+ # Without a colon the whole name is the class, and plenty of real classes share a+ # word with a pseudo-class ("active", "disabled"), so only look past a colon.+ if ":" not in class_name:+ return False+ return class_name.rsplit(":", 1)[-1] in UNSUPPORTED_PSEUDO_CLASSES+class Event(models.Model):created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)diff --git a/posthog/models/property/util.py b/posthog/models/property/util.pyindex c16eafe277a4..8a750a47cdcd 100644--- a/posthog/models/property/util.py+++ b/posthog/models/property/util.py@@ -124,37 +124,64 @@ def _chain_escaped_value(value: str) -> str:return value.replace(r"\"", '"').replace('"', r"\"")-# Custom attributes sort under attr__<key> in the chain (see elements_to_string), and the-# regex has to name them in chain order to match.+# Attribute keys the elements chain serializes without the attr__ prefix that custom+# HTML attributes get. See elements_to_string in posthog/models/element/element.py._UNPREFIXED_CHAIN_ATTRIBUTES = {"attr_id", "href", "text", "nth-child", "nth-of-type"}-# A `;` inside a quoted value, like style="a: b; c: d", does not end the element.-_WITHIN_ELEMENT = r'(?:[^;"]|"(?:\\.|[^"\\])*")*?'def _chain_attribute_order(key: str) -> str:+ """The key this attribute sorts under in the elements chain.++ elements_to_string sorts by serialized key, so a custom attribute sorts under+ attr__<key>. Emit attributes in that order: the separators between them cannot+ match backwards, so an order the chain never produces can never match.+ """return key if key in _UNPREFIXED_CHAIN_ATTRIBUTES else f"attr__{key}"+# A semicolon separates elements only outside a quoted attribute value — an inline+# style="display: flex; gap: 4px" carries its own. Quotes inside a value are escaped+# as \" (see _escape in posthog/models/element/element.py), so an escaped quote must+# not close the span. split_chain_regex draws the boundary the same way. A backslash+# is consumed only together with the character after it, so a long run of backslashes+# has one way to match and cannot cause catastrophic backtracking.+_QUOTED_VALUE = r'"(?:\\.|[^"\\])*"'+_WITHIN_ELEMENT = r'(?:[^;"]|' + _QUOTED_VALUE + r")*?"+_WHOLE_ELEMENTS = r'(?:(?:[^;"]|' + _QUOTED_VALUE + r")*;)*"+# ClickHouse runs these through RE2, which has no negative lookahead. A class that+# excludes both whitespace and non-whitespace matches no character at all.+_MATCHES_NOTHING = r"[^\s\S]"++def build_selector_regex(selector: Selector) -> str:+ if selector.is_unsatisfiable():+ return _MATCHES_NOTHINGregex = r""- for tag in selector.parts:+ for index, tag in enumerate(selector.parts):+ if index > 0 and not tag.direct_descendant:+ # A descendant combinator (a space) matches through any number of+ # intermediate elements. Skip whole elements only — an unanchored .*+ # would let this part match inside a class name or attribute value.+ regex += _WHOLE_ELEMENTSif tag.data.get("tag_name") and isinstance(tag.data["tag_name"], str) and tag.data["tag_name"] != "*":# The elements in the elements_chain are separated by the semicolonregex += re.escape(tag.data["tag_name"])if tag.data.get("attr_class__contains"):- regex += r".*?\." + r"\..*?".join([re.escape(s) for s in sorted(tag.data["attr_class__contains"])])+ # Every condition of one selector part has to land inside one element+ regex += (+ _WITHIN_ELEMENT+ + r"\."+ + (r"\." + _WITHIN_ELEMENT).join([re.escape(s) for s in sorted(tag.data["attr_class__contains"])])+ )if tag.ch_attributes:- # Attributes parsed from [a="1"][b="2"] must all be on one element.- separator = _WITHIN_ELEMENT if tag.confine_to_element else r".*?"- regex += separator+ regex += _WITHIN_ELEMENTfor key, value in sorted(tag.ch_attributes.items(), key=lambda kv: _chain_attribute_order(kv[0])):# The full chain key stops [foo="1"] from matching inside attr__data-foo="1".- name = _chain_attribute_order(key) if tag.confine_to_element else key- regex += rf'{re.escape(name)}="{re.escape(_chain_escaped_value(str(value)))}"' + separator- # The rest of the element can carry characters an allowlist cannot- # anticipate (classes like w-1/2 or !mt-0), so skip anything up to the- # `;` element separator.- regex += r"[^;]*?($|;|:([^;^\s]*(;|$|\s)))"+ name = _chain_attribute_order(key) if tag.strict_attributes else key+ regex += rf'{re.escape(name)}="{re.escape(_chain_escaped_value(str(value)))}"' + _WITHIN_ELEMENT+ # The rest of the element can carry characters no allowlist anticipates+ # (classes like w-1/2 or !mt-0), so skip anything within the element.+ regex += _WITHIN_ELEMENT + r"($|;|:([^;^\s]*(;|$|\s)))"if tag.direct_descendant:regex += r".*"if regex:diff --git a/posthog/models/test/test_event_model.py b/posthog/models/test/test_event_model.pyindex a2a9cb376622..996f228faa70 100644--- a/posthog/models/test/test_event_model.py+++ b/posthog/models/test/test_event_model.py@@ -157,6 +157,21 @@ class TestSelectors(BaseTest):selector1 = Selector("div#root\\:id")self.assertEqual(selector1.parts[0].data, {"tag_name": "div", "attr_id": "root:id"})+ def test_class_before_attribute(self):+ # A class that precedes an attribute selector must not be captured as the tag name+ selector1 = Selector('.btn[ng-disabled="true"]')+ self.assertEqual(+ selector1.parts[0].data,+ {"attr_class__contains": ["btn"], "attributes__attr__ng-disabled": "true"},+ )++ def test_multiple_attributes(self):+ selector1 = Selector('[type="button"][ng-click="save()"]')+ self.assertEqual(+ selector1.parts[0].data,+ {"attributes__attr__type": "button", "attributes__attr__ng-click": "save()"},+ )+class TestSelectorRegexMatching(SimpleTestCase):@parameterized.expand(@@ -258,6 +273,24 @@ class TestSelectorRegexMatching(SimpleTestCase):[Element(tag_name="div", attributes={"attr__data-x": "b"})],False,),+ (+ "the same id attribute with two different values",+ '[id="a"][id="b"]',+ [Element(tag_name="div", attr_id="b")],+ False,+ ),+ (+ "an id and an id attribute with different values",+ '#a[id="b"]',+ [Element(tag_name="div", attr_id="a")],+ False,+ ),+ (+ "the same position with two different values",+ "li:nth-child(1):nth-child(2)",+ [Element(tag_name="li", nth_child=2)],+ False,+ ),("two attributes with an escaped quote in a value","[title='it\\'s'][data-x='a']",@@ -270,6 +303,12 @@ class TestSelectorRegexMatching(SimpleTestCase):[Element(tag_name="button", attributes={"attr__data-bar": "2", "attr__data-foo": "1"})],False,),+ (+ "one attribute name that matches the end of a longer name",+ 'button[label="Save"]',+ [Element(tag_name="button", attributes={"attr__aria-label": "Save"})],+ True,+ ),("two attributes after a tag and a position the element does not have",'button:nth-child(2)[type="button"][data-x="a"]',@@ -312,12 +351,56 @@ class TestSelectorRegexMatching(SimpleTestCase):[Element(tag_name="a"), Element(tag_name="b")],False,),+ (+ "a descendant part does not match text inside another element",+ "form button.btn",+ [+ Element(tag_name="button", attr_class=["btn"]),+ Element(tag_name="a", href="/form-signup"),+ ],+ False,+ ),+ (+ "class and attribute have to land on the same element",+ '.btn[ng-disabled="true"]',+ [+ Element(tag_name="span", attr_class=["btn"]),+ Element(tag_name="div", attributes={"attr__ng-disabled": "true"}),+ ],+ False,+ ),+ (+ "nth-child and nth-of-type together",+ "button.btn:nth-child(3):nth-of-type(1)",+ [Element(tag_name="button", attr_class=["btn"], nth_child=3, nth_of_type=1)],+ True,+ ),+ (+ "an id alongside an attribute the chain sorts before it",+ '#submit[type="button"]',+ [Element(tag_name="button", attr_id="submit", attributes={"attr__type": "button"})],+ True,+ ),])def test_selector_matches_elements_chain(self, _name, selector, elements, expected):regex = build_selector_regex(Selector(selector, escape_slashes=False))self.assertEqual(bool(re.search(regex, elements_to_string(elements))), expected)+ @parameterized.expand(+ [+ ("pseudo-class after a class", ".btn:hover", True),+ ("pseudo-class after a tag", "button:hover", True),+ ("attribute operator", '[href^="http"]', True),+ ("tailwind variant, which is a real class", ".hover:bg-blue", False),+ ("class named after a pseudo-class, with no colon to make it one", ".active", False),+ ("tailwind arbitrary value", ".sm:[max-width:640px]", False),+ ("universal selector, which the compiler supports", "*", False),+ ]+ )+ def test_unsupported_syntax_detection(self, _name, selector, expected):+ self.assertEqual(Selector(selector, escape_slashes=False).has_unsupported_syntax(), expected)+class TestSelectorRegexMonotonicity(SimpleTestCase):SELECTORS = [@@ -371,9 +454,15 @@ class TestSelectorRegexMonotonicity(SimpleTestCase):regex += r".*"return r"(^|;)" + regex if regex else r""- def test_fix_only_widens_matching(self):+ # The tail widening only adds matches, with one deliberate exception: the old+ # tail ran past a quote and found a class name inside an attribute value, on an+ # element that carries no such class. Element-confined matching drops that.+ INTENDED_NARROWING = (".class", 'span:attr__title="x.class y"nth-child="0"nth-of-type="0"')++ def test_fix_widens_matching_except_inside_quoted_values(self):chains = [elements_to_string(elements) for elements in self.ELEMENT_CHAINS]newly_matching_pairs = 0+ narrowing_seen = Falsefor selector_string in self.SELECTORS:selector = Selector(selector_string, escape_slashes=False)old_regex = self._pre_fix_build_selector_regex(selector)@@ -382,12 +471,18 @@ class TestSelectorRegexMonotonicity(SimpleTestCase):old_match = bool(re.search(old_regex, chain))new_match = bool(re.search(new_regex, chain))with self.subTest(selector=selector_string, chain=chain):- if old_match:+ if (selector_string, chain) == self.INTENDED_NARROWING:+ narrowing_seen = True+ self.assertTrue(old_match)+ self.assertFalse(new_match)+ elif old_match:self.assertTrue(new_match)if new_match and not old_match:newly_matching_pairs += 1# the corpus has to exercise the widening, or the superset check is vacuousself.assertGreater(newly_matching_pairs, 0)+ # and it has to still reach the narrowing, or that assertion is skipped silently+ self.assertTrue(narrowing_seen)@override_settings(CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA=True)diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.pyindex 35e8fa2d0031..2f0ddcbdec98 100644--- a/products/actions/backend/api/action.py+++ b/products/actions/backend/api/action.py@@ -1,11 +1,13 @@import jsonfrom collections import Counter, defaultdictfrom datetime import UTC, datetime+from functools import lru_cachefrom typing import Any, castfrom django.db import connectionfrom django.db.models import Count+import structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, PolymorphicProxySerializer, extend_schema, extend_schema_fieldfrom rest_framework import request, serializers, viewsets@@ -28,6 +30,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.constants import TREND_FILTER_TYPE_EVENTS+from posthog.dataclasses import frozenfrom posthog.event_usage import report_user_actionfrom posthog.models import Teamfrom posthog.models.event.event import Selector@@ -45,6 +48,8 @@ from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import Experimentfrom products.product_analytics.backend.facade.models import Insight+logger = structlog.get_logger(__name__)+_PropertyFilterUnion = PolymorphicProxySerializer(component_name="ActionStepPropertyFilter",serializers=[@@ -69,6 +74,51 @@ class _ActionStepPropertiesField(serializers.ListField):pass+# An entry holds the selector plus its compiled regex, which is larger, for the life of+# the process. Nobody hand-writes a CSS selector this long, so cap what gets retained.+_MAX_CACHED_SELECTOR_LENGTH = 1_000+++@frozen+class _CompiledSelector:+ regex: str | None+ warning: str | None+++def _compile_selector_uncached(selector_str: str) -> _CompiledSelector:+ try:+ selector = Selector(selector_str, escape_slashes=False)+ warning = None+ if selector.has_unsupported_syntax():+ warning = "This selector uses CSS we cannot match on. Try matching on the element tag, id, or class."+ return _CompiledSelector(regex=build_selector_regex(selector), warning=warning)+ except Exception:+ logger.exception("Failed to compile action selector")+ return _CompiledSelector(+ regex=None,+ warning="This selector could not be read, so it will not match any events. Check that it is valid CSS.",+ )+++@lru_cache(maxsize=2048)+def _compile_selector_cached(selector_str: str) -> _CompiledSelector:+ return _compile_selector_uncached(selector_str)+++def _compile_selector(selector_str: str) -> _CompiledSelector:+ # Cached because the selector_regex and selector_warning fields both need it for+ # every serialized action step. An outsized or non-string selector skips the cache:+ # lru_cache hashes its argument before the body runs, so an unhashable one would+ # raise from the lookup itself.+ if not isinstance(selector_str, str) or len(selector_str) > _MAX_CACHED_SELECTOR_LENGTH:+ return _compile_selector_uncached(selector_str)+ return _compile_selector_cached(selector_str)+++def _selector_str(obj) -> str | None:+ return obj.get("selector") if isinstance(obj, dict) else getattr(obj, "selector", None)++class ActionStepJSONSerializer(serializers.Serializer):event = serializers.CharField(required=False,@@ -87,7 +137,12 @@ class ActionStepJSONSerializer(serializers.Serializer):allow_null=True,help_text="CSS selector to match the target element (e.g. 'div > button.cta').",)- selector_regex = serializers.SerializerMethodField()+ selector_regex = serializers.SerializerMethodField(+ help_text="Compiled regex the selector matches against the event elements chain. Null when no selector is set."+ )+ selector_warning = serializers.SerializerMethodField(+ help_text="Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent."+ )tag_name = serializers.CharField(required=False,allow_null=True,@@ -131,14 +186,12 @@ class ActionStepJSONSerializer(serializers.Serializer):)def get_selector_regex(self, obj) -> str | None:- selector_str = obj.get("selector") if isinstance(obj, dict) else getattr(obj, "selector", None)- if not selector_str:- return None- try:- selector = Selector(selector_str, escape_slashes=False)- return build_selector_regex(selector)- except Exception:- return None+ selector_str = _selector_str(obj)+ return _compile_selector(selector_str).regex if selector_str else None++ def get_selector_warning(self, obj) -> str | None:+ selector_str = _selector_str(obj)+ return _compile_selector(selector_str).warning if selector_str else Noneclass ActionSerializer(diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.pyindex 185bca926fb7..035ea453dc54 100644--- a/products/actions/backend/api/test/test_action.py+++ b/products/actions/backend/api/test/test_action.py@@ -10,12 +10,15 @@ from posthog.test.base import ()from unittest.mock import ANY, patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models import Tag, Userfrom posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, deny_warehouse_table_to_member+from products.actions.backend.api.action import ActionStepJSONSerializerfrom products.actions.backend.models.action import Actionfrom products.actions.backend.models.selector_match_change import ActionSelectorMatchChangefrom products.cdp.backend.models.hog_functions.hog_function import HogFunction@@ -68,6 +71,7 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):"properties": None,"selector": "div > button","selector_regex": ANY,+ "selector_warning": None,"tag_name": None,"text": "sign up","text_matching": None,@@ -247,6 +251,7 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):"properties": [{"key": "$browser", "value": "Chrome"}],"selector": "div > button","selector_regex": ANY,+ "selector_warning": None,"tag_name": None,"text": "sign up NOW","text_matching": None,@@ -260,6 +265,7 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):"properties": None,"selector": None,"selector_regex": None,+ "selector_warning": None,"tag_name": None,"text": None,"text_matching": None,@@ -980,3 +986,23 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):results = response.json()["results"]action_result = next(r for r in results if r["id"] == action.id)assert action_result["reference_count"] == 4+++class TestSelectorWarning(SimpleTestCase):+ @parameterized.expand(+ [+ ("class_then_attribute", '.btn[ng-disabled="true"]'),+ ("compound_attributes", '[type="button"][ng-click="save()"]'),+ ("descendant", "form button.btn"),+ ("plain_tag", "div > button"),+ ]+ )+ def test_no_warning_for_matchable_selector(self, _name: str, selector: str) -> None:+ assert ActionStepJSONSerializer().get_selector_warning({"selector": selector}) is None++ def test_warns_for_selector_that_never_matches(self) -> None:+ # Pseudo-class selectors are unsupported and compile to a regex that matches nothing.+ assert ActionStepJSONSerializer().get_selector_warning({"selector": "input:disabled"}) is not None++ def test_no_warning_without_selector(self) -> None:+ assert ActionStepJSONSerializer().get_selector_warning({}) is Nonediff --git a/products/actions/frontend/generated/api.schemas.ts b/products/actions/frontend/generated/api.schemas.tsindex e910a8ed5904..874692ebdbd0 100644--- a/products/actions/frontend/generated/api.schemas.ts+++ b/products/actions/frontend/generated/api.schemas.ts@@ -450,8 +450,16 @@ export interface ActionStepJSONApi {* @nullable*/selector?: string | null- /** @nullable */+ /**+ * Compiled regex the selector matches against the event elements chain. Null when no selector is set.+ * @nullable+ */readonly selector_regex: string | null+ /**+ * Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent.+ * @nullable+ */+ readonly selector_warning: string | null/*** HTML tag name to match (e.g. "button", "a", "input").* @nullablediff --git a/products/actions/frontend/generated/api.zod.ts b/products/actions/frontend/generated/api.zod.tsindex a0e5c00fae00..0d3b92f9582a 100644--- a/products/actions/frontend/generated/api.zod.ts+++ b/products/actions/frontend/generated/api.zod.ts@@ -373,7 +373,18 @@ export const ActionsCreateBody = /* @__PURE__ */ zod.string().nullish().describe("CSS selector to match the target element (e.g. 'div > button.cta')."),- selector_regex: zod.string().nullable(),+ selector_regex: zod+ .string()+ .nullable()+ .describe(+ 'Compiled regex the selector matches against the event elements chain. Null when no selector is set.'+ ),+ selector_warning: zod+ .string()+ .nullable()+ .describe(+ 'Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent.'+ ),tag_name: zod.string().nullish()@@ -796,7 +807,18 @@ export const ActionsUpdateBody = /* @__PURE__ */ zod.string().nullish().describe("CSS selector to match the target element (e.g. 'div > button.cta')."),- selector_regex: zod.string().nullable(),+ selector_regex: zod+ .string()+ .nullable()+ .describe(+ 'Compiled regex the selector matches against the event elements chain. Null when no selector is set.'+ ),+ selector_warning: zod+ .string()+ .nullable()+ .describe(+ 'Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent.'+ ),tag_name: zod.string().nullish()@@ -1221,7 +1243,18 @@ export const ActionsPartialUpdateBody = /* @__PURE__ */ zod.string().nullish().describe("CSS selector to match the target element (e.g. 'div > button.cta')."),- selector_regex: zod.string().nullable(),+ selector_regex: zod+ .string()+ .nullable()+ .describe(+ 'Compiled regex the selector matches against the event elements chain. Null when no selector is set.'+ ),+ selector_warning: zod+ .string()+ .nullable()+ .describe(+ 'Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent.'+ ),tag_name: zod.string().nullish()diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex 5058111d98c5..ff9fe75546de 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -678,6 +678,7 @@ export namespace Schemas {properties?: (Array<ActionStepPropertyFilter> | null) | undefined;selector?: (string | null) | undefined;selector_regex: string | null;+ selector_warning: string | null;tag_name?: (string | null) | undefined;text?: (string | null) | undefined;text_matching?: (ActionStepMatchingEnum | NullEnum) | undefined;diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 130be1a08053..4edde2c7c672 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -3465,8 +3465,17 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControl)+class _SurveyAPIActionStepSerializer(ActionStepJSONSerializer):+ # This payload is cached and downloaded by every SDK client, so it carries only what+ # a client needs in order to match. selector_warning is guidance for the Actions editor.+ def get_fields(self):+ fields = super().get_fields()+ fields.pop("selector_warning", None)+ return fields++class SurveyAPIActionSerializer(serializers.ModelSerializer):- steps = ActionStepJSONSerializer(many=True, required=False)+ steps = _SurveyAPIActionStepSerializer(many=True, required=False)class Meta:model = Actiondiff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambrindex 25f2aee305ac..bc8ccf3a2934 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambr@@ -24,12 +24,12 @@FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS web_goals_person_id,min(events__session.`$start_timestamp`) AS start_timestamp,- countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?data\\-node\\-key="interactions".*?[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0), in(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),- (SELECT cohortpeople.person_id AS person_id- FROM cohortpeople- WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999))- GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.version- HAVING greater(sum(cohortpeople.sign), 0)))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_0,+ countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?data\\-node\\-key="interactions"(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0), in(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),+ (SELECT cohortpeople.person_id AS person_id+ FROM cohortpeople+ WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999))+ GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.version+ HAVING greater(sum(cohortpeople.sign), 0)))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_0,countIf(0) AS action_previous_count_0,if(greater(action_current_count_0, 0), web_goals_person_id, NULL) AS action_current_person_id_0,if(greater(action_previous_count_0, 0), web_goals_person_id, NULL) AS action_previous_person_id_0,@@ -37,15 +37,15 @@countIf(0) AS action_previous_count_1,if(greater(action_current_count_1, 0), web_goals_person_id, NULL) AS action_current_person_id_1,if(greater(action_previous_count_1, 0), web_goals_person_id, NULL) AS action_previous_person_id_1,- countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-input[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_2,+ countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-input(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_2,countIf(0) AS action_previous_count_2,if(greater(action_current_count_2, 0), web_goals_person_id, NULL) AS action_current_person_id_2,if(greater(action_previous_count_2, 0), web_goals_person_id, NULL) AS action_previous_person_id_2,- countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-btn\\..*?text\\-white[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), arrayExists(x -> ifNull(equals(x, 'text page'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_3,+ countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-btn\\.(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?text\\-white(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), arrayExists(x -> ifNull(equals(x, 'text page'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_3,countIf(0) AS action_previous_count_3,if(greater(action_current_count_3, 0), web_goals_person_id, NULL) AS action_current_person_id_3,if(greater(action_previous_count_3, 0), web_goals_person_id, NULL) AS action_previous_person_id_3,- countIf(and(and(equals(events.event, '$autocapture'), and(match(events.elements_chain, '(^|;)a[^;]*?($|;|:([^;^\\s]*(;|$|\\s))).*?\\.ant\\-btn[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), greater(arrayCount(x -> in(x, ['a']), events.elements_chain_elements), 0)), arrayExists(x -> ifNull(equals(x, 'text'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_4,+ countIf(and(and(equals(events.event, '$autocapture'), and(match(events.elements_chain, '(^|;)a(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))(?:(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*;)*(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-btn(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), greater(arrayCount(x -> in(x, ['a']), events.elements_chain_elements), 0)), arrayExists(x -> ifNull(equals(x, 'text'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_4,countIf(0) AS action_previous_count_4,if(greater(action_current_count_4, 0), web_goals_person_id, NULL) AS action_current_person_id_4,if(greater(action_previous_count_4, 0), web_goals_person_id, NULL) AS action_previous_person_id_4@@ -63,12 +63,12 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)- WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?data\\-node\\-key="interactions".*?[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0), in(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),- (SELECT cohortpeople.person_id AS person_id- FROM cohortpeople- WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999))- GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.version- HAVING greater(sum(cohortpeople.sign), 0)))), and(equals(events.event, '$pageview'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-input[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-btn\\..*?text\\-white[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), arrayExists(x -> ifNull(equals(x, 'text page'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)), and(equals(events.event, '$autocapture'), and(match(events.elements_chain, '(^|;)a[^;]*?($|;|:([^;^\\s]*(;|$|\\s))).*?\\.ant\\-btn[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), greater(arrayCount(x -> in(x, ['a']), events.elements_chain_elements), 0)), arrayExists(x -> ifNull(equals(x, 'text'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0), and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'mat_$host'), ''), 'null'), '^"|"$', ''), 'teest.com'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'mat_$current_url'), ''), 'null'), '^"|"$', '')), '%https://teest.com%'), 0)), 1))+ WHERE and(equals(events.team_id, 99999), and(isNotNull(events.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?data\\-node\\-key="interactions"(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0), in(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),+ (SELECT cohortpeople.person_id AS person_id+ FROM cohortpeople+ WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999))+ GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.version+ HAVING greater(sum(cohortpeople.sign), 0)))), and(equals(events.event, '$pageview'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-input(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-btn\\.(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?text\\-white(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), arrayExists(x -> ifNull(equals(x, 'text page'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)), and(equals(events.event, '$autocapture'), and(match(events.elements_chain, '(^|;)a(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))(?:(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*;)*(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-btn(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), greater(arrayCount(x -> in(x, ['a']), events.elements_chain_elements), 0)), arrayExists(x -> ifNull(equals(x, 'text'), 0), events.elements_chain_texts), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$current_url'), ''), 'null'), '^"|"$', ''), 'https://teest.com'), 0)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0), and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'mat_$host'), ''), 'null'), '^"|"$', ''), 'teest.com'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'mat_$current_url'), ''), 'null'), '^"|"$', '')), '%https://teest.com%'), 0)), 1))GROUP BY events.`$session_id`)WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0)LIMIT 100 SETTINGS readonly=2,diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.new_events_schema.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.new_events_schema.ambrindex bf3a164fa3fa..91e2080493ee 100644--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.new_events_schema.ambr+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.new_events_schema.ambr@@ -21,12 +21,12 @@FROM(SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS web_goals_person_id,min(events__session.`$start_timestamp`) AS start_timestamp,- countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?data\\-node\\-key="interactions".*?[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0), in(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),- (SELECT cohortpeople.person_id AS person_id- FROM cohortpeople- WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999))- GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.version- HAVING greater(sum(cohortpeople.sign), 0)))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_0,+ countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?data\\-node\\-key="interactions"(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0), in(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),+ (SELECT cohortpeople.person_id AS person_id+ FROM cohortpeople+ WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999))+ GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.version+ HAVING greater(sum(cohortpeople.sign), 0)))), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_0,countIf(0) AS action_previous_count_0,if(greater(action_current_count_0, 0), web_goals_person_id, NULL) AS action_current_person_id_0,if(greater(action_previous_count_0, 0), web_goals_person_id, NULL) AS action_previous_person_id_0,@@ -34,15 +34,15 @@countIf(0) AS action_previous_count_1,if(greater(action_current_count_1, 0), web_goals_person_id, NULL) AS action_current_person_id_1,if(greater(action_previous_count_1, 0), web_goals_person_id, NULL) AS action_previous_person_id_1,- countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-input[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_2,+ countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-input(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_2,countIf(0) AS action_previous_count_2,if(greater(action_current_count_2, 0), web_goals_person_id, NULL) AS action_current_person_id_2,if(greater(action_previous_count_2, 0), web_goals_person_id, NULL) AS action_previous_person_id_2,- countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-btn\\..*?text\\-white[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), arrayExists(x -> ifNull(equals(x, 'text page'), 0), events.elements_chain_texts), ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), 'https://teest.com'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_3,+ countIf(and(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-btn\\.(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?text\\-white(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), arrayExists(x -> ifNull(equals(x, 'text page'), 0), events.elements_chain_texts), ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), 'https://teest.com'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_3,countIf(0) AS action_previous_count_3,if(greater(action_current_count_3, 0), web_goals_person_id, NULL) AS action_current_person_id_3,if(greater(action_previous_count_3, 0), web_goals_person_id, NULL) AS action_previous_person_id_3,- countIf(and(and(equals(events.event, '$autocapture'), and(match(events.elements_chain, '(^|;)a[^;]*?($|;|:([^;^\\s]*(;|$|\\s))).*?\\.ant\\-btn[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), greater(arrayCount(x -> in(x, ['a']), events.elements_chain_elements), 0)), arrayExists(x -> ifNull(equals(x, 'text'), 0), events.elements_chain_texts), ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), 'https://teest.com'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_4,+ countIf(and(and(equals(events.event, '$autocapture'), and(match(events.elements_chain, '(^|;)a(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))(?:(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*;)*(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-btn(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), greater(arrayCount(x -> in(x, ['a']), events.elements_chain_elements), 0)), arrayExists(x -> ifNull(equals(x, 'text'), 0), events.elements_chain_texts), ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), 'https://teest.com'), 0)), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))))) AS action_current_count_4,countIf(0) AS action_previous_count_4,if(greater(action_current_count_4, 0), web_goals_person_id, NULL) AS action_current_person_id_4,if(greater(action_previous_count_4, 0), web_goals_person_id, NULL) AS action_previous_person_id_4@@ -60,12 +60,12 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)- WHERE and(equals(events.team_id, 99999), and(isNotNull(events.properties.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?data\\-node\\-key="interactions".*?[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0), in(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),- (SELECT cohortpeople.person_id AS person_id- FROM cohortpeople- WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999))- GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.version- HAVING greater(sum(cohortpeople.sign), 0)))), and(equals(events.event, '$pageview'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-input[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;).*?\\.ant\\-btn\\..*?text\\-white[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), arrayExists(x -> ifNull(equals(x, 'text page'), 0), events.elements_chain_texts), ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), 'https://teest.com'), 0)), and(equals(events.event, '$autocapture'), and(match(events.elements_chain, '(^|;)a[^;]*?($|;|:([^;^\\s]*(;|$|\\s))).*?\\.ant\\-btn[^;]*?($|;|:([^;^\\s]*(;|$|\\s)))'), greater(arrayCount(x -> in(x, ['a']), events.elements_chain_elements), 0)), arrayExists(x -> ifNull(equals(x, 'text'), 0), events.elements_chain_texts), ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), 'https://teest.com'), 0)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0), and(ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`mat_$host`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`mat_$host`)), if(isNull(nullIf(toString(events.properties.`mat_$host`), '')), NULL, if(and(in(ascii(toString(events.properties.`mat_$host`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`mat_$host`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`mat_$host`), '[]'), '{}'), toString(events.properties.`mat_$host`)))), 'teest.com'), 0), ifNull(ilike(toString(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`mat_$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`mat_$current_url`)), if(isNull(nullIf(toString(events.properties.`mat_$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`mat_$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`mat_$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`mat_$current_url`), '[]'), '{}'), toString(events.properties.`mat_$current_url`))))), '%https://teest.com%'), 0)), 1))+ WHERE and(equals(events.team_id, 99999), and(isNotNull(events.properties.`$session_id`), or(equals(events.event, '$pageview'), equals(events.event, '$screen'), or(and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?data\\-node\\-key="interactions"(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0), in(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id),+ (SELECT cohortpeople.person_id AS person_id+ FROM cohortpeople+ WHERE and(equals(cohortpeople.team_id, 99999), equals(cohortpeople.cohort_id, 99999))+ GROUP BY cohortpeople.person_id, cohortpeople.cohort_id, cohortpeople.version+ HAVING greater(sum(cohortpeople.sign), 0)))), and(equals(events.event, '$pageview'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-input(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), ifNull(like(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), '%https://teest.com%'), 0)), and(equals(events.event, '$autocapture'), match(events.elements_chain, '(^|;)(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-btn\\.(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?text\\-white(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), arrayExists(x -> ifNull(equals(x, 'text page'), 0), events.elements_chain_texts), ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), 'https://teest.com'), 0)), and(equals(events.event, '$autocapture'), and(match(events.elements_chain, '(^|;)a(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))(?:(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*;)*(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?\\.ant\\-btn(?:[^;"]|"(?:\\\\.|[^"\\\\])*")*?($|;|:([^;^\\s]*(;|$|\\s)))'), greater(arrayCount(x -> in(x, ['a']), events.elements_chain_elements), 0)), arrayExists(x -> ifNull(equals(x, 'text'), 0), events.elements_chain_texts), ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`$current_url`)), if(isNull(nullIf(toString(events.properties.`$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`$current_url`), '[]'), '{}'), toString(events.properties.`$current_url`)))), 'https://teest.com'), 0)))), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0), and(ifNull(equals(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`mat_$host`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`mat_$host`)), if(isNull(nullIf(toString(events.properties.`mat_$host`), '')), NULL, if(and(in(ascii(toString(events.properties.`mat_$host`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`mat_$host`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`mat_$host`), '[]'), '{}'), toString(events.properties.`mat_$host`)))), 'teest.com'), 0), ifNull(ilike(toString(if(notEquals(JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`mat_$current_url`)), '{}'), JSONStripEmptyStringsAndNulls(toJSONString(events.properties.^`mat_$current_url`)), if(isNull(nullIf(toString(events.properties.`mat_$current_url`), '')), NULL, if(and(in(ascii(toString(events.properties.`mat_$current_url`)), tuple(91, 123)), in(ascii(toJSONString(events.properties.`mat_$current_url`)), tuple(91, 123))), nullIf(nullIf(toJSONString(events.properties.`mat_$current_url`), '[]'), '{}'), toString(events.properties.`mat_$current_url`))))), '%https://teest.com%'), 0)), 1))GROUP BY events.properties.`$session_id`)WHERE or(and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-28 00:00:00', 'UTC'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2025-01-29 23:59:59', 'UTC')))), 0)LIMIT 100 SETTINGS readonly=2,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 527b1dbd5368..762c77cf93eb 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -4114,8 +4114,16 @@ export namespace Schemas {* @nullable*/selector?: string | null;- /** @nullable */+ /**+ * Compiled regex the selector matches against the event elements chain. Null when no selector is set.+ * @nullable+ */readonly selector_regex: string | null;+ /**+ * Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent.+ * @nullable+ */+ readonly selector_warning: string | null;/*** HTML tag name to match (e.g. "button", "a", "input").* @nullablediff --git a/services/mcp/src/generated/actions/api.ts b/services/mcp/src/generated/actions/api.tsindex 013d454e418c..1165ffab811e 100644--- a/services/mcp/src/generated/actions/api.ts+++ b/services/mcp/src/generated/actions/api.ts@@ -413,7 +413,18 @@ export const ActionsCreateBody = () => zod.string().nullish().describe("CSS selector to match the target element (e.g. 'div > button.cta')."),- selector_regex: zod.string().nullish(),+ selector_regex: zod+ .string()+ .nullish()+ .describe(+ 'Compiled regex the selector matches against the event elements chain. Null when no selector is set.'+ ),+ selector_warning: zod+ .string()+ .nullish()+ .describe(+ 'Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent.'+ ),tag_name: zod.string().nullish()@@ -862,7 +873,18 @@ export const ActionsPartialUpdateBody = () => zod.string().nullish().describe("CSS selector to match the target element (e.g. 'div > button.cta')."),- selector_regex: zod.string().nullish(),+ selector_regex: zod+ .string()+ .nullish()+ .describe(+ 'Compiled regex the selector matches against the event elements chain. Null when no selector is set.'+ ),+ selector_warning: zod+ .string()+ .nullish()+ .describe(+ 'Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent.'+ ),tag_name: zod.string().nullish()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/action-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/action-create.jsonindex c84d80796760..ea9043df8f2b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/action-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/action-create.json@@ -411,7 +411,19 @@{"type": "null"}- ]+ ],+ "description": "Compiled regex the selector matches against the event elements chain. Null when no selector is set."+ },+ "selector_warning": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent."},"tag_name": {"anyOf": [diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/action-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/action-update.jsonindex dc9be23aff43..3ec899356138 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/action-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/action-update.json@@ -415,7 +415,19 @@{"type": "null"}- ]+ ],+ "description": "Compiled regex the selector matches against the event elements chain. Null when no selector is set."+ },+ "selector_warning": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Set when the selector compiles to a matcher that cannot match any event. Null when the selector is valid or absent."},"tag_name": {"anyOf": [