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 | products/exports/backend/tasks/test/test_csv_exporter_url_sanitising.py | .py | from posthog.test.base import APIBaseTest
from parameterized import parameterized
from posthog.utils import PotentialSecurityProblemException, absolute_uri
class TestCSVExporterURLSanitization(APIBaseTest):
def test_sanitize_url_when_provided_path(self) -> None:
with self.settings(SITE_URL="https://some... | 51 | 2,013 |
posthog | products/exports/backend/temporal/subscriptions/types.py | .py | import uuid
import typing
import dataclasses
from posthog.hogql.errors import ExposedHogQLError, ResolutionError
from posthog.slo.types import SloConfig
# AI report query failures we never name in owner/recipient-facing copy. The recipient didn't
# write the query, so the OOM advice is unactionable. Type still lands... | 370 | 15,122 |
posthog | products/exports/backend/temporal/subscriptions/workflows.py | .py | import json
import uuid
import asyncio
import datetime as dt
from collections.abc import Callable, Coroutine
from typing import Any
import temporalio.common
import temporalio.workflow
from temporalio.exceptions import ActivityError, ApplicationError, WorkflowAlreadyStartedError
from posthog.event_usage import EventSo... | 780 | 38,797 |
posthog | products/exports/backend/temporal/subscriptions/test_results_summarizer.py | .py | import pytest
import structlog
from parameterized import parameterized_class
from products.exports.backend.temporal.subscriptions.results_summarizer import MAX_SUMMARY_LENGTH, build_results_summary
class TestBuildResultsSummaryEmpty:
def test_none_results(self):
assert build_results_summary("TrendsQuery... | 354 | 14,013 |
posthog | products/exports/backend/temporal/subscriptions/llm_change_summary.py | .py | from __future__ import annotations
import os
import re
import base64
from dataclasses import dataclass
from typing import TYPE_CHECKING
from django.conf import settings
import structlog
import posthoganalytics
from posthoganalytics.ai.openai import OpenAI
from prometheus_client import Counter
if TYPE_CHECKING:
... | 458 | 23,142 |
posthog | products/exports/backend/temporal/subscriptions/test_llm_change_summary.py | .py | from types import SimpleNamespace
import pytest
from unittest.mock import MagicMock, patch
from products.exports.backend.temporal.subscriptions.llm_change_summary import (
_attach_images_to_user_message,
build_initial_prompt_messages,
build_prompt_messages,
generate_change_summary,
)
def _make_state... | 762 | 33,229 |
posthog | products/exports/backend/temporal/subscriptions/test_snapshot_image_loading.py | .py | from contextlib import contextmanager
import pytest
from unittest.mock import patch
from products.exports.backend.models.exported_asset import ExportedAsset
from products.exports.backend.temporal.subscriptions.snapshot_activities import (
MAX_SUMMARY_IMAGES,
SUBSCRIPTION_SUMMARY_IMAGE_SKIPPED,
_load_insig... | 205 | 7,474 |
posthog | products/exports/backend/temporal/subscriptions/snapshot_activities.py | .py | import uuid
from typing import Any
import posthoganalytics
import temporalio.activity
from asgiref.sync import sync_to_async
from prometheus_client import Counter
from structlog import get_logger
from posthog.constants import SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY
from posthog.ph_client import ph_scope... | 612 | 24,475 |
posthog | products/exports/backend/temporal/subscriptions/test_prompt_sanitization.py | .py | import pytest
from products.exports.backend.temporal.subscriptions.prompt_sanitization import (
sanitize_core_memory_text,
sanitize_user_text,
)
class TestSanitizeUserText:
@pytest.mark.parametrize(
"raw,expected",
[
("Pageviews", "Pageviews"),
("", ""),
... | 177 | 6,541 |
posthog | products/exports/backend/temporal/subscriptions/results_summarizer.py | .py | import math
from typing import Any
from structlog import get_logger
from posthog.security.llm_prompt_sanitization import GENERIC_VALUE_MAX_LEN, SERIES_LABEL_MAX_LEN, sanitize_user_text
LOGGER = get_logger(__name__)
MAX_SUMMARY_LENGTH = 2000
# Query kinds whose metric values map onto the insight's Y-axis format, so... | 334 | 13,603 |
posthog | products/exports/backend/temporal/subscriptions/__init__.py | .py | from products.exports.backend.temporal.subscriptions.activities import (
advance_next_delivery_date,
create_delivery_record,
create_export_assets,
deliver_subscription,
deliver_subscription_v2,
fetch_due_subscriptions_activity,
notify_subscription_delivery_failure,
update_delivery_record... | 41 | 1,363 |
posthog | products/exports/backend/temporal/subscriptions/prompt_sanitization.py | .py | """Backwards-compat re-export. The real implementation now lives in
`posthog.security.llm_prompt_sanitization` so it can be shared across products
(marketing analytics, subscriptions, future Max tools).
Keep these imports stable β `llm_change_summary.py` and any external pins
import from here.
"""
from posthog.securi... | 32 | 893 |
posthog | products/exports/backend/temporal/subscriptions/insight_snapshot.py | .py | """Build JSON-serializable insight payloads for subscription delivery history.
``SubscriptionDelivery.content_snapshot`` is built in two layers so the shape
lives here only:
1. :func:`build_initial_content_snapshot` β top-level ``dashboard`` / ``insights`` /
``total_insight_count`` when the delivery row is created... | 288 | 11,642 |
posthog | products/exports/backend/temporal/subscriptions/test_delivery_activities.py | .py | import uuid
import pytest
from unittest.mock import MagicMock, patch
from asgiref.sync import sync_to_async
from temporalio.exceptions import ApplicationError
from temporalio.testing import ActivityEnvironment
from posthog.email import EmailDeliveryError
from posthog.slo.types import SloArea, SloConfig, SloOperation... | 182 | 8,001 |
posthog | products/exports/backend/temporal/subscriptions/test_snapshot_annotations.py | .py | from datetime import datetime
from types import SimpleNamespace
from typing import Any
from zoneinfo import ZoneInfo
import pytest
from posthog.test.base import APIBaseTest
from parameterized import parameterized
from products.annotations.backend.api.annotation_context import resolve_snapshot_date_range
from product... | 99 | 4,022 |
posthog | products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.py | .py | import uuid
from datetime import datetime
from zoneinfo import ZoneInfo
import pytest
import structlog
from asgiref.sync import sync_to_async
from temporalio.testing import ActivityEnvironment
from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery
from products.exports.backend.te... | 547 | 19,424 |
posthog | products/exports/backend/temporal/subscriptions/test_insight_snapshot.py | .py | import json
import datetime as dt
from decimal import Decimal
import pytest
from posthog.caching.insight_result import InsightResult
from products.exports.backend.temporal.subscriptions.insight_snapshot import (
_has_comparison_enabled,
_serialize_insight_result,
)
def _build_insight_result(**overrides) ->... | 111 | 4,143 |
posthog | products/exports/backend/temporal/subscriptions/activities.py | .py | import json
import uuid
import typing
import datetime as dt
import dataclasses
from datetime import datetime
from django.db.models import Q
from django.utils import timezone as tz
import temporalio.activity
from structlog import get_logger
from temporalio.exceptions import ApplicationError
from posthog.sync import d... | 661 | 27,936 |
posthog | products/exports/backend/temporal/subscriptions/retry_policy.py | .py | import datetime as dt
from temporalio.common import RetryPolicy
SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY = RetryPolicy(
initial_interval=dt.timedelta(seconds=5),
maximum_interval=dt.timedelta(minutes=1),
maximum_attempts=3,
)
SUBSCRIPTION_VALIDATE_RETRY_POLICY = RetryPolicy(
initial_interval=dt.tim... | 22 | 581 |
posthog | products/exports/backend/temporal/subscriptions/delivery_common.py | .py | from collections.abc import Awaitable, Callable
from typing import Any
from slack_sdk.errors import SlackApiError
from structlog import get_logger
from temporalio.exceptions import ApplicationError
from posthog.email import EmailDeliveryError
from posthog.exceptions_capture import capture_exception
from posthog.model... | 241 | 11,117 |
posthog | products/exports/backend/temporal/subscriptions/test_types.py | .py | from parameterized import parameterized
from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
from products.exports.backend.temporal.subscriptions.types import (
UNDISCLOSED_QUERY_ERROR_TYPES,
DeliveryStatus,
GenerateAIReportResult,
)
def test_undisclosed_query_error_types_track_the_exceptio... | 95 | 4,440 |
posthog | products/exports/backend/temporal/subscriptions/test_delivery_summary.py | .py | from unittest.mock import MagicMock
from ee.tasks.subscriptions.slack_subscriptions import _prepare_slack_message
def _make_subscription(title: str = "Weekly report"):
sub = MagicMock()
sub.title = title
sub.target_value = "C12345|#test-channel"
resource_info = MagicMock()
resource_info.kind = "I... | 72 | 2,594 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py | .py | import uuid
import asyncio
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import UTC, datetime
from enum import StrEnum
from typing import Optional, Union
import structlog
from posthog.schema import AssistantHogQLQuery
from posthog.hogql.errors import ExposedHogQLError, Internal... | 552 | 25,084 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py | .py | import re
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta, tzinfo
from typing import Optional, Union
from django.db.models import F, Q
import structlog
from pydantic import ValidationError
from posthog.schema import CachedTeamTaxonomyQueryResponse,... | 615 | 28,379 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/schemas.py | .py | from typing import Literal
from pydantic import BaseModel, Field
# Hard cap on AI report query-plan steps β the contract the schema validator, planner prompt, and
# synthesis result budget all key off. Named once here so they can't silently drift apart.
MAX_QUERY_PLAN_STEPS = 25
class QueryPlanStep(BaseModel):
... | 46 | 1,696 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py | .py | import uuid
from datetime import UTC, datetime
from urllib.parse import urlencode
import nh3
import structlog
from markdown_it import MarkdownIt
from markdown_to_mrkdwn import SlackMarkdownConverter
from posthog.email import EmailMessage, raise_if_delivery_rejected
from posthog.exceptions_capture import capture_excep... | 375 | 14,590 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/activities.py | .py | import uuid
import datetime as dt
import dataclasses
from datetime import datetime
from django.utils import timezone as tz
import dateutil.parser
import temporalio.activity
from asgiref.sync import sync_to_async
from structlog import get_logger
from temporalio.exceptions import ApplicationError
from posthog.dataclas... | 374 | 18,212 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py | .py | import re
from typing import Literal
import structlog
from posthog.models import Team
from posthog.ph_client import ph_scoped_capture
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
logger = structlog.get_logger(__name__)
# LLMPrompt names a team can author in the Prompt product to overri... | 408 | 23,150 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py | .py | from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
from posthog.schema import CachedTeamTaxonomyQueryResponse, TeamTaxonomyItem, TeamTaxonomyQuery
from ... | 935 | 45,687 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py | .py | import uuid
from datetime import UTC, datetime, timedelta
import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, MagicMock, patch
from parameterized import parameterized
from posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES
from products.exports.backend.models.subscrip... | 504 | 23,355 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py | .py | from datetime import datetime
from zoneinfo import ZoneInfo
import pytest
from asgiref.sync import sync_to_async
from parameterized import parameterized
from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery
from products.exports.backend.temporal.subscriptions.ai_subscription.act... | 211 | 8,363 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/test/test_prompts.py | .py | from unittest.mock import MagicMock, patch
from parameterized import parameterized
from products.exports.backend.temporal.subscriptions.ai_subscription.prompts import resolve_prompt
_P = "products.exports.backend.temporal.subscriptions.ai_subscription.prompts"
@patch(f"{_P}.ph_scoped_capture")
@patch(f"{_P}.get_pr... | 72 | 2,610 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline_integration.py | .py | from datetime import UTC, datetime
from posthog.test.base import (
ClickhouseTestMixin,
NonAtomicBaseTest,
_create_event,
_create_person,
flush_persons_and_events,
)
from unittest.mock import MagicMock, patch
from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline impo... | 191 | 10,112 |
posthog | products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py | .py | import asyncio
from datetime import UTC, datetime, timedelta
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, ResolutionError
from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
from products.exports.backend.tem... | 711 | 31,852 |
posthog | products/exports/backend/tests/test_facade.py | .py | from django.test import SimpleTestCase
from parameterized import parameterized
from products.exports.backend.facade.api import _validate_adhoc_export_context
class TestValidateAdhocExportContext(SimpleTestCase):
def test_accepts_insight_viz_wrapped_source(self):
_validate_adhoc_export_context(
... | 25 | 921 |
posthog | products/exports/backend/tests/test_exported_asset_model.py | .py | from datetime import UTC, datetime, timedelta
from tempfile import NamedTemporaryFile
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from parameterized import parameterized
from posthog.storage.object_storage import ObjectStorageError
from products.export... | 259 | 9,893 |
posthog | products/exports/backend/api/exports.py | .py | from datetime import timedelta
from typing import Any, Literal
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.timezone import now
import structlog
import posthoganalytics
from ... | 598 | 27,649 |
posthog | products/exports/backend/api/test/test_exports.py | .py | from contextlib import nullcontext
from datetime import datetime, timedelta
from typing import Optional
import pytest
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, _create_event, flush_persons_and_events
from unittest.mock import ANY, AsyncMock, patch
from django.http import HttpRespons... | 1,899 | 81,042 |
posthog | products/exports/backend/facade/exporters.py | .py | from collections.abc import Callable
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from products.exports.backend.models.exported_asset import ExportedAsset
ExportFormatHandler = Callable[["ExportedAsset"], None]
_export_format_handlers: dict[str, ExportFormatHandler] = {}
def register_export_format_handl... | 22 | 801 |
posthog | products/exports/backend/facade/api.py | .py | """Public Python interface for creating and retrieving one-off exports."""
from collections.abc import Collection
from datetime import timedelta
from django.conf import settings
from django.http.response import HttpResponseBase
import structlog
from asgiref.sync import async_to_sync
from temporalio.common import Wor... | 238 | 9,667 |
posthog | products/exports/backend/models/__init__.py | .py | from .exported_asset import ExportedAsset
from .subscription import Subscription, SubscriptionDelivery
__all__ = [
"ExportedAsset",
"Subscription",
"SubscriptionDelivery",
]
| 9 | 187 |
posthog | products/exports/backend/models/exported_asset.py | .py | import re
import secrets
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.ut... | 377 | 15,348 |
posthog | products/exports/backend/models/subscription.py | .py | import sys
from collections.abc import Iterator
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from django.contrib.postgres.fields import ArrayField
from d... | 646 | 27,297 |
posthog | products/exports/backend/admin/subscription_admin.py | .py | from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from posthog.admin.paginators.no_count_paginator import NoCountPaginator
from products.exports.backend.models.subscription import Subscription
@admin.register(Subscription)
class SubscriptionAdmin(admin.ModelA... | 49 | 1,437 |
posthog | products/exports/backend/admin/exported_asset_admin.py | .py | from urllib.parse import urljoin
from django.conf import settings
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from products.exports.backend.models.exported_asset import ExportedAsset
@admin.register(ExportedAsset)
class ExportedAssetAdmin(admin.ModelAdm... | 86 | 2,575 |
posthog | products/approvals/backend/scheduled_changes.py | .py | """Creation-time approval gating for feature-flag scheduled changes.
A ``ScheduledChange`` row is created ungated and later applied by the Celery task
``process_scheduled_changes`` via ``FeatureFlag.scheduled_changes_dispatcher``. Without this
module a scheduled change could flip a policy-gated field (enabling a flag,... | 358 | 18,301 |
posthog | products/approvals/backend/notifications.py | .py | from typing import TYPE_CHECKING
from structlog import get_logger
from posthog.email import EmailMessage, get_email_team_and_org_context, is_email_available
from posthog.models import User
from posthog.utils import absolute_uri
from products.notifications.backend.facade.api import (
NotificationData,
Notific... | 300 | 10,254 |
posthog | products/approvals/backend/exceptions.py | .py | class ApprovalException(Exception):
"""Base exception for approval-related errors"""
pass
class PreconditionFailed(ApprovalException):
"""Raised when preconditions for applying a change no longer hold"""
pass
class ApplyFailed(ApprovalException):
"""Raised when applying an approved change fail... | 85 | 2,300 |
posthog | products/approvals/backend/models.py | .py | from datetime import timedelta
from typing import TYPE_CHECKING, Optional
from django.db import models
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
if TYPE_CHECKING:
from products.approvals.backend.actions.base import BaseAction
from products.approvals.backend.models impor... | 239 | 8,184 |
posthog | products/approvals/backend/apps.py | .py | from django.apps import AppConfig
class ApprovalsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "products.approvals.backend"
label = "approvals"
| 8 | 191 |
posthog | products/approvals/backend/serializers.py | .py | from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from posthog.api.shared import UserBasicSerializer
from products.approvals.backend.models import Approval, ApprovalPolicy, ChangeRequest
class ChangeRequestSerializer(serializers.ModelSerializer):
created_by = UserBasic... | 276 | 9,622 |
posthog | products/approvals/backend/routes.py | .py | from posthog.api.routing import RouterRegistry
from products.approvals.backend import api as approval_api
def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"change_requests",
approval_api.ChangeRequestViewSet,
"project_change_requests",
["team_id"],... | 19 | 496 |
posthog | products/approvals/backend/permissions.py | .py | from rest_framework import permissions
class CanApprove(permissions.BasePermission):
"""
Checks:
1. User is in the approver set (from policy_snapshot)
2. User is not the requester (if self-approval not allowed)
"""
message = "You do not have permission to approve this change request"
def... | 70 | 2,441 |
posthog | products/approvals/backend/services.py | .py | import logging
from dataclasses import dataclass
from typing import Any, Optional
from django.db import transaction
from django.utils import timezone
from posthog.event_usage import report_user_action
from posthog.models import User
from products.approvals.backend.actions.registry import get_action
from products.app... | 417 | 14,903 |
posthog | products/approvals/backend/decorators.py | .py | import logging
from dataclasses import dataclass, field
from functools import wraps
from typing import Any, Literal, Optional, Union
from django.conf import settings
from django.db import transaction
from django.utils import timezone
from rest_framework import status
from rest_framework.exceptions import APIException... | 586 | 22,967 |
posthog | products/approvals/backend/mixins.py | .py | from rest_framework import status
from rest_framework.response import Response
from products.approvals.backend.exceptions import ApprovalRequired, PolicyConflict
from products.approvals.backend.serializers import ChangeRequestSerializer
class ApprovalHandlingMixin:
"""
Mixin for ViewSets to handle approval-g... | 46 | 1,880 |
posthog | products/approvals/backend/api.py | .py | import logging
from typing import Any, cast
from django.db.models import QuerySet
import django_filters
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema
from rest_framework import exceptions, status, viewsets
from rest_framework.decorators import action
fro... | 220 | 9,105 |
posthog | products/approvals/backend/policies.py | .py | from dataclasses import dataclass
from typing import Any
@dataclass
class PolicyDecision:
"""Result of policy evaluation"""
result: str
reason: str
message: str
approvers: dict
policy_snapshot: dict
class PolicyEngine:
"""Evaluates approval policies"""
COMPARISON_OPERATORS = {
... | 346 | 11,782 |
posthog | products/approvals/backend/tasks.py | .py | from typing import Any
from django.db import transaction
from django.utils import timezone
from celery import shared_task
from structlog import get_logger
from posthog.scoping_audit import skip_team_scope_audit
from products.approvals.backend.models import ChangeRequest, ChangeRequestState, ValidationStatus
from pr... | 166 | 6,288 |
posthog | products/approvals/backend/actions/feature_flags.py | .py | from abc import abstractmethod
from typing import Any, Optional
from django.db import transaction
from products.approvals.backend.actions.base import BaseAction
from products.approvals.backend.exceptions import ApplyFailed, PreconditionFailed
from products.feature_flags.backend.api.feature_flag import FeatureFlagSeri... | 638 | 25,263 |
posthog | products/approvals/backend/actions/registry.py | .py | from typing import Optional
from products.approvals.backend.actions.base import BaseAction
ACTION_REGISTRY: dict[str, type[BaseAction]] = {}
def register_actions():
from products.approvals.backend.actions.feature_flags import (
DisableFeatureFlagAction,
EnableFeatureFlagAction,
UpdateFea... | 24 | 733 |
posthog | products/approvals/backend/actions/base.py | .py | from abc import ABC, abstractmethod
from typing import Any, Optional
from posthog.models import Team
class BaseAction(ABC):
"""
Base class for all gatable actions.
Each action defines:
- How to detect if a request matches
- How to extract intent from a request
- How to validate intent
- ... | 188 | 5,808 |
posthog | products/approvals/backend/tests/test_notifications.py | .py | from datetime import timedelta
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.utils import timezone
from posthog.email import CUSTOMER_IO_TEMPLATE_ID_MAP
from posthog.models.instance_setting import override_instance_config
from products.approvals.backend.models import ... | 572 | 25,929 |
posthog | products/approvals/backend/tests/test_create_feature_flag_gate.py | .py | from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from products.approvals.backend.actions.feature_flags import (
DisableFeatureFlagAction,
EnableFeatureFlagAction,
UpdateFeatureFlagAction,
)
from products.approvals.backend.models import ApprovalPol... | 265 | 12,844 |
posthog | products/approvals/backend/tests/test_tasks.py | .py | from datetime import timedelta
from posthog.test.base import BaseTest
from unittest.mock import patch
from django.utils import timezone
from parameterized import parameterized
from products.approvals.backend.models import ChangeRequest
from products.approvals.backend.tasks import expire_old_change_requests, validat... | 160 | 6,408 |
posthog | products/approvals/backend/tests/test_services.py | .py | from datetime import timedelta
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.utils import timezone
from parameterized import parameterized
from products.approvals.backend.exceptions import InvalidStateError
from products.approvals.backend.models import ChangeRequest, ... | 54 | 1,991 |
posthog | products/approvals/backend/tests/test_scheduled_change_gating.py | .py | from datetime import UTC, datetime, timedelta
from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.utils import timezone
from posthog.models import User
from posthog.tasks.process_scheduled_changes import process_scheduled_changes
from products.approvals.backe... | 750 | 33,768 |
posthog | products/approvals/backend/tests/test_update_feature_flag_action.py | .py | from datetime import timedelta
from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.utils import timezone
from parameterized import parameterized
from posthog.models import Team
from products.approvals.backend.actions.feature_flags import (
Dis... | 627 | 24,571 |
posthog | products/approvals/backend/tests/test_feature_flag_bypass_matrix.py | .py | """Consolidated adversarial bypass matrix for feature-flag approval gating.
This is the living catalog of every mutation path that can change a policy-gated
feature-flag field, and the regression lock proving each one routes through the
approval gate. The headline invariant: with an enabled policy, NOTHING changes a
g... | 564 | 24,254 |
posthog | products/approvals/backend/tests/test_policy_engine.py | .py | from collections.abc import Sequence
from posthog.test.base import APIBaseTest
from parameterized import parameterized
from posthog.models.organization import OrganizationMembership
from products.approvals.backend.models import ApprovalPolicy
from products.approvals.backend.policies import PolicyEngine
class Test... | 381 | 14,385 |
posthog | products/approvals/backend/tests/test_decorators.py | .py | from contextlib import suppress
from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from posthog.api.utils import ServiceRequest
from products.approvals.backend.exceptions import ApprovalRequired
from products.approvals.backend.models import ApprovalPolicy, Cha... | 158 | 5,658 |
posthog | products/approvals/backend/tests/test_approvals_api.py | .py | from datetime import timedelta
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models import User
from products.approvals... | 790 | 32,567 |
posthog | products/alerts/backend/destinations.py | .py | """Django persistence and dispatch for alert notification destinations."""
from __future__ import annotations
import re
from collections.abc import Collection, Sequence
from dataclasses import asdict, dataclass
from datetime import datetime
from typing import Any
from urllib.parse import urlsplit
from uuid import UUI... | 289 | 10,658 |
posthog | products/alerts/backend/admin.py | .py | from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from posthog.admin.paginators.no_count_paginator import NoCountPaginator
from products.alerts.backend.models.alert import AlertConfiguration
@admin.register(AlertConfiguration)
class AlertConfigurationAdmin(ad... | 48 | 1,418 |
posthog | products/alerts/backend/email_notifications.py | .py | from collections.abc import Collection
from posthog.email import EmailMessage
def send_alert_email(
*,
recipients: Collection[str],
campaign_key: str,
subject: str,
template_name: str,
template_context: dict[str, object],
) -> None:
message = EmailMessage(
campaign_key=campaign_ke... | 23 | 533 |
posthog | products/alerts/backend/apps.py | .py | from django.apps import AppConfig
class AlertsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "products.alerts.backend"
label = "alerts"
def ready(self) -> None:
# Connect the alert activity-log and cleanup receivers (hog-function teardown,
# subscriptio... | 16 | 723 |
posthog | products/alerts/backend/delivery_slo.py | .py | from collections.abc import Iterator, Mapping
from contextlib import contextmanager
from posthog.slo.context import JsonValue, SloHandle, SloSpec, slo_operation
from posthog.slo.types import SloArea, SloOperation
from posthog.utils import get_instance_region
@contextmanager
def alert_delivery_slo(
*,
alert_t... | 35 | 1,020 |
posthog | products/alerts/backend/scheduling.py | .py | """Scheduling math for alert checks.
Sub-daily checks preserve their existing cadence. Daily, weekly, and monthly
checks anchor to calendar instants in the team's local timezone. Quiet hours
and weekend skipping layer local-time restrictions on top of those schedules.
Pure Python with no Django or model imports. Time... | 448 | 16,535 |
posthog | products/alerts/backend/activity_logging.py | .py | """Activity-log and cleanup receivers for alert configuration changes.
Kept in their own import-light module so the alerts AppConfig can wire them at ready()
without importing the API module β whose module-scope imports reach the alert detector
stack (posthog.tasks.alerts -> numpy). The Temporal/celery alert-check pat... | 163 | 6,402 |
posthog | products/alerts/backend/max_tools.py | .py | from textwrap import dedent
from typing import Any, Literal, Union, cast
from django.core.exceptions import ValidationError
from django.db import transaction
from asgiref.sync import sync_to_async
from pydantic import BaseModel, Field
from posthog.schema import (
AlertCalculationInterval,
AlertConditionType,... | 567 | 24,786 |
posthog | products/alerts/backend/routes.py | .py | from posthog.api.routing import RouterRegistry
import products.alerts.backend.api.alert as alert
def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"alerts",
alert.AlertViewSet,
"project_alerts",
["team_id"],
)
# ThresholdViewSet is registere... | 15 | 458 |
posthog | products/alerts/backend/insight_alert_state_machine.py | .py | from __future__ import annotations
from datetime import datetime, timedelta
from typing import TYPE_CHECKING
from posthog.schema_enums import AlertState as InsightAlertState
from products.alerts.backend.state_machine import (
AlertCheckOutcome,
AlertPolicy,
AlertSnapshot,
AlertState,
CheckInput,
... | 103 | 3,117 |
posthog | products/alerts/backend/state_machine.py | .py | """Shared alert lifecycle state machine.
Products (logs, billing, ...) each evaluate their own domain data, but the alert
lifecycle β firing, resolving, erroring, breaking, snoozing, cooldown suppression β
is the same machine everywhere. This module is that machine, following the
Prometheus/Alertmanager split: evaluat... | 384 | 14,998 |
posthog | products/alerts/backend/destination_configs.py | .py | """Shared configuration builders for alert destinations."""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, NotRequired, TypedDict
from django.db import models
class DestinationType(models.TextChoices):
SLACK = "slack", "Slack"
... | 230 | 7,650 |
posthog | products/alerts/backend/test_max_tools.py | .py | from datetime import UTC, datetime
import pytest
from posthog.test.base import BaseTest
from unittest import mock
import pydantic
from asgiref.sync import sync_to_async
from langchain_core.runnables import RunnableConfig
from parameterized import parameterized
from posthog.schema import AlertCalculationInterval, Ale... | 663 | 25,874 |
posthog | products/alerts/backend/evaluation/comparator.py | .py | from collections.abc import Callable
from posthog.schema import (
AlertCondition,
AlertConditionType,
InsightsThresholdBounds,
InsightThreshold,
InsightThresholdType,
IntervalType,
)
from posthog.tasks.alerts.utils import AlertEvaluationResult
from products.alerts.backend.evaluation.contract ... | 190 | 7,674 |
posthog | products/alerts/backend/evaluation/hogql.py | .py | import math
from decimal import Decimal
from typing import Any
from posthog.schema import AlertCondition, AlertConditionType, HogQLAlertConfig, HogQLAlertEvaluation
from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results... | 429 | 22,370 |
posthog | products/alerts/backend/evaluation/detector.py | .py | from typing import Any, Optional, cast
from zoneinfo import ZoneInfo
import numpy as np
from posthog.schema import TrendsAlertConfig, TrendsQuery
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.clickhouse.query_tagging ... | 338 | 15,139 |
posthog | products/alerts/backend/evaluation/__init__.py | .py | from products.alerts.backend.evaluation.dispatcher import check_alert_for_insight
__all__ = ["check_alert_for_insight"]
| 4 | 121 |
posthog | products/alerts/backend/evaluation/contract.py | .py | from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Protocol
from posthog.schema import AlertCondition, AlertConditionType, IntervalType
from posthog.api.services.query import ExecutionMode
from posthog.models.team import Team
from posthog.models.user import User
from produ... | 135 | 6,584 |
posthog | products/alerts/backend/evaluation/trends.py | .py | from collections.abc import Callable
from typing import Any, cast
from posthog.schema import (
AlertCondition,
AlertConditionType,
InsightThreshold,
InsightThresholdType,
IntervalType,
TrendsAlertConfig,
TrendsQuery,
)
from posthog.api.services.query import ExecutionMode
from posthog.cachi... | 240 | 11,375 |
posthog | products/alerts/backend/evaluation/metrics.py | .py | from typing import Any
from posthog.schema import InsightThreshold, MetricsAlertConfig, MetricsQuery
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.event_usage import EventSource
from products.alerts.backend.evaluation... | 117 | 4,990 |
posthog | products/alerts/backend/evaluation/dispatcher.py | .py | from posthog.schema import AlertCondition, InsightThreshold, IntervalType, NodeKind
from posthog.api.services.query import ExecutionMode
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult
from posthog.utils import get_fro... | 95 | 5,317 |
posthog | products/alerts/backend/evaluation/funnel_strategies.py | .py | from typing import Any, cast
from posthog.schema import FunnelConversionMetric, FunnelsAlertConfig, FunnelsQuery, FunnelVizType
from products.alerts.backend.evaluation.contract import AlertExtractionError, ComparableSeries, SeriesPoint
# Funnel alerts evaluate a conversion-rate percentage (0β100): a steps funnel at ... | 231 | 11,979 |
posthog | products/alerts/backend/evaluation/funnels.py | .py | from typing import Any
from posthog.schema import AlertCondition, AlertConditionType, FunnelsAlertConfig, FunnelsQuery, IntervalType
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.event_usage import EventSource
from pos... | 98 | 4,885 |
posthog | products/alerts/backend/evaluation/validation.py | .py | from collections.abc import Callable
from dataclasses import dataclass
from pydantic import ValidationError as PydanticValidationError
from posthog.schema import (
AlertCalculationInterval,
AlertCondition,
AlertConditionType,
FunnelsAlertConfig,
FunnelsQuery,
HogQLAlertConfig,
HogQLAlertEv... | 364 | 16,002 |
posthog | products/alerts/backend/evaluation/formatting.py | .py | """Format alert-breach values and breakdown labels the way the insight itself displays them.
This is a backend port of the frontend `formatAggregationAxisValue`
(`frontend/src/scenes/insights/aggregationAxisFormat.ts`): given a trends insight's axis config
(`aggregationAxisFormat`, prefix/postfix, decimal places) plus... | 217 | 8,345 |
posthog | products/alerts/backend/evaluation/test/test_high_frequency_freshness.py | .py | import pytest
from unittest.mock import MagicMock, patch
from posthog.schema import (
AlertCalculationInterval,
AlertCondition,
AlertConditionType,
BaseMathType,
ChartDisplayType,
EventsNode,
InsightsThresholdBounds,
InsightThreshold,
InsightThresholdType,
IntervalType,
Node... | 173 | 7,103 |
posthog | products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py | .py | from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
from posthog.api.services.query import ExecutionMode
from products.alerts.backend.evaluation.hogql import HogQLExtractor
from products.alerts.backend.models.alert import A... | 68 | 2,967 |
posthog | products/alerts/backend/evaluation/test/test_date_range_overrides.py | .py | from unittest import TestCase
from unittest.mock import MagicMock, patch
import numpy as np
from parameterized import parameterized
from posthog.schema import AlertConditionType, DateRange, IntervalType, TrendsQuery
from posthog.api.services.query import ExecutionMode
from posthog.tasks.alerts.detector import _date_... | 126 | 5,502 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.