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/comment/access.py | .py | from uuid import UUID
def task_comment_target_is_accessible(
*, team_id: int, user_id: int | None, task_id: str | UUID, scope: str, item_id: str | None
) -> bool:
from products.tasks.backend.facade.api import (
task_comment_target_is_accessible as task_target_is_accessible, # noqa: PLC0415 # Import ... | 45 | 1,291 |
posthog | posthog/comment/formatting.py | .py | """Convert between PostHog rich content/markdown and Slack payload formats."""
import re
import html as html_mod
import unicodedata
from collections.abc import Callable, Iterable
from typing import Any
from urllib.parse import urlparse
from uuid import UUID
JSON = dict[str, Any]
# Pre-compiled regexes for performanc... | 1,046 | 40,311 |
posthog | posthog/settings/payments.py | .py | from posthog.settings.utils import get_from_env
STRIPE_PUBLIC_KEY = get_from_env("STRIPE_PUBLIC_KEY", None, optional=True)
| 4 | 124 |
posthog | posthog/settings/web.py | .py | # Web app specific settings/middleware/apps setup
import os
from datetime import timedelta
import structlog
from corsheaders.defaults import default_headers
from whitenoise.compress import Compressor
from posthog.scopes import get_scope_descriptions
from posthog.settings.base_variables import BASE_DIR, CLOUD_DEPLOYME... | 1,382 | 75,280 |
posthog | posthog/settings/canvas.py | .py | import os
from posthog.settings.base_variables import BASE_DIR, TEST
from posthog.settings.utils import get_list
CANVAS_ARTIFACT_ORIGIN = os.getenv("CANVAS_ARTIFACT_ORIGIN", "").rstrip("/")
CANVAS_ARTIFACT_SIGNING_KEYS = get_list(os.getenv("CANVAS_ARTIFACT_SIGNING_KEYS", ""))
if TEST and not CANVAS_ARTIFACT_SIGNING_K... | 15 | 729 |
posthog | posthog/settings/personhog.py | .py | from posthog.settings.utils import get_from_env, str_to_bool
PERSONHOG_ADDR = get_from_env("PERSONHOG_ADDR", "")
PERSONHOG_TIMEOUT_MS = get_from_env("PERSONHOG_TIMEOUT_MS", 5000, type_cast=int)
# gRPC channel options
PERSONHOG_KEEPALIVE_TIME_MS = get_from_env("PERSONHOG_KEEPALIVE_TIME_MS", 30_000, type_cast=int)
PERS... | 26 | 1,682 |
posthog | posthog/settings/feature_flags.py | .py | import os
import json
from contextlib import suppress
from posthog.settings.access import SECRET_KEY
from posthog.settings.base_variables import TEST
from posthog.settings.utils import get_from_env, get_list, str_to_bool
# Used mostly by the hobby install to have some feature flags enabled by default
# NOTE: This onl... | 151 | 8,611 |
posthog | posthog/settings/email.py | .py | import os
from posthog.settings.access import SECRET_KEY
from posthog.settings.utils import get_list
MESSAGING_HASH_SALT: str = os.getenv("MESSAGING_HASH_SALT") or SECRET_KEY
MESSAGING_HASH_SALT_FALLBACKS: list[str] = [
salt for salt in get_list(os.getenv("MESSAGING_HASH_SALT_FALLBACKS", "")) if salt
]
| 10 | 310 |
posthog | posthog/settings/logs.py | .py | import os
import logging
import warnings
import threading
from typing import Any
import structlog
from opentelemetry import trace
from posthog.settings.base_variables import DEBUG, IS_INTERACTIVE_SHELL, TEST
# Setup logging
LOGGING_FORMATTER_NAME = os.getenv("LOGGING_FORMATTER_NAME", "default")
# The level the inte... | 194 | 8,170 |
posthog | posthog/settings/session_replay.py | .py | from posthog.settings import get_from_env
from posthog.utils import str_to_bool
# TRICKY: we saw unusual memory usage behavior in EU clickhouse cluster
# when allowing use of denormalized properties in some session replay event queries
# it is likely this can be returned to the default of True in future but would need... | 42 | 2,351 |
posthog | posthog/settings/utils.py | .py | import os
from collections.abc import Callable
from typing import Any, Optional
from django.core.exceptions import ImproperlyConfigured
from posthog.utils import str_to_bool
__all__ = [
"assert_debug_not_in_production",
"generate_rsa_private_key_pem",
"get_from_env",
"get_list",
"str_to_bool",
]
... | 81 | 2,970 |
posthog | posthog/settings/service_requirements.py | .py | import structlog
from posthog.settings.base_variables import DEBUG, IS_COLLECT_STATIC, TEST
from posthog.settings.utils import get_from_env, str_to_bool
from posthog.version_requirement import ServiceVersionRequirement
logger = structlog.get_logger(__name__)
SKIP_SERVICE_VERSION_REQUIREMENTS = get_from_env(
"SK... | 24 | 908 |
posthog | posthog/settings/kafka.py | .py | """Kafka settings, resolved per-cluster-profile.
Each `KafkaClusterProfile` gets its own env var namespace — `KAFKA_<PROFILE>_*` —
for hosts, security, SASL, and producer tuning. When a profile-specific value is
unset, resolution falls back to `KAFKA_DEFAULT_*`, then to built-in defaults.
Public legacy env var names ... | 222 | 9,852 |
posthog | posthog/settings/__init__.py | .py | """
Django settings for posthog project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
# isort: ski... | 145 | 6,055 |
posthog | posthog/settings/overrides.py | .py | # Imported before anything else to overwrite env vars!
import os
import sys
"""
There are several options:
1) running in pycharm
second argument is "test"
2) running pytest at the CLI
first argument is the path to pytest and ends pytest
3) running pytest using the script at /bin/tests
first ar... | 39 | 1,436 |
posthog | posthog/settings/continuous_profiling.py | .py | import os
from posthog.settings.utils import get_from_env
CONTINUOUS_PROFILING_ENABLED: bool = get_from_env("CONTINUOUS_PROFILING_ENABLED", False, type_cast=bool)
PYROSCOPE_SERVER_ADDRESS: str = os.getenv("PYROSCOPE_SERVER_ADDRESS", "")
PYROSCOPE_APPLICATION_NAME: str = os.getenv("PYROSCOPE_APPLICATION_NAME", "")
PYR... | 9 | 404 |
posthog | posthog/settings/ee.py | .py | EE_AVAILABLE = False
try:
from ee.apps import EnterpriseConfig # noqa: F401
except ImportError:
pass
else:
EE_AVAILABLE = True
| 9 | 141 |
posthog | posthog/settings/ses.py | .py | import os
from typing import Optional
from posthog.settings.base_variables import DEBUG, TEST
if TEST or DEBUG:
SES_ENDPOINT = os.getenv("SES_ENDPOINT", "http://localhost:4566")
SES_ACCESS_KEY_ID: Optional[str] = os.getenv("SES_ACCESS_KEY_ID", "test")
SES_SECRET_ACCESS_KEY: Optional[str] = os.getenv("SES_... | 29 | 1,436 |
posthog | posthog/settings/shell_plus.py | .py | from posthog.settings.utils import get_from_env, str_to_bool
# shell_plus settings
# https://django-extensions.readthedocs.io/en/latest/shell_plus.html
SHELL_PLUS_PRINT_SQL = get_from_env("PRINT_SQL", False, type_cast=str_to_bool)
SHELL_PLUS_POST_IMPORTS = [
(
"datetime",
(
"datetime",... | 24 | 761 |
posthog | posthog/settings/statsd.py | .py | import os
# Metrics - StatsD
STATSD_HOST = os.getenv("STATSD_HOST")
STATSD_PORT = os.getenv("STATSD_PORT", 8125)
STATSD_PREFIX = os.getenv("STATSD_PREFIX", "")
STATSD_TELEGRAF = True
STATSD_CLIENT = "statshog"
STATSD_SEPARATOR = "_"
| 10 | 234 |
posthog | posthog/settings/celery.py | .py | from datetime import timedelta
from kombu import Exchange, Queue
from posthog.settings.base_variables import TEST
from posthog.settings.data_stores import REDIS_URL
# Only listen to the default queue "celery", unless overridden via the CLI
CELERY_QUEUES = (Queue("celery", Exchange("celery"), "celery"),)
CELERY_DEFAU... | 43 | 2,113 |
posthog | posthog/settings/integrations.py | .py | from posthog.settings.utils import get_from_env, get_list, str_to_bool
# Integration service. Both unset (the default) means credential reads fall back to the
# local environment; see posthog/integration_secrets/client.py for the contract.
INTEGRATION_SERVICE_URL = get_from_env("INTEGRATION_SERVICE_URL", "")
# Comma-s... | 193 | 12,998 |
posthog | posthog/settings/geoip.py | .py | import os
from posthog.settings.base_variables import BASE_DIR
GEOIP_PATH = os.path.join(BASE_DIR, "share")
| 6 | 110 |
posthog | posthog/settings/temporal.py | .py | import os
from posthog.settings.access import SECRET_KEY
from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUG
from posthog.settings.utils import get_from_env, get_list, str_to_bool
TEMPORAL_NAMESPACE: str = os.getenv("TEMPORAL_NAMESPACE", "default")
TEMPORAL_HOST: str = os.getenv("TEMPORAL_HOST", "temp... | 237 | 14,578 |
posthog | posthog/settings/demo.py | .py | from posthog.settings.base_variables import TEST
from posthog.settings.utils import get_from_env
DEMO_MATRIX_N_CLUSTERS = get_from_env("DEMO_MATRIX_N_CLUSTERS", 3000 if not TEST else 1, type_cast=int)
| 5 | 202 |
posthog | posthog/settings/cohorts.py | .py | import os
from posthog.settings.utils import get_from_env, str_to_bool
# Off by default ("none"); enable per environment via the env override
# A set-but-empty value survives as "", which the parser reads as "all teams".
REALTIME_COHORT_TEAM_ALLOWLIST: str = os.getenv("REALTIME_COHORT_TEAM_ALLOWLIST", "none")
# Teams... | 71 | 4,248 |
posthog | posthog/settings/ingestion.py | .py | import os
from posthog.settings.utils import get_from_env, get_list, get_set
from posthog.utils import str_to_bool
INGESTION_LAG_METRIC_TEAM_IDS = get_list(os.getenv("INGESTION_LAG_METRIC_TEAM_IDS", ""))
# KEEP IN SYNC WITH plugin-server/src/config/config.ts
BUFFER_CONVERSION_SECONDS = get_from_env("BUFFER_CONVERSIO... | 125 | 8,198 |
posthog | posthog/settings/metrics.py | .py | import os
PROMETHEUS_METRICS_EXPORT_PORT = os.getenv("PROMETHEUS_METRICS_EXPORT_PORT", "8001")
| 4 | 96 |
posthog | posthog/settings/async_migrations.py | .py | from posthog.settings.utils import get_from_env, str_to_bool
# To help reduce PG load during deploys we're setting this to True by default.
# We don't currently have any async migrations that need to be added/ran.
SKIP_ASYNC_MIGRATIONS_SETUP = get_from_env("SKIP_ASYNC_MIGRATIONS_SETUP", True, type_cast=str_to_bool)
A... | 10 | 453 |
posthog | posthog/settings/base_variables.py | .py | import os
import sys
import structlog
from posthog.settings.utils import assert_debug_not_in_production, get_from_env, str_to_bool
logger = structlog.get_logger(__name__)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR: str = os.path.dirname(os.path.dirname(os.path.dirname(os.path.a... | 93 | 4,902 |
posthog | posthog/settings/batch_exports.py | .py | import os
from posthog.settings.utils import get_from_env, get_list
from posthog.utils import str_to_bool
BATCH_EXPORT_S3_UPLOAD_CHUNK_SIZE_BYTES: int = 1024 * 1024 * 50 # 50MB
BATCH_EXPORT_S3_RECORD_BATCH_QUEUE_MAX_SIZE_BYTES: int = get_from_env(
"BATCH_EXPORT_S3_RECORD_BATCH_QUEUE_MAX_SIZE_BYTES", 1024 * 1024 ... | 144 | 7,812 |
posthog | posthog/settings/dynamic_settings.py | .py | from posthog.settings.utils import get_from_env, str_to_bool
CONSTANCE_DATABASE_PREFIX = "constance:posthog:"
# Warning: Dynamically updating these settings should only be done through the API.
# CONSTANCE_CONFIG: https://django-constance.readthedocs.io/en/latest/
#
# To edit, visit: ${SITE_URL}/admin/posthog/instanc... | 414 | 18,720 |
posthog | posthog/settings/session_replay_v2.py | .py | import os
from typing import Optional
from posthog.settings import get_from_env
from posthog.settings.base_variables import DEBUG, TEST
from posthog.settings.utils import str_to_bool
if TEST or DEBUG:
SESSION_RECORDING_V2_S3_ENDPOINT = os.getenv("SESSION_RECORDING_V2_S3_ENDPOINT", "http://seaweedfs:8333")
SES... | 42 | 2,300 |
posthog | posthog/settings/managed_migrations.py | .py | import os
from typing import Optional
from posthog.settings.base_variables import DEBUG, TEST
from posthog.settings.object_storage import OBJECT_STORAGE_REGION
from posthog.settings.utils import get_from_env
from posthog.utils import str_to_bool
# S3-compatible store holding managed-migration trial run output (browsa... | 45 | 2,529 |
posthog | posthog/settings/exports.py | .py | from posthog.settings.utils import get_from_env
BROWSERLESS_CDP_URL: str = get_from_env("BROWSERLESS_CDP_URL", "")
BROWSERLESS_TOKEN: str = get_from_env("BROWSERLESS_TOKEN", "")
BROWSERLESS_SESSION_TIMEOUT_MS: int = get_from_env("BROWSERLESS_SESSION_TIMEOUT_MS", 180000, type_cast=int)
BROWSERLESS_CONNECT_TIMEOUT_MS: i... | 7 | 394 |
posthog | posthog/settings/data_stores.py | .py | import os
import json
from contextlib import suppress
from pathlib import Path
from typing import Optional
from django.core.exceptions import ImproperlyConfigured
import dj_database_url
from posthog.product_db_config import load_product_db_routes
from posthog.settings.base_variables import DEBUG, IN_EVAL_TESTING, IS... | 705 | 35,475 |
posthog | posthog/settings/activity_log.py | .py | from posthog.settings.base_variables import TEST
from posthog.settings.utils import get_from_env
ACTIVITY_LOG_TRANSACTION_MANAGEMENT = get_from_env("ACTIVITY_LOG_TRANSACTION_MANAGEMENT", not TEST, type_cast=bool)
| 5 | 214 |
posthog | posthog/settings/dagster.py | .py | import os
from posthog.settings.base_variables import CLOUD_DEPLOYMENT
DAGSTER_S3_BUCKET: str = os.getenv("DAGSTER_S3_BUCKET", "posthog-dags")
DAGSTER_DEFAULT_SLACK_ALERTS_CHANNEL: str = os.getenv("DAGSTER_DEFAULT_SLACK_ALERTS_CHANNEL", "#alerts-clickhouse")
_QUERY_LOG_ARCHIVE_EXPORT_BUCKETS = {
"US": "posthog-q... | 56 | 3,140 |
posthog | posthog/settings/access.py | .py | # Settings which restrict access to the site across the app
import os
import sys
import structlog
from posthog.settings.base_variables import DEBUG, STATIC_COLLECTION, TEST
from posthog.settings.utils import get_from_env, get_list, str_to_bool
logger = structlog.get_logger(__name__)
# SSL & cookie defaults
if os.ge... | 184 | 10,113 |
posthog | posthog/settings/test_logs.py | .py | import logging
import logging.config
from opentelemetry import (
context as otel_context,
trace,
)
from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlags
from posthog.settings import logs
def _record(level: int) -> logging.LogRecord:
return logging.LogRecord("test", level, __file__, 1... | 67 | 2,358 |
posthog | posthog/settings/data_warehouse.py | .py | import os
from posthog.settings import TEST
from posthog.settings.base_variables import DEBUG
from posthog.settings.data_stores import DATABASE_URL, PRODUCT_DB_WRITER_URLS
from posthog.settings.utils import get_from_env, str_to_bool
DATAWAREHOUSE_LOCAL_BUCKET_REGION = os.getenv("DATAWAREHOUSE_LOCAL_BUCKET_REGION", "u... | 166 | 11,241 |
posthog | posthog/settings/object_storage.py | .py | import os
from typing import Optional
from posthog.settings import get_from_env
from posthog.settings.base_variables import DEBUG, TEST
from posthog.utils import str_to_bool
if TEST or DEBUG:
OBJECT_STORAGE_ENDPOINT = os.getenv("OBJECT_STORAGE_ENDPOINT", "http://objectstorage:19000")
OBJECT_STORAGE_ACCESS_KEY... | 121 | 8,285 |
posthog | posthog/settings/schedules.py | .py | from posthog.settings.base_variables import TEST
from posthog.settings.utils import get_from_env
USE_PRECALCULATED_CH_COHORT_PEOPLE = not TEST
# Schedules to recalculate cohorts. Follows crontab syntax.
CALCULATE_COHORTS_DAY_SCHEDULE = get_from_env(
"CALCULATE_COHORTS_DAY_SCHEDULE",
"*/2 6-17 * * *",
)
CALCUL... | 59 | 2,248 |
posthog | posthog/security/llm_prompt_sanitization.py | .py | """Sanitize user-controlled text before embedding it in an LLM prompt.
Shared across products (subscriptions, marketing analytics, Max tools).
"""
from __future__ import annotations
import re
import unicodedata
INSIGHT_NAME_MAX_LEN = 120
INSIGHT_DESCRIPTION_MAX_LEN = 500
SERIES_LABEL_MAX_LEN = 200
SUBSCRIPTION_TITL... | 109 | 4,016 |
posthog | posthog/security/outbound_proxy.py | .py | """Outbound proxy helpers for HTTP requests.
External calls use the standard library defaults — ``requests``,
``httpx``, and ``aiohttp`` all honour ``HTTP_PROXY`` / ``HTTPS_PROXY``
env vars automatically (``trust_env=True`` is the default for
``requests`` and ``httpx``; ``aiohttp`` needs it set explicitly).
Internal ... | 59 | 1,933 |
posthog | posthog/security/url_validation.py | .py | import ipaddress
import urllib.parse as urlparse
from collections.abc import Iterable, Mapping
from concurrent.futures import Future, ThreadPoolExecutor, wait
from threading import BoundedSemaphore
from django.conf import settings
import structlog
import dns.resolver
import dns.exception
from posthog.cloud_utils imp... | 349 | 12,666 |
posthog | posthog/security/spreadsheet_safety.py | .py | """Defensive helpers for content destined for spreadsheet apps."""
from typing import Any
# Characters that can trigger formula execution in spreadsheet applications
_FORMULA_TRIGGER_CHARS = ("=", "+", "-", "@", "\t", "\r")
def sanitize_formula_injection(value: Any) -> Any:
"""Prefix dangerous cell values with ... | 21 | 743 |
posthog | posthog/security/pinned_requests.py | .py | """SSRF-hardened HTTP requests with DNS pinning.
``validate_url_and_pin_ips`` alone leaves a TOCTOU window: the hostname is
resolved once for validation and again when ``requests`` opens the connection,
so a rebinding DNS record can pass validation and still connect internally.
``PinnedIPAdapter`` closes that window b... | 198 | 8,610 |
posthog | posthog/security/test_llm_prompt_sanitization.py | .py | import pytest
from posthog.security.llm_prompt_sanitization import (
sanitize_core_memory_text,
sanitize_user_text,
strip_llm_framing_markers,
)
class TestSanitizeUserText:
@pytest.mark.parametrize(
"raw,expected",
[
("Pageviews", "Pageviews"),
("", ""),
... | 229 | 8,031 |
posthog | posthog/security/command_exec_audit.py | .py | """Process-execution audit logging."""
import os
import re
import uuid
import shlex
import subprocess
import contextvars
from collections.abc import Callable, Mapping
from types import ModuleType
from typing import Any, Optional
import wrapt
import structlog
# C exec primitive under subprocess.Popen; absent on some ... | 443 | 16,182 |
posthog | posthog/security/test/test_url_validation.py | .py | import ipaddress
from concurrent.futures import Future, ThreadPoolExecutor
from threading import Barrier, BoundedSemaphore
import pytest
from posthog.security import url_validation as uv
@pytest.fixture(autouse=True)
def force_prod(monkeypatch):
# Ensure tests run with production-like SSRF behavior unless overr... | 348 | 15,856 |
posthog | posthog/security/test/test_pinned_requests.py | .py | import ipaddress
import pytest
from unittest.mock import MagicMock, patch
import requests
from requests.adapters import HTTPAdapter
from posthog.security import pinned_requests as pr
class TestPinnedRequest:
def test_blocked_url_raises_before_any_connection(self):
with (
patch.object(pr, "v... | 102 | 4,375 |
posthog | posthog/security/test/test_command_exec_audit.py | .py | import os
import uuid
import shutil
import subprocess
from collections.abc import Mapping, Sequence
from typing import Any
from posthog.test.base import APIBaseTest
from unittest import TestCase, mock, skipUnless
from django.test import override_settings
from django.urls import path
import structlog
from parameteriz... | 411 | 19,123 |
posthog | posthog/security/test/test_outbound_proxy.py | .py | import pytest
import httpx
import requests
import requests_mock as rm
from posthog.security.outbound_proxy import (
internal_httpx_async_client,
internal_httpx_client,
internal_requests,
internal_requests_session,
)
# ---------------------------------------------------------------------------
# inter... | 130 | 4,221 |
posthog | posthog/taxonomy/property_definition_api.py | .py | import json
import uuid
import dataclasses
from typing import Any, Optional, Self, Union, cast
from django.db import DEFAULT_DB_ALIAS, OperationalError, connections, models, router, transaction
from django.db.models import Manager, QuerySet
from django.db.models.functions import Coalesce
from django.http import Http40... | 1,026 | 43,418 |
posthog | posthog/taxonomy/property_access.py | .py | from posthog.models import PropertyDefinition, Team, User
def restricted_property_names(team: Team, user: User | None, property_type: PropertyDefinition.Type) -> set[str]:
"""Property names the user may not read for this type, per field-level access control.
Mirrors PropertyDefinitionViewSet._get_restricted_... | 21 | 1,202 |
posthog | posthog/taxonomy/taxonomy.py | .py | import re
from typing import Literal, NotRequired, TypedDict
STALE_EVENT_DAYS = 30
class CoreFilterDefinition(TypedDict):
"""Like the CoreFilterDefinition type in the frontend, except no JSX.Element allowed."""
label: str
label_llm: NotRequired[str]
description: NotRequired[str]
description_llm:... | 3,952 | 185,977 |
posthog | posthog/taxonomy/test/test_event_properties_taxonomy.py | .py | from posthog.taxonomy.taxonomy import (
CAMPAIGN_PROPERTIES,
CORE_FILTER_DEFINITIONS_BY_GROUP,
SESSION_INITIAL_PROPERTIES_ADAPTED_FROM_EVENTS,
)
def test_event_properties_includes_campaign_properties() -> None:
keys = CORE_FILTER_DEFINITIONS_BY_GROUP["event_properties"].keys()
for campaign_param i... | 36 | 1,436 |
posthog | posthog/tasks/demo_reset_master_team.py | .py | from django.db import transaction
def demo_reset_master_team() -> None:
# Deferred: the demo matrix pulls mimesis (fake-data generator); this module is
# eager-imported by posthog/tasks/__init__, so a module-level import drags it onto startup.
from products.demo.backend.facade.api import HedgeboxMatrix, M... | 13 | 479 |
posthog | posthog/tasks/report_utils.py | .py | import dataclasses
from datetime import datetime
from typing import Any, Optional, Union, cast
from django.conf import settings
import structlog
from dateutil import parser
from posthoganalytics.client import Client
from posthog.cloud_utils import is_cloud
from posthog.exceptions_capture import capture_exception
fro... | 155 | 5,665 |
posthog | posthog/tasks/push_notifications.py | .py | """Celery task wrapper around the synchronous Expo push helper.
The helper does sync ``requests.post`` with a 10-second timeout — fine in a
worker, dangerous inside a request/response cycle or an async Temporal
activity. Schedule this task via ``transaction.on_commit(lambda: …delay(…))``
to dispatch pushes off the hot... | 71 | 2,665 |
posthog | posthog/tasks/email.py | .py | import uuid
import datetime
from enum import Enum
from typing import Any, Literal, Optional, cast
from urllib.parse import quote
from django.conf import settings
from django.db import transaction
from django.db.models import OuterRef, Subquery
from django.utils import timezone
import structlog
import posthoganalytics... | 2,506 | 102,524 |
posthog | posthog/tasks/hypercache_verification.py | .py | """
Celery tasks for HyperCache verification.
Provides separate tasks for verifying and fixing each HyperCache-backed cache
(flags, flag definitions, team metadata). Split into separate tasks to:
- Give each cache its own time budget (avoiding timeouts)
- Enable independent monitoring and metrics
- Allow parallel exec... | 275 | 11,316 |
posthog | posthog/tasks/update_survey_iteration.py | .py | from datetime import date, timedelta
from django.utils import timezone
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from products.feature_flags.backend.facade.api import create_flag, update_flag
from products.feature_flags.backend.facade.filters import replace_release_conditi... | 154 | 6,090 |
posthog | posthog/tasks/utils.py | .py | import time
import threading
from typing import Any
from celery import Task
from prometheus_client import CollectorRegistry, Gauge
# Re-exported for the many existing `from posthog.tasks.utils import CeleryQueue` consumers.
# The enum lives in posthog.celery_queues so import-light modules can use it at decorator-eval... | 68 | 2,393 |
posthog | posthog/tasks/stop_surveys_reached_target.py | .py | from datetime import datetime
from itertools import groupby
from django.db.models import Q
from django.utils import timezone
from posthog.schema import ProductKey
from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
from posthog.... | 112 | 4,275 |
posthog | posthog/tasks/surveys.py | .py | import structlog
from celery import shared_task
from posthog.models.team import Team
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
from products.surveys.backend.models import surveys_hypercache
logger = structlog.get_logger(__name__)
@shared_task(ignore_result=... | 33 | 1,009 |
posthog | posthog/tasks/team_access_cache_tasks.py | .py | """
Targeted invalidation for the per-token auth cache.
Sync functions are called by Django signal handlers to invalidate cache
entries immediately. Each has an async Celery task counterpart used as
a retry fallback if the synchronous attempt fails.
"""
from collections.abc import Callable
from typing import Any
imp... | 140 | 5,391 |
posthog | posthog/tasks/early_access_feature.py | .py | from typing import Any, Optional
from django.db import IntegrityError, connection, transaction
from django.utils import timezone
import structlog
import posthoganalytics
from celery import shared_task
from posthog.hogql import ast
from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, LimitContext
from postho... | 194 | 8,517 |
posthog | posthog/tasks/process_scheduled_changes.py | .py | import os
import json
import socket
from datetime import UTC, datetime
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import IntegrityError, OperationalError, transaction
from django.utils import timezone
import structlog
from... | 404 | 21,093 |
posthog | posthog/tasks/js_snippet_versioning.py | .py | from django.conf import settings
import structlog
from celery import shared_task
from posthog.exceptions_capture import capture_exception
from posthog.models.js_snippet_versioning import sync_manifest_from_s3
from posthog.tasks.utils import CeleryQueue
logger = structlog.get_logger(__name__)
@shared_task(ignore_re... | 25 | 898 |
posthog | posthog/tasks/usage_report.py | .py | import os
import gzip
import json
import uuid
import base64
import logging
import dataclasses
from collections import Counter, defaultdict
from collections.abc import Callable, Sequence
from datetime import UTC, datetime, timedelta
from typing import Any, Literal, Optional, TypedDict, Union
from django.conf import set... | 3,602 | 158,369 |
posthog | posthog/tasks/sync_all_organization_available_product_features.py | .py | from collections.abc import Sequence
from typing import cast
from posthog.cloud_utils import is_cloud
from posthog.models.organization import Organization
def sync_all_organization_available_product_features() -> None:
if is_cloud():
return
for organization in cast(Sequence[Organization], Organizatio... | 14 | 478 |
posthog | posthog/tasks/poll_query_performance.py | .py | import re
import math
from itertools import groupby
from typing import Any, Optional
from structlog import get_logger
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser, Workload
from posthog.clickhouse.client.execute_async import QueryStatusManager
from... | 90 | 3,165 |
posthog | posthog/tasks/warehouse.py | .py | import structlog
from celery import shared_task
from posthog.ph_client import get_client
from posthog.scoping_audit import skip_team_scope_audit
logger = structlog.get_logger(__name__)
@shared_task(ignore_result=True)
@skip_team_scope_audit
def validate_data_warehouse_table_columns(team_id: int, table_id: str) -> N... | 40 | 1,406 |
posthog | posthog/tasks/email_utils.py | .py | from collections.abc import Callable
from typing import Any
def auto_select_digest_project(
user: Any,
team_data: dict[int, dict],
setting_key: str,
sort_key: Callable[[dict], float],
persist: bool = True,
) -> bool:
"""Auto-select the busiest project for first-time digest users.
Returns ... | 62 | 2,056 |
posthog | posthog/tasks/comment_slack_sync.py | .py | import time
from typing import Any, cast
import structlog
import posthoganalytics
from celery import Task, shared_task
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from posthog.comment.formatting import slack_files_to_placeholder_lines, slack_to_content_and_rich_content
from posthog.help... | 380 | 17,043 |
posthog | posthog/tasks/__init__.py | .py | # Make tasks ready for celery autoimport
from . import (
activity_log,
async_migrations,
calculate_cohort,
comment_slack_sync,
demo_create_data,
demo_reset_master_team,
early_access_feature,
email,
exporter,
health_checks,
integrations,
llm_prompt_cache,
plugin_serve... | 56 | 1,153 |
posthog | posthog/tasks/gateway_credential.py | .py | """
Celery tasks for the gateway credential cache.
Independent of the team_metadata / team-llm-gateway pipelines so the caches can
fail or roll back without affecting each other. The signal handlers that drive
these tasks live in
posthog/storage/gateway_credential_signal_handlers.py.
"""
import time
from django.conf... | 132 | 5,501 |
posthog | posthog/tasks/llm_prompt_cache.py | .py | import logging
from celery import shared_task
from posthog.storage.llm_prompt_cache import invalidate_prompt_version_cache_range
from posthog.tasks.utils import CeleryQueue
logger = logging.getLogger(__name__)
@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
def invalidate_archived_prompt_versions... | 28 | 873 |
posthog | posthog/tasks/split_person.py | .py | from typing import Optional
import structlog
from celery import shared_task
from posthog.models import Person
from posthog.scoping_audit import skip_team_scope_audit
logger = structlog.get_logger(__name__)
@shared_task(ignore_result=True, max_retries=1)
@skip_team_scope_audit
def split_person(
person_id: int,
... | 60 | 1,976 |
posthog | posthog/tasks/auth_token_cache_verification.py | .py | """
Celery task for periodic auth token cache verification.
Scans all per-token auth cache entries in Redis and verifies them against
the database, deleting any stale entries that signal-based invalidation
may have missed. This is a safety net for long-TTL cache entries.
"""
import time
from django.conf import setti... | 91 | 3,699 |
posthog | posthog/tasks/plugin_server.py | .py | from typing import Optional
from celery import shared_task
from structlog import get_logger
from posthog.tasks.email import get_members_to_notify_for_pipeline_error, send_fatal_plugin_error
from posthog.tasks.utils import CeleryQueue
from products.cdp.backend.models.plugin import PluginConfig
from products.notificat... | 136 | 5,635 |
posthog | posthog/tasks/integrations.py | .py | from celery import shared_task
from posthog.models.integration import (
FirebaseIntegration,
GitHubIntegration,
GoogleCloudIntegration,
defer_repository_cache_fields,
refresh_backoff_active,
)
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
from ... | 138 | 5,809 |
posthog | posthog/tasks/demo_create_data.py | .py | from django.core.cache import cache
from celery import shared_task
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.scoping_audit import skip_team_scope_audit
@shared_task(ignore_result=True)
@skip_team_scope_audit
def create_data_for_demo_team(team_id: int, user_id: int, ... | 23 | 926 |
posthog | posthog/tasks/scheduled.py | .py | from random import randrange
from typing import Any
from django.conf import settings
from celery import Celery
from celery.canvas import Signature
from celery.schedules import crontab
from posthog.caching.warming import schedule_warming_for_teams_task
from posthog.clickhouse.client.execute_async import QueryStatusMa... | 949 | 34,569 |
posthog | posthog/tasks/calculate_cohort.py | .py | import time
from datetime import datetime, timedelta
from typing import Optional
from django.conf import settings
from django.db.models import Case, DurationField, ExpressionWrapper, F, Q, QuerySet, When
from django.utils import timezone
import structlog
import posthoganalytics
from celery import Task, chain, current... | 999 | 40,587 |
posthog | posthog/tasks/remote_config.py | .py | import time
from django.conf import settings
import structlog
from celery import shared_task
from posthog.models.remote_config import RemoteConfig
from posthog.models.team import Team
from posthog.scoping_audit import skip_team_scope_audit
from posthog.storage.remote_config_cache import cleanup_stale_expiry_tracking... | 119 | 4,033 |
posthog | posthog/tasks/team_metadata.py | .py | """
Celery tasks for team metadata cache management.
Provides async tasks for updating and syncing team metadata caches.
"""
import time
from typing import Any
from django.conf import settings
from django.db import transaction
from django.db.models.signals import post_save, pre_delete
from django.dispatch import rec... | 255 | 9,435 |
posthog | posthog/tasks/async_migrations.py | .py | from celery import shared_task, states
from celery.result import AsyncResult
from posthog.async_migrations.runner import (
run_async_migration_operations,
run_migration_healthcheck,
start_async_migration,
update_migration_progress,
)
from posthog.async_migrations.utils import force_stop_migration, proc... | 78 | 2,778 |
posthog | posthog/tasks/sync_billing.py | .py | from celery import shared_task
from posthog.exceptions_capture import capture_exception
from posthog.scoping_audit import skip_team_scope_audit
@shared_task(ignore_result=True, rate_limit="5/s")
@skip_team_scope_audit
def sync_members_to_billing(organization_id: str) -> None:
from posthog.models import Organizat... | 38 | 1,272 |
posthog | posthog/tasks/activity_log.py | .py | import structlog
from celery import shared_task
from posthog.cdp.internal_events import InternalEventEvent, InternalEventPerson, produce_internal_event
from posthog.models import Team
from posthog.scoping_audit import skip_team_scope_audit
logger = structlog.get_logger(__name__)
@shared_task(ignore_result=True)
@sk... | 68 | 2,387 |
posthog | posthog/tasks/team_llm_gateway_policy.py | .py | """
Celery tasks for the llm-gateway policy cache.
Independent of the team_metadata cache pipeline so the two caches can fail
(or be rolled back) without affecting each other. The signal handlers that
drive these tasks on Team changes live in
posthog/storage/team_llm_gateway_policy_signal_handlers.py.
"""
import time... | 84 | 3,083 |
posthog | posthog/tasks/tasks.py | .py | import time
import datetime
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING:
from posthog.event_usage import AnalyticsProps
from uuid import UUID
from django.conf import settings
from django.db import OperationalError, ProgrammingError, connection
from django.... | 1,766 | 72,747 |
posthog | posthog/tasks/update_survey_adaptive_sampling.py | .py | import json
from datetime import datetime, timedelta
from django.utils.timezone import now
from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
from products.feature_flags.backend.facade.api import update_flag
from products.feature_flags.backend.facade.filters import set_first_release_co... | 78 | 3,150 |
posthog | posthog/tasks/ai_observability_usage_report.py | .py | from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
import structlog
from cachetools import cached
from celery import Task, shared_task
from dateutil import parser
from posthoganalytics.client import Client as PostHogClient
from retry import retry
from posthog.clickh... | 1,273 | 51,413 |
posthog | posthog/tasks/health_checks.py | .py | from celery import shared_task
from structlog import get_logger
from posthog.tasks.utils import CeleryQueue
logger = get_logger(__name__)
@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)
def evaluate_health_check_for_team(kind: str, team_id: int) -> None:
# Deferred: posthog.dags.__init__ calls... | 23 | 850 |
posthog | posthog/tasks/exporter.py | .py | from time import perf_counter
from typing import Optional
import structlog
import posthoganalytics
from celery import current_task, shared_task
from prometheus_client import Counter, Histogram
from posthog.event_usage import EventSource, groups
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from post... | 186 | 7,112 |
posthog | posthog/tasks/test/test_hypercache_verification.py | .py | """
Tests for HyperCache verification Celery tasks.
Tests cover:
- Each task verifies its respective cache
- Errors are captured and re-raised
- Tasks skip when FLAGS_REDIS_URL not configured
"""
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, TestCase, override_settings
from cele... | 280 | 12,499 |
posthog | posthog/tasks/test/test_warehouse.py | .py | from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from posthog.tasks.warehouse import validate_data_warehouse_table_columns
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
class TestWarehouse(APIBaseTest):
@patch("posthog.tasks.warehouse.get_cli... | 31 | 1,180 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.