Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(temporal): decouple health check framework from dagster (#59989)

Rafael Audibert5bf93c2bfc14
diff --git a/posthog/dags/common/health/README.md b/posthog/dags/common/health/README.md
deleted file mode 100644
index e47515e3641c..000000000000
--- a/posthog/dags/common/health/README.md
+++ /dev/null
@@ -1,240 +0,0 @@
-# Health check framework
-
-A framework for running scheduled health checks across PostHog teams. Define a detect function, call `create_health_check`, and the framework handles team batching, parallel execution, issue persistence, auto-resolution, rollout control, and Dagster observability.
-
-Issues are written to the `posthog_healthissue` table and automatically resolved when a team passes a subsequent check run.
-
-## Quick start
-
-### 1. Write a detect function
-
-A detect function receives a batch of team IDs and returns issues found:
-
-```python
-import dagster
-from posthog.dags.common.health.types import HealthCheckResult
-from posthog.models.health_issue import HealthIssue
-
-def detect_stale_data(
- team_ids: list[int], context: dagster.OpExecutionContext
-) -> dict[int, list[HealthCheckResult]]:
- # Your detection logic here — query ClickHouse, check state, etc.
- issues: dict[int, list[HealthCheckResult]] = {}
-
- stale_team_ids = find_teams_with_stale_data(team_ids)
-
- for team_id in stale_team_ids:
- issues[team_id] = [
- HealthCheckResult(
- severity=HealthIssue.Severity.WARNING,
- payload={"reason": "No events in 7 days"},
- hash_keys=[],
- )
- ]
-
- return issues
-```
-
-Teams not present in the returned dict are considered healthy. Their active issues (for this `kind`) are auto-resolved.
-
-### 2. Create the health check
-
-```python
-from posthog.dags.common import JobOwners
-from posthog.dags.common.health.detectors import batch_detector
-from posthog.dags.common.health.framework import create_health_check
-
-stale_data_check = create_health_check(
- name="stale_data",
- kind="stale_data",
- detector=batch_detector(detect_stale_data),
- owner=JobOwners.TEAM_WEB_ANALYTICS,
- schedule="0 * * * *", # hourly
-)
-```
-
-### 3. Register in a Dagster location
-
-Add the job and schedule to a location file (e.g. `posthog/dags/locations/health.py`):
-
-```python
-import dagster
-from . import resources
-
-defs = dagster.Definitions(
- jobs=[stale_data_check.job],
- schedules=[s for s in [stale_data_check.schedule] if s],
- resources=resources,
-)
-```
-
-If you skip the `schedule` parameter, the job can still be triggered manually from the Dagster UI.
-
-## Detectors
-
-A detector wraps your detect function and determines how the framework calls it and what execution defaults to use.
-
-### `batch_detector`
-
-Your function receives the full batch of team IDs at once. Best for checks that can evaluate many teams in a single operation (e.g. one SQL query).
-
-```python
-from posthog.dags.common.health.detectors import batch_detector
-
-detector = batch_detector(detect_fn)
-```
-
-Spread a preset dict to control batching and concurrency:
-
-```python
-from posthog.dags.common.health.detectors import (
- CLICKHOUSE_BATCH_EXECUTION_POLICY,
- DEFAULT_EXECUTION_POLICY,
- batch_detector,
-)
-
-detector = batch_detector(detect_fn) # uses DEFAULT_EXECUTION_POLICY values
-detector = batch_detector(detect_fn, **CLICKHOUSE_BATCH_EXECUTION_POLICY)
-
-# Override a single field from a preset
-detector = batch_detector(detect_fn, **{**CLICKHOUSE_BATCH_EXECUTION_POLICY, "max_concurrent": 3})
-```
-
-**Signature:** `(team_ids: list[int], context: OpExecutionContext) -> dict[int, list[HealthCheckResult]]`
-
-| Preset | batch_size | max_concurrent |
-| ----------------------------------- | ---------- | -------------- |
-| `DEFAULT_EXECUTION_POLICY` | 1000 | 5 |
-| `CLICKHOUSE_BATCH_EXECUTION_POLICY` | 250 | 1 |
-
-## HealthCheckResult
-
-Every detected issue is a `HealthCheckResult`:
-
-```python
-HealthCheckResult(
- severity=HealthIssue.Severity.WARNING, # "critical", "warning", or "info"
- payload={"reason": "No events", "last_seen": "2025-01-01"},
- hash_keys=["reason"], # optional
-)
-```
-
-| Field | Type | Description |
-| ----------- | ---------------------- | ------------------------------------ |
-| `severity` | `HealthIssue.Severity` | One of `CRITICAL`, `WARNING`, `INFO` |
-| `payload` | `dict[str, Any]` | Arbitrary data stored with the issue |
-| `hash_keys` | `list[str] \| None` | Controls issue identity (see below) |
-
-### Issue identity and `hash_keys`
-
-An active issue is uniquely identified by `(team_id, kind, unique_hash)`. The `unique_hash` is derived from `kind` + `payload`, controlled by `hash_keys`. `kind` is always included as a prefix in the hash content, so the hash is always scoped to the issue kind.
-
-| `hash_keys` value | Hash content | Use case |
-| ------------------------ | ------------------------------ | --------------------------------------------------------- |
-| `None` (default) | `kind` + full payload | Each unique payload produces a distinct issue |
-| `[]` | `kind` only (payload = `{}`) | One active issue per team per kind |
-| `["field_a", "field_b"]` | `kind` + selected payload keys | Identity based on specific fields, ignoring volatile ones |
-
-## Issue lifecycle
-
-On each check run, for every team in the batch:
-
-1. **Upsert** — Issues returned by the detector are written (or updated) as `status=active`.
-2. **Resolve** — Active issues for checked teams that were _not_ returned by the detector are marked `status=resolved`.
-
-## `create_health_check` reference
-
-```python
-create_health_check(
- name: str,
- kind: str,
- detector: HealthDetector,
- owner: JobOwners,
- *,
- team_ids: list[int] | None = None,
- schedule: str | None = None,
- batch_size: int | None = None,
- max_concurrent: int | None = None,
- rollout_percentage: float | None = None,
- not_processed_threshold: float = 0.1,
- dry_run: bool = False,
-) -> HealthCheckDefinition
-```
-
-| Parameter | Type | Default | Description |
-| ------------------------- | ------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
-| `name` | `str` | required | Unique name used in Dagster op/job naming |
-| `kind` | `str` | required | Issue kind written to the `posthog_healthissue` table. Must be globally unique |
-| `detector` | `HealthDetector` | required | Detector wrapping your detect function |
-| `owner` | `JobOwners` | required | Team that owns this check (used for Slack alert routing) |
-| `team_ids` | `list[int] \| None` | `None` | Restrict to specific teams. `None` processes all teams |
-| `schedule` | `str \| None` | `None` | Cron expression (UTC). Omit for manual-only jobs |
-| `batch_size` | `int \| None` | `None` | Override detector default batch size |
-| `max_concurrent` | `int \| None` | `None` | Override detector default concurrency |
-| `rollout_percentage` | `float \| None` | `None` | Fraction of teams to include (0–1, e.g. 0.01 = 1%). Deterministic by team ID |
-| `not_processed_threshold` | `float` | `0.1` | Fail the job if this fraction of teams are skipped or errored |
-| `dry_run` | `bool` | `False` | Run detection but skip DB writes (upsert/resolve). Sets the default for scheduled runs; can be overridden per-run in the Dagster launchpad |
-
-**Returns** a `HealthCheckDefinition` with `.job` and `.schedule` attributes for Dagster registration.
-
-## Configuration guide
-
-### Batch size and concurrency
-
-Teams are split into batches of `batch_size` IDs. Up to `max_concurrent` batches run in parallel as Dagster dynamic ops. Each batch has a retry policy (2 retries, exponential backoff with jitter).
-
-Defaults depend on the detector's execution policy:
-
-| Preset | batch_size | max_concurrent |
-| ----------------------------------- | ---------- | -------------- |
-| `DEFAULT_EXECUTION_POLICY` | 1000 | 5 |
-| `CLICKHOUSE_BATCH_EXECUTION_POLICY` | 250 | 1 |
-
-Override at the `create_health_check` call site if needed.
-
-### Rollout percentage
-
-`rollout_percentage` deterministically selects a subset of teams using a SHA-256 hash of each team ID. The selection is stable across runs — the same teams are always included at the same percentage.
-
-Use this to canary a new health check:
-
-```python
-# Start with 1% of teams
-stale_data_check = create_health_check(
- ...
- rollout_percentage=0.01,
-)
-
-# Later, increase to 100%
-```
-
-At `rollout_percentage=1.0` (default when omitted), all teams are processed.
-
-### Failure threshold
-
-If more than `not_processed_threshold` (default 10%) of teams are skipped or errored, the entire job fails with `HealthCheckThresholdExceeded`. This catches detector bugs early — if your detect function is crashing for a large fraction of teams, the job alerts rather than silently resolving issues.
-
-### Worked example
-
-With 300,000 total teams:
-
-| Setting | Value | Effect |
-| ------------------------- | ------ | ---------------------------------- |
-| `rollout_percentage` | `0.01` | 3,000 teams selected (1%) |
-| `batch_size` | `250` | 12 batches created |
-| `max_concurrent` | `2` | Up to 2 batches run at a time |
-| `not_processed_threshold` | `0.1` | Job fails if >300 teams skip/error |
-
-## Component files
-
-| File | Role |
-| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
-| `framework.py` | Builds Dagster jobs and schedules via `create_health_check`. Applies retry policy and concurrency. Emits per-batch and aggregate metadata |
-| `detectors.py` | Detector constructors and execution policy resolution |
-| `processing.py` | Orchestrates detect → validate → upsert → resolve for each batch |
-| `db.py` | Converts `HealthCheckResult` into `HealthIssue` model writes |
-| `query.py` | ClickHouse query helper with safe defaults and placeholder validation |
-| `validation.py` | Validates batch detector output (drops unknown team IDs, non-result items) |
-| `types.py` | `HealthCheckResult`, `BatchResult`, type aliases |
-| `../ops.py` | Team selection, deterministic rollout filtering, batch chunking |
-| `../../models/health_issue.py` | Django model with `bulk_upsert` and `bulk_resolve` |
diff --git a/posthog/dags/common/health/__init__.py b/posthog/dags/common/health/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/dags/common/health/detectors.py b/posthog/dags/common/health/detectors.py
deleted file mode 100644
index 1ce06d46d6c8..000000000000
--- a/posthog/dags/common/health/detectors.py
+++ /dev/null
@@ -1,46 +0,0 @@
-from dataclasses import dataclass
-
-from posthog.dags.common.health.types import BatchDetectFn
-
-
-@dataclass(frozen=True)
-class HealthExecutionPolicy:
- batch_size: int
- max_concurrent: int
-
-
-DEFAULT_EXECUTION_POLICY = {"batch_size": 1000, "max_concurrent": 5}
-CLICKHOUSE_BATCH_EXECUTION_POLICY = {"batch_size": 250, "max_concurrent": 1}
-
-
-@dataclass(frozen=True)
-class HealthDetector:
- detect_fn: BatchDetectFn
- execution_policy: HealthExecutionPolicy
-
-
-def batch_detector(detect_fn: BatchDetectFn, *, batch_size: int = 1000, max_concurrent: int = 5) -> HealthDetector:
- return HealthDetector(
- detect_fn=detect_fn,
- execution_policy=HealthExecutionPolicy(batch_size=batch_size, max_concurrent=max_concurrent),
- )
-
-
-def resolve_execution_policy(
- detector: HealthDetector,
- *,
- batch_size: int | None = None,
- max_concurrent: int | None = None,
-) -> HealthExecutionPolicy:
- base_policy = detector.execution_policy
- resolved = HealthExecutionPolicy(
- batch_size=batch_size if batch_size is not None else base_policy.batch_size,
- max_concurrent=max_concurrent if max_concurrent is not None else base_policy.max_concurrent,
- )
-
- if resolved.batch_size <= 0:
- raise ValueError(f"batch_size must be > 0, got {resolved.batch_size}")
- if resolved.max_concurrent <= 0:
- raise ValueError(f"max_concurrent must be > 0, got {resolved.max_concurrent}")
-
- return resolved
diff --git a/posthog/dags/common/health/framework.py b/posthog/dags/common/health/framework.py
deleted file mode 100644
index f4e6d34a87bc..000000000000
--- a/posthog/dags/common/health/framework.py
+++ /dev/null
@@ -1,220 +0,0 @@
-from collections.abc import Mapping
-from types import MappingProxyType
-
-import dagster
-
-from posthog.dags.common import JobOwners, check_for_concurrent_runs
-from posthog.dags.common.health.detectors import HealthDetector, resolve_execution_policy
-from posthog.dags.common.health.observability import push_health_check_metrics
-from posthog.dags.common.health.processing import _process_batch_detection
-from posthog.dags.common.health.types import BatchResult, HealthCheckDefinition, HealthCheckThresholdExceeded
-from posthog.dags.common.ops import get_all_team_ids_op
-
-_REGISTERED_KINDS: dict[str, str] = {}
-
-_default_retry_policy: dagster.RetryPolicy = dagster.RetryPolicy(
- max_retries=2,
- delay=30,
- backoff=dagster.Backoff.EXPONENTIAL,
- jitter=dagster.Jitter.PLUS_MINUS,
-)
-
-
-def get_registered_kinds() -> Mapping[str, str]:
- return MappingProxyType(_REGISTERED_KINDS)
-
-
-def _reset_registry() -> None:
- """Clear the kind registry. For test use only."""
- _REGISTERED_KINDS.clear()
-
-
-def _to_batch_dagster_metadata(result: BatchResult, teams_per_second: float) -> dict[str, dagster.MetadataValue]:
- return {
- "detect_duration_seconds": dagster.MetadataValue.float(result.detect_duration),
- "db_write_duration_seconds": dagster.MetadataValue.float(result.db_write_duration),
- "resolve_duration_seconds": dagster.MetadataValue.float(result.resolve_duration),
- "total_duration_seconds": dagster.MetadataValue.float(result.total_duration),
- "teams_per_second": dagster.MetadataValue.float(teams_per_second),
- "batch_size": dagster.MetadataValue.int(result.batch_size),
- "issues_upserted": dagster.MetadataValue.int(result.issues_upserted),
- "issues_resolved": dagster.MetadataValue.int(result.issues_resolved),
- "teams_with_issues": dagster.MetadataValue.int(result.teams_with_issues),
- "teams_healthy": dagster.MetadataValue.int(result.teams_healthy),
- "teams_failed": dagster.MetadataValue.int(result.teams_failed),
- "teams_skipped": dagster.MetadataValue.int(result.teams_skipped),
- }
-
-
-def _to_aggregate_dagster_metadata(totals: BatchResult, teams_per_second: float) -> dict[str, dagster.MetadataValue]:
- return {
- "total_teams": dagster.MetadataValue.int(totals.batch_size),
- "total_issues_upserted": dagster.MetadataValue.int(totals.issues_upserted),
- "total_issues_resolved": dagster.MetadataValue.int(totals.issues_resolved),
- "total_teams_with_issues": dagster.MetadataValue.int(totals.teams_with_issues),
- "total_teams_healthy": dagster.MetadataValue.int(totals.teams_healthy),
- "total_teams_failed": dagster.MetadataValue.int(totals.teams_failed),
- "total_teams_skipped": dagster.MetadataValue.int(totals.teams_skipped),
- "total_duration_seconds": dagster.MetadataValue.float(float(totals.total_duration)),
- "teams_per_second": dagster.MetadataValue.float(float(teams_per_second)),
- }
-
-
-def _create_check_batch_op(name: str, kind: str, detector: HealthDetector) -> dagster.OpDefinition:
- @dagster.op(name=f"{name}_check_batch", retry_policy=_default_retry_policy)
- def check_batch_op(context: dagster.OpExecutionContext, team_ids: list[int]) -> BatchResult:
- ops = context.run_config.get("ops", {})
- dry_run = False
- if isinstance(ops, dict):
- team_ids_op = ops.get("get_all_team_ids_op", {})
- if isinstance(team_ids_op, dict):
- config = team_ids_op.get("config", {})
- if isinstance(config, dict):
- dry_run = bool(config.get("dry_run", False))
- result = _process_batch_detection(team_ids, kind, detector.detect_fn, context, dry_run=dry_run)
-
- context.add_output_metadata(_to_batch_dagster_metadata(result, result.teams_per_second))
-
- return result
-
- return check_batch_op
-
-
-def _aggregate_results(
- results: list[BatchResult],
- kind: str,
- not_processed_threshold: float,
- context: dagster.OpExecutionContext,
-) -> None:
- totals = BatchResult()
- for r in results:
- totals += r
-
- context.log.info(
- f"Health check '{kind}' completed: {totals.batch_size:,} teams in {totals.total_duration:.0f}s "
- f"({totals.teams_per_second:.0f} teams/sec)\n"
- f" Issues: {totals.issues_upserted:,} upserted, {totals.issues_resolved:,} resolved\n"
- f" Teams: {totals.teams_with_issues:,} with issues, {totals.teams_healthy:,} healthy, "
- f"{totals.teams_skipped:,} skipped, {totals.teams_failed:,} failed"
- )
-
- context.add_output_metadata(_to_aggregate_dagster_metadata(totals, totals.teams_per_second))
-
- not_processed = totals.teams_skipped + totals.teams_failed
- threshold_exceeded = totals.batch_size > 0 and totals.not_processed_rate > not_processed_threshold
-
- push_health_check_metrics(kind, totals, success=not threshold_exceeded)
-
- if threshold_exceeded:
- raise HealthCheckThresholdExceeded(
- f"Health check '{kind}': {not_processed:,}/{totals.batch_size:,} teams not processed "
- f"({totals.not_processed_rate:.1%}), exceeds threshold {not_processed_threshold:.1%} "
- f"(skipped={totals.teams_skipped:,}, failed={totals.teams_failed:,})"
- )
-
-
-def _create_aggregate_op(
- name: str,
- kind: str,
- not_processed_threshold: float,
-) -> dagster.OpDefinition:
- @dagster.op(name=f"{name}_aggregate")
- def aggregate_op(context: dagster.OpExecutionContext, results: list[BatchResult]) -> None:
- _aggregate_results(results, kind, not_processed_threshold, context)
-
- return aggregate_op
-
-
-def create_health_check(
- name: str,
- kind: str,
- detector: HealthDetector,
- owner: JobOwners,
- *,
- team_ids: list[int] | None = None,
- schedule: str | None = None,
- batch_size: int | None = None,
- max_concurrent: int | None = None,
- rollout_percentage: float | None = None,
- not_processed_threshold: float = 0.1,
- dry_run: bool = False,
-) -> HealthCheckDefinition:
- """Create a complete health check pipeline as a Dagster job.
-
- Args:
- name: Unique name for the health check (used in Dagster op/job names).
- kind: The health issue kind string written to the health_issues table.
- detector: Detector definition used to detect health issues.
- owner: The team that owns this health check for Slack alert routing.
- team_ids: If provided, only process these team IDs. If None, processes all teams.
- schedule: Optional cron expression for scheduling.
- batch_size: Optional override for detector default batch size.
- max_concurrent: Optional override for detector default concurrency.
- rollout_percentage: Optional deterministic team rollout fraction (0–1, e.g. 0.01 = 1%).
- not_processed_threshold: Fail if this fraction of teams are skipped or failed.
- dry_run: If True, run detection but skip DB writes (upsert/resolve).
-
- Returns:
- HealthCheckDefinition
- """
- existing = _REGISTERED_KINDS.get(kind)
- if existing is not None and existing != name:
- raise ValueError(f"Health check kind '{kind}' already registered by '{existing}'")
- _REGISTERED_KINDS[kind] = name
-
- policy = resolve_execution_policy(
- detector,
- batch_size=batch_size,
- max_concurrent=max_concurrent,
- )
-
- batch_op = _create_check_batch_op(name, kind, detector)
- aggregate_op = _create_aggregate_op(name, kind, not_processed_threshold)
-
- op_config: dict = {"batch_size": policy.batch_size}
- if team_ids is not None:
- op_config["team_ids"] = team_ids
- if rollout_percentage is not None:
- op_config["rollout_percentage"] = rollout_percentage
-
- op_config["dry_run"] = dry_run
-
- job_config = {
- "ops": {
- "get_all_team_ids_op": {
- "config": op_config,
- },
- }
- }
-
- @dagster.job(
- name=f"{name}_health_check_job",
- description=f"Health check: {kind}",
- executor_def=dagster.multiprocess_executor.configured({"max_concurrent": policy.max_concurrent}),
- tags={"owner": owner.value},
- config=job_config,
- )
- def health_check_job():
- team_batches = get_all_team_ids_op()
- results = team_batches.map(batch_op)
- aggregate_op(results.collect())
-
- schedule_def = None
- if schedule is not None:
-
- @dagster.schedule(
- cron_schedule=schedule,
- job=health_check_job,
- execution_timezone="UTC",
- name=f"{name}_health_check_schedule",
- tags={"owner": owner.value},
- )
- def health_check_schedule(context: dagster.ScheduleEvaluationContext):
- skip_reason = check_for_concurrent_runs(context, tags={})
- if skip_reason:
- return skip_reason
- return dagster.RunRequest(run_config=job_config)
-
- schedule_def = health_check_schedule
-
- return HealthCheckDefinition(job=health_check_job, schedule=schedule_def)
diff --git a/posthog/dags/common/health/jobs/__init__.py b/posthog/dags/common/health/jobs/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/dags/common/health/jobs/web_analytics/__init__.py b/posthog/dags/common/health/jobs/web_analytics/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/dags/common/health/processing.py b/posthog/dags/common/health/processing.py
deleted file mode 100644
index 0d48b29b2799..000000000000
--- a/posthog/dags/common/health/processing.py
+++ /dev/null
@@ -1,47 +0,0 @@
-import time
-
-import dagster
-
-from posthog.dags.common.health.db import _resolve_stale_issues, _upsert_issues
-from posthog.dags.common.health.types import BatchDetectFn, BatchResult
-from posthog.dags.common.health.validation import _validate_batch_output
-
-
-def _process_batch_detection(
- team_ids: list[int],
- kind: str,
- detect_fn: BatchDetectFn,
- context: dagster.OpExecutionContext,
- *,
- dry_run: bool = False,
-) -> BatchResult:
- result = BatchResult(batch_size=len(team_ids))
-
- start = time.monotonic()
- issues_by_team = detect_fn(team_ids, context)
- result.detect_duration = time.monotonic() - start
-
- issues_by_team = _validate_batch_output(issues_by_team, set(team_ids), kind, context)
-
- result.teams_with_issues = len(issues_by_team)
- result.teams_healthy = len(team_ids) - len(issues_by_team)
-
- if dry_run:
- issue_count = sum(len(v) for v in issues_by_team.values())
- context.log.info(
- f"[dry_run] Health check '{kind}': {result.teams_with_issues} teams with {issue_count} issues, "
- f"{result.teams_healthy} healthy — skipping DB writes"
- )
- return result
-
- start = time.monotonic()
- result.issues_upserted = _upsert_issues(kind, issues_by_team)
- result.db_write_duration = time.monotonic() - start
-
- healthy_team_ids = set(team_ids) - set(issues_by_team.keys())
-
- start = time.monotonic()
- result.issues_resolved = _resolve_stale_issues(kind, issues_by_team, healthy_team_ids)
- result.resolve_duration = time.monotonic() - start
-
- return result
diff --git a/posthog/dags/common/health/query.py b/posthog/dags/common/health/query.py
deleted file mode 100644
index 89fb14c02ae4..000000000000
--- a/posthog/dags/common/health/query.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from collections.abc import Mapping
-from typing import Any
-
-import dagster
-
-from posthog.clickhouse.client import sync_execute
-
-_DEFAULT_HEALTH_QUERY_SETTINGS: dict[str, Any] = {
- "max_execution_time": 30,
- "max_threads": 2,
-}
-
-
-def _validate_clickhouse_team_query(sql: str) -> None:
- if "%(team_ids)s" not in sql:
- raise ValueError("Health ClickHouse queries must include a %(team_ids)s placeholder")
-
-
-def execute_clickhouse_health_team_query(
- sql: str,
- *,
- team_ids: list[int],
- lookback_days: int | None = None,
- context: dagster.OpExecutionContext,
- params: Mapping[str, Any] | None = None,
- settings: Mapping[str, Any] | None = None,
-) -> list[tuple[Any, ...]]:
- if lookback_days is not None and lookback_days <= 0:
- raise ValueError(f"lookback_days must be > 0, got {lookback_days}")
- if not team_ids:
- return []
-
- _validate_clickhouse_team_query(sql)
-
- query_params: dict[str, Any] = {
- "team_ids": team_ids,
- }
-
- if lookback_days is not None:
- query_params["lookback_days"] = lookback_days
-
- if params:
- reserved = {"team_ids", "lookback_days"} & set(params.keys())
- if reserved:
- raise ValueError(f"Reserved params cannot be overridden: {', '.join(sorted(reserved))}")
- query_params.update(params)
-
- query_settings = dict(_DEFAULT_HEALTH_QUERY_SETTINGS)
- if settings:
- query_settings.update(settings)
-
- context.log.info(f"Running health ClickHouse query for {len(team_ids)} teams")
- return sync_execute(sql, query_params, settings=query_settings) or []
diff --git a/posthog/dags/common/health/types.py b/posthog/dags/common/health/types.py
deleted file mode 100644
index efd1b3146fb4..000000000000
--- a/posthog/dags/common/health/types.py
+++ /dev/null
@@ -1,64 +0,0 @@
-import dataclasses
-from collections.abc import Callable
-from dataclasses import dataclass
-from typing import Any
-
-import dagster
-
-from posthog.models.health_issue import HealthIssue
-
-BatchDetectFn = Callable[[list[int], dagster.OpExecutionContext], dict[int, list["HealthCheckResult"]]]
-
-
-@dataclass
-class HealthCheckResult:
- severity: HealthIssue.Severity
- payload: dict[str, Any]
- hash_keys: list[str] | None = None
-
- def __post_init__(self) -> None:
- valid = set(HealthIssue.Severity.values)
- if self.severity not in valid:
- raise ValueError(f"Invalid severity '{self.severity}', must be one of: {', '.join(sorted(valid))}")
-
-
-@dataclass
-class BatchResult:
- batch_size: int = 0
- issues_upserted: int = 0
- issues_resolved: int = 0
- teams_with_issues: int = 0
- teams_healthy: int = 0
- teams_failed: int = 0
- teams_skipped: int = 0
- detect_duration: float = 0.0
- db_write_duration: float = 0.0
- resolve_duration: float = 0.0
-
- @property
- def total_duration(self) -> float:
- return self.detect_duration + self.db_write_duration + self.resolve_duration
-
- @property
- def teams_per_second(self) -> float:
- return self.batch_size / self.total_duration if self.total_duration > 0 else 0
-
- @property
- def not_processed_rate(self) -> float:
- return (self.teams_failed + self.teams_skipped) / self.batch_size if self.batch_size > 0 else 0
-
- # Adds up all fields from another BatchResult, e.g. totals += batch_result
- def __iadd__(self, other: "BatchResult") -> "BatchResult":
- for f in dataclasses.fields(self):
- setattr(self, f.name, getattr(self, f.name) + getattr(other, f.name))
- return self
-
-
-@dataclass
-class HealthCheckDefinition:
- job: dagster.JobDefinition
- schedule: dagster.ScheduleDefinition | None
-
-
-class HealthCheckThresholdExceeded(Exception):
- pass
diff --git a/posthog/dags/common/health/validation.py b/posthog/dags/common/health/validation.py
deleted file mode 100644
index e413b21eae63..000000000000
--- a/posthog/dags/common/health/validation.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import dagster
-
-from posthog.dags.common.health.types import HealthCheckResult
-from posthog.exceptions_capture import capture_exception
-
-
-def _validate_batch_output(
- issues_by_team: dict[int, list[HealthCheckResult]],
- valid_team_ids: set[int],
- kind: str,
- context: dagster.OpExecutionContext,
-) -> dict[int, list[HealthCheckResult]]:
- validated: dict[int, list[HealthCheckResult]] = {}
- for team_id, results in issues_by_team.items():
- if team_id not in valid_team_ids:
- err = ValueError(f"Health check '{kind}': detector returned team_id={team_id} not in input batch")
- context.log.warning(str(err))
- capture_exception(err, {"health_check_kind": kind, "team_id": team_id})
- continue
- if not isinstance(results, list) or len(results) == 0:
- context.log.warning(f"Health check '{kind}': empty/invalid results for team_id={team_id}, ignoring")
- continue
- valid_results = [r for r in results if isinstance(r, HealthCheckResult)]
- if len(valid_results) != len(results):
- context.log.warning(
- f"Health check '{kind}': {len(results) - len(valid_results)} non-HealthCheckResult items "
- f"for team_id={team_id}"
- )
- if valid_results:
- validated[team_id] = valid_results
- return validated
diff --git a/posthog/dags/locations/shared.py b/posthog/dags/locations/shared.py
index 82e12602acc9..cbfe8b0ee8fa 100644
--- a/posthog/dags/locations/shared.py
+++ b/posthog/dags/locations/shared.py
@@ -4,9 +4,6 @@ from posthog.clickhouse.cluster import ClickhouseCluster
from posthog.clickhouse.custom_metrics import MetricsClient
from posthog.dags import slack_alerts
-from products.web_analytics.dags.no_live_events import no_live_events_check
-from products.web_analytics.dags.no_pageleave_events import no_pageleave_events_check
-
from . import resources
@@ -25,12 +22,6 @@ def report_job_status_metric(
# Used for definitions that are shared between locations.
# Mainly sensors
defs = dagster.Definitions(
- jobs=[
- # Health Checks
- # Ingestion
- no_live_events_check.job,
- no_pageleave_events_check.job,
- ],
sensors=[
slack_alerts.notify_slack_on_failure,
*[
diff --git a/posthog/dags/tests/test_health_check_framework.py b/posthog/dags/tests/test_health_check_framework.py
deleted file mode 100644
index 3cf5c59c0875..000000000000
--- a/posthog/dags/tests/test_health_check_framework.py
+++ /dev/null
@@ -1,106 +0,0 @@
-import pytest
-from unittest.mock import MagicMock, patch
-
-import dagster
-from parameterized import parameterized
-
-from posthog.dags.common.health.detectors import (
- CLICKHOUSE_BATCH_EXECUTION_POLICY,
- batch_detector,
- resolve_execution_policy,
-)
-from posthog.dags.common.health.processing import _process_batch_detection
-from posthog.dags.common.health.types import HealthCheckResult
-from posthog.dags.common.ops import _filter_team_ids_for_rollout
-from posthog.models.health_issue import HealthIssue
-
-
-def _batch_detect_fn(team_ids: list[int], context: dagster.OpExecutionContext) -> dict[int, list[HealthCheckResult]]:
- if not team_ids:
- return {}
- return {
- team_ids[0]: [
- HealthCheckResult(
- severity=HealthIssue.Severity.INFO,
- payload={"ok": True},
- )
- ]
- }
-
-
-class TestHealthExecutionPolicies:
- def test_default_policy_for_generic_detector(self):
- detector = batch_detector(_batch_detect_fn)
- policy = resolve_execution_policy(detector)
-
- assert policy.batch_size == 1000
- assert policy.max_concurrent == 5
-
- def test_default_policy_for_clickhouse_detector(self):
- detector = batch_detector(_batch_detect_fn, **CLICKHOUSE_BATCH_EXECUTION_POLICY)
- policy = resolve_execution_policy(detector)
-
- assert policy.batch_size == 250
- assert policy.max_concurrent == 1
-
- def test_policy_overrides(self):
- detector = batch_detector(_batch_detect_fn, **CLICKHOUSE_BATCH_EXECUTION_POLICY)
- policy = resolve_execution_policy(detector, batch_size=500, max_concurrent=2)
-
- assert policy.batch_size == 500
- assert policy.max_concurrent == 2
-
- @parameterized.expand([("batch_size", 0), ("max_concurrent", 0)])
- def test_policy_rejects_non_positive_values(self, field: str, value: int):
- detector = batch_detector(_batch_detect_fn)
- kwargs = {field: value}
-
- with pytest.raises(ValueError):
- resolve_execution_policy(detector, **kwargs)
-
-
-class TestTeamRolloutSelection:
- @parameterized.expand(
- [
- ("zero", 0.0, 0),
- ("tiny_rounds_up", 0.001, 1),
- ("one_percent", 0.01, 1),
- ("five_percent", 0.05, 5),
- ("full", 1.0, 100),
- ]
- )
- def test_rollout_filtering(self, _name: str, rollout_percentage: float, expected_count: int):
- team_ids = list(range(1, 101))
- selected = _filter_team_ids_for_rollout(team_ids, rollout_percentage)
- assert len(selected) == expected_count
-
- @parameterized.expand(
- [
- ("negative", -1.0),
- ("over_one", 1.1),
- ]
- )
- def test_rollout_filter_rejects_invalid_percentages(self, _name: str, rollout_percentage: float):
- with pytest.raises(ValueError):
- _filter_team_ids_for_rollout([100], rollout_percentage)
-
- def test_rollout_is_deterministic(self):
- team_ids = list(range(1, 101))
- first = _filter_team_ids_for_rollout(team_ids, 0.05)
- second = _filter_team_ids_for_rollout(team_ids, 0.05)
- assert first == second
-
-
-class TestDryRun:
- @patch("posthog.dags.common.health.processing._resolve_stale_issues")
- @patch("posthog.dags.common.health.processing._upsert_issues")
- def test_batch_dry_run_skips_db_writes(self, mock_upsert: MagicMock, mock_resolve: MagicMock):
- context = MagicMock(spec=dagster.OpExecutionContext)
- result = _process_batch_detection([1, 2], "test_kind", _batch_detect_fn, context, dry_run=True)
-
- mock_upsert.assert_not_called()
- mock_resolve.assert_not_called()
- assert result.teams_with_issues == 1
- assert result.teams_healthy == 1
- assert result.issues_upserted == 0
- assert result.issues_resolved == 0
diff --git a/posthog/temporal/health_checks/activities.py b/posthog/temporal/health_checks/activities.py
index 23e8b1eded27..10922b43ecb8 100644
--- a/posthog/temporal/health_checks/activities.py
+++ b/posthog/temporal/health_checks/activities.py
@@ -11,11 +11,11 @@ import temporalio.activity
from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level
from posthog.clickhouse.query_tagging import Feature, tag_queries
-from posthog.dags.common.health.observability import push_health_check_metrics
from posthog.models.organization import OrganizationMembership
from posthog.sync import database_sync_to_async
from posthog.temporal.common.rollout import filter_ids_for_rollout
from posthog.temporal.health_checks.models import BatchResult, HealthCheckWorkflowInputs
+from posthog.temporal.health_checks.observability import push_health_check_metrics
from posthog.temporal.health_checks.processing import _process_batch_detection
from posthog.temporal.health_checks.registry import ensure_registry_loaded, get_detect_fn, get_product
diff --git a/posthog/dags/common/health/db.py b/posthog/temporal/health_checks/db.py
similarity index 93%
rename from posthog/dags/common/health/db.py
rename to posthog/temporal/health_checks/db.py
index 563979e4eb0b..279f6adedb83 100644
--- a/posthog/dags/common/health/db.py
+++ b/posthog/temporal/health_checks/db.py
@@ -1,5 +1,5 @@
-from posthog.dags.common.health.types import HealthCheckResult
from posthog.models.health_issue import HealthIssue
+from posthog.temporal.health_checks.models import HealthCheckResult
def _upsert_issues(
diff --git a/posthog/temporal/health_checks/models.py b/posthog/temporal/health_checks/models.py
index db5d4e53534f..3f5aa0cdf8e9 100644
--- a/posthog/temporal/health_checks/models.py
+++ b/posthog/temporal/health_checks/models.py
@@ -1,16 +1,59 @@
from __future__ import annotations
+import dataclasses
from collections.abc import Callable
from dataclasses import dataclass
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
+
+from posthog.models.health_issue import HealthIssue
if TYPE_CHECKING:
from posthog.temporal.health_checks.framework import HealthCheckRegistration
-from posthog.dags.common.health.types import (
- BatchResult as BatchResult,
- HealthCheckResult as HealthCheckResult,
-)
+
+@dataclass
+class HealthCheckResult:
+ severity: HealthIssue.Severity
+ payload: dict[str, Any]
+ hash_keys: list[str] | None = None
+
+ def __post_init__(self) -> None:
+ valid = set(HealthIssue.Severity.values)
+ if self.severity not in valid:
+ raise ValueError(f"Invalid severity '{self.severity}', must be one of: {', '.join(sorted(valid))}")
+
+
+@dataclass
+class BatchResult:
+ batch_size: int = 0
+ issues_upserted: int = 0
+ issues_resolved: int = 0
+ teams_with_issues: int = 0
+ teams_healthy: int = 0
+ teams_failed: int = 0
+ teams_skipped: int = 0
+ detect_duration: float = 0.0
+ db_write_duration: float = 0.0
+ resolve_duration: float = 0.0
+
+ @property
+ def total_duration(self) -> float:
+ return self.detect_duration + self.db_write_duration + self.resolve_duration
+
+ @property
+ def teams_per_second(self) -> float:
+ return self.batch_size / self.total_duration if self.total_duration > 0 else 0
+
+ @property
+ def not_processed_rate(self) -> float:
+ return (self.teams_failed + self.teams_skipped) / self.batch_size if self.batch_size > 0 else 0
+
+ # Adds up all fields from another BatchResult, e.g. totals += batch_result
+ def __iadd__(self, other: BatchResult) -> BatchResult:
+ for f in dataclasses.fields(self):
+ setattr(self, f.name, getattr(self, f.name) + getattr(other, f.name))
+ return self
+
BatchDetectFn = Callable[[list[int]], dict[int, list[HealthCheckResult]]]
diff --git a/posthog/dags/common/health/observability.py b/posthog/temporal/health_checks/observability.py
similarity index 98%
rename from posthog/dags/common/health/observability.py
rename to posthog/temporal/health_checks/observability.py
index 29db9b117a8d..7b912f32c0db 100644
--- a/posthog/dags/common/health/observability.py
+++ b/posthog/temporal/health_checks/observability.py
@@ -5,9 +5,9 @@ from django.conf import settings
import structlog
from prometheus_client import Gauge
-from posthog.dags.common.health.types import BatchResult
from posthog.exceptions_capture import capture_exception
from posthog.metrics import pushed_metrics_registry
+from posthog.temporal.health_checks.models import BatchResult
logger = structlog.get_logger(__name__)
diff --git a/posthog/temporal/health_checks/processing.py b/posthog/temporal/health_checks/processing.py
index 6fd03a245508..c5bc46cb766f 100644
--- a/posthog/temporal/health_checks/processing.py
+++ b/posthog/temporal/health_checks/processing.py
@@ -2,7 +2,7 @@ import time
import structlog
-from posthog.dags.common.health.db import _resolve_stale_issues, _upsert_issues
+from posthog.temporal.health_checks.db import _resolve_stale_issues, _upsert_issues
from posthog.temporal.health_checks.models import BatchDetectFn, BatchResult
from posthog.temporal.health_checks.validation import _validate_batch_output
diff --git a/products/web_analytics/backend/test/test_no_pageleave_events.py b/products/web_analytics/backend/test/test_no_pageleave_events.py
index d2c49af573db..e18f3d8e493c 100644
--- a/products/web_analytics/backend/test/test_no_pageleave_events.py
+++ b/products/web_analytics/backend/test/test_no_pageleave_events.py
@@ -3,7 +3,7 @@ from unittest.mock import MagicMock, patch
from posthog.models.health_issue import HealthIssue
-from products.web_analytics.dags.no_pageleave_events import detect_no_pageleave_events
+from products.web_analytics.backend.temporal.health_checks.no_pageleave_events import NoPageleaveEventsCheck
@pytest.mark.parametrize(
@@ -15,12 +15,11 @@ from products.web_analytics.dags.no_pageleave_events import detect_no_pageleave_
],
ids=["all_healthy", "single_team_missing_pageleave", "multiple_teams_mixed"],
)
-@patch("products.web_analytics.dags.no_pageleave_events.execute_clickhouse_health_team_query")
+@patch("products.web_analytics.backend.temporal.health_checks.no_pageleave_events.execute_clickhouse_health_team_query")
def test_detect_no_pageleave_events(mock_query: MagicMock, mock_rows: list, expected_teams: set) -> None:
mock_query.return_value = mock_rows
- context = MagicMock()
- result = detect_no_pageleave_events([1, 2, 3, 42], context)
+ result = NoPageleaveEventsCheck().detect([1, 2, 3, 42])
assert set(result.keys()) == expected_teams
for team_id in expected_teams:
diff --git a/products/web_analytics/dags/no_live_events.py b/products/web_analytics/dags/no_live_events.py
deleted file mode 100644
index e1771f4ab7aa..000000000000
--- a/products/web_analytics/dags/no_live_events.py
+++ /dev/null
@@ -1,51 +0,0 @@
-import dagster
-
-from posthog.dags.common import JobOwners
-from posthog.dags.common.health.detectors import CLICKHOUSE_BATCH_EXECUTION_POLICY, batch_detector
-from posthog.dags.common.health.framework import create_health_check
-from posthog.dags.common.health.query import execute_clickhouse_health_team_query
-from posthog.dags.common.health.types import HealthCheckResult
-from posthog.models.health_issue import HealthIssue
-
-NO_LIVE_EVENTS_LOOKBACK_DAYS = 30
-NO_LIVE_EVENTS_SQL = """
-SELECT team_id
-FROM events
-WHERE team_id IN %(team_ids)s
- AND event = '$pageview'
- AND timestamp >= now() - INTERVAL %(lookback_days)s DAY
-GROUP BY team_id
-"""
-
-
-def detect_no_live_events(
- team_ids: list[int], context: dagster.OpExecutionContext
-) -> dict[int, list[HealthCheckResult]]:
- rows = execute_clickhouse_health_team_query(
- NO_LIVE_EVENTS_SQL,
- team_ids=team_ids,
- lookback_days=NO_LIVE_EVENTS_LOOKBACK_DAYS,
- context=context,
- )
-
- teams_with_recent_pageviews = {team_id for team_id, *_ in rows}
-
- issues: dict[int, list[HealthCheckResult]] = {}
- for team_id in set(team_ids) - teams_with_recent_pageviews:
- issues[team_id] = [
- HealthCheckResult(
- severity=HealthIssue.Severity.CRITICAL,
- payload={"reason": f"No $pageview events in last {NO_LIVE_EVENTS_LOOKBACK_DAYS} days"},
- hash_keys=[],
- )
- ]
-
- return issues
-
-
-no_live_events_check = create_health_check(
- name="no_live_events",
- kind="no_live_events",
- detector=batch_detector(detect_no_live_events, **CLICKHOUSE_BATCH_EXECUTION_POLICY),
- owner=JobOwners.TEAM_WEB_ANALYTICS,
-)
diff --git a/products/web_analytics/dags/no_pageleave_events.py b/products/web_analytics/dags/no_pageleave_events.py
deleted file mode 100644
index 29566ebd3b34..000000000000
--- a/products/web_analytics/dags/no_pageleave_events.py
+++ /dev/null
@@ -1,53 +0,0 @@
-import dagster
-
-from posthog.dags.common import JobOwners
-from posthog.dags.common.health.detectors import CLICKHOUSE_BATCH_EXECUTION_POLICY, batch_detector
-from posthog.dags.common.health.framework import create_health_check
-from posthog.dags.common.health.query import execute_clickhouse_health_team_query
-from posthog.dags.common.health.types import HealthCheckResult
-from posthog.models.health_issue import HealthIssue
-
-NO_PAGELEAVE_LOOKBACK_DAYS = 30
-NO_PAGELEAVE_SQL = """
-SELECT team_id
-FROM events
-WHERE team_id IN %(team_ids)s
- AND event IN ('$pageview', '$pageleave')
- AND timestamp >= now() - INTERVAL %(lookback_days)s DAY
-GROUP BY team_id
-HAVING countIf(event = '$pageview') > 0
- AND countIf(event = '$pageleave') = 0
-"""
-
-
-def detect_no_pageleave_events(
- team_ids: list[int], context: dagster.OpExecutionContext
-) -> dict[int, list[HealthCheckResult]]:
- rows = execute_clickhouse_health_team_query(
- NO_PAGELEAVE_SQL,
- team_ids=team_ids,
- lookback_days=NO_PAGELEAVE_LOOKBACK_DAYS,
- context=context,
- )
-
- issues: dict[int, list[HealthCheckResult]] = {}
- for (team_id,) in rows:
- issues[team_id] = [
- HealthCheckResult(
- severity=HealthIssue.Severity.WARNING,
- payload={
- "reason": f"Team has $pageview events but no $pageleave events in last {NO_PAGELEAVE_LOOKBACK_DAYS} days"
- },
- hash_keys=[],
- )
- ]
-
- return issues
-
-
-no_pageleave_events_check = create_health_check(
- name="no_pageleave_events",
- kind="no_pageleave_events",
- detector=batch_detector(detect_no_pageleave_events, **CLICKHOUSE_BATCH_EXECUTION_POLICY),
- owner=JobOwners.TEAM_WEB_ANALYTICS,
-)