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/clickhouse/materialized_columns.py
.py
from collections.abc import Mapping from posthog.clickhouse.materialized_column_types import ( DMAT_STRING_COLUMN_NAME_PREFIX, MATERIALIZATION_VALID_TABLES, MATERIALIZED_COLUMN_NAME_PREFIXES, ColumnName, MaterializedColumn, TablesWithMaterializedColumns, ) from posthog.models.instance_setting i...
63
2,498
posthog
posthog/clickhouse/events_json.py
.py
"""ClickHouse schema declarations for the native-JSON events tables. Table names, JSON subcolumn type declarations, and index DDL for the events-JSON schema. Django-free so the HogQL engine (printer, property planner) can import these without booting Django; posthog.models.event.sql re-exports the public names for exi...
265
15,709
posthog
posthog/clickhouse/system_status.py
.py
from collections.abc import Generator from datetime import timedelta from os.path import abspath, dirname, join from zoneinfo import ZoneInfo from django.utils import timezone import posthoganalytics from dateutil.relativedelta import relativedelta from posthog.api.dead_letter_queue import get_dead_letter_queue_size...
234
7,466
posthog
posthog/clickhouse/query_log_archive.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import Buffer, Distributed, MergeTreeEngine, ReplicationScheme QUERY_LOG_ARCHIVE_DATA_TABLE = "query_log_archive" QUERY_LOG_ARCHIVE_MV = "query_log_archive_mv" QUERY_LOG_ARCHIVE_OLD_TABLE = "query_log_archive_v2" QUERY_LOG_ARCHIVE_WRITABLE_DISTRIB...
898
41,705
posthog
posthog/clickhouse/table_engines.py
.py
import uuid from enum import StrEnum from django.conf import settings class ReplicationScheme(StrEnum): NOT_SHARDED = "NOT_SHARDED" SHARDED = "SHARDED" REPLICATED = "REPLICATED" # Relevant documentation: # - https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/ # - https://clickhouse.c...
141
5,267
posthog
posthog/clickhouse/cluster.py
.py
from __future__ import annotations import re import abc import time import logging import itertools from collections import defaultdict from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence, Set from concurrent.futures import ALL_COMPLETED, FIRST_EXCEPTION, Future, ThreadPoolExecutor, as_complete...
975
41,205
posthog
posthog/clickhouse/cancel.py
.py
from statshog.defaults.django import statsd from posthog import settings from posthog.api.services.query import logger from posthog.clickhouse.client import sync_execute from posthog.clickhouse.client.connection import default_client from posthog.settings import CLICKHOUSE_CLUSTER def cancel_query_on_cluster(team_id...
48
2,439
posthog
posthog/clickhouse/workload.py
.py
from enum import StrEnum class Workload(StrEnum): # Default workload DEFAULT = "DEFAULT" # Analytics queries, other 'lively' queries ONLINE = "ONLINE" # Historical exports, other long-running processes where latency is less critical OFFLINE = "OFFLINE" # Logs queries LOGS = "LOGS" ...
15
382
posthog
posthog/clickhouse/distributed_system_processes.py
.py
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.settings.data_stores import CLICKHOUSE_CLUSTER # Deliberately using skip_unavailable_shards, as the things that use this table are usually not 100% critical, and can have bad knock-on effects if they keep waiting for shards. def DISTRIBUTED_SYSTEM...
14
634
posthog
posthog/clickhouse/plugin_log_entries.py
.py
from posthog import settings from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.clickhouse.kafka_engine import KAFKA_COLUMNS, kafka_engine, ttl_period from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree from posthog.kafka_client.topics import KAFKA_PLUGIN_LOG_ENTRIES PLUGIN_...
102
3,354
posthog
posthog/clickhouse/kafka_engine.py
.py
# Note for the vary: these engine definitions (and many table definitions) are not in sync with cloud! from typing import Literal from django.conf import settings # Consumer group names for Kafka tables. # US deployment uses named groups after the cluster reshard, other deployments use legacy group names. # Once we m...
148
7,353
posthog
posthog/clickhouse/dictionaries.py
.py
from django.conf import settings from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds def dictionary_source_clickhouse(table: str) -> str: """Build a dictionary SOURCE(CLICKHOUSE(...)) clause authed as the dedicated low-privilege dict_reader user (falls back to the default us...
17
741
posthog
posthog/clickhouse/log_entries_v2_test.py
.py
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.clickhouse.kafka_engine import KAFKA_COLUMNS, kafka_engine, ttl_period from posthog.clickhouse.table_engines import ReplacingMergeTree from posthog.kafka_client.topics import KAFKA_LOG_ENTRIES_V2_TEST from posthog.settings import CLICKHOUSE_CLUSTER, ...
108
3,528
posthog
posthog/clickhouse/adhoc_events_deletion.py
.py
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.clickhouse.table_engines import ReplacingMergeTreeDeleted ADHOC_EVENTS_DELETION_TABLE = "adhoc_events_deletion" def ADHOC_EVENTS_DELETION_TABLE_SQL(on_cluster=True): return """ CREATE TABLE IF NOT EXISTS {table_name} {on_cluster_clause} ( ...
33
1,049
posthog
posthog/clickhouse/schema.py
.py
# This file contains all CREATE TABLE queries, used to sync and test schema import re from collections.abc import Callable from posthog.clickhouse.dead_letter_queue import ( DEAD_LETTER_QUEUE_TABLE_MV_SQL, DEAD_LETTER_QUEUE_TABLE_SQL, KAFKA_DEAD_LETTER_QUEUE_TABLE_SQL, WRITABLE_DEAD_LETTER_QUEUE_TABLE_...
654
24,398
posthog
posthog/clickhouse/indexes.py
.py
# Speeds up filtering by _timestamp columns def index_by_kafka_timestamp(table: str): return f"INDEX kafka_timestamp_minmax_{table} _timestamp TYPE minmax GRANULARITY 3"
4
174
posthog
posthog/clickhouse/property_values.py
.py
from django.conf import settings from posthog.clickhouse.kafka_engine import CONSUMER_GROUP_PROPERTY_VALUES, kafka_engine from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplicationScheme from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_PROPERTY_VALUES TABLE_NAME = "property_va...
106
3,297
posthog
posthog/clickhouse/dead_letter_queue.py
.py
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.clickhouse.indexes import index_by_kafka_timestamp from posthog.clickhouse.kafka_engine import KAFKA_COLUMNS, kafka_engine, ttl_period from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree from posthog.kafka_client.topics impor...
144
4,129
posthog
posthog/clickhouse/explain.py
.py
import json from dataclasses import dataclass from posthog.schema import QueryIndexUsage from posthog.hogql.context import HogQLContext from posthog.clickhouse.client import sync_execute def find_all_reads(explain: dict) -> list[dict]: """ Looks for a Plan/Subplan with "Indexes" element. ClickHouse' MergeT...
144
5,279
posthog
posthog/clickhouse/base_sql.py
.py
COPY_ROWS_BETWEEN_TEAMS_BASE_SQL = """ INSERT INTO {table_name} (team_id, {columns_except_team_id}) SELECT %(target_team_id)s, {columns_except_team_id} FROM {table_name} WHERE team_id = %(source_team_id)s """
5
217
posthog
posthog/clickhouse/log_entries.py
.py
from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE from posthog.clickhouse.kafka_engine import ( CONSUMER_GROUP_LOG_ENTRIES, CONSUMER_GROUP_LOG_ENTRIES_WS, KAFKA_COLUMNS, kafka_engine, ttl_period, ) from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme...
234
7,436
posthog
posthog/clickhouse/property_groups.py
.py
import dataclasses from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass from typing import Optional TableName = str PropertySourceColumnName = str PropertyGroupName = str @dataclass class PropertyGroupDefinition: key_filter_expression: str key_filter_function: Callable[[s...
293
11,663
posthog
posthog/clickhouse/materialized_column_types.py
.py
"""Materialized-column types and constants the HogQL engine can import without booting Django. The Django-side lookups (instance settings, the EE column cache) live in posthog.clickhouse.materialized_columns, which re-exports these names for existing callers. """ from typing import Protocol from posthog.property_col...
31
1,086
posthog
posthog/clickhouse/query_tagging.py
.py
# This module is responsible for adding tags/metadata to outgoing clickhouse queries in a thread-safe manner import os import sys import uuid import types import contextvars from collections.abc import Generator from contextlib import contextmanager, suppress from enum import StrEnum from typing import TYPE_CHECKING, A...
895
35,776
posthog
posthog/clickhouse/client/execute.py
.py
import sys import time import types import logging import threading import traceback from collections.abc import Iterator, Sequence from contextlib import contextmanager from enum import StrEnum from functools import lru_cache from time import perf_counter from typing import Any, Optional, TypedDict, Union from django...
743
29,498
posthog
posthog/clickhouse/client/__init__.py
.py
from typing import TYPE_CHECKING from posthog.clickhouse.client.execute import query_with_columns, sync_execute if TYPE_CHECKING: from posthog.clickhouse.client.execute_async import execute_process_query __all__ = [ "sync_execute", "query_with_columns", "execute_process_query", ] # execute_async im...
23
770
posthog
posthog/clickhouse/client/connection.py
.py
import os import logging from collections.abc import Mapping from contextlib import contextmanager from dataclasses import field from enum import StrEnum from functools import cache from typing import TYPE_CHECKING from django.conf import settings from clickhouse_driver import Client as SyncClient from clickhouse_poo...
358
12,829
posthog
posthog/clickhouse/client/tracing.py
.py
import re import logging from functools import wraps from time import perf_counter from typing import cast from opentelemetry import trace from opentelemetry.trace import Status, StatusCode from posthog.clickhouse.client.connection import ClickHouseUser, Workload from posthog.settings import CLICKHOUSE_DATABASE, CLIC...
107
4,758
posthog
posthog/clickhouse/client/limit.py
.py
import time import uuid import dataclasses from collections.abc import Callable from contextlib import contextmanager from functools import wraps from time import sleep from typing import Optional from celery import current_task from prometheus_client import Counter from posthog import redis, settings from posthog.cl...
490
19,502
posthog
posthog/clickhouse/client/migration_tools.py
.py
import logging from functools import cache from typing import Optional from infi.clickhouse_orm import migrations from posthog import settings from posthog.clickhouse.client.connection import DATA_NODE_ROLES, SINGLE_SHARD_DATA_NODE_ROLES, NodeRole from posthog.clickhouse.cluster import ClickhouseCluster, Query, get_c...
121
5,595
posthog
posthog/clickhouse/client/escape.py
.py
# Methods used for rendering a ClickHouse query, given a template string and a # set of parameters. # # This uses the `escape_param` function from the `clickhouse-driver` package, # but passes an empty `Context` object to it. Prior to # https://github.com/mymarilyn/clickhouse-driver/commit/87090902f0270ed51a0b6754d5cbf...
125
4,921
posthog
posthog/clickhouse/client/async_task_chain.py
.py
import uuid import typing import threading from contextlib import contextmanager from functools import partial from django.db import transaction from celery import chain from celery.canvas import Signature from celery.result import EagerResult from posthog.schema import QueryStatus if typing.TYPE_CHECKING: from...
98
2,803
posthog
posthog/clickhouse/client/execute_async.py
.py
import uuid import datetime from typing import TYPE_CHECKING, Optional, cast import orjson as json import structlog import posthoganalytics from prometheus_client import Histogram from pydantic import BaseModel from rest_framework.exceptions import APIException, NotFound from posthog.schema import ClickhouseQueryProg...
474
19,721
posthog
posthog/clickhouse/client/test/test_connection.py
.py
import pytest from posthog.clickhouse.client.connection import ( Workload, get_http_client, get_pool, make_ch_pool, set_default_clickhouse_workload_type, ) from posthog.clickhouse.client.execute import sync_execute @pytest.mark.django_db def test_insert_with_http_client(): sync_execute("DROP ...
79
2,662
posthog
posthog/clickhouse/client/test/test_execute_async.py
.py
import json import uuid import datetime from typing import Any from posthog.test.base import ClickhouseTestMixin, snapshot_clickhouse_queries from unittest.mock import MagicMock, patch from django.db import transaction from django.test import SimpleTestCase, TestCase from parameterized import parameterized from pos...
660
30,193
posthog
posthog/clickhouse/client/test/test_tracing.py
.py
import pytest from unittest.mock import MagicMock, Mock, patch from clickhouse_driver.errors import ServerException from opentelemetry.trace import Status, StatusCode from posthog.clickhouse.client.connection import ClickHouseUser, Workload from posthog.clickhouse.client.tracing import trace_clickhouse_query_decorato...
327
13,950
posthog
posthog/clickhouse/client/test/test_escape.py
.py
from typing import Any import pytest from parameterized import parameterized from posthog.clickhouse.client.escape import substitute_params, substitute_params_for_display class TestSubstituteParams: @parameterized.expand( [ ( "basic values", "SELECT * FROM ta...
119
4,678
posthog
posthog/clickhouse/client/test/test_execute.py
.py
import pytest from unittest.mock import MagicMock, patch from posthog.clickhouse.client.connection import ClickHouseUser, Workload from posthog.clickhouse.client.execute import sync_execute from posthog.clickhouse.client.limit import ConcurrencySlot, RateLimit, get_llm_analytics_rate_limiter from posthog.clickhouse.qu...
108
5,302
posthog
posthog/clickhouse/client/test/test_limit.py
.py
import uuid import asyncio from collections.abc import Callable from posthog.test.base import BaseTest from unittest.mock import Mock, patch from parameterized import parameterized from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded, ConcurrencySlot, RateLimit from posthog.clickhouse.query_tagging i...
579
25,215
posthog
posthog/clickhouse/traces/trace_attributes.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import AggregatingMergeTree, MergeTreeEngine, ReplicationScheme TABLE_NAME = "trace_attributes" TABLE_NAME_V2 = "trace_attributes2" def _trace_attributes_table_sql(table_name: str, engine: str): return f""" CREATE TABLE IF NOT EXISTS {settin...
48
1,738
posthog
posthog/clickhouse/traces/__init__.py
.py
from .spans import ( KAFKA_TRACE_SPANS_AVRO_MV, KAFKA_TRACE_SPANS_AVRO_TABLE_SQL, TRACE_ATTRIBUTES_DISTRIBUTED_TABLE_SQL, TRACE_SPAN_TO_ATTRIBUTES2_MV, TRACE_SPAN_TO_ATTRIBUTES_MV, TRACE_SPAN_TO_RESOURCE_ATTRIBUTES2_MV, TRACE_SPAN_TO_RESOURCE_ATTRIBUTES_MV, TRACE_SPAN_TO_SPAN_ATTRIBUTES2...
35
1,191
posthog
posthog/clickhouse/traces/spans.py
.py
from django.conf import settings from posthog.clickhouse.kafka_engine import kafka_engine from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme from .trace_attributes import ( TABLE_NAME as TRACE_ATTRIBUTES_TABLE_NAME, TABLE_NAME_V2 as TRACE_ATTRIBUTES_TABLE_NAME_V2, ) ...
418
15,163
posthog
posthog/clickhouse/logs/logs_kafka_metrics.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplicationScheme TABLE_NAME = "logs_kafka_metrics" def LOGS_KAFKA_METRICS_TABLE_SQL(): return f""" CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME} ( `_partiti...
36
1,209
posthog
posthog/clickhouse/logs/logs32.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme from .log_attributes import TABLE_NAME as LOG_ATTRIBUTES_TABLE_NAME from .log_attributes3 import TABLE_NAME as LOG_ATTRIBUTES3_TABLE_NAME TABLE_NAME = "logs32" TTL = lambda: ( "TTL times...
328
12,202
posthog
posthog/clickhouse/logs/__init__.py
.py
from .log_attributes import LOG_ATTRIBUTES_DISTRIBUTED_TABLE_SQL, LOG_ATTRIBUTES_TABLE_SQL from .log_attributes2 import LOG_ATTRIBUTES2_DISTRIBUTED_TABLE_SQL, LOG_ATTRIBUTES2_TABLE_SQL from .log_attributes3 import LOG_ATTRIBUTES3_DISTRIBUTED_TABLE_SQL, LOG_ATTRIBUTES3_TABLE_SQL from .logs32 import ( LOG_ATTRIBUTES3...
62
2,350
posthog
posthog/clickhouse/logs/logs_billing_metrics.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplicationScheme TABLE_NAME = "logs_billing_metrics" def LOGS_BILLING_METRICS_TABLE_SQL(): return f""" CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME} ( `team...
39
1,277
posthog
posthog/clickhouse/logs/log_attributes2.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplicationScheme TABLE_NAME = "log_attributes2" def LOG_ATTRIBUTES2_TABLE_SQL(): return f""" CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME} ( `team_id` Int32...
47
1,836
posthog
posthog/clickhouse/logs/logs_volume_buckets.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme # Per-5-minute log volume rollup for anomaly detection. One row per # (team, bucket, generation, series) where the series identity is # (service_name, namespace, environment, severity_text) — ...
66
2,982
posthog
posthog/clickhouse/logs/log_attributes.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplicationScheme TABLE_NAME = "log_attributes" STORAGE_POLICY = lambda: "hot" if settings.CLICKHOUSE_LOGS_ENABLE_STORAGE_POLICY else "default" def LOG_ATTRIBUTES_TABLE_SQL(): return f""" CREATE TAB...
49
2,069
posthog
posthog/clickhouse/logs/log_attributes3.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplicationScheme TABLE_NAME = "log_attributes3" def LOG_ATTRIBUTES3_TABLE_SQL(): return f""" CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME} ( `team_id` Int32...
48
1,895
posthog
posthog/clickhouse/logs/logs34.py
.py
from django.conf import settings from posthog.clickhouse.kafka_engine import kafka_engine from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme from .log_attributes2 import TABLE_NAME as LOG_ATTRIBUTES_TABLE_NAME from .log_attributes3 import TABLE_NAME as LOG_ATTRIBUTES3_TABLE_N...
458
16,033
posthog
posthog/clickhouse/hcl/codegen/gen_migration.py
.py
#!/usr/bin/env python3 """Generate a ClickHouse migration from a declarative-HCL change. Uses `hclexp plan` to diff the **committed goldens** (current managed state) against the **working-tree composition** (desired) for every role at once, per env. Because goldens hold only the managed set, a DROP here is a real remo...
248
10,996
posthog
posthog/clickhouse/metrics/metric_events.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplacingMergeTree, ReplicationScheme # Raw, un-aggregated metrics stored as a TSDB series/samples split (not the # fat one-row-per-event shape logs/traces use — a metric sample is a single # number, so inlinin...
105
4,773
posthog
posthog/clickhouse/metrics/__init__.py
.py
from .metric_attributes import METRIC_ATTRIBUTES_TABLE_SQL from .metric_events import ( METRIC_SAMPLES_DISTRIBUTED_TABLE_SQL, METRIC_SAMPLES_TABLE_SQL, METRIC_SERIES_DISTRIBUTED_TABLE_SQL, METRIC_SERIES_TABLE_SQL, ) from .metrics1 import ( METRIC_ATTRIBUTES_MV, METRIC_RESOURCE_ATTRIBUTES_MV, ...
26
706
posthog
posthog/clickhouse/metrics/metric_attributes.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import AggregatingMergeTree, ReplicationScheme TABLE_NAME = "metric_attributes" def METRIC_ATTRIBUTES_TABLE_SQL(): return f""" CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_LOGS_CLUSTER_DATABASE}.{TABLE_NAME} ( `team_id` Int32 CODEC(Do...
32
1,424
posthog
posthog/clickhouse/metrics/metrics1.py
.py
from django.conf import settings from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme from .metric_attributes import TABLE_NAME as METRIC_ATTRIBUTES_TABLE_NAME TABLE_NAME = "metrics1" def METRICS1_TABLE_SQL(): return f""" CREATE TABLE IF NOT EXISTS {settings.CLICKHOUSE_L...
182
6,540
posthog
posthog/clickhouse/preaggregation/marketing_touchpoints_sql.py
.py
# Reusable, attribution-config-agnostic touchpoint precompute: one row per UTM-tagged # pageview (team, person, timestamp + the tracked UTM dimensions). Unlike # conversion_goal_attributed_preaggregated (which caches per-goal attribution RESULTS, # keyed by job_id = goal+mode+window), this caches the raw touchpoints — ...
90
2,965
posthog
posthog/clickhouse/preaggregation/web_stats_preaggregated_sql.py
.py
# Table for storing lazy-precomputed web stats table aggregates # # Stores per-hour, per-team, per-breakdown aggregate states for the two metrics # surfaced by WebStatsTableQueryRunner's simple breakdowns: unique users and # total pageviews. Reads merge across hourly buckets to answer arbitrary date # ranges within the...
112
4,550
posthog
posthog/clickhouse/preaggregation/conversion_goal_attributed_sql.py
.py
# Pre-attributed output of the conversion-goal pipeline: one row per # (team, job, person, conversion_timestamp, touchpoint_timestamp) with the # attribution weight for that touchpoint. Single-touch emits weight=1.0 and one # row per conversion; multi-touch emits N rows per conversion with fractional # weights that sum...
102
3,114
posthog
posthog/clickhouse/preaggregation/sql.py
.py
# These tables are used to save and re-use intermediate results from queries # They are hidden behind a flag that is only visible behind a HogQLQueryModifier that is only settable in the query debugger # One unsolved problem so far is ensuring that we can read our own writes, as often we write to this table immediate...
83
3,054
posthog
posthog/clickhouse/preaggregation/web_goals_preaggregated_sql.py
.py
# Table for storing lazy-precomputed web goals (conversion) aggregates. # # One row per (team, job, UTC hour, action_id) where action_id is one of the # top-5 actions the runner picks at query time # (`Action.objects…order_by("pinned_at", "-last_calculated_at")[:5]`). The set # of action expressions and IDs is baked in...
108
4,160
posthog
posthog/clickhouse/preaggregation/web_stats_frustration_preaggregated_sql.py
.py
# Table for storing lazy-precomputed web stats FRUSTRATION metrics # (rage clicks, dead clicks, exceptions). # # One row per (team, job, UTC hour, breakdown_value). The strategy that drives # the frustration tile groups events per session × breakdown_value, then sums # the per-session counts across sessions. Each sessi...
111
4,630
posthog
posthog/clickhouse/preaggregation/web_vitals_paths_preaggregated_sql.py
.py
# Table for storing lazy-precomputed web vitals path-breakdown quantiles # # Stores per-day, per-team, per-path quantile-state aggregates matching # `WebVitalsPathBreakdownQueryRunner`'s output. Reads merge across daily # buckets and pick a single percentile (p75/p90/p99) via array indexing. # # Buckets are keyed by `t...
115
4,985
posthog
posthog/clickhouse/preaggregation/experiment_exposures_sql.py
.py
# Table for storing preaggregated experiment exposures # # Instead of scanning the events table on every experiment query to find # who was exposed to which variant, we compute this once and store it here. # Subsequent queries read from this table instead of scanning events. # # See posthog/hogql_queries/experiments/PR...
90
2,848
posthog
posthog/clickhouse/preaggregation/experiment_metric_events_sql.py
.py
# Table for storing preaggregated experiment metric events # # Instead of scanning the events table on every experiment query to find # metric events (funnel steps, mean values, etc.), we compute this once # and store it here. Subsequent queries read from this table instead of # scanning events. # # For funnels: one ro...
104
3,507
posthog
posthog/clickhouse/preaggregation/web_stats_dimensional_preaggregated_sql.py
.py
# Table for storing scheduled-precomputed web stats with fixed dimensions. # # This is the precomputation-framework successor to the v2 pre-aggregation table # `web_pre_aggregated_stats`. It carries the same fixed dimension set (host, # device_type, pathname, browser, os, utm_*, geoip, …) baked into the schema, so # re...
159
5,659
posthog
posthog/clickhouse/preaggregation/web_overview_preaggregated_sql.py
.py
# Table for storing lazy-precomputed web overview aggregates # # Stores per-hour, per-team aggregate states for the five metrics surfaced by # WebOverviewQueryRunner: unique users, unique sessions, total pageviews, # average session duration, average bounce rate. Reads merge across hourly # buckets to answer arbitrary ...
103
4,102
posthog
posthog/clickhouse/preaggregation/web_bounces_dimensional_preaggregated_sql.py
.py
# Table for storing scheduled-precomputed web bounce metrics with fixed dimensions. # # Precomputation-framework successor to the v2 pre-aggregation table # `web_pre_aggregated_bounces`. Same fixed dimension set as the stats table minus # `pathname` (bounces are attributed per session, not per pathname), plus the # bou...
145
4,787
posthog
posthog/clickhouse/preaggregation/marketing_costs_sql.py
.py
# Reusable cost precompute: marketing source cost rows (per source, campaign, ad_group, ad, day) # materialized out of the external data-warehouse tables (S3) into native ClickHouse. The cost side # of marketing analytics is a `UNION ALL` of N source adapters reading S3-backed DWH tables; that S3 # read is the dashboar...
94
2,861
posthog
posthog/clickhouse/preaggregation/web_stats_paths_preaggregated_sql.py
.py
# Table for storing lazy-precomputed web stats PATHS aggregates (path tile # with bounce rate). # # One row per (team, job, UTC hour, breakdown_value) where breakdown_value is # the URL path (optionally prepended with host). For each session, we emit one # row per pathname it touched. The bounce aggregate is set only w...
169
6,775
posthog
posthog/clickhouse/preaggregation/marketing_conversions_sql.py
.py
# Reusable, attribution-config-agnostic conversion precompute: one row per conversion event # (team, person, timestamp, math value + the conversion-side tracked UTM dimensions). Sibling of # marketing_touchpoints_preaggregated: touchpoints cache the pageview side, this caches the # conversion side. Keyed by (event/acti...
92
3,083
posthog
posthog/clickhouse/test/test_migrations.py
.py
import os import re import ast import sys import importlib from collections import defaultdict from pathlib import Path from unittest import TestCase, mock from infi.clickhouse_orm.utils import import_submodules from posthog.clickhouse.client.connection import DATA_NODE_ROLES, NodeRole # Migrations created before t...
305
14,510
posthog
posthog/clickhouse/test/test_custom_metrics.py
.py
from collections.abc import Iterator import pytest from posthog.test.base import reset_clickhouse_database from posthog.clickhouse.cluster import ClickhouseCluster, Query, get_cluster from posthog.clickhouse.custom_metrics import MetricsClient @pytest.fixture def cluster(django_db_setup) -> Iterator[ClickhouseClust...
42
1,187
posthog
posthog/clickhouse/test/test_preaggregation_model.py
.py
import uuid from datetime import UTC, datetime from posthog.test.base import BaseTest, ClickhouseTestMixin from posthog.clickhouse.client import sync_execute from posthog.clickhouse.preaggregation.sql import DISTRIBUTED_PREAGGREGATION_RESULTS_TABLE class TestPreaggregationModel(ClickhouseTestMixin, BaseTest): d...
135
4,813
posthog
posthog/clickhouse/test/test_0064.py
.py
# ruff: noqa import importlib from posthog.test.base import BaseTest, ClickhouseDestroyTablesMixin, _create_event from posthog.clickhouse.client import sync_execute module = importlib.import_module("posthog.clickhouse.migrations.0064_materialize_elements_chain") add_columns_to_required_tables = module.add_columns_to...
43
1,412
posthog
posthog/clickhouse/test/test_deletion_coverage.py
.py
from posthog.test.base import BaseTest, ClickhouseTestMixin from django.conf import settings from posthog.clickhouse.client import sync_execute from posthog.models.deletion_targets import PERSONAL_DATA_TARGETS, TTL_ONLY_TABLES class TestDeletionCoverage(ClickhouseTestMixin, BaseTest): def test_storage_tables_ca...
46
2,303
posthog
posthog/clickhouse/test/test_kill_switch.py
.py
from unittest.mock import MagicMock, patch from parameterized import parameterized from posthog.clickhouse.client.execute import ( _KILL_SWITCH_SETTINGS, KillSwitchLevel, _get_kill_switch_level, _get_kill_switch_team_sets, default_settings, get_kill_switch_level, get_team_kill_switch_level...
236
9,899
posthog
posthog/clickhouse/test/test_explain.py
.py
import json from dataclasses import dataclass import pytest from posthog.schema import QueryIndexUsage from posthog.clickhouse.explain import ( ReadIndexUsage, extract_index_usage_from_plan, find_all_reads, guestimate_index_use, ) @dataclass class DataTestCase: query: str reads: int rea...
564
23,998
posthog
posthog/clickhouse/test/test_sessions_model.py
.py
from posthog.test.base import BaseTest, ClickhouseDestroyTablesMixin, ClickhouseTestMixin, _create_event from posthog.clickhouse.client import query_with_columns, sync_execute from posthog.models import Team distinct_id_counter = 0 session_id_counter = 0 def create_distinct_id(): global distinct_id_counter ...
305
9,798
posthog
posthog/clickhouse/test/test_raw_sessions_model.py
.py
import datetime from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event from posthog.clickhouse.client import query_with_columns, sync_execute from posthog.models.raw_sessions.sessions_v2 import RAW_SESSION_TABLE_BACKFILL_SELECT_SQL from posthog.models.utils import uuid7 distinct_id_counter = 0 se...
371
12,371
posthog
posthog/clickhouse/test/test_enable_analyzer.py
.py
import xml.etree.ElementTree as ET from pathlib import Path from posthog.hogql.constants import HogQLGlobalSettings, get_default_hogql_global_settings REPO_ROOT = Path(__file__).resolve().parents[3] class TestClickHouseProfileDefaults: def test_docker_profiles_do_not_explicitly_override_analyzer(self): ...
32
1,384
posthog
posthog/clickhouse/test/test_raw_sessions_v3_model.py
.py
import datetime from posthog.test.base import ( BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events, snapshot_clickhouse_queries, ) from posthog.clickhouse.client import query_with_columns, sync_execute from posthog.models.raw_sessions.sessions_v3 import ( DISTRIBUTED_RAW_SE...
805
26,604
posthog
posthog/clickhouse/test/test_alter_replicated_validation.py
.py
import unittest from unittest import mock from parameterized import parameterized from posthog.clickhouse.client.connection import DATA_NODE_ROLES, SINGLE_SHARD_DATA_NODE_ROLES, NodeRole from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions class TestAlterReplicatedValidation(unittest.TestCa...
134
5,703
posthog
posthog/clickhouse/test/test_cluster.py
.py
import re import json import uuid from collections import defaultdict from collections.abc import Callable, Iterator, Mapping import pytest from posthog.test.base import materialized from unittest.mock import Mock, patch, sentinel from clickhouse_driver import Client from clickhouse_driver.errors import ServerExcepti...
840
35,445
posthog
posthog/clickhouse/test/test_query_tagging.py
.py
import json import uuid import asyncio from types import SimpleNamespace import pytest from posthog.test.base import BaseTest, ClickhouseTestMixin from parameterized import parameterized from pydantic import ValidationError from posthog.hogql.query import execute_hogql_query from posthog.clickhouse.client import sy...
811
30,720
posthog
posthog/clickhouse/test/test_dmat_dictionary.py
.py
"""Real-ClickHouse integration tests for the dmat slot-assignments dictionary. These tests pin the dict mechanics that the dmat backfill mutation depends on: - `dictHas` returns true for known `(team_id, column_index)` keys, false otherwise. - `dictGetString` returns the inserted property name for known keys. - Reload...
116
4,169
posthog
posthog/clickhouse/test/test_schema.py
.py
import re import uuid from collections.abc import Iterator import pytest from posthog.clickhouse.kafka_engine import CONSUMER_GROUP_EVENTS_JSON_NATIVE_JSON, KAFKA_COLUMNS_WITH_PARTITION from posthog.clickhouse.schema import ( CREATE_KAFKA_TABLE_QUERIES, CREATE_MERGETREE_TABLE_QUERIES, CREATE_TABLE_QUERIES...
130
5,321
posthog
posthog/migration_helpers/test_not_valid_constraint.py
.py
"""Functional tests for AddConstraintNotValid / ValidateConstraint. Each test creates and drops a real table inside the standard test database so we can poke pg_constraint.convalidated directly and exercise the two-phase NOT VALID -> VALIDATE flow against live Postgres. """ import uuid import pytest from django.db ...
271
9,752
posthog
posthog/migration_helpers/test_concurrent_index.py
.py
"""Functional tests for the concurrent-index helpers. Each test creates and drops a real table inside the standard test database so we can poke pg_index.indisvalid directly and assert the helper's recovery path. The table name is unique per test run to avoid colliding with anything else in the schema. """ import uuid...
443
15,387
posthog
posthog/migration_helpers/not_valid_constraint.py
.py
"""Two-phase CHECK constraint helpers: add NOT VALID, then VALIDATE separately. Adding a constraint the normal way (Django's `AddConstraint` -> `ALTER TABLE ... ADD CONSTRAINT ... CHECK (...)`) validates every existing row while holding an ACCESS EXCLUSIVE lock. On a large or hot table that blocks all traffic for the ...
165
7,687
posthog
posthog/migration_helpers/__init__.py
.py
from posthog.migration_helpers.concurrent_index import ( CreateIndexConcurrently, DropIndexConcurrently, SafeAddIndexConcurrently, SafeRemoveIndexConcurrently, ) from posthog.migration_helpers.not_valid_constraint import AddConstraintNotValid, ValidateConstraint from posthog.migration_helpers.not_valid_...
20
633
posthog
posthog/migration_helpers/concurrent_index.py
.py
"""Idempotent CREATE/DROP INDEX CONCURRENTLY operations for Django migrations. The Django built-ins (`AddIndexConcurrently`, `RemoveIndexConcurrently`) emit bare `CREATE/DROP INDEX CONCURRENTLY` with no `IF [NOT] EXISTS`, and there is no hook to disable `lock_timeout` / `statement_timeout`. Under bin/migrate's exponen...
389
15,939
posthog
posthog/migration_helpers/test_not_valid_foreign_key.py
.py
import uuid import pytest from django.db import connection, models, transaction from django.db.migrations.state import ModelState, ProjectState from django.db.utils import IntegrityError from posthog.migration_helpers import AddForeignKeyNotValid, ValidateForeignKey MODEL_NAME = "TmpFkModel" @pytest.fixture def t...
251
9,061
posthog
posthog/migration_helpers/not_valid_foreign_key.py
.py
"""Two-phase FOREIGN KEY helper: add the FK as NOT VALID, then VALIDATE separately. Adding a foreign key the normal way (a plain `ForeignKey` in a model, which Django emits inline in `CREATE TABLE` or as `ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY`) takes a SHARE ROW EXCLUSIVE lock on the *referenced parent* table...
187
9,556
posthog
posthog/resource_limits/evaluator.py
.py
from typing import TYPE_CHECKING from posthog.event_usage import report_user_action from posthog.resource_limits.registry import get_definition if TYPE_CHECKING: from posthog.models.organization import Organization from posthog.models.team.team import Team from posthog.models.user import User def get_li...
69
2,473
posthog
posthog/resource_limits/__init__.py
.py
from posthog.resource_limits.evaluator import check_count_limit, get_limit, get_organization_limit from posthog.resource_limits.registry import REGISTRY, LimitDefinition, LimitKey __all__ = [ "REGISTRY", "LimitDefinition", "LimitKey", "check_count_limit", "get_limit", "get_organization_limit", ...
12
322
posthog
posthog/resource_limits/registry.py
.py
from dataclasses import dataclass, field from enum import StrEnum from typing import Literal PlanTier = Literal["free", "paid", "enterprise"] class LimitKey(StrEnum): """Stable string identifiers for every entry in the catalog. Use these at every call site to avoid typo'd lookups.""" MAX_DASHBOARDS_PER_...
87
3,220
posthog
posthog/resource_limits/test/test_evaluator.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from parameterized import parameterized from posthog.constants import AvailableFeature from posthog.resource_limits import LimitKey, check_count_limit, get_limit, get_organization_limit from posthog.resource_limits.registry import REGISTRY, LimitD...
114
4,165
posthog
posthog/personhog_client/test_metrics_interceptor.py
.py
from __future__ import annotations import pytest from unittest.mock import MagicMock, patch import grpc from parameterized import parameterized from posthog.personhog_client.interceptor import MetricsInterceptor, _MutableClientCallDetails def _make_call_details( method: str = "/personhog.service.v1.PersonHogSe...
126
4,384
posthog
posthog/personhog_client/test_converters.py
.py
import json from datetime import UTC, datetime from types import SimpleNamespace import pytest from parameterized import parameterized from posthog.personhog_client.converters import ( GroupTypeMappingResult, proto_group_to_model, proto_group_type_mapping_to_dict, proto_group_type_mapping_to_result, ...
359
13,448