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
posthog/api/test/test_utils.py
.py
import json import requests from typing import Any, cast from django.http import HttpRequest from django.test import SimpleTestCase from django.test.client import RequestFactory from parameterized import parameterized from rest_framework import status from rest_framework.exceptions import ValidationError as DRFValidat...
468
21,324
posthog
posthog/api/test/test_cohort.py
.py
import json from datetime import datetime, timedelta from typing import Any, Optional from freezegun import freeze_time from posthog.test.base import ( APIBaseTest, ClickhouseTestMixin, QueryMatchingTest, _create_event, _create_person, flush_persons_and_events, setup_test_organization_team_...
7,018
284,133
posthog
posthog/api/test/test_log_entries.py
.py
from datetime import UTC, datetime, timedelta from freezegun import freeze_time from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest from rest_framework import status from posthog.clickhouse.client.execute import sync_execute from products.cdp.backend.models.hog_functions.hog_function i...
154
6,066
posthog
posthog/api/test/test_toolbar_oauth_authorize.py
.py
from urllib.parse import parse_qs, urlparse from posthog.test.base import APIBaseTest from unittest.mock import patch class TestToolbarOAuthAuthorize(APIBaseTest): def setUp(self): super().setUp() self.team.app_urls = ["https://mysite.com"] self.team.save() self.user.current_team ...
113
4,680
posthog
posthog/api/test/test_query.py
.py
import json from freezegun import freeze_time from posthog.test.base import ( APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, also_test_with_materialized_columns, flush_persons_and_events, snapshot_clickhouse_queries, ) from unittest import mock from unittest.mock import pa...
1,594
65,053
posthog
posthog/api/test/test_user_home_settings.py
.py
from typing import Any, cast from posthog.test.base import APIBaseTest from rest_framework import status from posthog.models import UserHomeSettings class TestUserHomeSettingsAPI(APIBaseTest): def test_retrieve_empty_settings(self): response = self.client.get("/api/user_home_settings/@me/") se...
99
3,331
posthog
posthog/api/test/test_embedding_worker.py
.py
from datetime import UTC, datetime from unittest.mock import MagicMock, patch from posthog.api.embedding_worker import DocumentKey, get_recently_seen_documents def _doc(document_id: str, product: str = "signals") -> DocumentKey: return DocumentKey( product=product, document_type="signal", ...
70
2,359
posthog
posthog/api/test/test_id_jag.py
.py
""" Tests for the ID-JAG token endpoint + the resource-server side authentication backend. The strategy is: * Generate a throwaway RSA keypair in `setUpClass` and use it to sign a synthetic IdP-issued ID-JAG. We patch `posthog.api.id_jag._get_jwks_client` to return a `PyJWK` whose `.key` is the matching publ...
1,021
48,774
posthog
posthog/api/test/notebooks/test_notebook_filtering.py
.py
from typing import Any from posthog.test.base import APIBaseTest, QueryMatchingTest from parameterized import parameterized from rest_framework import status from posthog.models import User from products.notebooks.backend.models import Notebook PLAYLIST_CONTENT = lambda: { "type": "ph-recording-playlist", ...
428
18,046
posthog
posthog/api/test/notebooks/test_notebook.py
.py
from freezegun import freeze_time from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries from unittest import mock from parameterized import parameterized from rest_framework import status from posthog.models import Organization, Team from posthog.models.user import User from product...
508
20,668
posthog
posthog/api/test/rust_integration/test_cohort_generation.py
.py
""" Integration tests for the Rust batch flag evaluation endpoint used by static cohort generation (`get_cohort_actors_for_feature_flag`). These cover the Django-client ↔ Rust-endpoint contract: internal-token auth, payload shape, version pinning, pagination, and matched-person results, using the real `batch_evaluate_...
125
4,718
posthog
posthog/api/test/rust_integration/test_flags.py
.py
""" Rust /flags integration tests. No Django test framework. Each test: 1. Inserts persons via psycopg2 (persons database) 2. Creates cohorts/flags via Django HTTP API (authenticated with personal API key) 3. Calls Rust /flags endpoint and asserts on the result """ import os from typing import Any import pytest fro...
276
9,668
posthog
posthog/api/test/rust_integration/conftest.py
.py
""" Fixtures for standalone Rust /flags integration tests. No Django test framework. Tests use: - Django ORM for bootstrapping the test environment (org, team, user, API key) - psycopg2 for person/group inserts (bypassing event ingestion) - requests for Django API calls (cohorts, flags) - requests for Rust /flags eval...
324
11,989
posthog
posthog/api/test/dashboards/test_dashboard_text_tiles.py
.py
import datetime from typing import Any, Optional, Union from freezegun import freeze_time from posthog.test.base import APIBaseTest, QueryMatchingTest from unittest import mock from django.test import override_settings from rest_framework import status from posthog.api.test.dashboards import DashboardAPI from posth...
326
13,749
posthog
posthog/api/test/dashboards/__init__.py
.py
from typing import Any, Literal, Optional from rest_framework import status from posthog.models.team import Team from products.dashboards.backend.widget_registry import DashboardWidgetType class DashboardAPI: def __init__(self, client, team: Team, assertEqual): self.client = client self.team = ...
347
11,572
posthog
posthog/api/test/dashboards/test_dashboard_button_tiles.py
.py
from freezegun import freeze_time from posthog.test.base import APIBaseTest from django.test import override_settings from parameterized import parameterized from rest_framework import status from posthog.api.test.dashboards import DashboardAPI class TestDashboardButtonTiles(APIBaseTest): def setUp(self) -> No...
180
7,678
posthog
posthog/api/test/dashboards/test_dashboard_duplication.py
.py
import pytest from posthog.test.base import APIBaseTest, QueryMatchingTest from parameterized import parameterized from rest_framework import status from posthog.api.test.dashboards import DashboardAPI from posthog.constants import AvailableFeature from posthog.models.organization import OrganizationMembership from p...
206
8,426
posthog
posthog/api/test/dashboards/test_dashboard_delete_tile.py
.py
from posthog.test.base import APIBaseTest from unittest.mock import ANY, patch from django.test import override_settings from parameterized import parameterized from rest_framework import status from posthog.api.test.dashboards import DashboardAPI from products.dashboards.backend.models.dashboard_tile import Dashbo...
201
10,294
posthog
posthog/api/test/dashboards/test_dashboard.py
.py
import json import datetime from freezegun import freeze_time from posthog.test.base import APIBaseTest, FuzzyInt, QueryMatchingTest, snapshot_postgres_queries from unittest import mock from unittest.mock import ANY, MagicMock, patch from django.core.cache import cache from django.test import override_settings from d...
4,340
199,670
posthog
posthog/api/advanced_activity_logs/test_field_discovery.py
.py
from typing import Any from posthog.test.base import BaseTest from posthog.api.advanced_activity_logs.fields_cache import _get_cache_key, get_client from posthog.models.activity_logging.activity_log import ActivityLog from .field_discovery import AdvancedActivityLogFieldDiscovery class FieldDiscoveryTest(BaseTest)...
113
4,810
posthog
posthog/api/advanced_activity_logs/utils.py
.py
from datetime import datetime, timedelta from typing import Optional from django.utils import timezone from posthog.constants import AvailableFeature from posthog.models import Organization from .constants import ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_LIMIT, ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_UNIT def get_...
37
1,244
posthog
posthog/api/advanced_activity_logs/test_pagination_schema.py
.py
from django.test import SimpleTestCase from rest_framework.request import Request from rest_framework.test import APIRequestFactory from posthog.api.advanced_activity_logs.viewset import ActivityLogPagination class TestActivityLogPaginationSchema(SimpleTestCase): def test_count_is_not_required_because_cursor_re...
25
977
posthog
posthog/api/advanced_activity_logs/filters.py
.py
import re from typing import Any from django.db.models import JSONField, Q, QuerySet from django.db.models.fields.json import KeyTransform from rest_framework import serializers from posthog.models.activity_logging.activity_log import ActivityLog _ALLOWED_DETAIL_FILTER_OPERATIONS = {"exact", "contains", "in"} # Na...
401
17,714
posthog
posthog/api/advanced_activity_logs/__init__.py
.py
from .field_discovery import AdvancedActivityLogFieldDiscovery from .filters import AdvancedActivityLogFilterManager from .viewset import ( ActivityLogPagination, ActivityLogSerializer, ActivityLogViewSet, AdvancedActivityLogFiltersSerializer, AdvancedActivityLogsViewSet, OrganizationAdvancedAct...
22
646
posthog
posthog/api/advanced_activity_logs/constants.py
.py
SMALL_ORG_THRESHOLD = 20000 BATCH_SIZE = 10000 SAMPLING_PERCENTAGE = 10 CACHE_TTL_SECONDS = 12 * 60 * 60 # 12 hours CACHE_KEY_PREFIX = "activity_log:details_fields" # Fallbacks need to be kept in sync with the smallest AUDIT_LOG feature limits in billing ADVANCED_ACTIVITY_LOGS_LOOKBACK_FALLBACK_LIMIT = 2 ADVANCED_ACTI...
9
364
posthog
posthog/api/advanced_activity_logs/ocsf.py
.py
"""OCSF 1.5.0 representation of activity log entries, for ingestion into a SIEM. Values of changed fields are omitted unless the caller opts in: `detail` is a free-form diff, so any activity type can carry the content of the changed object (notebook rejections embed whole documents, group property writes embedded prop...
160
6,348
posthog
posthog/api/advanced_activity_logs/test_filters.py
.py
import json from typing import Any from posthog.test.base import BaseTest from django.http import QueryDict from django.test import SimpleTestCase from parameterized import parameterized from rest_framework import serializers from posthog.models.activity_logging.activity_log import ActivityLog from .filters import...
458
19,626
posthog
posthog/api/advanced_activity_logs/viewset.py
.py
import re import json import hashlib import logging from datetime import datetime from typing import Any, Optional, cast, get_args from urllib.parse import urlencode from django.db.models import Q, QuerySet from drf_spectacular.utils import extend_schema from rest_framework import mixins, serializers, viewsets from r...
805
35,163
posthog
posthog/api/advanced_activity_logs/test_json_tolerant_list_field.py
.py
from django.http import QueryDict from django.test import SimpleTestCase from parameterized import parameterized from posthog.api.advanced_activity_logs.viewset import AdvancedActivityLogFiltersSerializer def _querydict(pairs: list[tuple[str, str]]) -> QueryDict: qd = QueryDict(mutable=True) for key, value ...
36
1,522
posthog
posthog/api/advanced_activity_logs/fields_cache.py
.py
import json from typing import Optional from posthog.exceptions_capture import capture_exception from posthog.redis import get_client from .constants import CACHE_KEY_PREFIX, CACHE_TTL_SECONDS, SMALL_ORG_THRESHOLD def _get_cache_key(organization_id: str) -> str: return f"{CACHE_KEY_PREFIX}:{organization_id}" ...
54
1,514
posthog
posthog/api/advanced_activity_logs/test_pagination_ordering.py
.py
from datetime import timedelta from freezegun import freeze_time from posthog.test.base import APIBaseTest from django.utils import timezone from parameterized import parameterized from rest_framework.request import Request from rest_framework.test import APIRequestFactory from posthog.api.advanced_activity_logs.vi...
136
5,431
posthog
posthog/api/advanced_activity_logs/test_ocsf.py
.py
from typing import Optional from posthog.test.base import APIBaseTest from parameterized import parameterized from posthog.api.advanced_activity_logs.ocsf import ActivityLogOCSFSerializer from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail class TestActivityLogOCSF(APIBaseTest): ...
133
5,570
posthog
posthog/api/advanced_activity_logs/field_discovery.py
.py
import gc import json import dataclasses from datetime import timedelta from typing import Any, TypedDict from django.db import connection from django.db.models import QuerySet from django.utils import timezone from posthog.models.activity_logging.activity_log import ActivityLog, Change from posthog.models.utils impo...
385
15,154
posthog
posthog/session/middleware.py
.py
from django.conf import settings from django.contrib.auth import BACKEND_SESSION_KEY from django.http import HttpRequest, HttpResponseRedirect from posthog.models import User from posthog.session.activity import sync_current_session_metadata from posthog.session.risk import RiskTier, evaluate_session_risk class User...
50
2,388
posthog
posthog/session/activity.py
.py
import uuid import hashlib from typing import Optional from django.contrib.auth import BACKEND_SESSION_KEY from django.core.cache import cache from django.db import transaction from django.db.models import F from django.http import HttpRequest from django.utils import timezone from loginas.utils import is_impersonate...
140
6,276
posthog
posthog/session/reauth.py
.py
from typing import Optional from django.conf import settings from django.contrib.sessions.backends.base import SessionBase def sensitive_action_reference(session: SessionBase) -> Optional[float]: """Start of the sensitive-action freshness window: the most recent of session creation or the last step-up re-aut...
22
974
posthog
posthog/session/models.py
.py
from django.contrib.sessions.base_session import AbstractBaseSession from django.db import models class Session(AbstractBaseSession): """The application's session model, stored on the `django_session` table. Subclasses Django's `AbstractBaseSession` and is wired in via `SESSION_ENGINE` (`posthog.session....
47
2,395
posthog
posthog/session/apps.py
.py
from django.apps import AppConfig class PostHogSessionConfig(AppConfig): name = "posthog.session" label = "posthog_session" verbose_name = "Sessions" def ready(self) -> None: import posthog.session.signals # noqa: F401, PLC0415 — registers the post_delete session cleanup
11
302
posthog
posthog/session/signals.py
.py
from django.db.models.signals import post_delete from django.dispatch import receiver from posthog.models.user import User from posthog.session.models import Session @receiver(post_delete, sender=User) def delete_sessions_on_user_deletion(sender: type[User], instance: User, **kwargs: object) -> None: """Purge a ...
16
620
posthog
posthog/session/backfill.py
.py
import time from dataclasses import dataclass from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY from django.utils import timezone import structlog from loginas import settings as la_settings from posthog.constants import AUTH_BACKEND_KEYS from posthog.models import User from posthog.session.models imp...
79
2,964
posthog
posthog/session/risk.py
.py
from dataclasses import dataclass from datetime import datetime from enum import Enum, IntEnum from math import asin, cos, radians, sin, sqrt from typing import Any, Optional from django.conf import settings from django.contrib.auth import BACKEND_SESSION_KEY from django.contrib.sessions.backends.base import SessionBa...
366
16,264
posthog
posthog/session/backend.py
.py
from typing import TYPE_CHECKING, Any, cast from django.contrib.auth import SESSION_KEY from django.contrib.sessions.backends.base import CreateError, UpdateError from django.contrib.sessions.backends.db import SessionStore as DBStore from django.db import DatabaseError, IntegrityError, router, transaction from django...
115
4,641
posthog
posthog/session/test/test_backend.py
.py
import uuid from importlib import import_module from posthog.test.base import BaseTest, NonAtomicBaseTest from django.conf import settings from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY from django.contrib.sessions.backends.base import UpdateError from asgiref.sync import async_to_sync from loginas...
155
5,869
posthog
posthog/session/test/test_middleware.py
.py
from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from django.http import HttpResponse, StreamingHttpResponse from django.test import RequestFactory from posthog.session.middleware import UserAuthSessionActivityMiddleware class TestUserAuthSessionActivityMiddleware(BaseTest): def...
38
1,655
posthog
posthog/session/test/test_backfill.py
.py
import uuid from datetime import timedelta from importlib import import_module from posthog.test.base import BaseTest from django.conf import settings from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY from django.utils import timezone from dagster import build_op_context from loginas import settings a...
124
4,548
posthog
posthog/session/test/test_risk_middleware.py
.py
import uuid from datetime import timedelta from importlib import import_module from posthog.test.base import BaseTest from unittest.mock import patch from django.conf import settings from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY from django.http import HttpResponse from django.test import RequestFa...
520
27,392
posthog
posthog/session/test/test_risk.py
.py
from datetime import UTC, datetime, timedelta from typing import Any from posthog.test.base import BaseTest from unittest.mock import patch from django.test import RequestFactory, SimpleTestCase from django.test.utils import override_settings from parameterized import parameterized from posthog.session.risk import ...
184
8,499
posthog
posthog/session/test/test_activity.py
.py
import uuid from datetime import timedelta from importlib import import_module from posthog.test.base import BaseTest from django.conf import settings from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY from django.core.cache import cache from django.test import RequestFactory from django.utils import ti...
242
10,087
posthog
posthog/egress/vapi/transport.py
.py
"""Gated, recorded transport for calls to the Vapi API.""" import hashlib from typing import Any import requests from posthog.egress.limiter.policies import Priority from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient from posthog.egress.vapi.limiter import consume_vapi_api_sync from p...
76
2,285
posthog
posthog/egress/vapi/limiter.py
.py
"""Outbound Vapi API budget keyed by the configured API token fingerprint.""" from django.conf import settings from posthog.egress.limiter.outbound import get_outbound_rate_limiter from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy VAPI_DOMAIN = "vapi" def _vapi_policy(_key: str) -> ...
30
868
posthog
posthog/egress/vapi/__init__.py
.py
from posthog.egress.vapi.transport import vapi_request __all__ = ["vapi_request"]
4
83
posthog
posthog/egress/vapi/observability.py
.py
"""Vapi outbound API request telemetry.""" import requests from prometheus_client import Counter, Gauge from posthog.egress.observability.observability import ( EgressMetrics, EgressObservability, RateLimitSnapshot, register_egress_observability, ) from posthog.egress.vapi.limiter import VAPI_DOMAIN ...
59
1,764
posthog
posthog/egress/logodev/transport.py
.py
"""logo.dev incarnation of the egress transport. ``logodev_request`` is the one way to call logo.dev from anywhere in the codebase: it gates on the instance's shared account budget and records telemetry by construction. The caller owns the endpoint-specific auth: image requests use a publishable key query parameter, w...
75
2,919
posthog
posthog/egress/logodev/limiter.py
.py
"""logo.dev egress budget. logo.dev meters usage per account, and each PostHog instance configures the image and Search API credentials from that account, so the whole instance draws from a single shared budget under a constant scope. logo.dev publishes no hard rate-limit numbers, so the defaults are deliberately mode...
60
3,022
posthog
posthog/egress/logodev/observability.py
.py
"""logo.dev egress telemetry. Every logo.dev call funnels through these recorders so request volume lands on one metric set whichever subsystem made the call (CDP icon picker, MCP store icons, ...), attributed by the ``source`` label. logo.dev reports no rate-limit response headers, so the parser returns an empty snap...
92
3,359
posthog
posthog/egress/transport/transport.py
.py
"""Generic outbound egress transport — the third egress lane, composing the limiter and observability. An :class:`EgressClient` makes an outbound HTTP request that is *gated* (against the shared per-owner budget) and *recorded* (request volume + the API's rate-limit headers) by construction, so no caller can make a re...
100
4,993
posthog
posthog/egress/observability/observability.py
.py
"""Generic outbound API egress observability — the metrics analog of the egress limiter. Mirrors the limiter's shape (:mod:`posthog.egress.limiter.outbound`): a domain-agnostic mechanism, with each third-party API registered as a *domain* that supplies its own metric set and a parser for that API's rate-limit response...
198
9,138
posthog
posthog/egress/limiter/backends.py
.py
"""``limits``-backed implementation of the outbound limiter. All limiter-library and Redis specifics live here so the facade and consumers stay backend-agnostic — swap the library by replacing this module. A sliding-window-counter over Redis holds the shared budget across worker processes: O(1) memory per key, self-ex...
122
6,150
posthog
posthog/egress/limiter/outbound.py
.py
"""The outbound egress rate limiter facade. This is the only surface consumers should touch. Call ``acquire`` (async) or ``consume_sync`` with a limiter key whose domain has a registered ``RatePolicy``; it returns True if the call fits the shared budget, False if it would exceed it. Both are non-blocking — the caller ...
74
3,253
posthog
posthog/egress/limiter/policies.py
.py
"""Outbound egress rate policies and their registry. A *policy* is a budget for calls leaving PostHog to a third-party API. Consumers identify a budget with a limiter key shaped ``"{domain}:{scope}:{id}"`` (e.g. ``"github:installation:123"``); the facade resolves the key to a policy by its ``domain`` (the first segmen...
102
5,031
posthog
posthog/egress/github/transport.py
.py
"""GitHub incarnation of the egress transport. ``github_request`` is the one way to call GitHub from anywhere in the codebase: it gates on the shared per-installation budget and records telemetry by construction, so a caller physically can't forget either. It is *token-agnostic* — pass whatever ``Authorization`` heade...
151
6,760
posthog
posthog/egress/github/limiter.py
.py
"""GitHub egress — the first consumer of the outbound rate limiter. A GitHub App installation gets 5,000–15,000 REST requests/hour on the ``core`` resource depending on the account's plan tier, shared across every PostHog consumer of that installation (warehouse sources, Tasks, Code, Conversations, Visual review). Git...
269
12,506
posthog
posthog/egress/github/observability.py
.py
"""GitHub egress telemetry — the first domain registered with the generic observability mechanism. Every GitHub API client in the codebase funnels its responses through ``record_github_api_response`` so request volume and GitHub's own ``X-RateLimit-*`` headers land on one metric set, regardless of which subsystem made...
160
6,940
posthog
posthog/egress/test/test_outbound_rate_limiter.py
.py
import pytest import posthog.egress.limiter.backends as backends_module import posthog.egress.limiter.outbound as outbound_module import posthog.egress.limiter.policies as policies_module from posthog.egress.github.limiter import GitHubRateResource, acquire_github_installation, github_installation_key from posthog.egr...
205
9,962
posthog
posthog/egress/test/test_vapi_transport.py
.py
from unittest.mock import patch from django.test import SimpleTestCase import requests from posthog.egress.vapi.transport import vapi_request class TestVapiTransport(SimpleTestCase): def test_request_keeps_token_in_authorization_header_and_uses_fingerprint_scope(self) -> None: response = requests.Respo...
33
1,119
posthog
posthog/egress/test/test_github_transport.py
.py
from unittest.mock import MagicMock, patch from django.test import SimpleTestCase import requests from parameterized import parameterized from requests.structures import CaseInsensitiveDict from posthog.egress.github.limiter import GitHubRateResource from posthog.egress.github.transport import GitHubClient, github_r...
49
2,234
posthog
posthog/egress/test/test_github_observability.py
.py
from unittest.mock import MagicMock from django.test import SimpleTestCase import requests from parameterized import parameterized from prometheus_client import REGISTRY from requests.structures import CaseInsensitiveDict from posthog.egress.github.observability import ( _normalize_github_endpoint, record_gi...
194
7,142
posthog
posthog/egress/test/test_logodev.py
.py
from django.test import SimpleTestCase from parameterized import parameterized from posthog.egress.logodev.limiter import consume_logodev_sync, logodev_account_key from posthog.egress.logodev.observability import _normalize_logodev_endpoint class TestLogoDevEgress(SimpleTestCase): @parameterized.expand( ...
28
1,418
posthog
posthog/egress/test/test_github_limiter.py
.py
import uuid from django.core.cache import cache from django.test import SimpleTestCase import requests from parameterized import parameterized from requests.structures import CaseInsensitiveDict from posthog.egress.github.limiter import ( GitHubRateResource, _last_written, _observed_memo, _tier_budge...
169
8,178
posthog
posthog/queries/insight.py
.py
from typing import TYPE_CHECKING, Optional from rest_framework.exceptions import ValidationError from posthog.clickhouse.client import sync_execute from posthog.clickhouse.query_tagging import tag_queries from posthog.errors import ExposedCHQueryError if TYPE_CHECKING: from posthog.types import FilterType # Wr...
40
1,121
posthog
posthog/queries/query_date_range.py
.py
from datetime import datetime, timedelta from functools import cached_property from typing import Literal, Optional from zoneinfo import ZoneInfo from django.utils import timezone from dateutil.relativedelta import relativedelta from posthog.models.filters import AnyFilter from posthog.models.filters.base_filter imp...
213
8,735
posthog
posthog/queries/util.py
.py
import json from datetime import UTC, datetime from enum import Enum, auto from typing import Any, Optional, Union, overload from zoneinfo import ZoneInfo from rest_framework.exceptions import ValidationError from posthog.interval_specs import UnsupportedIntervalError, get_interval_func, get_trunc_func from posthog.m...
156
6,534
posthog
posthog/queries/person_query.py
.py
from typing import Any, Optional, Union, cast from uuid import UUID from posthog.clickhouse.materialized_columns import ColumnName from posthog.constants import PropertyOperatorType from posthog.models import Filter from posthog.models.entity import Entity from posthog.models.filters.path_filter import PathFilter from...
463
19,181
posthog
posthog/queries/actor_base_query.py
.py
import uuid from datetime import datetime from typing import Any, Literal, Optional, TypedDict, Union from django.db.models.query import QuerySet import structlog from posthog.schema import ActorsQuery from posthog.hogql_queries.actor_strategies import PersonStrategy from posthog.hogql_queries.insights.paginators i...
184
6,036
posthog
posthog/queries/property_values.py
.py
from typing import Optional from opentelemetry import trace from posthog.models.person.sql import SELECT_PERSON_PROP_VALUES_SQL, SELECT_PERSON_PROP_VALUES_SQL_WITH_FILTER from posthog.models.property.util import get_property_string_expr from posthog.models.team import Team from posthog.queries.insight import insight_...
109
4,295
posthog
posthog/queries/person_distinct_id_query.py
.py
from posthog.models.event.new_events_schema import events_read_table from posthog.models.person.sql import GET_TEAM_PERSON_DISTINCT_IDS # TODO: Remove the `team_id` param, which is no longer needed – we do all the value interpolation at query time def get_team_distinct_ids_query( team_id: int, *, relevant_events_...
17
764
posthog
posthog/queries/base.py
.py
import re import datetime from collections.abc import Callable from typing import Any, Optional, TypeVar from zoneinfo import ZoneInfo from dateutil import parser from dateutil.relativedelta import relativedelta from rest_framework.exceptions import ValidationError from posthog.models.filters.filter import Filter fro...
154
5,809
posthog
posthog/queries/property_optimizer.py
.py
from dataclasses import dataclass from typing import Optional, cast from rest_framework.exceptions import ValidationError from posthog.constants import PropertyOperatorType from posthog.models.property import Property, PropertyGroup @dataclass(frozen=True) class PropertyGroups: outer: Optional[PropertyGroup] ...
102
4,289
posthog
posthog/queries/properties_timeline/__init__.py
.py
from .properties_timeline import PropertiesTimeline, PropertiesTimelinePoint __all__ = ["PropertiesTimeline", "PropertiesTimelinePoint"]
4
138
posthog
posthog/queries/properties_timeline/properties_timeline.py
.py
import json import datetime from typing import Any, TypedDict, Union, cast from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode 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_que...
211
9,137
posthog
posthog/queries/test/test_util.py
.py
from django.test import TestCase from posthog.queries.util import correct_result_for_sampling class TestQueriesUtil(TestCase): def test_correct_resullt_for_sampling(self): res = correct_result_for_sampling(1, 0.1, None) self.assertEqual(res, 10) res = correct_result_for_sampling(1, 0.01,...
25
747
posthog
posthog/queries/test/test_base.py
.py
import datetime from zoneinfo import ZoneInfo import unittest from freezegun import freeze_time from posthog.test.base import APIBaseTest from dateutil import tz from posthog.models.filters.path_filter import PathFilter from posthog.queries.base import determine_parsed_incoming_date, relative_date_parse_for_feature_...
209
10,493
posthog
posthog/queries/test/test_actors_base_query.py
.py
from typing import Any from posthog.test.base import ( APIBaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_events, snapshot_postgres_queries, ) from posthog.models.person.util import get_persons_by_uuids from posthog.queries.actor_base_query import ( get_groups, get_people,...
158
4,919
posthog
posthog/queries/test/test_person_query.py
.py
import re from freezegun import freeze_time from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_events from posthog.clickhouse.client import sync_execute from posthog.models import Filter from posthog.queries.column_optimizer.column_optimizer import ColumnOptimizer from p...
87
3,412
posthog
posthog/queries/test/test_query_date_range.py
.py
from freezegun import freeze_time from posthog.test.base import APIBaseTest from posthog.models.filters.filter import Filter from posthog.queries.query_date_range import QueryDateRange class TestQueryDateRange(APIBaseTest): def test_parsed_date(self): with freeze_time("2021-08-25T00:00:00.000Z"): ...
132
5,232
posthog
posthog/queries/column_optimizer/foss_column_optimizer.py
.py
from collections import ( Counter, Counter as TCounter, ) from collections.abc import Generator from typing import Union, cast from posthog.clickhouse.materialized_columns import ColumnName, get_materialized_column_for_property from posthog.constants import TREND_FILTER_TYPE_ACTIONS, FunnelCorrelationType from...
181
7,506
posthog
posthog/queries/column_optimizer/column_optimizer.py
.py
# isort: skip_file from posthog.settings import EE_AVAILABLE if EE_AVAILABLE: from ee.clickhouse.queries.column_optimizer import ( EnterpriseColumnOptimizer as ColumnOptimizer, ) else: from posthog.queries.column_optimizer.foss_column_optimizer import ( # type: ignore FOSSColumnOptimizer a...
12
359
posthog
posthog/queries/trends/util.py
.py
import datetime from datetime import timedelta from typing import TypeVar from zoneinfo import ZoneInfo import structlog from dateutil.relativedelta import relativedelta from posthog.constants import NON_TIME_SERIES_DISPLAY_TYPES, UNIQUE_GROUPS from posthog.models.entity import Entity from posthog.models.filters impo...
70
2,391
posthog
posthog/hogql_queries/access_controlled_resources.py
.py
from typing import TYPE_CHECKING, Optional from pydantic import BaseModel from posthog.schema import ( DataWarehouseNode, EntityType, FunnelsDataWarehouseNode, LifecycleDataWarehouseNode, RetentionEntity, ) from posthog.rbac.user_access_control import RESOURCE_FALLBACK_MAP if TYPE_CHECKING: ...
168
9,042
posthog
posthog/hogql_queries/sessions_timeline_query_runner.py
.py
import json from functools import cached_property from typing import cast from posthog.schema import ( CachedSessionsTimelineQueryResponse, EventType, SessionsTimelineQuery, SessionsTimelineQueryResponse, TimelineEntry, ) from posthog.hogql import ast from posthog.hogql.context import HogQLContext...
257
10,961
posthog
posthog/hogql_queries/document_embeddings_query_runner.py
.py
import datetime from collections.abc import Callable from typing import Literal from zoneinfo import ZoneInfo from posthog.schema import ( CachedDocumentSimilarityQueryResponse, DocumentSimilarityQuery, DocumentSimilarityQueryResponse, EmbeddedDocument, EmbeddingDistance, EmbeddingRecord, ) fr...
405
16,174
posthog
posthog/hogql_queries/events_query_runner.py
.py
import re from datetime import datetime, timedelta from functools import cached_property from typing import cast from django.utils.timezone import now import orjson import structlog from posthog.schema import CachedEventsQueryResponse, DashboardFilter, EventsQuery, EventsQueryResponse from posthog.hogql import ast ...
703
35,207
posthog
posthog/hogql_queries/query_metadata.py
.py
from datetime import datetime, timedelta from typing import Any, TypeVar, Union from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.utils.timezone import now from pydantic import BaseModel, ConfigDict from posthog.schema import ( ActionsNode, ActorsQ...
271
10,617
posthog
posthog/hogql_queries/refresh_policy.py
.py
"""Single source of truth for how an insight result is (re)computed per request. Every HTTP surface that renders insight tiles (the insight detail/list endpoints, the dashboard detail/stream/run_insights actions, and shared/embedded rendering) funnels into `InsightSerializer.insight_result`, which computes an `Executi...
94
4,740
posthog
posthog/hogql_queries/query_failure_handling.py
.py
from datetime import UTC, datetime from typing import Optional from rest_framework.exceptions import APIException from posthog.hogql.constants import LimitContext from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level, get_team_kill_switch_level from posthog.errors import CHQueryErrorTo...
83
3,949
posthog
posthog/hogql_queries/property_values_query_runner.py
.py
import json import uuid from datetime import datetime from functools import cached_property from typing import Optional, cast from django.utils import timezone import posthoganalytics from posthog.schema import ( CachedPropertyValuesQueryResponse, PropertyType, PropertyValueItem, PropertyValuesQuery,...
282
11,739
posthog
posthog/hogql_queries/sessions_query_runner.py
.py
import re from datetime import timedelta from typing import Optional from django.utils.timezone import now from posthog.schema import ( CachedSessionsQueryResponse, DashboardFilter, EventPropertyFilter, PropertyOperator, SessionsQuery, SessionsQueryResponse, ) from posthog.hogql import ast fr...
680
33,958
posthog
posthog/hogql_queries/actor_strategies.py
.py
import uuid as uuid_mod from datetime import UTC, datetime from typing import Literal, Optional, cast import orjson as json import structlog from posthog.schema import ActorsQuery, InsightActorsQuery, TrendsQuery from posthog.hogql import ast from posthog.hogql.parser import parse_expr, parse_select from posthog.hog...
328
12,399
posthog
posthog/hogql_queries/actors_query_runner.py
.py
import itertools from collections.abc import Iterable, Iterator, Sequence from typing import TYPE_CHECKING, Any, Optional if TYPE_CHECKING: from posthog.event_usage import AnalyticsProps from posthoganalytics import feature_enabled from posthog.schema import ( ActorsQuery, ActorsQueryResponse, Cached...
582
26,828
posthog
posthog/hogql_queries/hogql_query_runner.py
.py
from collections.abc import Callable from datetime import datetime from typing import Any, Optional, cast from posthog.schema import ( CachedHogQLQueryResponse, DashboardFilter, DateRange, HogQLFilters, HogQLQuery, HogQLQueryResponse, ) from posthog.hogql import ast from posthog.hogql.constant...
201
8,974