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/alerts/backend/evaluation/test/test_funnels_extractor.py
.py
import pytest from unittest.mock import MagicMock, patch from posthog.schema import AlertConditionType from posthog.api.services.query import ExecutionMode from products.alerts.backend.evaluation.contract import AlertExtractionError from products.alerts.backend.evaluation.funnels import FunnelsExtractor CALC_PATH =...
280
12,885
posthog
products/alerts/backend/evaluation/test/test_hogql_detector.py
.py
import pytest from unittest.mock import MagicMock, patch from posthog.schema import HogQLAlertConfig from posthog.api.services.query import ExecutionMode from posthog.tasks.alerts.detector import _compute_min_samples_for_detector from products.alerts.backend.evaluation.contract import AlertExtractionError from produ...
154
7,359
posthog
products/alerts/backend/evaluation/test/test_contract.py
.py
import pytest from posthog.schema import AlertCondition, AlertConditionType from products.alerts.backend.evaluation.contract import lookback_intervals_for @pytest.mark.parametrize( "condition_type,expected_intervals", [ (AlertConditionType.ABSOLUTE_VALUE, 2), (AlertConditionType.RELATIVE_INC...
18
553
posthog
products/alerts/backend/evaluation/test/test_comparator.py
.py
import pytest from posthog.schema import ( AlertCondition, AlertConditionType, InsightsThresholdBounds, InsightThreshold, InsightThresholdType, IntervalType, ) from products.alerts.backend.evaluation.comparator import evaluate_threshold from products.alerts.backend.evaluation.contract import C...
237
10,351
posthog
products/alerts/backend/evaluation/test/test_formatting.py
.py
import pytest from posthog.schema import AggregationAxisFormat, TrendsFilter from products.alerts.backend.evaluation.formatting import format_aggregation_value, make_trends_value_formatter A = AggregationAxisFormat @pytest.mark.parametrize( "value,kwargs,expected", [ # numeric: thousands separators...
63
3,136
posthog
products/alerts/backend/evaluation/test/test_hogql_extractor.py
.py
from decimal import Decimal import pytest from unittest.mock import MagicMock, patch from posthog.schema import ( AlertCondition, AlertConditionType, InsightsThresholdBounds, InsightThreshold, InsightThresholdType, ) from posthog.api.services.query import ExecutionMode from products.alerts.backe...
369
15,688
posthog
products/alerts/backend/evaluation/test/test_check_ongoing_default.py
.py
from parameterized import parameterized from posthog.schema import AlertCalculationInterval from products.alerts.backend.evaluation.validation import should_default_check_ongoing_interval TRENDS = "TrendsAlertConfig" FUNNELS = "FunnelsAlertConfig" def _trends_query(interval="day", non_time_series=False): query...
102
3,888
posthog
products/alerts/backend/api/alert.py
.py
import uuid from typing import Annotated, Any, cast from zoneinfo import ZoneInfo from django.db import transaction from django.db.models import OuterRef, Prefetch, Q, QuerySet, Subquery import posthoganalytics from drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schema, extend_schema_view from py...
1,365
60,866
posthog
products/alerts/backend/api/alert_schedule_restriction.py
.py
"""Pydantic OpenAPI types for alert quiet hours (schedule_restriction JSONField).""" from __future__ import annotations from pydantic import BaseModel, ConfigDict, Field class AlertScheduleRestrictionWindow(BaseModel): model_config = ConfigDict(extra="forbid") start: str = Field( ..., descr...
37
1,157
posthog
products/alerts/backend/api/test/test_alert.py
.py
from copy import deepcopy from datetime import UTC, datetime, timedelta from typing import Any from freezegun import freeze_time from posthog.test.base import APIBaseTest, QueryMatchingTest from unittest import mock from django.core.cache import cache from parameterized import parameterized from rest_framework impor...
2,419
108,910
posthog
products/alerts/backend/facade/api.py
.py
import uuid from collections.abc import Collection from datetime import datetime, timedelta from typing import Literal from zoneinfo import ZoneInfo from django.db import transaction from django.utils import timezone import structlog from posthog.models.activity_logging.model_activity import ActingUserContext from p...
178
8,149
posthog
products/alerts/backend/test/test_destinations.py
.py
from posthog.test.base import APIBaseTest from unittest.mock import MagicMock, patch from parameterized import parameterized from rest_framework.exceptions import ValidationError from products.alerts.backend.destinations import ( AlertDelivery, alert_internal_event_delivered, list_active_alert_destination...
300
12,989
posthog
products/alerts/backend/test/test_email_notifications.py
.py
from unittest.mock import MagicMock, call, patch from django.template.loader import render_to_string from products.alerts.backend.email_notifications import send_alert_email @patch("products.alerts.backend.email_notifications.EmailMessage") def test_send_alert_email_delivers_to_every_recipient(MockEmailMessage: Mag...
89
3,301
posthog
products/alerts/backend/test/test_grid_scheduling.py
.py
import random from datetime import UTC, datetime, timedelta from uuid import UUID import pytest from unittest import TestCase from hypothesis import ( given, settings, strategies as st, ) from parameterized import parameterized from products.alerts.backend.scheduling import ( DEFAULT_SCHEDULE_INTERVA...
465
21,833
posthog
products/alerts/backend/test/test_scheduling.py
.py
from datetime import UTC, datetime from typing import Any import pytest from parameterized import parameterized from products.alerts.backend.scheduling import ( BlockedWindow, CalendarInterval, is_weekend, next_calendar_check_time, parse_blocked_windows_tuples, scan_next_unblocked_utc, va...
270
11,403
posthog
products/alerts/backend/test/test_state_machine.py
.py
from datetime import UTC, datetime, timedelta from parameterized import parameterized from products.alerts.backend.state_machine import ( LOGS_ALERT_POLICY, AlertCheckOutcome, AlertPolicy, AlertSnapshot, AlertState, CheckInput, NotificationAction, evaluate_alert_check, ) NOW = datetim...
289
10,595
posthog
products/alerts/backend/test/test_insight_alert_state_machine.py
.py
from datetime import UTC, datetime from types import SimpleNamespace from typing import cast from posthog.schema_enums import AlertState as InsightAlertState from products.alerts.backend.insight_alert_state_machine import ( apply_disable, apply_enable, apply_snooze, apply_threshold_change, apply_u...
84
3,178
posthog
products/alerts/backend/test/test_delivery_slo.py
.py
from unittest.mock import MagicMock, patch from posthog.slo.types import SloOperation, SloOutcome from products.alerts.backend.delivery_slo import alert_delivery_slo @patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="EU") @patch("posthog.slo.context.emit_slo_completed") @patch("posthog...
38
1,377
posthog
products/alerts/backend/test/test_destination_configs.py
.py
from products.alerts.backend.destination_configs import AlertDestinationAction, EventKindSpec, slack_blocks, teams_text DEFAULT_SPEC = EventKindSpec( event_id="$insight_alert_firing", display_kind="firing", header="Insight alert firing", details=(("Threshold", "30"),), primary_action_url="https://e...
57
2,460
posthog
products/alerts/backend/models/alert.py
.py
from __future__ import annotations from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING from django.core.exceptions import ValidationError from django.db import models if TYPE_CHECKING: from posthog.event_usage import AnalyticsProps from posthog.models.organization import Organizati...
496
22,442
posthog
products/alerts/backend/models/__init__.py
.py
from .alert import Alert, AlertCheck, AlertConfiguration, AlertSubscription, Threshold __all__ = [ "Alert", "AlertCheck", "AlertConfiguration", "AlertSubscription", "Threshold", ]
10
201
posthog
posthog/web_memory_probe.py
.py
import gc import os import ctypes import signal import logging from types import FrameType import structlog logger = logging.getLogger(__name__) PROBE_ENABLED_ENV = "WEB_MEMORY_PROBE_ENABLED" # glibc mallinfo2() layout β€” all size_t (see `man mallinfo2`). mallinfo2 (glibc >= 2.33) # supersedes mallinfo(), whose int ...
161
6,753
posthog
posthog/middleware.py
.py
import os import re import json import time import uuid import posixpath from collections.abc import Callable from contextlib import suppress from datetime import UTC, datetime, timedelta from ipaddress import ip_address, ip_network from typing import Optional, cast from urllib.parse import urlencode from django.conf ...
1,544
68,206
posthog
posthog/types.py
.py
from typing import Union from posthog.schema import ( AccountCustomPropertyFilter, ActionsNode, CohortPropertyFilter, DataWarehouseNode, DataWarehousePersonPropertyFilter, DataWarehousePropertyFilter, ElementPropertyFilter, EmptyPropertyFilter, ErrorTrackingIssueFilter, EventMet...
102
2,921
posthog
posthog/database_healthcheck.py
.py
import time from typing import Optional from django.conf import settings from django.db import connections import structlog DATABASE_FOR_FLAG_MATCHING = ( "default" if ("decide" not in settings.READ_REPLICA_OPT_IN or "replica" not in settings.DATABASES) else "replica" ) logger = structlog.get_logger(__name__) ...
66
1,898
posthog
posthog/scopes.py
.py
from collections.abc import Iterable from typing import Literal, get_args ## API Scopes # These are the scopes that are used to define the permissions of the API tokens. # Not every model needs a scope - it should more be for top-level things # Typically each object should have `read` and `write` scopes, but some obje...
558
24,223
posthog
posthog/interval_specs.py
.py
from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timedelta from typing import Literal, Optional, Union, cast from dateutil.relativedelta import relativedelta from posthog.schema_enums import IntervalType IntervalLiteral = Literal["second", "minute", "hour", "day",...
184
6,478
posthog
posthog/internal_api_secret.py
.py
from django.conf import settings def usable_internal_api_secrets() -> list[str]: """Internal API secrets accepted when authenticating service-to-service calls: the primary plus any still-trusted fallbacks (zero-downtime rotation), dropping empties. Values are whitespace-normalized at settings load (postho...
11
516
posthog
posthog/wsgi.py
.py
""" WSGI config for posthog project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import gc import os from django.core.wsgi import get_wsgi_application import structlog from po...
118
5,611
posthog
posthog/push_notifications.py
.py
"""Send push notifications to mobile devices via the Expo push service. The Expo push API accepts up to 100 messages per HTTP call and returns one ticket per message. Tickets carry transient errors (delivery failed, push token invalid) but final delivery success is only confirmed by polling receipts. For the PostHog ...
169
5,781
posthog
posthog/week_start_day.py
.py
"""Week-start-day enum the HogQL engine can import without booting Django (no settings or app registry). `django.db.models.IntegerChoices` is plain enum machinery β€” defining a subclass touches neither settings nor the app registry, so this module imports cleanly in a bare interpreter. posthog.models.team.team re-expor...
18
603
posthog
posthog/errors.py
.py
import re from dataclasses import dataclass from enum import StrEnum from typing import Optional from clickhouse_driver.errors import ServerException from posthog.hogql.errors import ExposedHogQLError from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded from posthog.exceptions import ( ClickHouse...
1,038
50,350
posthog
posthog/oauth2_urls.py
.py
from django.urls import path, re_path from posthog.api.oauth import ( DynamicClientRegistrationView, OAuthAuthorizationServerMetadataView, OAuthAuthorizationView, OAuthClientManifestView, OAuthConnectDiscoveryInfoView, OAuthIntrospectTokenView, OAuthJwksInfoView, OAuthProtectedResourceM...
45
1,816
posthog
posthog/email.py
.py
import html import uuid import smtplib import datetime import dataclasses from decimal import Decimal from typing import TYPE_CHECKING, Any, Literal, Optional if TYPE_CHECKING: from posthog.models import Organization, Team, User from django.conf import settings from django.core import exceptions, mail from django...
608
25,205
posthog
posthog/gzip_middleware.py
.py
import re from django.conf import settings from django.middleware.gzip import GZipMiddleware class InvalidGZipAllowList(Exception): pass def allowed_path(path: str, allowed_paths: list) -> bool: return any(pattern.search(path) for pattern in allowed_paths) class ScopedGZipMiddleware(GZipMiddleware): ...
53
2,041
posthog
posthog/warehouse_source_prewarm.py
.py
import time from django.conf import settings import structlog logger = structlog.get_logger(__name__) def prewarm_warehouse_source_registry() -> None: """Load the full warehouse source catalog (every vendor SDK) at web-worker startup so the worker's first warehouse query doesn't pay the multi-second import...
38
1,420
posthog
posthog/utils.py
.py
import os import re import gzip import json import time import uuid import zlib import base64 import string import asyncio import hashlib import secrets import datetime import datetime as dt import ipaddress import dataclasses from collections.abc import Callable, Generator, Mapping, Sequence from contextlib import con...
2,300
87,379
posthog
posthog/jwt.py
.py
import hashlib from datetime import UTC, datetime, timedelta from enum import Enum from typing import Any from django.conf import settings import jwt from cryptography.hazmat.primitives import serialization JWT_ALGORITHM = "HS256" class PosthogJwtAudience(Enum): UNSUBSCRIBE = "posthog:unsubscribe" EXPORTED...
83
2,948
posthog
posthog/exceptions.py
.py
from typing import Any, Optional, TypedDict from django.http.request import HttpRequest from django.http.response import JsonResponse import structlog from rest_framework import status from rest_framework.exceptions import APIException, ValidationError from rest_framework.response import Response from posthog.clickh...
203
8,885
posthog
posthog/query_creator_access.py
.py
from typing import Any, Optional from posthog.models.organization import OrganizationMembership from posthog.models.team import Team from posthog.models.user import User from posthog.ph_client import ph_scoped_capture def creator_access_revoked(user: Optional[User], team: Team) -> bool: """True when `user` no lo...
49
1,889
posthog
posthog/otel_instrumentation.py
.py
import os import atexit import typing import logging from django.http import HttpRequest, HttpResponse import structlog from opentelemetry import trace from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter from opentelemetry.instrumentation.aiohttp_client import AioHttpClientInstrumentor ...
234
10,850
posthog
posthog/apps.py
.py
import os from django.apps import AppConfig from django.conf import settings import structlog import posthoganalytics from asgiref.sync import async_to_sync from posthoganalytics.client import Client from posthog.git import get_git_branch, get_git_commit_short from posthog.utils import ( _build_flag_provider, ...
257
12,651
posthog
posthog/sampling.py
.py
import structlog logger = structlog.get_logger(__name__) def clamp_to_range( value, min_val: float, max_val: float, label: str | None = None, fallback_value: float | None = None ) -> float: """ Clamps a value to a range. This has been ported from posthog-js. https://github.com/PostHog/posthog-js/blob...
80
2,754
posthog
posthog/user_permissions.py
.py
from functools import cached_property from typing import Any, Optional, cast from uuid import UUID from posthog.constants import AvailableFeature from posthog.models import Organization, OrganizationMembership, Team, User from products.dashboards.backend.models.dashboard import Dashboard from products.dashboards.back...
382
17,154
posthog
posthog/celery_task_names.py
.py
# Task names pinned by vmalert liveness alerts in PostHog/charts (currently # FlagsCacheVerificationNotRunning), which fire on # `increase(posthog_celery_task_success_total{task_name="..."}[window]) == 0`. # # Each name here must be passed as `name=` to its @shared_task decorator, so the # task_name label the alert mat...
25
1,283
posthog
posthog/dbrouter.py
.py
from posthog.settings.data_stores import READ_REPLICA_OPT_IN class ReplicaRouter: def __init__(self, opt_in=None): self.opt_in = opt_in if opt_in else READ_REPLICA_OPT_IN """ A database router to route reads to a separate Aurora endpoint This adds opt-in routing for models, pointing them to ...
50
1,723
posthog
posthog/health.py
.py
# Defines the healthcheck endpoints to be used by process orchestration system # deployments to ensure: # 1. new deployments are not marked as ready if they are misconfigured, e.g. # kafka settings are wrong # 2. pods that are dead for some reason are taken out of service # 3. traffic is not routed to pods that...
333
13,213
posthog
posthog/filters.py
.py
from typing import Optional, TypeVar, Union from django.db import models from django.db.models import Q from django.db.models.query import QuerySet, RawQuerySet from rest_framework import filters, settings from rest_framework.request import Request from rest_framework.views import APIView _MT = TypeVar("_MT", bound=...
98
3,446
posthog
posthog/celery_queues.py
.py
# NOTE: These are the queues used for logically separating workloads. # Many queues are consumed by one "consumer" - a worker configured to consume from that queue. # The goal should be to split up queues based on the type of work being done, so that we can scale effectively # and change the consumer configs without th...
44
1,627
posthog
posthog/continuous_profiling.py
.py
import os import logging logger = logging.getLogger(__name__) # K8s metadata environment variables for Pyroscope tags K8S_TAG_ENV_VARS = { "namespace": "K8S_NAMESPACE", "pod": "K8S_POD_NAME", "node": "K8S_NODE_NAME", "pod_template_hash": "K8S_POD_TEMPLATE_HASH", "app_instance": "K8S_APP_INSTANCE",...
85
3,070
posthog
posthog/date_util.py
.py
from datetime import UTC, datetime, timedelta def start_of_minute(dt: datetime) -> datetime: return datetime(year=dt.year, month=dt.month, day=dt.day, hour=dt.hour, minute=dt.minute, tzinfo=dt.tzinfo) def start_of_hour(dt: datetime) -> datetime: return datetime(year=dt.year, month=dt.month, day=dt.day, hour...
31
1,017
posthog
posthog/constants.py
.py
from enum import StrEnum from typing import Literal from semantic_version import Version FROZEN_POSTHOG_VERSION = Version("1.43.0") # Frozen at the last self-hosted version, just for backwards compat now INTERNAL_BOT_EMAIL_SUFFIX = "@posthogbot.user" POSTHOG_INTERNAL_EMAIL_SUFFIX = "@posthog.com" # N.B. Keep this ...
412
13,706
posthog
posthog/scoping_audit.py
.py
"""Module-import-safe marker for the celery-task-team-scope-audit semgrep rule. Lives at the top of the `posthog` package (not under `posthog.models`) because Celery task modules import this at module load β€” and importing from `posthog.models.*` at that point triggers `posthog.models.__init__` to load every model in t...
49
1,926
posthog
posthog/asgi.py
.py
import gc import os import time import asyncio # Django Imports from django.conf import settings from django.core.asgi import get_asgi_application # Structlog Import import structlog from posthog.warehouse_source_prewarm import prewarm_warehouse_source_registry os.environ["DJANGO_SETTINGS_MODULE"] = "posthog.settin...
181
7,535
posthog
posthog/dataclasses.py
.py
from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import Any, TypeVar, dataclass_transform, overload _T = TypeVar("_T") @overload def frozen(cls: type[_T], /) -> type[_T]: ... @overload def frozen( *, frozen: bool = True, kw_only: boo...
42
1,202
posthog
posthog/persons_db.py
.py
"""Direct, off-ORM connections to the persons database. Cold admin/utility paths β€” Temporal activities, management commands, Dagster jobs β€” that are too bespoke for the personhog gRPC client connect to the persons database through this module. It returns raw psycopg connections that do **not** go through Django's ORM,...
65
2,987
posthog
posthog/views.py
.py
import os from dataclasses import dataclass from datetime import timedelta from functools import wraps from html import escape from typing import Any, Union from urllib.parse import parse_qs, urlencode, urlparse, urlunparse from django.apps import apps from django.conf import settings from django.contrib.admin.sites i...
791
31,693
posthog
posthog/utils_cors.py
.py
from urllib.parse import urlparse from django.http import HttpRequest, HttpResponse import structlog logger = structlog.get_logger(__name__) CORS_ALLOWED_TRACING_HEADERS = ( "traceparent", "request-id", "request-context", "x-amzn-trace-id", "x-cloud-trace-context", "Sentry-Trace", "Bagga...
82
2,604
posthog
posthog/llm_prompt.py
.py
import json from typing import Any def normalize_prompt_to_string(value: Any) -> str: if isinstance(value, str): return value try: return json.dumps(value, ensure_ascii=False) except Exception: return ""
12
242
posthog
posthog/sync.py
.py
# From django channels https://github.com/django/channels/blob/b6dc8c127d7bda3f5e5ae205332b1388818540c5/channels/db.py#L16 from collections.abc import Callable, Coroutine from concurrent.futures import ThreadPoolExecutor from time import time from typing import Any, Optional, ParamSpec, TypeVar, Union, overload from ...
138
4,340
posthog
posthog/auth.py
.py
import re import hmac import time import hashlib import logging import functools from abc import abstractmethod from datetime import timedelta from typing import TYPE_CHECKING, Any, Optional, TypedDict, Union from urllib.parse import parse_qs, urlparse from django.apps import apps from django.conf import settings from...
1,297
52,970
posthog
posthog/version_requirement.py
.py
from semantic_version.base import SimpleSpec, Version from posthog import redis class ServiceVersionRequirement: accepted_services = ("clickhouse", "postgresql", "redis") def __init__(self, service, supported_version): if service not in self.accepted_services: services_str = ", ".join(se...
88
2,598
posthog
posthog/rate_limit.py
.py
import re import json import time import hashlib from contextlib import suppress from datetime import timedelta from functools import lru_cache from typing import TYPE_CHECKING from django.conf import settings from django.urls import resolve from django.utils import timezone from prometheus_client import Counter from...
1,576
61,074
posthog
posthog/shared_link_user.py
.py
"""Lives outside posthog.auth so the hogql layer can import it without a circular import.""" from __future__ import annotations from typing import TYPE_CHECKING from django.contrib.auth.models import AnonymousUser if TYPE_CHECKING: from posthog.models.sharing_configuration import SharingConfiguration class Sh...
30
1,192
posthog
posthog/celery.py
.py
import os import time import errno import threading from django.dispatch import receiver import structlog from celery import Celery from celery.signals import ( celeryd_init, setup_logging, task_failure, task_postrun, task_prerun, task_retry, task_success, worker_process_init, work...
343
12,929
posthog
posthog/raw_sessions_v3_ad_ids.py
.py
# Django-free home for the raw-sessions-v3 lower-tier ad-id list. Kept out of # posthog.models.raw_sessions.sessions_v3 (whose package __init__ boots the Django ORM) so the # HogQL sessions_v3 schema table can build its field catalog at import without booting Django. # posthog.models.raw_sessions.sessions_v3 re-exports...
23
590
posthog
posthog/domain_connect.py
.py
"""Domain Connect protocol support for automated DNS configuration. Implements the synchronous Domain Connect flow (with request signing) so that users can configure DNS records at supported providers with a single click instead of manually copy-pasting records. See https://www.domainconnect.org/ for the protocol spe...
364
13,552
posthog
posthog/urls.py
.py
from collections.abc import Callable from typing import Any, cast from urllib.parse import urlencode, urlparse from django.conf import settings from django.core.cache import cache from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.template import loader from dj...
797
34,295
posthog
posthog/git.py
.py
import re import subprocess from functools import cache from typing import Optional _git_commit_baked_in: Optional[str] = None try: # Docker containers should have a commit.txt file in the base directory with the git # commit hash used to generate them. with open("commit.txt") as f: _git_commit_bak...
84
2,779
posthog
posthog/geoip.py
.py
import ipaddress from dataclasses import dataclass from functools import lru_cache from typing import Optional, TypedDict from django.contrib.gis.geoip2 import GeoIP2 import structlog from posthog.exceptions_capture import capture_exception logger = structlog.get_logger(__name__) try: geoip: Optional[GeoIP2] =...
141
5,136
posthog
posthog/workos_radar.py
.py
""" WorkOS Radar integration for bot/fraud detection during authentication flows. This module provides a client for the WorkOS Radar Attempts API to evaluate signup attempts for potential fraud or bot activity. When Radar returns a BLOCK verdict, the attempt is rejected with a SuspiciousAttemptBlocked exception unless...
336
10,330
posthog
posthog/turnstile.py
.py
""" Cloudflare Turnstile integration for challenge verification. Provides token verification against Cloudflare's siteverify API and single-use nonce management via Redis for tying challenges to specific signup attempts. """ import uuid import hashlib from django.conf import settings import requests import structlo...
94
2,725
posthog
posthog/uuidt.py
.py
import uuid import secrets import datetime from collections import defaultdict from time import time, time_ns from typing import TYPE_CHECKING, Any, Optional, Union # Django-free UUID helpers. Kept out of posthog.models.utils (which imports the Django ORM at # module level) so the HogQL engine can use them without boo...
132
5,578
posthog
posthog/exceptions_capture.py
.py
import contextvars from collections.abc import Iterator from contextlib import contextmanager # Ambient properties merged into every capture_exception raised within the current execution # context. Lets a long-running subsystem (e.g. a data warehouse import) tag captured exceptions # with the job/source they belong to...
86
2,969
posthog
posthog/product_db_router.py
.py
from __future__ import annotations from functools import lru_cache from django.conf import settings from django.core.checks import Error, register from posthog.product_db_config import ProductDBRoute, load_product_db_routes from posthog.settings.base_variables import TEST @lru_cache(maxsize=1) def get_product_db_r...
88
3,196
posthog
posthog/product_db_config.py
.py
from __future__ import annotations import logging from dataclasses import dataclass from pathlib import Path import yaml logger = logging.getLogger(__name__) PRODUCT_DB_ROUTING_FILE = "products/db_routing.yaml" @dataclass(frozen=True) class ProductDBRoute: app_label: str database: str source: str ...
56
1,459
posthog
posthog/data_freshness.py
.py
""" Per-project data freshness: is anything at all still reaching this project? Products declare what counts as their data in `products/<name>/backend/data_freshness.py`, discovered the same way `routes.py` is. This module only runs the shared queries and combines the answers. Runs on an interactive path, so declarat...
318
12,518
posthog
posthog/metrics.py
.py
# Shared metrics and labels for prometheus metrics from contextlib import contextmanager from django.conf import settings import structlog # Patch prometheus_client to bypass HTTP_PROXY/HTTPS_PROXY for pushgateway calls. # The pushgateway is an internal service β€” the outbound proxy would reject it. # ProxyHandler({}...
83
3,017
posthog
posthog/property_columns.py
.py
"""Type aliases naming the tables and columns that store event/person/group properties. Django-free so the HogQL engine and the materialized-columns layer can import them without booting Django; posthog.models.property re-exports them for existing callers. """ from typing import Literal PropertyName = str TableWithP...
17
566
posthog
posthog/event_usage.py
.py
""" Module to centralize event reporting on the server-side. """ import re from enum import StrEnum from typing import TYPE_CHECKING, NotRequired, Optional, Required, TypedDict from urllib.parse import urlparse from django.contrib.auth.models import AnonymousUser import posthoganalytics from opentelemetry import tra...
632
22,624
posthog
posthog/passkey.py
.py
""" Secure wrapper functions for passkey operations. This module provides a secure interface to the webauthn library, enforcing security best practices and consistent configuration across all passkey operations. If you need webauthn without strict user verification/biometrics, use the webauthn library directly (or cre...
166
5,583
posthog
posthog/permissions.py
.py
import os import time import uuid from typing import Optional, cast from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.models import Model import posthoganalytics from loginas.utils import is_impersonated_session from rest_framework.exceptions import Authentication...
1,174
50,648
posthog
posthog/cache_utils.py
.py
import threading from collections.abc import Callable from dataclasses import dataclass, field from datetime import datetime, timedelta from typing import Any, Generic, ParamSpec, TypeVar, cast from django.utils.timezone import now import orjson from django_redis.serializers.base import BaseSerializer from rest_frame...
96
2,996
posthog
posthog/otel_metrics.py
.py
"""OTLP metrics push into the PostHog Metrics product (Python twin of nodejs/src/common/metrics/otel-metrics.ts). Pushes metrics through the same OTel-SDK path customers use, pointed at our own ingest (the `capture-logs` service, path `/i/v1/metrics`), authenticated with a project token. Off unless both OTEL_METRICS_E...
239
10,060
posthog
posthog/products.py
.py
import json import importlib import importlib.util from collections import defaultdict from collections.abc import Iterator from pathlib import Path from types import ModuleType from typing import TYPE_CHECKING, Optional from django.apps import apps from django.conf import settings from posthog.schema_enums import Pr...
134
4,971
posthog
posthog/decorators.py
.py
from collections.abc import Callable from functools import wraps from loginas.utils import is_impersonated_session from rest_framework.request import Request from rest_framework.response import Response def disallow_if_impersonated( message: str = "Impersonated sessions cannot perform this action.", allowed_...
47
1,886
posthog
posthog/cloud_utils.py
.py
import os from datetime import timedelta from typing import TYPE_CHECKING, Any, Optional from django.conf import settings from django.db.utils import ProgrammingError from django.utils import timezone from posthog.exceptions_capture import capture_exception if TYPE_CHECKING: from ee.models.license import License...
93
2,916
posthog
posthog/redis.py
.py
# flake8: noqa from typing import Any, Dict, Optional import asyncio import weakref from django.conf import settings from django.core.exceptions import ImproperlyConfigured import redis import redis.exceptions as redis_exceptions from redis import asyncio as aioredis from redis.asyncio.retry import Retry from redis.b...
171
6,597
posthog
posthog/otel_logs.py
.py
"""OTLP log push into the PostHog Logs product (the logs counterpart of `posthog/otel_metrics.py`). `otel_log_mirror_processor(...)` is a structlog processor, not a stdlib `logging.Handler`: the Temporal workers log through a non-stdlib structlog factory that a stdlib handler never sees. A no-op unless OTLP_LOGS_INGES...
212
8,856
posthog
posthog/ph_client.py
.py
import atexit import threading from collections.abc import Mapping from contextlib import contextmanager from numbers import Number from typing import Any from uuid import UUID import structlog import posthoganalytics from posthog.cloud_utils import is_cloud from posthog.utils import get_instance_region PH_US_API_KE...
170
5,971
posthog
posthog/credentials.py
.py
from dataclasses import dataclass, field from typing import NewType # Distinct static types for the two halves of an AWS key pair. They are plain `str` at runtime. # The point is that a type checker rejects passing a secret where a key id is expected. AWSAccessKeyId = NewType("AWSAccessKeyId", str) AWSSecretAccessKey ...
35
1,508
posthog
posthog/schema_helpers.py
.py
from typing import Literal, assert_never, get_origin from pydantic import BaseModel, ValidationError from posthog.schema import ( BaseMathType, ChartDisplayType, FunnelsQuery, LifecycleQuery, PathsQuery, PathsV2Query, RetentionQuery, StickinessQuery, TrendsQuery, ) from posthog.ho...
220
8,631
posthog
posthog/db_circuit_breaker.py
.py
from __future__ import annotations import time import logging from dataclasses import dataclass from functools import lru_cache from django.conf import settings import redis from statshog.defaults.django import statsd from posthog.dataclasses import frozen from posthog.redis import get_client logger = logging.getL...
291
10,755
posthog
posthog/udf_versioner.py
.py
import os import re import shutil import argparse import datetime # nosemgrep: python.lang.security.use-defused-xml.use-defused-xml (Comment is safe - only parsing functions have XXE risks) from xml.etree.ElementTree import Comment import defusedxml.ElementTree as ET UDF_VERSION = 12 # Last modified by: @aspicer, 2...
83
3,316
posthog
posthog/api_queries_quota.py
.py
"""Per-organization monthly counter of chargeable API query bytes read. The product-owned metering for the free-tier API queries quota: incremented from the ClickHouse client for chargeable queries, read by the query runner's quota check. Kept dependency-light (Redis only) so both layers can import it without cycles. ...
58
1,999
posthog
posthog/web_memory_sampler.py
.py
import os import time import logging import threading import structlog from prometheus_client import Gauge logger = logging.getLogger(__name__) DEFAULT_SAMPLE_INTERVAL_SECONDS = 30.0 # Web-worker RSS, scraped via bin/unit_metrics.py's MultiProcessCollector. `livemax` # reports the maximum across live workers as a s...
104
3,972
posthog
posthog/renderers.py
.py
import orjson from rest_framework.renderers import BaseRenderer, JSONRenderer from rest_framework.utils.encoders import JSONEncoder CleaningMarker = bool | dict[int, "CleaningMarker"] class SafeJSONRenderer(JSONRenderer): def render(self, data, accepted_media_type=None, renderer_context=None) -> bytes: i...
27
783
posthog
posthog/synthetic_user.py
.py
"""Lives outside posthog.auth to avoid a circular import when imported by posthog.hogql.""" from typing import Optional class SyntheticUser: """Tagged base class for non-real principals authenticated via service tokens. Behavior (subclasses may override `readable_system_table_access_scopes`): * `Datab...
42
1,479
posthog
posthog/schema_discriminators.py
.py
"""Callable discriminator for the AnyPropertyFilter union in the generated posthog/schema.py. bin/patch-schema-property-filter-discriminator.py rewrites every inlined property-filter union in posthog/schema.py into a tagged union discriminated by this function. A callable (rather than ``Field(discriminator="type")``) ...
50
2,409
posthog
posthog/person_db_router.py
.py
# posthog/person_db_router.py import threading import contextlib from prometheus_client import Counter # A persons-DB model resolved through the Django ORM. personhog serves person/group/cohort data, # so this should stay at zero in production β€” a nonzero value means a code path still reaches a # persons model via t...
137
5,740