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/management/commands/execute_temporal_workflow.py
.py
import json import asyncio import logging from uuid import uuid4 from django.conf import settings from django.core.management.base import BaseCommand from temporalio.common import RetryPolicy, WorkflowIDReusePolicy from posthog.temporal.ai import AI_WORKFLOWS from posthog.temporal.ai_observability import WORKFLOWS a...
184
7,916
posthog
posthog/management/commands/update_billing_quotas.py
.py
import pprint from django.core.management.base import BaseCommand from ee.billing.quota_limiting import update_all_orgs_billing_quotas class Command(BaseCommand): help = "Update billing rate limiting for all organizations" def add_arguments(self, parser): parser.add_argument("--dry-run", type=bool,...
38
1,580
posthog
posthog/management/commands/backfill_project_ids.py
.py
import time from django.core.management.base import BaseCommand from django.db import connection class Command(BaseCommand): help = "Backfill project_id in action tables from posthog_team.project_id in batches" def add_arguments(self, parser): parser.add_argument("--table-name", type=str, required=T...
167
7,145
posthog
posthog/management/commands/export_distinct_ids.py
.py
import random from django.conf import settings from django.core.management.base import BaseCommand from posthog.models import Team from posthog.persons_db import persons_db_connection class Command(BaseCommand): help = "Export distinct IDs to a text file for static cohort import" def add_arguments(self, pa...
152
5,987
posthog
posthog/management/commands/ensure_migration_defaults.py
.py
from __future__ import annotations import importlib from typing import Any from django.apps import apps from django.core.management.base import BaseCommand from posthog.models.data_color_theme import DataColorTheme from products.dashboards.backend.models.dashboard_templates import DashboardTemplate from products.de...
228
9,109
posthog
posthog/management/commands/change_plugin_private_access.py
.py
import uuid import logging from django.core.management import CommandError from django.core.management.base import BaseCommand import structlog from posthog.models import Organization from products.cdp.backend.models.plugin import Plugin logger = structlog.get_logger(__name__) logger.setLevel(logging.INFO) class...
70
2,423
posthog
posthog/management/commands/sync_import_pipeline_schedules.py
.py
from django.core.management.base import BaseCommand from products.data_warehouse.backend.facade.api import external_data_workflow_exists, sync_external_data_job_workflow from products.warehouse_sources.backend.facade.models import ExternalDataSchema class Command(BaseCommand): help = "Sync data warehouse import ...
25
1,104
posthog
posthog/management/commands/setup_local_api_key.py
.py
# ruff: noqa: T201 allow print statements """ Creates a deterministic personal API key for local development. Usage: python manage.py setup_local_api_key The key value is fixed so it survives database resets. Safety: Only runs when DEBUG=True and CLOUD_DEPLOYMENT is unset. """ from django.conf import settings f...
131
5,507
posthog
posthog/management/commands/start_temporal_workflow.py
.py
import asyncio import logging from uuid import uuid4 from django.conf import settings from django.core.management.base import BaseCommand from temporalio.common import RetryPolicy, WorkflowIDReusePolicy from posthog.temporal.ai import AI_WORKFLOWS from posthog.temporal.common.client import connect from posthog.tempo...
184
7,933
posthog
posthog/management/commands/migrate_retention_show_mean.py
.py
from django.core.management.base import BaseCommand from django.db import transaction from products.product_analytics.backend.models.insight import Insight def migrate_show_mean_from_boolean_to_string(batch_size: int, live_run: bool = False) -> None: """ Migrate the showMean boolean field to meanRetentionCal...
69
2,892
posthog
posthog/management/commands/plugin_server_load_test.py
.py
import sys import time import logging import secrets import datetime as dt import dataclasses from itertools import chain from django.conf import settings from django.core.management.base import BaseCommand import structlog from kafka import KafkaAdminClient, KafkaConsumer, TopicPartition from posthog.api.capture im...
153
5,388
posthog
posthog/management/commands/run_rbac_migrations.py
.py
import logging from datetime import datetime from typing import Any from django.core.management.base import BaseCommand import structlog from posthog.models.organization import Organization from posthog.rbac.migrations.rbac_dashboard_migration import rbac_dashboard_access_control_migration from posthog.rbac.migratio...
286
12,525
posthog
posthog/management/commands/resave_cohorts.py
.py
from __future__ import annotations from typing import Any from django.core.management.base import BaseCommand, CommandParser import structlog from posthog.api.cohort import validate_filters_and_compute_realtime_support from posthog.models.team.team import Team from products.cohorts.backend.models.cohort import Coh...
294
12,452
posthog
posthog/management/commands/migrate_replay_retention.py
.py
from django.core.management.base import BaseCommand from django.core.paginator import Paginator from posthog.constants import AvailableFeature from posthog.models.team import Team class Command(BaseCommand): help = "Migrate teams from legacy Replay retention to 30d/90d retention" def add_arguments(self, par...
61
2,456
posthog
posthog/management/commands/sync_from_billing.py
.py
from django.core.management.base import BaseCommand from posthog.models import Organization from posthog.tasks.sync_billing import sync_from_billing class Command(BaseCommand): help = "Sync latest from billing" def add_arguments(self, parser): parser.add_argument("--organization-ids", type=str, help...
40
1,458
posthog
posthog/management/commands/analyze_team_cache_sizes.py
.py
""" Management command to analyze actual team cache sizes for accurate memory estimation. IMPORTANT: This command requires FLAGS_REDIS_URL to be set. It will error if the dedicated flags cache is not configured to prevent analyzing the wrong cache. """ import gzip import json import statistics from posthog.managemen...
175
7,860
posthog
posthog/management/commands/cleanup_orphaned_vercel_billing.py
.py
from django.core.management.base import BaseCommand, CommandError from posthog.cloud_utils import get_cached_instance_license from posthog.models import Organization from posthog.models.organization import OrganizationMembership from posthog.models.organization_integration import OrganizationIntegration from ee.billi...
131
4,976
posthog
posthog/management/commands/seed_oauth_app_scopes.py
.py
from typing import Any from django.core.management.base import BaseCommand, CommandError, CommandParser from posthog.models.oauth import OAuthApplication from posthog.scopes import ( ALL_SCOPES, DEFAULT_CEILING_SENTINEL, OAUTH_SCOPES_HIDDEN, PRIVILEGED_SCOPES, effective_ceiling, ) def parse_scop...
118
4,902
posthog
posthog/management/commands/score_one_chunk.py
.py
"""Manual smoke-test for the session surfacing scoring pipeline. Pulls one bucket of unscored sessions from ClickHouse, runs the XGBoost booster, and prints the scores. Read-only (writes nothing back). Handy to verify the model loads and predicts in a fresh env, eyeball the score distribution, or reproduce a prod scor...
114
4,553
posthog
posthog/management/commands/restore_session_recording_keys.py
.py
import json import time from django.core.management.base import BaseCommand, CommandError import boto3 from botocore.exceptions import ClientError from posthog.clickhouse.client import sync_execute from posthog.settings.data_stores import CLICKHOUSE_CLUSTER LIVE_TABLE_NAME = "session-recording-keys" BACKUP_VAULT_NA...
314
13,195
posthog
posthog/management/commands/change_plugin_config_referenced_plugin.py
.py
import time from django.core.management.base import BaseCommand from products.cdp.backend.models.plugin import Plugin, PluginConfig class Command(BaseCommand): help = "Set the plugin_id of a given config or set of configs to something else" def add_arguments(self, parser): parser.add_argument( ...
57
2,419
posthog
posthog/management/commands/verify_flags_cache.py
.py
""" Management command to verify flags cache consistency. Compares cached flags 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 pyth...
105
3,969
posthog
posthog/management/commands/send_digest_to_team.py
.py
from django.core.management.base import BaseCommand, CommandError from posthog.models import Team from posthog.tasks.email import send_team_hog_functions_digest class Command(BaseCommand): help = "Send HogFunctions digest email to a specific team to test notification logic" def add_arguments(self, parser): ...
40
1,423
posthog
posthog/management/commands/migrate.py
.py
"""Custom migrate command with migration caching for worktree workflows. Extends Django's migrate command to: 1. Check for orphaned migrations before applying new ones 2. Offer to automatically roll back orphaned migrations 3. Cache migration files after applying them for later rollback This enables proper schema rol...
318
13,062
posthog
posthog/management/commands/fingerprint_embeddings_backfill.py
.py
import json import logging from datetime import timedelta from typing import TYPE_CHECKING from django.apps import apps from django.core.management.base import BaseCommand import structlog from posthog.clickhouse.client.execute import sync_execute from posthog.kafka_client.routing import producer_scope from posthog....
138
5,138
posthog
posthog/management/commands/backfill_insights_query_metadata.py
.py
from __future__ import annotations import math import time from datetime import datetime from django.core.management.base import BaseCommand from django.db import transaction from django.db.models import Q import structlog from posthog.hogql_queries.query_metadata import InsightQueryMetadata from products.product_...
213
8,617
posthog
posthog/management/commands/sync_replicated_schema.py
.py
import re import logging from collections import defaultdict from django.conf import settings from django.core.management.base import BaseCommand import structlog from posthog.clickhouse.client import sync_execute from posthog.clickhouse.query_tagging import Feature, Product, tags_context from posthog.clickhouse.sch...
118
4,347
posthog
posthog/management/commands/migrate_ses_tenants.py
.py
import logging from collections.abc import Iterable from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.core.paginator import Paginator from django.db.models import Q import boto3 from botocore.exceptions import BotoCoreError, ClientError from posthog.models...
199
8,352
posthog
posthog/management/commands/backfill_persons_and_groups_on_events.py
.py
# ruff: noqa: T201 allow print statements import logging from time import sleep from typing import Any from uuid import uuid4 from django.conf import settings from django.core.management.base import BaseCommand import structlog from posthog.clickhouse.client import sync_execute from posthog.clickhouse.query_tagging...
207
6,770
posthog
posthog/management/commands/upload_surfacing_model.py
.py
"""Upload a trained XGBoost booster (.ubj) to object storage. Uses `posthog.storage.object_storage` so it works against prod S3, staging, and local object storage with no config changes. After upload, set on the worker: SESSION_SURFACING_MODEL_S3_URI=s3://<bucket>/<key> Examples: ./bin/python manage.py upload...
88
3,556
posthog
posthog/management/commands/verify_flag_definitions_cache.py
.py
""" Management command to verify flag definitions cache consistency. Compares cached flag definitions data against database to detect discrepancies. When --fix is used, the cache is updated to match the database. Usage: # Verify all teams python manage.py verify_flag_definitions_cache # Verify specific t...
102
3,944
posthog
posthog/management/commands/backfill_hogflow_billable_action_types.py
.py
import time import logging from django.core.management.base import BaseCommand from django.core.paginator import Paginator from django.db import transaction from products.workflows.backend.models.hog_flow.hog_flow import BILLABLE_ACTION_TYPES, HogFlow logger = logging.getLogger(__name__) class Command(BaseCommand)...
145
5,596
posthog
posthog/management/commands/sync_to_billing.py
.py
from django.core.management.base import BaseCommand from posthog.models import Organization from posthog.tasks.sync_billing import sync_members_to_billing class Command(BaseCommand): help = "Run a sync to send to billing" def add_arguments(self, parser): parser.add_argument( "--action", ...
50
1,866
posthog
posthog/management/commands/sync_exceptions_to_clickhouse.py
.py
import logging from typing import TYPE_CHECKING from django.apps import apps from django.core.management.base import BaseCommand import structlog from posthog.clickhouse.client.execute import sync_execute from posthog.kafka_client.routing import flush_all_producers from products.error_tracking.backend.facade import...
120
4,705
posthog
posthog/management/commands/report_migration_metric.py
.py
import logging from django.conf import settings from django.core.management.base import BaseCommand from prometheus_client import CollectorRegistry, Gauge, push_to_gateway logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Report Django migration metrics to Prometheus pushgateway" de...
79
2,470
posthog
posthog/management/commands/generate_bot_demo_data.py
.py
import random from datetime import timedelta from uuid import uuid4 from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from posthog.models import Team from posthog.models.event.util import create_event from products.demo.backend.facade.api import ( SITE_URL, U...
233
6,973
posthog
posthog/management/commands/backfill_billing_organization_users.py
.py
import csv from django.core.management import BaseCommand import structlog from posthog.models.organization import Organization, OrganizationMembership from ee.billing.billing_manager import BillingManager logger = structlog.get_logger(__name__) class Command(BaseCommand): """ Used to sync organization_u...
67
2,142
posthog
posthog/management/commands/_base_hypercache_command.py
.py
""" Base class for HyperCache management commands. Provides common utilities for HyperCache management commands. This is specific to HyperCache instances (feature flags, team metadata, etc.). For other cache types, create a different base class. """ from django.conf import settings from django.core.management.base im...
978
38,083
posthog
posthog/management/commands/shell.py
.py
import logging from django.conf import settings from django.core.management.commands.shell import Command as DjangoShellCommand class Command(DjangoShellCommand): """Quieter `manage.py shell`. Startup logging is forced to ERROR in settings while an interactive shell is detected (see posthog/settings/log...
30
1,294
posthog
posthog/management/commands/warm_flag_definitions_cache.py
.py
""" Management command to warm the flag definitions cache used for SDK local evaluation. Usage: # Initial cache warm (preserves existing caches) python manage.py warm_flag_definitions_cache # Warm specific teams python manage.py warm_flag_definitions_cache --team-ids 12345 67890 # Custom batch si...
53
1,933
posthog
posthog/management/commands/generate_experiment_data.py
.py
import sys import json import time import uuid import random import logging from datetime import datetime, timedelta from typing import Any, Literal, Union from django.conf import settings from django.core.management.base import BaseCommand import posthoganalytics from pydantic import BaseModel, Field, ValidationErro...
763
26,777
posthog
posthog/management/commands/run_async_migrations.py
.py
import logging from collections.abc import Sequence from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand import structlog from semantic_version.base import Version from posthog.async_migrations.runner import complete_migration, is_migration_dependency_fulfilled,...
165
6,583
posthog
posthog/management/commands/api_keys.py
.py
# ruff: noqa: T201 allow print statements from django.core.management.base import BaseCommand from posthog.models import Team class Command(BaseCommand): help = "Get project tokens through command line instead of having to go through settings" def handle(self, *args, **options): for team in Team.ob...
14
427
posthog
posthog/management/commands/warm_flags_cache.py
.py
""" Management command to warm the flags 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_flags_cache # Warm spe...
61
2,052
posthog
posthog/management/commands/apply_llm_metric.py
.py
from django.conf import settings from django.core.management.base import BaseCommand, CommandError from posthog.models import User from products.experiments.backend.llm_metric_templates import TEMPLATE_NAMES, apply_metric_to_experiment from products.experiments.backend.models.experiment import Experiment class Comm...
62
2,284
posthog
posthog/management/commands/test/test_llm_gateway_team.py
.py
from datetime import UTC, datetime from decimal import Decimal from io import StringIO from posthog.test.base import BaseTest from unittest.mock import patch from django.core.management import call_command from django.core.management.base import CommandError from parameterized import parameterized from posthog.mode...
162
7,163
posthog
posthog/management/commands/test/test_resave_hog_functions.py
.py
from posthog.test.base import BaseTest from unittest.mock import call, patch from django.core.management import call_command from posthog.models.integration import Integration from products.cdp.backend.models.hog_functions.hog_function import HogFunction class TestResaveHogFunctions(BaseTest): def setUp(self):...
103
4,176
posthog
posthog/management/commands/test/test_refresh_hog_flows.py
.py
from io import StringIO from posthog.test.base import BaseTest from unittest.mock import patch from django.core.management import call_command from posthog.management.commands.refresh_hog_flows import remove_event_filters_from_conditionals from posthog.models import Team from products.workflows.backend.models.hog_f...
400
16,354
posthog
posthog/management/commands/test/test_warm_remote_configs_cache.py
.py
from io import StringIO from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from django.core.management import call_command from django.core.management.base import CommandError from django.test import override_settings from parameterized import parameterized from posthog.caching.flags_...
145
6,174
posthog
posthog/management/commands/test/test_rotate_temporal_schedule_encryption_key.py
.py
import csv import uuid import asyncio import datetime as dt from io import StringIO import pytest from django.core.management import call_command from cryptography.fernet import InvalidToken from temporalio.client import ( Client, Schedule, ScheduleActionStartWorkflow, ScheduleDescription, Schedu...
315
11,438
posthog
posthog/management/commands/test/test_flag_legacy_oauth_integrations.py
.py
import json import base64 from posthog.test.base import BaseTest from django.core.management import call_command from django.test import override_settings from parameterized import parameterized from posthog.models.integration import CONFIG_LEGACY_OAUTH_CLIENT, Integration def _id_token(audience: str | list[str])...
65
2,684
posthog
posthog/management/commands/test/test_base_hypercache_command.py
.py
""" Tests for BaseHyperCacheCommand error handling. Tests cover: - Graceful handling of Redis timeouts in get_cache_stats() - Error counting when verify_team() raises exceptions - Error reporting in verification results - Continued processing after individual team errors """ from functools import partial from io impo...
1,023
40,651
posthog
posthog/management/commands/test/test_backfill_workflows_slack_integration.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from django.core.management import call_command from posthog.management.commands import backfill_workflows_slack_integration as backfill from posthog.management.commands.backfill_workflows_slack_integration import _rewrite_slack_workspace_in_actio...
158
6,657
posthog
posthog/management/commands/test/test_sync_user_settings.py
.py
import os from urllib.parse import urlparse from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from django.core.management import call_command from django.core.management.base import CommandError from parameterized import parameterized from posthog.models import User from posthog.mode...
404
16,235
posthog
posthog/management/commands/test/test_send_digest_to_team.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from django.core.management import call_command from django.core.management.base import CommandError class TestSendDigestToTeamCommand(BaseTest): def test_send_digest_to_existing_team(self): """Test that the command successfully calls...
41
2,135
posthog
posthog/management/commands/test/test_rerun_google_ads_failed_invocations.py
.py
from io import StringIO from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from django.core.management import call_command from products.cdp.backend.models.hog_functions.hog_function import HogFunction RERUN_HELPER = "posthog.management.commands.rerun_google_ads_failed_invocations.rer...
111
5,110
posthog
posthog/management/commands/test/test_send_ai_observability_usage_report.py
.py
import pytest from freezegun import freeze_time from unittest.mock import patch from django.core.cache import cache from django.core.management import call_command from django.core.management.base import CommandError from posthog.tasks.ai_observability_usage_report import usage_report_dispatch_lock_key TASK_PATH = "...
151
5,664
posthog
posthog/management/commands/test/test_backfill_distinct_id_overrides.py
.py
import uuid import operator from posthog.test.base import BaseTest, ClickhouseTestMixin from posthog.clickhouse.client.execute import sync_execute from posthog.management.commands.backfill_distinct_id_overrides import Backfill class ExecuteBackfillTestCase(ClickhouseTestMixin, BaseTest): def __run_test_backfill...
58
2,064
posthog
posthog/management/commands/test/test_analyze_migration_risk.py
.py
from io import StringIO from unittest.mock import patch from django.test import TestCase class TestAnalyzeMigrationRisk(TestCase): def test_check_missing_migrations_when_none_needed(self): """Should return empty string when no migrations are needed.""" from posthog.management.commands.analyze_mi...
187
8,069
posthog
posthog/management/commands/test/test_js_snippet_version.py
.py
import json from unittest.mock import patch from django.core.cache import cache from django.core.management import call_command from django.core.management.base import CommandError from django.test import SimpleTestCase, override_settings from posthog.models.js_snippet_versioning import REDIS_POINTER_MAP_KEY, Manife...
230
10,559
posthog
posthog/management/commands/test/test_invalidate_flags_auth_cache.py
.py
import json from io import StringIO from posthog.test.base import BaseTest from django.core.management import call_command from django.core.management.base import CommandError from django.test import override_settings import redis as redis_lib from parameterized import parameterized from posthog.models.organization...
185
7,705
posthog
posthog/management/commands/test/test_migrate_hooks.py
.py
from posthog.test.base import BaseTest from posthog.cdp.templates.hog_function_template import sync_template_to_db from posthog.cdp.templates.zapier.template_zapier import template as template_zapier from posthog.management.commands.migrate_hooks import migrate_hooks from products.actions.backend.models.action import...
76
2,867
posthog
posthog/management/commands/test/test_migrate_legacy_geoip_transformations.py
.py
from io import StringIO from posthog.test.base import BaseTest from unittest.mock import patch from django.core.management import call_command from posthog.cdp.validation import compile_hog from products.cdp.backend.models.hog_function_template import HogFunctionTemplate from products.cdp.backend.models.hog_functio...
141
5,762
posthog
posthog/management/commands/test/test_migrations_are_safe.py
.py
import re from posthog.management.commands.test_migrations_are_safe import validate_migration_sql def test_new_tables_must_not_have_int_32_ids() -> None: sql_for_model_with_int32 = """ BEGIN; -- -- Create model StrawMan -- CREATE TABLE "posthog_strawman" ("id" serial NOT NULL PRIMARY KEY, "name" varchar(400) NUL...
177
5,621
posthog
posthog/management/commands/test/test_backfill_persons_and_groups_on_events.py
.py
from time import sleep from uuid import UUID, uuid4 import pytest from posthog.test.base import BaseTest, ClickhouseTestMixin from django.conf import settings from posthog.clickhouse.client import sync_execute from posthog.conftest import create_clickhouse_tables from posthog.management.commands.backfill_persons_and...
110
3,606
posthog
posthog/management/commands/test/test_setup_local_gateway_credential.py
.py
from io import StringIO from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from django.core.management import call_command from django.core.management.base import CommandError from posthog.models.project_secret_api_key import ProjectSecretAPIKey from posthog.models.utils import hash_ke...
66
2,825
posthog
posthog/management/commands/test/test_sync_hog_function_templates.py
.py
import pytest from unittest.mock import MagicMock, patch from django.core.management import call_command from posthog.cdp.templates import HOG_FUNCTION_TEMPLATES from posthog.management.commands.sync_hog_function_templates import ( TEST_INCLUDE_NODEJS_TEMPLATE_IDS, TEST_INCLUDE_PYTHON_TEMPLATE_IDS, TYPES_...
281
12,409
posthog
posthog/management/commands/test/test_audit_encrypted_field_keys.py
.py
import json import base64 from io import StringIO from typing import Any, cast from posthog.test.base import BaseTest from django.core.management import call_command from django.core.management.base import CommandError from django.db import connections, router from django.test import SimpleTestCase, override_settings...
401
17,922
posthog
posthog/management/commands/test/test_restore_session_recording_keys.py
.py
import datetime from io import StringIO import pytest from unittest.mock import MagicMock, patch from django.core.management import call_command from django.core.management.base import CommandError from botocore.exceptions import ClientError from parameterized import parameterized RECOVERY_ARN = "arn:aws:backup:us-...
667
25,232
posthog
posthog/management/commands/test/test_sync_persons_to_clickhouse.py
.py
import logging from datetime import UTC, datetime, timedelta from uuid import UUID, uuid4 import pytest from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest from unittest import mock from psycopg.types.json import Jsonb import posthog.management.commands.sync_persons_to_clickhouse from posthog.clickh...
745
26,814
posthog
posthog/management/commands/test/test_execute_temporal_workflow.py
.py
import pytest from unittest.mock import AsyncMock, MagicMock, patch from django.core.management import call_command from products.web_analytics.backend.temporal.weekly_digest.types import SendTestDigestInput, WAWeeklyDigestInput @pytest.mark.django_db @pytest.mark.parametrize( "workflow_name,inputs,expected_inp...
44
1,568
posthog
posthog/management/commands/test/test_send_usage_report.py
.py
from freezegun import freeze_time from unittest.mock import patch from django.core.management import call_command @freeze_time("2026-06-02T12:00:00Z") def test_send_usage_report_defaults_to_current_date() -> None: with patch("posthog.management.commands.send_usage_report.send_all_org_usage_reports") as mock_send...
31
977
posthog
posthog/management/commands/test/test_set_recorder_script.py
.py
from io import StringIO from posthog.test.base import BaseTest from unittest import mock from django.core.management import call_command from parameterized import parameterized from posthog.models import Team from posthog.sampling import sample_on_property class TestSetRecorderScriptCommand(BaseTest): def tes...
167
6,359
posthog
posthog/management/commands/test/test_reenable_schemas_by_error.py
.py
from datetime import UTC, datetime import pytest from unittest.mock import patch from django.core.management import call_command from posthog.api.test.test_organization import create_organization from posthog.api.test.test_team import create_team from products.warehouse_sources.backend.facade.models import External...
189
7,275
posthog
posthog/management/commands/test/test_migrate_ses_tenants.py
.py
from posthog.test.base import BaseTest from unittest.mock import patch from django.test import override_settings from posthog.management.commands.migrate_ses_tenants import migrate_ses_tenants from posthog.models.integration import Integration class _FakeSESv2Client: def __init__(self): self.created_ten...
165
7,805
posthog
posthog/management/commands/test/test_survey_cohort_bytecode_stl.py
.py
import os import json import tempfile from posthog.test.base import BaseTest from django.core.management import call_command from parameterized import parameterized from posthog.management.commands.survey_cohort_bytecode_stl import ( aggregate_survey, iter_bytecode_leaves, iter_instructions, ) from pro...
356
13,012
posthog
posthog/management/commands/test/test_run_async_migrations.py
.py
import logging import pytest from django.core.management import call_command from semantic_version.base import Version from posthog.async_migrations.setup import ALL_ASYNC_MIGRATIONS from posthog.constants import FROZEN_POSTHOG_VERSION pytestmark = pytest.mark.django_db def test_run_async_migrations_doesnt_raise...
78
2,695
posthog
posthog/management/commands/test/test_seed_oauth_app_scopes.py
.py
from io import StringIO from posthog.test.base import BaseTest from django.core.management import call_command from django.core.management.base import CommandError from parameterized import parameterized from posthog.models.oauth import OAuthApplication class TestSeedOAuthAppScopes(BaseTest): def _create_app(...
123
4,910
posthog
posthog/management/commands/test/test_resave_cohorts.py
.py
from __future__ import annotations from typing import Any from posthog.test.base import BaseTest from django.core.management import call_command from posthog.models.team.team import Team from products.cohorts.backend.models.cohort import Cohort from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION de...
511
20,112
posthog
posthog/management/commands/test/test_refresh_hog_functions.py
.py
from io import StringIO from posthog.test.base import BaseTest from unittest.mock import patch from django.core.management import call_command from posthog.models import Team from products.cdp.backend.models.hog_functions.hog_function import HogFunction class TestRefreshHogFunctions(BaseTest): def setUp(self)...
142
5,644
posthog
posthog/management/commands/test/test_update_hog_function_code.py
.py
from io import StringIO from posthog.test.base import BaseTest from unittest.mock import patch from django.core.management import call_command from parameterized import parameterized from posthog.cdp.validation import compile_hog as compile_hog_for_check from products.cdp.backend.models.hog_functions.hog_function ...
393
18,522
posthog
posthog/management/commands/test/test_background_delete_model.py
.py
from uuid import uuid4 from posthog.test.base import BaseTest from unittest.mock import MagicMock, patch from django.core.management.base import CommandError from posthog.management.commands.background_delete_model import Command from posthog.models import Tag # Uses a plain main-DB, team-scoped model (Tag) as the ...
280
12,966
posthog
posthog/management/commands/test/test_sync_replicated_schema.py
.py
import pytest from posthog.test.base import BaseTest, ClickhouseTestMixin from django.conf import settings from posthog.clickhouse.client import sync_execute from posthog.conftest import create_clickhouse_tables from posthog.management.commands.sync_replicated_schema import Command @pytest.mark.ee class TestSyncRep...
68
2,485
posthog
posthog/management/commands/test/test_start_temporal_worker.py
.py
import pytest from posthog.management.commands.start_temporal_worker import ( DATA_SYNC_WORKFLOWS, WA_DIGEST_ACTIVITIES, WA_DIGEST_WORKFLOWS, WEEKLY_DIGEST_WORKFLOWS, _task_queue_specs, workflows_include_data_import_syncs, ) class _NotADataSyncWorkflow: pass # Data-import sources import...
51
2,094
posthog
posthog/kafka_client/client.py
.py
"""Low-level Kafka primitives. Most call sites should NOT import from this module directly. The public entry points for producing are in `posthog.kafka_client.routing`: * `get_producer(topic=...)` / `producer_scope(topic=...)` for sync producers * `async_producer_scope(topic=...)` for per-call async producers * `new_...
487
18,434
posthog
posthog/kafka_client/topics.py
.py
# Keep this in sync with plugin-server/src/config/kafka-topics.ts from posthog.settings.data_stores import SUFFIX from posthog.settings.kafka import KAFKA_PREFIX from posthog.settings.utils import get_from_env KAFKA_EVENTS_JSON = f"{KAFKA_PREFIX}clickhouse_events_json{SUFFIX}" KAFKA_EXCEPTIONS_INGESTION = f"{KAFKA_PR...
93
5,766
posthog
posthog/kafka_client/profiles.py
.py
"""Kafka cluster profile names. Isolated module so `posthog.settings.kafka` can import the profile list without pulling in `kafka_client.client` / `django.conf.settings` (which would create a circular import at Django settings-load time). """ from enum import StrEnum class KafkaClusterProfile(StrEnum): DEFAULT ...
19
520
posthog
posthog/kafka_client/helper.py
.py
"""Helper for SSL-certificate-based Kafka auth (self-hosted deployments). Originally for Heroku-style base64-encoded certificates (https://github.com/heroku/kafka-helper). Only `ssl_cert_config` is called — `_KafkaProducer` merges it into its confluent config when `KAFKA_BASE64_KEYS` is true. """ import os import ate...
96
3,219
posthog
posthog/kafka_client/routing.py
.py
"""Topic → producer routing. Call sites specify a topic (or an explicit profile); the router resolves it to a cluster profile and returns a producer configured for that profile. This centralises cluster routing so moving a topic between clusters (e.g. MSK → Warpstream) is a one-line change in TOPIC_ROUTING rather than...
305
12,356
posthog
posthog/kafka_client/test/test_client.py
.py
import os import json import uuid import pytest from unittest.mock import MagicMock, patch from django.test import TestCase, override_settings from parameterized import parameterized from posthog.kafka_client.client import _KafkaProducer from posthog.settings.kafka import KafkaProfileSettings def _make_profiles(*...
288
11,721
posthog
posthog/kafka_client/test/test_kafka_settings.py
.py
"""Tests for `posthog/settings/kafka.py` — the per-profile Kafka settings module.""" from unittest import TestCase from unittest.mock import patch from parameterized import parameterized from posthog.kafka_client.profiles import KafkaClusterProfile from posthog.settings import kafka as kafka_settings class PerProf...
222
10,567
posthog
posthog/kafka_client/test/test_routing.py
.py
from contextlib import contextmanager from typing import cast from unittest import TestCase, mock from unittest.mock import MagicMock, patch from django.test import override_settings from parameterized import parameterized from posthog.kafka_client import routing from posthog.kafka_client.routing import ( Kafka...
285
11,117
posthog
posthog/rbac/query_access.py
.py
"""Check that a user's access control lets them read everything a HogQL query selects from. Enforcement lives in the schema: Database.create_for(user) leaves out tables and views the user is denied, so resolving a query against it fails on anything they can't read - including tables reached through nested views. Extra...
38
1,939
posthog
posthog/rbac/access_control_api_mixin.py
.py
from typing import TYPE_CHECKING if TYPE_CHECKING: from ee.api.rbac.access_control import AccessControlViewSetMixin from ee.api.rbac.access_control_settings import AccessControlSettingsViewSetMixin else: try: from ee.api.rbac.access_control import AccessControlViewSetMixin except ImportError: ...
22
571
posthog
posthog/rbac/decorators.py
.py
from typing import TYPE_CHECKING if TYPE_CHECKING: from posthog.rbac.user_access_control import AccessControlLevel from posthog.scopes import APIScopeObject def field_access_control(field, resource: "APIScopeObject", level: "AccessControlLevel"): """ Helper function for creating access-controlled fie...
23
674
posthog
posthog/rbac/user_access_control.py
.py
import json from collections import defaultdict from collections.abc import Callable, Iterable, Sequence from dataclasses import dataclass from enum import Enum from functools import cache, cached_property from typing import TYPE_CHECKING, Any, Literal, Optional, cast, get_args from django.db.models import Case, CharF...
1,732
76,876
posthog
posthog/rbac/test/test_user_access_control_pbt.py
.py
import uuid import itertools from collections.abc import Callable from dataclasses import dataclass from typing import Any, Optional, cast import pytest from posthog.test.base import BaseTest from unittest import TestCase from django.apps import apps from django.db import models, transaction from django.utils import ...
900
42,360
posthog
posthog/rbac/test/test_user_access_control.py
.py
import pytest from posthog.test.base import BaseTest from unittest.mock import patch from parameterized import parameterized from rest_framework import serializers from posthog.constants import AvailableFeature from posthog.models.file_system.file_system import FileSystem from posthog.models.organization import Organ...
2,195
99,934
posthog
posthog/rbac/test/test_field_access_control.py
.py
from typing import Any, cast import pytest from posthog.test.base import BaseTest from django.db import models from rest_framework import serializers from rest_framework.exceptions import ValidationError from posthog.models.team import Team from posthog.rbac.decorators import field_access_control from posthog.rbac....
146
6,156
posthog
posthog/comment/__init__.py
.py
"""Cross-channel logic shared by anything that mirrors comment threads to external surfaces. Sits alongside the ``posthog.models.comment`` data layer: this package holds the channel-agnostic content conversion and Slack identity helpers reused by the conversations (support) product and core discussions. """
7
310