repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
posthog
products/cdp/backend/admin/plugin_attachment_inline.py
.py
import json from django.contrib import admin from django.db.models import Model from django.http import HttpRequest from django.utils.html import format_html from products.cdp.backend.models.plugin import PluginAttachment ATTACHMENT_PREVIEW_SIZE_LIMIT_BYTES = 1024 * 1024 class PluginAttachmentInline(admin.StackedI...
49
1,830
posthog
products/cdp/backend/admin/plugin_config_admin.py
.py
from django.contrib import admin from django.utils.html import format_html from products.cdp.backend.admin.plugin_attachment_inline import PluginAttachmentInline from products.cdp.backend.models.plugin import PluginConfig @admin.register(PluginConfig) class PluginConfigAdmin(admin.ModelAdmin): list_select_relate...
66
1,956
posthog
products/cdp/backend/admin/hog_function_admin.py
.py
from datetime import timedelta from io import StringIO from django import forms from django.contrib import admin, messages from django.core.management import call_command from django.shortcuts import render from django.urls import path, reverse from django.utils.html import format_html from posthog.management.command...
200
7,533
posthog
products/cdp/backend/admin/plugin_admin.py
.py
from django.contrib import admin from django.utils.html import format_html from products.cdp.backend.models.plugin import Plugin @admin.register(Plugin) class PluginAdmin(admin.ModelAdmin): list_display = ("id", "name", "organization_id", "is_global") list_display_links = ("id", "name") list_filter = ("p...
69
1,979
posthog
products/web_analytics/dags/web_preaggregated_asset_checks.py
.py
import time from datetime import UTC, datetime, timedelta from typing import Any, Optional, cast import chdb import structlog from dagster import AssetCheckExecutionContext, AssetCheckResult, AssetCheckSeverity, Field, MetadataValue, asset_check from posthog.schema import DateRange, HogQLQueryModifiers, WebOverviewIt...
575
23,952
posthog
products/web_analytics/dags/eager_web_analytics_precompute.py
.py
"""Eager web analytics precompute — hourly baseline warming. .. deprecated:: Being wound down — prefer the lazy-on-read path, do not extend this matrix. This warmer only covers a *single* point in query-param space (unfiltered `properties=[]`, `filterTestAccounts=True`, `limit=10`, the fixed `BASELINE...
712
36,065
posthog
products/web_analytics/dags/cache_warming.py
.py
import os import re import gzip import json import time import zlib import random import threading import statistics from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait from datetime import datetime, timedelta from typing import TYPE_CHECKING, Optional from django.core.exceptions import ObjectDoes...
1,233
64,399
posthog
products/web_analytics/dags/web_analytics_watchdog.py
.py
import os from datetime import UTC, datetime, timedelta import dagster import pydantic from dagster import AssetExecutionContext, MetadataValue from posthog.clickhouse.client import sync_execute from posthog.clickhouse.query_tagging import tags_context from posthog.dags.common import JobOwners, dagster_tags from pro...
325
13,088
posthog
products/web_analytics/dags/clear_oom_pins.py
.py
"""Operator job to list or clear web-analytics precompute OOM pins. A pinned team's precompute inserts are capped to 1-day windows (set reactively after a MEMORY_LIMIT_EXCEEDED insert, self-expiring in 14 days). Clear a pin when the underlying pressure is gone, e.g. after a cluster upscale or a stored-row cap reductio...
64
2,353
posthog
products/web_analytics/dags/web_preaggregated_team_selection.py
.py
import os from typing import Any, cast import dagster from clickhouse_driver import Client from posthog.clickhouse.client import sync_execute from posthog.clickhouse.cluster import ClickhouseCluster from posthog.dags.common import JobOwners, settings_with_log_comment from posthog.models.team.team import Team from pos...
237
9,020
posthog
products/web_analytics/dags/web_pre_aggregated_accuracy.py
.py
from datetime import datetime, timedelta import dagster import pydantic from dagster import AssetExecutionContext, MetadataValue, WeeklyPartitionsDefinition, asset from posthog.clickhouse.client import sync_execute from posthog.clickhouse.query_tagging import tags_context from posthog.dags.common import JobOwners, da...
211
8,757
posthog
products/web_analytics/dags/web_preaggregated.py
.py
import os from collections.abc import Callable from datetime import UTC, datetime, timedelta from functools import wraps from typing import Union import dagster from dagster import BackfillPolicy, DailyPartitionsDefinition from posthog.schema import ProductKey from posthog.clickhouse import query_tagging from postho...
330
12,298
posthog
products/web_analytics/dags/cache_favicons.py
.py
from typing import cast from urllib.parse import urlparse from django.conf import settings import httpx import dagster from dagster_aws.s3 import S3Resource from posthog.clickhouse.client import sync_execute from posthog.dags.common import JobOwners from posthog.models.team import Team def get_last_cached_domains(...
243
9,751
posthog
products/web_analytics/dags/web_preaggregated_utils.py
.py
import os from collections.abc import Callable from datetime import datetime, timedelta from functools import partial from typing import Optional import dagster from dagster import Array, Backoff, DagsterRunStatus, Field, Jitter, RetryPolicy, RunsFilter, SkipReason from posthog.clickhouse.client.connection import Nod...
208
8,553
posthog
products/web_analytics/dags/web_dimensional_precompute.py
.py
"""Scheduled population of the fixed-dimension web precompute tables. This job drives the precomputation framework: for each selected team it calls `ensure_*_dimensional_precomputed` over a rolling 90-day window, and the framework splits that into daily jobs, tracks them in Postgres (`PreaggregationJob`) and only (re)...
190
8,525
posthog
products/web_analytics/dags/tests/test_web_preaggregated_asset_checks.py
.py
from products.web_analytics.dags.web_preaggregated_asset_checks import create_accuracy_check_result def test_create_accuracy_check_result_handles_integer_values_for_dagster(): """ Test that create_accuracy_check_result properly handles integer values that would cause Dagster's MetadataValue.float() to fai...
43
1,708
posthog
products/web_analytics/dags/tests/test_clear_oom_pins.py
.py
import dagster from posthog import redis from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import ( _oom_pin_key, is_team_oom_pinned, pin_team_oom, ) from products.web_analytics.dags.clear_oom_pins import web_analytics_clear_precompute_oom_pins_job TEAMS = (901901, 901902) de...
51
1,575
posthog
products/web_analytics/dags/tests/test_cache_warming.py
.py
import gzip import json import threading from types import SimpleNamespace from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from django.utils.dateparse import parse_datetime import dagster from parameterized import parameterized from posthog.clickhouse.query_tagging import Feature, ...
1,094
51,034
posthog
products/web_analytics/dags/tests/test_cache_favicons.py
.py
import pytest from unittest.mock import Mock, patch from products.web_analytics.dags.cache_favicons import ( get_authorized_domains, get_last_cached_domains, upload_if_missing, ) class TestGetLastCachedDomains: @pytest.mark.parametrize( "asset_key", ["cache_favicons", "cache_authorize...
262
11,001
posthog
products/web_analytics/dags/tests/test_web_dimensional_precompute.py
.py
import os from datetime import UTC, datetime from posthog.test.base import APIBaseTest from unittest.mock import patch import dagster from posthog.models import Organization, Team from products.web_analytics.dags.web_dimensional_precompute import ( DEFAULT_ROLLOUT_TEAM_IDS, PRECOMPUTE_CHUNK_DAYS, PRECOM...
155
7,567
posthog
products/web_analytics/dags/tests/test_web_preaggregated_team_selection.py
.py
import os import pytest from posthog.test.base import APIBaseTest from unittest.mock import Mock, patch import dagster from posthog.models.team.team import Team from posthog.models.web_preaggregated.team_selection import ( DEFAULT_ENABLED_TEAM_IDS, DEFAULT_WEEKLY_PAGEVIEWS_THRESHOLD, get_teams_by_weekly_...
682
27,760
posthog
products/web_analytics/dags/tests/test_eager_web_analytics_precompute.py
.py
from collections.abc import MutableMapping from contextlib import contextmanager from datetime import timedelta from typing import Any from posthog.test.base import APIBaseTest from unittest.mock import Mock, patch from django.test import override_settings from django.utils import timezone import dagster from parame...
460
22,442
posthog
products/web_analytics/dags/tests/test_web_preaggregated_utils.py
.py
import inspect from unittest.mock import Mock from dagster import DagsterInstance, DagsterRunStatus, RunsFilter, SkipReason, job, op, schedule import products.web_analytics.dags.web_preaggregated as wp from products.web_analytics.dags.web_preaggregated import ( web_pre_aggregate_current_day_schedule, web_pre...
193
7,451
posthog
products/web_analytics/dags/tests/test_web_analytics_watchdog.py
.py
import datetime from typing import Any import pytest from freezegun import freeze_time from unittest.mock import Mock, patch import dagster from products.web_analytics.dags.web_analytics_watchdog import ( build_remediation_configs, check_partition_accuracy, web_analytics_watchdog, web_analytics_watch...
340
13,196
posthog
products/web_analytics/scripts/refresh_bot_ip_ranges.py
.py
#!/usr/bin/env python3 """Refresh the bot IP ranges vendored in bot_ip_networks.py. Crawler operators publish the IP ranges their bots run from as machine-readable JSON (all use Google's `prefixes` format). Some of that traffic (notably Google's mobile rendering service and ChatGPT's browsing) uses real browser user a...
107
5,250
posthog
products/web_analytics/backend/apps.py
.py
from django.apps import AppConfig class WebAnalyticsConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "products.web_analytics.backend" label = "web_analytics"
8
202
posthog
products/web_analytics/backend/serializers.py
.py
from rest_framework import serializers class WoWChangeSerializer(serializers.Serializer): percent = serializers.IntegerField(help_text="Absolute percentage change, rounded to nearest integer.") direction = serializers.ChoiceField( choices=["Up", "Down"], help_text="Direction of the change relative to ...
94
5,472
posthog
products/web_analytics/backend/max_tools.py
.py
import json import asyncio import logging from datetime import date from typing import Any, Literal from urllib.parse import urlsplit, urlunsplit from langchain_core.prompts import ChatPromptTemplate from pydantic import BaseModel, Field from posthog.schema import PropertyType, PropertyValuesQuery, WebAnalyticsAssist...
1,034
43,469
posthog
products/web_analytics/backend/routes.py
.py
from posthog.api.routing import RouterRegistry from products.web_analytics.backend.api import WebAnalyticsViewSet from products.web_analytics.backend.api.heatmaps_api import ( HeatmapScreenshotViewSet, HeatmapViewSet, LegacyHeatmapViewSet, SavedHeatmapViewSet, ) from products.web_analytics.backend.api....
43
1,786
posthog
products/web_analytics/backend/weekly_digest.py
.py
from django.conf import settings import structlog from posthog.schema import ( CompareFilter, DateRange, ProductKey, WebAnalyticsOrderByDirection, WebAnalyticsOrderByFields, WebGoalsQuery, WebOverviewQuery, WebStatsBreakdown, WebStatsTableQuery, ) from posthog.clickhouse.query_tag...
294
9,988
posthog
products/web_analytics/backend/heatmap_screenshot_grounding.py
.py
"""Ground heatmap hot-spot coordinates against an actual page screenshot. A heatmap report says "4 rage clicks at x≈0.83, y≈600px" — meaningless without seeing what sits there. This module reuses a cached heatmap *screenshot* (a rendered page image), draws numbered markers at the hot coordinates, and asks a vision mod...
223
8,870
posthog
products/web_analytics/backend/prompts.py
.py
FILTER_EXAMPLES_PROMPT = """ <examples_and_rules> ## Examples and Rules 1. Combining Filters Properties is always a list of filters that will be applied with an AND operator. There's no OR operator for different keys. You can let the request know that you don't support OR filters. However, inside the same type of key...
238
9,224
posthog
products/web_analytics/backend/recap.py
.py
from datetime import date, timedelta from urllib.parse import urlencode from zoneinfo import ZoneInfo from django.conf import settings from django.utils import timezone from posthog.hogql_queries.query_runner import ExecutionMode from posthog.models import Team from posthog.models.user import User from products.web_...
255
9,201
posthog
products/web_analytics/backend/heatmap_preflight.py
.py
import re import time from dataclasses import dataclass from hashlib import sha256 from typing import Literal from urllib.parse import SplitResult, urljoin, urlsplit from django.conf import settings from django.core.cache import cache import requests import structlog from posthog.security.pinned_requests import SSRF...
216
9,139
posthog
products/web_analytics/backend/management/commands/backfill_web_analytics_achievements.py
.py
from typing import cast from django.core.management.base import BaseCommand, CommandParser from products.web_analytics.backend.achievements.backfill import backfill_team class Command(BaseCommand): help = ( "Seed cumulative Web analytics achievement progress for a team from historical data. " "D...
21
835
posthog
products/web_analytics/backend/management/commands/suggest_path_cleaning_rules.py
.py
"""Generate AI-suggested path-cleaning rules for web-analytics teams and print them for review. Suggests only — applying rewrites historical numbers in every cleaned chart, so it stays a human decision. `--apply` merges the generated rules into a team's existing `path_cleaning_filters` (never overwriting) and is opt-i...
161
6,926
posthog
products/web_analytics/backend/tasks/__init__.py
.py
from . import heatmap_screenshot, lazy_precompute_revalidation __all__ = ["heatmap_screenshot", "lazy_precompute_revalidation"]
4
129
posthog
products/web_analytics/backend/tasks/heatmap_screenshot.py
.py
import re import time from datetime import timedelta from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit from django.conf import settings from django.db import transaction from django.utils import timezone import requests import structlog import posthoganalytics from celery import Task, shared_task fr...
647
26,334
posthog
products/web_analytics/backend/tasks/lazy_precompute_revalidation.py
.py
"""Background revalidation for stale-served lazy precompute reads. The revalidate half of the stale-while-revalidate semantics (RFC 5861): when a user-facing read is served from expired-within-grace jobs, the read path enqueues this task (see `web_lazy_precompute_common.enqueue_stale_revalidation`) to re-run the query...
105
4,641
posthog
products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
.py
from contextlib import contextmanager from datetime import timedelta from posthog.test.base import APIBaseTest from unittest.mock import MagicMock, patch from django.test import SimpleTestCase, override_settings from django.utils import timezone from celery.exceptions import SoftTimeLimitExceeded from parameterized ...
623
29,722
posthog
products/web_analytics/backend/tasks/test/test_lazy_precompute_revalidation.py
.py
from posthog.test.base import BaseTest from unittest import mock from posthog.schema import DateRange, WebOverviewQuery from posthog.clickhouse.query_tagging import get_query_tag_value, reset_query_tags from posthog.hogql_queries.query_runner import ExecutionMode from products.web_analytics.backend.hogql_queries.web...
59
2,835
posthog
products/web_analytics/backend/temporal/__init__.py
.py
from products.web_analytics.backend.temporal.digest_notification import ( ACTIVITIES as DIGEST_NOTIFICATION_ACTIVITIES, WORKFLOWS as DIGEST_NOTIFICATION_WORKFLOWS, ) from products.web_analytics.backend.temporal.weekly_digest import ( ACTIVITIES as WEEKLY_DIGEST_ACTIVITIES, WORKFLOWS as WEEKLY_DIGEST_WOR...
12
470
posthog
products/web_analytics/backend/temporal/digest_common.py
.py
from datetime import timedelta from django.db.models import QuerySet from temporalio import common from posthog.models.organization import Organization ACTIVITY_RETRY_POLICY = common.RetryPolicy( maximum_attempts=3, initial_interval=timedelta(seconds=30), backoff_coefficient=2.0, maximum_interval=ti...
33
1,124
posthog
products/web_analytics/backend/temporal/weekly_digest/types.py
.py
import dataclasses from enum import StrEnum class DigestOutcome(StrEnum): """Outcome of attempting to send a single digest email to a single user.""" SENT = "sent" DRY_RUN = "dry_run" SKIPPED_OPTOUT = "skipped_optout" SKIPPED_NO_DATA = "skipped_no_data" FAILED = "failed" @dataclasses.datacl...
121
3,211
posthog
products/web_analytics/backend/temporal/weekly_digest/workflows.py
.py
import json import asyncio import dataclasses from datetime import timedelta from temporalio import common, workflow from temporalio.exceptions import ApplicationError from posthog.temporal.common.base import PostHogWorkflow with workflow.unsafe.imports_passed_through(): from products.web_analytics.backend.tempo...
153
5,714
posthog
products/web_analytics/backend/temporal/weekly_digest/__init__.py
.py
from products.web_analytics.backend.temporal.weekly_digest.activities import ( get_org_batch_page, push_wa_digest_metrics_activity, run_wa_digest_batch, send_test_wa_digest, ) from products.web_analytics.backend.temporal.weekly_digest.workflows import ( WAWeeklyDigestTestWorkflow, WAWeeklyDigest...
19
526
posthog
products/web_analytics/backend/temporal/weekly_digest/activities.py
.py
import time from datetime import datetime, timedelta from itertools import batched from django.conf import settings from django.db import close_old_connections from django.db.models import Exists, OuterRef, QuerySet from django.utils import timezone import structlog import posthoganalytics from prometheus_client impo...
499
18,542
posthog
products/web_analytics/backend/temporal/digest_notification/types.py
.py
import dataclasses from enum import StrEnum class NotificationDigestOutcome(StrEnum): SENT = "sent" CONTROL = "control" DRY_RUN = "dry_run" SKIPPED_NO_DATA = "skipped_no_data" FAILED = "failed" @dataclasses.dataclass class WADigestNotificationInput: dry_run: bool = False batch_size: int ...
98
2,381
posthog
products/web_analytics/backend/temporal/digest_notification/workflows.py
.py
import json import asyncio import dataclasses from datetime import timedelta from temporalio import common, workflow from temporalio.exceptions import ApplicationError from posthog.temporal.common.base import PostHogWorkflow with workflow.unsafe.imports_passed_through(): from products.web_analytics.backend.tempo...
138
5,306
posthog
products/web_analytics/backend/temporal/digest_notification/__init__.py
.py
from products.web_analytics.backend.temporal.digest_notification.activities import ( get_org_batch_page, run_wa_digest_notification_batch, send_test_wa_digest_notification, ) from products.web_analytics.backend.temporal.digest_notification.workflows import ( WADigestNotificationTestWorkflow, WADiges...
17
540
posthog
products/web_analytics/backend/temporal/digest_notification/activities.py
.py
import time from itertools import batched from typing import cast from uuid import UUID from django.db import close_old_connections import structlog import posthoganalytics from temporalio import activity from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level from posthog.clickhouse.que...
518
18,569
posthog
products/web_analytics/backend/temporal/health_checks/scroll_depth.py
.py
from posthog.dags.common.owners import JobOwners from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.detectors import CLICKHOUSE_BATCH_EXECUTION_POLICY from posthog.temporal.health_checks.framework import ( _SEVERITY_WEIGHT, AlertContent, HealthCheck, Remediation, ...
92
3,867
posthog
products/web_analytics/backend/temporal/health_checks/no_pageleave_events.py
.py
from posthog.clickhouse.query_tagging import Product from posthog.dags.common.owners import JobOwners from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.detectors import CLICKHOUSE_BATCH_EXECUTION_POLICY from posthog.temporal.health_checks.framework import ( _SEVERITY_WEIGHT, ...
97
4,081
posthog
products/web_analytics/backend/temporal/health_checks/path_cleaning_suggestions.py
.py
from django.conf import settings import structlog from posthog.clickhouse.query_tagging import Product from posthog.dags.common.owners import JobOwners from posthog.models import Team from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.detectors import HealthExecutionPolicy from po...
123
6,041
posthog
products/web_analytics/backend/temporal/health_checks/authorized_urls.py
.py
from django.db.models import Q from posthog.dags.common.owners import JobOwners from posthog.models.health_issue import HealthIssue from posthog.models.team import Team from posthog.temporal.health_checks.detectors import DEFAULT_EXECUTION_POLICY from posthog.temporal.health_checks.framework import ( _SEVERITY_WEI...
90
4,174
posthog
products/web_analytics/backend/temporal/health_checks/no_live_events.py
.py
from posthog.clickhouse.query_tagging import Product from posthog.dags.common.owners import JobOwners from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.detectors import CLICKHOUSE_BATCH_EXECUTION_POLICY from posthog.temporal.health_checks.framework import ( _SEVERITY_WEIGHT, ...
98
4,318
posthog
products/web_analytics/backend/temporal/health_checks/reverse_proxy.py
.py
from posthog.dags.common.owners import JobOwners from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.detectors import CLICKHOUSE_BATCH_EXECUTION_POLICY from posthog.temporal.health_checks.framework import ( _SEVERITY_WEIGHT, AlertContent, HealthCheck, Remediation, ...
95
4,143
posthog
products/web_analytics/backend/temporal/health_checks/partial_proxy.py
.py
import re from collections import defaultdict from posthog.dags.common.owners import JobOwners from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.detectors import CLICKHOUSE_BATCH_EXECUTION_POLICY from posthog.temporal.health_checks.framework import ( _SEVERITY_WEIGHT, Aler...
150
6,226
posthog
products/web_analytics/backend/temporal/health_checks/web_vitals.py
.py
from posthog.dags.common.owners import JobOwners from posthog.models.health_issue import HealthIssue from posthog.temporal.health_checks.detectors import CLICKHOUSE_BATCH_EXECUTION_POLICY from posthog.temporal.health_checks.framework import ( _SEVERITY_WEIGHT, AlertContent, HealthCheck, Remediation, ...
94
3,830
posthog
products/web_analytics/backend/achievements/definitions.py
.py
from dataclasses import dataclass, field from enum import StrEnum class AchievementScope(StrEnum): USER = "user" TEAM = "team" class TrackKey(StrEnum): STREAK = "streak" LOYALTY = "loyalty" EXPLORER = "explorer" DETECTIVE = "detective" CONVERSIONS = "conversions" TRAFFIC = "traffic" ...
199
6,568
posthog
products/web_analytics/backend/achievements/__init__.py
.py
from products.web_analytics.backend.achievements.definitions import ( TRACKS, AchievementScope, Stage, TrackDefinition, TrackKey, serialize_definitions, ) __all__ = [ "TRACKS", "AchievementScope", "Stage", "TrackDefinition", "TrackKey", "serialize_definitions", ]
18
313
posthog
products/web_analytics/backend/achievements/evaluators.py
.py
from collections.abc import Callable from dataclasses import dataclass from datetime import date, timedelta from posthog.hogql import ast from posthog.hogql.parser import parse_select from posthog.hogql.property import action_to_expr from posthog.hogql.query import execute_hogql_query from posthog.models.team.team im...
170
6,101
posthog
products/web_analytics/backend/achievements/backfill.py
.py
from django.utils import timezone import structlog from posthog.models import OrganizationMembership from posthog.models.team.team import Team from posthog.models.user import User from products.web_analytics.backend.achievements.definitions import TRACKS, AchievementScope, TrackDefinition from products.web_analytics...
72
2,939
posthog
products/web_analytics/backend/achievements/tasks.py
.py
from datetime import date, datetime, timedelta from functools import partial from uuid import UUID from django.core.cache import cache from django.db import transaction from django.utils import timezone import structlog import posthoganalytics from celery import shared_task from posthog.exceptions_capture import cap...
284
11,156
posthog
products/web_analytics/backend/api/web_analytics_path_cleaning_suggestions.py
.py
from typing import Any from django.db import transaction import posthoganalytics from drf_spectacular.utils import extend_schema from rest_framework import serializers, viewsets from rest_framework.decorators import action from rest_framework.exceptions import NotFound, PermissionDenied from rest_framework.request im...
193
10,261
posthog
products/web_analytics/backend/api/heatmaps_api.py
.py
from datetime import date, datetime, timedelta from json import JSONDecodeError, loads from typing import Any, List, Literal, cast, get_args # noqa: UP035 from django.core.exceptions import FieldError from django.db import transaction from django.db.models import Q from django.http import HttpResponse from django.uti...
1,486
69,565
posthog
products/web_analytics/backend/api/web_analytics_filter_preset.py
.py
from typing import Any, Optional from django.db.models import Q, QuerySet from django.utils.timezone import now from django_filters.rest_framework import DjangoFilterBackend from rest_framework import serializers, viewsets from posthog.api.forbid_destroy_model import ForbidDestroyModel from posthog.api.routing impor...
171
5,831
posthog
products/web_analytics/backend/api/__init__.py
.py
from .api import WebAnalyticsViewSet __all__ = ["WebAnalyticsViewSet"]
4
72
posthog
products/web_analytics/backend/api/web_analytics_achievements.py
.py
from typing import cast from django.db import transaction from django.db.models import F, Q from drf_spectacular.utils import extend_schema from rest_framework import serializers, viewsets from rest_framework.decorators import action from rest_framework.request import Request from rest_framework.response import Respo...
350
16,703
posthog
products/web_analytics/backend/api/heatmaps_utils.py
.py
from datetime import timedelta import posthoganalytics DEFAULT_TARGET_WIDTHS = [320, 375, 425, 768, 1024, 1440, 1920] # Each width is one screenshot render (one Browserless session on the cloud path), so cap how many a # single heatmap can fan out to. MAX_TARGET_WIDTHS = 16 PREWARM_PREVIEW_WIDTH = 1024 PREWARM_TTL =...
31
1,026
posthog
products/web_analytics/backend/api/api.py
.py
from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema from rest_framework import serializers, viewsets from rest_framework.decorators import action from rest_framework.request import Request from rest_framework.response import Response from po...
127
5,501
posthog
products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
.py
import time from datetime import UTC, datetime from typing import TYPE_CHECKING, Optional import structlog from prometheus_client import Counter from posthog.schema import HogQLQueryModifiers from posthog.hogql import ast from posthog.hogql.modifiers import create_default_modifiers_for_team from posthog.clickhouse....
449
20,234
posthog
products/web_analytics/backend/hogql_queries/first_pageview_flag.py
.py
from typing import TYPE_CHECKING, Any, Optional import structlog import posthoganalytics from posthog.schema import ProductKey, SessionPropertyFilter, WebStatsBreakdown if TYPE_CHECKING: from posthog.models import Team logger = structlog.get_logger(__name__) FIRST_PAGEVIEW_ATTRIBUTION_FEATURE_FLAG = "web-analy...
131
5,854
posthog
products/web_analytics/backend/hogql_queries/traffic_type.py
.py
""" Traffic type classification helper functions for web analytics. These wrap the HogQL classification functions, usable anywhere HogQL runs: - SQL editor: ad-hoc analysis (e.g. SELECT isLikelyBot(properties.$raw_user_agent)) - HogQLQuery / Trends: filter or group by traffic type - Web analytics query runners Each h...
90
3,526
posthog
products/web_analytics/backend/hogql_queries/external_clicks.py
.py
from typing import Literal, cast from posthog.schema import ( CachedWebStatsTableQueryResponse, WebAnalyticsOrderByDirection, WebAnalyticsOrderByFields, WebAnalyticsPreComputeStrategy, WebExternalClicksTableQuery, WebExternalClicksTableQueryResponse, WebStatsTableQueryResponse, ) from post...
138
5,217
posthog
products/web_analytics/backend/hogql_queries/notable_changes.py
.py
import math from typing import Required, TypedDict, Union import structlog from posthog.schema import ( CachedWebNotableChangesQueryResponse, HogQLQueryModifiers, WebAnalyticsPreComputeStrategy, WebNotableChangeItem, WebNotableChangesQuery, WebNotableChangesQueryResponse, ) from posthog.hogql...
313
12,229
posthog
products/web_analytics/backend/hogql_queries/stats_table.py
.py
import math from collections.abc import Callable from dataclasses import dataclass from typing import Literal, Optional, Union, cast from posthog.schema import ( CachedWebStatsTableQueryResponse, EventPropertyFilter, HogQLQueryModifiers, PersonPropertyFilter, WebAnalyticsOrderByDirection, WebAn...
1,086
51,084
posthog
products/web_analytics/backend/hogql_queries/first_pageview_attribution.py
.py
from typing import TYPE_CHECKING, Any, Optional, cast from posthog.schema import HogQLQueryModifiers, PropertyOperator, SessionPropertyFilter, WebStatsBreakdown from posthog.hogql import ast from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_expr from posthog.hogql.parser imp...
307
13,453
posthog
products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
.py
"""Lazy precompute path for the Web Analytics PATHS (page + bounce) tile. Mirrors `web_overview_lazy_precompute.py` and shares its eligibility gate via `web_lazy_precompute_common`. The precomputed table stores one row per (team, job, UTC hour, breakdown_value) where `breakdown_value` is the URL path (optionally prefi...
1,040
48,839
posthog
products/web_analytics/backend/hogql_queries/bot_ip_definitions.py
.py
from dataclasses import dataclass from functools import cache from ipaddress import IPv6Address, collapse_addresses, ip_network from products.web_analytics.backend.hogql_queries.bot_ip_networks import ( AHREFSBOT_NETWORKS, APPLEBOT_NETWORKS, BINGBOT_NETWORKS, GOOGLE_COMMON_CRAWLER_NETWORKS, GOOGLE_...
160
6,048
posthog
products/web_analytics/backend/hogql_queries/stats_table_strategies.py
.py
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING from posthog.hogql import ast from posthog.hogql.parser import parse_expr, parse_select from products.web_analytics.backend.hogql_queries.query_constants.stats_table_queries import ( FIRST_PAGEVIEW_INNER_QUERY...
468
21,345
posthog
products/web_analytics/backend/hogql_queries/web_goals.py
.py
from collections.abc import Iterator, Sequence from typing import Optional, TypeVar from posthog.schema import ( CachedWebGoalsQueryResponse, WebAnalyticsOrderByFields, WebAnalyticsPreComputeStrategy, WebGoalsQuery, WebGoalsQueryResponse, ) from posthog.hogql import ast from posthog.hogql.parser i...
357
14,902
posthog
products/web_analytics/backend/hogql_queries/web_trends_lazy_precompute.py
.py
import time from datetime import UTC, datetime from enum import Enum from typing import TYPE_CHECKING, Any, Optional from django.conf import settings import structlog import posthoganalytics from prometheus_client import Counter from posthog.schema import ( ChartDisplayType, CompareFilter, DateRange, ...
497
20,603
posthog
products/web_analytics/backend/hogql_queries/page_url_search_query_runner.py
.py
from posthog.schema import ( CachedWebPageURLSearchQueryResponse, PageURL, WebAnalyticsPreComputeStrategy, WebPageURLSearchQuery, WebPageURLSearchQueryResponse, ) from posthog.hogql import ast from posthog.hogql.context import HogQLContext from posthog.hogql.query import execute_hogql_query from p...
101
3,755
posthog
products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
.py
"""Shared eligibility gate + helpers for web-analytics lazy precompute paths. Both the web overview lazy precompute and the web stats PATHS lazy precompute share the same rollout/safety gate (org feature flag + per-query opt-out, whole-hour timezone, no conversion goal, no sampling, no v2 UUID sessions, any event/pers...
794
38,027
posthog
products/web_analytics/backend/hogql_queries/web_overview_pre_aggregated.py
.py
from typing import TYPE_CHECKING, cast from posthog.hogql import ast from posthog.hogql.parser import parse_select from posthog.hogql.property import property_to_expr from products.web_analytics.backend.hogql_queries.pre_aggregated.properties import WEB_OVERVIEW_SUPPORTED_PROPERTIES from products.web_analytics.backen...
268
11,530
posthog
products/web_analytics/backend/hogql_queries/web_bots.py
.py
from posthog.schema import ( CachedWebBotsTableQueryResponse, WebBotsBreakdown, WebBotsTableQuery, WebBotsTableQueryResponse, ) from posthog.hogql import ast from posthog.hogql.constants import LimitContext from posthog.hogql.parser import parse_select from posthog.hogql.property import property_to_exp...
113
3,624
posthog
products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
.py
"""Lazy precompute path for the Web Analytics GOALS tile. Mirrors `web_stats_paths_lazy_precompute.py` and shares its eligibility gate via `web_lazy_precompute_common`. The precomputed table stores one row per (team, job, UTC hour, action_id): - `action_id = -1` carries the per-hour denominator: unique persons whose ...
561
23,003
posthog
products/web_analytics/backend/hogql_queries/test_web_analytics_tables_version.py
.py
from posthog.test.base import APIBaseTest from posthog.schema import DateRange, WebOverviewQuery, WebStatsBreakdown, WebStatsTableQuery from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRu...
76
3,921
posthog
products/web_analytics/backend/hogql_queries/bot_definitions.py
.py
from dataclasses import dataclass @dataclass class BotDefinition: name: str # Display name: "Googlebot", "ChatGPT" category: str # Category: "search_crawler", "ai_crawler", "ai_search", "ai_assistant" traffic_type: str # Type: "Bot", "AI Agent", "Automation" operator: str # Operator/company: "Goog...
696
33,252
posthog
products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
.py
"""Shared lazy-precompute building blocks for web analytics query runners. The web overview and web stats table runners both serve eligible queries from on-demand precomputed ClickHouse tables via the `lazy_computation` framework. The pieces that do not depend on which runner is calling — eligibility gating, filter-ex...
455
19,664
posthog
products/web_analytics/backend/hogql_queries/metrics.py
.py
from prometheus_client import Counter, Histogram # We use a Histogram rather than Summary because: # - Histograms expose _sum and _count, enabling server-side average calculations # - Bucket boundaries allow percentile estimation (p50, p95, p99) without client-side aggregation # - Buckets are tuned for ClickHouse quer...
46
1,361
posthog
products/web_analytics/backend/hogql_queries/session_attribution_explorer_query_runner.py
.py
from posthog.schema import ( CachedSessionAttributionExplorerQueryResponse, HogQLFilters, SessionAttributionExplorerQuery, SessionAttributionExplorerQueryResponse, SessionAttributionGroupBy, SessionTableVersion, ) from posthog.hogql import ast from posthog.hogql.constants import LimitContext fr...
161
5,568
posthog
products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py
.py
from posthog.schema import ( CachedWebStatsTableQueryResponse, WebAnalyticsPreComputeStrategy, WebVitalsMetricBand, WebVitalsPathBreakdownQuery, WebVitalsPathBreakdownQueryResponse, WebVitalsPathBreakdownResult, WebVitalsPathBreakdownResultItem, ) from posthog.hogql import ast from posthog....
130
5,084
posthog
products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
.py
import json import time from dataclasses import dataclass from datetime import UTC, datetime from typing import TYPE_CHECKING, Literal, Optional import structlog from prometheus_client import Counter from posthog.schema import ( HogQLQueryModifiers, WebAnalyticsOrderByDirection, WebAnalyticsOrderByFields,...
736
33,275
posthog
products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
.py
import typing from abc import ABC from datetime import datetime, timedelta from math import ceil from time import perf_counter from typing import Optional, Union from zoneinfo import ZoneInfo from django.conf import settings import structlog from prometheus_client import Counter from structlog.contextvars import boun...
795
33,243
posthog
products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py
.py
import time from datetime import ( UTC, datetime, time as dt_time, ) from typing import TYPE_CHECKING, Optional import structlog from prometheus_client import Counter from posthog.schema import ( HogQLQueryModifiers, WebAnalyticsPreComputeStrategy, WebVitalsMetric, WebVitalsMetricBand, ...
439
17,667
posthog
products/web_analytics/backend/hogql_queries/web_overview.py
.py
import math from typing import Optional, Union import structlog from posthog.schema import ( CachedWebOverviewQueryResponse, HogQLQueryModifiers, WebAnalyticsPreComputeStrategy, WebOverviewQuery, WebOverviewQueryResponse, ) from posthog.hogql import ast from posthog.hogql.parser import parse_expr...
624
26,916
posthog
products/web_analytics/backend/hogql_queries/bot_ua_fixtures.py
.py
""" Real-world bot and browser user agent strings for testing and demo data generation. Organized by traffic category. Used by: - posthog/hogql/functions/test/test_traffic_type_real_ua.py (test coverage) - posthog/management/commands/generate_bot_demo_data.py (demo data) """ BOT_USER_AGENTS: dict[str, list[str]] = { ...
308
25,455
posthog
products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py
.py
"""Lazy precompute path for the Web Analytics FRUSTRATION metrics tile. Mirrors `web_stats_paths_lazy_precompute.py` and shares its eligibility gate via `web_lazy_precompute_common`. The precomputed table stores one row per (team, job, UTC hour, breakdown_value) where `breakdown_value` is whatever the strategy's `_cou...
580
25,363