: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
refactor(cdp): render the filter taxonomy from the real taxonomy (#90579)
Phil Haack4ed397ad4b1b
diff --git a/ee/hogai/chat_agent/taxonomy/format.py b/ee/hogai/chat_agent/taxonomy/format.pyindex 7122ec21e2b0..5eb812109c32 100644--- a/ee/hogai/chat_agent/taxonomy/format.py+++ b/ee/hogai/chat_agent/taxonomy/format.py@@ -6,7 +6,7 @@ from xml.etree import ElementTree as ETimport yaml-from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, is_hidden_from_assistantdef format_property_values(@@ -107,7 +107,7 @@ def enrich_props_with_descriptions(for prop_name, prop_type in props:description = Noneif entity_definition := entity_definitions.get(prop_name):- if entity_definition.get("system") or entity_definition.get("ignored_in_assistant"):+ if is_hidden_from_assistant(entity_definition):continuedescription = entity_definition.get("description_llm") or entity_definition.get("description")else:diff --git a/ee/hogai/utils/helpers.py b/ee/hogai/utils/helpers.pyindex 087ce2ba8ec9..b407d9446d66 100644--- a/ee/hogai/utils/helpers.py+++ b/ee/hogai/utils/helpers.py@@ -42,7 +42,7 @@ from posthog.hogql_queries.ai.team_taxonomy_query_runner import TeamTaxonomyQuerfrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models import Team, Userfrom posthog.settings import EE_AVAILABLE-from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, is_hidden_from_assistantfrom ee.hogai.utils.anthropic import SUPPORTED_ANTHROPIC_BLOCKSfrom ee.hogai.utils.types.base import (@@ -229,7 +229,7 @@ def _process_events_data(]for item in response.results:event_def = CORE_FILTER_DEFINITIONS_BY_GROUP.get("events", {}).get(item.event)- if event_def and (event_def.get("system") or event_def.get("ignored_in_assistant")):+ if event_def and is_hidden_from_assistant(event_def):continue # Skip system or ignored events (safety net, already filtered in SQL)events.append(item.event)@@ -255,9 +255,7 @@ def _process_events_data(if event_core_definition := CORE_FILTER_DEFINITIONS_BY_GROUP["events"].get(event_name):# Only skip if it's not in context (context events should always be included)- if event_name not in context_event_names and (- event_core_definition.get("system") or event_core_definition.get("ignored_in_assistant")- ):+ if event_name not in context_event_names and is_hidden_from_assistant(event_core_definition):continue # Skip irrelevant events but keep events the user has added to the contextif core_description := _format_core_event_description(event_core_definition):event_data["description"] = core_descriptiondiff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 85db34428c0e..a18f490c2fa4 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -1,4 +1,5 @@import re+from collections.abc import Iteratorfrom typing import Literal, NotRequired, TypedDictSTALE_EVENT_DAYS = 30@@ -20,6 +21,18 @@ class CoreFilterDefinition(TypedDict):primary_property: NotRequired[str]+def is_hidden_from_assistant(definition: CoreFilterDefinition) -> bool:+ """Whether an LLM prompt must leave this entry out."""+ return bool(definition.get("system") or definition.get("ignored_in_assistant"))+++def visible_definitions(group: str) -> Iterator[tuple[str, CoreFilterDefinition]]:+ """The entries of a taxonomy group that an LLM prompt may show."""+ for name, definition in CORE_FILTER_DEFINITIONS_BY_GROUP[group].items():+ if not is_hidden_from_assistant(definition):+ yield name, definition++"""Same as https://github.com/PostHog/posthog-js/blob/master/src/utils/event-utils.tsIdeally this would be imported from one place.@@ -3999,9 +4012,7 @@ PROPERTY_NAME_ALIASES_BY_TYPE: dict[str, dict[str, str]] = {}IGNORED_EVENT_NAMES: list[str] = [- name- for name, defn in CORE_FILTER_DEFINITIONS_BY_GROUP.get("events", {}).items()- if defn.get("system") or defn.get("ignored_in_assistant")+ name for name, defn in CORE_FILTER_DEFINITIONS_BY_GROUP.get("events", {}).items() if is_hidden_from_assistant(defn)]# Core PostHog events, derived from the taxonomy. Used to determine which eventsdiff --git a/products/cdp/backend/max_tools.py b/products/cdp/backend/max_tools.pyindex e739af5009b6..8dee549dec28 100644--- a/products/cdp/backend/max_tools.py+++ b/products/cdp/backend/max_tools.py@@ -13,21 +13,17 @@ from posthog.cdp.validation import compile_hogfrom products.cdp.backend.prompts import (DESTINATION_LIMITATIONS_MESSAGE,- EVENT_PROPERTY_TAXONOMY_MESSAGE,- EVENT_TAXONOMY_MESSAGE,- FILTER_TAXONOMY_MESSAGE,HOG_EXAMPLE_MESSAGE,HOG_FUNCTION_FILTERS_ASSISTANT_ROOT_SYSTEM_PROMPT,- HOG_FUNCTION_FILTERS_SYSTEM_PROMPT,HOG_FUNCTION_INPUTS_ASSISTANT_ROOT_SYSTEM_PROMPT,HOG_FUNCTION_INPUTS_SYSTEM_PROMPT,HOG_GRAMMAR_MESSAGE,HOG_TRANSFORMATION_ASSISTANT_ROOT_SYSTEM_PROMPT,IDENTITY_MESSAGE_HOG,INPUT_SCHEMA_TYPES_MESSAGE,- PERSON_TAXONOMY_MESSAGE,TRANSFORMATION_LIMITATIONS_MESSAGE,TRANSFORMATION_STRUCTURE_MESSAGE,+ render_filters_system_prompt,)from ee.hogai.chat_agent.schema_generator.parsers import PydanticOutputParserException@@ -165,23 +161,7 @@ class CreateHogFunctionFiltersTool(MaxTool):current_filters = self.context.get("current_filters", "{}")function_type = self.context.get("function_type", "destination")- system_content = (- HOG_FUNCTION_FILTERS_SYSTEM_PROMPT- + f"\n\nCurrent filters: {current_filters}"- + f"\nFunction type: {function_type}"- + "\n\n<event_taxonomy>\n"- + EVENT_TAXONOMY_MESSAGE- + "\n</event_taxonomy>\n\n"- + "\n\n<event_property_taxonomy>\n"- + EVENT_PROPERTY_TAXONOMY_MESSAGE- + "\n</event_property_taxonomy>\n\n"- + "\n\n<person_property_taxonomy>\n"- + PERSON_TAXONOMY_MESSAGE- + "\n</person_property_taxonomy>\n\n"- + "\n\n<filter_taxonomy>\n"- + FILTER_TAXONOMY_MESSAGE- + "\n</filter_taxonomy>"- )+ system_content = render_filters_system_prompt(function_type, current_filters)user_content = f"Create filters for this hog function: {instructions}"diff --git a/products/cdp/backend/prompts.py b/products/cdp/backend/prompts.pyindex 221ccc7fbe48..8f350cbe3f2f 100644--- a/products/cdp/backend/prompts.py+++ b/products/cdp/backend/prompts.py@@ -1,3 +1,53 @@+from collections.abc import Iterable, Iterator++# nosemgrep: python.lang.security.use-defused-xml.use-defused-xml (XML generation only, no parsing - no XXE risk)+from xml.etree import ElementTree as ET++from posthog.schema import PropertyOperator++from posthog.taxonomy.taxonomy import CoreFilterDefinition, visible_definitions++from products.cdp.backend.models.hog_functions.hog_function import TYPES_WITH_TRANSPILED_FILTERS, HogFunctionType++from ee.hogai.summarizers.property_filters import PROPERTY_FILTER_VERBOSE_NAME++# `flag_evaluates_to` compiles only on a `type: "flag"` filter. Hog function filters are only ever+# event, person, or group, and `property_to_expr` raises `NotImplementedError` for those.+UNSUPPORTED_FILTER_OPERATORS = frozenset({PropertyOperator.FLAG_EVALUATES_TO})++# These operators emit `sortableSemver` and `multiSearchAnyCaseInsensitive`, which the JavaScript+# STL never defines. On the types that transpile filters instead of compiling bytecode, a filter+# using one saves without error and then throws `ReferenceError` on the first event.+JS_UNSUPPORTED_FILTER_OPERATORS = frozenset(+ {+ PropertyOperator.SEMVER_EQ,+ PropertyOperator.SEMVER_NEQ,+ PropertyOperator.SEMVER_GT,+ PropertyOperator.SEMVER_GTE,+ PropertyOperator.SEMVER_LT,+ PropertyOperator.SEMVER_LTE,+ PropertyOperator.SEMVER_TILDE,+ PropertyOperator.SEMVER_CARET,+ PropertyOperator.SEMVER_WILDCARD,+ PropertyOperator.ICONTAINS_MULTI,+ PropertyOperator.NOT_ICONTAINS_MULTI,+ }+)++# Transformations run during ingestion against `TRANSFORMATION_AVAILABLE_GLOBALS`, which holds no+# `person` and no group slots, so a person or group filter evaluates against null and never matches.+# `HogFunctionFilters` hides those taxonomic groups for the same reason.+TYPES_WITHOUT_PERSON_GLOBALS = frozenset(+ {HogFunctionType.TRANSFORMATION.value, HogFunctionType.TRANSFORMATION_LOG.value}+)++# Stands in for <person_property_taxonomy> on the types that have no person globals.+EVENT_ONLY_FILTER_SCOPE = (+ "<filter_scope><usage>This function runs during ingestion, where only the event is in scope. "+ "Use `event` property filters only. A `person` or `group` filter saves without error and then "+ "matches nothing, so the function never runs.</usage></filter_scope>"+)+HOG_TRANSFORMATION_ASSISTANT_ROOT_SYSTEM_PROMPT = """The user is currently editing or creating a Hog transformation function. They expect your help with writing and tweaking Hog code.@@ -851,1751 +901,94 @@ These functions are not available in the current version of HogQL (NEVER USE THE- arrayConcat"""-EVENT_TAXONOMY_MESSAGE = """-Here is the taxonomy for events:-"events": {- # in front end this key is the empty string- "All events": {- "label": "All events",- "description": "This is a wildcard that matches all events.",- },- "$pageview": {- "label": "Pageview",- "description": "When a user loads (or reloads) a page.",- },- "$pageleave": {- "label": "Pageleave",- "description": "When a user leaves a page.",- },- "$autocapture": {- "label": "Autocapture",- "description": "User interactions that were automatically captured.",- "examples": ["clicked button"],- "ignored_in_assistant": True, # Autocapture is only useful with autocapture-specific filters, which the LLM isn't adept at yet- },- "$$heatmap": {- "label": "Heatmap",- "description": "Internal carrier for heatmap data. Routed to a separate heatmaps store during ingestion and do not contribute to event counts.",- "ignored_in_assistant": True, # Heatmap events are not useful for LLM- },- "$copy_autocapture": {- "label": "Clipboard autocapture",- "description": "Selected text automatically captured when a user copies or cuts.",- "ignored_in_assistant": True, # Too niche- },- "$screen": {- "label": "Screen",- "description": "When a user loads a screen in a mobile app.",- },- "$set": {- "label": "Set person properties",- "description": "Setting person properties. Sent as `$set`.",- "ignored_in_assistant": True,- },- "$opt_in": {- "label": "Opt in",- "description": "When a user opts into analytics.",- "ignored_in_assistant": True, # Irrelevant product-wise- },- "$feature_flag_called": {- "label": "Feature flag called",- "description": (- 'The feature flag that was called.\n\nWarning! This only works in combination with the $feature_flag event. If you want to filter other events, try "Active feature flags".'- ),- "examples": ["beta-feature"],- "ignored_in_assistant": True, # Mostly irrelevant product-wise- },- "$feature_view": {- "label": "Feature view",- "description": "When a user views a feature.",- "ignored_in_assistant": True, # Specific to posthog-js/react, niche- },- "$feature_interaction": {- "label": "Feature interaction",- "description": "When a user interacts with a feature.",- "ignored_in_assistant": True, # Specific to posthog-js/react, niche- },- "$feature_enrollment_update": {- "label": "Feature enrollment",- "description": "When a user enrolls with a feature.",- "description_llm": "When a user opts in or out of a beta feature. This event is specific to the PostHog Early Access Features product, and is only relevant if the project is using this product.",- },- "$capture_metrics": {- "label": "Capture metrics",- "description": "Metrics captured with values pertaining to your systems at a specific point in time.",- "ignored_in_assistant": True, # Irrelevant product-wise- },- "$identify": {- "label": "Identify",- "description": "A user has been identified with properties.",- "description_llm": "Identifies an anonymous user. The event shows how many users used an account, so do not use it for active users metrics because a user may skip identification.",- },- "$create_alias": {- "label": "Alias",- "description": "An alias ID has been added to a user.",- "ignored_in_assistant": True, # Irrelevant product-wise- },- "$merge_dangerously": {- "label": "Merge",- "description": "An alias ID has been added to a user.",- "ignored_in_assistant": True, # Irrelevant product-wise- },- "$groupidentify": {- "label": "Group identify",- "description": "A group has been identified with properties.",- "ignored_in_assistant": True, # Irrelevant product-wise- },- "$rageclick": {- "label": "Rageclick",- "description": "A user has rapidly and repeatedly clicked in a single place.",- },- "$dead_click": {- "label": "Dead click",- "description": "A user has clicked on something that is probably not clickable.",- },- "$exception": {- "label": "Exception",- "description": "An unexpected error or unhandled exception in your application.",- },- "$web_vitals": {- "label": "Web vitals",- "description": "Automatically captured web vitals data.",- },- "$ai_generation": {- "label": "AI generation (LLM)",- "description": "A call to an LLM model. Contains the input prompt, output, model used and costs.",- },- "$ai_metric": {- "label": "AI metric (LLM)",- "description": "An evaluation metric for a trace of a generative AI model (LLM). Contains the trace ID, metric name, and metric value.",- },- "$ai_feedback": {- "label": "AI feedback (LLM)",- "description": "User-provided feedback for a trace of a generative AI model (LLM).",- },- "$ai_trace": {- "label": "AI trace (LLM)",- "description": "A generative AI trace. Usually a trace tracks a single user interaction and contains one or more AI generation calls.",- },- "$ai_span": {- "label": "AI span (LLM)",- "description": "A generative AI span. Usually a span tracks a unit of work for a trace of generative AI models (LLMs).",- },- "$ai_embedding": {- "label": "AI embedding (LLM)",- "description": "A call to an embedding model.",- },- "$csp_violation": {- "label": "CSP violation",- "description": "Content Security Policy violation reported by a browser to our csp endpoint.",- "examples": ["Unauthorized inline script", "Trying to load resources from unauthorized domain"],- },- "Application opened": {- "label": "Application opened",- "description": "When a user opens the mobile app either for the first time or from the foreground.",- },- "Application backgrounded": {- "label": "Application backgrounded",- "description": "When a user puts the mobile app in the background.",- },- "Application updated": {- "label": "Application updated",- "description": "When a user upgrades the mobile app.",- },- "Application installed": {- "label": "Application installed",- "description": "When a user installs the mobile app.",- },- "Application became active": {- "label": "Application became active",- "description": "When a user puts the mobile app in the foreground.",- },- "Deep link opened": {- "label": "Deep link opened",- "description": "When a user opens the mobile app via a deep link.",- },- },-"""-EVENT_METADATA_TAXONOMY = """-"metadata": {- "distinct_id": {- "label": "Distinct ID",- "description": "The current distinct ID of the user.",- "examples": ["16ff262c4301e5-0aa346c03894bc-39667c0e-1aeaa0-16ff262c431767"],- },- "timestamp": {- "label": "Timestamp",- "description": "Time the event happened.",- "examples": ["2023-05-20T15:30:00Z"],- },- "event": {- "label": "Event",- "description": "The name of the event.",- "examples": ["$pageview"],- },- "person_id": {- "label": "Person ID",- "description": "The ID of the person, depending on the person properties mode.",- "examples": ["16ff262c4301e5-0aa346c03894bc-39667c0e-1aeaa0-16ff262c431767"],- },- },-"""+def _render_taxonomy_group(+ definitions: Iterable[tuple[str, CoreFilterDefinition]], root_tag: str, entry_tag: str+) -> str:+ root = ET.Element(root_tag)+ for name, definition in definitions:+ entry = ET.SubElement(root, entry_tag)+ ET.SubElement(entry, "name").text = name+ if prop_type := definition.get("type"):+ ET.SubElement(entry, "type").text = prop_type+ if description := (+ definition.get("description_llm") or definition.get("description") or definition.get("label")+ ):+ ET.SubElement(entry, "description").text = description+ if examples := definition.get("examples"):+ ET.SubElement(entry, "examples").text = ", ".join(str(example) for example in examples)+ return ET.tostring(root, encoding="unicode")+++def render_event_taxonomy() -> str:+ return _render_taxonomy_group(visible_definitions("events"), "event_taxonomy", "event")+++def _filterable_event_properties() -> Iterator[tuple[str, CoreFilterDefinition]]:+ """Event properties a hog function filter can resolve, so the two the compiler mishandles are out."""+ for name, definition in visible_definitions("event_properties"):+ # A virtual property (e.g. `$virt_is_bot`) compiles to a bare top-level global the CDP+ # filter globals never define, so a filter on one throws at runtime. `distinct_id` compiles+ # to `properties.distinct_id`, but CDP stores the identifier at the top level, so an+ # event-type filter on it always evaluates false; `property_to_expr` special-cases+ # `type: "person", key: "distinct_id"`, so the person block is where it stays described.+ if definition.get("virtual") or name == "distinct_id":+ continue+ yield name, definition+++def render_event_property_taxonomy() -> str:+ return _render_taxonomy_group(_filterable_event_properties(), "event_property_taxonomy", "property")+++def render_person_property_taxonomy() -> str:+ # The taxonomy copies almost every event property onto the person, so a description here would+ # repeat <event_property_taxonomy> and nearly double the prompt. Describe only the names that+ # section does not carry, because the model has nowhere else to read their meaning.+ event_property_names = {name for name, _ in _filterable_event_properties()}+ root = ET.Element("person_property_taxonomy")+ ET.SubElement(root, "usage").text = (+ "A person property named like an event property means the same thing, so read its "+ "description in <event_property_taxonomy>. A `$initial_` prefix means the value from the "+ "first time the person was seen; without it, the value from the most recent time."+ )+ for name, definition in visible_definitions("person_properties"):+ # Virtual properties are computed in HogQL and are absent from the person record a hog+ # function filters against, so a filter on one saves cleanly and then never matches.+ if definition.get("virtual"):+ continue+ entry = ET.SubElement(root, "property")+ ET.SubElement(entry, "name").text = name+ if prop_type := definition.get("type"):+ ET.SubElement(entry, "type").text = prop_type+ if _is_person_only(name, event_property_names):+ if description := (definition.get("description_llm") or definition.get("description")):+ ET.SubElement(entry, "description").text = description+ return ET.tostring(root, encoding="unicode")+++def _is_person_only(name: str, event_property_names: set[str]) -> bool:+ """True when the name has no counterpart in the event property taxonomy, in either form."""+ base = name.removeprefix("$initial_")+ return (+ name not in event_property_names and base not in event_property_names and f"${base}" not in event_property_names+ )-EVENT_PROPERTY_TAXONOMY_MESSAGE = """-Here is the taxonomy for event properties:-"event_properties": {- "$config_defaults": {- "label": "Config defaults",- "description": "The version of the PostHog config defaults that were used when capturing the event.",- "type": "String",- },- "$python_runtime": {- "label": "Python runtime",- "description": "The Python runtime that was used to capture the event.",- "examples": ["CPython"],- },- "$python_version": {- "label": "Python version",- "description": "The Python version that was used to capture the event.",- "examples": ["3.11.5"],- },- "$go_version": {- "label": "Go version",- "description": "The Go version that was used to capture the event.",- "examples": ["go1.23.0"],- },- "$sdk_debug_replay_internal_buffer_length": {- "label": "Replay internal buffer length",- "description": "Useful for debugging. The internal buffer length for replay.",- "examples": ["100"],- },- "$sdk_debug_replay_internal_buffer_size": {- "label": "Replay internal buffer size",- "description": "Useful for debugging. The internal buffer size for replay.",- "examples": ["100"],- },- "$sdk_debug_retry_queue_size": {- "label": "Retry queue size",- "description": "Useful for debugging. The size of the retry queue.",- "examples": ["100"],- },- "$last_posthog_reset": {- "label": "Timestamp of last call to `Reset` in the web sdk",- "description": "The timestamp of the last call to `Reset` in the web SDK. This can be useful for debugging.",- "ignored_in_assistant": True,- },- # do we need distinct_id and $session_duration here in the back end?- "$copy_type": {- "label": "Copy type",- "description": "Type of copy event.",- "examples": ["copy", "cut"],- "ignored_in_assistant": True,- },- "$selected_content": {- "label": "Copied content",- "description": "The content that was selected when the user copied or cut.",- "ignored_in_assistant": True,- },- "$set": {- "label": "Set person properties",- "description": "Person properties to be set. Sent as `$set`.",- "ignored_in_assistant": True,- },- "$set_once": {- "label": "Set person properties once",- "description": "Person properties to be set if not set already (i.e. first-touch). Sent as `$set_once`.",- "ignored_in_assistant": True,- },- "$pageview_id": {- "label": "Pageview ID",- "description": "PostHog's internal ID for matching events to a pageview.",- },- "$autocapture_disabled_server_side": {- "label": "Autocapture disabled server-side",- "description": "If autocapture has been disabled server-side.",- },- "$console_log_recording_enabled_server_side": {- "label": "Console log recording enabled server-side",- "description": "If console log recording has been enabled server-side.",- },- "$session_entry__kx": {- "description": "Klaviyo Tracking ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry _kx",- },- "$session_entry_dclid": {- "description": "DoubleClick ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry dclid",- },- "$session_entry_epik": {- "description": "Pinterest Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry epik",- },- "$session_entry_fbclid": {- "description": "Facebook Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry fbclid",- },- "$session_entry_gad_source": {- "description": "Google Ads Source Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry gad_source",- },- "$session_entry_gbraid": {- "description": "Google Ads, web to app Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry gbraid",- },- "$session_entry_gclid": {- "description": "Google Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry gclid",- },- "$session_entry_gclsrc": {- "description": "Google Click Source Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry gclsrc",- },- "$session_entry_host": {- "description": "The hostname of the Current URL. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["example.com", "localhost:8000"],- "label": "Session entry Host",- },- "$session_entry_igshid": {- "description": "Instagram Share ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry igshid",- },- "$session_entry_irclid": {- "description": "Impact Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry irclid",- },- "$session_entry_li_fat_id": {- "description": "LinkedIn First-Party Ad Tracking ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry li_fat_id",- },- "$session_entry_mc_cid": {- "description": "Mailchimp Campaign ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry mc_cid",- },- "$session_entry_msclkid": {- "description": "Microsoft Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry msclkid",- },- "$session_entry_pathname": {- "description": "The path of the Current URL, which means everything in the url after the domain. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["/pricing", "/about-us/team"],- "label": "Session entry Path name",- },- "$session_entry_qclid": {- "description": "Quora Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry qclid",- },- "$session_entry_rdt_cid": {- "description": "Reddit Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry rdt_cid",- },- "$session_entry_referrer": {- "description": "URL of where the user came from. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["https://google.com/search?q=posthog&rlz=1C..."],- "label": "Session entry Referrer URL",- },- "$session_entry_referring_domain": {- "description": "Domain of where the user came from. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["google.com", "facebook.com"],- "label": "Session entry Referring domain",- },- "$session_entry_sccid": {- "description": "Snapchat Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry sccid",- },- "$session_entry_ttclid": {- "description": "TikTok Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry ttclid",- },- "$session_entry_twclid": {- "description": "Twitter Click ID Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry twclid",- },- "$session_entry_url": {- "description": "The URL visited at the time of the event. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["https://example.com/interesting-article?parameter=true"],- "label": "Session entry Current URL",- },- "$session_entry_utm_campaign": {- "description": "UTM campaign tag. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["feature launch", "discount"],- "label": "Session entry UTM campaign",- },- "$session_entry_utm_content": {- "description": "UTM content tag. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["bottom link", "second button"],- "label": "Session entry UTM content",- },- "$session_entry_utm_medium": {- "description": "UTM medium tag. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["Social", "Organic", "Paid", "Email"],- "label": "Session entry UTM medium",- },- "$session_entry_utm_source": {- "description": "UTM source tag. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["Google", "Bing", "Twitter", "Facebook"],- "label": "Session entry UTM source",- },- "$session_entry_utm_term": {- "description": "UTM term tag. Captured at the start of the session and remains constant for the duration of the session.",- "examples": ["free goodies"],- "label": "Session entry UTM term",- },- "$session_entry_wbraid": {- "description": "Google Ads, app to web Captured at the start of the session and remains constant for the duration of the session.",- "label": "Session entry wbraid",- },- "$session_recording_recorder_version_server_side": {- "label": "Session recording recorder version server-side",- "description": "The version of the session recording recorder that is enabled server-side.",- "examples": ["v2"],- },- "$session_is_sampled": {- "label": "Whether the session is sampled",- "description": "Whether the session is sampled for session recording.",- "examples": ["true", "false"],- },- "$feature_flag_payloads": {- "label": "Feature flag payloads",- "description": "Feature flag payloads active in the environment.",- },- "$capture_failed_request": {- "label": "Capture failed request",- "description": "",- },- "$lib_rate_limit_remaining_tokens": {- "label": "Clientside rate limit remaining tokens",- "description": "Remaining rate limit tokens for the posthog-js library client-side rate limiting implementation.",- "examples": ["100"],- },- "token": {- "label": "Token",- "description": "Token used for authentication.",- "examples": ["ph_abcdefg"],- },- "$sentry_exception": {- "label": "Sentry exception",- "description": "Raw Sentry exception data.",- },- "$sentry_exception_message": {- "label": "Sentry exception message",- },- "$sentry_exception_type": {- "label": "Sentry exception type",- "description": "Class name of the exception object.",- },- "$sentry_tags": {- "label": "Sentry tags",- "description": "Tags sent to Sentry along with the exception.",- },- "$exception_types": {- "label": "Exception type",- "description": "The type of the exception.",- "examples": ["TypeError"],- },- "$exception_functions": {- "label": "Exception function",- "description": "A function contained in the exception.",- },- "$exception_values": {"label": "Exception message", "description": "The description of the exception."},- "$exception_sources": {"label": "Exception source", "description": "A source file included in the exception."},- "$exception_steps": {- "label": "Exception steps",- "description": "Application-defined steps captured before the exception to provide context about the actions leading up to it.",- "system": True,- },- "$exception_list": {- "label": "Exception list",- "description": "List of one or more associated exceptions.",- },- "$exception_level": {- "label": "Exception level",- "description": "Exception categorized by severity.",- "examples": ["error"],- },- "$exception_fingerprint": {- "label": "Exception fingerprint",- "description": "A fingerprint used to group issues, can be set clientside.",- },- "$exception_fingerprint_version": {- "label": "Exception fingerprint version",- "description": "The version of the fingerprinting algorithm used to group the exception.",- "system": True,- },- "$exception_issue_id": {- "label": "Exception issue ID",- "description": "The id of the issue the fingerprint was associated with at ingest time.",- },- "$exception_source": {- "label": "Exception capture source",- "description": "The SDK integration or runtime hook that captured the exception.",- "examples": ["panic", "rails", "php_exception_handler"],- },- "$exception_handled": {- "label": "Exception was handled",- "description": "Whether this was a handled or unhandled exception.",- },- "$cymbal_errors": {- "label": "Exception processing errors",- "description": "Errors encountered while trying to process exceptions.",- },- "$exception_capture_enabled_server_side": {- "label": "Exception capture enabled server side",- "description": "Whether exception autocapture was enabled in remote config.",- },- "$ce_version": {- "label": "$ce_version",- "description": "",- },- "$anon_distinct_id": {- "label": "Anon distinct ID",- "description": "If the user was previously anonymous, their anonymous ID will be set here.",- "examples": ["16ff262c4301e5-0aa346c03894bc-39667c0e-1aeaa0-16ff262c431767"],- },- "$event_type": {- "label": "Event type",- "description": "When the event is an $autocapture event, this specifies what the action was against the element.",- "examples": ["click", "submit", "change"],- },- "$insert_id": {- "label": "Insert ID",- "description": "Unique insert ID for the event.",- },- "$time": {- "label": "$time (deprecated)",- "description": "Use the SQL field `timestamp` instead. This field was previously set on some client side events.",- "examples": ["1681211521.345"],- },- "$browser_type": {- "label": "Browser type",- "description": "This is only added when posthog-js config.opt_out_useragent_filter is true.",- "examples": ["browser", "bot"],- },- "$device_id": {- "label": "Device ID",- "description": "Unique ID for that device, consistent even if users are logging in/out.",- "examples": ["16ff262c4301e5-0aa346c03894bc-39667c0e-1aeaa0-16ff262c431767"],- },- "$replay_minimum_duration": {- "label": "Replay config - minimum duration",- "description": "Config for minimum duration before emitting a session recording.",- "examples": ["1000"],- },- "$replay_sample_rate": {- "label": "Replay config - sample rate",- "description": "Config for sampling rate of session recordings.",- "examples": ["0.1"],- },- "$session_recording_start_reason": {- "label": "Session recording start reason",- "description": "Reason for starting the session recording. Useful for e.g. if you have sampling enabled and want to see on batch exported events which sessions have recordings available.",- "examples": ["sampling_override", "recording_initialized", "linked_flag_match"],- },- "$session_recording_canvas_recording": {- "label": "Session recording canvas recording",- "description": "Session recording canvas capture config.",- "examples": ['{"enabled": false}'],- },- "$session_recording_network_payload_capture": {- "label": "Session recording network payload capture",- "description": "Session recording network payload capture config.",- "examples": ['{"recordHeaders": false}'],- },- "$configured_session_timeout_ms": {- "label": "Configured session timeout",- "description": "Configured session timeout in milliseconds.",- "examples": ["1800000"],- },- "$replay_script_config": {- "label": "Replay script config",- "description": "Sets an alternative recorder script for the web sdk.",- "examples": ['{"script": "recorder-next"}'],- },- "$session_recording_url_trigger_activated_session": {- "label": "Session recording URL trigger activated session",- "description": "Session recording URL trigger activated session config. Used by posthog-js to track URL activation of session replay.",- },- "$session_recording_url_trigger_status": {- "label": "Session recording URL trigger status",- "description": "Session recording URL trigger status. Used by posthog-js to track URL activation of session replay.",- },- "$recording_status": {- "label": "Session recording status",- "description": "The status of session recording at the time the event was captured",- },- "$cymbal_errors": {- "label": "Exception processing errors",- "description": "Errors encountered while trying to process exceptions.",- },- "$geoip_city_name": {- "label": "City name",- "description": "Name of the city matched to this event's IP address.",- "examples": ["Sydney", "Chennai", "Brooklyn"],- },- "$geoip_country_name": {- "label": "Country name",- "description": "Name of the country matched to this event's IP address.",- "examples": ["Australia", "India", "United States"],- },- "$geoip_country_code": {- "label": "Country code",- "description": "Code of the country matched to this event's IP address.",- "examples": ["AU", "IN", "US"],- },- "$geoip_continent_name": {- "label": "Continent name",- "description": "Name of the continent matched to this event's IP address.",- "examples": ["Oceania", "Asia", "North America"],- },- "$geoip_continent_code": {- "label": "Continent code",- "description": "Code of the continent matched to this event's IP address.",- "examples": ["OC", "AS", "NA"],- },- "$geoip_postal_code": {- "label": "Postal code",- "description": "Approximated postal code matched to this event's IP address.",- "examples": ["2000", "600004", "11211"],- },- "$geoip_postal_code_confidence": {- "label": "Postal code identification confidence score",- "description": "If provided by the licensed geoip database",- "examples": ["null", "0.1"],- },- "$geoip_latitude": {- "label": "Latitude",- "description": "Approximated latitude matched to this event's IP address.",- "examples": ["-33.8591", "13.1337", "40.7"],- },- "$geoip_longitude": {- "label": "Longitude",- "description": "Approximated longitude matched to this event's IP address.",- "examples": ["151.2", "80.8008", "-73.9"],- },- "$geoip_time_zone": {- "label": "Timezone",- "description": "Timezone matched to this event's IP address.",- "examples": ["Australia/Sydney", "Asia/Kolkata", "America/New_York"],- },- "$geoip_subdivision_1_name": {- "label": "Subdivision 1 name",- "description": "Name of the subdivision matched to this event's IP address.",- "examples": ["New South Wales", "Tamil Nadu", "New York"],- },- "$geoip_subdivision_1_code": {- "label": "Subdivision 1 code",- "description": "Code of the subdivision matched to this event's IP address.",- "examples": ["NSW", "TN", "NY"],- },- "$geoip_subdivision_2_name": {- "label": "Subdivision 2 name",- "description": "Name of the second subdivision matched to this event's IP address.",- },- "$geoip_subdivision_2_code": {- "label": "Subdivision 2 code",- "description": "Code of the second subdivision matched to this event's IP address.",- },- "$geoip_subdivision_2_confidence": {- "label": "Subdivision 2 identification confidence score",- "description": "If provided by the licensed geoip database",- "examples": ["null", "0.1"],- },- "$geoip_subdivision_3_name": {- "label": "Subdivision 3 name",- "description": "Name of the third subdivision matched to this event's IP address.",- },- "$geoip_subdivision_3_code": {- "label": "Subdivision 3 code",- "description": "Code of the third subdivision matched to this event's IP address.",- },- "$geoip_disable": {- "label": "GeoIP disabled",- "description": "Whether to skip GeoIP processing for the event.",- },- "$geoip_city_confidence": {- "label": "GeoIP detection city confidence",- "description": "Confidence level of the city matched to this event's IP address.",- "examples": ["0.5"],- },- "$geoip_country_confidence": {- "label": "GeoIP detection country confidence",- "description": "Confidence level of the country matched to this event's IP address.",- "examples": ["0.5"],- },- "$geoip_accuracy_radius": {- "label": "GeoIP detection accuracy radius",- "description": "Accuracy radius of the location matched to this event's IP address (in kilometers).",- "examples": ["50"],- },- "$geoip_subdivision_1_confidence": {- "label": "GeoIP detection subdivision 1 confidence",- "description": "Confidence level of the first subdivision matched to this event's IP address.",- "examples": ["0.5"],- },- "$el_text": {- "label": "Element text",- "description": "The text of the element that was clicked. Only sent with Autocapture events.",- "examples": ["Click here!"],- },- "$app_build": {- "label": "App build",- "description": "The build number for the app.",- },- "$app_name": {- "label": "App name",- "description": "The name of the app.",- },- "$app_namespace": {- "label": "App namespace",- "description": "The namespace of the app as identified in the app store.",- "examples": ["com.posthog.app"],- },- "$app_version": {- "label": "App version",- "description": "The version of the app.",- },- "$device_manufacturer": {- "label": "Device manufacturer",- "description": "The manufacturer of the device",- "examples": ["Apple", "Samsung"],- },- "$device_name": {- "label": "Device name",- "description": "Name of the device",- "examples": ["iPhone 12 Pro", "Samsung Galaxy 10"],- },- "$is_emulator": {- "label": "Is emulator",- "description": "Indicates whether the app is running on an emulator or a physical device",- "examples": ["true", "false"],- },- "$is_mac_catalyst_app": {- "label": "Is Mac Catalyst app",- "description": "Indicates whether the app is a Mac Catalyst app running on macOS",- "examples": ["true", "false"],- },- "$is_ios_running_on_mac": {- "label": "Is iOS app running on Mac",- "description": "Indicates whether the app is an iOS app running on macOS (Apple Silicon)",- "examples": ["true", "false"],- },- "$locale": {- "label": "Locale",- "description": "The locale of the device",- "examples": ["en-US", "de-DE"],- },- "$os_name": {- "label": "OS name",- "description": "The Operating System name",- "examples": ["iOS", "Android"],- },- "$os_version": {- "label": "OS version",- "description": "The Operating System version.",- "examples": ["15.5"],- },- "$os_distro": {- "label": "OS distro",- "description": "The distribution name in case of Linux.",- "examples": ["Ubuntu", "Debian", "Fedora"],- },- "$timezone": {- "label": "Timezone",- "description": "The timezone as reported by the device",- },- "$timezone_offset": {- "label": "Timezone offset",- "description": "The timezone offset, as reported by the device. Minutes difference from UTC.",- "type": "Numeric",- },- "$touch_x": {- "label": "Touch X",- "description": "The location of a Touch event on the X axis",- },- "$touch_y": {- "label": "Touch Y",- "description": "The location of a Touch event on the Y axis",- },- "$plugins_succeeded": {- "label": "Plugins succeeded",- "description": "Plugins that successfully processed the event, e.g. edited properties (plugin method `processEvent`).",- },- "$groups": {- "label": "Groups",- "description": "Relevant groups",- },- "$group_0": {- "label": "Group 1",- },- "$group_1": {- "label": "Group 2",- },- "$group_2": {- "label": "Group 3",- },- "$group_3": {- "label": "Group 4",- },- "$group_4": {- "label": "Group 5",- },- "$group_set": {- "label": "Group set",- "description": "Group properties to be set",- },- "$group_key": {- "label": "Group key",- "description": "Specified group key",- },- "$group_type": {- "label": "Group type",- "description": "Specified group type",- },- "$window_id": {- "label": "Window ID",- "description": "Unique window ID for session recording disambiguation",- },- "$session_id": {- "label": "Session ID",- "description": "Unique session ID for session recording disambiguation",- },- "$plugins_failed": {- "label": "Plugins failed",- "description": "Plugins that failed to process the event (plugin method `processEvent`).",- },- "$plugins_deferred": {- "label": "Plugins deferred",- "description": "Plugins to which the event was handed off post-ingestion, e.g. for export (plugin method `onEvent`).",- },- "$$plugin_metrics": {- "label": "Plugin metric",- "description": "Performance metrics for a given plugin.",- },- "$creator_event_uuid": {- "label": "Creator event ID",- "description": "Unique ID for the event, which created this person.",- "examples": ["16ff262c4301e5-0aa346c03894bc-39667c0e-1aeaa0-16ff262c431767"],- },- "utm_source": {- "label": "UTM source",- "description": "UTM source tag.",- "examples": ["Google", "Bing", "Twitter", "Facebook"],- },- "$initial_utm_source": {- "label": "Initial UTM source",- "description": "UTM source tag.",- "examples": ["Google", "Bing", "Twitter", "Facebook"],- },- "utm_medium": {- "label": "UTM medium",- "description": "UTM medium tag.",- "examples": ["Social", "Organic", "Paid", "Email"],- },- "utm_campaign": {- "label": "UTM campaign",- "description": "UTM campaign tag.",- "examples": ["feature launch", "discount"],- },- "utm_name": {- "label": "UTM name",- "description": "UTM campaign tag, sent via Segment.",- "examples": ["feature launch", "discount"],- },- "utm_content": {- "label": "UTM content",- "description": "UTM content tag.",- "examples": ["bottom link", "second button"],- },- "utm_term": {- "label": "UTM term",- "description": "UTM term tag.",- "examples": ["free goodies"],- },- "$performance_page_loaded": {- "label": "Page loaded",- "description": "The time taken until the browser's page load event in milliseconds.",- },- "$performance_raw": {- "label": "Browser performance",- "description": "The browser performance entries for navigation (the page), paint, and resources. That were available when the page view event fired",- },- "$had_persisted_distinct_id": {- "label": "$had_persisted_distinct_id",- "description": "",- },- "$sentry_event_id": {- "label": "Sentry event ID",- "description": "This is the Sentry key for an event.",- "examples": ["byroc2ar9ee4ijqp"],- },- "$timestamp": {- "label": "Timestamp (deprecated)",- "description": "Use the SQL field `timestamp` instead. This field was previously set on some client side events.",- "examples": ["2023-05-20T15:30:00Z"],- },- "$sent_at": {- "label": "Sent at",- "description": "Time the event was sent to PostHog. Used for correcting the event timestamp when the device clock is off.",- "examples": ["2023-05-20T15:31:00Z"],- },- "$browser": {- "label": "Browser",- "description": "Name of the browser the user has used.",- "examples": ["Chrome", "Firefox"],- },- "$os": {- "label": "OS",- "description": "The operating system of the user.",- "examples": ["Windows", "Mac OS X"],- },- "$browser_language": {- "label": "Browser language",- "description": "Language.",- "examples": ["en", "en-US", "cn", "pl-PL"],- },- "$browser_language_prefix": {- "label": "Browser language prefix",- "description": "Language prefix.",- "examples": [- "en",- "ja",- ],- },- "$current_url": {- "label": "Current URL",- "description": "The URL visited at the time of the event.",- "examples": ["https://example.com/interesting-article?parameter=true"],- },- "$browser_version": {- "label": "Browser version",- "description": "The version of the browser that was used. Used in combination with Browser.",- "examples": ["70", "79"],- },- "$raw_user_agent": {- "label": "Raw user agent",- "description": "PostHog process information like browser, OS, and device type from the user agent string. This is the raw user agent string.",- "examples": ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko)"],- },- "$user_agent": {- "label": "Raw user agent",- "description": "Some SDKs (like Android) send the raw user agent as $user_agent.",- "examples": ["Dalvik/2.1.0 (Linux; U; Android 11; Pixel 3 Build/RQ2A.210505.002)"],- },- "$screen_height": {- "label": "Screen height",- "description": "The height of the user's entire screen (in pixels).",- "examples": ["2160", "1050"],- },- "$screen_width": {- "label": "Screen width",- "description": "The width of the user's entire screen (in pixels).",- "examples": ["1440", "1920"],- },- "$screen_name": {- "label": "Screen name",- "description": "The name of the active screen.",- },- "$viewport_height": {- "label": "Viewport height",- "description": "The height of the user's actual browser window (in pixels).",- "examples": ["2094", "1031"],- },- "$viewport_width": {- "label": "Viewport width",- "description": "The width of the user's actual browser window (in pixels).",- "examples": ["1439", "1915"],- },- "$lib": {- "label": "Library",- "description": "What library was used to send the event.",- "examples": ["web", "posthog-ios"],- },- "$lib_custom_api_host": {- "label": "Library custom API host",- "description": "The custom API host used to send the event.",- "examples": ["https://ph.example.com"],- },- "$lib_version": {- "label": "Library version",- "description": "Version of the library used to send the event. Used in combination with Library.",- "examples": ["1.0.3"],- },- "$lib_version__major": {- "label": "Library version (major)",- "description": "Major version of the library used to send the event.",- "examples": [1],- },- "$lib_version__minor": {- "label": "Library version (minor)",- "description": "Minor version of the library used to send the event.",- "examples": [0],- },- "$lib_version__patch": {- "label": "Library version (patch)",- "description": "Patch version of the library used to send the event.",- "examples": [3],- },- "$referrer": {- "label": "Referrer URL",- "description": "URL of where the user came from.",- "examples": ["https://google.com/search?q=posthog&rlz=1C..."],- },- "$referring_domain": {- "label": "Referring domain",- "description": "Domain of where the user came from.",- "examples": ["google.com", "facebook.com"],- },- "$user_id": {- "label": "User ID",- "description": "This variable will be set to the distinct ID if you've called `posthog.identify('distinct id')`. If the user is anonymous, it'll be empty.",- },- "$ip": {- "label": "IP address",- "description": "IP address for this user when the event was sent.",- "examples": ["203.0.113.0"],- },- "$host": {- "label": "Host",- "description": "The hostname of the Current URL.",- "examples": ["example.com", "localhost:8000"],- },- "$pathname": {- "label": "Path name",- "description": "The path of the Current URL, which means everything in the url after the domain.",- "examples": ["/pricing", "/about-us/team"],- },- "$search_engine": {- "label": "Search engine",- "description": "The search engine the user came in from (if any).",- "examples": ["Google", "DuckDuckGo"],- },- "$active_feature_flags": {- "label": "Active feature flags",- "description": "Keys of the feature flags that were active while this event was sent.",- "examples": ["['beta-feature']"],- },- "$enabled_feature_flags": {- "label": "Enabled feature flags",- "description": "Keys and multivariate values of the feature flags that were active while this event was sent.",- "examples": ['{"flag": "value"}'],- },- "$feature_flag_response": {- "label": "Feature flag response",- "description": "What the call to feature flag responded with.",- "examples": ["true", "false"],- },- "$feature_flag_payload": {- "label": "Feature flag response payload",- "description": "The JSON payload that the call to feature flag responded with (if any)",- "examples": ['{"variant": "test"}'],- },- "$feature_flag": {- "label": "Feature flag",- "description": 'The feature flag that was called.\n\nWarning! This only works in combination with the $feature_flag_called event. If you want to filter other events, try "Active feature flags".',- "examples": ["beta-feature"],- },- "$feature_flag_reason": {- "label": "Feature flag evaluation reason",- "description": "The reason the feature flag was matched or not matched.",- "examples": ["Matched condition set 1"],- },- "$feature_flag_request_id": {- "label": "Feature flag request ID",- "description": "The unique identifier for the request that retrieved this feature flag result.\n\nNote: Primarily used by PostHog support for debugging issues with feature flags.",- "examples": ["01234567-89ab-cdef-0123-456789abcdef"],- },- "$feature_flag_evaluated_at": {- "label": "Feature flag evaluated at",- "description": "The timestamp (in milliseconds since Unix epoch) when the feature flag was evaluated.",- "examples": ["1732051200000"],- },- "$feature_flag_version": {- "label": "Feature flag version",- "description": "The version of the feature flag that was called.",- "examples": ["3"],- },- "$survey_response": {- "label": "Survey response",- "description": "The response value for the first question in the survey.",- "examples": ["I love it!", 5, "['choice 1', 'choice 3']"],- },- "$survey_name": {- "label": "Survey name",- "description": "The name of the survey.",- "examples": ["Product Feedback for New Product", "Home page NPS"],- },- "$survey_questions": {- "label": "Survey questions",- "description": "The questions asked in the survey.",- },- "$survey_id": {- "label": "Survey ID",- "description": "The unique identifier for the survey.",- },- "$survey_iteration": {- "label": "Survey iteration number",- "description": "The iteration number for the survey.",- },- "$survey_iteration_start_date": {- "label": "Survey iteration start date",- "description": "The start date for the current iteration of the survey.",- },- "$survey_submission_id": {- "description": "The unique identifier for the survey submission. Relevant for partial submissions, as they submit multiple 'survey sent' events. This is what allows us to count them as a single submission.",- "label": "Survey submission ID",- },- "$survey_completed": {- "description": "If a survey was fully completed (all questions answered), this will be true.",- "label": "Survey completed",- },- "$survey_partially_completed": {- "description": "If a survey was partially completed (some questions answered) on dismissal, this will be true.",- "label": "Survey partially completed",- },- "$device": {- "label": "Device",- "description": "The mobile device that was used.",- "examples": ["iPad", "iPhone", "Android"],- },- "$sentry_url": {- "label": "Sentry URL",- "description": "Direct link to the exception in Sentry",- "examples": ["https://sentry.io/..."],- },- "$device_type": {- "label": "Device type",- "description": "The type of device that was used.",- "examples": ["Mobile", "Tablet", "Desktop"],- },- "$screen_density": {- "label": "Screen density",- "description": 'The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system\'s display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.',- "examples": [2.75],- },- "$device_model": {- "label": "Device model",- "description": "The model of the device that was used.",- "examples": ["iPhone9,3", "SM-G965W"],- },- "$network_wifi": {- "label": "Network WiFi",- "description": "Whether the user was on WiFi when the event was sent.",- "examples": ["true", "false"],- },- "$network_bluetooth": {- "label": "Network Bluetooth",- "description": "Whether the user was on Bluetooth when the event was sent.",- "examples": ["true", "false"],- },- "$network_cellular": {- "label": "Network Cellular",- "description": "Whether the user was on cellular when the event was sent.",- "examples": ["true", "false"],- },- "$client_session_initial_referring_host": {- "label": "Referrer host",- "description": "Host that the user came from. (First-touch, session-scoped)",- "examples": ["google.com", "facebook.com"],- },- "$client_session_initial_pathname": {- "label": "Initial path",- "description": "Path that the user started their session on. (First-touch, session-scoped)",- "examples": ["/register", "/some/landing/page"],- },- "$client_session_initial_utm_source": {- "label": "Initial UTM source",- "description": "UTM Source. (First-touch, session-scoped)",- "examples": ["Google", "Bing", "Twitter", "Facebook"],- },- "$client_session_initial_utm_campaign": {- "label": "Initial UTM campaign",- "description": "UTM Campaign. (First-touch, session-scoped)",- "examples": ["feature launch", "discount"],- },- "$client_session_initial_utm_medium": {- "label": "Initial UTM medium",- "description": "UTM Medium. (First-touch, session-scoped)",- "examples": ["Social", "Organic", "Paid", "Email"],- },- "$client_session_initial_utm_content": {- "label": "Initial UTM source",- "description": "UTM Source. (First-touch, session-scoped)",- "examples": ["bottom link", "second button"],- },- "$client_session_initial_utm_term": {- "label": "Initial UTM term",- "description": "UTM term. (First-touch, session-scoped)",- "examples": ["free goodies"],- },- "$network_carrier": {- "label": "Network carrier",- "description": "The network carrier that the user is on.",- "examples": ["cricket", "telecom"],- },- "from_background": {- "label": "From background",- "description": "Whether the app was opened for the first time or from the background.",- "examples": ["true", "false"],- },- "url": {- "label": "URL",- "description": "The deep link URL that the app was opened from.",- "examples": ["https://open.my.app"],- },- "referring_application": {- "label": "Referrer application",- "description": "The namespace of the app that made the request.",- "examples": ["com.posthog.app"],- },- "version": {- "label": "App version",- "description": "The version of the app",- "examples": ["1.0.0"],- },- "previous_version": {- "label": "App previous version",- "description": "The previous version of the app",- "examples": ["1.0.0"],- },- "build": {- "label": "App build",- "description": "The build number for the app",- "examples": ["1"],- },- "previous_build": {- "label": "App previous build",- "description": "The previous build number for the app",- "examples": ["1"],- },- "gclid": {- "label": "gclid",- "description": "Google Click ID",- },- "rdt_cid": {- "label": "rdt_cid",- "description": "Reddit Click ID",- },- "epik": {- "label": "epik",- "description": "Pinterest Click ID",- },- "qclid": {- "label": "qclid",- "description": "Quora Click ID",- },- "sccid": {- "label": "sccid",- "description": "Snapchat Click ID",- },- "irclid": {- "label": "irclid",- "description": "Impact Click ID",- },- "_kx": {- "label": "_kx",- "description": "Klaviyo Tracking ID",- },- "gad_source": {- "label": "gad_source",- "description": "Google Ads Source",- },- "gclsrc": {- "label": "gclsrc",- "description": "Google Click Source",- },- "dclid": {- "label": "dclid",- "description": "DoubleClick ID",- },- "gbraid": {- "label": "gbraid",- "description": "Google Ads, web to app",- },- "wbraid": {- "label": "wbraid",- "description": "Google Ads, app to web",- },- "fbclid": {- "label": "fbclid",- "description": "Facebook Click ID",- },- "msclkid": {- "label": "msclkid",- "description": "Microsoft Click ID",- },- "twclid": {- "label": "twclid",- "description": "Twitter Click ID",- },- "li_fat_id": {- "label": "li_fat_id",- "description": "LinkedIn First-Party Ad Tracking ID",- },- "mc_cid": {- "label": "mc_cid",- "description": "Mailchimp Campaign ID",- },- "igshid": {- "label": "igshid",- "description": "Instagram Share ID",- },- "ttclid": {- "label": "ttclid",- "description": "TikTok Click ID",- },- "$is_identified": {- "label": "Is identified",- "description": "When the person was identified",- },- "$initial_person_info": {- "label": "Initial person info",- "description": "posthog-js initial person information. used in the $set_once flow",- "system": True,- },- "revenue": {- "label": "Revenue",- "description": "The revenue associated with the event. By default, this is in USD, but the currency property can be used to specify a different currency.",- "examples": [10.0],- },- "currency": {- "label": "Currency",- "description": "The currency code associated with the event.",- "examples": ["USD", "EUR", "GBP", "CAD"],- },- "$web_vitals_enabled_server_side": {- "label": "Web vitals enabled server side",- "description": "Whether web vitals was enabled in remote config",- },- "$web_vitals_FCP_event": {- "label": "Web vitals FCP measure event details",- },- "$web_vitals_FCP_value": {- "label": "Web vitals FCP value",- },- "$web_vitals_LCP_event": {- "label": "Web vitals LCP measure event details",- },- "$web_vitals_LCP_value": {- "label": "Web vitals LCP value",- },- "$web_vitals_INP_event": {- "label": "Web vitals INP measure event details",- },- "$web_vitals_INP_value": {- "label": "Web vitals INP value",- },- "$web_vitals_CLS_event": {- "label": "Web vitals CLS measure event details",- },- "$web_vitals_CLS_value": {- "label": "Web vitals CLS value",- },- "$web_vitals_allowed_metrics": {- "label": "Web vitals allowed metrics",- "description": "Allowed web vitals metrics config.",- "examples": ['["LCP", "CLS"]'],- "system": True,- },- "$prev_pageview_last_scroll": {- "label": "Previous pageview last scroll",- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- "examples": [0],- },- "$prev_pageview_id": {- "label": "Previous pageview ID",- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- "examples": ["1"],- "system": True,- },- "$prev_pageview_last_scroll_percentage": {- "label": "Previous pageview last scroll percentage",- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- "examples": [0],- },- "$prev_pageview_max_scroll": {- "examples": [0],- "label": "Previous pageview max scroll",- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- },- "$prev_pageview_max_scroll_percentage": {- "examples": [0],- "label": "Previous pageview max scroll percentage",- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- },- "$prev_pageview_last_content": {- "examples": [0],- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- "label": "Previous pageview last content",- },- "$prev_pageview_last_content_percentage": {- "examples": [0],- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- "label": "Previous pageview last content percentage",- },- "$prev_pageview_max_content": {- "examples": [0],- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- "label": "Previous pageview max content",- },- "$prev_pageview_max_content_percentage": {- "examples": [0],- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- "label": "Previous pageview max content percentage",- },- "$prev_pageview_pathname": {- "examples": ["/pricing", "/about-us/team"],- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- "label": "Previous pageview pathname",- },- "$prev_pageview_duration": {- "examples": [0],- "description": "posthog-js adds these to the page leave event, they are used in web analytics calculations",- "label": "Previous pageview duration",- },- "$surveys_activated": {- "label": "Surveys activated",- "description": "The surveys that were activated for this event.",- },- "$process_person_profile": {- "label": "Person profile processing flag",- "description": "The setting from an SDK to control whether an event has person processing enabled",- "system": True,- },- "$dead_clicks_enabled_server_side": {- "label": "Dead clicks enabled server side",- "description": "Whether dead clicks were enabled in remote config",- "system": True,- },- "$dead_click_scroll_delay_ms": {- "label": "Dead click scroll delay in milliseconds",- "description": "The delay between a click and the next scroll event",- "system": True,- },- "$dead_click_mutation_delay_ms": {- "label": "Dead click mutation delay in milliseconds",- "description": "The delay between a click and the next mutation event",- "system": True,- },- "$dead_click_absolute_delay_ms": {- "label": "Dead click absolute delay in milliseconds",- "description": "The delay between a click and having seen no activity at all",- "system": True,- },- "$dead_click_selection_changed_delay_ms": {- "label": "Dead click selection changed delay in milliseconds",- "description": "The delay between a click and the next text selection change event",- "system": True,- },- "$dead_click_last_mutation_timestamp": {- "label": "Dead click last mutation timestamp",- "description": "debug signal time of the last mutation seen by dead click autocapture",- "system": True,- },- "$dead_click_event_timestamp": {- "label": "Dead click event timestamp",- "description": "debug signal time of the event that triggered dead click autocapture",- "system": True,- },- "$dead_click_scroll_timeout": {- "label": "Dead click scroll timeout",- "description": "whether the dead click autocapture passed the threshold for waiting for a scroll event",- },- "$dead_click_mutation_timeout": {- "label": "Dead click mutation timeout",- "description": "whether the dead click autocapture passed the threshold for waiting for a mutation event",- "system": True,- },- "$dead_click_absolute_timeout": {- "label": "Dead click absolute timeout",- "description": "whether the dead click autocapture passed the threshold for waiting for any activity",- "system": True,- },- "$dead_click_selection_changed_timeout": {- "label": "Dead click selection changed timeout",- "description": "whether the dead click autocapture passed the threshold for waiting for a text selection change event",- "system": True,- },- # AI- "$ai_base_url": {- "label": "AI base URL (LLM)",- "description": "The base URL of the request made to the LLM API.",- "examples": ["https://api.openai.com/v1/"],- },- "$ai_http_status": {- "label": "AI HTTP status (LLM)",- "description": "The HTTP status code of the request made to the LLM API.",- "examples": [200, 429],- },- "$ai_input": {- "label": "AI input (LLM)",- "description": "The input JSON that was sent to the LLM API.",- "examples": ['{"content": "Explain quantum computing in simple terms.", "role": "user"}'],- },- "$ai_input_tokens": {- "label": "AI input tokens (LLM)",- "description": "The number of tokens in the input prompt that was sent to the LLM API.",- "examples": [23],- },- "$ai_output_choices": {- "label": "AI output (LLM)",- "description": "The output message choices JSON that was received from the LLM API.",- "examples": [- '{"choices": [{"text": "Quantum computing is a type of computing that harnesses the power of quantum mechanics to perform operations on data."}]}',- ],- },- "$ai_output_tokens": {- "label": "AI output tokens (LLM)",- "description": "The number of tokens in the output from the LLM API.",- "examples": [23],- },- "$ai_cache_read_input_tokens": {- "label": "AI cache read input tokens (LLM)",- "description": "The number of tokens read from the cache for the input prompt.",- "examples": [23],- },- "$ai_cache_creation_input_tokens": {- "label": "AI cache creation input tokens (LLM)",- "description": "The number of tokens created in the cache for the input prompt (anthropic only).",- "examples": [23],- },- "$ai_reasoning_tokens": {- "label": "AI reasoning tokens (LLM)",- "description": "The number of tokens in the reasoning output from the LLM API.",- "examples": [23],- },- "$ai_input_cost_usd": {- "label": "AI input cost USD (LLM)",- "description": "The cost in USD of the input tokens sent to the LLM API.",- "examples": [0.0017],- },- "$ai_output_cost_usd": {- "label": "AI output cost USD (LLM)",- "description": "The cost in USD of the output tokens received from the LLM API.",- "examples": [0.0024],- },- "$ai_total_cost_usd": {- "label": "AI total cost USD (LLM)",- "description": "The total cost in USD of the request made to the LLM API (input + output costs).",- "examples": [0.0041],- },- "$ai_latency": {- "label": "AI latency (LLM)",- "description": "The latency of the request made to the LLM API, in seconds.",- "examples": [0.361],- },- "$ai_time_to_first_token": {- "label": "AI time to first token (LLM)",- "description": "The time in seconds from request start until the first token was received. Only applicable for streaming responses.",- "examples": [0.125, 0.5],- },- "$ai_model": {- "label": "AI model (LLM)",- "description": "The model used to generate the output from the LLM API.",- "examples": ["gpt-4o-mini"],- },- "$ai_model_parameters": {- "label": "AI model parameters (LLM)",- "description": "The parameters used to configure the model in the LLM API, in JSON.",- "examples": ['{"temperature": 0.5, "max_tokens": 50}'],- },- "$ai_tools": {- "label": "AI tools (LLM)",- "description": "The tools available to the LLM.",- "examples": [- '[{"type": "function", "function": {"name": "tool1", "arguments": {"arg1": "value1", "arg2": "value2"}}}]',- ],- },- "$ai_stream": {- "label": "AI stream (LLM)",- "description": "Whether the response from the LLM API was streamed.",- "examples": ["true", "false"],- },- "$ai_temperature": {- "label": "AI temperature (LLM)",- "description": "The temperature parameter used in the request to the LLM API.",- "examples": [0.7, 1.0],- },- "$ai_input_state": {- "label": "AI Input State (LLM)",- "description": "Input state of the LLM agent.",- },- "$ai_output_state": {- "label": "AI Output State (LLM)",- "description": "Output state of the LLM agent.",- },- "$ai_provider": {- "label": "AI Provider (LLM)",- "description": "The provider of the AI model used to generate the output from the LLM API.",- "examples": ["openai"],- },- "$ai_trace_id": {- "label": "AI Trace ID (LLM)",- "description": "The trace ID of the request made to the LLM API. Used to group together multiple generations into a single trace.",- "examples": ["c9222e05-8708-41b8-98ea-d4a21849e761"],- },- "$ai_request_url": {- "label": "AI Request URL (LLM)",- "description": "The full URL of the request made to the LLM API.",- "examples": ["https://api.openai.com/v1/chat/completions"],- },- "$ai_metric_name": {- "label": "AI Metric Name (LLM)",- "description": "The name assigned to the metric used to evaluate the LLM trace.",- "examples": ["rating", "accuracy"],- },- "$ai_metric_value": {- "label": "AI Metric Value (LLM)",- "description": "The value assigned to the metric used to evaluate the LLM trace.",- "examples": ["negative", "95"],- },- "$ai_feedback_text": {- "label": "AI Feedback Text (LLM)",- "description": "The text provided by the user for feedback on the LLM trace.",- "examples": ['"The response was helpful, but it did not use the provided context."'],- },- "$ai_parent_id": {- "label": "AI Parent ID (LLM)",- "description": "The parent span ID of a span or generation, used to group a trace into a tree view.",- "examples": ["bdf42359-9364-4db7-8958-c001f28c9255"],- },- "$ai_span_id": {- "label": "AI Span ID (LLM)",- "description": "The unique identifier for a LLM trace, generation, or span.",- "examples": ["bdf42359-9364-4db7-8958-c001f28c9255"],- },- "$ai_span_name": {- "label": "AI Span Name (LLM)",- "description": "The name given to this LLM trace, generation, or span.",- "examples": ["summarize_text"],- },- "$csp_document_url": {- "label": "Document URL",- "description": "The URL of the document where the violation occurred.",- "examples": ["https://example.com/page"],- },- "$csp_violated_directive": {- "label": "Violated directive",- "description": "The CSP directive that was violated.",- "examples": ["script-src", "img-src", "default-src"],- },- "$csp_effective_directive": {- "label": "Effective directive",- "description": "The CSP directive that was effectively violated.",- "examples": ["script-src", "img-src", "default-src"],- },- "$csp_original_policy": {- "label": "Original policy",- "description": "The CSP policy that was active when the violation occurred.",- "examples": ["default-src 'self'; script-src 'self' example.com"],- },- "$csp_disposition": {- "label": "Disposition",- "description": "The disposition of the CSP policy that was violated (enforce or report).",- "examples": ["enforce", "report"],- },- "$csp_blocked_url": {- "label": "Blocked URL",- "description": "The URL that was blocked by the CSP policy.",- "examples": ["https://malicious-site.com/script.js"],- },- "$csp_line_number": {- "label": "Line number",- "description": "The line number in the source file where the violation occurred.",- "examples": ["42"],- },- "$csp_column_number": {- "label": "Column number",- "description": "The column number in the source file where the violation occurred.",- "examples": ["13"],- },- "$csp_source_file": {- "label": "Source file",- "description": "The source file where the violation occurred.",- "examples": ["script.js"],- },- "$csp_status_code": {- "label": "Status code",- "description": "The HTTP status code that was returned when trying to load the blocked resource.",- "examples": ["200", "404"],- },- "$csp_script_sample": {- "label": "Script sample",- "description": "An escaped sample of the script that caused the violation. Usually capped at 40 characters.",- "examples": ["eval('alert(1)')"],- },- "$csp_report_type": {- "label": "Report type",- "description": "The type of CSP report.",- },- "$csp_raw_report": {- "label": "Raw CSP report",- "description": "The raw CSP report as received from the browser.",- },- "$csp_referrer": {- "label": "CSP Referrer",- "description": "The referrer of the CSP report if available.",- "examples": ["https://example.com/referrer"],- },- "$csp_version": {- "label": "CSP Policy version",- "description": "The version of the CSP policy. Must be provided in the report URL.",- "examples": ["1.0"],- },- }-"""-PERSON_TAXONOMY_MESSAGE = """-Here is the taxonomy for person properties:-"person_properties": {- "email": {- "label": "Email address",- "description": "The email address of the user.",- "type": "String",- },- "$virt_initial_channel_type": {- "description": "What type of acquisition channel this user initially came from. Learn more about channels types and how to customise them in [our documentation](https://posthog.com/docs/data/channel-type)",- "examples": ["Paid Search", "Organic Video", "Direct"],- "label": "Initial channel type",- "type": "String",- "virtual": True,- },- "$virt_initial_referring_domain_type": {- "description": "What type of referring domain this user initially came from.",- "examples": ["Search", "Video", "Direct"],- "label": "Initial referring domain type",- "type": "String",- "virtual": True,- },- }-"""-FILTER_TAXONOMY_MESSAGE = """-Here is the taxonomy for event properties:-PROPERTY_FILTER_VERBOSE_NAME: dict[PropertyOperator, str] = {- PropertyOperator.EXACT: "matches exactly",- PropertyOperator.IS_NOT: "is not",- PropertyOperator.ICONTAINS: "contains",- PropertyOperator.NOT_ICONTAINS: "doesn't contain",- PropertyOperator.REGEX: "matches regex",- PropertyOperator.NOT_REGEX: "doesn't match regex",- PropertyOperator.GT: "greater than",- PropertyOperator.GTE: "greater than or equal to",- PropertyOperator.LT: "less than",- PropertyOperator.LTE: "less than or equal to",- PropertyOperator.IS_SET: "is set",- PropertyOperator.IS_NOT_SET: "is not set",- PropertyOperator.IS_DATE_EXACT: "is on exact date",- PropertyOperator.IS_DATE_BEFORE: "is before date",- PropertyOperator.IS_DATE_AFTER: "is after date",- PropertyOperator.BETWEEN: "is between",- PropertyOperator.NOT_BETWEEN: "is not between",- PropertyOperator.MIN: "is a minimum value",- PropertyOperator.MAX: "is a maximum value",- PropertyOperator.IN_: "is one of the values in",- PropertyOperator.NOT_IN: "is not one of the values in",- PropertyOperator.IS_CLEANED_PATH_EXACT: "has a link without a hash and URL parameters that matches exactly",-}-"""+def render_filter_operator_taxonomy(function_type: str) -> str:+ unsupported = UNSUPPORTED_FILTER_OPERATORS+ if function_type in TYPES_WITH_TRANSPILED_FILTERS:+ unsupported = unsupported | JS_UNSUPPORTED_FILTER_OPERATORS+ root = ET.Element("filter_taxonomy")+ ET.SubElement(root, "usage").text = "A filter's `operator` field takes the `value` below, never the `meaning`."+ for operator, verbose_name in PROPERTY_FILTER_VERBOSE_NAME.items():+ if operator in unsupported:+ continue+ entry = ET.SubElement(root, "operator")+ ET.SubElement(entry, "value").text = operator.value+ ET.SubElement(entry, "meaning").text = verbose_name+ return ET.tostring(root, encoding="unicode")+HOG_FUNCTION_FILTERS_SYSTEM_PROMPT = """You are an expert at creating filters for PostHog hog functions.@@ -2627,14 +1020,33 @@ Property types can be:- "person" for person properties- "group" for group properties-Common operators:-- "exact" for exact matches-- "icontains" for contains-- "regex" for regex patterns-- "gt", "lt", "gte", "lte" for numeric comparisons+To match every event, leave "events" as an empty list. "All events" in <event_taxonomy> is a wildcard label, not an event name, so a filter using it as an "id" matches nothing.++Pick the operator that says what the user asked for. <filter_taxonomy> lists every one you may use.Return ONLY the JSON object inside <filters> tags. Do not add any other text or explanation."""++def render_filters_system_prompt(function_type: str, current_filters: str) -> str:+ """The full system prompt for the filters tool, carrying only the taxonomy this type can filter on."""+ return "\n\n".join(+ [+ HOG_FUNCTION_FILTERS_SYSTEM_PROMPT,+ render_event_taxonomy(),+ render_event_property_taxonomy(),+ # The scope note takes the person block's place rather than preceding the taxonomy, so a+ # type that drops that block still shares every preceding byte with one that keeps it.+ EVENT_ONLY_FILTER_SCOPE+ if function_type in TYPES_WITHOUT_PERSON_GLOBALS+ else render_person_property_taxonomy(),+ render_filter_operator_taxonomy(function_type),+ # Last, so the taxonomy above stays an identical prefix across teams and requests+ # and the provider's prompt cache can hit it.+ f"Current filters: {current_filters}\nFunction type: {function_type}",+ ]+ )++HOG_FUNCTION_INPUTS_SYSTEM_PROMPT = """You are an expert at creating input variable schemas for PostHog hog functions.Your task is to analyze the hog code and create appropriate input variable schemas based on the instructions.diff --git a/products/cdp/backend/test_prompts.py b/products/cdp/backend/test_prompts.pynew file mode 100644index 000000000000..9167578d11eb--- /dev/null+++ b/products/cdp/backend/test_prompts.py@@ -0,0 +1,160 @@+import os++import defusedxml.ElementTree as ET+from parameterized import parameterized++from posthog.schema import PropertyOperator++from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, visible_definitions++from products.cdp.backend.prompts import (+ UNSUPPORTED_FILTER_OPERATORS,+ render_event_property_taxonomy,+ render_event_taxonomy,+ render_filter_operator_taxonomy,+ render_filters_system_prompt,+ render_person_property_taxonomy,+)++from ee.hogai.summarizers.property_filters import PROPERTY_FILTER_VERBOSE_NAME+++def _texts(xml: str, tag: str) -> set[str]:+ return {element.text or "" for element in ET.fromstring(xml).iter(tag)}+++class TestTaxonomyPrompts:+ def test_render_covers_every_visible_taxonomy_entry(self):+ assert _texts(render_event_taxonomy(), "name") == {name for name, _ in visible_definitions("events")}++ def test_render_person_properties_covers_every_visible_non_virtual_entry(self):+ # Virtual properties are excluded because a filter on one never matches at CDP runtime.+ assert _texts(render_person_property_taxonomy(), "name") == {+ name for name, definition in visible_definitions("person_properties") if not definition.get("virtual")+ }++ def test_render_event_properties_excludes_virtual_and_distinct_id(self):+ # Both compile to a lookup CDP never populates: a virtual property throws at runtime, and+ # `distinct_id` silently evaluates false.+ names = _texts(render_event_property_taxonomy(), "name")++ assert names == {+ name+ for name, definition in visible_definitions("event_properties")+ if not definition.get("virtual") and name != "distinct_id"+ }+ # Anchored on a literal, so dropping the exclusion fails here instead of moving in lockstep+ # with the derived set above.+ assert CORE_FILTER_DEFINITIONS_BY_GROUP["event_properties"]["$virt_is_bot"].get("virtual")+ assert "$virt_is_bot" not in names+ assert "distinct_id" not in names++ @parameterized.expand(+ [+ ("events", render_event_taxonomy, "$autocapture"),+ ("event_properties", render_event_property_taxonomy, "$exception_steps"),+ ("person_properties", render_person_property_taxonomy, "$initial_person_info"),+ ]+ )+ def test_render_omits_hidden_taxonomy_entries(self, group, render, hidden_name):+ # Asserted against literal names rather than `visible_definitions`, which the renderers+ # also call: if that filter stopped excluding hidden entries, both sides would move+ # together and the completeness test above would still pass.+ assert hidden_name in CORE_FILTER_DEFINITIONS_BY_GROUP[group]+ assert hidden_name not in _texts(render(), "name")++ def test_render_event_taxonomy_carries_descriptions_and_examples(self):+ events = {event.findtext("name"): event for event in ET.fromstring(render_event_taxonomy()).iter("event")}++ identify = CORE_FILTER_DEFINITIONS_BY_GROUP["events"]["$identify"]+ # `$identify` has both, so this also pins the `description_llm` precedence.+ assert events["$identify"].findtext("description") == identify["description_llm"]+ assert (+ events["$pageview"].findtext("description")+ == CORE_FILTER_DEFINITIONS_BY_GROUP["events"]["$pageview"]["description"]+ )+ assert events["$csp_violation"].findtext("examples")++ @parameterized.expand(+ [+ ("email", True), # no counterpart in <event_property_taxonomy>+ ("distinct_id", True), # excluded from the event block, so this is where it is described+ ("$browser", False), # a copy; the usage note sends the model to <event_property_taxonomy>+ ("$initial_browser", False),+ ]+ )+ def test_render_person_properties_describes_only_names_the_event_section_lacks(self, name, has_description):+ properties = {+ prop.findtext("name"): prop for prop in ET.fromstring(render_person_property_taxonomy()).iter("property")+ }++ assert (properties[name].findtext("description") is not None) == has_description++ def test_render_operators_uses_wire_values(self):+ values = _texts(render_filter_operator_taxonomy("destination"), "value")++ assert values == {+ operator.value for operator in PROPERTY_FILTER_VERBOSE_NAME if operator not in UNSUPPORTED_FILTER_OPERATORS+ }+ # These three have to stay reachable: they are the operators the model cannot express by+ # any other means, so losing them from the prompt silently narrows what it can filter on.+ assert {+ PropertyOperator.STARTS_WITH.value,+ PropertyOperator.ENDS_WITH.value,+ PropertyOperator.SEMVER_GTE.value,+ } <= values++ def test_render_operators_omits_operators_hog_functions_cannot_compile(self):+ assert PropertyOperator.FLAG_EVALUATES_TO in UNSUPPORTED_FILTER_OPERATORS+ assert PropertyOperator.FLAG_EVALUATES_TO.value not in _texts(+ render_filter_operator_taxonomy("destination"), "value"+ )++ @parameterized.expand([("site_destination",), ("site_app",)])+ def test_render_operators_omits_js_unsupported_operators_for_transpiled_types(self, function_type):+ # Listed literally, not read from the renderer's own exclusion set, so a family member that+ # stopped being excluded fails here rather than moving both sides together.+ broken_on_site = {+ PropertyOperator.ICONTAINS_MULTI.value,+ PropertyOperator.NOT_ICONTAINS_MULTI.value,+ PropertyOperator.SEMVER_EQ.value,+ PropertyOperator.SEMVER_NEQ.value,+ PropertyOperator.SEMVER_GT.value,+ PropertyOperator.SEMVER_GTE.value,+ PropertyOperator.SEMVER_LT.value,+ PropertyOperator.SEMVER_LTE.value,+ PropertyOperator.SEMVER_TILDE.value,+ PropertyOperator.SEMVER_CARET.value,+ PropertyOperator.SEMVER_WILDCARD.value,+ }++ assert broken_on_site.isdisjoint(_texts(render_filter_operator_taxonomy(function_type), "value"))+ # Scoped to the transpiled types: the bytecode STL defines both functions, so a destination+ # keeps every one of them.+ assert broken_on_site <= _texts(render_filter_operator_taxonomy("destination"), "value")++ @parameterized.expand(+ [+ ("transformation", False),+ ("transformation_log", False),+ ("destination", True),+ ("site_destination", True),+ ]+ )+ def test_system_prompt_swaps_the_person_block_for_a_scope_note_without_person_globals(+ self, function_type, has_person_globals+ ):+ prompt = render_filters_system_prompt(function_type, "{}")++ assert ("<person_property_taxonomy>" in prompt) == has_person_globals+ assert ("<filter_scope>" in prompt) != has_person_globals+ assert "<event_property_taxonomy>" in prompt++ def test_system_prompt_keeps_one_shared_prefix_up_to_the_person_block(self):+ # The taxonomy ahead of that block is what the provider's prompt cache can reuse across+ # function types, so a type-specific section must never be spliced in before it.+ destination = render_filters_system_prompt("destination", "{}")+ transformation = render_filters_system_prompt("transformation", "{}")+ shared = len(os.path.commonprefix([destination, transformation]))++ assert shared > destination.index("<person_property_taxonomy>") - 1