: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
feat(web-analytics): let custom bot rules combine multiple conditions (#97589)
Lucas Ricoyc6c2c57b1c27
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f0c2eea39801..aee3b749fffd 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9117,9 +9117,9 @@ snapshots:scenes-app-settings-environment--settings-environment-csp-reporting--light:hash: v1.k794b7964.a842c3f0ee5a6731d1051c47f04fd6da35d42f85cc3e0ba40afba80d2ea66b91.uj0d249fCiw0N7_QZI0owaFQ77omJCKRsMDMnmJrX5kscenes-app-settings-environment--settings-environment-customization--dark:- hash: v1.k794b7964.ae39c49782511f159250740436cf205216986f9e19d4a4327cd101a4f25fb389.3-ot9aTpgSaOkMqsk6irfOWN9EKadpujudg7rRIgxiw+ hash: v1.k794b7964.733008c798c06e23d720d436305309a65629a935744756a4c8e4e5e756dcc748.9DwtKFmRAscXfykv_qKOY-EFRu1khCjaL1AzLp2li-4scenes-app-settings-environment--settings-environment-customization--light:- hash: v1.k794b7964.80e0de7aa7c2aa17ed72e58eec01af1045acd1d3839a3b14f5dd81908fe28d1c.VBMZLN5BK5qz0_nHRm94WT5O1bKu72RjJ9LfFkdYp_A+ hash: v1.k794b7964.4772fd359da282e2586c6bc6b7eba6668662eac41803613fbddf5271304b5e6f.FCxfQ9xkkG7YInXfD1TKRkd6slogyuDI2svOObZniygscenes-app-settings-environment--settings-environment-danger-zone--dark:hash: v1.k794b7964.586910a373b9a9cf63d114f527d0bb8580033d25a81be6f830e07bf244a7c316.-ID92-MgwgAf0sdCeF84tYBSJ1RcHGOvApRVSsJNYeEscenes-app-settings-environment--settings-environment-danger-zone--light:@@ -9245,9 +9245,9 @@ snapshots:scenes-app-settings-project--settings-project-autocapture--light:hash: v1.k794b7964.397d4848babe9a8d2fd98b15ffe998d685521cb5135ff4ad1a70951e6062ec71.HMYh2-IfWjQd_PDBPGoPGrX_LVi2OHg7wzBFzJAmslAscenes-app-settings-project--settings-project-customization--dark:- hash: v1.k794b7964.ae39c49782511f159250740436cf205216986f9e19d4a4327cd101a4f25fb389.O6BKfuQnThce5dmkq0TiUUwYcF6CGC52St7qIeVV6_U+ hash: v1.k794b7964.733008c798c06e23d720d436305309a65629a935744756a4c8e4e5e756dcc748.63gIVcPQej_vpXAZwRAdYhwSlQiAeRw9vbQjBFxBj7wscenes-app-settings-project--settings-project-customization--light:- hash: v1.k794b7964.80e0de7aa7c2aa17ed72e58eec01af1045acd1d3839a3b14f5dd81908fe28d1c.lkSZRstT2d9iJdI0uWce2eBwXdYce69ZD2FvlR-I6IM+ hash: v1.k794b7964.4772fd359da282e2586c6bc6b7eba6668662eac41803613fbddf5271304b5e6f.OIaHxXmboD9j1oKyuGHP5cPg8y7dePEPTRd93sQqkpYscenes-app-settings-project--settings-project-danger-zone--dark:hash: v1.k794b7964.d18bc16d7f8d14a2168e67a889a5229659191e35393f829ce1b5eb6c0876a269.nQC3Mf7fvxzoZTD0m9ndbrfXV9nQin3tsW49wkX6Zqkscenes-app-settings-project--settings-project-danger-zone--light:diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 720678b0b714..960373f9b9e3 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -17145,34 +17145,26 @@],"type": "string"},- "CustomBotDefinition": {+ "CustomBotCondition": {"additionalProperties": false,- "description": "A bot a project defines itself, on top of PostHog's built-in bot list.",+ "description": "One condition of a project's bot rule.","properties": {- "category": {- "description": "Reported by `$virt_traffic_category`. Defaults to `custom`.",- "type": "string"- },"id": {"type": "string"},"key": {"$ref": "#/definitions/CustomBotField",- "description": "The event property this rule reads."+ "description": "The event property this condition reads."},"matcher": {"$ref": "#/definitions/CustomBotMatcher"},- "name": {- "description": "Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches.",- "type": "string"- },"pattern": {"description": "Matched against the property named by `key`.","type": "string"}},- "required": ["name", "key", "pattern", "matcher", "id"],+ "required": ["key", "pattern", "matcher", "id"],"type": "object"},"CustomBotField": {@@ -17196,9 +17188,38 @@"type": "string"},"CustomBotMatcher": {- "enum": ["contains", "regex", "cidr"],+ "enum": ["contains", "regex", "exact", "cidr"],"type": "string"},+ "CustomBotRule": {+ "additionalProperties": false,+ "description": "A bot a project defines itself, on top of PostHog's built-in bot list.",+ "properties": {+ "category": {+ "description": "Reported by `$virt_traffic_category`. Defaults to `custom`.",+ "type": "string"+ },+ "combiner": {+ "$ref": "#/definitions/FilterLogicalOperator",+ "description": "Whether every condition must match (AND) or any one of them (OR)."+ },+ "id": {+ "type": "string"+ },+ "items": {+ "items": {+ "$ref": "#/definitions/CustomBotCondition"+ },+ "type": "array"+ },+ "name": {+ "description": "Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches.",+ "type": "string"+ }+ },+ "required": ["name", "combiner", "items", "id"],+ "type": "object"+ },"CustomChannelCondition": {"additionalProperties": false,"properties": {@@ -29587,7 +29608,7 @@},"customBotDefinitions": {"items": {- "$ref": "#/definitions/CustomBotDefinition"+ "$ref": "#/definitions/CustomBotRule"},"type": "array"},diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex e4bbc17bd38f..ac4e3ac7561f 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -521,7 +521,7 @@ export interface HogQLQueryModifiers {propertyGroupsMode?: 'enabled' | 'disabled' | 'optimized'useMaterializedViews?: booleancustomChannelTypeRules?: CustomChannelRule[]- customBotDefinitions?: CustomBotDefinition[]+ customBotDefinitions?: CustomBotRule[]useWebAnalyticsPreAggregatedTables?: boolean/** Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients. */webAnalyticsFirstPageviewFilters?: boolean@@ -6839,22 +6839,32 @@ export enum CustomBotField {export enum CustomBotMatcher {Contains = 'contains',Regex = 'regex',+ /** Case-sensitive equality against the whole property value. */+ Exact = 'exact',/** Matches an IP against a network range, e.g. `192.0.2.0/24`. Only valid with `$ip`. */Cidr = 'cidr',}-/** A bot a project defines itself, on top of PostHog's built-in bot list. */-export interface CustomBotDefinition {- /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */- name: string- /** The event property this rule reads. */+/** One condition of a project's bot rule. */+export interface CustomBotCondition {+ /** The event property this condition reads. */key: CustomBotField/** Matched against the property named by `key`. */pattern: stringmatcher: CustomBotMatcher+ id: string // the ID is only needed for the settings editor, so only needs to be unique within one rule+}++/** A bot a project defines itself, on top of PostHog's built-in bot list. */+export interface CustomBotRule {+ /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */+ name: string/** Reported by `$virt_traffic_category`. Defaults to `custom`. */category?: string- id: string // the ID is only needed for the settings editor, so only needs to be unique within one set of definitions+ /** Whether every condition must match (AND) or any one of them (OR). */+ combiner: FilterLogicalOperator+ items: CustomBotCondition[]+ id: string // the ID is only needed for the settings editor, so only needs to be unique within one set of rules}export enum DefaultChannelTypes {diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 4573ba88e26e..86fc00215f97 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -25,7 +25,7 @@ import { GitHub, Linear, Slack } from 'scenes/integrations/definitions'import { BounceRateDurationSetting } from 'scenes/settings/environment/BounceRateDuration'import { BounceRatePageViewModeSetting } from 'scenes/settings/environment/BounceRatePageViewMode'import { CookielessServerHashModeSetting } from 'scenes/settings/environment/CookielessServerHashMode'-import { CustomBotDefinitions } from 'scenes/settings/environment/CustomBotDefinitions'+import { CustomBotRules } from 'scenes/settings/environment/CustomBotRules'import { CustomChannelTypes } from 'scenes/settings/environment/CustomChannelTypes'import { DeadClicksAutocaptureSettings } from 'scenes/settings/environment/DeadClicksAutocaptureSettings'import { MaxChangelogSettings } from 'scenes/settings/environment/MaxChangelogSettings'@@ -328,7 +328,7 @@ export const SETTINGS_MAP: SettingSection[] = [description:'Add your own crawlers and scripts to the bots PostHog already detects, so you can tell them apart from real visitors.',docsUrl: 'https://posthog.com/docs/web-analytics/bot-detection',- component: <CustomBotDefinitions />,+ component: <CustomBotRules />,keywords: ['bot', 'crawler', 'spider', 'scraper', 'user agent', 'ai'],},{diff --git a/frontend/src/scenes/settings/environment/CustomBotDefinitions.tsx b/frontend/src/scenes/settings/environment/CustomBotDefinitions.tsxdeleted file mode 100644index db16efb177d1..000000000000--- a/frontend/src/scenes/settings/environment/CustomBotDefinitions.tsx+++ /dev/null@@ -1,276 +0,0 @@-import { deepEqual as equal } from 'fast-equals'-import { useActions, useValues } from 'kea'-import { useState } from 'react'--import { IconPlus, IconTrash } from '@posthog/icons'--import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'-import { TeamMembershipLevel } from 'lib/constants'-import { LemonBanner } from 'lib/lemon-ui/LemonBanner'-import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonInput } from 'lib/lemon-ui/LemonInput'-import { LemonLabel } from 'lib/lemon-ui/LemonLabel'-import { LemonSelect } from 'lib/lemon-ui/LemonSelect'-import { LemonTable } from 'lib/lemon-ui/LemonTable'-import { LemonTag } from 'lib/lemon-ui/LemonTag'-import { Link } from 'lib/lemon-ui/Link'-import { uuid } from 'lib/utils/dom'-import { teamLogic } from 'scenes/teamLogic'--import { CustomBotDefinition, CustomBotField, CustomBotMatcher } from '~/queries/schema/schema-general'--import {- CUSTOM_BOT_CATEGORY,- CUSTOM_BOT_CATEGORY_OPTIONS,- CUSTOM_BOT_FIELD_OPTIONS,- MAX_CUSTOM_BOT_DEFINITIONS,- defaultMatcherFor,- fieldLabel,- matcherOptionsFor,- matchesValue,- patternPlaceholderFor,- sanitizeCustomBotDefinitions,- validateCustomBotDefinition,-} from './customBotDefinitionsUtils'--function newDefinition(): CustomBotDefinition {- return {- id: uuid(),- name: '',- key: CustomBotField.RawUserAgent,- pattern: '',- matcher: CustomBotMatcher.Contains,- category: CUSTOM_BOT_CATEGORY,- }-}--export function CustomBotDefinitions(): JSX.Element {- const { currentTeam, currentTeamLoading } = useValues(teamLogic)- const { updateCurrentTeam } = useActions(teamLogic)-- // The saved state is whatever the server currently holds, so a save that the backend rejects- // leaves the editor dirty and retryable instead of falsely reading as saved.- const savedDefinitions = currentTeam?.modifiers?.customBotDefinitions ?? []- const [definitions, setDefinitions] = useState<CustomBotDefinition[]>(savedDefinitions)- const [testValues, setTestValues] = useState<Partial<Record<CustomBotField, string>>>({})-- const restrictedReason = useRestrictedArea({- scope: RestrictionScope.Project,- minimumAccessLevel: TeamMembershipLevel.Admin,- })- const canEdit = !restrictedReason-- const firstError = definitions.map(validateCustomBotDefinition).find(Boolean)- // Sanitize both sides: a rule written through the API can lack the optional category or carry- // unpadded whitespace, and a pristine editor must not read as dirty for normalization alone.- const isUnchanged = equal(sanitizeCustomBotDefinitions(definitions), sanitizeCustomBotDefinitions(savedDefinitions))- const testedFields = CUSTOM_BOT_FIELD_OPTIONS.filter((option) =>- definitions.some((definition) => definition.key === option.value)- )- const matched = definitions.filter((definition) => matchesValue(definition, testValues[definition.key] ?? ''))- // Only values for a property still in use count as test input, so removing a rule does not leave- // a stale value showing a phantom "no match".- const hasTestInput = testedFields.some((field) => testValues[field.value]?.trim())- // $ip is dropped on ingest when a project anonymizes IPs, so a range would never match.- const ipRulesAreDead =- currentTeam?.anonymize_ips && definitions.some((definition) => definition.key === CustomBotField.IP)-- const updateDefinition = (id: string, update: Partial<CustomBotDefinition>): void => {- setDefinitions(definitions.map((d) => (d.id === id ? { ...d, ...update } : d)))- }-- const changeKey = (definition: CustomBotDefinition, key: CustomBotField): void => {- // Regex works on every property, so treat it as a deliberate choice and keep it. Anything- // else follows the new property, which moves an IP rule onto ranges.- const matcher = definition.matcher === CustomBotMatcher.Regex ? CustomBotMatcher.Regex : defaultMatcherFor(key)- updateDefinition(definition.id, { key, matcher })- }-- const save = (): void => {- const sanitized = sanitizeCustomBotDefinitions(definitions)- setDefinitions(sanitized)- // On success the team reloads with these definitions and isUnchanged flips to true; on a- // rejected save the team is unchanged, so the editor stays dirty and the error is actionable.- updateCurrentTeam({- modifiers: { ...currentTeam?.modifiers, customBotDefinitions: sanitized },- })- }-- return (- <div className="flex flex-col gap-4">- <p className="mb-0">- A bot you add here counts as a bot everywhere <code>Is bot</code> is available, including insights, web- analytics, and SQL. PostHog's built-in list already covers crawlers that identify themselves, like- GPTBot and Googlebot. Your rules are checked first, so you can give one of those a different name or- category.- </p>- <p className="mb-0">- Match the user agent to catch a crawler that names itself, or the IP address to catch one that sends a- browser user agent from a range you know.{' '}- <Link to="https://posthog.com/docs/web-analytics/bot-detection">Read more about bot detection</Link>- </p>-- <LemonTable- dataSource={definitions}- emptyState="No bots added yet. PostHog's built-in list still applies. Add one to extend it."- columns={[- {- title: 'Name',- key: 'name',- width: '22%',- render: (_, definition) => (- <LemonInput- value={definition.name}- onChange={(name) => updateDefinition(definition.id, { name })}- placeholder="Acme scraper"- disabledReason={restrictedReason}- />- ),- },- {- title: 'Matches when',- key: 'pattern',- render: (_, definition) => {- const error = validateCustomBotDefinition(definition)- return (- <div className="flex flex-col gap-1">- <div className="flex items-center gap-2">- <LemonSelect- value={definition.key}- options={CUSTOM_BOT_FIELD_OPTIONS}- onChange={(key) => changeKey(definition, key)}- disabledReason={restrictedReason}- />- <LemonSelect- value={definition.matcher}- options={matcherOptionsFor(definition.key)}- onChange={(matcher) => updateDefinition(definition.id, { matcher })}- disabledReason={restrictedReason}- />- <LemonInput- className="flex-1 font-mono"- value={definition.pattern}- onChange={(pattern) => updateDefinition(definition.id, { pattern })}- placeholder={patternPlaceholderFor(definition.key, definition.matcher)}- status={error ? 'danger' : undefined}- disabledReason={restrictedReason}- />- </div>- {error ? <span className="text-danger text-xs">{error}</span> : null}- </div>- )- },- },- {- title: 'Category',- key: 'category',- width: '18%',- render: (_, definition) => (- <LemonSelect- className="w-full"- value={definition.category || CUSTOM_BOT_CATEGORY}- options={CUSTOM_BOT_CATEGORY_OPTIONS}- onChange={(category) => updateDefinition(definition.id, { category })}- disabledReason={restrictedReason}- />- ),- },- {- key: 'remove',- width: 0,- render: (_, definition) =>- canEdit ? (- <LemonButton- icon={<IconTrash />}- size="small"- tooltip="Remove"- onClick={() => setDefinitions(definitions.filter((d) => d.id !== definition.id))}- />- ) : null,- },- ]}- />-- {canEdit ? (- <div className="flex items-center gap-2">- <LemonButton- type="secondary"- icon={<IconPlus />}- onClick={() => setDefinitions([...definitions, newDefinition()])}- disabledReason={- definitions.length >= MAX_CUSTOM_BOT_DEFINITIONS- ? `You can define at most ${MAX_CUSTOM_BOT_DEFINITIONS} bots`- : undefined- }- >- Add bot- </LemonButton>- <LemonButton- type="primary"- onClick={save}- loading={currentTeamLoading}- disabledReason={- currentTeamLoading- ? 'Saving'- : firstError- ? 'Fix the errors above first'- : isUnchanged- ? 'No changes to save'- : undefined- }- >- Save- </LemonButton>- </div>- ) : null}-- {ipRulesAreDead ? (- <LemonBanner type="warning">- This project anonymizes IP addresses, so events arrive without one and a rule on the IP address- never matches. Turn off IP anonymization in Project settings, or match on another property.- </LemonBanner>- ) : null}-- {testedFields.length > 0 ? (- <div className="flex flex-col gap-2">- <LemonLabel info="Only your own bots are checked here. A real query also matches PostHog's built-in list, after your rules.">- Test a value- </LemonLabel>- {testedFields.map((field) => (- <div key={field.value} className="flex items-center gap-2">- <span className="w-32 shrink-0 text-muted text-xs">{field.label}</span>- <LemonInput- className="flex-1 font-mono"- value={testValues[field.value] ?? ''}- onChange={(value) => setTestValues({ ...testValues, [field.value]: value })}- placeholder={- field.value === CustomBotField.IP ? '192.0.2.55' : `Paste a ${field.label}`- }- />- </div>- ))}- {matched.length > 0 ? (- <span className="flex items-center gap-1 flex-wrap">- Matches- {matched.map((definition) => (- <LemonTag key={definition.id} type="success">- {definition.name || fieldLabel(definition.key)}- </LemonTag>- ))}- </span>- ) : hasTestInput ? (- <span className="text-muted">- No custom rule matched. PostHog's built-in list still applies.- </span>- ) : null}- </div>- ) : null}-- {savedDefinitions.length > 0 ? (- <LemonBanner type="info">- Changes apply to new and existing data. Refresh an insight or dashboard to see them applied.- </LemonBanner>- ) : null}- </div>- )-}diff --git a/frontend/src/scenes/settings/environment/CustomBotRules.tsx b/frontend/src/scenes/settings/environment/CustomBotRules.tsxnew file mode 100644index 000000000000..1238549ac09d--- /dev/null+++ b/frontend/src/scenes/settings/environment/CustomBotRules.tsx@@ -0,0 +1,375 @@+import { deepEqual as equal } from 'fast-equals'+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconPlus } from '@posthog/icons'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { VerticalNestedDND } from 'lib/components/VerticalNestedDND/VerticalNestedDND'+import { TeamMembershipLevel } from 'lib/constants'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonLabel } from 'lib/lemon-ui/LemonLabel'+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { LemonTag } from 'lib/lemon-ui/LemonTag'+import { Link } from 'lib/lemon-ui/Link'+import { uuid } from 'lib/utils/dom'+import { teamLogic } from 'scenes/teamLogic'++import { CustomBotCondition, CustomBotField, CustomBotMatcher, CustomBotRule } from '~/queries/schema/schema-general'+import { FilterLogicalOperator } from '~/types'++import {+ CUSTOM_BOT_CATEGORY,+ CUSTOM_BOT_CATEGORY_OPTIONS,+ CUSTOM_BOT_FIELD_OPTIONS,+ MAX_CONDITIONS_PER_RULE,+ MAX_CUSTOM_BOT_RULES,+ MAX_TOTAL_CONDITIONS,+ defaultMatcherFor,+ fieldLabel,+ matcherLabel,+ matcherOptionsFor,+ patternPlaceholderFor,+ ruleMatchesValues,+ sanitizeCustomBotRules,+ parseCustomBotRules,+ validateCustomBotCondition,+ validateCustomBotRule,+ validateCustomBotRuleSet,+} from './customBotRulesUtils'++// Lowercase: the labels render mid-sentence ("when all conditions are met").+const combinerOptions = [+ { label: 'all', value: FilterLogicalOperator.And },+ { label: 'any', value: FilterLogicalOperator.Or },+]++function categoryLabel(category: string | undefined): string {+ const value = category || CUSTOM_BOT_CATEGORY+ return CUSTOM_BOT_CATEGORY_OPTIONS.find((option) => option.value === value)?.label ?? value+}++/** The list without edit affordances: the shared editor always renders drag handles and delete+buttons, which would look actionable to someone whose changes can never be saved. */+function ReadOnlyBotRules({ rules }: { rules: CustomBotRule[] }): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ {rules.map((rule) => (+ <div key={rule.id} className="border rounded p-3 flex flex-col gap-1">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-semibold">{rule.name}</span>+ <LemonTag>{categoryLabel(rule.category)}</LemonTag>+ </div>+ {rule.items.length > 1 ? (+ <span className="text-muted text-xs">+ When {rule.combiner === FilterLogicalOperator.Or ? 'any' : 'all'} of these conditions are+ met:+ </span>+ ) : null}+ {rule.items.map((condition) => (+ <span key={condition.id} className="text-sm">+ {fieldLabel(condition.key)} {matcherLabel(condition.matcher)}{' '}+ <code>{condition.pattern}</code>+ </span>+ ))}+ </div>+ ))}+ </div>+ )+}++function newCondition(): CustomBotCondition {+ return {+ id: uuid(),+ key: CustomBotField.RawUserAgent,+ matcher: CustomBotMatcher.Contains,+ pattern: '',+ }+}++function newRule(): CustomBotRule {+ return {+ id: uuid(),+ name: '',+ category: CUSTOM_BOT_CATEGORY,+ combiner: FilterLogicalOperator.And,+ items: [newCondition()],+ }+}++export function CustomBotRules(): JSX.Element {+ const { currentTeam, currentTeamLoading } = useValues(teamLogic)+ const { updateCurrentTeam } = useActions(teamLogic)++ // The saved state is whatever the server currently holds, so a save that the backend rejects+ // leaves the editor dirty and retryable instead of falsely reading as saved.+ const rawSavedRules = currentTeam?.modifiers?.customBotDefinitions+ const savedRules = parseCustomBotRules(rawSavedRules)+ // A save writes the parsed list back in full, so entries that did not parse would be removed+ // silently. Tell the user instead of losing them without a trace.+ const droppedCount = (Array.isArray(rawSavedRules) ? rawSavedRules.length : 0) - savedRules.length+ const [rules, setRules] = useState<CustomBotRule[]>(savedRules)+ const [testValues, setTestValues] = useState<Partial<Record<CustomBotField, string>>>({})++ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })+ const canEdit = !restrictedReason++ const anyRuleError = rules.map(validateCustomBotRule).find(Boolean)+ const setError = validateCustomBotRuleSet(rules)+ const totalConditions = rules.reduce((sum, rule) => sum + rule.items.length, 0)+ // Sanitize both sides: a rule written through the API can lack the optional category or carry+ // unpadded whitespace, and a pristine editor must not read as dirty for normalization alone.+ const isUnchanged = equal(sanitizeCustomBotRules(rules), sanitizeCustomBotRules(savedRules))+ const usedFields = CUSTOM_BOT_FIELD_OPTIONS.filter((option) =>+ rules.some((rule) => rule.items.some((condition) => condition.key === option.value))+ )+ const matched = rules.filter((rule) => ruleMatchesValues(rule, testValues))+ // Only values for a property still in use count as test input, so removing a rule does not leave+ // a stale value showing a phantom "no match".+ const hasTestInput = usedFields.some((field) => testValues[field.value]?.trim())+ // $ip is dropped on ingest when a project anonymizes IPs, so a range would never match.+ const ipRulesAreDead =+ currentTeam?.anonymize_ips &&+ rules.some((rule) => rule.items.some((condition) => condition.key === CustomBotField.IP))++ const save = (): void => {+ // On success the team reloads with these rules and isUnchanged flips to true; on a+ // rejected save the team is unchanged, so the editor stays dirty and the error is actionable.+ updateCurrentTeam({+ modifiers: { ...currentTeam?.modifiers, customBotDefinitions: sanitizeCustomBotRules(rules) },+ })+ }++ return (+ <div className="flex flex-col gap-4">+ <p className="mb-0">+ A bot you add here counts as a bot everywhere <code>Is bot</code> is available, including insights, web+ analytics, and SQL. PostHog's built-in list already covers crawlers that identify themselves, like+ GPTBot and Googlebot. Your rules are checked first, so you can give one of those a different name or+ category.+ </p>+ <p className="mb-0">+ Match the user agent to catch a crawler that names itself, the IP address to catch one that sends a+ browser user agent from a range you know, or combine conditions to catch one that only stands out+ through a combination, like an 800x600 screen.{' '}+ <Link to="https://posthog.com/docs/web-analytics/bot-detection">Read more about bot detection</Link>+ </p>++ {rules.length === 0 ? (+ <p className="text-muted mb-0">+ No bots added yet. PostHog's built-in list still applies. Add one to extend it.+ </p>+ ) : null}++ {droppedCount > 0 ? (+ <LemonBanner type="warning">+ {droppedCount === 1 ? 'One saved rule' : `${droppedCount} saved rules`} could not be read and will+ be removed if you save. Contact support if you did not expect this.+ </LemonBanner>+ ) : null}++ {!canEdit ? (+ <ReadOnlyBotRules rules={rules} />+ ) : (+ <VerticalNestedDND<CustomBotCondition, CustomBotRule>+ initialItems={rules}+ onChange={setRules}+ renderContainerItem={(rule, { updateContainerItem }) => {+ const ruleError = validateCustomBotRule(rule)+ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-row items-center gap-2 flex-wrap">+ <span>Flag as bot</span>+ <LemonInput+ className="flex-1 min-w-40"+ value={rule.name}+ onChange={(name) => updateContainerItem({ ...rule, name })}+ placeholder="Acme scraper"+ disabledReason={restrictedReason}+ />+ <span>in category</span>+ <LemonSelect+ value={rule.category || CUSTOM_BOT_CATEGORY}+ options={CUSTOM_BOT_CATEGORY_OPTIONS}+ onChange={(category) => updateContainerItem({ ...rule, category })}+ disabledReason={restrictedReason}+ />+ </div>+ {rule.items.length === 1 ? (+ <span>when this condition is met</span>+ ) : (+ <div className="flex flex-row items-center gap-2">+ <span>when</span>+ <LemonSelect+ value={rule.combiner}+ options={combinerOptions}+ onChange={(combiner) => updateContainerItem({ ...rule, combiner })}+ disabledReason={restrictedReason}+ />+ <span>conditions are met</span>+ </div>+ )}+ {ruleError && !rule.items.some(validateCustomBotCondition) ? (+ <span className="text-danger text-xs">{ruleError}</span>+ ) : null}+ </div>+ )+ }}+ renderChildItem={(condition, { updateChildItem }) => {+ const error = validateCustomBotCondition(condition)+ const changeKey = (key: CustomBotField): void => {+ // Regex works on every property, so treat it as a deliberate choice and keep+ // it. Anything else follows the new property, which moves an IP condition+ // onto ranges and a screen dimension onto equality.+ const matcher =+ condition.matcher === CustomBotMatcher.Regex+ ? CustomBotMatcher.Regex+ : defaultMatcherFor(key)+ updateChildItem({ ...condition, key, matcher })+ }+ return (+ <div className="w-full flex flex-col gap-1">+ <div className="flex flex-row items-center gap-2">+ <LemonSelect+ value={condition.key}+ options={CUSTOM_BOT_FIELD_OPTIONS}+ onChange={changeKey}+ disabledReason={restrictedReason}+ />+ <LemonSelect+ value={condition.matcher}+ options={matcherOptionsFor(condition.key)}+ onChange={(matcher) => updateChildItem({ ...condition, matcher })}+ disabledReason={restrictedReason}+ />+ <LemonInput+ className="flex-1 font-mono"+ value={condition.pattern}+ onChange={(pattern) => updateChildItem({ ...condition, pattern })}+ placeholder={patternPlaceholderFor(condition.key, condition.matcher)}+ status={error ? 'danger' : undefined}+ disabledReason={restrictedReason}+ />+ </div>+ {error ? <span className="text-danger text-xs">{error}</span> : null}+ </div>+ )+ }}+ renderAddChildItem={(rule, { onAddChild }) =>+ canEdit ? (+ <LemonButton+ type="secondary"+ icon={<IconPlus />}+ onClick={() => onAddChild(rule.id)}+ data-attr="custom-bot-rules-add-condition"+ disabledReason={+ rule.items.length >= MAX_CONDITIONS_PER_RULE+ ? `A rule can have at most ${MAX_CONDITIONS_PER_RULE} conditions`+ : totalConditions >= MAX_TOTAL_CONDITIONS+ ? `You can have at most ${MAX_TOTAL_CONDITIONS} conditions across all rules`+ : undefined+ }+ >+ Add condition+ </LemonButton>+ ) : null+ }+ renderAddContainerItem={({ onAddContainer }) =>+ canEdit ? (+ <LemonButton+ type="secondary"+ icon={<IconPlus />}+ onClick={onAddContainer}+ data-attr="custom-bot-rules-add-rule"+ disabledReason={+ rules.length >= MAX_CUSTOM_BOT_RULES+ ? `You can define at most ${MAX_CUSTOM_BOT_RULES} bots`+ : totalConditions >= MAX_TOTAL_CONDITIONS+ ? `You can have at most ${MAX_TOTAL_CONDITIONS} conditions across all rules`+ : undefined+ }+ >+ Add bot+ </LemonButton>+ ) : null+ }+ renderAdditionalControls={() =>+ canEdit ? (+ <LemonButton+ type="primary"+ onClick={save}+ loading={currentTeamLoading}+ data-attr="custom-bot-rules-save"+ disabledReason={+ currentTeamLoading+ ? 'Saving'+ : anyRuleError+ ? 'Fix the errors above first'+ : (setError ?? (isUnchanged ? 'No changes to save' : undefined))+ }+ >+ Save+ </LemonButton>+ ) : null+ }+ createNewContainerItem={newRule}+ createNewChildItem={newCondition}+ />+ )}++ {ipRulesAreDead ? (+ <LemonBanner type="warning">+ This project anonymizes IP addresses, so events arrive without one and a condition on the IP address+ never matches. Turn off "Discard client IP data" in your project settings, or match on another+ property.+ </LemonBanner>+ ) : null}++ {usedFields.length > 0 ? (+ <div className="flex flex-col gap-2">+ <LemonLabel info="Only your own bots are checked here. A real query also matches PostHog's built-in list, after your rules.">+ Test a value+ </LemonLabel>+ {usedFields.map((field) => (+ <div key={field.value} className="flex items-center gap-2">+ <span className="w-32 shrink-0 text-muted text-xs">{field.label}</span>+ <LemonInput+ className="flex-1 font-mono"+ value={testValues[field.value] ?? ''}+ onChange={(value) => setTestValues({ ...testValues, [field.value]: value })}+ placeholder={+ field.value === CustomBotField.IP ? '192.0.2.55' : `Paste a ${field.label}`+ }+ />+ </div>+ ))}+ {matched.length > 0 ? (+ <span className="flex items-center gap-1 flex-wrap">+ Matches+ {matched.map((rule) => (+ <LemonTag key={rule.id} type="success">+ {rule.name || fieldLabel(rule.items[0]?.key ?? CustomBotField.RawUserAgent)}+ </LemonTag>+ ))}+ </span>+ ) : hasTestInput ? (+ <span className="text-muted">+ No custom rule matched. PostHog's built-in list still applies.+ </span>+ ) : null}+ </div>+ ) : null}++ {savedRules.length > 0 ? (+ <LemonBanner type="info">+ Changes apply to new and existing data. Refresh an insight or dashboard to see them applied.+ </LemonBanner>+ ) : null}+ </div>+ )+}diff --git a/frontend/src/scenes/settings/environment/customBotDefinitionsUtils.test.ts b/frontend/src/scenes/settings/environment/customBotDefinitionsUtils.test.tsdeleted file mode 100644index 4d1db8a4627d..000000000000--- a/frontend/src/scenes/settings/environment/customBotDefinitionsUtils.test.ts+++ /dev/null@@ -1,151 +0,0 @@-import { CustomBotDefinition, CustomBotField, CustomBotMatcher } from '~/queries/schema/schema-general'--import { matchesValue, validateCustomBotDefinition } from './customBotDefinitionsUtils'--const definition = (overrides: Partial<CustomBotDefinition> = {}): CustomBotDefinition => ({- id: '1',- name: 'Acme scraper',- key: CustomBotField.RawUserAgent,- pattern: 'AcmeBot',- matcher: CustomBotMatcher.Contains,- ...overrides,-})--const ipRule = (pattern: string): CustomBotDefinition =>- definition({ key: CustomBotField.IP, matcher: CustomBotMatcher.Cidr, pattern })--describe('customBotDefinitionsUtils', () => {- // These rules mirror the ones the API enforces. When they drift, a rule the editor calls valid- // comes back as a 400 on save instead of an inline error next to the row.- describe('validateCustomBotDefinition', () => {- test.each([- ['empty name', { name: '' }, 'Give this bot a name.'],- ['empty pattern', { pattern: ' ' }, 'Add a value to match.'],- [- 'lookahead',- { pattern: 'Acme(?=Bot)', matcher: CustomBotMatcher.Regex },- 'This uses a lookahead, which is not supported here.',- ],- [- 'unparsable regex',- { pattern: 'Acme(', matcher: CustomBotMatcher.Regex },- 'This is not a valid regular expression.',- ],- [- // The server's re.compile rejects (?U), so the editor must too or Save 400s. Only- // i, m and s are translated to JavaScript flags.- 'a leading inline flag the server rejects',- { pattern: '(?U)AcmeBot', matcher: CustomBotMatcher.Regex },- 'This is not a valid regular expression.',- ],- [- 'a range on a property that is not an IP',- { matcher: CustomBotMatcher.Cidr, pattern: '192.0.2.0/24' },- 'Ranges only work with the IP address property.',- ],- ])('rejects %s', (_name, overrides, expected) => {- expect(validateCustomBotDefinition(definition(overrides))).toEqual(expected)- })-- test.each([- ['a bare address', '192.0.2.7'],- ['a v4 range', '192.0.2.0/24'],- ['a v6 range', '2001:db8::/32'],- ['host bits set', '192.0.2.7/24'],- ])('accepts %s', (_name, pattern) => {- expect(validateCustomBotDefinition(ipRule(pattern))).toBeNull()- })-- test.each([- ['a hostname', 'not-an-ip'],- ['an octet over 255', '192.0.2.999'],- // Python's ipaddress rejects leading zeros, so the tester must too or Save 400s.- ['a leading-zero octet', '192.168.001.1'],- ['a prefix wider than the family', '192.0.2.0/33'],- ['too many parts', '192.0.2.0/24/8'],- ])('rejects %s as a range', (_name, pattern) => {- expect(validateCustomBotDefinition(ipRule(pattern))).toEqual('This is not a valid IP address or range.')- })-- test.each([- ['a plain substring', {}],- ['a substring with regex metacharacters', { pattern: 'Acme (bot) v1.0' }],- ['an anchored regex', { pattern: '^AcmeBot/[0-9]+$', matcher: CustomBotMatcher.Regex }],- // The server and ClickHouse accept a leading inline flag group; JavaScript RegExp does- // not, so these would wrongly block Save without the flag translation.- ['a leading case-insensitive flag', { pattern: '(?i)(acme|globex)bot', matcher: CustomBotMatcher.Regex }],- ['leading multiline and dotall flags', { pattern: '(?ms)^Acme.Bot', matcher: CustomBotMatcher.Regex }],- // Python also accepts stacked and repeated flag groups; RegExp rejects both a leftover- // (?s) group in the body and a doubled letter in the flags argument.- ['stacked leading flag groups', { pattern: '(?i)(?s)acme.bot', matcher: CustomBotMatcher.Regex }],- ['a repeated flag letter', { pattern: '(?ii)acmebot', matcher: CustomBotMatcher.Regex }],- ])('accepts %s', (_name, overrides) => {- expect(validateCustomBotDefinition(definition(overrides))).toBeNull()- })- })-- describe('matchesValue', () => {- // The backend compiles a substring pattern with (?i), so the tester has to be- // case-insensitive too or it tells people the wrong thing.- test.each([- ['same case', 'AcmeBot/1.0', true],- ['different case', 'acmebot/1.0', true],- ['no match', 'Mozilla/5.0', false],- ])('substring matching, %s', (_name, value, expected) => {- expect(matchesValue(definition(), value)).toBe(expected)- })-- it('treats a substring pattern as a literal, not a regex', () => {- const literal = definition({ pattern: 'Acme.Bot' })-- expect(matchesValue(literal, 'Acme.Bot')).toBe(true)- expect(matchesValue(literal, 'AcmeXBot')).toBe(false)- })-- it('matches with a regex pattern', () => {- const regex = definition({ pattern: 'AcmeBot/[0-9]+', matcher: CustomBotMatcher.Regex })-- expect(matchesValue(regex, 'AcmeBot/12')).toBe(true)- expect(matchesValue(regex, 'AcmeBot/vNext')).toBe(false)- })-- it('applies stacked leading flag groups when matching', () => {- const regex = definition({ pattern: '(?i)(?s)acme.bot', matcher: CustomBotMatcher.Regex })-- expect(matchesValue(regex, 'ACME\nBOT')).toBe(true)- expect(matchesValue(regex, 'GlobexBot')).toBe(false)- })-- it('applies a leading (?i) flag so a case-insensitive rule matches', () => {- // ClickHouse regex matching is case-sensitive by default, so (?i) is the natural way to- // write one. new RegExp rejects the inline group, so without translation this reports no match.- const regex = definition({ pattern: '(?i)acmebot', matcher: CustomBotMatcher.Regex })-- expect(matchesValue(regex, 'ACMEBOT/1.0')).toBe(true)- expect(matchesValue(regex, 'Mozilla/5.0')).toBe(false)- })-- // Subnet membership is the one thing here a person cannot check by eye, so the tester- // answering it wrongly would be worse than not offering it.- test.each([- ['first address in range', '192.0.2.0/24', '192.0.2.0', true],- ['inside range', '192.0.2.0/24', '192.0.2.55', true],- ['last address in range', '192.0.2.0/24', '192.0.2.255', true],- ['just outside range', '192.0.2.0/24', '192.0.3.0', false],- ['neighbouring range', '192.0.2.0/24', '10.0.2.55', false],- ['bare address matches itself', '192.0.2.7', '192.0.2.7', true],- ['bare address rejects another', '192.0.2.7', '192.0.2.8', false],- ['range written with host bits still matches its network', '192.0.2.7/24', '192.0.2.99', true],- ['a v6 address inside a v6 range', '2001:db8::/32', '2001:db8:1234::1', true],- ['a v6 address outside a v6 range', '2001:db8::/32', '2001:dba9::1', false],- ['a v4 address is not inside a v6 range', '2001:db8::/32', '192.0.2.55', false],- ['a v6 address is not inside a v4 range', '192.0.2.0/24', '2001:db8::1', false],- ])('range matching, %s', (_name, pattern, value, expected) => {- expect(matchesValue(ipRule(pattern), value)).toBe(expected)- })-- it('does not match when the value is not an address', () => {- expect(matchesValue(ipRule('192.0.2.0/24'), 'not-an-ip')).toBe(false)- })- })-})diff --git a/frontend/src/scenes/settings/environment/customBotRulesUtils.test.ts b/frontend/src/scenes/settings/environment/customBotRulesUtils.test.tsnew file mode 100644index 000000000000..aa599370d5e1--- /dev/null+++ b/frontend/src/scenes/settings/environment/customBotRulesUtils.test.ts@@ -0,0 +1,300 @@+import { CustomBotCondition, CustomBotField, CustomBotMatcher, CustomBotRule } from '~/queries/schema/schema-general'+import { FilterLogicalOperator } from '~/types'++import {+ conditionMatchesValue,+ ruleMatchesValues,+ parseCustomBotRules,+ validateCustomBotCondition,+ validateCustomBotRule,+ validateCustomBotRuleSet,+} from './customBotRulesUtils'++const condition = (overrides: Partial<CustomBotCondition> = {}): CustomBotCondition => ({+ id: 'c1',+ key: CustomBotField.RawUserAgent,+ pattern: 'AcmeBot',+ matcher: CustomBotMatcher.Contains,+ ...overrides,+})++const rule = (overrides: Partial<CustomBotRule> = {}): CustomBotRule => ({+ id: '1',+ name: 'Acme scraper',+ combiner: FilterLogicalOperator.And,+ items: [condition()],+ ...overrides,+})++const ipCondition = (pattern: string): CustomBotCondition =>+ condition({ key: CustomBotField.IP, matcher: CustomBotMatcher.Cidr, pattern })++describe('customBotRulesUtils', () => {+ // These rules mirror the ones the API enforces. When they drift, a rule the editor calls valid+ // comes back as a 400 on save instead of an inline error next to the row.+ describe('validateCustomBotCondition', () => {+ test.each([+ ['empty pattern', { pattern: ' ' }, 'Add a value to match.'],+ [+ 'lookahead',+ { pattern: 'Acme(?=Bot)', matcher: CustomBotMatcher.Regex },+ 'This uses a lookahead, which is not supported here.',+ ],+ [+ 'unparsable regex',+ { pattern: 'Acme(', matcher: CustomBotMatcher.Regex },+ 'This is not a valid regular expression.',+ ],+ [+ // The server's re.compile rejects (?U), so the editor must too or Save 400s. Only+ // i, m and s are translated to JavaScript flags.+ 'a leading inline flag the server rejects',+ { pattern: '(?U)AcmeBot', matcher: CustomBotMatcher.Regex },+ 'This is not a valid regular expression.',+ ],+ [+ 'a range on a property that is not an IP',+ { matcher: CustomBotMatcher.Cidr, pattern: '192.0.2.0/24' },+ 'Ranges only work with the IP address property.',+ ],+ ])('rejects %s', (_name, overrides, expected) => {+ expect(validateCustomBotCondition(condition(overrides))).toEqual(expected)+ })++ test.each([+ ['a bare address', '192.0.2.7'],+ ['a v4 range', '192.0.2.0/24'],+ ['a v6 range', '2001:db8::/32'],+ ['host bits set', '192.0.2.7/24'],+ ])('accepts %s', (_name, pattern) => {+ expect(validateCustomBotCondition(ipCondition(pattern))).toBeNull()+ })++ test.each([+ ['a hostname', 'not-an-ip'],+ ['an octet over 255', '192.0.2.999'],+ // Python's ipaddress rejects leading zeros, so the tester must too or Save 400s.+ ['a leading-zero octet', '192.168.001.1'],+ ['a prefix wider than the family', '192.0.2.0/33'],+ ['too many parts', '192.0.2.0/24/8'],+ ])('rejects %s as a range', (_name, pattern) => {+ expect(validateCustomBotCondition(ipCondition(pattern))).toEqual('This is not a valid IP address or range.')+ })++ test.each([+ ['a plain substring', {}],+ ['a substring with regex metacharacters', { pattern: 'Acme (bot) v1.0' }],+ [+ 'an equality on a number',+ { key: CustomBotField.ScreenWidth, matcher: CustomBotMatcher.Exact, pattern: '800' },+ ],+ ['an anchored regex', { pattern: '^AcmeBot/[0-9]+$', matcher: CustomBotMatcher.Regex }],+ // The server and ClickHouse accept a leading inline flag group; JavaScript RegExp does+ // not, so these would wrongly block Save without the flag translation.+ ['a leading case-insensitive flag', { pattern: '(?i)(acme|globex)bot', matcher: CustomBotMatcher.Regex }],+ ['leading multiline and dotall flags', { pattern: '(?ms)^Acme.Bot', matcher: CustomBotMatcher.Regex }],+ // Python also accepts stacked and repeated flag groups; RegExp rejects both a leftover+ // (?s) group in the body and a doubled letter in the flags argument.+ ['stacked leading flag groups', { pattern: '(?i)(?s)acme.bot', matcher: CustomBotMatcher.Regex }],+ ['a repeated flag letter', { pattern: '(?ii)acmebot', matcher: CustomBotMatcher.Regex }],+ ])('accepts %s', (_name, overrides) => {+ expect(validateCustomBotCondition(condition(overrides))).toBeNull()+ })+ })++ describe('validateCustomBotRule', () => {+ test.each([+ ['an empty name', rule({ name: '' }), 'Give this bot a name.'],+ ['no conditions', rule({ items: [] }), 'Add at least one condition.'],+ ['an unusable condition', rule({ items: [condition({ pattern: '' })] }), 'Add a value to match.'],+ [+ // Dragging a condition into a rule can exceed the cap without the add button.+ 'too many conditions',+ rule({ items: Array.from({ length: 11 }, (_, i) => condition({ id: String(i) })) }),+ 'A rule can have at most 10 conditions.',+ ],+ ])('rejects %s', (_name, value, expected) => {+ expect(validateCustomBotRule(value)).toEqual(expected)+ })++ it('accepts a usable rule', () => {+ expect(validateCustomBotRule(rule())).toBeNull()+ })+ })++ describe('validateCustomBotRuleSet', () => {+ // The per-rule cap cannot see siblings, so a set over the aggregate budget would save as+ // valid in the editor and 400 on the server without this mirror.+ it('rejects a set over the aggregate condition budget', () => {+ const rules = Array.from({ length: 11 }, (_, i) =>+ rule({+ id: String(i),+ items: Array.from({ length: 10 }, (_, j) => condition({ id: `${i}-${j}` })),+ })+ )++ expect(validateCustomBotRuleSet(rules)).toEqual('You can have at most 100 conditions across all rules.')+ expect(validateCustomBotRuleSet(rules.slice(0, 10))).toBeNull()+ })+ })++ describe('conditionMatchesValue', () => {+ // The backend compiles a substring pattern with (?i), so the tester has to be+ // case-insensitive too or it tells people the wrong thing.+ test.each([+ ['same case', 'AcmeBot/1.0', true],+ ['different case', 'acmebot/1.0', true],+ ['no match', 'Mozilla/5.0', false],+ ])('substring matching, %s', (_name, value, expected) => {+ expect(conditionMatchesValue(condition(), value)).toBe(expected)+ })++ it('treats a substring pattern as a literal, not a regex', () => {+ const literal = condition({ pattern: 'Acme.Bot' })++ expect(conditionMatchesValue(literal, 'Acme.Bot')).toBe(true)+ expect(conditionMatchesValue(literal, 'AcmeXBot')).toBe(false)+ })++ // The backend compiles equality to an anchored pattern, so a substring hit must not count.+ test.each([+ ['the exact value', '800', '800', true],+ ['a longer value containing it', '800', '1800', false],+ ['a different case', 'AcmeBot', 'ACMEBOT', false],+ ])('equality matching, %s', (_name, pattern, value, expected) => {+ expect(conditionMatchesValue(condition({ matcher: CustomBotMatcher.Exact, pattern }), value)).toBe(expected)+ })++ it('matches with a regex pattern', () => {+ const regex = condition({ pattern: 'AcmeBot/[0-9]+', matcher: CustomBotMatcher.Regex })++ expect(conditionMatchesValue(regex, 'AcmeBot/12')).toBe(true)+ expect(conditionMatchesValue(regex, 'AcmeBot/vNext')).toBe(false)+ })++ it('applies stacked leading flag groups when matching', () => {+ const regex = condition({ pattern: '(?i)(?s)acme.bot', matcher: CustomBotMatcher.Regex })++ expect(conditionMatchesValue(regex, 'ACME\nBOT')).toBe(true)+ expect(conditionMatchesValue(regex, 'GlobexBot')).toBe(false)+ })++ it('applies a leading (?i) flag so a case-insensitive rule matches', () => {+ // ClickHouse regex matching is case-sensitive by default, so (?i) is the natural way to+ // write one. new RegExp rejects the inline group, so without translation this reports no match.+ const regex = condition({ pattern: '(?i)acmebot', matcher: CustomBotMatcher.Regex })++ expect(conditionMatchesValue(regex, 'ACMEBOT/1.0')).toBe(true)+ expect(conditionMatchesValue(regex, 'Mozilla/5.0')).toBe(false)+ })++ // Subnet membership is the one thing here a person cannot check by eye, so the tester+ // answering it wrongly would be worse than not offering it.+ test.each([+ ['first address in range', '192.0.2.0/24', '192.0.2.0', true],+ ['inside range', '192.0.2.0/24', '192.0.2.55', true],+ ['last address in range', '192.0.2.0/24', '192.0.2.255', true],+ ['just outside range', '192.0.2.0/24', '192.0.3.0', false],+ ['neighbouring range', '192.0.2.0/24', '10.0.2.55', false],+ ['bare address matches itself', '192.0.2.7', '192.0.2.7', true],+ ['bare address rejects another', '192.0.2.7', '192.0.2.8', false],+ ['range written with host bits still matches its network', '192.0.2.7/24', '192.0.2.99', true],+ ['a v6 address inside a v6 range', '2001:db8::/32', '2001:db8:1234::1', true],+ ['a v6 address outside a v6 range', '2001:db8::/32', '2001:dba9::1', false],+ ['a v4 address is not inside a v6 range', '2001:db8::/32', '192.0.2.55', false],+ ['a v6 address is not inside a v4 range', '192.0.2.0/24', '2001:db8::1', false],+ ])('range matching, %s', (_name, pattern, value, expected) => {+ expect(conditionMatchesValue(ipCondition(pattern), value)).toBe(expected)+ })++ it('does not match when the value is not an address', () => {+ expect(conditionMatchesValue(ipCondition('192.0.2.0/24'), 'not-an-ip')).toBe(false)+ })+ })++ describe('ruleMatchesValues', () => {+ const headless = rule({+ name: 'Headless 800x600',+ items: [+ condition({+ id: 'w',+ key: CustomBotField.ScreenWidth,+ matcher: CustomBotMatcher.Exact,+ pattern: '800',+ }),+ condition({+ id: 'h',+ key: CustomBotField.ScreenHeight,+ matcher: CustomBotMatcher.Exact,+ pattern: '600',+ }),+ ],+ })++ // The tester has to combine the way the query does, or it tells people a rule fires when+ // it will not.+ test.each([+ ['AND with both values', FilterLogicalOperator.And, { width: '800', height: '600' }, true],+ ['AND with one value', FilterLogicalOperator.And, { width: '800', height: '768' }, false],+ ['OR with one value', FilterLogicalOperator.Or, { width: '800', height: '768' }, true],+ ['OR with neither value', FilterLogicalOperator.Or, { width: '1024', height: '768' }, false],+ ])('%s', (_name, combiner, values, expected) => {+ expect(+ ruleMatchesValues(+ { ...headless, combiner },+ {+ [CustomBotField.ScreenWidth]: values.width,+ [CustomBotField.ScreenHeight]: values.height,+ }+ )+ ).toBe(expected)+ })+ })++ describe('parseCustomBotRules', () => {+ it('mints deterministic ids so id-less rules do not collapse in the id-keyed editor', () => {+ const raw = [rule({ id: '', name: 'One' }), rule({ id: '', name: 'Two' })]+ const parsed = parseCustomBotRules(raw)++ expect(parsed).toHaveLength(2)+ expect(parsed[0].id).toBeTruthy()+ expect(parsed[0].id).not.toEqual(parsed[1].id)+ // Deterministic ids: a random id would read as an endless unsaved change.+ expect(parseCustomBotRules(raw)).toEqual(parsed)+ })++ it('re-mints colliding ids so rules do not collapse in the id-keyed editor', () => {+ const parsed = parseCustomBotRules([rule({ id: 'dup' }), rule({ id: 'dup', name: 'Second' })])++ expect(parsed).toHaveLength(2)+ expect(parsed[0].id).not.toEqual(parsed[1].id)+ })++ it('re-mints even when an explicit id collides with a fallback id', () => {+ // A stored id can share the fallback shape; the minted replacement must still be unique.+ const parsed = parseCustomBotRules([rule({ id: 'rule-1' }), rule({ id: '', name: 'Second' })])++ const ids = parsed.map((r) => r.id)+ expect(new Set(ids).size).toEqual(ids.length)+ })++ it('keeps parseable rules and drops what does not parse', () => {+ const current = rule()++ // A malformed entry must be dropped, not blind-cast: it would otherwise throw in+ // validation during render and crash the settings scene. An unknown matcher must+ // also drop, or the editor calls valid what the server 400s. A pre-combiner flat+ // entry has no items, so it drops too.+ expect(+ parseCustomBotRules([+ current,+ 'garbage',+ { id: '1', name: 'Flat', key: '$raw_user_agent', matcher: 'contains', pattern: 'AcmeBot' },+ { id: 'x', items: [{}] },+ { items: [condition()], name: null },+ { id: 'y', name: 'n', items: [{ ...condition(), matcher: 'startswith' }] },+ ])+ ).toEqual([current])+ })+ })+})diff --git a/frontend/src/scenes/settings/environment/customBotDefinitionsUtils.ts b/frontend/src/scenes/settings/environment/customBotRulesUtils.tssimilarity index 55%rename from frontend/src/scenes/settings/environment/customBotDefinitionsUtils.tsrename to frontend/src/scenes/settings/environment/customBotRulesUtils.tsindex a1a3ba9d197a..ce98b7c16f4c 100644--- a/frontend/src/scenes/settings/environment/customBotDefinitionsUtils.ts+++ b/frontend/src/scenes/settings/environment/customBotRulesUtils.ts@@ -1,7 +1,11 @@-import { CustomBotDefinition, CustomBotField, CustomBotMatcher } from '~/queries/schema/schema-general'+import { CustomBotCondition, CustomBotField, CustomBotMatcher, CustomBotRule } from '~/queries/schema/schema-general'+import { FilterLogicalOperator } from '~/types'export const CUSTOM_BOT_CATEGORY = 'custom'-export const MAX_CUSTOM_BOT_DEFINITIONS = 50+export const MAX_CUSTOM_BOT_RULES = 50+export const MAX_CONDITIONS_PER_RULE = 10+// The per-list and per-rule caps multiply, so the aggregate cap is what limits a query.+export const MAX_TOTAL_CONDITIONS = 100export const MAX_PATTERN_LENGTH = 200export const MAX_NAME_LENGTH = 100@@ -26,10 +30,22 @@ export const CUSTOM_BOT_FIELD_OPTIONS: { value: CustomBotField; label: string }[const MATCHER_LABELS: Record<CustomBotMatcher, string> = {[CustomBotMatcher.Contains]: 'contains',+ [CustomBotMatcher.Exact]: 'equals',[CustomBotMatcher.Regex]: 'matches regex',[CustomBotMatcher.Cidr]: 'is in range',}+// "equals" and "contains" sit next to each other in the same select but differ in case handling,+// so each says which it is.+const MATCHER_TOOLTIPS: Partial<Record<CustomBotMatcher, string>> = {+ [CustomBotMatcher.Contains]: 'Case-insensitive',+ [CustomBotMatcher.Exact]: 'Case-sensitive, matches the whole value',+}++export function matcherLabel(matcher: CustomBotMatcher): string {+ return MATCHER_LABELS[matcher]+}+// Mirrors TRAFFIC_TYPE_BY_CATEGORY in// products/web_analytics/backend/hogql_queries/custom_bot_definitions.pyexport const CUSTOM_BOT_CATEGORY_OPTIONS: { value: string; label: string }[] = [@@ -45,21 +61,31 @@ export const CUSTOM_BOT_CATEGORY_OPTIONS: { value: string; label: string }[] = [{ value: 'headless_browser', label: 'Headless browser' },]+const NUMERIC_FIELDS = [CustomBotField.ScreenWidth, CustomBotField.ScreenHeight]+export function fieldLabel(key: CustomBotField): string {return CUSTOM_BOT_FIELD_OPTIONS.find((option) => option.value === key)?.label ?? key}/** Comparing an IP to a network range is the only sensible default, and only works on an IP. */-export function matcherOptionsFor(key: CustomBotField): { value: CustomBotMatcher; label: string }[] {+export function matcherOptionsFor(key: CustomBotField): { value: CustomBotMatcher; label: string; tooltip?: string }[] {const matchers =key === CustomBotField.IP- ? [CustomBotMatcher.Cidr, CustomBotMatcher.Contains, CustomBotMatcher.Regex]- : [CustomBotMatcher.Contains, CustomBotMatcher.Regex]- return matchers.map((matcher) => ({ value: matcher, label: MATCHER_LABELS[matcher] }))+ ? [CustomBotMatcher.Cidr, CustomBotMatcher.Contains, CustomBotMatcher.Exact, CustomBotMatcher.Regex]+ : [CustomBotMatcher.Contains, CustomBotMatcher.Exact, CustomBotMatcher.Regex]+ return matchers.map((matcher) => ({+ value: matcher,+ label: MATCHER_LABELS[matcher],+ tooltip: MATCHER_TOOLTIPS[matcher],+ }))}export function defaultMatcherFor(key: CustomBotField): CustomBotMatcher {- return key === CustomBotField.IP ? CustomBotMatcher.Cidr : CustomBotMatcher.Contains+ if (key === CustomBotField.IP) {+ return CustomBotMatcher.Cidr+ }+ // A screen dimension is a single number, so equality is the match someone means.+ return NUMERIC_FIELDS.includes(key) ? CustomBotMatcher.Exact : CustomBotMatcher.Contains}export function patternPlaceholderFor(key: CustomBotField, matcher: CustomBotMatcher): string {@@ -69,6 +95,10 @@ export function patternPlaceholderFor(key: CustomBotField, matcher: CustomBotMatif (matcher === CustomBotMatcher.Regex) {return key === CustomBotField.RawUserAgent ? 'AcmeBot/[0-9]+' : '^/api/'}+ // The contains placeholder for an IP is a prefix, which an equality match can never satisfy.+ if (matcher === CustomBotMatcher.Exact && key === CustomBotField.IP) {+ return '192.0.2.55'+ }return ({[CustomBotField.RawUserAgent]: 'AcmeBot',@@ -196,52 +226,77 @@ function parseCidr(pattern: string): { value: bigint; width: bigint; prefix: bigreturn { ...parsed, prefix: BigInt(prefixText) }}-export function validateCustomBotDefinition(definition: CustomBotDefinition): string | null {- if (!definition.name.trim()) {- return 'Give this bot a name.'- }- if (definition.name.length > MAX_NAME_LENGTH) {- return `Name cannot be longer than ${MAX_NAME_LENGTH} characters.`- }- if (!definition.pattern.trim()) {- return definition.matcher === CustomBotMatcher.Cidr+export function validateCustomBotCondition(condition: CustomBotCondition): string | null {+ if (!condition.pattern.trim()) {+ return condition.matcher === CustomBotMatcher.Cidr? 'Add an IP address or range to match.': 'Add a value to match.'}- if (definition.pattern.length > MAX_PATTERN_LENGTH) {+ if (condition.pattern.length > MAX_PATTERN_LENGTH) {return `Pattern cannot be longer than ${MAX_PATTERN_LENGTH} characters.`}- if (definition.matcher === CustomBotMatcher.Cidr) {- if (definition.key !== CustomBotField.IP) {+ if (condition.matcher === CustomBotMatcher.Cidr) {+ if (condition.key !== CustomBotField.IP) {return 'Ranges only work with the IP address property.'}- return parseCidr(definition.pattern) ? null : 'This is not a valid IP address or range.'+ return parseCidr(condition.pattern) ? null : 'This is not a valid IP address or range.'}- if (definition.matcher !== CustomBotMatcher.Regex) {+ if (condition.matcher !== CustomBotMatcher.Regex) {return null}for (const { pattern, label } of UNSUPPORTED_CONSTRUCTS) {- if (pattern.test(definition.pattern)) {+ if (pattern.test(condition.pattern)) {return `This uses a ${label}, which is not supported here.`}}try {- compileCustomBotRegex(definition.pattern)+ compileCustomBotRegex(condition.pattern)} catch {return 'This is not a valid regular expression.'}return null}-/** Whether a rule matches one property value, mirroring how the rule is compiled for the query. */-export function matchesValue(definition: CustomBotDefinition, value: string): boolean {- if (!value.trim() || validateCustomBotDefinition(definition)) {+export function validateCustomBotRule(rule: CustomBotRule): string | null {+ if (!rule.name.trim()) {+ return 'Give this bot a name.'+ }+ if (rule.name.length > MAX_NAME_LENGTH) {+ return `Name cannot be longer than ${MAX_NAME_LENGTH} characters.`+ }+ if (rule.items.length === 0) {+ return 'Add at least one condition.'+ }+ // Dragging a condition into a rule can exceed the cap without ever using the add button.+ if (rule.items.length > MAX_CONDITIONS_PER_RULE) {+ return `A rule can have at most ${MAX_CONDITIONS_PER_RULE} conditions.`+ }+ for (const condition of rule.items) {+ const error = validateCustomBotCondition(condition)+ if (error) {+ return error+ }+ }+ return null+}++export function validateCustomBotRuleSet(rules: CustomBotRule[]): string | null {+ const total = rules.reduce((sum, rule) => sum + rule.items.length, 0)+ if (total > MAX_TOTAL_CONDITIONS) {+ return `You can have at most ${MAX_TOTAL_CONDITIONS} conditions across all rules.`+ }+ return null+}++/** Whether a condition matches one property value, mirroring how it is compiled for the query. */+export function conditionMatchesValue(condition: CustomBotCondition, value: string): boolean {+ if (!value.trim() || validateCustomBotCondition(condition)) {return false}- if (definition.matcher === CustomBotMatcher.Cidr) {- const network = parseCidr(definition.pattern)+ if (condition.matcher === CustomBotMatcher.Cidr) {+ const network = parseCidr(condition.pattern)const candidate = parseIp(value.trim())if (!network || !candidate || network.width !== candidate.width) {return false@@ -249,25 +304,101 @@ export function matchesValue(definition: CustomBotDefinition, value: string): boconst mask = ((1n << network.prefix) - 1n) << (network.width - network.prefix)return (network.value & mask) === (candidate.value & mask)}- if (definition.matcher === CustomBotMatcher.Regex) {+ if (condition.matcher === CustomBotMatcher.Regex) {try {- return compileCustomBotRegex(definition.pattern).test(value)+ return compileCustomBotRegex(condition.pattern).test(value)} catch {return false}}- return value.toLowerCase().includes(definition.pattern.trim().toLowerCase())+ if (condition.matcher === CustomBotMatcher.Exact) {+ return value === condition.pattern.trim()+ }+ return value.toLowerCase().includes(condition.pattern.trim().toLowerCase())+}++/** Whether a rule matches the test values, one value per property, combined the way the query is. */+export function ruleMatchesValues(rule: CustomBotRule, values: Partial<Record<CustomBotField, string>>): boolean {+ if (validateCustomBotRule(rule)) {+ return false+ }+ const matches = rule.items.map((condition) => conditionMatchesValue(condition, values[condition.key] ?? ''))+ return rule.combiner === FilterLogicalOperator.Or ? matches.some(Boolean) : matches.every(Boolean)+}++function isCondition(value: unknown): value is CustomBotCondition {+ if (!value || typeof value !== 'object') {+ return false+ }+ const condition = value as CustomBotCondition+ // Enum membership matters: an unknown matcher would read as valid in the editor and then 400+ // on save against the server's strict parsing.+ return (+ typeof condition.pattern === 'string' &&+ CUSTOM_BOT_FIELD_OPTIONS.some((option) => option.value === condition.key) &&+ Object.values(CustomBotMatcher).includes(condition.matcher)+ )+}++/** Read stored rules, dropping entries that do not parse — including any saved by a+pre-combiner release. One bad entry must not take down the one surface that could fix it; the+caller compares lengths against the raw list to tell the user a save removes dropped entries.++Minted ids must be deterministic (index-based, not random): the saved-rules comparison runs per+render, and a random id would read as an endless unsaved change. */+export function parseCustomBotRules(raw: unknown): CustomBotRule[] {+ if (!Array.isArray(raw)) {+ return []+ }+ const rules: CustomBotRule[] = []+ // A shared or missing id collapses entries in the id-keyed drag-and-drop context.+ const seenIds = new Set<string>()+ const uniqueId = (candidate: string, fallback: string): string => {+ let id = candidate && !seenIds.has(candidate) ? candidate : fallback+ // The fallback can itself collide with an explicit id that happens to share its shape.+ let suffix = 0+ while (seenIds.has(id)) {+ id = `${fallback}-${suffix++}`+ }+ seenIds.add(id)+ return id+ }+ raw.forEach((entry, index) => {+ if (!entry || typeof entry !== 'object') {+ return+ }+ const current = entry as CustomBotRule+ if (!Array.isArray(current.items) || typeof current.name !== 'string' || !current.items.every(isCondition)) {+ return+ }+ rules.push({+ ...current,+ id: uniqueId(current.id, `rule-${index}`),+ combiner: current.combiner === FilterLogicalOperator.Or ? current.combiner : FilterLogicalOperator.And,+ items: current.items.map((condition, conditionIndex) => ({+ ...condition,+ id: uniqueId(condition.id, `rule-${index}-${conditionIndex}`),+ })),+ })+ })+ return rules}-export function sanitizeCustomBotDefinitions(definitions: CustomBotDefinition[]): CustomBotDefinition[] {- return definitions- .filter((definition) => definition.name.trim() && definition.pattern.trim())- .map((definition) => ({- id: definition.id,- name: definition.name.trim(),- key: definition.key,- pattern: definition.pattern.trim(),- matcher: definition.matcher,- category: definition.category || CUSTOM_BOT_CATEGORY,+export function sanitizeCustomBotRules(rules: CustomBotRule[]): CustomBotRule[] {+ return rules+ .map((rule) => ({+ id: rule.id,+ name: rule.name.trim(),+ category: rule.category || CUSTOM_BOT_CATEGORY,+ combiner: rule.combiner,+ items: rule.items+ .filter((condition) => condition.pattern.trim())+ .map((condition) => ({+ id: condition.id,+ key: condition.key,+ matcher: condition.matcher,+ pattern: condition.pattern.trim(),+ })),}))+ .filter((rule) => rule.name && rule.items.length > 0)}diff --git a/frontend/src/scenes/web-analytics/BotPropertyFilters.tsx b/frontend/src/scenes/web-analytics/BotPropertyFilters.tsxindex 0a58f92374ba..387249ccc7d4 100644--- a/frontend/src/scenes/web-analytics/BotPropertyFilters.tsx+++ b/frontend/src/scenes/web-analytics/BotPropertyFilters.tsx@@ -10,7 +10,7 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { IconWithCount } from 'lib/lemon-ui/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'-import { CUSTOM_BOT_CATEGORY } from 'scenes/settings/environment/customBotDefinitionsUtils'+import { CUSTOM_BOT_CATEGORY } from 'scenes/settings/environment/customBotRulesUtils'import { teamLogic } from 'scenes/teamLogic'import { WebAnalyticsPropertyFilters } from '~/queries/schema/schema-general'diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 6280eb9aaddd..4ad452ce8e00 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -125,7 +125,9 @@ from products.web_analytics.backend.hogql_queries.custom_bot_definitions importMAX_CUSTOM_BOT_DEFINITIONS,assert_patterns_compile as assert_custom_bot_patterns_compile,compiled_patterns as compiled_custom_bot_patterns,- validate_definition as validate_custom_bot_definition,+ parse_rules as parse_custom_bot_rules,+ validate_rule as validate_custom_bot_rule,+ validate_rule_set as validate_custom_bot_rule_set,)from products.workflows.backend.models.team_workflows_config import EmailTrackingConsentMode, TeamWorkflowsConfig@@ -1883,26 +1885,44 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin{"bounceRateDurationSeconds": "Must be between 1 and 120 seconds."})+ if "customBotDefinitions" in value and isinstance(value["customBotDefinitions"], list):+ # Cap before parsing, so an oversized list is rejected without instantiating a model+ # per entry.+ if len(value["customBotDefinitions"]) > MAX_CUSTOM_BOT_DEFINITIONS:+ raise exceptions.ValidationError(+ {"customBotDefinitions": f"You can define at most {MAX_CUSTOM_BOT_DEFINITIONS} bots."}+ )+ # Strict, so a malformed rule is rejected with a specific error rather than the+ # generic "Invalid modifier key.", and the stored list is normalized.+ try:+ parsed = parse_custom_bot_rules(value["customBotDefinitions"], strict=True)+ except ValueError as error:+ raise exceptions.ValidationError({"customBotDefinitions": str(error)})+ value = {**value, "customBotDefinitions": [rule.model_dump(exclude_none=True) for rule in parsed]}+try:modifiers = HogQLQueryModifiers(**value)except Exception:raise exceptions.ValidationError(f"Invalid modifier key.")if "customBotDefinitions" in value:- definitions = modifiers.customBotDefinitions or []- if len(definitions) > MAX_CUSTOM_BOT_DEFINITIONS:+ rules = modifiers.customBotDefinitions or []+ if len(rules) > MAX_CUSTOM_BOT_DEFINITIONS:raise exceptions.ValidationError({"customBotDefinitions": f"You can define at most {MAX_CUSTOM_BOT_DEFINITIONS} bots."})- for definition in definitions:+ for rule in rules:# An unusable pattern would break every query that reads $virt_is_bot for this# project, so it is rejected here rather than dropped silently at query time.try:- validate_custom_bot_definition(definition)+ validate_custom_bot_rule(rule)except ValueError as error:- raise exceptions.ValidationError({"customBotDefinitions": f"{definition.name}: {error}"})+ # An empty name would render as an orphaned leading colon.+ message = f"{rule.name}: {error}" if rule.name else str(error)+ raise exceptions.ValidationError({"customBotDefinitions": message})try:- assert_custom_bot_patterns_compile(compiled_custom_bot_patterns(definitions))+ validate_custom_bot_rule_set(rules)+ assert_custom_bot_patterns_compile(compiled_custom_bot_patterns(rules))except ValueError as error:raise exceptions.ValidationError({"customBotDefinitions": str(error)})diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex c7eef4e19f97..9834aecd192d 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -1215,44 +1215,71 @@ def team_api_test_factory():@parameterized.expand([- ("substring", {"key": "$raw_user_agent", "pattern": "AcmeBot", "matcher": "contains"}, True),- ("regex", {"key": "$raw_user_agent", "pattern": "AcmeBot/[0-9]+", "matcher": "regex"}, True),- ("ip range", {"key": "$ip", "pattern": "192.0.2.0/24", "matcher": "cidr"}, True),- ("another property", {"key": "$lib", "pattern": "posthog-python", "matcher": "contains"}, True),- ("empty pattern", {"key": "$raw_user_agent", "pattern": "", "matcher": "contains"}, False),- ("lookahead", {"key": "$raw_user_agent", "pattern": "Acme(?=Bot)", "matcher": "regex"}, False),- ("unparsable regex", {"key": "$raw_user_agent", "pattern": "Acme(", "matcher": "regex"}, False),- ("unusable ip range", {"key": "$ip", "pattern": "not-an-ip", "matcher": "cidr"}, False),+ ("substring", [{"key": "$raw_user_agent", "pattern": "AcmeBot", "matcher": "contains"}], True),+ ("regex", [{"key": "$raw_user_agent", "pattern": "AcmeBot/[0-9]+", "matcher": "regex"}], True),+ ("ip range", [{"key": "$ip", "pattern": "192.0.2.0/24", "matcher": "cidr"}], True),+ ("another property", [{"key": "$lib", "pattern": "posthog-python", "matcher": "contains"}], True),+ ("exact matcher", [{"key": "$screen_width", "pattern": "800", "matcher": "exact"}], True),+ (+ "multi-condition rule",+ [+ {"key": "$screen_width", "pattern": "800", "matcher": "exact"},+ {"key": "$screen_height", "pattern": "600", "matcher": "exact"},+ ],+ True,+ ),+ ("empty pattern", [{"key": "$raw_user_agent", "pattern": "", "matcher": "contains"}], False),+ ("lookahead", [{"key": "$raw_user_agent", "pattern": "Acme(?=Bot)", "matcher": "regex"}], False),+ ("unparsable regex", [{"key": "$raw_user_agent", "pattern": "Acme(", "matcher": "regex"}], False),+ ("unusable ip range", [{"key": "$ip", "pattern": "not-an-ip", "matcher": "cidr"}], False),# A range can only ever match an IP, so pairing it with a user agent is a mistake.("range on a user agent",- {"key": "$raw_user_agent", "pattern": "192.0.2.0/24", "matcher": "cidr"},+ [{"key": "$raw_user_agent", "pattern": "192.0.2.0/24", "matcher": "cidr"}],False,),("unsupported property",- {"key": "$some_other_property", "pattern": "acme", "matcher": "contains"},+ [{"key": "$some_other_property", "pattern": "acme", "matcher": "contains"}],+ False,+ ),+ (+ "one unusable condition fails the rule",+ [+ {"key": "$screen_width", "pattern": "800", "matcher": "exact"},+ {"key": "$screen_height", "pattern": "Acme(", "matcher": "regex"},+ ],False,),])def test_modifiers_customBotDefinitions_validation(- self, _name: str, definition: dict, should_succeed: bool+ self, _name: str, conditions: list[dict], should_succeed: bool) -> None:# A rule that cannot run would break every query that reads $virt_is_bot for this- # project, so it has to be rejected on save rather than dropped at query time.+ # project, so it has to be rejected on save rather than dropped silently at query time.response = self.client.patch(f"/api/environments/{self.team.id}",{"modifiers": {- "customBotDefinitions": [{"id": "1", "name": "Acme scraper", **definition}],+ "customBotDefinitions": [+ {+ "id": "1",+ "name": "Acme scraper",+ "combiner": "AND",+ "items": [+ {"id": f"c{index}", **condition} for index, condition in enumerate(conditions)+ ],+ }+ ],}},)if should_succeed:assert response.status_code == status.HTTP_200_OK, response.json()- assert response.json()["modifiers"]["customBotDefinitions"][0]["pattern"] == definition["pattern"]+ stored = response.json()["modifiers"]["customBotDefinitions"][0]+ assert stored["items"][0]["pattern"] == conditions[0]["pattern"]else:assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()diff --git a/posthog/hogql/functions/test/test_traffic_type_functions.py b/posthog/hogql/functions/test/test_traffic_type_functions.pyindex 0711375333ee..77cff376c9b6 100644--- a/posthog/hogql/functions/test/test_traffic_type_functions.py+++ b/posthog/hogql/functions/test/test_traffic_type_functions.py@@ -6,7 +6,7 @@ from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flusfrom parameterized import parameterized-from posthog.schema import CustomBotDefinition, CustomBotField, CustomBotMatcher, HogQLQueryModifiers+from posthog.schema import CustomBotCondition, CustomBotField, CustomBotMatcher, CustomBotRule, HogQLQueryModifiersfrom posthog.hogql import astfrom posthog.hogql.context import HogQLContext@@ -24,6 +24,8 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.query import execute_hogql_query+from posthog.schema_enums import FilterLogicalOperator+from products.actions.backend.models.action import Actionfrom products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONSfrom products.web_analytics.backend.hogql_queries.bot_ip_definitions import BOT_IP_DEFINITIONS@@ -651,7 +653,14 @@ class TestMacroExpansionGuard(BaseTest):# Without any rule the same nesting is allowed# (test_non_duplicating_macro_inside_duplicating_macro_is_allowed).modifiers = HogQLQueryModifiers(- customBotDefinitions=[CustomBotDefinition(id="1", name="Acme", key=key, pattern=pattern, matcher=matcher)]+ customBotDefinitions=[+ CustomBotRule(+ id="1",+ name="Acme",+ combiner=FilterLogicalOperator.AND_,+ items=[CustomBotCondition(id="c1", key=key, pattern=pattern, matcher=matcher)],+ )+ ])context = HogQLContext(team_id=self.team.pk, enable_select_queries=True, modifiers=modifiers)query = parse_select("SELECT __preview_isBot(toString(__preview_isBot(properties.x))) FROM events")@@ -702,11 +711,10 @@ CHROME_USER_AGENT = ()-def _custom_bot(**kwargs) -> CustomBotDefinition:- return CustomBotDefinition(+def _custom_condition(**kwargs) -> CustomBotCondition:+ return CustomBotCondition(**{- "id": "1",- "name": "Acme scraper",+ "id": "c1","key": CustomBotField.FIELD_RAW_USER_AGENT,"pattern": "AcmeBot","matcher": CustomBotMatcher.CONTAINS,@@ -715,10 +723,23 @@ def _custom_bot(**kwargs) -> CustomBotDefinition:)+def _custom_bot(**kwargs) -> CustomBotRule:+ condition_overrides = {key: kwargs.pop(key) for key in ("key", "pattern", "matcher") if key in kwargs}+ return CustomBotRule(+ **{+ "id": "1",+ "name": "Acme scraper",+ "combiner": FilterLogicalOperator.AND_,+ "items": kwargs.pop("items", None) or [_custom_condition(**condition_overrides)],+ **kwargs,+ }+ )++class TestCustomBotDefinitions(ClickhouseTestMixin, BaseTest):"""Runs the project's rules the way a query does: team settings, then ClickHouse."""- def _classify(self, definitions: list[CustomBotDefinition], properties: dict) -> tuple:+ def _classify(self, definitions: list[CustomBotRule], properties: dict) -> tuple:self.team.modifiers = {"customBotDefinitions": [d.model_dump(mode="json") for d in definitions]}self.team.save()@@ -868,3 +889,59 @@ class TestCustomBotDefinitions(ClickhouseTestMixin, BaseTest):)assert (is_bot, category) == (True, "no_user_agent")++ @parameterized.expand(+ [+ # The reason conditions combine: neither 800 wide nor 600 tall alone identifies the+ # headless browser, only the pair does.+ ("AND with both matching", FilterLogicalOperator.AND_, {"$screen_width": 800, "$screen_height": 600}, True),+ ("AND with one matching", FilterLogicalOperator.AND_, {"$screen_width": 800, "$screen_height": 768}, False),+ ("OR with one matching", FilterLogicalOperator.OR_, {"$screen_width": 800, "$screen_height": 768}, True),+ ("OR with none matching", FilterLogicalOperator.OR_, {"$screen_width": 1024, "$screen_height": 768}, False),+ ]+ )+ def test_a_multi_condition_rule_combines_the_way_it_says(+ self, _name: str, combiner: FilterLogicalOperator, screen: dict, expected: bool+ ):+ is_bot, name, _category = self._classify(+ [+ _custom_bot(+ name="Headless 800x600",+ combiner=combiner,+ items=[+ _custom_condition(+ id="w",+ key=CustomBotField.FIELD_SCREEN_WIDTH,+ matcher=CustomBotMatcher.EXACT,+ pattern="800",+ ),+ _custom_condition(+ id="h",+ key=CustomBotField.FIELD_SCREEN_HEIGHT,+ matcher=CustomBotMatcher.EXACT,+ pattern="600",+ ),+ ],+ )+ ],+ {"$raw_user_agent": CHROME_USER_AGENT, **screen},+ )++ assert (is_bot, name) == (expected, "Headless 800x600" if expected else "")++ def test_an_exact_condition_does_not_match_a_longer_value(self):+ # Equality is the reason the matcher exists: a contains rule on "800" would also flag every+ # 1800-wide screen.+ is_bot, _name, _category = self._classify(+ [+ _custom_bot(+ name="Exactly 800",+ key=CustomBotField.FIELD_SCREEN_WIDTH,+ matcher=CustomBotMatcher.EXACT,+ pattern="800",+ )+ ],+ {"$raw_user_agent": CHROME_USER_AGENT, "$screen_width": 1800},+ )++ assert is_bot is Falsediff --git a/posthog/hogql/functions/traffic_type.py b/posthog/hogql/functions/traffic_type.pyindex 00bc6423f8e0..da0007041b48 100644--- a/posthog/hogql/functions/traffic_type.py+++ b/posthog/hogql/functions/traffic_type.py@@ -18,9 +18,9 @@ products.web_analytics.backend.hogql_queries so that changes to bot data do nota HogQL review.A project can extend the built-in list with its own rules, which arrive as query modifiers. Each-rule matches one event property, so the rules are checked as an ordered chain ahead of the-built-ins rather than merged into the built-in pattern array. A project's own rule wins when both-match.+rule combines one or more single-property conditions, so the rules are checked as an ordered chain+ahead of the built-ins rather than merged into the built-in pattern array. A project's own rule+wins when both match."""from typing import TYPE_CHECKING, Optional@@ -39,8 +39,11 @@ from products.web_analytics.backend.hogql_queries.custom_bot_definitions importIP_FIELD,NUMERIC_FIELDS,USER_AGENT_FIELD,+ CidrCondition,CidrGroup,+ CompositeGroup,CustomBotGroup,+ PatternCondition,compile_definitions,)@@ -55,11 +58,12 @@ def _custom_groups(modifiers: Optional["HogQLQueryModifiers"]) -> list[CustomBotdef has_user_agent_rule(modifiers: Optional["HogQLQueryModifiers"]) -> bool:- """Whether the project has a rule on the user agent — the only rule kind that makes the one-arg- isLikelyBot expansion reference its argument twice (see the resolver's re-entrancy guard)."""+ """Whether the project has a condition on the user agent — the only condition kind that makes+ the one-arg isLikelyBot expansion reference its argument twice (see the resolver's re-entrancy+ guard)."""if modifiers is None or not modifiers.customBotDefinitions:return False- return any(definition.key == USER_AGENT_FIELD for definition in modifiers.customBotDefinitions)+ return any(item.key == USER_AGENT_FIELD for rule in modifiers.customBotDefinitions for item in rule.items)def _string_array(values: list[str]) -> ast.Array:@@ -105,7 +109,53 @@ class CustomRuleBranch:label: ast.Expr+def _safe_pattern_property(key: str, property_expr: ast.Expr) -> ast.Expr:+ # A numeric property (screen width/height) reaches hyperscan as a string, so a pattern like+ # "800" matches the value 800. String properties skip the cast.+ matched_property = ast.Call(name="toString", args=[property_expr]) if key in NUMERIC_FIELDS else property_expr+ return ast.Call(name="ifNull", args=[matched_property, ast.Constant(value="")])+++def _condition_expr(condition: PatternCondition | CidrCondition, property_expr: ast.Expr) -> ast.Expr:+ if isinstance(condition, CidrCondition):+ return _ip_group_match(_safe_ip_expr(property_expr), condition.prefixlen, (condition.network,))+ # The same hyperscan family as the grouped rules, so the save-time compile probe covers this+ # pattern too.+ return ast.Call(+ name="multiMatchAny",+ args=[_safe_pattern_property(condition.key, property_expr), _string_array([condition.pattern])],+ )+++def _composite_branch(group: CompositeGroup, args: list[ast.Expr], attr: str) -> Optional[CustomRuleBranch]:+ condition_exprs: list[ast.Expr] = []+ for condition in group.conditions:+ property_expr = _property_expr(condition.key, args)+ if property_expr is None:+ # For AND, one unreachable property makes the rule unanswerable as written, so skip+ # the whole rule rather than evaluate a partial version that could over-match. For OR,+ # a reachable condition matching means the full rule would match too, so evaluating+ # the reachable subset never over-matches and drops fewer events than skipping.+ if group.combiner != "OR":+ return None+ continue+ condition_exprs.append(_condition_expr(condition, property_expr))+ if not condition_exprs:+ return None+ matched: ast.Expr+ if len(condition_exprs) == 1:+ matched = condition_exprs[0]+ elif group.combiner == "OR":+ matched = ast.Or(exprs=condition_exprs)+ else:+ matched = ast.And(exprs=condition_exprs)+ return CustomRuleBranch(matched=matched, label=ast.Constant(value=getattr(group.definition, attr)))++def _custom_group_branch(group: CustomBotGroup, args: list[ast.Expr], attr: str) -> Optional[CustomRuleBranch]:+ if isinstance(group, CompositeGroup):+ return _composite_branch(group, args, attr)+property_expr = _property_expr(group.key, args)if property_expr is None:return None@@ -119,12 +169,7 @@ def _custom_group_branch(group: CustomBotGroup, args: list[ast.Expr], attr: str)multi_if_args.append(ast.Constant(value=0))index_call: ast.Expr = ast.Call(name="multiIf", args=multi_if_args)else:- # A numeric property (screen width/height) reaches multiMatchAllIndices as a string, so- # a rule pattern like "800" matches the value 800. String properties skip the cast.- matched_property = (- ast.Call(name="toString", args=[property_expr]) if group.key in NUMERIC_FIELDS else property_expr- )- safe_property = ast.Call(name="ifNull", args=[matched_property, ast.Constant(value="")])+ safe_property = _safe_pattern_property(group.key, property_expr)# arrayMin over ALL matching patterns, not multiMatchAnyIndex: when two of a project's own# rules match the same value, the one listed first wins. multiMatchAnyIndex would report# whichever pattern matches earliest in the string, so a specific rule listed above a broaddiff --git a/posthog/hogql/modifiers.py b/posthog/hogql/modifiers.pyindex 36a579c68075..be55cb6b63bf 100644--- a/posthog/hogql/modifiers.py+++ b/posthog/hogql/modifiers.py@@ -51,7 +51,7 @@ def create_default_modifiers_for_team() -> "HogQLQueryModifiers":from pydantic import ValidationError # noqa: PLC0415- from posthog.schema import CustomBotDefinition, CustomChannelRule, HogQLQueryModifiers # noqa: PLC0415+ from posthog.schema import CustomChannelRule, HogQLQueryModifiers # noqa: PLC0415if modifiers is None:modifiers = HogQLQueryModifiers()@@ -73,20 +73,15 @@ def create_default_modifiers_for_team(except ValidationError:passelif key == "customBotDefinitions":- # drop the definitions that don't parse, keep the rest — one bad entry should- # not take a project's whole bot list out of every query. A non-dict entry- # (from a hand-edited modifiers JSON) is unparseable, so drop it too rather than- # let it reach compile_definitions and crash every classification query.+ # parse_rules drops the entries that don't parse — one bad entry should not+ # take a project's whole bot list out of every query. warn_on_drop=False+ # because this runs per query; the API list and save paths report drops.+ from products.web_analytics.backend.hogql_queries.custom_bot_definitions import ( # noqa: PLC0415+ parse_rules,+ )+if isinstance(value, list):- definitions = []- for definition in value:- if not isinstance(definition, dict):- continue- try:- definitions.append(CustomBotDefinition(**definition))- except ValidationError:- pass- setattr(modifiers, key, definitions)+ setattr(modifiers, key, parse_rules(value, warn_on_drop=False))else:setattr(modifiers, key, value)diff --git a/posthog/hogql/test/test_modifiers.py b/posthog/hogql/test/test_modifiers.pyindex 01aa28adbd92..2c373ebff30b 100644--- a/posthog/hogql/test/test_modifiers.py+++ b/posthog/hogql/test/test_modifiers.py@@ -92,7 +92,12 @@ class TestModifiers(BaseTest):"customBotDefinitions": ["not-a-rule",{"pattern": "no name so invalid"},- {"id": "1", "name": "Acme", "key": "$raw_user_agent", "pattern": "AcmeBot", "matcher": "contains"},+ {+ "id": "1",+ "name": "Acme",+ "combiner": "AND",+ "items": [{"id": "c1", "key": "$raw_user_agent", "pattern": "AcmeBot", "matcher": "contains"}],+ },]}self.team.save()diff --git a/posthog/schema.py b/posthog/schema.pyindex 5fb80d5c567f..693b097204f3 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -4820,7 +4820,17 @@ class CohortPropertyFilter(BaseModel):value: int-class CustomBotDefinition(BaseModel):+class CustomBotCondition(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ id: str+ key: CustomBotField = Field(..., description="The event property this condition reads.")+ matcher: CustomBotMatcher+ pattern: str = Field(..., description="Matched against the property named by `key`.")+++class CustomBotRule(BaseModel):model_config = ConfigDict(extra="forbid",)@@ -4828,14 +4838,16 @@ class CustomBotDefinition(BaseModel):default=None,description="Reported by `$virt_traffic_category`. Defaults to `custom`.",)+ combiner: FilterLogicalOperator = Field(+ ...,+ description="Whether every condition must match (AND) or any one of them (OR).",+ )id: str- key: CustomBotField = Field(..., description="The event property this rule reads.")- matcher: CustomBotMatcher+ items: list[CustomBotCondition]name: str = Field(...,description=("Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches."),)- pattern: str = Field(..., description="Matched against the property named by `key`.")class CustomChannelCondition(BaseModel):@@ -5618,7 +5630,7 @@ class HogQLQueryModifiers(BaseModel):bounceRateDurationSeconds: float | None = NonebounceRatePageViewMode: BounceRatePageViewMode | None = NoneconvertToProjectTimezone: bool | None = None- customBotDefinitions: list[CustomBotDefinition] | None = None+ customBotDefinitions: list[CustomBotRule] | None = NonecustomChannelTypeRules: list[CustomChannelRule] | None = NonedataWarehouseEventsModifiers: list[DataWarehouseEventsModifier] | None = Nonedebug: bool | None = Nonediff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 7012a545c40f..57d94a755d66 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -904,6 +904,7 @@ class CustomBotField(StrEnum):class CustomBotMatcher(StrEnum):CONTAINS = "contains"REGEX = "regex"+ EXACT = "exact"CIDR = "cidr"diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex dc801caa25a7..abd6967e38de 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1206,6 +1206,13 @@ export const BounceRatePageViewModeApi = {UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',} as const+export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]++export const FilterLogicalOperatorApi = {+ And: 'AND',+ Or: 'OR',+} as const+export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]export const CustomBotFieldApi = {@@ -1230,28 +1237,29 @@ export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof Custexport const CustomBotMatcherApi = {Contains: 'contains',Regex: 'regex',+ Exact: 'exact',Cidr: 'cidr',} as const-export interface CustomBotDefinitionApi {- /** Reported by `$virt_traffic_category`. Defaults to `custom`. */- category?: string | null+export interface CustomBotConditionApi {id: string- /** The event property this rule reads. */+ /** The event property this condition reads. */key: CustomBotFieldApimatcher: CustomBotMatcherApi- /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */- name: string/** Matched against the property named by `key`. */pattern: string}-export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]--export const FilterLogicalOperatorApi = {- And: 'AND',- Or: 'OR',-} as const+export interface CustomBotRuleApi {+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */+ category?: string | null+ /** Whether every condition must match (AND) or any one of them (OR). */+ combiner: FilterLogicalOperatorApi+ id: string+ items: CustomBotConditionApi[]+ /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */+ name: string+}export type CustomChannelFieldApi = (typeof CustomChannelFieldApi)[keyof typeof CustomChannelFieldApi]@@ -1397,7 +1405,7 @@ export interface HogQLQueryModifiersApi {bounceRateDurationSeconds?: number | nullbounceRatePageViewMode?: BounceRatePageViewModeApi | nullconvertToProjectTimezone?: boolean | null- customBotDefinitions?: CustomBotDefinitionApi[] | null+ customBotDefinitions?: CustomBotRuleApi[] | nullcustomChannelTypeRules?: CustomChannelRuleApi[] | nulldataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | nulldebug?: boolean | nulldiff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex fcff13ed7952..33c7a0830597 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -1383,6 +1383,13 @@ export const BounceRatePageViewModeApi = {UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',} as const+export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]++export const FilterLogicalOperatorApi = {+ And: 'AND',+ Or: 'OR',+} as const+export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]export const CustomBotFieldApi = {@@ -1407,28 +1414,29 @@ export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof Custexport const CustomBotMatcherApi = {Contains: 'contains',Regex: 'regex',+ Exact: 'exact',Cidr: 'cidr',} as const-export interface CustomBotDefinitionApi {- /** Reported by `$virt_traffic_category`. Defaults to `custom`. */- category?: string | null+export interface CustomBotConditionApi {id: string- /** The event property this rule reads. */+ /** The event property this condition reads. */key: CustomBotFieldApimatcher: CustomBotMatcherApi- /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */- name: string/** Matched against the property named by `key`. */pattern: string}-export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]--export const FilterLogicalOperatorApi = {- And: 'AND',- Or: 'OR',-} as const+export interface CustomBotRuleApi {+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */+ category?: string | null+ /** Whether every condition must match (AND) or any one of them (OR). */+ combiner: FilterLogicalOperatorApi+ id: string+ items: CustomBotConditionApi[]+ /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */+ name: string+}export type CustomChannelFieldApi = (typeof CustomChannelFieldApi)[keyof typeof CustomChannelFieldApi]@@ -1574,7 +1582,7 @@ export interface HogQLQueryModifiersApi {bounceRateDurationSeconds?: number | nullbounceRatePageViewMode?: BounceRatePageViewModeApi | nullconvertToProjectTimezone?: boolean | null- customBotDefinitions?: CustomBotDefinitionApi[] | null+ customBotDefinitions?: CustomBotRuleApi[] | nullcustomChannelTypeRules?: CustomChannelRuleApi[] | nulldataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | nulldebug?: boolean | nulldiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex f0b9d9e45583..bdaa607727a7 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -334,6 +334,13 @@ export const BounceRatePageViewModeApi = {UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',} as const+export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]++export const FilterLogicalOperatorApi = {+ And: 'AND',+ Or: 'OR',+} as const+export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]export const CustomBotFieldApi = {@@ -358,28 +365,29 @@ export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof Custexport const CustomBotMatcherApi = {Contains: 'contains',Regex: 'regex',+ Exact: 'exact',Cidr: 'cidr',} as const-export interface CustomBotDefinitionApi {- /** Reported by `$virt_traffic_category`. Defaults to `custom`. */- category?: string | null+export interface CustomBotConditionApi {id: string- /** The event property this rule reads. */+ /** The event property this condition reads. */key: CustomBotFieldApimatcher: CustomBotMatcherApi- /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */- name: string/** Matched against the property named by `key`. */pattern: string}-export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]--export const FilterLogicalOperatorApi = {- And: 'AND',- Or: 'OR',-} as const+export interface CustomBotRuleApi {+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */+ category?: string | null+ /** Whether every condition must match (AND) or any one of them (OR). */+ combiner: FilterLogicalOperatorApi+ id: string+ items: CustomBotConditionApi[]+ /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */+ name: string+}export type CustomChannelFieldApi = (typeof CustomChannelFieldApi)[keyof typeof CustomChannelFieldApi]@@ -525,7 +533,7 @@ export interface HogQLQueryModifiersApi {bounceRateDurationSeconds?: number | nullbounceRatePageViewMode?: BounceRatePageViewModeApi | nullconvertToProjectTimezone?: boolean | null- customBotDefinitions?: CustomBotDefinitionApi[] | null+ customBotDefinitions?: CustomBotRuleApi[] | nullcustomChannelTypeRules?: CustomChannelRuleApi[] | nulldataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | nulldebug?: boolean | nulldiff --git a/products/web_analytics/backend/api/custom_bot_rules.py b/products/web_analytics/backend/api/custom_bot_rules.pyindex 37abdff365da..5ff7508f5931 100644--- a/products/web_analytics/backend/api/custom_bot_rules.py+++ b/products/web_analytics/backend/api/custom_bot_rules.py@@ -9,8 +9,6 @@ from rest_framework.exceptions import NotFound, PermissionDenied, ValidationErrofrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.schema import CustomBotDefinition-from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.models import Teamfrom posthog.models.organization import OrganizationMembership@@ -19,33 +17,33 @@ from products.web_analytics.backend.hogql_queries.custom_bot_definitions importCIDR_MATCHER,CUSTOM_BOT_FIELDS,MAX_CUSTOM_BOT_DEFINITIONS,+ MAX_ID_LENGTH,PATTERN_MATCHERS,assert_patterns_compile,compiled_patterns,- validate_definition,+ parse_rules,+ validate_rule,+ validate_rule_set,)_MATCHERS = (*PATTERN_MATCHERS, CIDR_MATCHER)+_COMBINERS = ("AND", "OR")_FIELD_LIST = ", ".join(CUSTOM_BOT_FIELDS)-class CustomBotRuleSerializer(serializers.Serializer):- id = serializers.CharField(read_only=True, help_text="Stable id for the rule. Pass it to the delete endpoint.")- name = serializers.CharField(- help_text="Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know."+class WebAnalyticsBotConditionSerializer(serializers.Serializer):+ id = serializers.CharField(+ required=False,+ max_length=MAX_ID_LENGTH,+ help_text="Stable id for the condition. Generated when omitted.",)- key = serializers.CharField(help_text=f"Event property the rule reads. One of: {_FIELD_LIST}.")+ key = serializers.CharField(help_text=f"Event property the condition reads. One of: {_FIELD_LIST}.")matcher = serializers.CharField(- help_text="How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property)."+ help_text="How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), 'exact' (case-sensitive equality), or 'cidr' (an IP network range, only valid with the `$ip` property).")pattern = serializers.CharField(help_text="Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24.")- category = serializers.CharField(- required=False,- allow_blank=False,- help_text="Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too.",- )def validate_key(self, value: str) -> str:if value not in CUSTOM_BOT_FIELDS:@@ -58,16 +56,43 @@ class CustomBotRuleSerializer(serializers.Serializer):return value+class WebAnalyticsBotRuleSerializer(serializers.Serializer):+ id = serializers.CharField(read_only=True, help_text="Stable id for the rule. Pass it to the delete endpoint.")+ name = serializers.CharField(+ help_text="Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know."+ )+ category = serializers.CharField(+ required=False,+ allow_blank=False,+ help_text="Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too.",+ )+ combiner = serializers.CharField(+ required=False,+ default="AND",+ help_text="How the conditions combine: 'AND' flags an event only when every condition matches, 'OR' when any one of them does.",+ )+ items = WebAnalyticsBotConditionSerializer(+ many=True,+ help_text="The conditions of this rule. Each one reads a single event property.",+ )++ def validate_combiner(self, value: str) -> str:+ if value not in _COMBINERS:+ raise serializers.ValidationError(f"Must be one of: {', '.join(_COMBINERS)}.")+ return value++class CustomBotRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"""A project's own bot rules, stored on the team and read by `Is bot`, `Bot name`, and thetraffic-type properties everywhere HogQL runs. A rule extends the built-in bot list rather thanreplacing it, so a project can flag a scraper PostHog does not know about."""scope_object = "web_analytics"- serializer_class = CustomBotRuleSerializer+ serializer_class = WebAnalyticsBotRuleSerializer- def _definitions(self) -> list[dict[str, Any]]:- return list((self.team.modifiers or {}).get("customBotDefinitions") or [])+ def _rules(self) -> list[dict[str, Any]]:+ raw = (self.team.modifiers or {}).get("customBotDefinitions") or []+ return [rule.model_dump(exclude_none=True) for rule in parse_rules(raw)]def _require_project_admin(self) -> None:# A rule reshapes bot classification across the whole project, and it is stored on the@@ -78,10 +103,10 @@ class CustomBotRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):raise PermissionDenied("Only project admins can change bot rules.")@staticmethod- def _save(team: Team, definitions: list[dict[str, Any]]) -> None:+ def _save(team: Team, rules: list[dict[str, Any]]) -> None:# Merge so replacing the rules never wipes another modifier the team relies on.modifiers = dict(team.modifiers or {})- modifiers["customBotDefinitions"] = definitions+ modifiers["customBotDefinitions"] = rulesteam.modifiers = modifiersteam.save(update_fields=["modifiers"])@@ -89,31 +114,38 @@ class CustomBotRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):operation_id="web_analytics_bot_rules_list",summary="List custom bot rules",description="The project's own bot rules, in the order they are checked at query time.",- responses={200: CustomBotRuleSerializer(many=True)},+ responses={200: WebAnalyticsBotRuleSerializer(many=True)},)def list(self, request: Request, **kwargs: Any) -> Response:- return Response(self._definitions())+ return Response(self._rules())@extend_schema(operation_id="web_analytics_bot_rules_create",summary="Create a custom bot rule",- description="Add one bot rule to the project. The pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.",- request=CustomBotRuleSerializer,- responses={201: CustomBotRuleSerializer},+ description="Add one bot rule to the project. A rule combines one or more single-property conditions with AND or OR. A pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.",+ request=WebAnalyticsBotRuleSerializer,+ responses={201: WebAnalyticsBotRuleSerializer},)def create(self, request: Request, **kwargs: Any) -> Response:self._require_project_admin()- serializer = CustomBotRuleSerializer(data=request.data)+ serializer = WebAnalyticsBotRuleSerializer(data=request.data)serializer.is_valid(raise_exception=True)data = serializer.validated_datarule = {"id": str(uuid4()),"name": data["name"],- "key": data["key"],- "matcher": data["matcher"],- "pattern": data["pattern"],+ "combiner": data["combiner"],+ "items": [+ {+ "id": item.get("id") or str(uuid4()),+ "key": item["key"],+ "matcher": item["matcher"],+ "pattern": item["pattern"],+ }+ for item in data["items"]+ ],}if data.get("category"):rule["category"] = data["category"]@@ -121,9 +153,9 @@ class CustomBotRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# Validate (and probe ClickHouse) before locking, so the row lock is held only for the# read-check-write and never across the ClickHouse round trip.try:- definition = CustomBotDefinition(**rule)- validate_definition(definition)- assert_patterns_compile(compiled_patterns([definition]))+ parsed = parse_rules([rule], strict=True)[0]+ validate_rule(parsed)+ assert_patterns_compile(compiled_patterns([parsed]))except ValueError as error:raise ValidationError(str(error))@@ -133,10 +165,14 @@ class CustomBotRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# Locks the Team row because the read-check-write below mutates team.modifiers itself;# there is no per-product config row for bot definitions to lock instead.team = Team.objects.select_for_update().get(pk=self.team.pk) # nosemgrep: hot-parent-row-select-for-update- definitions = list((team.modifiers or {}).get("customBotDefinitions") or [])- if len(definitions) >= MAX_CUSTOM_BOT_DEFINITIONS:+ rules = list((team.modifiers or {}).get("customBotDefinitions") or [])+ if len(rules) >= MAX_CUSTOM_BOT_DEFINITIONS:raise ValidationError(f"You can define at most {MAX_CUSTOM_BOT_DEFINITIONS} bots.")- self._save(team, [*definitions, rule])+ try:+ validate_rule_set([*parse_rules(rules, warn_on_drop=False), parsed])+ except ValueError as error:+ raise ValidationError(str(error))+ self._save(team, [*rules, rule])return Response(rule, status=201)@@ -153,9 +189,9 @@ class CustomBotRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# Locks the Team row because the read-check-write below mutates team.modifiers itself;# there is no per-product config row for bot definitions to lock instead.team = Team.objects.select_for_update().get(pk=self.team.pk) # nosemgrep: hot-parent-row-select-for-update- definitions = list((team.modifiers or {}).get("customBotDefinitions") or [])- remaining = [definition for definition in definitions if definition["id"] != pk]- if len(remaining) == len(definitions):+ rules = list((team.modifiers or {}).get("customBotDefinitions") or [])+ remaining = [entry for entry in rules if not (isinstance(entry, dict) and entry.get("id") == pk)]+ if len(remaining) == len(rules):raise NotFound("No such bot rule.")self._save(team, remaining)diff --git a/products/web_analytics/backend/api/test/test_custom_bot_rules.py b/products/web_analytics/backend/api/test/test_custom_bot_rules.pyindex 0eef6fda4812..44cb98d719fd 100644--- a/products/web_analytics/backend/api/test/test_custom_bot_rules.py+++ b/products/web_analytics/backend/api/test/test_custom_bot_rules.py@@ -22,7 +22,7 @@ class TestCustomBotRulesAPI(ClickhouseTestMixin, APIBaseTest):create = self.client.post(self._url(),- {"name": "Acme", "key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"},+ {"name": "Acme", "items": [{"key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"}]},)assert create.status_code == status.HTTP_403_FORBIDDEN, create.json()assert self.client.delete(self._url("any-id/")).status_code == status.HTTP_403_FORBIDDEN@@ -32,10 +32,11 @@ class TestCustomBotRulesAPI(ClickhouseTestMixin, APIBaseTest):def test_create_list_and_delete_round_trip(self) -> None:create = self.client.post(self._url(),- {"name": "Office scraper", "key": "$ip", "matcher": "cidr", "pattern": "192.0.2.0/24"},+ {"name": "Office scraper", "items": [{"key": "$ip", "matcher": "cidr", "pattern": "192.0.2.0/24"}]},)assert create.status_code == status.HTTP_201_CREATED, create.json()rule_id = create.json()["id"]+ assert [item["pattern"] for item in create.json()["items"]] == ["192.0.2.0/24"]self.team.refresh_from_db()stored = self.team.modifiers["customBotDefinitions"]@@ -49,27 +50,56 @@ class TestCustomBotRulesAPI(ClickhouseTestMixin, APIBaseTest):self.team.refresh_from_db()assert self.team.modifiers["customBotDefinitions"] == []- def test_create_preserves_other_modifiers(self) -> None:- self.team.modifiers = {"bounceRateDurationSeconds": 42}- self.team.save()-+ def test_create_a_multi_condition_rule(self) -> None:create = self.client.post(self._url(),- {"name": "Acme", "key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"},+ {+ "name": "Headless 800x600",+ "combiner": "AND",+ "items": [+ {"key": "$screen_width", "matcher": "exact", "pattern": "800"},+ {"key": "$screen_height", "matcher": "exact", "pattern": "600"},+ ],+ },)assert create.status_code == status.HTTP_201_CREATED, create.json()+ body = create.json()+ assert body["combiner"] == "AND"+ assert [(item["key"], item["matcher"], item["pattern"]) for item in body["items"]] == [+ ("$screen_width", "exact", "800"),+ ("$screen_height", "exact", "600"),+ ]self.team.refresh_from_db()- assert self.team.modifiers["bounceRateDurationSeconds"] == 42- assert len(self.team.modifiers["customBotDefinitions"]) == 1+ assert self.team.modifiers["customBotDefinitions"] == [body]@parameterized.expand([- ("unknown property", {"key": "$nope", "matcher": "contains", "pattern": "AcmeBot"}),- ("unknown matcher", {"key": "$raw_user_agent", "matcher": "startswith", "pattern": "AcmeBot"}),- ("cidr on a non-ip property", {"key": "$raw_user_agent", "matcher": "cidr", "pattern": "192.0.2.0/24"}),- ("regex clickhouse cannot run", {"key": "$raw_user_agent", "matcher": "regex", "pattern": "(?=lookahead)"}),- ("blank category", {"key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot", "category": ""}),+ ("unknown property", {"items": [{"key": "$nope", "matcher": "contains", "pattern": "AcmeBot"}]}),+ ("unknown matcher", {"items": [{"key": "$raw_user_agent", "matcher": "startswith", "pattern": "AcmeBot"}]}),+ (+ "cidr on a non-ip property",+ {"items": [{"key": "$raw_user_agent", "matcher": "cidr", "pattern": "192.0.2.0/24"}]},+ ),+ (+ "regex clickhouse cannot run",+ {"items": [{"key": "$raw_user_agent", "matcher": "regex", "pattern": "(?=lookahead)"}]},+ ),+ (+ "blank category",+ {"items": [{"key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"}], "category": ""},+ ),+ (+ # A shared id collapses entries in the id-keyed editor.+ "duplicate condition ids",+ {+ "combiner": "AND",+ "items": [+ {"id": "a", "key": "$screen_width", "matcher": "exact", "pattern": "800"},+ {"id": "a", "key": "$screen_height", "matcher": "exact", "pattern": "600"},+ ],+ },+ ),])def test_rejects_unusable_rules(self, _name: str, body: dict) -> None:@@ -78,6 +108,31 @@ class TestCustomBotRulesAPI(ClickhouseTestMixin, APIBaseTest):self.team.refresh_from_db()assert (self.team.modifiers or {}).get("customBotDefinitions", []) == []+ def test_create_rejects_a_rule_set_over_the_aggregate_condition_budget(self) -> None:+ # The per-rule serializer caps cannot see the stored rules, so the budget check must.+ self.team.modifiers = {+ "customBotDefinitions": [+ {+ "id": str(i),+ "name": f"Bot {i}",+ "combiner": "AND",+ "items": [+ {"id": f"{i}-{j}", "key": "$raw_user_agent", "matcher": "contains", "pattern": f"Bot{i}-{j}"}+ for j in range(10)+ ],+ }+ for i in range(10)+ ]+ }+ self.team.save()++ create = self.client.post(+ self._url(),+ {"name": "One too many", "items": [{"key": "$raw_user_agent", "matcher": "contains", "pattern": "x"}]},+ )+ assert create.status_code == status.HTTP_400_BAD_REQUEST, create.json()+ assert "across all rules" in str(create.json())+def test_delete_unknown_id_is_not_found(self) -> None:response = self.client.delete(self._url("does-not-exist/"))assert response.status_code == status.HTTP_404_NOT_FOUNDdiff --git a/products/web_analytics/backend/hogql_queries/custom_bot_definitions.py b/products/web_analytics/backend/hogql_queries/custom_bot_definitions.pyindex ada60e3df9f7..3844f01250ae 100644--- a/products/web_analytics/backend/hogql_queries/custom_bot_definitions.py+++ b/products/web_analytics/backend/hogql_queries/custom_bot_definitions.py@@ -5,9 +5,11 @@ BOT_DEFINITIONS only covers bots that declare themselves in the user agent, andones we know about. A project adds its own rules in project settings when a scraper matters tothem but is missing from that list — an internal load test, a partner integration, a niche crawler.-Each rule matches one event property. The user agent says who a caller claims to be, so it is the-default, but a bot that sends a browser user agent is only identifiable by where it comes from-(`$ip`) or what it calls with (`$lib`), which is why the property is selectable.+A rule holds one or more conditions, each on one event property, combined with AND or OR. The user+agent says who a caller claims to be, so it is the default property, but a bot that sends a browser+user agent is only identifiable by where it comes from (`$ip`), what it calls with (`$lib`), or a+combination of properties no real browser produces (an 800x600 screen), which is why the property+is selectable and conditions can be combined.The definitions are stored on `team.modifiers` and reach HogQL through`HogQLQueryModifiers.customBotDefinitions`, so they extend `$virt_is_bot`, `$virt_bot_name`,@@ -18,7 +20,7 @@ Substring and regex rules end up inside a ClickHouse `multiMatchAllIndices` callwith hyperscan. Hyperscan supports less than PCRE, and a pattern it rejects fails every query thatreads one of those fields for the project. Two guards keep that from happening:-- `validate_definition` runs on save and rejects what we can catch in Python.+- `validate_rule` runs on save and rejects what we can catch in Python.- `assert_patterns_compile` asks ClickHouse itself whether the patterns compile, because Python's`re` accepting a pattern does not mean hyperscan will.@@ -28,7 +30,7 @@ to the API before a rule tightened cannot break every query for the project.import refrom ipaddress import ip_network-from typing import TYPE_CHECKING, Union+from typing import TYPE_CHECKING, Literal, Unionimport structlog@@ -38,14 +40,20 @@ from products.web_analytics.backend.hogql_queries.bot_definitions import BotDefifrom products.web_analytics.backend.hogql_queries.bot_ip_definitions import ipv6_prefix_groupsif TYPE_CHECKING:- from posthog.schema import CustomBotDefinition+ from posthog.schema import CustomBotRulelogger = structlog.get_logger(__name__)-# Bounds the work added to every query that reads a classification field.+# Bounds the work added to every query that reads a classification field. The per-list and+# per-rule caps multiply, so the aggregate cap is what actually limits a query: modifiers can+# also arrive in a client-supplied query, and each condition is a hyperscan call per row.MAX_CUSTOM_BOT_DEFINITIONS = 50+MAX_CONDITIONS_PER_RULE = 10+MAX_TOTAL_CONDITIONS = 100MAX_PATTERN_LENGTH = 200MAX_NAME_LENGTH = 100+# Ids are stored on team.modifiers, which is read on every query for the team.+MAX_ID_LENGTH = 100USER_AGENT_FIELD = "$raw_user_agent"IP_FIELD = "$ip"@@ -77,7 +85,7 @@ CUSTOM_BOT_FIELDS: dict[str, str] = {NUMERIC_FIELDS: frozenset[str] = frozenset({"$screen_width", "$screen_height"})CIDR_MATCHER = "cidr"-PATTERN_MATCHERS = ("contains", "regex")+PATTERN_MATCHERS = ("contains", "regex", "exact")# Category used when a project does not pick one.CUSTOM_CATEGORY = "custom"@@ -141,7 +149,33 @@ class CidrGroup:definitions: list[BotDefinition]-CustomBotGroup = Union[PatternGroup, CidrGroup]+@frozen+class PatternCondition:+ key: str+ pattern: str+++@frozen+class CidrCondition:+ key: str+ prefixlen: int+ network: str+++@frozen+class CompositeGroup:+ """One rule with several conditions, matched when they combine true under `combiner`.++ Unlike the single-condition groups, a composite rule cannot share a hyperscan pass with other+ rules — its conditions read different properties — so each one is its own group.+ """++ combiner: Literal["AND", "OR"]+ conditions: list[Union[PatternCondition, CidrCondition]]+ definition: BotDefinition+++CustomBotGroup = Union[PatternGroup, CidrGroup, CompositeGroup]def _escape_literal(value: str) -> str:@@ -149,9 +183,14 @@ def _escape_literal(value: str) -> str:def compile_pattern(pattern: str, matcher: str) -> str:- """Turn a substring or regex rule into the regex handed to multiMatchAllIndices."""+ """Turn a substring, equality, or regex condition into the regex handed to hyperscan."""if matcher == "regex":return pattern+ # Equality compiles to an anchored literal so it can share the hyperscan pass with the other+ # matchers. Case-sensitive: it exists for values like a screen width or a country code, where+ # the exact bytes are the point.+ if matcher == "exact":+ return f"^{_escape_literal(pattern)}$"# Substring matching is case-insensitive so people do not have to think about how an SDK cases# its user agent.return f"(?i){_escape_literal(pattern)}"@@ -206,17 +245,76 @@ def validate_pattern(pattern: str, matcher: str, key: str) -> None:raise ValueError(f"Pattern is not a valid regular expression: {error}.") from error-def validate_definition(definition: "CustomBotDefinition") -> None:- """Raise ValueError when a definition cannot be used."""- if not definition.name or not definition.name.strip():+def validate_rule(rule: "CustomBotRule") -> None:+ """Raise ValueError when a rule cannot be used."""+ if not rule.name or not rule.name.strip():raise ValueError("Bot name cannot be empty.")- if len(definition.name) > MAX_NAME_LENGTH:+ if len(rule.name) > MAX_NAME_LENGTH:raise ValueError(f"Bot name cannot be longer than {MAX_NAME_LENGTH} characters.")- if definition.key not in CUSTOM_BOT_FIELDS:- raise ValueError(f"Cannot match on property '{definition.key}'.")- if definition.category and definition.category not in TRAFFIC_TYPE_BY_CATEGORY:- raise ValueError(f"Unknown category '{definition.category}'.")- validate_pattern(definition.pattern, definition.matcher.value, definition.key)+ if rule.category and rule.category not in TRAFFIC_TYPE_BY_CATEGORY:+ raise ValueError(f"Unknown category '{rule.category}'.")+ if len(rule.id) > MAX_ID_LENGTH:+ raise ValueError(f"Rule id cannot be longer than {MAX_ID_LENGTH} characters.")+ if not rule.items:+ raise ValueError("A rule needs at least one condition.")+ if len(rule.items) > MAX_CONDITIONS_PER_RULE:+ raise ValueError(f"A rule can have at most {MAX_CONDITIONS_PER_RULE} conditions.")+ # A shared id collapses entries in the editor's id-keyed drag-and-drop context.+ seen_ids = {rule.id}+ for item in rule.items:+ if len(item.id) > MAX_ID_LENGTH:+ raise ValueError(f"Condition id cannot be longer than {MAX_ID_LENGTH} characters.")+ if item.id in seen_ids:+ raise ValueError("Condition ids must be unique within a rule and differ from the rule id.")+ seen_ids.add(item.id)+ if item.key not in CUSTOM_BOT_FIELDS:+ raise ValueError(f"Cannot match on property '{item.key}'.")+ validate_pattern(item.pattern, item.matcher.value, item.key)+++def validate_rule_set(rules: list["CustomBotRule"]) -> None:+ """Raise ValueError when the rules together exceed the aggregate condition budget."""+ total = sum(len(rule.items) for rule in rules)+ if total > MAX_TOTAL_CONDITIONS:+ raise ValueError(f"You can have at most {MAX_TOTAL_CONDITIONS} conditions across all rules.")+++def parse_rules(raw: list, strict: bool = False, warn_on_drop: bool = True) -> list["CustomBotRule"]:+ """Parse stored or submitted rules.++ By default an entry that does not parse — including one saved by a pre-combiner release — is+ dropped: one bad entry must not take a project's whole bot list out of every query. `strict`+ raises instead, for the save paths, where dropping would lose a rule silently.++ `warn_on_drop=False` is for the per-query path, where one permanently bad stored entry would+ otherwise log in proportion to the team's query volume.+ """+ from pydantic import ValidationError # noqa: PLC0415 — keeps pydantic models off the django.setup import path++ from posthog.schema import CustomBotRule # noqa: PLC0415 — same++ rules: list[CustomBotRule] = []+ for entry in raw:+ if isinstance(entry, CustomBotRule):+ rules.append(entry)+ continue+ try:+ if not isinstance(entry, dict):+ raise ValueError("Each rule must be an object.")+ rules.append(CustomBotRule(**entry))+ except (ValidationError, ValueError, TypeError) as error:+ if strict:+ raise ValueError(f"Invalid bot rule: {error}") from error+ if warn_on_drop:+ # A dropped rule stops classifying with no other trace, so make the drop visible+ # the same way the bypassed compile probe is.+ logger.warning(+ "custom_bot_rule_dropped",+ entry_id=str(entry.get("id", ""))[:MAX_ID_LENGTH] if isinstance(entry, dict) else "",+ name=str(entry.get("name", ""))[:MAX_NAME_LENGTH] if isinstance(entry, dict) else "",+ error=str(error),+ )+ return rules# ClickHouse codes that mean "this pattern is the problem": BAD_ARGUMENTS and@@ -267,57 +365,109 @@ def assert_patterns_compile(patterns: list[str]) -> None:return-def _to_bot_definition(definition: "CustomBotDefinition") -> BotDefinition:- category = definition.category or CUSTOM_CATEGORY+def _to_bot_definition(rule: "CustomBotRule") -> BotDefinition:+ category = rule.category or CUSTOM_CATEGORYreturn BotDefinition(- name=definition.name,+ name=rule.name,category=category,traffic_type=TRAFFIC_TYPE_BY_CATEGORY.get(category, "Bot"),# A project's own label is the only operator we have for a bot we don't know.- operator=definition.name,+ operator=rule.name,)-def compile_definitions(definitions: list["CustomBotDefinition"] | None) -> list[CustomBotGroup]:- """Compile a project's definitions into the groups the HogQL builder emits.+def _compile_composite(rule: "CustomBotRule") -> CompositeGroup:+ conditions: list[Union[PatternCondition, CidrCondition]] = []+ for item in rule.items:+ if item.matcher.value == CIDR_MATCHER:+ prefixlen, network = compile_cidr(item.pattern)+ conditions.append(CidrCondition(key=item.key, prefixlen=prefixlen, network=network))+ else:+ conditions.append(PatternCondition(key=item.key, pattern=compile_pattern(item.pattern, item.matcher.value)))+ combiner: Literal["AND", "OR"] = "OR" if rule.combiner.value == "OR" else "AND"+ return CompositeGroup(combiner=combiner, conditions=conditions, definition=_to_bot_definition(rule))+++def compile_definitions(rules: list["CustomBotRule"] | None) -> list[CustomBotGroup]:+ """Compile a project's rules into the groups the HogQL builder emits.- Rules that match the same property the same way share a group, and the groups come back in the- order their first rule appears, which is the order they are checked at query time.+ Contiguous one-condition rules that match the same property the same way share a group — one+ hyperscan pass over that property at query time. A rule with several conditions becomes its+ own group. The groups come back in list order, which is the order they are checked at query+ time, so the editor's drag-to-reorder is the precedence.- Unusable definitions are dropped rather than raised on: one saved before a rule tightened, or+ Unusable rules are dropped rather than raised on: one saved before a rule tightened, orwritten straight to the API, must not break every query for the project."""- if not definitions:+ if not rules:return []- # (property, kind) -> the rules that share that group. Insertion order is the order the groups- # are checked, so a dict keeps first appearance meaningful.- buckets: dict[tuple[str, str], list[CustomBotDefinition]] = {}- for definition in definitions[:MAX_CUSTOM_BOT_DEFINITIONS]:+ # Contiguous one-condition rules on the same (property, kind) share a group — one hyperscan+ # pass. Any other rule in between (a composite, or a rule on another property) closes the run:+ # the editor promises list order is precedence, so a later rule must never slide into a group+ # positioned above something listed before it. Interleaved orderings therefore degrade to one+ # group per rule; a raised MAX_CUSTOM_BOT_DEFINITIONS should revisit this.+ open_bucket_key: tuple[str, str] | None = None+ open_bucket: list[CustomBotRule] = []+ order: list[Union[tuple[str, str, list[CustomBotRule]], CustomBotRule]] = []+ total_conditions = 0+ for rule in rules[:MAX_CUSTOM_BOT_DEFINITIONS]:try:- validate_definition(definition)+ validate_rule(rule)except ValueError:continue- kind = CIDR_MATCHER if definition.matcher.value == CIDR_MATCHER else "pattern"- buckets.setdefault((definition.key, kind), []).append(definition)-- return [- CidrGroup(- key=key,- networks=[compile_cidr(rule.pattern) for rule in rules],- definitions=[_to_bot_definition(rule) for rule in rules],- )- if kind == CIDR_MATCHER- else PatternGroup(- key=key,- patterns=[compile_pattern(rule.pattern, rule.matcher.value) for rule in rules],- definitions=[_to_bot_definition(rule) for rule in rules],- )- for (key, kind), rules in buckets.items()- ]---def compiled_patterns(definitions: list["CustomBotDefinition"] | None) -> list[str]:- """Every regex a project's definitions put in front of hyperscan, for the save-time check."""- groups = compile_definitions(definitions)- return [pattern for group in groups if isinstance(group, PatternGroup) for pattern in group.patterns]+ # The aggregate budget is enforced here as well as on save, because modifiers can arrive+ # in a client-supplied query that never went through a save path. Stop rather than skip:+ # dropping only the oversized rule would let a later rule jump the precedence order.+ total_conditions += len(rule.items)+ if total_conditions > MAX_TOTAL_CONDITIONS:+ break+ if len(rule.items) > 1:+ order.append(rule)+ open_bucket_key = None+ continue+ item = rule.items[0]+ kind = CIDR_MATCHER if item.matcher.value == CIDR_MATCHER else "pattern"+ bucket_key = (str(item.key), kind)+ if bucket_key != open_bucket_key:+ open_bucket_key = bucket_key+ open_bucket = []+ order.append((str(item.key), kind, open_bucket))+ open_bucket.append(rule)++ groups: list[CustomBotGroup] = []+ for entry in order:+ if not isinstance(entry, tuple):+ groups.append(_compile_composite(entry))+ continue+ key, kind, bucket = entry+ if kind == CIDR_MATCHER:+ groups.append(+ CidrGroup(+ key=key,+ networks=[compile_cidr(rule.items[0].pattern) for rule in bucket],+ definitions=[_to_bot_definition(rule) for rule in bucket],+ )+ )+ else:+ groups.append(+ PatternGroup(+ key=key,+ patterns=[compile_pattern(rule.items[0].pattern, rule.items[0].matcher.value) for rule in bucket],+ definitions=[_to_bot_definition(rule) for rule in bucket],+ )+ )+ return groups+++def compiled_patterns(rules: list["CustomBotRule"] | None) -> list[str]:+ """Every regex a project's rules put in front of hyperscan, for the save-time check."""+ patterns: list[str] = []+ for group in compile_definitions(rules):+ if isinstance(group, PatternGroup):+ patterns.extend(group.patterns)+ elif isinstance(group, CompositeGroup):+ patterns.extend(+ condition.pattern for condition in group.conditions if isinstance(condition, PatternCondition)+ )+ return patternsdiff --git a/products/web_analytics/backend/hogql_queries/test/test_custom_bot_definitions.py b/products/web_analytics/backend/hogql_queries/test/test_custom_bot_definitions.pyindex 26a8588239d0..46003234ad55 100644--- a/products/web_analytics/backend/hogql_queries/test/test_custom_bot_definitions.py+++ b/products/web_analytics/backend/hogql_queries/test/test_custom_bot_definitions.py@@ -3,29 +3,38 @@ from posthog.test.base import BaseTest, ClickhouseTestMixinfrom parameterized import parameterized-from posthog.schema import CustomBotDefinition, CustomBotField, CustomBotMatcher+from posthog.schema import CustomBotCondition, CustomBotField, CustomBotMatcher, CustomBotRule++from posthog.hogql import ast+from posthog.hogql.functions.traffic_type import _composite_branch++from posthog.schema_enums import FilterLogicalOperatorfrom products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONSfrom products.web_analytics.backend.hogql_queries.custom_bot_definitions import (+ MAX_CONDITIONS_PER_RULE,MAX_CUSTOM_BOT_DEFINITIONS,MAX_PATTERN_LENGTH,+ MAX_TOTAL_CONDITIONS,TRAFFIC_TYPE_BY_CATEGORY,CidrGroup,+ CompositeGroup,PatternGroup,assert_patterns_compile,compile_cidr,compile_definitions,compile_pattern,compiled_patterns,- validate_definition,+ parse_rules,+ validate_rule,+ validate_rule_set,)-def definition(**kwargs) -> CustomBotDefinition:- return CustomBotDefinition(+def condition(**kwargs) -> CustomBotCondition:+ return CustomBotCondition(**{- "id": "1",- "name": "Acme scraper",+ "id": "c1","key": CustomBotField.FIELD_RAW_USER_AGENT,"pattern": "AcmeBot","matcher": CustomBotMatcher.CONTAINS,@@ -34,8 +43,23 @@ def definition(**kwargs) -> CustomBotDefinition:)-def cidr_definition(**kwargs) -> CustomBotDefinition:- return definition(+def rule(+ *, items: list[CustomBotCondition] | None = None, combiner=FilterLogicalOperator.AND_, **kwargs+) -> CustomBotRule:+ condition_overrides = {key: kwargs.pop(key) for key in ("key", "pattern", "matcher") if key in kwargs}+ return CustomBotRule(+ **{+ "id": "1",+ "name": "Acme scraper",+ "combiner": combiner,+ "items": items if items is not None else [condition(**condition_overrides)],+ **kwargs,+ }+ )+++def cidr_rule(**kwargs) -> CustomBotRule:+ return rule(**{"key": CustomBotField.FIELD_IP, "matcher": CustomBotMatcher.CIDR, "pattern": "192.0.2.0/24", **kwargs})@@ -55,6 +79,17 @@ class TestPatternCompilation:def test_regex_is_passed_through(self):assert compile_pattern("AcmeBot/[0-9]+", "regex") == "AcmeBot/[0-9]+"+ @parameterized.expand(+ [+ # Unanchored, "800" would also flag every 1800-wide screen; unescaped, "1.5" would+ # also match "125".+ ("a number", "800", "^800$"),+ ("a value with metacharacters", "1.5", r"^1\.5$"),+ ]+ )+ def test_exact_compiles_to_an_anchored_literal(self, _name: str, pattern: str, expected: str):+ assert compile_pattern(pattern, "exact") == expected+@parameterized.expand([# The IP matcher compares in IPv6 space, so an IPv4 range shifts by 96 bits and its@@ -98,11 +133,45 @@ class TestValidation:"not a valid regular expression",),("unknown category", {"category": "not_a_category"}, "Unknown category"),+ ("no conditions", {"items": []}, "at least one condition"),+ # Ids are stored on team.modifiers, which is read on every query for the team.+ ("oversized rule id", {"id": "a" * 101}, "Rule id cannot be longer"),])- def test_rejects_unusable_definitions(self, _name: str, overrides: dict, expected_message: str):+ def test_rejects_unusable_rules(self, _name: str, overrides: dict, expected_message: str):with pytest.raises(ValueError, match=expected_message):- validate_definition(definition(**overrides))+ validate_rule(rule(**overrides))++ def test_rejects_a_rule_set_over_the_aggregate_condition_budget(self):+ # The per-list and per-rule caps multiply to 500 conditions; the aggregate budget is what+ # actually bounds a query's hyperscan work.+ rules = [+ rule(id=str(i), items=[condition(id=f"{i}-{j}") for j in range(MAX_CONDITIONS_PER_RULE)])+ for i in range(MAX_TOTAL_CONDITIONS // MAX_CONDITIONS_PER_RULE + 1)+ ]++ with pytest.raises(ValueError, match="across all rules"):+ validate_rule_set(rules)++ def test_rejects_a_rule_with_too_many_conditions(self):+ # Every condition is a read added to every query that selects a classification field.+ overloaded = rule(items=[condition(id=str(i + 10)) for i in range(MAX_CONDITIONS_PER_RULE + 1)])++ with pytest.raises(ValueError, match="at most"):+ validate_rule(overloaded)++ @parameterized.expand(+ [+ # A shared id collapses entries in the id-keyed editor.+ ("two conditions share an id", [{"id": "a"}, {"id": "a"}]),+ ("a condition reuses the rule id", [{"id": "1"}]),+ ]+ )+ def test_rejects_colliding_condition_ids(self, _name: str, item_overrides: list[dict]):+ colliding = rule(items=[condition(**overrides) for overrides in item_overrides])++ with pytest.raises(ValueError, match="unique"):+ validate_rule(colliding)@parameterized.expand([@@ -111,11 +180,29 @@ class TestValidation:("anchored regex", {"pattern": "^AcmeBot/[0-9]+$", "matcher": CustomBotMatcher.REGEX}),("a non-default property", {"key": CustomBotField.FIELD_LIB, "pattern": "posthog-python"}),("a numeric property", {"key": CustomBotField.FIELD_SCREEN_WIDTH, "pattern": "800"}),+ (+ "equality on a numeric property",+ {"key": CustomBotField.FIELD_SCREEN_WIDTH, "pattern": "800", "matcher": CustomBotMatcher.EXACT},+ ),("browser language", {"key": CustomBotField.FIELD_BROWSER_LANGUAGE, "pattern": "@posix"}),])- def test_accepts_usable_definitions(self, _name: str, overrides: dict):- validate_definition(definition(**overrides))+ def test_accepts_usable_rules(self, _name: str, overrides: dict):+ validate_rule(rule(**overrides))++ def test_accepts_a_multi_condition_rule(self):+ validate_rule(+ rule(+ items=[+ condition(+ id="w", key=CustomBotField.FIELD_SCREEN_WIDTH, matcher=CustomBotMatcher.EXACT, pattern="800"+ ),+ condition(+ id="h", key=CustomBotField.FIELD_SCREEN_HEIGHT, matcher=CustomBotMatcher.EXACT, pattern="600"+ ),+ ]+ )+ )@parameterized.expand([@@ -126,7 +213,7 @@ class TestValidation:])def test_accepts_usable_ip_ranges(self, _name: str, pattern: str):- validate_definition(cidr_definition(pattern=pattern))+ validate_rule(cidr_rule(pattern=pattern))@parameterized.expand([@@ -140,48 +227,77 @@ class TestValidation:)def test_rejects_unusable_ip_ranges(self, _name: str, pattern: str):with pytest.raises(ValueError):- validate_definition(cidr_definition(pattern=pattern))+ validate_rule(cidr_rule(pattern=pattern))def test_rejects_a_range_on_a_property_that_is_not_an_ip(self):# Comparing a user agent to a network range can never match, so it is a mistake worth# naming rather than a rule that silently does nothing.with pytest.raises(ValueError, match="IP ranges only work with"):- validate_definition(definition(matcher=CustomBotMatcher.CIDR, pattern="192.0.2.0/24"))+ validate_rule(rule(matcher=CustomBotMatcher.CIDR, pattern="192.0.2.0/24"))def test_rejects_a_property_outside_the_supported_set(self):- raw = definition().model_dump()+ raw = condition().model_dump()raw["key"] = "$some_other_property"with pytest.raises(ValueError, match="Cannot match on property"):- validate_definition(CustomBotDefinition.model_construct(**raw))+ validate_rule(rule(items=[CustomBotCondition.model_construct(**raw)]))+++class TestParseRules:+ def test_keeps_parseable_rules_and_drops_what_does_not_parse(self):+ current = rule().model_dump(exclude_none=True)+ # A pre-combiner flat entry has no items, so it is dropped like any other unparseable entry.+ flat = {"id": "9", "name": "Flat", "key": "$raw_user_agent", "matcher": "contains", "pattern": "AcmeBot"}++ parsed = parse_rules([current, "garbage", flat, {"items": "not-a-list"}])++ assert [r.name for r in parsed] == ["Acme scraper"]++ def test_strict_raises_instead_of_dropping(self):+ # On the save paths a silently dropped rule reads as saved; the error has to surface.+ with pytest.raises(ValueError, match="Invalid bot rule"):+ parse_rules([{"pattern": "no items"}], strict=True)class TestCompileDefinitions:- def test_unusable_definitions_are_dropped_not_raised(self):- # A definition that got past validation (saved before a rule tightened, or written straight+ def test_unusable_rules_are_dropped_not_raised(self):+ # A rule that got past validation (saved before a rule tightened, or written straight# to the API) must not break every query that reads $virt_is_bot for the project.groups = compile_definitions([- definition(id="1", pattern="Acme(?=Bot)", matcher=CustomBotMatcher.REGEX),- definition(id="2", name="Good bot", pattern="GoodBot"),+ rule(id="1", pattern="Acme(?=Bot)", matcher=CustomBotMatcher.REGEX),+ rule(id="2", name="Good bot", pattern="GoodBot"),])- assert [bot.name for group in groups for bot in group.definitions] == ["Good bot"]+ assert [bot.name for group in groups if isinstance(group, PatternGroup) for bot in group.definitions] == [+ "Good bot"+ ]- def test_definitions_beyond_the_cap_are_dropped(self):- groups = compile_definitions(- [definition(id=str(i), name=f"Bot {i}") for i in range(MAX_CUSTOM_BOT_DEFINITIONS + 10)]- )+ def test_rules_beyond_the_aggregate_condition_budget_are_dropped(self):+ # Client-supplied query modifiers never pass a save path, so the budget must hold at+ # compile time too or a crafted query forces one hyperscan call per condition per row.+ rules = [+ rule(id=str(i), name=f"Bot {i}", items=[condition(id=f"{i}-{j}") for j in range(MAX_CONDITIONS_PER_RULE)])+ for i in range(MAX_TOTAL_CONDITIONS // MAX_CONDITIONS_PER_RULE + 5)+ ]++ groups = compile_definitions(rules)- assert sum(len(group.definitions) for group in groups) == MAX_CUSTOM_BOT_DEFINITIONS+ total = sum(len(group.conditions) if isinstance(group, CompositeGroup) else 1 for group in groups)+ assert total <= MAX_TOTAL_CONDITIONS++ def test_rules_beyond_the_cap_are_dropped(self):+ groups = compile_definitions([rule(id=str(i), name=f"Bot {i}") for i in range(MAX_CUSTOM_BOT_DEFINITIONS + 10)])++ assert sum(len(group.definitions) for group in groups if isinstance(group, PatternGroup)) == (+ MAX_CUSTOM_BOT_DEFINITIONS+ )def test_rules_on_the_same_property_share_one_group(self):# Each group is one pass over the property at query time, so two user agent rules must not# become two passes.- groups = compile_definitions(- [definition(id="1", name="One", pattern="One"), definition(id="2", name="Two", pattern="Two")]- )+ groups = compile_definitions([rule(id="1", name="One", pattern="One"), rule(id="2", name="Two", pattern="Two")])assert len(groups) == 1assert isinstance(groups[0], PatternGroup)@@ -192,47 +308,171 @@ class TestCompileDefinitions:# them match.groups = compile_definitions([- definition(id="1", name="By host", key=CustomBotField.FIELD_HOST, pattern="scraper.example.com"),- cidr_definition(id="2", name="By IP"),- definition(id="3", name="By user agent", pattern="AcmeBot"),+ rule(id="1", name="By host", key=CustomBotField.FIELD_HOST, pattern="scraper.example.com"),+ cidr_rule(id="2", name="By IP"),+ rule(id="3", name="By user agent", pattern="AcmeBot"),])- assert [group.key for group in groups] == [+ assert [group.key for group in groups if not isinstance(group, CompositeGroup)] == [CustomBotField.FIELD_HOST.value,CustomBotField.FIELD_IP.value,CustomBotField.FIELD_RAW_USER_AGENT.value,]+ def test_only_contiguous_rules_share_a_group(self):+ # List order is precedence: a later same-property rule must not jump the rule between them.+ groups = compile_definitions(+ [+ rule(id="1", name="First UA", pattern="First"),+ rule(id="2", name="By host", key=CustomBotField.FIELD_HOST, pattern="scraper.example.com"),+ rule(id="3", name="Last UA", pattern="Last"),+ ]+ )++ assert [[bot.name for bot in group.definitions] for group in groups if isinstance(group, PatternGroup)] == [+ ["First UA"],+ ["By host"],+ ["Last UA"],+ ]+def test_a_property_matched_two_ways_gets_a_group_each(self):# A range check and a pattern check are different expressions, so they cannot share a pass.groups = compile_definitions([- cidr_definition(id="1", name="Office"),- definition(id="2", name="Loopback-ish", key=CustomBotField.FIELD_IP, pattern="127."),+ cidr_rule(id="1", name="Office"),+ rule(id="2", name="Loopback-ish", key=CustomBotField.FIELD_IP, pattern="127."),])assert [type(group) for group in groups] == [CidrGroup, PatternGroup]+ def test_a_multi_condition_rule_becomes_its_own_group_in_order(self):+ # A composite rule reads several properties, so it cannot share another group's hyperscan+ # pass, and it must keep its place in the precedence order between the other groups.+ groups = compile_definitions(+ [+ rule(id="1", name="First", pattern="First"),+ rule(+ id="2",+ name="Headless 800x600",+ items=[+ condition(+ id="w", key=CustomBotField.FIELD_SCREEN_WIDTH, matcher=CustomBotMatcher.EXACT, pattern="800"+ ),+ condition(+ id="h",+ key=CustomBotField.FIELD_SCREEN_HEIGHT,+ matcher=CustomBotMatcher.EXACT,+ pattern="600",+ ),+ ],+ ),+ rule(id="3", name="Last", key=CustomBotField.FIELD_HOST, pattern="scraper.example.com"),+ ]+ )++ assert [type(group) for group in groups] == [PatternGroup, CompositeGroup, PatternGroup]+ composite = groups[1]+ assert isinstance(composite, CompositeGroup)+ assert composite.combiner == "AND"+ assert composite.definition.name == "Headless 800x600"++ def test_a_bucket_does_not_reach_back_across_a_composite(self):+ # The editor promises list order is precedence. Sharing a bucket across the composite+ # would check the last rule ahead of the composite listed above it, so the label of an+ # event both match would go to the wrong rule.+ composite = rule(+ id="2",+ name="Headless 800x600",+ items=[+ condition(id="w", key=CustomBotField.FIELD_SCREEN_WIDTH, matcher=CustomBotMatcher.EXACT, pattern="800"),+ condition(+ id="h", key=CustomBotField.FIELD_SCREEN_HEIGHT, matcher=CustomBotMatcher.EXACT, pattern="600"+ ),+ ],+ )+ groups = compile_definitions(+ [rule(id="1", name="First", pattern="First"), composite, rule(id="3", name="Last", pattern="Last")]+ )++ assert [type(group) for group in groups] == [PatternGroup, CompositeGroup, PatternGroup]+ assert isinstance(groups[0], PatternGroup)+ assert isinstance(groups[2], PatternGroup)+ assert [bot.name for bot in groups[0].definitions] == ["First"]+ assert [bot.name for bot in groups[2].definitions] == ["Last"]+def test_category_drives_traffic_type(self):- groups = compile_definitions([definition(category="ai_crawler")])+ groups = compile_definitions([rule(category="ai_crawler")])+ assert isinstance(groups[0], PatternGroup)bot = groups[0].definitions[0]assert bot.category == "ai_crawler"assert bot.traffic_type == "AI Agent"def test_defaults_to_the_custom_category(self):- bot = compile_definitions([definition()])[0].definitions[0]+ groups = compile_definitions([rule()])+ assert isinstance(groups[0], PatternGroup)+ bot = groups[0].definitions[0]assert bot.category == "custom"assert bot.traffic_type == "Bot"- def test_compiled_patterns_skips_ip_ranges(self):- # The save-time check hands these to hyperscan, which cannot compile a network range.- patterns = compiled_patterns([definition(id="1"), cidr_definition(id="2")])+ def test_compiled_patterns_skips_ip_ranges_but_covers_composite_conditions(self):+ # The save-time check hands these to hyperscan, which cannot compile a network range. A+ # composite rule's pattern conditions run through hyperscan too, so missing them here would+ # let an uncompilable pattern save and then break every classification query.+ patterns = compiled_patterns(+ [+ rule(id="1"),+ cidr_rule(id="2"),+ rule(+ id="3",+ name="Composite",+ items=[+ condition(+ id="w", key=CustomBotField.FIELD_SCREEN_WIDTH, matcher=CustomBotMatcher.EXACT, pattern="800"+ ),+ condition(+ id="ip", key=CustomBotField.FIELD_IP, matcher=CustomBotMatcher.CIDR, pattern="192.0.2.0/24"+ ),+ ],+ ),+ ]+ )++ assert patterns == ["(?i)AcmeBot", "^800$"]+++class TestCompositeBranch:+ @parameterized.expand(+ [+ # A reachable OR condition matching means the full rule would match too, so the+ # reachable subset must still be evaluated instead of skipping the whole rule.+ ("OR keeps the reachable condition", FilterLogicalOperator.OR_, True),+ # A partial AND could flag events the full rule would not, so it must skip entirely.+ ("AND skips the whole rule", FilterLogicalOperator.AND_, False),+ ]+ )+ def test_a_composite_with_an_unreachable_property_follows_its_combiner(+ self, _name: str, combiner: FilterLogicalOperator, expected_branch: bool+ ):+ groups = compile_definitions(+ [+ rule(+ combiner=combiner,+ items=[+ condition(id="ua", pattern="AcmeBot"),+ condition(id="host", key=CustomBotField.FIELD_HOST, pattern="scraper.example.com"),+ ],+ )+ ]+ )+ assert isinstance(groups[0], CompositeGroup)+ # A user agent not read from a properties object has no sibling to reach $host through.+ branch = _composite_branch(groups[0], [ast.Field(chain=["foo", "ua"])], "name")- assert patterns == ["(?i)AcmeBot"]+ assert (branch is not None) == expected_branchclass TestPatternsCompile(ClickhouseTestMixin, BaseTest):diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex 5a2a648fefac..be86d39c81a1 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -691,19 +691,31 @@ export interface RecordVisitResponseApi {recorded: boolean}-export interface CustomBotRuleApi {- /** Stable id for the rule. Pass it to the delete endpoint. */- readonly id: string- /** Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know. */- name: string- /** Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain. */+export interface WebAnalyticsBotConditionApi {+ /**+ * Stable id for the condition. Generated when omitted.+ * @maxLength 100+ */+ id?: string+ /** Event property the condition reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain. */key: string- /** How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property). */+ /** How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), 'exact' (case-sensitive equality), or 'cidr' (an IP network range, only valid with the `$ip` property). */matcher: string/** Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24. */pattern: string+}++export interface WebAnalyticsBotRuleApi {+ /** Stable id for the rule. Pass it to the delete endpoint. */+ readonly id: string+ /** Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know. */+ name: string/** Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too. */category?: string+ /** How the conditions combine: 'AND' flags an event only when every condition matches, 'OR' when any one of them does. */+ combiner?: string+ /** The conditions of this rule. Each one reads a single event property. */+ items: WebAnalyticsBotConditionApi[]}export interface ContentAutopilotSiteProfileApi {diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.tsindex 70ce5390ae37..677ccbafa0c6 100644--- a/products/web_analytics/frontend/generated/api.ts+++ b/products/web_analytics/frontend/generated/api.ts@@ -21,7 +21,6 @@ import type {ContentAutopilotSiteDiscoveryRequestApi,ContentAutopilotSiteDiscoveryResponseApi,ContentAutopilotSiteProfileApi,- CustomBotRuleApi,GeneratePathCleaningSuggestionResponseApi,HeatmapEventsResponseApi,HeatmapPreflightRequestApi,@@ -49,6 +48,7 @@ import type {SavedHeatmapListResponseApi,SavedHeatmapRequestApi,SavedListParams,+ WebAnalyticsBotRuleApi,WebAnalyticsContentAutopilotProfilesListParams,WebAnalyticsContentAutopilotProposalsListParams,WebAnalyticsContentAutopilotRunsListParams,@@ -589,8 +589,8 @@ export const getWebAnalyticsBotRulesListUrl = (projectId: string) => {export const webAnalyticsBotRulesList = async (projectId: string,options?: RequestInit-): Promise<CustomBotRuleApi[]> => {- return apiMutator<CustomBotRuleApi[]>(getWebAnalyticsBotRulesListUrl(projectId), {+): Promise<WebAnalyticsBotRuleApi[]> => {+ return apiMutator<WebAnalyticsBotRuleApi[]>(getWebAnalyticsBotRulesListUrl(projectId), {...options,method: 'GET',})@@ -601,19 +601,19 @@ export const getWebAnalyticsBotRulesCreateUrl = (projectId: string) => {}/**- * Add one bot rule to the project. The pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.+ * Add one bot rule to the project. A rule combines one or more single-property conditions with AND or OR. A pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.* @summary Create a custom bot rule*/export const webAnalyticsBotRulesCreate = async (projectId: string,- customBotRuleApi: NonReadonly<CustomBotRuleApi>,+ webAnalyticsBotRuleApi: NonReadonly<WebAnalyticsBotRuleApi>,options?: RequestInit-): Promise<CustomBotRuleApi> => {- return apiMutator<CustomBotRuleApi>(getWebAnalyticsBotRulesCreateUrl(projectId), {+): Promise<WebAnalyticsBotRuleApi> => {+ return apiMutator<WebAnalyticsBotRuleApi>(getWebAnalyticsBotRulesCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(customBotRuleApi),+ body: JSON.stringify(webAnalyticsBotRuleApi),})}diff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.tsindex f3c7b1d2989f..40e14d52ec7a 100644--- a/products/web_analytics/frontend/generated/api.zod.ts+++ b/products/web_analytics/frontend/generated/api.zod.ts@@ -257,36 +257,56 @@ export const WebAnalyticsAchievementsRecordInteractionBody = /* @__PURE__ */ zod})/**- * Add one bot rule to the project. The pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.+ * Add one bot rule to the project. A rule combines one or more single-property conditions with AND or OR. A pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.* @summary Create a custom bot rule*/+export const webAnalyticsBotRulesCreateBodyCombinerDefault = `AND`+export const webAnalyticsBotRulesCreateBodyItemsItemIdMax = 100+export const WebAnalyticsBotRulesCreateBody = /* @__PURE__ */ zod.object({name: zod.string().describe('Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know.'),- key: zod- .string()- .describe(- 'Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain.'- ),- matcher: zod- .string()- .describe(- "How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property)."- ),- pattern: zod- .string()- .describe(- "Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0\/24."- ),category: zod.string().optional().describe("Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too."),+ combiner: zod+ .string()+ .default(webAnalyticsBotRulesCreateBodyCombinerDefault)+ .describe(+ "How the conditions combine: 'AND' flags an event only when every condition matches, 'OR' when any one of them does."+ ),+ items: zod+ .array(+ zod.object({+ id: zod+ .string()+ .max(webAnalyticsBotRulesCreateBodyItemsItemIdMax)+ .optional()+ .describe('Stable id for the condition. Generated when omitted.'),+ key: zod+ .string()+ .describe(+ 'Event property the condition reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain.'+ ),+ matcher: zod+ .string()+ .describe(+ "How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), 'exact' (case-sensitive equality), or 'cidr' (an IP network range, only valid with the `$ip` property)."+ ),+ pattern: zod+ .string()+ .describe(+ "Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0\/24."+ ),+ })+ )+ .describe('The conditions of this rule. Each one reads a single event property.'),})export const webAnalyticsContentAutopilotProfilesCreateBodyNameMax = 255diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yamlindex c3bbd8806423..aa3bf3ad1f72 100644--- a/products/web_analytics/mcp/tools.yaml+++ b/products/web_analytics/mcp/tools.yaml@@ -172,12 +172,14 @@ tools:idempotent: falsetitle: Create a custom bot ruledescription: >- Add one bot rule so traffic matching it classifies as a bot. Set `key` to the event property to read (such- as $raw_user_agent or $ip), `matcher` to 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr'- (an IP network range, only with $ip), `pattern` to the value to match, and `name` to the label to report.- Optionally set `category` to a built-in category like ai_crawler to relabel the traffic type. The rule is- rejected if its pattern cannot run. Use this when a scraper is hitting the site that the built-in list- misses.+ Add one bot rule so traffic matching it classifies as a bot. A rule holds one or more conditions in `items`,+ combined with `combiner` ('AND' or 'OR', default 'AND'). Each condition sets `key` to the event property to+ read (such as $raw_user_agent, $screen_width, or $ip), `matcher` to 'contains' (case-insensitive substring),+ 'regex' (RE2), 'exact' (case-sensitive equality), or 'cidr' (an IP network range, only with $ip), and+ `pattern` to the value to match. Set `name` to the label to report, and optionally `category` to a built-in+ category like ai_crawler to relabel the traffic type. The rule is rejected if a pattern cannot run. Use this+ when a scraper is hitting the site that the built-in list misses, including one only identifiable by a+ combination of properties (an 800x600 screen).web-analytics-bot-rules-destroy:operation: web_analytics_bot_rules_destroyenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 90b8f04594d0..66f575164105 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -12495,7 +12495,7 @@}},"web-analytics-bot-rules-create": {- "description": "Add one bot rule so traffic matching it classifies as a bot. Set `key` to the event property to read (such as $raw_user_agent or $ip), `matcher` to 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only with $ip), `pattern` to the value to match, and `name` to the label to report. Optionally set `category` to a built-in category like ai_crawler to relabel the traffic type. The rule is rejected if its pattern cannot run. Use this when a scraper is hitting the site that the built-in list misses.",+ "description": "Add one bot rule so traffic matching it classifies as a bot. A rule holds one or more conditions in `items`, combined with `combiner` ('AND' or 'OR', default 'AND'). Each condition sets `key` to the event property to read (such as $raw_user_agent, $screen_width, or $ip), `matcher` to 'contains' (case-insensitive substring), 'regex' (RE2), 'exact' (case-sensitive equality), or 'cidr' (an IP network range, only with $ip), and `pattern` to the value to match. Set `name` to the label to report, and optionally `category` to a built-in category like ai_crawler to relabel the traffic type. The rule is rejected if a pattern cannot run. Use this when a scraper is hitting the site that the built-in list misses, including one only identifiable by a combination of properties (an 800x600 screen).","category": "Web analytics","feature": "web_analytics","summary": "Create a custom bot rule",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f2b466a12ccd..449f2bea6f12 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -13140,7 +13140,7 @@}},"web-analytics-bot-rules-create": {- "description": "Add one bot rule so traffic matching it classifies as a bot. Set `key` to the event property to read (such as $raw_user_agent or $ip), `matcher` to 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only with $ip), `pattern` to the value to match, and `name` to the label to report. Optionally set `category` to a built-in category like ai_crawler to relabel the traffic type. The rule is rejected if its pattern cannot run. Use this when a scraper is hitting the site that the built-in list misses.",+ "description": "Add one bot rule so traffic matching it classifies as a bot. A rule holds one or more conditions in `items`, combined with `combiner` ('AND' or 'OR', default 'AND'). Each condition sets `key` to the event property to read (such as $raw_user_agent, $screen_width, or $ip), `matcher` to 'contains' (case-insensitive substring), 'regex' (RE2), 'exact' (case-sensitive equality), or 'cidr' (an IP network range, only with $ip), and `pattern` to the value to match. Set `name` to the label to report, and optionally `category` to a built-in category like ai_crawler to relabel the traffic type. The rule is rejected if a pattern cannot run. Use this when a scraper is hitting the site that the built-in list misses, including one only identifiable by a combination of properties (an 800x600 screen).","category": "Web analytics","feature": "web_analytics","summary": "Create a custom bot rule",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5adbc3e7285e..71eb5af5cc07 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -1079,6 +1079,14 @@ export namespace Schemas {UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',} as const;+ export type FilterLogicalOperator = typeof FilterLogicalOperator[keyof typeof FilterLogicalOperator];+++ export const FilterLogicalOperator = {+ And: 'AND',+ Or: 'OR',+ } as const;+export type CustomBotField = typeof CustomBotField[keyof typeof CustomBotField];@@ -1105,29 +1113,29 @@ export namespace Schemas {export const CustomBotMatcher = {Contains: 'contains',Regex: 'regex',+ Exact: 'exact',Cidr: 'cidr',} as const;- export interface CustomBotDefinition {- /** Reported by `$virt_traffic_category`. Defaults to `custom`. */- category?: string | null;+ export interface CustomBotCondition {id: string;- /** The event property this rule reads. */+ /** The event property this condition reads. */key: CustomBotField;matcher: CustomBotMatcher;- /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */- name: string;/** Matched against the property named by `key`. */pattern: string;}- export type FilterLogicalOperator = typeof FilterLogicalOperator[keyof typeof FilterLogicalOperator];--- export const FilterLogicalOperator = {- And: 'AND',- Or: 'OR',- } as const;+ export interface CustomBotRule {+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */+ category?: string | null;+ /** Whether every condition must match (AND) or any one of them (OR). */+ combiner: FilterLogicalOperator;+ id: string;+ items: CustomBotCondition[];+ /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */+ name: string;+ }export type CustomChannelField = typeof CustomChannelField[keyof typeof CustomChannelField];@@ -1285,7 +1293,7 @@ export namespace Schemas {bounceRateDurationSeconds?: number | null;bounceRatePageViewMode?: BounceRatePageViewMode | null;convertToProjectTimezone?: boolean | null;- customBotDefinitions?: CustomBotDefinition[] | null;+ customBotDefinitions?: CustomBotRule[] | null;customChannelTypeRules?: CustomChannelRule[] | null;dataWarehouseEventsModifiers?: DataWarehouseEventsModifier[] | null;debug?: boolean | null;@@ -20907,21 +20915,6 @@ export namespace Schemas {evaluation_session_cap: number;}- export interface CustomBotRule {- /** Stable id for the rule. Pass it to the delete endpoint. */- readonly id: string;- /** Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know. */- name: string;- /** Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain. */- key: string;- /** How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property). */- matcher: string;- /** Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24. */- pattern: string;- /** Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too. */- category?: string;- }-/*** * `text` - text* * `link` - link@@ -89538,6 +89531,33 @@ export namespace Schemas {run_id: string;}+ export interface WebAnalyticsBotCondition {+ /**+ * Stable id for the condition. Generated when omitted.+ * @maxLength 100+ */+ id?: string;+ /** Event property the condition reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain. */+ key: string;+ /** How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), 'exact' (case-sensitive equality), or 'cidr' (an IP network range, only valid with the `$ip` property). */+ matcher: string;+ /** Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24. */+ pattern: string;+ }++ export interface WebAnalyticsBotRule {+ /** Stable id for the rule. Pass it to the delete endpoint. */+ readonly id: string;+ /** Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know. */+ name: string;+ /** Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too. */+ category?: string;+ /** How the conditions combine: 'AND' flags an event only when every condition matches, 'OR' when any one of them does. */+ combiner?: string;+ /** The conditions of this rule. Each one reads a single event property. */+ items: WebAnalyticsBotCondition[];+ }+export interface WebAnalyticsRecapResponse {/** Unique visitors. */visitors: NumericMetric;diff --git a/services/mcp/src/generated/web_analytics/api.ts b/services/mcp/src/generated/web_analytics/api.tsindex 9d06b7803b53..6b09a609f33e 100644--- a/services/mcp/src/generated/web_analytics/api.ts+++ b/services/mcp/src/generated/web_analytics/api.ts@@ -446,7 +446,7 @@ export const WebAnalyticsBotRulesListParams = () => zod.object({})/**- * Add one bot rule to the project. The pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.+ * Add one bot rule to the project. A rule combines one or more single-property conditions with AND or OR. A pattern is rejected if it cannot run, because a broken rule would break every query that classifies traffic for the project.* @summary Create a custom bot rule*/export const WebAnalyticsBotRulesCreateParams = () => zod.object({@@ -457,33 +457,53 @@ export const WebAnalyticsBotRulesCreateParams = () => zod.object({),})+export const webAnalyticsBotRulesCreateBodyCombinerDefault = `AND`+export const webAnalyticsBotRulesCreateBodyItemsItemIdMax = 100+export const WebAnalyticsBotRulesCreateBody = () => zod.object({name: zod.string().describe('Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know.'),- key: zod- .string()- .describe(- 'Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain.'- ),- matcher: zod- .string()- .describe(- "How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property)."- ),- pattern: zod- .string()- .describe(- "Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0\/24."- ),category: zod.string().optional().describe("Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too."),+ combiner: zod+ .string()+ .default(webAnalyticsBotRulesCreateBodyCombinerDefault)+ .describe(+ "How the conditions combine: 'AND' flags an event only when every condition matches, 'OR' when any one of them does."+ ),+ items: zod+ .array(+ zod.object({+ id: zod+ .string()+ .max(webAnalyticsBotRulesCreateBodyItemsItemIdMax)+ .optional()+ .describe('Stable id for the condition. Generated when omitted.'),+ key: zod+ .string()+ .describe(+ 'Event property the condition reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain.'+ ),+ matcher: zod+ .string()+ .describe(+ "How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), 'exact' (case-sensitive equality), or 'cidr' (an IP network range, only valid with the `$ip` property)."+ ),+ pattern: zod+ .string()+ .describe(+ "Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0\/24."+ ),+ })+ )+ .describe('The conditions of this rule. Each one reads a single event property.'),})/**diff --git a/services/mcp/src/tools/generated/web_analytics.ts b/services/mcp/src/tools/generated/web_analytics.tsindex 6cd3fb4227cc..31172be8bcdd 100644--- a/services/mcp/src/tools/generated/web_analytics.ts+++ b/services/mcp/src/tools/generated/web_analytics.ts@@ -244,7 +244,7 @@ const WebAnalyticsBotRulesCreateSchema = () => {const webAnalyticsBotRulesCreate = (): ToolBase<ReturnType<typeof WebAnalyticsBotRulesCreateSchema>,- Schemas.CustomBotRule+ Schemas.WebAnalyticsBotRule> => ({name: 'web-analytics-bot-rules-create',schema: WebAnalyticsBotRulesCreateSchema(),@@ -254,19 +254,16 @@ const webAnalyticsBotRulesCreate = (): ToolBase<if (params.name !== undefined) {body['name'] = params.name}- if (params.key !== undefined) {- body['key'] = params.key- }- if (params.matcher !== undefined) {- body['matcher'] = params.matcher- }- if (params.pattern !== undefined) {- body['pattern'] = params.pattern- }if (params.category !== undefined) {body['category'] = params.category}- const result = await context.api.request<Schemas.CustomBotRule>({+ if (params.combiner !== undefined) {+ body['combiner'] = params.combiner+ }+ if (params.items !== undefined) {+ body['items'] = params.items+ }+ const result = await context.api.request<Schemas.WebAnalyticsBotRule>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/web_analytics_bot_rules/`,body,@@ -297,13 +294,13 @@ const WebAnalyticsBotRulesListSchema = () => z.object({})const webAnalyticsBotRulesList = (): ToolBase<ReturnType<typeof WebAnalyticsBotRulesListSchema>,- WithPostHogUrl<Schemas.CustomBotRule[]>+ WithPostHogUrl<Schemas.WebAnalyticsBotRule[]>> => ({name: 'web-analytics-bot-rules-list',schema: WebAnalyticsBotRulesListSchema(),handler: async (context: Context, _params: z.infer<ReturnType<typeof WebAnalyticsBotRulesListSchema>>) => {const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.CustomBotRule[]>({+ const result = await context.api.request<Schemas.WebAnalyticsBotRule[]>({method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/web_analytics_bot_rules/`,})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-create.jsonindex 7d1c48ee33f5..e4c8d54eba2b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/web-analytics-bot-rules-create.json@@ -5,23 +5,43 @@"description": "Reported by the `Traffic category` property. Defaults to 'custom'. A built-in category such as ai_crawler or search_crawler relabels the traffic type too.","type": "string"},- "key": {- "description": "Event property the rule reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain.",+ "combiner": {+ "default": "AND",+ "description": "How the conditions combine: 'AND' flags an event only when every condition matches, 'OR' when any one of them does.","type": "string"},- "matcher": {- "description": "How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), or 'cidr' (an IP network range, only valid with the `$ip` property).",- "type": "string"+ "items": {+ "description": "The conditions of this rule. Each one reads a single event property.",+ "items": {+ "properties": {+ "id": {+ "description": "Stable id for the condition. Generated when omitted.",+ "maxLength": 100,+ "type": "string"+ },+ "key": {+ "description": "Event property the condition reads. One of: $raw_user_agent, $ip, $lib, $host, $pathname, $current_url, $browser, $os, $browser_language, $screen_width, $screen_height, $geoip_country_code, $referrer, $referring_domain.",+ "type": "string"+ },+ "matcher": {+ "description": "How `pattern` is compared: 'contains' (case-insensitive substring), 'regex' (RE2), 'exact' (case-sensitive equality), or 'cidr' (an IP network range, only valid with the `$ip` property).",+ "type": "string"+ },+ "pattern": {+ "description": "Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24.",+ "type": "string"+ }+ },+ "required": ["key", "matcher", "pattern"],+ "type": "object"+ },+ "type": "array"},"name": {"description": "Label reported by the `Bot name` property when the rule matches. Also the operator for a rule on a bot PostHog does not know.","type": "string"- },- "pattern": {- "description": "Value matched against the property named by `key`. For 'cidr' this is a network range like 192.0.2.0/24.",- "type": "string"}},- "required": ["name", "key", "matcher", "pattern"],+ "required": ["name", "items"],"type": "object"}