Skip to content

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

feat(web-analytics): let projects define their own bots definitions (#89491)

Lucas Ricoy1de6ee6546bb
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 25f7a275ac71..8c5e4b1e8e23 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8449,9 +8449,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-csp-reporting--light:
hash: v1.k794b7964.a842c3f0ee5a6731d1051c47f04fd6da35d42f85cc3e0ba40afba80d2ea66b91.uj0d249fCiw0N7_QZI0owaFQ77omJCKRsMDMnmJrX5k
scenes-app-settings-environment--settings-environment-customization--dark:
- hash: v1.k794b7964.1a38cfe1271e4a9f6290e392d9a6f4e3cd8847fe2dcdff60bb5bd31f01f6471f.KffiFQt4EKsxI1Rbjs7yMoIbB6QRSkml34IlulQ72Zs
+ hash: v1.k794b7964.ae39c49782511f159250740436cf205216986f9e19d4a4327cd101a4f25fb389.3-ot9aTpgSaOkMqsk6irfOWN9EKadpujudg7rRIgxiw
scenes-app-settings-environment--settings-environment-customization--light:
- hash: v1.k794b7964.35c10ee15e7424fb6966da088d7edb955e71e88e87288b71cfe0be2733d2a51c.pBLStD_u8lE5z1PuMkA3GGkSoFc4YNU1y-Q6-WDsBcg
+ hash: v1.k794b7964.80e0de7aa7c2aa17ed72e58eec01af1045acd1d3839a3b14f5dd81908fe28d1c.VBMZLN5BK5qz0_nHRm94WT5O1bKu72RjJ9LfFkdYp_A
scenes-app-settings-environment--settings-environment-danger-zone--dark:
hash: v1.k794b7964.586910a373b9a9cf63d114f527d0bb8580033d25a81be6f830e07bf244a7c316.-ID92-MgwgAf0sdCeF84tYBSJ1RcHGOvApRVSsJNYeE
scenes-app-settings-environment--settings-environment-danger-zone--light:
@@ -8577,9 +8577,9 @@ snapshots:
scenes-app-settings-project--settings-project-autocapture--light:
hash: v1.k794b7964.397d4848babe9a8d2fd98b15ffe998d685521cb5135ff4ad1a70951e6062ec71.HMYh2-IfWjQd_PDBPGoPGrX_LVi2OHg7wzBFzJAmslA
scenes-app-settings-project--settings-project-customization--dark:
- hash: v1.k794b7964.1a38cfe1271e4a9f6290e392d9a6f4e3cd8847fe2dcdff60bb5bd31f01f6471f.OVv8zCjGPjX8-NsbhgGEY8SivN_0m3yn6SwTMqF6CN0
+ hash: v1.k794b7964.ae39c49782511f159250740436cf205216986f9e19d4a4327cd101a4f25fb389.O6BKfuQnThce5dmkq0TiUUwYcF6CGC52St7qIeVV6_U
scenes-app-settings-project--settings-project-customization--light:
- hash: v1.k794b7964.35c10ee15e7424fb6966da088d7edb955e71e88e87288b71cfe0be2733d2a51c.Lf9oEEP9gWth52aeJ2143IvfkEAylnHS6pEtzIFvmhQ
+ hash: v1.k794b7964.80e0de7aa7c2aa17ed72e58eec01af1045acd1d3839a3b14f5dd81908fe28d1c.lkSZRstT2d9iJdI0uWce2eBwXdYce69ZD2FvlR-I6IM
scenes-app-settings-project--settings-project-danger-zone--dark:
hash: v1.k794b7964.d18bc16d7f8d14a2168e67a889a5229659191e35393f829ce1b5eb6c0876a269.nQC3Mf7fvxzoZTD0m9ndbrfXV9nQin3tsW49wkX6Zqk
scenes-app-settings-project--settings-project-danger-zone--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 2d29c06817ac..fbe2075de81c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -17268,6 +17268,45 @@
],
"type": "string"
},
+ "CustomBotDefinition": {
+ "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"
+ },
+ "id": {
+ "type": "string"
+ },
+ "key": {
+ "$ref": "#/definitions/CustomBotField",
+ "description": "The event property this rule 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"],
+ "type": "object"
+ },
+ "CustomBotField": {
+ "description": "The event properties a project's own bot rule can match on.",
+ "enum": ["$raw_user_agent", "$ip", "$lib", "$host", "$pathname", "$current_url"],
+ "type": "string"
+ },
+ "CustomBotMatcher": {
+ "enum": ["contains", "regex", "cidr"],
+ "type": "string"
+ },
"CustomChannelCondition": {
"additionalProperties": false,
"properties": {
@@ -29738,6 +29777,12 @@
"convertToProjectTimezone": {
"type": "boolean"
},
+ "customBotDefinitions": {
+ "items": {
+ "$ref": "#/definitions/CustomBotDefinition"
+ },
+ "type": "array"
+ },
"customChannelTypeRules": {
"items": {
"$ref": "#/definitions/CustomChannelRule"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index a24341d7c129..0f6958a16ecc 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -524,6 +524,7 @@ export interface HogQLQueryModifiers {
propertyGroupsMode?: 'enabled' | 'disabled' | 'optimized'
useMaterializedViews?: boolean
customChannelTypeRules?: CustomChannelRule[]
+ customBotDefinitions?: CustomBotDefinition[]
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
@@ -6796,6 +6797,37 @@ export interface CustomChannelRule {
id: string // the ID is only needed for the drag and drop, so only needs to be unique with one set of rules
}
+/** The event properties a project's own bot rule can match on. */
+export enum CustomBotField {
+ RawUserAgent = '$raw_user_agent',
+ IP = '$ip',
+ Lib = '$lib',
+ Host = '$host',
+ Pathname = '$pathname',
+ CurrentURL = '$current_url',
+}
+
+export enum CustomBotMatcher {
+ Contains = 'contains',
+ Regex = 'regex',
+ /** 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. */
+ key: CustomBotField
+ /** Matched against the property named by `key`. */
+ pattern: string
+ matcher: CustomBotMatcher
+ /** 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
+}
+
export enum DefaultChannelTypes {
CrossNetwork = 'Cross Network',
PaidSearch = 'Paid Search',
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index c428aef4b820..78122648b861 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -25,6 +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 { CustomChannelTypes } from 'scenes/settings/environment/CustomChannelTypes'
import { DeadClicksAutocaptureSettings } from 'scenes/settings/environment/DeadClicksAutocaptureSettings'
import { MaxChangelogSettings } from 'scenes/settings/environment/MaxChangelogSettings'
@@ -308,6 +309,17 @@ export const SETTINGS_MAP: SettingSection[] = [
component: <ProjectAccountFiltersSetting />,
keywords: ['test account', 'internal', 'exclude', 'filter'],
},
+ {
+ // Project-wide, like internal user filtering above: these definitions feed the
+ // `Is bot` property, which is available to every query, not only web analytics.
+ id: 'custom-bot-definitions',
+ title: 'Custom bots',
+ 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 />,
+ keywords: ['bot', 'crawler', 'spider', 'scraper', 'user agent', 'ai'],
+ },
{
id: 'business-model',
title: 'Business model',
diff --git a/frontend/src/scenes/settings/environment/CustomBotDefinitions.tsx b/frontend/src/scenes/settings/environment/CustomBotDefinitions.tsx
new file mode 100644
index 000000000000..db16efb177d1
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/CustomBotDefinitions.tsx
@@ -0,0 +1,276 @@
+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/customBotDefinitionsUtils.test.ts b/frontend/src/scenes/settings/environment/customBotDefinitionsUtils.test.ts
new file mode 100644
index 000000000000..4d1db8a4627d
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/customBotDefinitionsUtils.test.ts
@@ -0,0 +1,151 @@
+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/customBotDefinitionsUtils.ts b/frontend/src/scenes/settings/environment/customBotDefinitionsUtils.ts
new file mode 100644
index 000000000000..652fa35895ae
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/customBotDefinitionsUtils.ts
@@ -0,0 +1,257 @@
+import { CustomBotDefinition, CustomBotField, CustomBotMatcher } from '~/queries/schema/schema-general'
+
+export const CUSTOM_BOT_CATEGORY = 'custom'
+export const MAX_CUSTOM_BOT_DEFINITIONS = 50
+export const MAX_PATTERN_LENGTH = 200
+export const MAX_NAME_LENGTH = 100
+
+// Mirrors CUSTOM_BOT_FIELDS in
+// products/web_analytics/backend/hogql_queries/custom_bot_definitions.py
+export const CUSTOM_BOT_FIELD_OPTIONS: { value: CustomBotField; label: string }[] = [
+ { value: CustomBotField.RawUserAgent, label: 'Raw user agent' },
+ { value: CustomBotField.IP, label: 'IP address' },
+ { value: CustomBotField.Lib, label: 'Library' },
+ { value: CustomBotField.Host, label: 'Host' },
+ { value: CustomBotField.Pathname, label: 'Path name' },
+ { value: CustomBotField.CurrentURL, label: 'Current URL' },
+]
+
+const MATCHER_LABELS: Record<CustomBotMatcher, string> = {
+ [CustomBotMatcher.Contains]: 'contains',
+ [CustomBotMatcher.Regex]: 'matches regex',
+ [CustomBotMatcher.Cidr]: 'is in range',
+}
+
+// Mirrors TRAFFIC_TYPE_BY_CATEGORY in
+// products/web_analytics/backend/hogql_queries/custom_bot_definitions.py
+export const CUSTOM_BOT_CATEGORY_OPTIONS: { value: string; label: string }[] = [
+ { value: CUSTOM_BOT_CATEGORY, label: 'Custom' },
+ { value: 'ai_crawler', label: 'AI crawler' },
+ { value: 'ai_search', label: 'AI search' },
+ { value: 'ai_assistant', label: 'AI assistant' },
+ { value: 'search_crawler', label: 'Search crawler' },
+ { value: 'seo_crawler', label: 'SEO crawler' },
+ { value: 'social_crawler', label: 'Social crawler' },
+ { value: 'monitoring', label: 'Monitoring' },
+ { value: 'http_client', label: 'HTTP client' },
+ { value: 'headless_browser', label: 'Headless browser' },
+]
+
+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 }[] {
+ 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] }))
+}
+
+export function defaultMatcherFor(key: CustomBotField): CustomBotMatcher {
+ return key === CustomBotField.IP ? CustomBotMatcher.Cidr : CustomBotMatcher.Contains
+}
+
+export function patternPlaceholderFor(key: CustomBotField, matcher: CustomBotMatcher): string {
+ if (matcher === CustomBotMatcher.Cidr) {
+ return '192.0.2.0/24'
+ }
+ if (matcher === CustomBotMatcher.Regex) {
+ return key === CustomBotField.RawUserAgent ? 'AcmeBot/[0-9]+' : '^/api/'
+ }
+ return (
+ {
+ [CustomBotField.RawUserAgent]: 'AcmeBot',
+ [CustomBotField.IP]: '192.0.2.',
+ [CustomBotField.Lib]: 'posthog-python',
+ [CustomBotField.Host]: 'scraper.example.com',
+ [CustomBotField.Pathname]: '/api/products',
+ [CustomBotField.CurrentURL]: 'example.com/api',
+ }[key] ?? 'AcmeBot'
+ )
+}
+
+// ClickHouse matches these patterns with hyperscan, which supports less than JavaScript does.
+// Mirrors _UNSUPPORTED_CONSTRUCTS in the Python module above, so a person sees the problem while
+// typing instead of on save.
+const UNSUPPORTED_CONSTRUCTS: { pattern: RegExp; label: string }[] = [
+ { pattern: /\(\?=/, label: 'lookahead' },
+ { pattern: /\(\?!/, label: 'lookahead' },
+ { pattern: /\(\?<=/, label: 'lookbehind' },
+ { pattern: /\(\?<!/, label: 'lookbehind' },
+ { pattern: /\(\?>/, label: 'atomic group' },
+ { pattern: /\(\?\(/, label: 'conditional group' },
+ { pattern: /\(\?R/, label: 'recursion' },
+ { pattern: /\\[1-9]/, label: 'backreference' },
+ { pattern: /\\[zZGKCRX]/, label: 'unsupported escape' },
+]
+
+// Python's re (and re2) take regex flags as a leading inline group like (?i), which JavaScript
+// RegExp rejects outright. The server accepts them, and a contains rule is compiled to (?i) itself,
+// so translate them to JavaScript flags before compiling. Otherwise the editor would block a valid
+// case-insensitive rule such as (?i)(acme|globex)bot and the tester would report no match.
+//
+// Only i, m and s are recognized: they are the flags JavaScript supports, and unlike re2 the
+// server's re.compile rejects (?U)/(?L), so recognizing those here would accept a rule the API then
+// refuses. A rarer server-valid flag like (?x) is still refused in the editor, and a validation
+// error disables Save — such a rule can only be written through the API directly. Compare
+// compileForPreview in lib/components/PathCleanFilters/pathCleaningUtils.ts.
+const LEADING_INLINE_FLAGS = /^\(\?([ims]+)\)/
+
+function compileCustomBotRegex(pattern: string): RegExp {
+ // Consume every leading flag group and dedupe the letters: Python accepts stacked or repeated
+ // groups like (?i)(?s)x and (?ii)x, while RegExp rejects both a leftover (?s) group in the body
+ // and a repeated letter in the flags argument.
+ let flags = ''
+ let body = pattern
+ let match = body.match(LEADING_INLINE_FLAGS)
+ while (match) {
+ for (const flag of match[1]!) {
+ if (!flags.includes(flag)) {
+ flags += flag
+ }
+ }
+ body = body.slice(match[0].length)
+ match = body.match(LEADING_INLINE_FLAGS)
+ }
+ return new RegExp(body, flags)
+}
+
+/** An address as a number, with the width of its family. Null when it does not parse. */
+function parseIp(address: string): { value: bigint; width: bigint } | null {
+ if (!address.includes(':')) {
+ const octets = address.split('.')
+ if (octets.length !== 4) {
+ return null
+ }
+ let value = 0n
+ for (const octet of octets) {
+ // No leading zeros: Python's ipaddress rejects them, so the server would 400 a rule
+ // the tester had called valid.
+ if (!/^(0|[1-9]\d{0,2})$/.test(octet) || Number(octet) > 255) {
+ return null
+ }
+ value = (value << 8n) | BigInt(octet)
+ }
+ return { value, width: 32n }
+ }
+
+ const halves = address.split('::')
+ if (halves.length > 2) {
+ return null
+ }
+ const abbreviated = halves.length === 2
+ const head = halves[0] ? halves[0].split(':') : []
+ const tail = abbreviated && halves[1] ? halves[1].split(':') : []
+ const missing = 8 - head.length - tail.length
+ if (abbreviated ? missing < 0 : missing !== 0) {
+ return null
+ }
+ const groups = [...head, ...Array.from({ length: abbreviated ? missing : 0 }, () => '0'), ...tail]
+ let value = 0n
+ for (const group of groups) {
+ if (!/^[0-9a-f]{1,4}$/i.test(group)) {
+ return null
+ }
+ value = (value << 16n) | BigInt(parseInt(group, 16))
+ }
+ return { value, width: 128n }
+}
+
+/** Parse "192.0.2.0/24" or a bare address. The server validates with Python's `ipaddress`, which
+ * is the authority — this catches a typo while it is being typed. */
+function parseCidr(pattern: string): { value: bigint; width: bigint; prefix: bigint } | null {
+ const [address, prefixText, ...rest] = pattern.trim().split('/')
+ if (rest.length > 0) {
+ return null
+ }
+ const parsed = parseIp(address)
+ if (!parsed) {
+ return null
+ }
+ if (prefixText === undefined) {
+ return { ...parsed, prefix: parsed.width }
+ }
+ if (!/^\d{1,3}$/.test(prefixText) || BigInt(prefixText) > parsed.width) {
+ return null
+ }
+ return { ...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
+ ? 'Add an IP address or range to match.'
+ : 'Add a value to match.'
+ }
+ if (definition.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) {
+ return 'Ranges only work with the IP address property.'
+ }
+ return parseCidr(definition.pattern) ? null : 'This is not a valid IP address or range.'
+ }
+
+ if (definition.matcher !== CustomBotMatcher.Regex) {
+ return null
+ }
+ for (const { pattern, label } of UNSUPPORTED_CONSTRUCTS) {
+ if (pattern.test(definition.pattern)) {
+ return `This uses a ${label}, which is not supported here.`
+ }
+ }
+ try {
+ compileCustomBotRegex(definition.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)) {
+ return false
+ }
+ if (definition.matcher === CustomBotMatcher.Cidr) {
+ const network = parseCidr(definition.pattern)
+ const candidate = parseIp(value.trim())
+ if (!network || !candidate || network.width !== candidate.width) {
+ return false
+ }
+ const mask = ((1n << network.prefix) - 1n) << (network.width - network.prefix)
+ return (network.value & mask) === (candidate.value & mask)
+ }
+ if (definition.matcher === CustomBotMatcher.Regex) {
+ try {
+ return compileCustomBotRegex(definition.pattern).test(value)
+ } catch {
+ return false
+ }
+ }
+ return value.toLowerCase().includes(definition.pattern.trim().toLowerCase())
+}
+
+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,
+ }))
+}
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index dabc4ab89ce0..83f8817cdc71 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -123,6 +123,7 @@ export type SettingId =
| 'core-memory'
| 'correlation-analysis'
| 'csp-reporting'
+ | 'custom-bot-definitions'
| 'customer-analytics-accounts'
| 'customer-analytics-calendar-sync'
| 'customer-analytics-dashboard-events'
diff --git a/frontend/src/scenes/web-analytics/BotPropertyFilters.tsx b/frontend/src/scenes/web-analytics/BotPropertyFilters.tsx
index 60590e88ee02..0a58f92374ba 100644
--- a/frontend/src/scenes/web-analytics/BotPropertyFilters.tsx
+++ b/frontend/src/scenes/web-analytics/BotPropertyFilters.tsx
@@ -10,6 +10,8 @@ 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 { teamLogic } from 'scenes/teamLogic'
import { WebAnalyticsPropertyFilters } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator } from '~/types'
@@ -111,16 +113,18 @@ const CATEGORY_LABELS: Record<string, string> = {
monitoring: 'Monitoring',
http_client: 'HTTP client',
headless_browser: 'Headless browser',
+ [CUSTOM_BOT_CATEGORY]: 'Custom',
}
function getFilteredBotOptions(
selectedCategory: string | null,
- selectedCrawler: string | null
+ selectedCrawler: string | null,
+ customBots: BotDef[]
): {
categories: { label: string; value: string | null }[]
crawlers: { label: string; value: string | null }[]
} {
- let filtered = BOT_DEFINITIONS_LIST
+ let filtered = [...BOT_DEFINITIONS_LIST, ...customBots]
if (selectedCategory) {
filtered = filtered.filter((b) => b.category === selectedCategory)
@@ -198,10 +202,18 @@ export const BotPropertyFilters = (): JSX.Element => {
const [displayFilters, setDisplayFilters] = useState(false)
const { rawBotAnalyticsFilters } = useValues(botAnalyticsLogic)
const { setBotAnalyticsFilters } = useActions(botAnalyticsLogic)
+ const { currentTeam } = useValues(teamLogic)
+
+ // Bots the project defined itself classify the same way built-in ones do, so they belong in
+ // the same dropdowns.
+ const customBots: BotDef[] = (currentTeam?.modifiers?.customBotDefinitions ?? []).map((definition) => ({
+ name: definition.name,
+ category: definition.category || CUSTOM_BOT_CATEGORY,
+ }))
const selectedCategory = getBotFilterValue(rawBotAnalyticsFilters, '$virt_traffic_category')
const selectedCrawler = getBotFilterValue(rawBotAnalyticsFilters, '$virt_bot_name')
- const { categories, crawlers } = getFilteredBotOptions(selectedCategory, selectedCrawler)
+ const { categories, crawlers } = getFilteredBotOptions(selectedCategory, selectedCrawler, customBots)
const activeFilterCount = rawBotAnalyticsFilters.length
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index 317df0dd2701..67b46a34bd4a 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -3498,13 +3498,13 @@
"virtual": true
},
"$virt_is_bot": {
- "description": "Whether the event was generated by a bot, crawler, or automation tool, detected from the user agent or from operator-published bot IP ranges.",
+ "description": "Whether the event was generated by a bot, crawler, or automation tool, detected from the user agent, from operator-published bot IP ranges, or from a bot the project defined itself in settings.",
"label": "Is bot",
"type": "Boolean",
"virtual": true
},
"$virt_traffic_category": {
- "description": "Detailed traffic category: ai_crawler, ai_search, ai_assistant, search_crawler, seo_crawler, etc.",
+ "description": "Detailed traffic category: ai_crawler, ai_search, ai_assistant, search_crawler, seo_crawler, etc. Bots the project defined itself report the category picked in settings.",
"examples": [
"ai_crawler",
"ai_search",
diff --git a/posthog/api/team.py b/posthog/api/team.py
index c1f1c4657559..10eb0b477d01 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -120,6 +120,12 @@ from products.customer_analytics.backend.facade.team_extension import TeamCustom
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, normalize_context_name
from products.feature_flags.backend.models.team_feature_flag_policy_config import TeamFeatureFlagPolicyConfig
from products.logs.backend.models import TeamLogsConfig
+from products.web_analytics.backend.hogql_queries.custom_bot_definitions import (
+ MAX_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,
+)
from products.workflows.backend.models.team_workflows_config import EmailTrackingConsentMode, TeamWorkflowsConfig
tracer = trace.get_tracer(__name__)
@@ -1806,10 +1812,28 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
)
try:
- HogQLQueryModifiers(**value)
+ 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:
+ raise exceptions.ValidationError(
+ {"customBotDefinitions": f"You can define at most {MAX_CUSTOM_BOT_DEFINITIONS} bots."}
+ )
+ for definition in definitions:
+ # 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)
+ except ValueError as error:
+ raise exceptions.ValidationError({"customBotDefinitions": f"{definition.name}: {error}"})
+ try:
+ assert_custom_bot_patterns_compile(compiled_custom_bot_patterns(definitions))
+ except ValueError as error:
+ raise exceptions.ValidationError({"customBotDefinitions": str(error)})
+
return value
def validate_proactive_tasks_enabled(self, value: bool | None) -> bool | None:
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index fbfcf173d175..a2afe5306d03 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -1213,6 +1213,45 @@ def team_api_test_factory():
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ @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),
+ # 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"},
+ False,
+ ),
+ ("unsupported property", {"key": "$referrer", "pattern": "acme", "matcher": "contains"}, False),
+ ]
+ )
+ def test_modifiers_customBotDefinitions_validation(
+ self, _name: str, definition: 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.
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}",
+ {
+ "modifiers": {
+ "customBotDefinitions": [{"id": "1", "name": "Acme scraper", **definition}],
+ }
+ },
+ )
+
+ if should_succeed:
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["modifiers"]["customBotDefinitions"][0]["pattern"] == definition["pattern"]
+ else:
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
@patch("posthog.event_usage.report_user_action")
@freeze_time("2024-01-01T00:00:00Z")
def test_can_add_product_intent(self, mock_report_user_action: MagicMock) -> None:
diff --git a/posthog/hogql/functions/test/test_traffic_type_functions.py b/posthog/hogql/functions/test/test_traffic_type_functions.py
index 2b4174780f7b..a0a3b27df030 100644
--- a/posthog/hogql/functions/test/test_traffic_type_functions.py
+++ b/posthog/hogql/functions/test/test_traffic_type_functions.py
@@ -1,14 +1,18 @@
import ipaddress
+from uuid import uuid4
import pytest
-from posthog.test.base import BaseTest
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from parameterized import parameterized
+from posthog.schema import CustomBotDefinition, CustomBotField, CustomBotMatcher, HogQLQueryModifiers
+
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.errors import QueryError
from posthog.hogql.functions.traffic_type import (
+ _property_expr,
get_bot_name,
get_bot_operator,
get_bot_type,
@@ -18,6 +22,7 @@ from posthog.hogql.functions.traffic_type import (
)
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.query import execute_hogql_query
from products.actions.backend.models.action import Action
from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
@@ -42,6 +47,25 @@ class TestTrafficTypeFunctions:
# Third arg: array access
assert isinstance(result.args[2], ast.ArrayAccess)
+ @parameterized.expand(
+ [
+ # Canonical shape: a rule on another property reads it from the same properties object.
+ ("event properties", ["properties", "$raw_user_agent"], ["properties", "$host"]),
+ ("person-on-events", ["poe", "properties", "$raw_user_agent"], ["poe", "properties", "$host"]),
+ # A user agent not read from a properties object has no sibling to reach for, so the rule
+ # is skipped rather than inventing a column that fails the whole query.
+ ("arbitrary parent", ["foo", "ua"], None),
+ ("parent is not properties", ["events", "$raw_user_agent"], None),
+ ]
+ )
+ def test_property_expr_only_infers_sibling_from_a_properties_object(self, _name, chain, expected):
+ result = _property_expr("$host", [ast.Field(chain=chain)])
+ if expected is None:
+ assert result is None
+ else:
+ assert isinstance(result, ast.Field)
+ assert result.chain == expected
+
def test_get_traffic_type_uses_multiMatchAnyIndex(self):
node = ast.Call(name="getTrafficType", args=[])
user_agent_arg = ast.Field(chain=["properties", "$user_agent"])
@@ -605,6 +629,40 @@ class TestMacroExpansionGuard(BaseTest):
printed = self._print("SELECT __preview_getTrafficType(toString(__preview_isBot(properties.x))) FROM events")
assert "multiMatchAnyIndex" in printed
+ @parameterized.expand(
+ [
+ # A user-agent rule makes the one-arg form duplicate the user-agent argument, so
+ # nesting it becomes the same exponential vector and must be rejected.
+ (
+ "a user agent rule guards",
+ CustomBotField.FIELD_RAW_USER_AGENT,
+ CustomBotMatcher.CONTAINS,
+ "AcmeBot",
+ True,
+ ),
+ # A rule on another property reads a sibling field, not the argument, so a one-arg call
+ # embeds its argument once and the previously valid nesting has to keep resolving.
+ ("an ip rule does not guard", CustomBotField.FIELD_IP, CustomBotMatcher.CIDR, "192.0.2.0/24", False),
+ ]
+ )
+ def test_one_arg_is_bot_nesting_guard_tracks_user_agent_rules(
+ self, _name: str, key: CustomBotField, matcher: CustomBotMatcher, pattern: str, guarded: bool
+ ):
+ # 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)]
+ )
+ 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")
+
+ if guarded:
+ with pytest.raises(QueryError, match="cannot be nested inside another expanded function call"):
+ prepare_and_print_ast(query, context, "clickhouse")
+ else:
+ printed = prepare_and_print_ast(query, context, "clickhouse")[0]
+ assert "multiMatchAnyIndex" in printed
+
def test_two_arg_is_bot_expands_ip_ranges(self):
printed = self._print(
"SELECT isLikelyBot(toString(properties.$user_agent), toString(properties.$ip)) FROM events"
@@ -637,3 +695,165 @@ class TestMacroExpansionGuard(BaseTest):
)
printed = self._print(f"SELECT matchesAction({action.pk}) FROM events")
assert "multiMatchAnyIndex" in printed
+
+
+CHROME_USER_AGENT = (
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"
+)
+
+
+def _custom_bot(**kwargs) -> CustomBotDefinition:
+ return CustomBotDefinition(
+ **{
+ "id": "1",
+ "name": "Acme scraper",
+ "key": CustomBotField.FIELD_RAW_USER_AGENT,
+ "pattern": "AcmeBot",
+ "matcher": CustomBotMatcher.CONTAINS,
+ **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:
+ self.team.modifiers = {"customBotDefinitions": [d.model_dump(mode="json") for d in definitions]}
+ self.team.save()
+
+ tag = uuid4().hex
+ _create_event(
+ team=self.team,
+ distinct_id="visitor",
+ event="$pageview",
+ properties={**properties, "_test_tag": tag},
+ )
+ flush_persons_and_events()
+
+ response = execute_hogql_query(
+ "SELECT `$virt_is_bot`, `$virt_bot_name`, `$virt_traffic_category` "
+ f"FROM events WHERE properties._test_tag = '{tag}'",
+ self.team,
+ )
+ assert response.results is not None
+ return response.results[0]
+
+ def test_a_user_agent_rule_names_the_event(self):
+ is_bot, name, category = self._classify(
+ [_custom_bot(pattern="AcmeBot", category="ai_crawler")],
+ {"$raw_user_agent": "AcmeBot/1.0 (+https://example.com/bot)"},
+ )
+
+ assert (is_bot, name, category) == (True, "Acme scraper", "ai_crawler")
+
+ def test_an_ip_range_rule_catches_a_browser_user_agent(self):
+ # The reason a rule can pick its property: a scraper sending a real browser user agent is
+ # only identifiable by where it comes from.
+ is_bot, name, _category = self._classify(
+ [
+ _custom_bot(
+ name="Office crawler",
+ key=CustomBotField.FIELD_IP,
+ matcher=CustomBotMatcher.CIDR,
+ pattern="192.0.2.0/24",
+ )
+ ],
+ {"$raw_user_agent": CHROME_USER_AGENT, "$ip": "192.0.2.55"},
+ )
+
+ assert (is_bot, name) == (True, "Office crawler")
+
+ def test_an_ip_outside_the_range_is_left_alone(self):
+ is_bot, name, _category = self._classify(
+ [
+ _custom_bot(
+ name="Office crawler",
+ key=CustomBotField.FIELD_IP,
+ matcher=CustomBotMatcher.CIDR,
+ pattern="192.0.2.0/24",
+ )
+ ],
+ {"$raw_user_agent": CHROME_USER_AGENT, "$ip": "192.0.3.55"},
+ )
+
+ assert (is_bot, name) == (False, "")
+
+ def test_a_rule_reads_the_property_it_names(self):
+ # A property other than the user agent and the IP is reached through the properties object
+ # rather than a call argument, so this is the case that silently matches nothing if the
+ # lookup regresses.
+ is_bot, name, _category = self._classify(
+ [_custom_bot(name="Load test", key=CustomBotField.FIELD_LIB, pattern="posthog-python")],
+ {"$raw_user_agent": CHROME_USER_AGENT, "$lib": "posthog-python"},
+ )
+
+ assert (is_bot, name) == (True, "Load test")
+
+ @parameterized.expand(
+ [
+ # Someone who writes a rule for a bot PostHog already knows means to relabel it, so
+ # their rule takes both the name and the category.
+ ("a rule that matches", "GPTBot", ("Mine", "monitoring")),
+ # Rules extend the built-in list rather than replacing it, so an event no rule claims
+ # keeps the name PostHog gives it.
+ ("a rule that does not match", "AcmeBot", ("GPTBot", "ai_crawler")),
+ ]
+ )
+ def test_a_project_rule_is_named_ahead_of_a_built_in(self, _name: str, pattern: str, expected: tuple[str, str]):
+ # Precedence only holds while each group is checked in its own branch: multiMatchAnyIndex
+ # reports whichever pattern matches earliest in the string rather than earliest in the
+ # array, so merging the rules into the built-in array would decide this by user agent.
+ _is_bot, name, category = self._classify(
+ [_custom_bot(name="Mine", pattern=pattern, category="monitoring")],
+ {"$raw_user_agent": "Mozilla/5.0 (compatible; GPTBot/1.0)"},
+ )
+
+ assert (name, category) == expected
+
+ @parameterized.expand(
+ [
+ ("specific rule listed first", ["AcmeBot-Image", "Acme"], "AcmeBot-Image"),
+ ("broad rule listed first", ["Acme", "AcmeBot-Image"], "Acme"),
+ ]
+ )
+ def test_the_first_listed_rule_wins_when_two_rules_overlap(
+ self, _name: str, patterns: list[str], expected_name: str
+ ):
+ # Rules on one property share a single hyperscan pass, and hyperscan reports whichever
+ # pattern matches earliest in the string — here "Acme" always ends first, so an
+ # any-match index would name it in both orders. Taking the minimum of all matching
+ # pattern indices makes the settings page's list order decide instead.
+ _is_bot, name, _category = self._classify(
+ [_custom_bot(id=str(i), name=pattern, pattern=pattern) for i, pattern in enumerate(patterns)],
+ {"$raw_user_agent": "AcmeBot-Image/2.1 (+https://acme.example)"},
+ )
+
+ assert name == expected_name
+
+ def test_a_project_rule_beats_the_no_user_agent_bucket(self):
+ # Server logs arrive without a user agent. A project that named the IP wants its own name
+ # on those, not the generic empty-user-agent bucket.
+ _is_bot, name, category = self._classify(
+ [
+ _custom_bot(
+ name="Office crawler",
+ key=CustomBotField.FIELD_IP,
+ matcher=CustomBotMatcher.CIDR,
+ pattern="192.0.2.0/24",
+ )
+ ],
+ {"$ip": "192.0.2.55"},
+ )
+
+ assert (name, category) == ("Office crawler", "custom")
+
+ def test_a_missing_user_agent_still_falls_in_the_no_user_agent_bucket(self):
+ # Project rules move the empty-user-agent check out of the pattern array into its own
+ # branch, so it has to keep classifying events no rule claims.
+ is_bot, _name, category = self._classify(
+ [_custom_bot(pattern="AcmeBot")],
+ {"$ip": "203.0.113.9"},
+ )
+
+ assert (is_bot, category) == (True, "no_user_agent")
diff --git a/posthog/hogql/functions/traffic_type.py b/posthog/hogql/functions/traffic_type.py
index d44e911d9f29..b8f618230d53 100644
--- a/posthog/hogql/functions/traffic_type.py
+++ b/posthog/hogql/functions/traffic_type.py
@@ -16,18 +16,124 @@ The legacy __preview_* names still resolve as deprecated aliases.
Bot definitions (patterns, categories, names, IP ranges) live in
products.web_analytics.backend.hogql_queries so that changes to bot data do not require
a 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.
"""
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
from posthog.hogql import ast
+from posthog.dataclasses import frozen
+
from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
from products.web_analytics.backend.hogql_queries.bot_ip_definitions import (
BOT_IP_DEFINITIONS,
bot_ip_prefix_groups_by_definition,
merged_bot_ip_prefix_groups,
)
+from products.web_analytics.backend.hogql_queries.custom_bot_definitions import (
+ IP_FIELD,
+ USER_AGENT_FIELD,
+ CidrGroup,
+ CustomBotGroup,
+ compile_definitions,
+)
+
+if TYPE_CHECKING:
+ from posthog.schema import HogQLQueryModifiers
+
+
+def _custom_groups(modifiers: Optional["HogQLQueryModifiers"]) -> list[CustomBotGroup]:
+ if modifiers is None:
+ return []
+ return compile_definitions(modifiers.customBotDefinitions)
+
+
+def 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)."""
+ if modifiers is None or not modifiers.customBotDefinitions:
+ return False
+ return any(definition.key == USER_AGENT_FIELD for definition in modifiers.customBotDefinitions)
+
+
+def _string_array(values: list[str]) -> ast.Array:
+ return ast.Array(exprs=[ast.Constant(value=value) for value in values])
+
+
+def _matched(index_call: ast.Expr) -> ast.Expr:
+ return ast.CompareOperation(op=ast.CompareOperationOp.NotEq, left=index_call, right=ast.Constant(value=0))
+
+
+def _property_expr(key: str, args: list[ast.Expr]) -> Optional[ast.Expr]:
+ """The expression a project rule on `key` matches against, or None when this call cannot reach it.
+
+ The user agent and the client IP arrive as arguments. Any other property hangs off the same
+ properties object the user agent was read from, which only works when the caller passed a plain
+ property reference — a hand-written `isLikelyBot(concat(...))` has no properties object to
+ reach into, so rules on those properties are skipped rather than guessed at.
+ """
+ if key == USER_AGENT_FIELD:
+ return args[0]
+ ip_expr = _optional_ip_arg(args)
+ if key == IP_FIELD and ip_expr is not None:
+ return ip_expr
+ user_agent_expr = args[0]
+ # Only a user agent read straight from a properties object (properties.$raw_user_agent) has a
+ # sibling to reach for. Replacing the last segment of any other chain would invent a column, e.g.
+ # getBotName(foo.ua) -> foo.$host, and fail the whole query, so skip the rule instead.
+ if (
+ isinstance(user_agent_expr, ast.Field)
+ and len(user_agent_expr.chain) > 1
+ and user_agent_expr.chain[-1] == USER_AGENT_FIELD
+ and user_agent_expr.chain[-2] == "properties"
+ ):
+ return ast.Field(chain=[*user_agent_expr.chain[:-1], key])
+ return None
+
+
+@frozen
+class CustomRuleBranch:
+ """One group of a project's rules, compiled: whether it matched and which label it reports."""
+
+ matched: ast.Expr
+ label: ast.Expr
+
+
+def _custom_group_branch(group: CustomBotGroup, args: list[ast.Expr], attr: str) -> Optional[CustomRuleBranch]:
+ property_expr = _property_expr(group.key, args)
+ if property_expr is None:
+ return None
+
+ if isinstance(group, CidrGroup):
+ safe_ip = _safe_ip_expr(property_expr)
+ multi_if_args: list[ast.Expr] = []
+ for index, (prefixlen, address) in enumerate(group.networks, start=1):
+ multi_if_args.append(_ip_group_match(safe_ip, prefixlen, (address,)))
+ multi_if_args.append(ast.Constant(value=index))
+ multi_if_args.append(ast.Constant(value=0))
+ index_call: ast.Expr = ast.Call(name="multiIf", args=multi_if_args)
+ else:
+ safe_property = ast.Call(name="ifNull", args=[property_expr, ast.Constant(value="")])
+ # 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 broad
+ # one could never take the label. Still a single hyperscan pass; an empty match list
+ # arrayMins to 0, the same no-match sentinel.
+ index_call = ast.Call(
+ name="arrayMin",
+ args=[ast.Call(name="multiMatchAllIndices", args=[safe_property, _string_array(group.patterns)])],
+ )
+
+ labels = _string_array([getattr(definition, attr) for definition in group.definitions])
+ return CustomRuleBranch(
+ matched=_matched(index_call),
+ label=ast.ArrayAccess(array=labels, property=index_call, nullish=False),
+ )
def _safe_ip_expr(ip_expr: ast.Expr) -> ast.Expr:
@@ -96,90 +202,122 @@ def _ip_label_lookup(ip_expr: ast.Expr, attr: str, default: str) -> ast.Expr:
def _build_bot_array_lookup(
- user_agent_expr: ast.Expr,
+ args: list[ast.Expr],
attr: str, # "name", "operator", "category", or "traffic_type"
default: str = "",
empty_ua_value: str = "",
- ip_expr: Optional[ast.Expr] = None,
+ modifiers: Optional["HogQLQueryModifiers"] = None,
) -> ast.Expr:
- """Build a multiMatchAnyIndex + array lookup expression for efficient bot detection.
+ """Build the expression that resolves one classification label.
- Uses multiMatchAnyIndex which evaluates the user_agent expression once and checks
- all patterns, then uses array indexing to get the corresponding label.
+ Uses multiMatchAnyIndex, which evaluates the user agent once and checks all patterns, then
+ indexes the matching label out of a parallel array.
- NULL user agents are coalesced to empty string so they match the ^$ pattern
- and get classified as empty_ua_value instead of falling through to default.
+ NULL user agents are coalesced to empty string so a missing user agent classifies as
+ empty_ua_value instead of falling through to default.
- When ip_expr is given, user agents that match no pattern fall back to the IP-range
- lookup before defaulting.
+ When the client IP is given, anything the patterns miss falls back to the IP-range lookup
+ before defaulting.
"""
- # Coalesce NULL to empty string so NULL user agents match the ^$ pattern
+ user_agent_expr = args[0]
+ ip_expr = _optional_ip_arg(args)
+ # Coalesce NULL to empty string so NULL user agents are matchable
safe_user_agent = ast.Call(name="ifNull", args=[user_agent_expr, ast.Constant(value="")])
- # Build patterns array (all bot patterns + empty UA pattern)
- patterns = [*BOT_DEFINITIONS.keys(), "^$"]
- patterns_array = ast.Array(exprs=[ast.Constant(value=p) for p in patterns])
-
- # Build labels array (corresponding labels + empty UA label)
- labels = [getattr(bot_def, attr) for bot_def in BOT_DEFINITIONS.values()]
- labels.append(empty_ua_value)
- labels_array = ast.Array(exprs=[ast.Constant(value=label) for label in labels])
-
- # multiMatchAnyIndex(user_agent, patterns) -> returns 0 if no match, else 1-based index
- index_call = ast.Call(name="multiMatchAnyIndex", args=[safe_user_agent, patterns_array])
-
- # labels[index] - array access (1-based in ClickHouse)
- label_lookup = ast.ArrayAccess(array=labels_array, property=index_call, nullish=False)
-
fallback: ast.Expr = ast.Constant(value=default)
if ip_expr is not None:
fallback = _ip_label_lookup(ip_expr, attr, default)
- # if(index = 0, fallback, labels[index])
- return ast.Call(
- name="if",
- args=[
- ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=index_call, right=ast.Constant(value=0)),
- fallback,
- label_lookup,
- ],
+ builtin_labels = [getattr(bot_def, attr) for bot_def in BOT_DEFINITIONS.values()]
+ groups = _custom_groups(modifiers)
+
+ if not groups:
+ # No project rules: one pass over the built-in patterns plus the empty-user-agent sentinel.
+ patterns_array = _string_array([*BOT_DEFINITIONS.keys(), "^$"])
+ labels_array = _string_array([*builtin_labels, empty_ua_value])
+ index_call = ast.Call(name="multiMatchAnyIndex", args=[safe_user_agent, patterns_array])
+ return ast.Call(
+ name="if",
+ args=[
+ ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=index_call, right=ast.Constant(value=0)),
+ fallback,
+ ast.ArrayAccess(array=labels_array, property=index_call, nullish=False),
+ ],
+ )
+
+ # With project rules the checks become an ordered chain, in this order: the project's own
+ # rules, then the built-ins, then the empty user agent, then the built-in IP ranges. A rule
+ # someone wrote by hand says more about what they want counted than a default we shipped, so
+ # it wins — that also makes the setting predictable, since a rule that matches always names
+ # the event.
+ #
+ # It has to be a branch per group rather than one shared pattern array: multiMatchAnyIndex
+ # reports whichever pattern matches earliest in the string rather than earliest in the array,
+ # so merging the arrays would leave precedence up to the user agent being classified.
+ branches: list[ast.Expr] = []
+ for group in groups:
+ branch = _custom_group_branch(group, args, attr)
+ if branch is not None:
+ branches.extend([branch.matched, branch.label])
+ builtin_index = ast.Call(
+ name="multiMatchAnyIndex", args=[safe_user_agent, _string_array(list(BOT_DEFINITIONS.keys()))]
+ )
+ branches.extend(
+ [
+ _matched(builtin_index),
+ ast.ArrayAccess(array=_string_array(builtin_labels), property=builtin_index, nullish=False),
+ ]
)
+ branches.extend(
+ [
+ ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=safe_user_agent, right=ast.Constant(value="")),
+ ast.Constant(value=empty_ua_value),
+ ]
+ )
+ branches.append(fallback)
+ return ast.Call(name="multiIf", args=branches)
def _optional_ip_arg(args: list[ast.Expr]) -> Optional[ast.Expr]:
return args[1] if len(args) > 1 else None
-def get_bot_name(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:
+def get_bot_name(node: ast.Call, args: list[ast.Expr], modifiers: Optional["HogQLQueryModifiers"] = None) -> ast.Expr:
"""
HogQL function: getBotName(user_agent[, ip])
Returns bot name: "Googlebot", "ChatGPT", etc. Empty string for regular traffic.
"""
- return _build_bot_array_lookup(args[0], "name", default="", empty_ua_value="", ip_expr=_optional_ip_arg(args))
+ return _build_bot_array_lookup(args, "name", default="", empty_ua_value="", modifiers=modifiers)
-def get_bot_operator(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:
+def get_bot_operator(
+ node: ast.Call, args: list[ast.Expr], modifiers: Optional["HogQLQueryModifiers"] = None
+) -> ast.Expr:
"""
HogQL function: getBotOperator(user_agent[, ip])
Returns operator/company name: "Google", "OpenAI", "Anthropic", etc. Empty string for regular traffic.
"""
- return _build_bot_array_lookup(args[0], "operator", default="", empty_ua_value="", ip_expr=_optional_ip_arg(args))
+ return _build_bot_array_lookup(args, "operator", default="", empty_ua_value="", modifiers=modifiers)
-def get_traffic_type(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:
+def get_traffic_type(
+ node: ast.Call, args: list[ast.Expr], modifiers: Optional["HogQLQueryModifiers"] = None
+) -> ast.Expr:
"""
HogQL function: getTrafficType(user_agent[, ip])
Returns one of: 'AI Agent', 'Bot', 'Automation', 'Regular'
"""
return _build_bot_array_lookup(
- args[0], "traffic_type", default="Regular", empty_ua_value="Automation", ip_expr=_optional_ip_arg(args)
+ args, "traffic_type", default="Regular", empty_ua_value="Automation", modifiers=modifiers
)
-def get_traffic_category(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:
+def get_traffic_category(
+ node: ast.Call, args: list[ast.Expr], modifiers: Optional["HogQLQueryModifiers"] = None
+) -> ast.Expr:
"""
HogQL function: getTrafficCategory(user_agent[, ip])
@@ -187,11 +325,11 @@ def get_traffic_category(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:
For regular traffic, returns 'regular'.
"""
return _build_bot_array_lookup(
- args[0], "category", default="regular", empty_ua_value="no_user_agent", ip_expr=_optional_ip_arg(args)
+ args, "category", default="regular", empty_ua_value="no_user_agent", modifiers=modifiers
)
-def is_bot(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:
+def is_bot(node: ast.Call, args: list[ast.Expr], modifiers: Optional["HogQLQueryModifiers"] = None) -> ast.Expr:
"""
HogQL function: isLikelyBot(user_agent[, ip])
@@ -202,37 +340,39 @@ def is_bot(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:
Uses multiMatchAnyIndex for efficient single-pass matching (same as get_traffic_type etc.);
the IP check is a handful of hash-set lookups and only evaluates for rows the UA check
didn't already match (or() short-circuits).
+
+ Unlike the label lookups this only answers yes or no, so a project's rules can be OR'd in
+ rather than ordered against the built-ins — no rule can change the answer another one gave.
"""
user_agent_expr = args[0]
safe_user_agent = ast.Call(name="ifNull", args=[user_agent_expr, ast.Constant(value="")])
- patterns = [*BOT_DEFINITIONS.keys(), "^$"]
- patterns_array = ast.Array(exprs=[ast.Constant(value=p) for p in patterns])
-
+ patterns_array = _string_array([*BOT_DEFINITIONS.keys(), "^$"])
index_call = ast.Call(name="multiMatchAnyIndex", args=[safe_user_agent, patterns_array])
- matched: ast.Expr = ast.CompareOperation(
- op=ast.CompareOperationOp.NotEq,
- left=index_call,
- right=ast.Constant(value=0),
- )
+ conditions: list[ast.Expr] = [_matched(index_call)]
+ for group in _custom_groups(modifiers):
+ branch = _custom_group_branch(group, args, "name")
+ if branch is not None:
+ conditions.append(branch.matched)
ip_expr = _optional_ip_arg(args)
if ip_expr is not None:
- matched = ast.Or(exprs=[matched, _build_ip_match_expr(ip_expr)])
+ conditions.append(_build_ip_match_expr(ip_expr))
+
+ matched: ast.Expr = conditions[0] if len(conditions) == 1 else ast.Or(exprs=conditions)
# Cast to Bool so results render as true/false (not 0/1) in insights breakdowns.
return ast.Call(name="toBool", args=[matched])
-def get_bot_type(node: ast.Call, args: list[ast.Expr]) -> ast.Expr:
+def get_bot_type(node: ast.Call, args: list[ast.Expr], modifiers: Optional["HogQLQueryModifiers"] = None) -> ast.Expr:
"""
HogQL function: getBotType(user_agent[, ip])
Returns the bot category or empty string for regular traffic.
Categories: 'ai_crawler', 'ai_search', 'ai_assistant', 'search_crawler', 'seo_crawler',
- 'social_crawler', 'monitoring', 'http_client', 'headless_browser', 'no_user_agent', ''
+ 'social_crawler', 'monitoring', 'http_client', 'headless_browser', 'no_user_agent',
+ a project's own category, or ''
"""
- return _build_bot_array_lookup(
- args[0], "category", default="", empty_ua_value="no_user_agent", ip_expr=_optional_ip_arg(args)
- )
+ return _build_bot_array_lookup(args, "category", default="", empty_ua_value="no_user_agent", modifiers=modifiers)
diff --git a/posthog/hogql/modifiers.py b/posthog/hogql/modifiers.py
index 79eec09ef02f..8c7f2acc5a28 100644
--- a/posthog/hogql/modifiers.py
+++ b/posthog/hogql/modifiers.py
@@ -50,7 +50,7 @@ def create_default_modifiers_for_team(
) -> "HogQLQueryModifiers":
from pydantic import ValidationError # noqa: PLC0415
- from posthog.schema import CustomChannelRule, HogQLQueryModifiers # noqa: PLC0415
+ from posthog.schema import CustomBotDefinition, CustomChannelRule, HogQLQueryModifiers # noqa: PLC0415
if modifiers is None:
modifiers = HogQLQueryModifiers()
@@ -71,6 +71,21 @@ def create_default_modifiers_for_team(
setattr(modifiers, key, value)
except ValidationError:
pass
+ elif 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.
+ 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)
else:
setattr(modifiers, key, value)
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index 4a00fbef26d2..012455a021c4 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -41,6 +41,7 @@ from posthog.hogql.functions.traffic_type import (
get_bot_type,
get_traffic_category,
get_traffic_type,
+ has_user_agent_rule,
is_bot,
)
from posthog.hogql.hogqlx import HOGQLX_COMPONENTS, HOGQLX_TAGS, convert_to_hx
@@ -1914,22 +1915,40 @@ class Resolver(CloningVisitor):
)
if node.name in ("isLikelyBot", "__preview_isBot"):
# The two-arg form duplicates its IP argument across the per-prefix-length range
- # checks, so it needs the same re-entrancy guard as the lookup builders below.
- if len(node.args) > 1:
- return self._expand_duplicating_macro(node, lambda: is_bot(node=node, args=node.args))
- return self.visit(is_bot(node=node, args=node.args))
+ # checks, and a project's user-agent rules duplicate the user-agent argument the
+ # same way, so guard the expansion whenever either can happen. A one-arg call with
+ # no user-agent rule embeds its argument once — rules on other properties read a
+ # sibling field, not the argument — so it stays unguarded and can still be reached
+ # inside another macro's expansion.
+ modifiers = self.context.modifiers
+ duplicates_argument = len(node.args) > 1 or has_user_agent_rule(modifiers)
+ if duplicates_argument:
+ return self._expand_duplicating_macro(
+ node, lambda: is_bot(node=node, args=node.args, modifiers=modifiers)
+ )
+ return self.visit(is_bot(node=node, args=node.args, modifiers=modifiers))
# The bot-lookup builders below duplicate their argument, so they must expand under the
# re-entrancy guard to bound nested expansion (see _expand_duplicating_macro).
if node.name in ("getTrafficType", "__preview_getTrafficType"):
- return self._expand_duplicating_macro(node, lambda: get_traffic_type(node=node, args=node.args))
+ return self._expand_duplicating_macro(
+ node, lambda: get_traffic_type(node=node, args=node.args, modifiers=self.context.modifiers)
+ )
if node.name in ("getTrafficCategory", "__preview_getTrafficCategory"):
- return self._expand_duplicating_macro(node, lambda: get_traffic_category(node=node, args=node.args))
+ return self._expand_duplicating_macro(
+ node, lambda: get_traffic_category(node=node, args=node.args, modifiers=self.context.modifiers)
+ )
if node.name in ("getBotType", "__preview_getBotType"):
- return self._expand_duplicating_macro(node, lambda: get_bot_type(node=node, args=node.args))
+ return self._expand_duplicating_macro(
+ node, lambda: get_bot_type(node=node, args=node.args, modifiers=self.context.modifiers)
+ )
if node.name in ("getBotName", "__preview_getBotName"):
- return self._expand_duplicating_macro(node, lambda: get_bot_name(node=node, args=node.args))
+ return self._expand_duplicating_macro(
+ node, lambda: get_bot_name(node=node, args=node.args, modifiers=self.context.modifiers)
+ )
if node.name in ("getBotOperator", "__preview_getBotOperator"):
- return self._expand_duplicating_macro(node, lambda: get_bot_operator(node=node, args=node.args))
+ return self._expand_duplicating_macro(
+ node, lambda: get_bot_operator(node=node, args=node.args, modifiers=self.context.modifiers)
+ )
if node.name in ("_defaultChannelType", "_domainType"):
from posthog.hogql.database.schema.channel_type import ( # noqa: PLC0415 — avoid resolver->schema import cycle
expand_default_channel_type_call,
diff --git a/posthog/hogql/test/test_modifiers.py b/posthog/hogql/test/test_modifiers.py
index 8fc37b4fbe86..01aa28adbd92 100644
--- a/posthog/hogql/test/test_modifiers.py
+++ b/posthog/hogql/test/test_modifiers.py
@@ -84,6 +84,24 @@ class TestModifiers(BaseTest):
modifiers = create_default_modifiers_for_team(self.team)
assert modifiers.personsOnEventsMode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS
+ def test_unparseable_custom_bot_definitions_are_dropped(self):
+ # modifiers is hand-editable JSON (e.g. Django admin), so an entry that is not a rule object
+ # can reach here. It has to be dropped, not kept — a non-dict entry would otherwise crash
+ # every classification query when compile_definitions reads its fields.
+ self.team.modifiers = {
+ "customBotDefinitions": [
+ "not-a-rule",
+ {"pattern": "no name so invalid"},
+ {"id": "1", "name": "Acme", "key": "$raw_user_agent", "pattern": "AcmeBot", "matcher": "contains"},
+ ]
+ }
+ self.team.save()
+
+ modifiers = create_default_modifiers_for_team(self.team)
+
+ assert modifiers.customBotDefinitions is not None
+ assert [d.name for d in modifiers.customBotDefinitions] == ["Acme"]
+
@patch(
# _person_on_events_person_id_override_properties_on_events is normally determined by feature flag
"posthog.models.team.Team._person_on_events_person_id_override_properties_on_events",
diff --git a/posthog/schema.py b/posthog/schema.py
index f9dd66592fa2..d4742540b48d 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -71,6 +71,8 @@ from posthog.schema_enums import (
CountPerActorMathType as CountPerActorMathType,
CurrencyCode as CurrencyCode,
Curve as Curve,
+ CustomBotField as CustomBotField,
+ CustomBotMatcher as CustomBotMatcher,
CustomChannelField as CustomChannelField,
CustomChannelOperator as CustomChannelOperator,
DatabaseSchemaManagedViewTableKind as DatabaseSchemaManagedViewTableKind,
@@ -4776,6 +4778,24 @@ class CohortPropertyFilter(BaseModel):
value: int
+class CustomBotDefinition(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ category: str | None = Field(
+ default=None,
+ description="Reported by `$virt_traffic_category`. Defaults to `custom`.",
+ )
+ id: str
+ key: CustomBotField = Field(..., description="The event property this rule reads.")
+ matcher: CustomBotMatcher
+ 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):
model_config = ConfigDict(
extra="forbid",
@@ -5556,6 +5576,7 @@ class HogQLQueryModifiers(BaseModel):
bounceRateDurationSeconds: float | None = None
bounceRatePageViewMode: BounceRatePageViewMode | None = None
convertToProjectTimezone: bool | None = None
+ customBotDefinitions: list[CustomBotDefinition] | None = None
customChannelTypeRules: list[CustomChannelRule] | None = None
dataWarehouseEventsModifiers: list[DataWarehouseEventsModifier] | None = None
debug: bool | None = None
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 117a2c844156..648cd9093f98 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -884,6 +884,21 @@ class CurrencyCode(StrEnum):
ZMW = "ZMW"
+class CustomBotField(StrEnum):
+ FIELD_RAW_USER_AGENT = "$raw_user_agent"
+ FIELD_IP = "$ip"
+ FIELD_LIB = "$lib"
+ FIELD_HOST = "$host"
+ FIELD_PATHNAME = "$pathname"
+ FIELD_CURRENT_URL = "$current_url"
+
+
+class CustomBotMatcher(StrEnum):
+ CONTAINS = "contains"
+ REGEX = "regex"
+ CIDR = "cidr"
+
+
class CustomChannelField(StrEnum):
UTM_SOURCE = "utm_source"
UTM_MEDIUM = "utm_medium"
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index 99a3e9d59a47..507342407f84 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -3180,7 +3180,7 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
},
"$virt_is_bot": {
"label": "Is bot",
- "description": "Whether the event was generated by a bot, crawler, or automation tool, detected from the user agent or from operator-published bot IP ranges.",
+ "description": "Whether the event was generated by a bot, crawler, or automation tool, detected from the user agent, from operator-published bot IP ranges, or from a bot the project defined itself in settings.",
"type": "Boolean",
"virtual": True,
},
@@ -3193,7 +3193,7 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
},
"$virt_traffic_category": {
"label": "Traffic category",
- "description": "Detailed traffic category: ai_crawler, ai_search, ai_assistant, search_crawler, seo_crawler, etc.",
+ "description": "Detailed traffic category: ai_crawler, ai_search, ai_assistant, search_crawler, seo_crawler, etc. Bots the project defined itself report the category picked in settings.",
"examples": ["ai_crawler", "ai_search", "ai_assistant", "search_crawler", "regular"],
"type": "String",
"virtual": True,
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 0186f5a01dc4..d7911a6ab22d 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -1142,6 +1142,38 @@ export const BounceRatePageViewModeApi = {
UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',
} as const
+export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]
+
+export const CustomBotFieldApi = {
+ RawUserAgent: '$raw_user_agent',
+ Ip: '$ip',
+ Lib: '$lib',
+ Host: '$host',
+ Pathname: '$pathname',
+ CurrentUrl: '$current_url',
+} as const
+
+export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof CustomBotMatcherApi]
+
+export const CustomBotMatcherApi = {
+ Contains: 'contains',
+ Regex: 'regex',
+ Cidr: 'cidr',
+} as const
+
+export interface CustomBotDefinitionApi {
+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */
+ category?: string | null
+ id: string
+ /** The event property this rule reads. */
+ key: CustomBotFieldApi
+ matcher: 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 = {
@@ -1293,6 +1325,7 @@ export interface HogQLQueryModifiersApi {
bounceRateDurationSeconds?: number | null
bounceRatePageViewMode?: BounceRatePageViewModeApi | null
convertToProjectTimezone?: boolean | null
+ customBotDefinitions?: CustomBotDefinitionApi[] | null
customChannelTypeRules?: CustomChannelRuleApi[] | null
dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
debug?: boolean | null
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 3f13fe0a74ee..b3bbf95dd321 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1339,6 +1339,38 @@ export const BounceRatePageViewModeApi = {
UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',
} as const
+export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]
+
+export const CustomBotFieldApi = {
+ RawUserAgent: '$raw_user_agent',
+ Ip: '$ip',
+ Lib: '$lib',
+ Host: '$host',
+ Pathname: '$pathname',
+ CurrentUrl: '$current_url',
+} as const
+
+export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof CustomBotMatcherApi]
+
+export const CustomBotMatcherApi = {
+ Contains: 'contains',
+ Regex: 'regex',
+ Cidr: 'cidr',
+} as const
+
+export interface CustomBotDefinitionApi {
+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */
+ category?: string | null
+ id: string
+ /** The event property this rule reads. */
+ key: CustomBotFieldApi
+ matcher: 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 = {
@@ -1490,6 +1522,7 @@ export interface HogQLQueryModifiersApi {
bounceRateDurationSeconds?: number | null
bounceRatePageViewMode?: BounceRatePageViewModeApi | null
convertToProjectTimezone?: boolean | null
+ customBotDefinitions?: CustomBotDefinitionApi[] | null
customChannelTypeRules?: CustomChannelRuleApi[] | null
dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
debug?: boolean | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 44bd7b0f6774..b03b5e73602b 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -334,6 +334,38 @@ export const BounceRatePageViewModeApi = {
UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',
} as const
+export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]
+
+export const CustomBotFieldApi = {
+ RawUserAgent: '$raw_user_agent',
+ Ip: '$ip',
+ Lib: '$lib',
+ Host: '$host',
+ Pathname: '$pathname',
+ CurrentUrl: '$current_url',
+} as const
+
+export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof CustomBotMatcherApi]
+
+export const CustomBotMatcherApi = {
+ Contains: 'contains',
+ Regex: 'regex',
+ Cidr: 'cidr',
+} as const
+
+export interface CustomBotDefinitionApi {
+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */
+ category?: string | null
+ id: string
+ /** The event property this rule reads. */
+ key: CustomBotFieldApi
+ matcher: 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 = {
@@ -485,6 +517,7 @@ export interface HogQLQueryModifiersApi {
bounceRateDurationSeconds?: number | null
bounceRatePageViewMode?: BounceRatePageViewModeApi | null
convertToProjectTimezone?: boolean | null
+ customBotDefinitions?: CustomBotDefinitionApi[] | null
customChannelTypeRules?: CustomChannelRuleApi[] | null
dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
debug?: boolean | null
diff --git a/products/web_analytics/backend/hogql_queries/bot_ip_definitions.py b/products/web_analytics/backend/hogql_queries/bot_ip_definitions.py
index 78de65db8e84..9840312e7c23 100644
--- a/products/web_analytics/backend/hogql_queries/bot_ip_definitions.py
+++ b/products/web_analytics/backend/hogql_queries/bot_ip_definitions.py
@@ -130,7 +130,7 @@ BOT_IP_DEFINITIONS: dict[str, BotIPDefinition] = {
_IPV4_MAPPED_OFFSET = 96
-def _ipv6_prefix_groups(cidrs: tuple[str, ...]) -> tuple[tuple[int, tuple[str, ...]], ...]:
+def ipv6_prefix_groups(cidrs: tuple[str, ...]) -> tuple[tuple[int, tuple[str, ...]], ...]:
groups: dict[int, list[str]] = {}
for cidr in cidrs:
network = ip_network(cidr)
@@ -147,7 +147,7 @@ def _ipv6_prefix_groups(cidrs: tuple[str, ...]) -> tuple[tuple[int, tuple[str, .
@cache
def bot_ip_prefix_groups_by_definition() -> tuple[tuple[str, tuple[tuple[int, tuple[str, ...]], ...]], ...]:
"""Per-definition (prefixlen, network addresses) groups, for labeled lookups (bot name etc.)."""
- return tuple((key, _ipv6_prefix_groups(definition.networks)) for key, definition in BOT_IP_DEFINITIONS.items())
+ return tuple((key, ipv6_prefix_groups(definition.networks)) for key, definition in BOT_IP_DEFINITIONS.items())
@cache
@@ -156,4 +156,4 @@ def merged_bot_ip_prefix_groups() -> tuple[tuple[int, tuple[str, ...]], ...]:
all_networks = [ip_network(cidr) for definition in BOT_IP_DEFINITIONS.values() for cidr in definition.networks]
v4 = collapse_addresses(n for n in all_networks if n.version == 4)
v6 = collapse_addresses(n for n in all_networks if n.version == 6)
- return _ipv6_prefix_groups(tuple(str(n) for n in [*v4, *v6]))
+ return ipv6_prefix_groups(tuple(str(n) for n in [*v4, *v6]))
diff --git a/products/web_analytics/backend/hogql_queries/custom_bot_definitions.py b/products/web_analytics/backend/hogql_queries/custom_bot_definitions.py
new file mode 100644
index 000000000000..29d62a67debe
--- /dev/null
+++ b/products/web_analytics/backend/hogql_queries/custom_bot_definitions.py
@@ -0,0 +1,309 @@
+"""
+Project-defined bot definitions.
+
+BOT_DEFINITIONS only covers bots that declare themselves in the user agent, and it only covers the
+ones we know about. A project adds its own rules in project settings when a scraper matters to
+them 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.
+
+The definitions are stored on `team.modifiers` and reach HogQL through
+`HogQLQueryModifiers.customBotDefinitions`, so they extend `$virt_is_bot`, `$virt_bot_name`,
+`$virt_bot_operator`, `$virt_traffic_type` and `$virt_traffic_category` everywhere HogQL runs,
+not only in web analytics.
+
+Substring and regex rules end up inside a ClickHouse `multiMatchAllIndices` call, which compiles them
+with hyperscan. Hyperscan supports less than PCRE, and a pattern it rejects fails every query that
+reads 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.
+- `assert_patterns_compile` asks ClickHouse itself whether the patterns compile, because Python's
+ `re` accepting a pattern does not mean hyperscan will.
+
+`compile_definitions` drops anything that still fails validation, so a definition written straight
+to the API before a rule tightened cannot break every query for the project.
+"""
+
+import re
+from ipaddress import ip_network
+from typing import TYPE_CHECKING, Union
+
+import structlog
+
+from posthog.dataclasses import frozen
+
+from products.web_analytics.backend.hogql_queries.bot_definitions import BotDefinition
+from products.web_analytics.backend.hogql_queries.bot_ip_definitions import ipv6_prefix_groups
+
+if TYPE_CHECKING:
+ from posthog.schema import CustomBotDefinition
+
+logger = structlog.get_logger(__name__)
+
+# Bounds the work added to every query that reads a classification field.
+MAX_CUSTOM_BOT_DEFINITIONS = 50
+MAX_PATTERN_LENGTH = 200
+MAX_NAME_LENGTH = 100
+
+USER_AGENT_FIELD = "$raw_user_agent"
+IP_FIELD = "$ip"
+
+# Event properties a rule can match on, labelled the way the taxonomy already labels them.
+# Deliberately short: each property used adds a read to every query that selects a classification
+# field, so the list stays to properties that say who is calling rather than what they found.
+CUSTOM_BOT_FIELDS: dict[str, str] = {
+ USER_AGENT_FIELD: "Raw user agent",
+ IP_FIELD: "IP address",
+ "$lib": "Library",
+ "$host": "Host",
+ "$pathname": "Path name",
+ "$current_url": "Current URL",
+}
+
+CIDR_MATCHER = "cidr"
+PATTERN_MATCHERS = ("contains", "regex")
+
+# Category used when a project does not pick one.
+CUSTOM_CATEGORY = "custom"
+
+# Traffic type reported for each category. Kept explicit rather than derived from BOT_DEFINITIONS
+# because http_client is split across two traffic types there.
+# test_custom_bot_definitions.py fails if BOT_DEFINITIONS gains a category that is missing here.
+TRAFFIC_TYPE_BY_CATEGORY: dict[str, str] = {
+ "ai_crawler": "AI Agent",
+ "ai_search": "AI Agent",
+ "ai_assistant": "AI Agent",
+ "search_crawler": "Bot",
+ "seo_crawler": "Bot",
+ "social_crawler": "Bot",
+ "monitoring": "Bot",
+ "http_client": "Automation",
+ "headless_browser": "Automation",
+ CUSTOM_CATEGORY: "Bot",
+}
+
+# Hyperscan rejects these PCRE constructs. Listing them gives the person a specific error on save
+# instead of a broken project.
+_UNSUPPORTED_CONSTRUCTS: list[tuple[str, str]] = [
+ (r"\(\?=", "lookahead"),
+ (r"\(\?!", "lookahead"),
+ (r"\(\?<=", "lookbehind"),
+ (r"\(\?<!", "lookbehind"),
+ (r"\(\?>", "atomic group"),
+ (r"\(\?\(", "conditional group"),
+ (r"\(\?R", "recursion"),
+ (r"\\[1-9]", "backreference"),
+ (r"\\[zZGKCRX]", "unsupported escape"),
+]
+
+_REGEX_METACHARACTERS = re.compile(r"([.^$*+?()\[\]{}|\\])")
+
+
+@frozen
+class PatternGroup:
+ """Rules on one property, matched by a single multiMatchAllIndices pass over their patterns.
+
+ `patterns[i]` names `definitions[i]`, so the 1-based match index reads straight off
+ `definitions`.
+ """
+
+ key: str
+ patterns: list[str]
+ definitions: list[BotDefinition]
+
+
+@frozen
+class CidrGroup:
+ """Rules matched against the client IP by network range.
+
+ `networks[i]` is the (prefix length, IPv6 network address) of `definitions[i]`. IPv4 ranges are
+ already mapped into IPv6 space, matching how the built-in IP ranges are compared.
+ """
+
+ key: str
+ networks: list[tuple[int, str]]
+ definitions: list[BotDefinition]
+
+
+CustomBotGroup = Union[PatternGroup, CidrGroup]
+
+
+def _escape_literal(value: str) -> str:
+ return _REGEX_METACHARACTERS.sub(r"\\\1", value)
+
+
+def compile_pattern(pattern: str, matcher: str) -> str:
+ """Turn a substring or regex rule into the regex handed to multiMatchAllIndices."""
+ if matcher == "regex":
+ return 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)}"
+
+
+def compile_cidr(pattern: str) -> tuple[int, str]:
+ """Turn an IP rule into the (prefix length, network address) pair the IP matcher compares.
+
+ Normalized with strict=False first, matching what validation accepts — otherwise a range
+ written with host bits set, like 192.0.2.7/24, would save and then fail to compile.
+ """
+ network = ip_network(pattern.strip(), strict=False)
+ prefixlen, addresses = ipv6_prefix_groups((str(network),))[0]
+ return prefixlen, addresses[0]
+
+
+def validate_pattern(pattern: str, matcher: str, key: str) -> None:
+ """Raise ValueError when a pattern cannot be used, with a message meant for the person saving it."""
+ if not pattern or not pattern.strip():
+ raise ValueError("Pattern cannot be empty.")
+ if len(pattern) > MAX_PATTERN_LENGTH:
+ raise ValueError(f"Pattern cannot be longer than {MAX_PATTERN_LENGTH} characters.")
+
+ if matcher == CIDR_MATCHER:
+ if key != IP_FIELD:
+ raise ValueError(f"IP ranges only work with the {CUSTOM_BOT_FIELDS[IP_FIELD]} property.")
+ stripped = pattern.strip()
+ # A zone identifier ("fe80::1%eth0") parses in Python but ClickHouse toIPv6 rejects it, and
+ # a scoped link-local address can never be an event $ip. Reject it here so it cannot save and
+ # then break every query that reads a bot field for the project.
+ if "%" in stripped:
+ raise ValueError(f"'{pattern}' is not a valid IP address or range: a zone identifier is not supported.")
+ try:
+ # strict=False so "12.34.56.78/24" is read as its network rather than rejected for
+ # having host bits set.
+ ip_network(stripped, strict=False)
+ except ValueError as error:
+ raise ValueError(f"'{pattern}' is not a valid IP address or range: {error}.") from error
+ return
+
+ if matcher not in PATTERN_MATCHERS:
+ raise ValueError(f"Unknown matcher '{matcher}'.")
+ if matcher != "regex":
+ return
+
+ for construct, label in _UNSUPPORTED_CONSTRUCTS:
+ if re.search(construct, pattern):
+ raise ValueError(f"Pattern uses a {label}, which is not supported here.")
+ try:
+ re.compile(pattern)
+ except re.error as error:
+ 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():
+ raise ValueError("Bot name cannot be empty.")
+ if len(definition.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)
+
+
+# ClickHouse codes that mean "this pattern is the problem": BAD_ARGUMENTS and
+# CANNOT_COMPILE_REGEXP for a pattern hyperscan won't accept, HYPERSCAN_CANNOT_SCAN_TEXT for one
+# it accepts but considers too slow to run. Any other code is an infrastructure problem.
+_BAD_PATTERN_CH_CODES = {36, 427, 447}
+_TOO_SLOW_CH_CODE = 447
+
+# ClickHouse reports the underlying hyperscan reason as: Pattern 'x' failed with error 'reason'.
+_CH_PATTERN_REASON = re.compile(r"failed with error '([^']+)'")
+
+
+def assert_patterns_compile(patterns: list[str]) -> None:
+ """Raise ValueError when ClickHouse cannot compile the patterns.
+
+ Python's `re` is more permissive than hyperscan, so this asks the engine that actually runs
+ them. A pattern that gets through here and then fails at query time would break every query
+ reading $virt_is_bot for the project.
+ """
+ if not patterns:
+ return
+
+ from clickhouse_driver.errors import ServerException # noqa: PLC0415 — keeps the heavy dep off the import path
+
+ from posthog.clickhouse.client import sync_execute # noqa: PLC0415 — keeps the heavy dep off the import path
+
+ try:
+ # Probe with the same function the query uses, so a pattern the probe accepts compiles there too.
+ sync_execute("SELECT multiMatchAllIndices(%(probe)s, %(patterns)s)", {"probe": "", "patterns": patterns})
+ except ServerException as error:
+ if error.code not in _BAD_PATTERN_CH_CODES:
+ # ClickHouse is unreachable or unhappy for an unrelated reason; don't block the save,
+ # but record the skip so a bypassed probe is visible instead of silent.
+ logger.warning("custom_bot_patterns_probe_skipped", code=error.code, error=str(error))
+ return
+ if error.code == _TOO_SLOW_CH_CODE:
+ raise ValueError("One of these patterns is too slow to run. Try a more specific one.") from error
+ reason = _CH_PATTERN_REASON.search(str(error.message or ""))
+ raise ValueError(
+ f"One of these patterns is not supported: {reason.group(1)}"
+ if reason
+ else "One of these patterns is not supported. Try a simpler expression."
+ ) from error
+ except Exception:
+ # A failure inside the probe itself (driver misuse, a changed signature) would otherwise
+ # disable this guard silently. Keep failing open, but make the bypass visible.
+ logger.exception("custom_bot_patterns_probe_error")
+ return
+
+
+def _to_bot_definition(definition: "CustomBotDefinition") -> BotDefinition:
+ category = definition.category or CUSTOM_CATEGORY
+ return BotDefinition(
+ name=definition.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,
+ )
+
+
+def compile_definitions(definitions: list["CustomBotDefinition"] | None) -> list[CustomBotGroup]:
+ """Compile a project's definitions 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.
+
+ Unusable definitions are dropped rather than raised on: one saved before a rule tightened, or
+ written straight to the API, must not break every query for the project.
+ """
+ if not definitions:
+ 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]:
+ try:
+ validate_definition(definition)
+ 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]
diff --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.py
new file mode 100644
index 000000000000..a71a91248abd
--- /dev/null
+++ b/products/web_analytics/backend/hogql_queries/test/test_custom_bot_definitions.py
@@ -0,0 +1,260 @@
+import pytest
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+
+from posthog.schema import CustomBotDefinition, CustomBotField, CustomBotMatcher
+
+from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
+from products.web_analytics.backend.hogql_queries.custom_bot_definitions import (
+ MAX_CUSTOM_BOT_DEFINITIONS,
+ MAX_PATTERN_LENGTH,
+ TRAFFIC_TYPE_BY_CATEGORY,
+ CidrGroup,
+ PatternGroup,
+ assert_patterns_compile,
+ compile_cidr,
+ compile_definitions,
+ compile_pattern,
+ compiled_patterns,
+ validate_definition,
+)
+
+
+def definition(**kwargs) -> CustomBotDefinition:
+ return CustomBotDefinition(
+ **{
+ "id": "1",
+ "name": "Acme scraper",
+ "key": CustomBotField.FIELD_RAW_USER_AGENT,
+ "pattern": "AcmeBot",
+ "matcher": CustomBotMatcher.CONTAINS,
+ **kwargs,
+ }
+ )
+
+
+def cidr_definition(**kwargs) -> CustomBotDefinition:
+ return definition(
+ **{"key": CustomBotField.FIELD_IP, "matcher": CustomBotMatcher.CIDR, "pattern": "192.0.2.0/24", **kwargs}
+ )
+
+
+class TestPatternCompilation:
+ @parameterized.expand(
+ [
+ ("Acme (bot)", r"(?i)Acme \(bot\)"),
+ ("v1.0", r"(?i)v1\.0"),
+ ("a+b", r"(?i)a\+b"),
+ ]
+ )
+ def test_contains_escapes_regex_metacharacters(self, pattern: str, expected: str):
+ # An unescaped "(" would either change what the pattern matches or make hyperscan reject it.
+ assert compile_pattern(pattern, "contains") == expected
+
+ def test_regex_is_passed_through(self):
+ assert compile_pattern("AcmeBot/[0-9]+", "regex") == "AcmeBot/[0-9]+"
+
+ @parameterized.expand(
+ [
+ # The IP matcher compares in IPv6 space, so an IPv4 range shifts by 96 bits and its
+ # address becomes IPv4-mapped. Comparing a /24 as-is would match nothing.
+ ("192.0.2.0/24", (120, "::ffff:192.0.2.0")),
+ ("192.0.2.7", (128, "::ffff:192.0.2.7")),
+ # Host bits set: read as the network rather than rejected.
+ ("192.0.2.7/24", (120, "::ffff:192.0.2.0")),
+ ("2001:db8::/32", (32, "2001:db8::")),
+ ]
+ )
+ def test_cidr_compiles_into_ipv6_space(self, pattern: str, expected: tuple[int, str]):
+ assert compile_cidr(pattern) == expected
+
+
+class TestValidation:
+ @parameterized.expand(
+ [
+ ("empty", {"pattern": ""}, "Pattern cannot be empty"),
+ ("whitespace", {"pattern": " "}, "Pattern cannot be empty"),
+ ("too long", {"pattern": "a" * (MAX_PATTERN_LENGTH + 1)}, "cannot be longer"),
+ ("no name", {"name": ""}, "Bot name cannot be empty"),
+ (
+ "lookahead",
+ {"pattern": "Acme(?=Bot)", "matcher": CustomBotMatcher.REGEX},
+ "lookahead",
+ ),
+ (
+ "lookbehind",
+ {"pattern": "(?<=Acme)Bot", "matcher": CustomBotMatcher.REGEX},
+ "lookbehind",
+ ),
+ (
+ "backreference",
+ {"pattern": r"(Acme)\1", "matcher": CustomBotMatcher.REGEX},
+ "backreference",
+ ),
+ (
+ "invalid regex",
+ {"pattern": "Acme(", "matcher": CustomBotMatcher.REGEX},
+ "not a valid regular expression",
+ ),
+ ("unknown category", {"category": "not_a_category"}, "Unknown category"),
+ ]
+ )
+ def test_rejects_unusable_definitions(self, _name: str, overrides: dict, expected_message: str):
+ with pytest.raises(ValueError, match=expected_message):
+ validate_definition(definition(**overrides))
+
+ @parameterized.expand(
+ [
+ ("plain substring", {"pattern": "AcmeBot"}),
+ ("substring with metacharacters", {"pattern": "Acme (bot) v1.0"}),
+ ("anchored regex", {"pattern": "^AcmeBot/[0-9]+$", "matcher": CustomBotMatcher.REGEX}),
+ ("a non-default property", {"key": CustomBotField.FIELD_LIB, "pattern": "posthog-python"}),
+ ]
+ )
+ def test_accepts_usable_definitions(self, _name: str, overrides: dict):
+ validate_definition(definition(**overrides))
+
+ @parameterized.expand(
+ [
+ ("single address", "192.0.2.7"),
+ ("v4 range", "192.0.2.0/24"),
+ ("v6 range", "2001:db8::/32"),
+ ("host bits set", "192.0.2.7/24"),
+ ]
+ )
+ def test_accepts_usable_ip_ranges(self, _name: str, pattern: str):
+ validate_definition(cidr_definition(pattern=pattern))
+
+ @parameterized.expand(
+ [
+ ("not an address", "not-an-ip"),
+ ("prefix too long", "192.0.2.0/33"),
+ ("empty", " "),
+ # Python's ip_network keeps a zone identifier that ClickHouse toIPv6 later rejects, so a
+ # saved rule would break every query reading a bot field. Reject it at validation.
+ ("zone-scoped ipv6", "fe80::1%eth0"),
+ ]
+ )
+ def test_rejects_unusable_ip_ranges(self, _name: str, pattern: str):
+ with pytest.raises(ValueError):
+ validate_definition(cidr_definition(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"))
+
+ def test_rejects_a_property_outside_the_supported_set(self):
+ raw = definition().model_dump()
+ raw["key"] = "$some_other_property"
+
+ with pytest.raises(ValueError, match="Cannot match on property"):
+ validate_definition(CustomBotDefinition.model_construct(**raw))
+
+
+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
+ # 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"),
+ ]
+ )
+
+ assert [bot.name for group in groups 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)]
+ )
+
+ assert sum(len(group.definitions) for group in groups) == 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")]
+ )
+
+ assert len(groups) == 1
+ assert isinstance(groups[0], PatternGroup)
+ assert groups[0].patterns == ["(?i)One", "(?i)Two"]
+
+ def test_groups_come_back_in_the_order_their_first_rule_appears(self):
+ # Groups are checked in this order, so it decides which rule names an event that two of
+ # 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"),
+ ]
+ )
+
+ assert [group.key for group in groups] == [
+ CustomBotField.FIELD_HOST.value,
+ CustomBotField.FIELD_IP.value,
+ CustomBotField.FIELD_RAW_USER_AGENT.value,
+ ]
+
+ 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."),
+ ]
+ )
+
+ assert [type(group) for group in groups] == [CidrGroup, PatternGroup]
+
+ def test_category_drives_traffic_type(self):
+ groups = compile_definitions([definition(category="ai_crawler")])
+
+ 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]
+
+ 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")])
+
+ assert patterns == ["(?i)AcmeBot"]
+
+
+class TestPatternsCompile(ClickhouseTestMixin, BaseTest):
+ @parameterized.expand(
+ [
+ # Python's re accepts a huge bounded repeat and a POSIX class it does not know; ClickHouse
+ # rejects both. Without this check they would save fine and then break every query that
+ # reads $virt_is_bot for the project.
+ ("expensive bounded repeat", "a{0,100000}", "too slow"),
+ ("unknown POSIX class", "[[:foo:]]", "not supported"),
+ ]
+ )
+ def test_rejects_patterns_clickhouse_cannot_run(self, _name: str, pattern: str, expected_message: str):
+ with pytest.raises(ValueError, match=expected_message):
+ assert_patterns_compile([pattern])
+
+ def test_accepts_patterns_clickhouse_can_run(self):
+ assert_patterns_compile(["(?i)AcmeBot", "AcmeBot/[0-9]+", "^$"])
+
+
+class TestCategoryCoverage:
+ def test_every_built_in_category_has_a_traffic_type(self):
+ # A category added to BOT_DEFINITIONS without an entry here would silently report "Bot" for
+ # a project's own bots in that category.
+ missing = {bot.category for bot in BOT_DEFINITIONS.values()} - set(TRAFFIC_TYPE_BY_CATEGORY)
+
+ assert missing == set()
diff --git a/products/web_analytics/backend/hogql_queries/traffic_type.py b/products/web_analytics/backend/hogql_queries/traffic_type.py
index 06446905a8bf..bf50d610f913 100644
--- a/products/web_analytics/backend/hogql_queries/traffic_type.py
+++ b/products/web_analytics/backend/hogql_queries/traffic_type.py
@@ -10,9 +10,14 @@ Each helper takes the user agent expression and an optional client IP expression
signal catches crawlers that send real browser user agents from operator-published IP
ranges (e.g. Google's mobile rendering service).
+Pass the query modifiers so the project's own bot definitions are applied too. Callers that
+have no modifiers (tests, ad-hoc expression building) get the built-in definitions only.
+
The legacy __preview_* names still resolve as deprecated aliases.
"""
+from typing import TYPE_CHECKING, Optional
+
from posthog.hogql import ast
from posthog.hogql.functions.traffic_type import (
get_bot_name as _get_bot_name,
@@ -24,6 +29,9 @@ from posthog.hogql.functions.traffic_type import (
from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
+if TYPE_CHECKING:
+ from posthog.schema import HogQLQueryModifiers
+
__all__ = [
"BOT_DEFINITIONS",
"get_traffic_type_expr",
@@ -38,7 +46,11 @@ def _args(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None) -> list[ast.Expr]
return [user_agent_expr] if ip_expr is None else [user_agent_expr, ip_expr]
-def get_traffic_type_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:
+def get_traffic_type_expr(
+ user_agent_expr: ast.Expr,
+ ip_expr: ast.Expr | None = None,
+ modifiers: Optional["HogQLQueryModifiers"] = None,
+) -> ast.Expr:
"""
Classifies user agent (and optionally client IP) into traffic type.
@@ -48,10 +60,18 @@ def get_traffic_type_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None =
- "Automation" - HTTP clients, headless browsers, empty UA
- "Regular" - Default for unmatched user agents
"""
- return _get_traffic_type(node=ast.Call(name="getTrafficType", args=[]), args=_args(user_agent_expr, ip_expr))
+ return _get_traffic_type(
+ node=ast.Call(name="getTrafficType", args=[]),
+ args=_args(user_agent_expr, ip_expr),
+ modifiers=modifiers,
+ )
-def get_traffic_category_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:
+def get_traffic_category_expr(
+ user_agent_expr: ast.Expr,
+ ip_expr: ast.Expr | None = None,
+ modifiers: Optional["HogQLQueryModifiers"] = None,
+) -> ast.Expr:
"""
Returns subcategory expression for more granular classification.
@@ -59,31 +79,57 @@ def get_traffic_category_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | Non
social_crawler, monitoring, http_client, headless_browser, no_user_agent, regular
"""
return _get_traffic_category(
- node=ast.Call(name="getTrafficCategory", args=[]), args=_args(user_agent_expr, ip_expr)
+ node=ast.Call(name="getTrafficCategory", args=[]),
+ args=_args(user_agent_expr, ip_expr),
+ modifiers=modifiers,
)
-def is_bot_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:
+def is_bot_expr(
+ user_agent_expr: ast.Expr,
+ ip_expr: ast.Expr | None = None,
+ modifiers: Optional["HogQLQueryModifiers"] = None,
+) -> ast.Expr:
"""
Returns a boolean expression: true if bot/automation, false for regular traffic.
"""
- return _is_bot(node=ast.Call(name="isLikelyBot", args=[]), args=_args(user_agent_expr, ip_expr))
+ return _is_bot(
+ node=ast.Call(name="isLikelyBot", args=[]),
+ args=_args(user_agent_expr, ip_expr),
+ modifiers=modifiers,
+ )
-def get_bot_type_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:
+def get_bot_type_expr(
+ user_agent_expr: ast.Expr,
+ ip_expr: ast.Expr | None = None,
+ modifiers: Optional["HogQLQueryModifiers"] = None,
+) -> ast.Expr:
"""
Returns the bot category or empty string for regular traffic.
Categories: ai_crawler, ai_search, ai_assistant, search_crawler, seo_crawler,
social_crawler, monitoring, http_client, headless_browser, no_user_agent, "" (regular)
"""
- return _get_bot_type(node=ast.Call(name="getBotType", args=[]), args=_args(user_agent_expr, ip_expr))
+ return _get_bot_type(
+ node=ast.Call(name="getBotType", args=[]),
+ args=_args(user_agent_expr, ip_expr),
+ modifiers=modifiers,
+ )
-def get_bot_name_expr(user_agent_expr: ast.Expr, ip_expr: ast.Expr | None = None) -> ast.Expr:
+def get_bot_name_expr(
+ user_agent_expr: ast.Expr,
+ ip_expr: ast.Expr | None = None,
+ modifiers: Optional["HogQLQueryModifiers"] = None,
+) -> ast.Expr:
"""
Returns the bot name or empty string for regular traffic.
Examples: "Googlebot", "ChatGPT", "Claude", "curl", ""
"""
- return _get_bot_name(node=ast.Call(name="getBotName", args=[]), args=_args(user_agent_expr, ip_expr))
+ return _get_bot_name(
+ node=ast.Call(name="getBotName", args=[]),
+ args=_args(user_agent_expr, ip_expr),
+ modifiers=modifiers,
+ )
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
index 2048784aa014..b4e12d83f794 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
@@ -746,6 +746,7 @@ WHERE and(
return get_traffic_type_expr(
user_agent_expr or ast.Field(chain=["events", "properties", "$raw_user_agent"]),
ip_expr or ast.Field(chain=["events", "properties", "$ip"]),
+ modifiers=self.modifiers,
)
def _get_traffic_category_expr(
@@ -754,6 +755,7 @@ WHERE and(
return get_traffic_category_expr(
user_agent_expr or ast.Field(chain=["events", "properties", "$raw_user_agent"]),
ip_expr or ast.Field(chain=["events", "properties", "$ip"]),
+ modifiers=self.modifiers,
)
def get_cache_key(self) -> str:
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d29b7ef9d45a..3d0f04210942 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -785,6 +785,40 @@ export namespace Schemas {
UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',
} as const;
+ export type CustomBotField = typeof CustomBotField[keyof typeof CustomBotField];
+
+
+ export const CustomBotField = {
+ RawUserAgent: '$raw_user_agent',
+ Ip: '$ip',
+ Lib: '$lib',
+ Host: '$host',
+ Pathname: '$pathname',
+ CurrentUrl: '$current_url',
+ } as const;
+
+ export type CustomBotMatcher = typeof CustomBotMatcher[keyof typeof CustomBotMatcher];
+
+
+ export const CustomBotMatcher = {
+ Contains: 'contains',
+ Regex: 'regex',
+ Cidr: 'cidr',
+ } as const;
+
+ export interface CustomBotDefinition {
+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */
+ category?: string | null;
+ id: string;
+ /** The event property this rule 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];
@@ -949,6 +983,7 @@ export namespace Schemas {
bounceRateDurationSeconds?: number | null;
bounceRatePageViewMode?: BounceRatePageViewMode | null;
convertToProjectTimezone?: boolean | null;
+ customBotDefinitions?: CustomBotDefinition[] | null;
customChannelTypeRules?: CustomChannelRule[] | null;
dataWarehouseEventsModifiers?: DataWarehouseEventsModifier[] | null;
debug?: boolean | null;