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/persons_seed.py
.py
"""Direct persons-database reads and writes for local dev and seed management commands. These helpers read, insert, and update persons/groups straight in the persons database via a raw psycopg connection (see :mod:`posthog.persons_db`), bypassing the Django ORM so the persons database can be dropped from Django's ``DA...
209
7,958
posthog
posthog/conftest.py
.py
import os import time import subprocess from collections.abc import Callable from functools import partial from typing import Any from urllib.parse import quote_plus import pytest from posthog.test.base import PostHogTestCase, run_clickhouse_statement_in_parallel try: from hogli_commands.quarantine.pytest_support...
613
26,772
posthog
posthog/local_bootstrap/test_local_bootstrap.py
.py
from datetime import UTC, datetime import pytest from django.conf import settings from parameterized import parameterized from posthog.local_bootstrap.config import BootstrapConfig, BootstrapConfigError, S3Location, TableImportConfig from posthog.local_bootstrap.importer import ( ZERO_UUID, Progress, _a...
217
9,393
posthog
posthog/local_bootstrap/__init__.py
.py
"""Bootstrap a local PostHog project from an S3 dump of the events and persons tables. The dumps are produced by the PostHog S3 batch export feature (Parquet/JSONLines, optionally compressed). See ``posthog/management/commands/bootstrap_local_project.py`` for the CLI entry point. """ from posthog.local_bootstrap.conf...
33
897
posthog
posthog/local_bootstrap/importer.py
.py
from __future__ import annotations import json import uuid from collections.abc import Callable from contextlib import AbstractContextManager from dataclasses import dataclass, field from datetime import UTC, datetime from typing import Any from django.conf import settings from dateutil.parser import isoparse from p...
410
14,804
posthog
posthog/local_bootstrap/config.py
.py
from __future__ import annotations from dataclasses import dataclass, field from typing import Literal # Mirrors the file formats and compression methods supported by the PostHog S3 batch export # feature (see products/batch_exports/.../destinations/constants.py). Kept as a local copy so the # bootstrapper has no imp...
116
3,788
posthog
posthog/local_bootstrap/source.py
.py
from __future__ import annotations import os import gzip import json import tempfile import contextlib from collections.abc import Callable, Iterator from typing import IO, Any import boto3 import pyarrow.parquet as pq from posthog.local_bootstrap.config import ( COMPRESSION_EXTENSIONS, FILE_FORMAT_EXTENSION...
127
5,358
posthog
posthog/management/migration_analysis/operations.py
.py
"""Operation-specific analyzers for Django migration operations.""" import re from typing import Any, Optional from django.db import models from posthog.management.migration_analysis.models import OperationRisk from posthog.management.migration_analysis.utils import VolatileFunctionDetector, check_drop_properly_stag...
1,017
42,547
posthog
posthog/management/migration_analysis/utils.py
.py
"""Utility classes and functions for migration analysis.""" import re from typing import TYPE_CHECKING, Any, Optional from django.apps import apps if TYPE_CHECKING: from posthog.management.migration_analysis.models import OperationRisk class VolatileFunctionDetector: """Detects volatile functions in field ...
326
12,120
posthog
posthog/management/migration_analysis/analyzer.py
.py
"""Main risk analyzer for Django migrations.""" from posthog.management.migration_analysis.models import MigrationRisk, OperationRisk from posthog.management.migration_analysis.operations import ( AddConstraintAnalyzer, AddConstraintNotValidAnalyzer, AddFieldAnalyzer, AddIndexAnalyzer, AddIndexConc...
345
15,190
posthog
posthog/management/migration_analysis/models.py
.py
"""Data models for migration risk analysis.""" from dataclasses import dataclass, field from enum import Enum class RiskLevel(Enum): """Risk level definitions with scoring ranges""" SAFE = ("Safe", 0, 1) NEEDS_REVIEW = ("Needs Review", 2, 3) BLOCKED = ("Blocked", 4, 5) def __init__(self, catego...
73
2,430
posthog
posthog/management/migration_analysis/formatters.py
.py
"""Formatters for displaying migration risk analysis results.""" import json import textwrap from abc import ABC, abstractmethod from posthog.management.migration_analysis.models import MigrationRisk, RiskLevel class RiskFormatter(ABC): """Base class for risk report formatters.""" @abstractmethod def f...
264
9,465
posthog
posthog/management/migration_analysis/__init__.py
.py
""" Migration analysis package for Django migrations. Provides risk analysis and validation tools for database migrations. """
6
128
posthog
posthog/management/migration_analysis/deprecated_field_filter.py
.py
import re class DeprecatedFieldFilter: """ Filters 'Remove field' operations for fields wrapped in deprecate_field(). Django-deprecate-fields hides deprecated fields from model introspection unless 'makemigrations' is in sys.argv. This causes false positives where deprecated fields appear as miss...
184
7,241
posthog
posthog/management/migration_analysis/policies.py
.py
"""PostHog-specific migration policies. These are team coding guidelines, not database safety issues. Policies enforce architectural decisions and coding standards. """ import re from abc import ABC, abstractmethod from pathlib import Path from django.conf import settings from django.db import models from posthog.m...
694
31,454
posthog
posthog/management/migration_analysis/test/test_json_formatter.py
.py
import json import pytest from posthog.management.migration_analysis.formatters import JsonFormatter from posthog.management.migration_analysis.models import MigrationRisk, OperationRisk def _risk(app: str, name: str, score: int, file_path: str | None = None) -> MigrationRisk: return MigrationRisk( path...
72
2,804
posthog
posthog/management/migration_analysis/test/test_risk_analyzer.py
.py
from unittest.mock import MagicMock from django.conf import settings from django.db import migrations, models from parameterized import parameterized from posthog.management.migration_analysis.analyzer import RiskAnalyzer from posthog.management.migration_analysis.models import RiskLevel from posthog.management.migr...
2,559
109,776
posthog
posthog/management/commands/sync_remote_configs.py
.py
from django.core.management.base import BaseCommand from posthog.tasks.remote_config import sync_all_remote_configs class Command(BaseCommand): help = "Sync all RemoteConfigs" def handle(self, *args, **options): print("Syncing RemoteConfigs for all teams...") # noqa: T201 sync_all_remote_co...
13
379
posthog
posthog/management/commands/generate_random_product_tours.py
.py
import json import uuid import random from datetime import timedelta from typing import Any from zoneinfo import ZoneInfo from django.core.management.base import BaseCommand from django.utils import timezone from django.utils.text import slugify from nanoid import generate from posthog.clickhouse.client import sync_...
490
19,705
posthog
posthog/management/commands/migrate_team.py
.py
import logging import datetime as dt from django.core.management.base import BaseCommand, CommandError from django.db import transaction from posthog.models import Team from posthog.temporal.common.client import sync_connect from products.batch_exports.backend.models.batch_export import ( BATCH_EXPORT_INTERVALS,...
302
11,215
posthog
posthog/management/commands/sync_feature_flags.py
.py
# ruff: noqa: T201 allow print statements import re from typing import cast from django.core.management.base import BaseCommand from posthog.models import Team, User from products.feature_flags.backend.models.feature_flag import FeatureFlag # These flags won't be enabled when syncing feature flags # Turn these on ...
122
5,288
posthog
posthog/management/commands/test_ch_migrations_are_safe.py
.py
import os import re import sys import logging from django.core.management.base import BaseCommand, CommandError from git import Repo logger = logging.getLogger(__name__) MIGRATIONS_DIR = "posthog/clickhouse/migrations" MAX_MIGRATION_FILE = os.path.join(MIGRATIONS_DIR, "max_migration.txt") # Pre-existing duplicate ...
141
4,701
posthog
posthog/management/commands/backfill_agentic_provisioning_scope.py
.py
import logging from django.core.management.base import BaseCommand from django.db import transaction from django.utils import timezone from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken logger = logging.getLogger(__name__) class Command(BaseCommand): help = ( "Rehydr...
146
7,109
posthog
posthog/management/commands/setup_local_gateway_credential.py
.py
""" Provision the deterministic local ai-gateway dev credential, end to end: 1. admit the team to the gateway (delegates to `llm_gateway_team`) 2. upsert the `phs_` project-secret key (scope ``llm_gateway:read``) 3. publish its credential blob to the gateway's Redis, synchronously so `bin/start gateway` (resolv...
87
3,743
posthog
posthog/management/commands/clear_temporary_tokens.py
.py
from django.core.management.base import BaseCommand from posthog.models import User BATCH_SIZE = 5000 class Command(BaseCommand): help = "Clear temporary_token for all users (one-time cleanup after migrating to toolbar OAuth)" def add_arguments(self, parser): parser.add_argument("--batch-size", typ...
35
1,205
posthog
posthog/management/commands/reenable_schemas_by_error.py
.py
from datetime import UTC, datetime from django.core.management.base import BaseCommand import structlog from products.warehouse_sources.backend.facade.models import ExternalDataSchema, update_should_sync logger = structlog.get_logger(__name__) class Command(BaseCommand): help = "Re-enable schemas that were au...
113
3,988
posthog
posthog/management/commands/setup_dev.py
.py
from django.core.management.base import BaseCommand from django.db import transaction from django.utils import timezone from posthog.models import EventProperty, PersonalAPIKey, Team, User from posthog.models.utils import hash_key_value from products.cdp.backend.models.plugin import Plugin, PluginConfig, PluginSource...
104
4,718
posthog
posthog/management/commands/fix_invalid_flag_property_types.py
.py
from django.core.management.base import BaseCommand from products.feature_flags.backend.models.feature_flag import FeatureFlag # Valid property types for feature flags (from validate_filters in api/feature_flag.py) VALID_PROPERTY_TYPES = {"person", "cohort", "group", "flag"} # Map of invalid types to their correct r...
88
4,131
posthog
posthog/management/commands/set_recorder_script.py
.py
from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from posthog.models import Team from posthog.sampling import sample_on_property class Command(BaseCommand): help = """ Sets the recorder script for a sample of teams based on team ID hashing. Example usage: ...
84
3,034
posthog
posthog/management/commands/background_delete_model.py
.py
import logging from django.apps import apps from django.core.management.base import BaseCommand, CommandError import structlog from posthog.tasks.tasks import background_delete_model_task logger = structlog.get_logger(__name__) logger.setLevel(logging.INFO) class Command(BaseCommand): help = "Start a backgrou...
128
5,703
posthog
posthog/management/commands/backfill_team_experiment_stats_method.py
.py
from django.core.management.base import BaseCommand from posthog.models import Organization, Team class Command(BaseCommand): help = "Backfill default_experiment_stats_method from Organization to Team" def add_arguments(self, parser): parser.add_argument( "--dry-run", action=...
62
2,357
posthog
posthog/management/commands/generate_dlq_events.py
.py
import json import uuid import random from datetime import datetime, timedelta from typing import Any from django.core.management.base import BaseCommand from posthog.clickhouse.client import sync_execute from posthog.models.team.team import Team class Command(BaseCommand): help = "Generate dead letter queue ev...
345
16,253
posthog
posthog/management/commands/print_hog_stl_table.py
.py
# Print compatibility table from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Print a Hog/HogQL STL compatibility table" def handle(self, *args, **options): from posthog.hogql.functions.mapping import HOGQL_CLICKHOUSE_FUNCTIONS, HOGQL_COMPARISON_MAPPING ...
34
1,201
posthog
posthog/management/commands/reencrypt_flag_payloads.py
.py
from django.core.management.base import BaseCommand from django.db import transaction from django.db.models import QuerySet import structlog from cryptography.fernet import InvalidToken from products.feature_flags.backend.encrypted_flag_payloads import FlagPayloadCodec, flag_payload_codec from products.feature_flags....
105
5,416
posthog
posthog/management/commands/sync_hog_function_templates.py
.py
import time import dataclasses from django.conf import settings from django.core.management.base import BaseCommand import structlog from posthog.cdp.templates import HOG_FUNCTION_TEMPLATES from posthog.cdp.templates.hog_function_template import sync_template_to_db from posthog.plugins.plugin_server_api import get_h...
167
6,319
posthog
posthog/management/commands/generate_persons.py
.py
import random from typing import Any from django.core.management.base import BaseCommand from posthog.models import Team from posthog.models.utils import UUIDT from posthog.persons_db import persons_db_connection from posthog.persons_seed import insert_seed_distinct_id, insert_seed_person class Command(BaseCommand)...
885
23,978
posthog
posthog/management/commands/rotate_temporal_schedule_encryption_key.py
.py
import csv import sys import typing import asyncio import datetime as dt import collections.abc from argparse import ArgumentParser from django.conf import settings from django.core.management.base import BaseCommand import structlog from cryptography.fernet import InvalidToken from rich.console import Console from r...
327
11,434
posthog
posthog/management/commands/start_temporal_worker.py
.py
import os import signal import typing import asyncio import datetime as dt import functools import threading import faulthandler import collections.abc from collections import defaultdict import structlog from temporalio import workflow from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.co...
842
33,599
posthog
posthog/management/commands/fix_person_distinct_ids_after_delete.py
.py
import logging from django.core.management.base import BaseCommand import structlog from posthog.kafka_client.routing import flush_all_producers from posthog.models.person.deletion import reset_all_deleted_person_distinct_ids, reset_deleted_person_distinct_ids logger = structlog.get_logger(__name__) logger.setLevel...
53
1,944
posthog
posthog/management/commands/print_ch_migration_sql.py
.py
# ruff: noqa: T201 allow print statements """Render the SQL operations of one or more ClickHouse migrations. Unlike ``migrate_clickhouse --plan --print-sql``, this command does not connect to ClickHouse. It imports the requested migration modules, walks their ``operations`` list and prints every ``op._sql`` (the strin...
131
5,725
posthog
posthog/management/commands/refresh_hog_flows.py
.py
import time from django.core.management.base import BaseCommand from django.core.paginator import Paginator from django.test import RequestFactory import structlog from products.workflows.backend.api.hog_flow import HogFlowSerializer from products.workflows.backend.models.hog_flow.hog_flow import HogFlow logger = s...
165
6,167
posthog
posthog/management/commands/cleanup_expired_sharing_configs.py
.py
from django.core.management.base import BaseCommand from django.utils import timezone import structlog from posthog.models.sharing_configuration import SharingConfiguration logger = structlog.get_logger(__name__) class Command(BaseCommand): help = "Clean up expired sharing configurations" def add_argument...
43
1,373
posthog
posthog/management/commands/generate_test_events.py
.py
""" Generate test persons and events with evolving person properties. Usage: ./manage.py generate_test_events --team-id=1 --num-persons=10 --events-per-person=5 """ import uuid import random from dataclasses import dataclass, field from datetime import UTC, datetime from enum import Enum from typing import Any f...
244
8,363
posthog
posthog/management/commands/apply_persons_migrations.py
.py
"""Apply persons SQL migrations. Reads SQL migration files from rust/persons_migrations/ and executes them against the persons database identified by PERSONS_DB_WRITER_URL. Hobby deploys keep persons in the main database and skip the partitioning migrations (via --hobby); local dev and production apply all migrations....
215
8,410
posthog
posthog/management/commands/rerun_google_ads_failed_invocations.py
.py
""" Trigger reruns of failed invocations for every active Google Ads destination across every team. Written for the 2026-07-02 incident where Google Ads returned 401 UNAUTHENTICATED (`DEVELOPER_TOKEN_INVALID`) for every send, surfaced on our side as `error_kind='http_4xx'`. Once operators have swapped the developer to...
214
8,405
posthog
posthog/management/commands/backfill_workflows_slack_integration.py
.py
import copy import time import logging from typing import Any from django.core.management.base import BaseCommand from django.db import transaction from products.workflows.backend.models.hog_flow.hog_flow import HogFlow logger = logging.getLogger(__name__) # One-off backfill for team 2: the Slack integration was r...
145
5,717
posthog
posthog/management/commands/generate_stripe_app_tokens.py
.py
""" Generate PostHog OAuth tokens for the Stripe App in local development. Reuses existing valid tokens if available, otherwise creates new ones. Prints the tokens so you can paste them into the Stripe App's dev mode UI. Usage: ./manage.py generate_stripe_app_tokens --team-id=1 ./manage.py generate_stripe_app...
221
9,342
posthog
posthog/management/commands/reset_test_clickhouse_db.py
.py
from posthog.test.base import reset_clickhouse_database from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Resets the ClickHouse database for the test environment" # NOTE: This commands enables `TEST=1` environment variable via a hack # in posthog/settings/base_varia...
16
677
posthog
posthog/management/commands/analyze_flags_cache_sizes.py
.py
""" Management command to analyze actual flags cache sizes for accurate memory estimation. """ import gzip import json import statistics from posthog.management.commands._base_hypercache_command import BaseHyperCacheCommand from posthog.models.team import Team from products.feature_flags.backend.flags_cache import (...
192
8,383
posthog
posthog/management/commands/run_geoip.py
.py
import logging from pprint import pprint from django.contrib.gis.geoip2 import GeoIP2 from django.core.management.base import BaseCommand logging.getLogger("kafka").setLevel(logging.ERROR) # Hide kafka-python's logspam class Command(BaseCommand): help = "Run geoip2 for an ip address, try `DEBUG=1 ./manage.py r...
29
901
posthog
posthog/management/commands/generate_random_surveys.py
.py
import json import uuid import random from datetime import timedelta from typing import Any, Literal, TypedDict from zoneinfo import ZoneInfo from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from posthog.clickhouse.client import sync_execute from posthog.models impor...
1,165
58,235
posthog
posthog/management/commands/analyze_migration_risk.py
.py
# ruff: noqa: T201 allow print statements import os import sys from django.core.management.base import BaseCommand from django.db import migrations from posthog.management.migration_analysis.analyzer import RiskAnalyzer from posthog.management.migration_analysis.deprecated_field_filter import DeprecatedFieldFilter f...
203
8,223
posthog
posthog/management/commands/resave_hog_functions.py
.py
from django.core.management.base import BaseCommand from django.db import connection from products.cdp.backend.models.hog_functions.hog_function import HogFunction class Command(BaseCommand): help = "Re-enables HogFunctions that are connected to integrations by triggering a reload on the plugin server" def ...
41
1,648
posthog
posthog/management/commands/generate_demo_data.py
.py
# ruff: noqa: T201 allow print statements import sys import logging import secrets import datetime as dt from time import monotonic from typing import Optional from urllib.parse import quote from django.conf import settings from django.core import exceptions from django.core.management.base import BaseCommand, Comman...
417
18,190
posthog
posthog/management/commands/populate_experiment_timeseries.py
.py
import traceback from datetime import date, datetime, timedelta from typing import Union from zoneinfo import ZoneInfo from django.core.management.base import BaseCommand from django.utils import timezone from posthog.schema import ExperimentFunnelMetric, ExperimentMeanMetric, ExperimentQuery, ExperimentRatioMetric ...
176
7,172
posthog
posthog/management/commands/migrate_product_databases.py
.py
from __future__ import annotations from collections import defaultdict from django.conf import settings from django.core.management import call_command from django.core.management.base import BaseCommand import psycopg from psycopg import sql from posthog.product_db_router import get_product_db_routes from posthog....
73
2,717
posthog
posthog/management/commands/refresh_activity_log_fields_cache.py
.py
from django.core.management.base import BaseCommand from posthog.api.advanced_activity_logs.constants import SMALL_ORG_THRESHOLD from posthog.tasks.tasks import refresh_activity_log_fields_cache class Command(BaseCommand): help = "Refresh activity log fields cache for large organizations" def add_arguments(...
80
3,594
posthog
posthog/management/commands/devbox_migrate.py
.py
from django.core.management import call_command from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Run all migrations (Django, persons, ClickHouse) in a single process" def handle(self, *args, **options): self.stdout.write("Running Django migrations...") c...
19
666
posthog
posthog/management/commands/sync_persons_to_clickhouse.py
.py
"""Reconcile a team's person, distinct-id, and group rows from Postgres to ClickHouse. LOCAL/DEV USE ONLY for now: this loads the whole team's rows into memory (no batching), so it is not safe to run against large production teams. It exists to seed local ClickHouse from the local persons database (e.g. via the genera...
261
11,299
posthog
posthog/management/commands/setup_orphan_test_data.py
.py
""" Management command to create test data for sync_person_distinct_ids workflow. Creates orphaned persons in ClickHouse with various scenarios: - Fixable: Person in CH + PG, DID only in PG (should be synced) - Truly orphaned: Person in CH + PG, no DID anywhere (report only) - CH-only orphan: Person only in CH (should...
236
9,903
posthog
posthog/management/commands/backfill_distinct_id_overrides.py
.py
from __future__ import annotations import logging from collections.abc import Sequence from dataclasses import dataclass from django.core.management.base import BaseCommand, CommandError import structlog from posthog.clickhouse.client.execute import sync_execute from posthog.models.team.team import Team logger = s...
109
3,721
posthog
posthog/management/commands/migrate_plugins_to_hog_functions.py
.py
from django.core.management.base import BaseCommand from posthog.cdp.migrations import migrate_legacy_plugins class Command(BaseCommand): help = "Migrate plugins to HogFunctions" def add_arguments(self, parser): parser.add_argument( "--dry-run", action="store_true", ...
40
1,619
posthog
posthog/management/commands/audit_encrypted_field_keys.py
.py
import json import base64 import binascii from dataclasses import ( dataclass, field as dataclass_field, ) from django.apps import apps from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db import connections, router from cryptography.fernet import F...
299
13,107
posthog
posthog/management/commands/send_usage_report.py
.py
from django.core.management.base import BaseCommand from django.utils import timezone from posthog.tasks.usage_report import send_all_org_usage_reports class Command(BaseCommand): help = "Send the usage report for a given day" def add_arguments(self, parser): parser.add_argument("--dry-run", type=bo...
58
2,101
posthog
posthog/management/commands/survey_cohort_bytecode_stl.py
.py
"""Survey HogVM bytecode (STL functions + opcodes) across realtime cohorts, flagging Rust HogVM gaps.""" import json from collections import Counter, defaultdict from collections.abc import Iterable, Iterator from datetime import UTC, datetime from typing import Any from django.core.management.base import BaseCommand...
373
14,158
posthog
posthog/management/commands/migrate_clickhouse.py
.py
# ruff: noqa: T201 allow print statements import datetime from textwrap import indent from django.conf import settings from django.core.management.base import BaseCommand from cachetools import cached from infi.clickhouse_orm import Database from infi.clickhouse_orm.migrations import MigrationHistory from infi.click...
180
7,847
posthog
posthog/management/commands/update_hog_function_code.py
.py
import time from typing import TypedDict from django.core.management.base import BaseCommand from django.core.paginator import Paginator import structlog from posthog.cdp.validation import compile_hog from products.cdp.backend.models.hog_functions.hog_function import HogFunction logger = structlog.get_logger(__nam...
179
9,821
posthog
posthog/management/commands/stream_live_events.py
.py
""" Stream live demo events continuously for local development. Sends events through capture-rs so they appear in the livestream service. Usage: python manage.py stream_live_events # Run in foreground python manage.py stream_live_events & # Run in background python manage.py stream...
114
4,137
posthog
posthog/management/commands/verify_team_metadata_cache.py
.py
""" Management command to verify team metadata cache consistency. Compares cached data against database to detect discrepancies. IMPORTANT: This command requires FLAGS_REDIS_URL to be set. It will error if the dedicated flags cache is not configured to prevent misleading results. Usage: # Verify all teams py...
67
2,277
posthog
posthog/management/commands/bootstrap_local_project.py
.py
import secrets from typing import Any from django.conf import settings from django.core.management.base import BaseCommand, CommandError from posthog.local_bootstrap import ( BootstrapConfig, BootstrapConfigError, DiscoveredFile, Progress, S3Location, TableImportConfig, TablePlan, list...
230
10,333
posthog
posthog/management/commands/create_channel_definitions_file.py
.py
import re import json import asyncio import subprocess from collections import OrderedDict from dataclasses import dataclass from enum import StrEnum from typing import Optional from django.core.management.base import BaseCommand import aiohttp import structlog OUTPUT_FILE = "posthog/models/channel_type/channel_defi...
610
25,281
posthog
posthog/management/commands/flag_legacy_oauth_integrations.py
.py
from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db.models import F, Func, JSONField, Value import structlog from posthog.models.integration import CONFIG_LEGACY_OAUTH_CLIENT, Integration, issuing_oauth_client_ids logger = structlog.get_logger(__name__) ...
76
3,239
posthog
posthog/management/commands/warm_team_metadata_cache.py
.py
""" Management command to warm the team metadata cache. IMPORTANT: This command requires FLAGS_REDIS_URL to be set. It will error if the dedicated flags cache is not configured to prevent warming the wrong cache. Usage: # Initial cache warm (preserves existing caches) python manage.py warm_team_metadata_cache...
60
2,076
posthog
posthog/management/commands/migrate_hooks.py
.py
from django.core.management.base import BaseCommand from django.core.paginator import Paginator from posthog.plugins.plugin_server_api import reload_all_hog_functions_on_workers from posthog.settings.ee import EE_AVAILABLE from products.cdp.backend.models.hog_functions.hog_function import HogFunction def migrate_ho...
96
3,449
posthog
posthog/management/commands/create_ch_migration.py
.py
import os from django.core.management.base import BaseCommand from django.utils.timezone import now MIGRATION_PATH = "ee/clickhouse/migrations" FILE_DEFAULT = """ from infi.clickhouse_orm import migrations # type: ignore operations = [] """ # ex: python manage.py create_ch_migration <name of migration> class Comma...
49
1,214
posthog
posthog/management/commands/setup_test_environment.py
.py
from django.core.management.base import BaseCommand from django.test.runner import DiscoverRunner as TestRunner from infi.clickhouse_orm import Database from posthog.clickhouse.schema import ( CREATE_DATA_QUERIES, CREATE_DICTIONARY_QUERIES, CREATE_DISTRIBUTED_TABLE_QUERIES, CREATE_KAFKA_TABLE_QUERIES,...
122
4,424
posthog
posthog/management/commands/register_temporal_search_attributes.py
.py
import gc import asyncio import logging from django.core.management.base import BaseCommand import structlog import temporalio.api.enums.v1 as enums import temporalio.api.operatorservice.v1 as ops from temporalio.common import SearchAttributeKey from posthog.temporal.common.client import async_connect from posthog.t...
99
3,541
posthog
posthog/management/commands/js_snippet_version.py
.py
import json from datetime import UTC, datetime from django.conf import settings from django.core.cache import cache from django.core.management.base import BaseCommand, CommandError from posthog.models.js_snippet_versioning import ( REDIS_POINTER_MAP_KEY, S3_MANIFEST_KEY, S3_VERSIONS_KEY, ManifestSync...
193
7,300
posthog
posthog/management/commands/send_ai_observability_usage_report.py
.py
from typing import Any from django.core.cache import cache from django.core.management.base import BaseCommand, CommandError, CommandParser from django.utils import timezone import structlog from dateutil import parser from posthog.tasks.ai_observability_usage_report import ( USAGE_REPORT_DISPATCH_LOCK_TIMEOUT_S...
124
5,870
posthog
posthog/management/commands/run_autoreload_celery.py
.py
import os import sys import threading from typing import Literal from django.conf import settings from django.core.management.base import BaseCommand from posthog.tasks.utils import CeleryQueue # Directories to watch for .py changes WATCH_DIRS = ["posthog", "ee", "products"] class Command(BaseCommand): help = ...
129
4,663
posthog
posthog/management/commands/partition.py
.py
# ruff: noqa: T201 allow print statements import os from django.core.management.base import BaseCommand from django.db import connection def load_sql(filename): path = os.path.join(os.path.dirname(__file__), "../sql/", filename) with open(path, encoding="utf_8") as f: return f.read() class Command...
52
1,907
posthog
posthog/management/commands/test_migrations_are_safe.py
.py
# ruff: noqa: T201 allow print statements import os import re import sys import select from typing import Optional from django.core.management import call_command from django.core.management.base import BaseCommand, CommandError def _get_new_tables(sql: str): return re.findall(r'CREATE TABLE "([a-zA-Z0-9_]*)"',...
219
11,187
posthog
posthog/management/commands/llm_gateway_team.py
.py
""" Inspect or flip a team's llm-gateway admission state. Usage: python manage.py llm_gateway_team enable 42 python manage.py llm_gateway_team enable phc_demo python manage.py llm_gateway_team unenable 42 python manage.py llm_gateway_team revoke 42 python manage.py llm_gateway_team unrevoke 42 ...
164
6,880
posthog
posthog/management/commands/sync_user_settings.py
.py
# ruff: noqa: T201 allow print statements import os from typing import Any from django.core.management.base import BaseCommand, CommandError import requests from posthog.models import Team, User from posthog.models.file_system.file_system_shortcut import FileSystemShortcut from posthog.models.user_home_settings imp...
313
11,844
posthog
posthog/management/commands/find_enum_collisions.py
.py
"""Find drf-spectacular enum naming collisions and suggest ENUM_NAME_OVERRIDES entries. Replicates the collision detection logic from drf_spectacular.hooks.postprocess_schema_enums but prints actionable output instead of opaque warnings. Run this when `hogli build:openapi-schema` fails with messages like "enum naming...
107
5,022
posthog
posthog/management/commands/invalidate_flags_auth_cache.py
.py
""" Invalidate flags-service auth cache entries for a team. Clears cached token entries in Redis so the Rust feature-flags service re-validates against Postgres on the next request. Does NOT revoke the tokens themselves. Covers team secret tokens, project secret API keys, and personal API keys that have access to the ...
73
2,766
posthog
posthog/management/commands/schedule_temporal_workflows.py
.py
from django.core.management.base import BaseCommand import structlog from posthog.temporal.schedule import init_schedules logger = structlog.get_logger(__name__) class Command(BaseCommand): help = "Schedule Temporal Workflows" def handle(self, *args, **options): logger.info("Scheduling Temporal Wo...
17
386
posthog
posthog/management/commands/get_temporal_workflow_count.py
.py
import asyncio import logging from django.conf import settings from django.core.management.base import BaseCommand from prometheus_client import CollectorRegistry, Gauge, push_to_gateway from posthog.temporal.common.client import connect class Command(BaseCommand): help = "Get a count of Temporal Workflow exec...
112
3,904
posthog
posthog/management/commands/sync_feature_flags_from_api.py
.py
import json from collections.abc import Callable from django.core.management.base import BaseCommand import requests from posthog.models import Project, User from posthog.ph_client import PH_US_API_KEY from products.feature_flags.backend.models.feature_flag import FeatureFlag def _build_filters(flag_data: dict) -...
169
6,615
posthog
posthog/management/commands/sync_available_features.py
.py
import logging from django.core.management.base import BaseCommand import structlog from posthog.tasks.sync_all_organization_available_product_features import ( sync_all_organization_available_product_features, ) logger = structlog.get_logger(__name__) logger.setLevel(logging.INFO) class Command(BaseCommand):...
21
541
posthog
posthog/management/commands/notify_helm_install.py
.py
# ruff: noqa: T201 allow print statements # ruff: noqa: T203 allow pprint statements import os from pprint import pprint from django.conf import settings from django.core.management.base import BaseCommand import posthoganalytics from posthog.utils import get_helm_info_env, get_machine_id class Command(BaseComman...
39
1,235
posthog
posthog/management/commands/warm_remote_configs_cache.py
.py
""" One-shot backfill that writes already-built RemoteConfig.config blobs into the dedicated flags Redis so the Rust feature-flags service stops falling through to S3 on /flags config_response. After the writer wiring fix (RemoteConfig.get_hypercache() now targets the dedicated FLAGS_REDIS cache when configured), the ...
142
5,816
posthog
posthog/management/commands/sandbox_migrate.py
.py
"""Run all database migrations in a single Django process. Combines migrate, apply_persons_migrations, and migrate_clickhouse into one command to avoid three separate Django cold starts (~15s each). Used by the sandbox entrypoint to speed up boot time. Migrations run sequentially because ClickHouse migrations call ge...
53
1,893
posthog
posthog/management/commands/calculate_cohort.py
.py
import logging import traceback from django.core.management.base import BaseCommand from posthog.tasks.calculate_cohort import calculate_cohort_ch, increment_version_and_enqueue_calculate_cohort from products.cohorts.backend.models.cohort import Cohort logger = logging.getLogger(__name__) class Command(BaseComman...
40
1,395
posthog
posthog/management/commands/backfill_raw_sessions_table.py
.py
from __future__ import annotations import math import time import logging from dataclasses import dataclass from datetime import datetime, timedelta from typing import Optional from django.core.management.base import BaseCommand import structlog from posthog.clickhouse.client.connection import Workload from posthog...
160
6,280
posthog
posthog/management/commands/fix_orphaned_ch_persons.py
.py
import logging import argparse from django.core.management.base import BaseCommand import structlog from posthog.kafka_client.routing import flush_all_producers from posthog.models.person.deletion import OrphanRepairResult, find_orphaned_ch_persons, tombstone_orphaned_ch_persons logger = structlog.get_logger(__name...
113
4,205
posthog
posthog/management/commands/start_delete_mutation.py
.py
import logging from django.core.management.base import BaseCommand import structlog from posthog.tasks.tasks import clickhouse_clear_removed_data logger = structlog.get_logger(__name__) logger.setLevel(logging.INFO) class Command(BaseCommand): help = ( "Kick off the job to remove all data associated w...
27
638
posthog
posthog/management/commands/migrate_legacy_geoip_transformations.py
.py
import time from django.core.management.base import BaseCommand import structlog from posthog.cdp.validation import compile_hog from products.cdp.backend.models.hog_function_template import HogFunctionTemplate from products.cdp.backend.models.hog_functions.hog_function import HogFunction logger = structlog.get_log...
116
4,608
posthog
posthog/management/commands/refresh_hog_functions.py
.py
import time from django.core.management.base import BaseCommand from django.core.paginator import Paginator import structlog from products.cdp.backend.models.hog_functions.hog_function import HogFunction logger = structlog.get_logger(__name__) class Command(BaseCommand): help = "Refresh HogFunctions (both ena...
89
3,117
posthog
posthog/management/commands/migrate_experiments.py
.py
import logging from datetime import datetime from django.core.management.base import BaseCommand from posthog.schema import ExperimentFunnelsQuery, ExperimentTrendsQuery from posthog.exceptions_capture import capture_exception from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query fr...
79
3,137