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/temporal/cleanup_property_definitions/__init__.py
.py
from posthog.temporal.cleanup_property_definitions.activities import ( delete_property_definitions_from_clickhouse, delete_property_definitions_from_postgres, preview_property_definitions, ) from posthog.temporal.cleanup_property_definitions.workflows import CleanupPropertyDefinitionsWorkflow WORKFLOWS = [...
17
511
posthog
posthog/temporal/cleanup_property_definitions/activities.py
.py
from uuid import uuid4 from django.conf import settings from django.db import transaction from structlog.contextvars import bind_contextvars from temporalio import activity from posthog.models import PropertyDefinition, Team from posthog.sync import database_sync_to_async from posthog.temporal.cleanup_property_defin...
145
5,872
posthog
posthog/temporal/event_screenshots/types.py
.py
from uuid import UUID from pydantic import BaseModel class GenerateEventScreenshotsInput(BaseModel): team_id: int = 0 class EventType(BaseModel): event_definition_id: UUID name: str team_id: int class EventSession(BaseModel): session_id: str url: str timestamp: int class LoadEventSe...
43
766
posthog
posthog/temporal/event_screenshots/workflows.py
.py
from datetime import timedelta from temporalio import common, workflow from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.event_screenshots.activities import ( load_event_sessions, load_event_types, store_event_screenshot, take_event_screenshot, ) from posthog.temporal.even...
71
2,728
posthog
posthog/temporal/event_screenshots/__init__.py
.py
from posthog.temporal.event_screenshots.activities import ( load_event_sessions, load_event_types, store_event_screenshot, take_event_screenshot, ) from posthog.temporal.event_screenshots.workflows import GenerateEventScreenshotsWorkflow WORKFLOWS = [ GenerateEventScreenshotsWorkflow, ] ACTIVITIES...
19
429
posthog
posthog/temporal/event_screenshots/activities.py
.py
from uuid import uuid4 from django.db import connection from temporalio import activity from posthog.models import ObjectMediaPreview from posthog.sync import database_sync_to_async from posthog.tasks.exporter import export_asset_direct from posthog.temporal.common.clickhouse import get_client as get_ch_client from ...
173
4,666
posthog
posthog/temporal/usage_report/types.py
.py
"""Workflow + activity input/output models. All models use pydantic so the Temporal pydantic data converter handles `datetime` (and other rich types) natively — that lets us drop the ISO-string round-tripping that plain dataclasses would force. """ from datetime import datetime from typing import Literal, Optional f...
97
2,645
posthog
posthog/temporal/usage_report/workflow.py
.py
"""Temporal workflow that aggregates daily usage data and publishes it to S3 for the billing service. The workflow runs ~50 gather queries (each as its own retriable activity), then a single aggregation activity reads them all back from S3, builds one `FullUsageReport` dict per organization, and writes those reports a...
204
8,723
posthog
posthog/temporal/usage_report/storage.py
.py
"""S3 path conventions and IO helpers for the usage reports workflow. All keys are scoped under `{OBJECT_STORAGE_TASKS_FOLDER}/billing/usage_reports/{YYYY-MM-DD}/{run_id}/` so multiple runs on the same date never collide. The bucket is `settings.BILLING_USAGE_REPORTS_S3_BUCKET`, which falls back to `OBJECT_STORAGE_BUC...
121
3,971
posthog
posthog/temporal/usage_report/__init__.py
.py
from posthog.temporal.usage_report.activities import ( aggregate_and_chunk_org_reports, cleanup_intermediates, enqueue_pointer_message, run_query_to_s3, ) from posthog.temporal.usage_report.workflow import RunUsageReportsWorkflow WORKFLOWS = [ RunUsageReportsWorkflow, ] ACTIVITIES = [ run_quer...
19
424
posthog
posthog/temporal/usage_report/queries.py
.py
"""Registry of usage-report gathering queries. Each `QuerySpec` describes one fetch — typically one ClickHouse query, one Postgres aggregation, or one error-tracking API call — and how its result maps back to keys in the legacy `_get_all_usage_data` dict that `_get_team_report` consumes. Most queries produce a single...
705
28,958
posthog
posthog/temporal/usage_report/metrics.py
.py
"""Metric helpers for the usage-reports v2 sender pipeline. Everything records through the Temporal SDK metric meter (see `posthog.temporal.common.metrics.get_metric_meter`), so these series ride the worker's combined Prometheus endpoint alongside the built-in `temporal_*` metrics. Billing consumes the matching receiv...
106
3,967
posthog
posthog/temporal/usage_report/activities.py
.py
"""Temporal activities for the usage reports workflow. Each activity is a thin wrapper that delegates to either the public `posthog.tasks.usage_report` facade (org-report aggregation, instance metadata) or the local `aggregator` / `storage` modules. Heavy logic lives elsewhere so these stay easy to read and mock in te...
283
12,262
posthog
posthog/temporal/usage_report/aggregator.py
.py
"""Helpers for the aggregation step of the Temporal usage-reports flow. Most of this module is pure logic — turning S3-backed query results into the legacy `all_data` shape, fanning multi-key queries back out into their destination keys, and shaping per-organization JSONL lines for the chunked output. The Temporal-loc...
236
9,151
posthog
posthog/temporal/product_analytics/__init__.py
.py
from posthog.temporal.backfill_materialized_property import ( ACTIVITIES as BACKFILL_ACTIVITIES, BackfillMaterializedPropertiesBatchWorkflow, ) from .upgrade_queries_activities import get_insights_to_migrate, migrate_insights_batch from .upgrade_queries_workflow import UpgradeQueriesWorkflow WORKFLOWS = [ ...
18
496
posthog
posthog/temporal/product_analytics/upgrade_queries_workflow.py
.py
import json import datetime as dt import dataclasses from typing import Optional from temporalio import workflow from temporalio.common import RetryPolicy from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.product_analytics.upgrade_queries_activities import ( GetInsightsToMigrateActivi...
103
3,801
posthog
posthog/temporal/product_analytics/upgrade_queries_activities.py
.py
import textwrap import dataclasses from typing import Any, Optional, cast from django.db import connection from structlog import get_logger from temporalio import activity from posthog.exceptions_capture import capture_exception from posthog.schema_migrations import LATEST_VERSIONS, _discover_migrations from posthog...
98
3,394
posthog
posthog/temporal/delete_persons/__init__.py
.py
from posthog.temporal.delete_persons.delete_persons_workflow import ( DeletePersonsWorkflow, delete_persons_activity, preclean_cohort_members_activity, ) WORKFLOWS = [ DeletePersonsWorkflow, ] ACTIVITIES = [ delete_persons_activity, preclean_cohort_members_activity, ]
15
295
posthog
posthog/temporal/delete_persons/delete_persons_workflow.py
.py
import json import typing import asyncio import datetime as dt import itertools import dataclasses import temporalio.common import temporalio.activity import temporalio.workflow from structlog import get_logger from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.common.heartbeat import Hear...
252
9,800
posthog
posthog/temporal/dlq_replay/workflow.py
.py
import json import asyncio import datetime as dt import dataclasses from temporalio import workflow from temporalio.common import RetryPolicy from posthog.temporal.common.base import PostHogWorkflow with workflow.unsafe.imports_passed_through(): from posthog.temporal.dlq_replay.activities import ( GetTop...
137
4,896
posthog
posthog/temporal/dlq_replay/__init__.py
.py
from posthog.temporal.dlq_replay.activities import get_topic_partitions, replay_partition from posthog.temporal.dlq_replay.workflow import DLQReplayWorkflow WORKFLOWS = [DLQReplayWorkflow] ACTIVITIES = [get_topic_partitions, replay_partition]
6
244
posthog
posthog/temporal/dlq_replay/activities.py
.py
import ssl import asyncio import dataclasses import aiokafka from aiokafka import TopicPartition from structlog import get_logger from temporalio import activity from posthog.kafka_client.routing import get_profile_settings from posthog.temporal.common.heartbeat import Heartbeater LOGGER = get_logger(__name__) @da...
237
8,445
posthog
posthog/temporal/data_modeling/__init__.py
.py
from posthog.temporal.data_modeling.activities import ( check_duckgres_shadow_enabled_activity, create_data_modeling_job_activity, enrich_view_semantics_activity, fail_materialization_activity, get_dag_structure_activity, materialize_view_activity, materialize_view_duckgres_activity, not...
60
2,099
posthog
posthog/temporal/data_modeling/metrics.py
.py
from temporalio import activity, workflow from temporalio.common import MetricCounter, MetricHistogramFloat # custom latency histogram buckets, # since we lose some important granularity with default max at 60s DATA_MODELING_LATENCY_HISTOGRAM_METRICS = ( "temporal_activity_execution_latency", "temporal_activit...
189
6,136
posthog
posthog/temporal/data_modeling/run_workflow.py
.py
"""Data-modeling Temporal workflow v1 — FROZEN. Do not extend this module. v1 is being migrated to v2, which lives at `posthog/temporal/data_modeling/workflows/{materialize_view,execute_dag}.py`. New features, bug fixes for new behavior, and refactors belong in v2. Bug fixes that affect both versions can land here, b...
1,871
77,104
posthog
posthog/temporal/data_modeling/workflows/__init__.py
.py
from .enrich_view_semantics import EnrichViewSemanticsWorkflow from .execute_dag import ExecuteDAGWorkflow from .materialize_view import MaterializeViewWorkflow __all__ = [ "MaterializeViewWorkflow", "ExecuteDAGWorkflow", "EnrichViewSemanticsWorkflow", ]
10
268
posthog
posthog/temporal/data_modeling/workflows/execute_dag.py
.py
import json import asyncio import datetime as dt import dataclasses from collections import defaultdict import temporalio.common import temporalio.workflow import temporalio.exceptions from temporalio.workflow import ParentClosePolicy from posthog.exceptions_capture import capture_exception from posthog.temporal.comm...
531
22,209
posthog
posthog/temporal/data_modeling/workflows/materialize_view.py
.py
import json import datetime as dt import dataclasses from django.conf import settings import temporalio.common import temporalio.workflow import temporalio.exceptions from temporalio.exceptions import WorkflowAlreadyStartedError from posthog.exceptions_capture import capture_exception from posthog.temporal.common.ba...
484
22,271
posthog
posthog/temporal/data_modeling/workflows/enrich_view_semantics.py
.py
from datetime import timedelta from temporalio import workflow from temporalio.common import RetryPolicy from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.data_modeling.activities.enrich_view_semantics import ( EnrichViewSemanticsInputs, enrich_view_semantics_activity, ) @workfl...
28
947
posthog
posthog/temporal/data_modeling/activities/get_dag_structure.py
.py
import dataclasses from temporalio import activity from posthog.sync import database_sync_to_async_pool from posthog.temporal.common.logger import get_logger from products.data_modeling.backend.facade.models import DataModelingJobEngine, Edge, Node, NodeType from .utils import is_node_suspended, is_suspension_enfor...
90
3,444
posthog
posthog/temporal/data_modeling/activities/succeed_materialization.py
.py
import datetime as dt import dataclasses from django.db import transaction from celery import current_app from structlog import get_logger from structlog.contextvars import bind_contextvars from temporalio import activity from posthog.exceptions_capture import capture_exception from posthog.sync import database_sync...
165
6,022
posthog
posthog/temporal/data_modeling/activities/utils.py
.py
import re import datetime as dt from typing import TYPE_CHECKING from uuid import UUID from django.db import transaction from structlog.contextvars import bind_contextvars from posthog.models import Team from posthog.ph_client import feature_enabled_or_false from posthog.sync import database_sync_to_async_pool from ...
251
10,326
posthog
posthog/temporal/data_modeling/activities/create_data_modeling_job.py
.py
import dataclasses from structlog import get_logger from structlog.contextvars import bind_contextvars from temporalio import activity from posthog.sync import database_sync_to_async_pool from posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_context from products.data_modeling.backend.fa...
186
7,360
posthog
posthog/temporal/data_modeling/activities/preempt_dag_run.py
.py
import dataclasses from structlog import get_logger from structlog.contextvars import bind_contextvars from temporalio import activity from temporalio.client import Client, WorkflowExecutionStatus from temporalio.service import RPCError, RPCStatusCode from posthog.exceptions_capture import capture_exception from post...
189
8,780
posthog
posthog/temporal/data_modeling/activities/fail_materialization.py
.py
import datetime as dt import dataclasses from uuid import UUID from django.db import transaction from structlog import get_logger from structlog.contextvars import bind_contextvars from temporalio import activity from posthog.exceptions_capture import capture_exception from posthog.sync import database_sync_to_async...
212
8,786
posthog
posthog/temporal/data_modeling/activities/__init__.py
.py
from .create_data_modeling_job import ( UPSTREAM_NAMES_IN_SKIP_REASON, CreateDataModelingJobInputs, RecordSkippedDataModelingJobsInputs, SkippedDataModelingNode, create_data_modeling_job_activity, record_skipped_data_modeling_jobs_activity, ) from .enrich_view_semantics import EnrichViewSemantic...
66
2,392
posthog
posthog/temporal/data_modeling/activities/notify_materialization_failure.py
.py
"""Telling people a materialized view broke. Two shapes, because a failure arrives two ways: - A view materialized on its own ("Sync now", a single-node schedule) notifies from its own failure path, in `maybe_notify_materialization_failure`. - A view materialized inside a DAG run leaves the in-app notification to t...
301
12,580
posthog
posthog/temporal/data_modeling/activities/materialize_view.py
.py
import uuid import typing import asyncio import dataclasses from django.conf import settings import pyarrow as pa import deltalake import pyarrow.compute as pc import pyarrow.parquet as pq from structlog.contextvars import bind_contextvars from structlog.types import FilteringBoundLogger from temporalio import activi...
851
36,685
posthog
posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
.py
import time import typing import datetime as dt import dataclasses from structlog.contextvars import bind_contextvars from temporalio import activity from posthog.exceptions_capture import capture_exception from posthog.models import Team from posthog.ph_client import feature_enabled_or_false from posthog.sync import...
261
9,072
posthog
posthog/temporal/data_modeling/activities/incremental_write.py
.py
"""Upsert a batch of materialized rows into an existing Delta table, via deltalite. deltalite rather than delta-rs's MERGE because it commits once per batch instead of once per partition, keeps memory bounded, re-plans internally on a commit conflict, and — the reason that matters most here — has no DataFusion in its ...
202
9,018
posthog
posthog/temporal/data_modeling/activities/prepare_queryable_table.py
.py
import dataclasses from structlog import get_logger from temporalio import activity from posthog.sync import database_sync_to_async_pool from posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_context from products.data_modeling.backend.facade.api import promote_view_nodes_to_matview from ...
101
3,999
posthog
posthog/temporal/data_modeling/activities/enrich_view_semantics.py
.py
import dataclasses from typing import Any from temporalio import activity from posthog.exceptions_capture import capture_exception from posthog.sync import database_sync_to_async from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater from posthog.temporal.common.logger import get_write_only_...
47
1,812
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/types.py
.py
"""Workflow inputs/outputs. Specs carry a day + hash bucket only — ids and scores never cross the workflow boundary.""" from dataclasses import dataclass, field @dataclass class ExportScoresSweepInputs: pass @dataclass class ExportPartitionSpec: day: str # YYYY-MM-DD (UTC) chunk_id: int of_chunks:...
39
794
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py
.py
"""Daily tick: plan the (day × hash bucket) fan-out, export all partitions in parallel. Failed partitions don't fail the tick — deterministic keys mean the next run rewrites them.""" from __future__ import annotations import asyncio from temporalio import workflow from temporalio.common import RetryPolicy from post...
120
4,699
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/sql.py
.py
"""ClickHouse statement for the surfacing-score export sweep.""" SESSION_REPLAY_EVENTS_TABLE = "session_replay_events" def fetch_scored_sessions_page_sql(replay_events_table: str = SESSION_REPLAY_EVENTS_TABLE) -> str: """One keyset-paginated page of a (day, hash bucket) export slice. Bound parameters: %(of_c...
57
2,544
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/__init__.py
.py
from posthog.temporal.session_replay.surfacing_score_export_sweep.activities import ( export_scores_partition_activity, list_export_partitions_activity, ) from posthog.temporal.session_replay.surfacing_score_export_sweep.workflow import ExportSurfacingScoresWorkflow SURFACING_SCORE_EXPORT_SWEEP_WORKFLOWS = [Ex...
9
459
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/constants.py
.py
"""Static config for the surfacing-score export sweep: daily export of scored sessions from `session_replay_events` to the ML-account S3 bucket as dt-partitioned Parquet, keyed by the ML mirror's pseudonymous ids.""" from datetime import date, timedelta from posthog.temporal.session_replay.surfacing_scoring_sweep.con...
56
2,491
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/s3.py
.py
"""Destination config, object-key layout, and upload helper — same `{prefix}/dt=.../part-*.parquet` layout as the ML mirror's Parquet store, but with deterministic part names so re-runs overwrite. The destination is its own `SESSION_RECORDING_ML_SCORE_EXPORT_S3_*` config with NO fallback to the `SESSION_RECORDING_V2_S...
64
2,484
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/schedule.py
.py
"""Singleton per-region Schedule for the daily score export tick.""" from __future__ import annotations from django.conf import settings import structlog from temporalio import common from temporalio.client import ( Client, Schedule, ScheduleActionStartWorkflow, ScheduleIntervalSpec, ScheduleOver...
67
2,483
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/metrics.py
.py
"""Tick-level metrics for the surfacing score export sweep. The workflow gathers partition results with return_exceptions=True and summarizes rather than raising, so a tick where every partition fails still completes successfully. These counters make that visible: without them a total failure is only a log line, and t...
36
1,893
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py
.py
"""Activities: plan the (day × hash bucket) fan-out, then per partition fetch → pseudonymize → Parquet → S3 put. All scored sessions are exported, pseudonymized with the ML mirror's exact pseudonym scheme, so exported ids join onto `block-metadata` — which only exists for AI-training opted-in orgs (the mirror's gate) ...
209
7,725
posthog
posthog/temporal/session_replay/surfacing_score_export_sweep/pseudonymize.py
.py
"""Python port of the ML mirror's pseudonymization (`nodejs/.../ml-mirror/pseudonymize.ts` + `pseudonym-key.ts`). Must stay byte-identical, same key and env vars, or exported scores stop joining onto the mirrored dataset.""" from __future__ import annotations import os import hmac import hashlib import threading from...
97
3,289
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/types.py
.py
"""Dataclasses for the surfacing-scoring workflow inputs and outputs. All payloads are intentionally tiny so they fit comfortably under Temporal's ~2 MiB payload limit. Session IDs and feature vectors never flow through the workflow — each activity re-queries ClickHouse for its slice using the deterministic hash parti...
61
1,717
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/scorer.py
.py
"""XGBoost booster lifecycle for the session surfacing scorer. The booster is loaded **once per worker process** and held as a module-level singleton. XGBoost predict releases the GIL and is parallelized internally by libomp; we want libomp to use the worker pod's full CPU budget on a single chunk at a time, not split...
208
7,983
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py
.py
"""Parent workflow for session surfacing scoring. Per tick (driven by `schedule.py`): 1. `list_chunks_activity` plans the fan-out — N deterministic hash-partitioned chunks, each carrying a `(chunk_id, of_chunks, chunk_size)` spec only. 2. All chunks are dispatched via `asyncio.gather` so they run in par...
129
5,097
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/sql.py
.py
"""ClickHouse statements for the session surfacing scoring pipeline. The serving SELECT mirrors the training query in four CTEs: 1. `eligible_sessions`: hash-partitioned slice of unscored, eventful sessions (`HAVING max(surfacing_score) IS NULL AND sum(event_count) > 0`) from `session_replay_events`...
394
22,620
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/__init__.py
.py
"""Temporal pipeline that writes surfacing scores onto session_replay_events. See README.md in this directory for the architecture rationale. """ from posthog.temporal.session_replay.surfacing_scoring_sweep.activities import ( list_chunks_activity, score_chunk_activity, ) from posthog.temporal.session_replay....
14
535
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/constants.py
.py
"""Static config for the session surfacing scoring pipeline. The pipeline runs on a fixed Schedule (every SCHEDULE_INTERVAL) and per tick scores up to TARGET_SESSIONS_PER_TICK unscored sessions, sharded into DEFAULT_OF_CHUNKS deterministic hash buckets. """ from datetime import timedelta WORKFLOW_NAME = "score-sessi...
64
2,999
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/schedule.py
.py
"""Singleton Schedule lifecycle for the session scoring tick. This is intentionally a single global Schedule, not per-team — the underlying work is regional (one CH cluster per region) and the chunk fan-out is sized for total per-region throughput. Use `a_upsert_schedule()` once per region during deploy to register th...
102
4,091
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/feature_schema.py
.py
"""Parity checks for fetch_features_sql(), FEATURE_RANGES, and booster.feature_names.""" from __future__ import annotations from posthog.temporal.session_replay.surfacing_scoring_sweep.features import FEATURE_RANGES, assert_ranges_cover from posthog.temporal.session_replay.surfacing_scoring_sweep.sql import feature_c...
68
3,125
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/metrics.py
.py
import typing from django.conf import settings from temporalio import activity from temporalio.worker import ActivityInboundInterceptor, ExecuteActivityInput, Interceptor from posthog.temporal.ai_observability.metrics import ExecutionTimeRecorder, get_metric_meter SCORE_CHUNK_ACTIVITY_TYPE = "score_chunk_activity" ...
73
3,092
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/features.py
.py
"""Runtime range contract + parity validation for the session surfacing model. The XGBoost booster is the single source of truth for *which* features the model takes (its `.ubj` embeds `feature_names`); the worker reads them via `scorer.get_feature_names()`, so a retrained booster updates serving with no code change h...
280
11,888
posthog
posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py
.py
"""Temporal activities for the session surfacing scoring pipeline. Two activities: * `list_chunks_activity` — runs once per workflow tick to gauge backlog and emit deterministic chunk specs. Cheap. * `score_chunk_activity` — runs once per chunk; does fetch-features (CH SELECT) → predict (XGBoost) →...
330
13,113
posthog
posthog/temporal/session_replay/enforce_max_replay_retention/types.py
.py
from dataclasses import dataclass @dataclass(frozen=True) class EnforceMaxReplayRetentionInput: dry_run: bool batch_size: int = 100
8
142
posthog
posthog/temporal/session_replay/enforce_max_replay_retention/workflow.py
.py
from datetime import timedelta from temporalio import common, workflow from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.session_replay.enforce_max_replay_retention.activities import enforce_max_replay_retention from posthog.temporal.session_replay.enforce_max_replay_retention.types impor...
26
978
posthog
posthog/temporal/session_replay/enforce_max_replay_retention/__init__.py
.py
from posthog.temporal.session_replay.enforce_max_replay_retention.activities import enforce_max_replay_retention from posthog.temporal.session_replay.enforce_max_replay_retention.workflow import EnforceMaxReplayRetentionWorkflow ENFORCE_MAX_REPLAY_RETENTION_WORKFLOWS = [ EnforceMaxReplayRetentionWorkflow, ] ENFOR...
9
388
posthog
posthog/temporal/session_replay/enforce_max_replay_retention/activities.py
.py
from temporalio import activity from posthog.constants import AvailableFeature from posthog.models.team import Team from posthog.session_recordings.data_retention import ( parse_feature_to_entitlement, retention_violates_entitlement, validate_retention_period, ) from posthog.sync import database_sync_to_as...
87
3,779
posthog
posthog/temporal/session_replay/count_playlist_items/types.py
.py
from dataclasses import dataclass @dataclass(frozen=True) class PlaylistToCount: playlist_id: int @dataclass(frozen=True) class CountPlaylistInput: playlist_id: int
12
177
posthog
posthog/temporal/session_replay/count_playlist_items/workflow.py
.py
import asyncio from datetime import timedelta import temporalio.common import temporalio.workflow from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.session_replay.count_playlist_items.activities import ( c...
90
3,549
posthog
posthog/temporal/session_replay/count_playlist_items/counting_logic.py
.py
import json from datetime import datetime, timedelta from typing import Any from django.conf import settings from django.db.models import Count, F, Q from django.utils import timezone import posthoganalytics from prometheus_client import Counter, Gauge, Histogram from structlog import get_logger from posthog.schema ...
330
12,479
posthog
posthog/temporal/session_replay/count_playlist_items/__init__.py
.py
from posthog.session_recordings.playlist_filters import ( convert_filters_to_recordings_query, convert_playlist_to_recordings_query, ) from posthog.temporal.session_replay.count_playlist_items.activities import ( count_recordings_for_playlist, fetch_playlists_to_count, ) from posthog.temporal.session_re...
30
803
posthog
posthog/temporal/session_replay/count_playlist_items/activities.py
.py
from temporalio import activity from posthog.sync import database_sync_to_async from posthog.temporal.common.heartbeat import Heartbeater from posthog.temporal.common.logger import get_write_only_logger from posthog.temporal.session_replay.count_playlist_items.counting_logic import ( count_recordings_that_match_pl...
34
1,464
posthog
posthog/temporal/session_replay/replay_count_metrics/types.py
.py
from dataclasses import dataclass @dataclass(frozen=True) class ReplayCountMetricsInput: pass
7
100
posthog
posthog/temporal/session_replay/replay_count_metrics/workflow.py
.py
from datetime import timedelta from temporalio import common, workflow from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.session_replay.replay_count_metrics.activities import collect_replay_count_metrics from posthog.temporal.session_replay.replay_count_metrics.types import ReplayCountMet...
26
900
posthog
posthog/temporal/session_replay/replay_count_metrics/__init__.py
.py
from posthog.temporal.session_replay.replay_count_metrics.activities import collect_replay_count_metrics from posthog.temporal.session_replay.replay_count_metrics.workflow import ReplayCountMetricsWorkflow REPLAY_COUNT_METRICS_WORKFLOWS = [ ReplayCountMetricsWorkflow, ] REPLAY_COUNT_METRICS_ACTIVITIES = [collect_...
9
342
posthog
posthog/temporal/session_replay/replay_count_metrics/activities.py
.py
from prometheus_client import Gauge from temporalio import activity from posthog.clickhouse.query_tagging import Feature, Product, tag_queries from posthog.metrics import pushed_metrics_registry from posthog.temporal.common.clickhouse import get_client from posthog.temporal.common.logger import get_write_only_logger f...
73
2,547
posthog
posthog/temporal/session_replay/delete_recordings/types.py
.py
from datetime import datetime from typing import Annotated, Literal from pydantic import BaseModel, Field MAX_DELETE_BATCH_SIZE = 100 class DeletionProgress(BaseModel): """Accumulated state across continue-as-new executions.""" cursor: str | None = None total_found: int = 0 total_deleted: int = 0 ...
128
2,899
posthog
posthog/temporal/session_replay/delete_recordings/workflow.py
.py
import asyncio from datetime import timedelta from itertools import batched from typing import Literal from temporalio import common, workflow from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.session_replay.delete_recordings.activities import ( cleanup_session_id_chunks, delete_r...
333
12,475
posthog
posthog/temporal/session_replay/delete_recordings/__init__.py
.py
from posthog.temporal.session_replay.delete_recordings.activities import ( cleanup_session_id_chunks, delete_recordings, load_recordings_with_person, load_recordings_with_query, load_recordings_with_team_id, load_session_id_chunk, purge_deleted_metadata, ) from posthog.temporal.session_repla...
35
1,047
posthog
posthog/temporal/session_replay/delete_recordings/metrics.py
.py
import typing import datetime as dt from django.conf import settings from temporalio import activity, workflow from temporalio.worker import ( ActivityInboundInterceptor, ExecuteActivityInput, ExecuteWorkflowInput, Interceptor, WorkflowInboundInterceptor, WorkflowInterceptorClassInput, ) from...
165
5,881
posthog
posthog/temporal/session_replay/delete_recordings/activities.py
.py
import json from datetime import UTC, datetime from urllib import parse from uuid import uuid4 from django.conf import settings from structlog.contextvars import bind_contextvars from temporalio import activity from posthog.clickhouse.query_tagging import Feature, Product, tag_queries from posthog.models import Team...
251
10,247
posthog
posthog/temporal/session_replay/delete_recordings/object_storage.py
.py
"""S3-backed chunked storage for session ID deletion workflows. Avoids exceeding Temporal's ~2MB payload limit by storing session IDs as chunked files in S3 instead of inline in the workflow input. Write path (sync, from Django admin): uses posthog.storage.object_storage.write() Read/delete path (async, from Temporal...
100
3,138
posthog
posthog/temporal/session_replay/rasterize_recording/types.py
.py
import hashlib from datetime import timedelta from typing import Literal from pydantic import BaseModel, model_validator # Retry envelope for the Node rasterize activity (scheduled in workflow._run). Shared so the relayed # recording-api token's TTL (rasterize.py) is derived from the same numbers and can't silently d...
106
3,768
posthog
posthog/temporal/session_replay/rasterize_recording/workflow.py
.py
import datetime as dt from typing import Any import temporalio.workflow as wf from temporalio import common from posthog.temporal.common.base import PostHogWorkflow from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY with wf.unsafe.imports_passed_through(): ...
170
6,437
posthog
posthog/temporal/session_replay/rasterize_recording/__init__.py
.py
from posthog.temporal.session_replay.rasterize_recording.activities import ( build_rasterization_input, bump_stuck_counter_activity, clear_stuck_counter_activity, finalize_rasterization, ) from posthog.temporal.session_replay.rasterize_recording.workflow import RasterizeRecordingWorkflow RASTERIZE_RECO...
16
530
posthog
posthog/temporal/session_replay/rasterize_recording/activities/stuck_counter.py
.py
from dataclasses import dataclass from datetime import timedelta import structlog from redis.asyncio import Redis as AsyncRedis from temporalio import activity from posthog.redis import get_async_client logger = structlog.get_logger(__name__) _STUCK_KEY_PREFIX = "replay:rasterize:stuck" # Each new failure refreshes...
72
2,094
posthog
posthog/temporal/session_replay/rasterize_recording/activities/__init__.py
.py
from .rasterize import build_rasterization_input, finalize_rasterization from .stuck_counter import ( BumpStuckCounterInput, bump_stuck_counter_activity, clear_stuck_counter_activity, read_stuck_session_ids, ) __all__ = [ "BumpStuckCounterInput", "build_rasterization_input", "bump_stuck_cou...
17
434
posthog
posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
.py
from datetime import timedelta from django.conf import settings from django.db import close_old_connections, transaction import structlog from temporalio import activity from posthog.session_recordings.recordings.recording_api_jwt import mint_recording_api_token, recording_api_jwt_enabled from posthog.storage import...
200
8,531
posthog
posthog/temporal/proxy_service/delete.py
.py
import json import uuid import typing as t import asyncio import datetime as dt from dataclasses import dataclass from django.db import connection import grpc.aio import temporalio.common from asgiref.sync import sync_to_async from structlog.contextvars import bind_contextvars from temporalio import activity, workflo...
232
8,323
posthog
posthog/temporal/proxy_service/monitor.py
.py
import ssl import json import uuid import socket import typing as t import asyncio import datetime as dt import ipaddress from dataclasses import dataclass import grpc.aio import requests import dns.resolver import temporalio.common from structlog.contextvars import bind_contextvars from temporalio import activity, wo...
621
25,746
posthog
posthog/temporal/proxy_service/__init__.py
.py
# ruff: noqa: F401 intentionally not using these from posthog.temporal.proxy_service.common import ( activity_capture_event, activity_send_proxy_created_email, activity_update_proxy_record, ) from posthog.temporal.proxy_service.create import ( CreateManagedProxyInputs, CreateManagedProxyWorkflow, ...
55
1,521
posthog
posthog/temporal/proxy_service/create.py
.py
import json import math import uuid import random import typing as t import asyncio import datetime as dt import ipaddress from dataclasses import asdict, dataclass from django.conf import settings import grpc.aio import requests import dns.resolver import dns.asyncresolver import temporalio.common from structlog imp...
716
28,980
posthog
posthog/temporal/proxy_service/cloudflare.py
.py
""" Cloudflare for SaaS API client for managing Custom Hostnames and Worker Routes. This module provides functions to interact with Cloudflare's API for: - Creating/deleting Custom Hostnames (for TLS certificate provisioning) - Creating/deleting Worker Routes (for routing traffic to the proxy worker) - Getting Custom ...
275
8,852
posthog
posthog/temporal/proxy_service/common.py
.py
import uuid import typing as t from dataclasses import dataclass from django.conf import settings from django.db import connection import grpc.aio import posthoganalytics from asgiref.sync import sync_to_async from structlog.contextvars import bind_contextvars from temporalio import activity from posthog.event_usage...
243
7,748
posthog
posthog/temporal/proxy_service/test/monitor_test.py
.py
import json import ipaddress import pytest from freezegun import freeze_time from unittest.mock import MagicMock, Mock, patch from django.test import TestCase import requests from parameterized import parameterized from posthog.models import Organization, ProxyRecord from posthog.temporal.proxy_service.monitor impo...
252
11,722
posthog
posthog/temporal/proxy_service/test/test_cloudflare.py
.py
from django.test import SimpleTestCase, TestCase from parameterized import parameterized from posthog.temporal.proxy_service.cloudflare import ( CloudflareAPIError, CustomHostnameSSLStatus, CustomHostnameStatus, _parse_hostname, ) # Every status Cloudflare can send, which is a superset of what the en...
114
4,049
posthog
posthog/temporal/proxy_service/test/dns_test.py
.py
import time import uuid import asyncio from unittest.mock import MagicMock, patch from django.test import TestCase import requests import dns.resolver from parameterized import parameterized from posthog.temporal.proxy_service.monitor import CheckActivityInput, check_dns, check_proxy_is_live RECORD_ID = uuid.UUID(...
125
4,415
posthog
posthog/temporal/proxy_service/test/test_create_workflow.py
.py
import uuid import pytest from unittest.mock import patch import temporalio.worker from temporalio import activity from temporalio.client import WorkflowFailureError from temporalio.exceptions import ApplicationError from temporalio.testing import WorkflowEnvironment from temporalio.worker import Worker from posthog...
184
6,861
posthog
posthog/temporal/proxy_service/test/test_send_proxy_email.py
.py
import uuid import pytest from unittest.mock import MagicMock, patch from posthog.models import ProxyRecord from posthog.models.organization import Organization from posthog.models.user import User from posthog.temporal.proxy_service.common import SendProxyCreatedEmailInputs, activity_send_proxy_created_email @pyte...
118
4,725
posthog
posthog/temporal/proxy_service/proto/__init__.py
.py
# ruff: noqa: F401 intentionally not using these # the pb2 files are copied manually from github.com/posthog/proxy-provisioner for now # this file just manually imports what we import elsewhere from posthog.temporal.proxy_service.proto.proxy_provisioner_pb2 import ( READY as CertificateState_READY, CreateReque...
12
468