: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): mirror posthog_featureflag into clickhouse (#85528)
Phil Haack1f8e8ffba1d7
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.ymlindex 5c26c90f570f..85c2aa4484f6 100644--- a/.github/workflows/ci-dagster.yml+++ b/.github/workflows/ci-dagster.yml@@ -165,6 +165,9 @@ jobs:- 'products/warehouse_sources/backend/models/**/*.py'- 'products/error_tracking/backend/**/*.py'- 'products/event_definitions/backend/**/*.py'+ # The postgres-to-clickhouse ETL DAG imports the encrypted-flag+ # payload redaction constant from the flags backend.+ - 'products/feature_flags/backend/**/*.py'- 'products/growth/backend/**/*.py'- 'products/signals/backend/**/*.py'- 'products/marketing_analytics/backend/**/*.py'diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.pyindex b7147c718dd4..64f6ea0fda20 100644--- a/posthog/dags/locations/clickhouse.py+++ b/posthog/dags/locations/clickhouse.py@@ -29,6 +29,7 @@ defs = dagster.Definitions(orm_examples.pending_deletions,postgres_to_clickhouse_etl.organizations_in_clickhouse,postgres_to_clickhouse_etl.teams_in_clickhouse,+ postgres_to_clickhouse_etl.feature_flags_in_clickhouse,],jobs=[add_index_to_materialized_column.add_index_to_materialized_column,diff --git a/posthog/dags/postgres_to_clickhouse_etl.py b/posthog/dags/postgres_to_clickhouse_etl.pyindex 30da74a651be..ae941702ebce 100644--- a/posthog/dags/postgres_to_clickhouse_etl.py+++ b/posthog/dags/postgres_to_clickhouse_etl.py@@ -1,11 +1,25 @@-"""ETL pipeline for syncing posthog_organization and posthog_team tables from Postgres to ClickHouse."""+"""ETL pipeline for syncing posthog_organization, posthog_team, and posthog_featureflag from Postgres to ClickHouse.++Table-driven: every table's columns, DDL, transform behavior, and watermark expression live on one+TableConfig entry. Adding a table means authoring one config entry plus its DDL function.++How correctness is shared with the storage engine:+- Incremental windows overlap by ``TableConfig.lookback_seconds`` (falling back to the job-level+ ``backward_lookback_seconds``) so a row committed after its timestamp slot passed the prior+ high-watermark is still picked up next run. Re-emitting a row the mirror already holds costs+ writes rather than correctness, so flags, the largest mirror, rewinds one hourly cycle while+ orgs and teams absorb a day of missed runs.+- ReplicatedReplacingMergeTree collapses re-emitted rows at merge time, but only for a table whose+ ORDER BY is identity alone. posthog_featureflag qualifies and keeps the newest row by+ ``updated_at``. posthog_organization and posthog_team still trail ``updated_at`` in their ORDER+ BY, so every version gets its own sort key and none of them collapse; a follow-up migration+ reshapes those two. Readers use FINAL / argMax either way.+"""import jsonimport uuid-from dataclasses import (- dataclass,- field as dataclass_field,-)+from collections.abc import Callable+from dataclasses import fieldfrom datetime import datetime, timedeltafrom typing import Any, Optional, Union@@ -32,39 +46,89 @@ from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.cluster import Query, get_clusterfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.dags.common import JobOwners+from posthog.dataclasses import frozen++from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE+++@frozen+class TableConfig:+ """Declarative description of one Postgres→ClickHouse mirror.++ - ``key``: columns that identify a row across writes. Must be immutable for the life of the row+ so a soft-delete-rename (feature flags rename ``key`` on tombstone) lands as an update, not a+ new identity. The same key drives the ClickHouse ORDER BY prefix. Unused by the sync runner+ today; the reconcile job (follow-up branch) matches rows on it.+ - ``watermark_column``: the non-null change-timestamp column mirrored in ClickHouse and used+ to advance the incremental high-watermark. The transform is responsible for never emitting+ a NULL here (feature flags fall back to ``created_at``).+ - ``watermark_expr``: SQL expression used in place of ``watermark_column`` when filtering and+ ordering the Postgres read, for tables whose watermark column is nullable at the source.+ Flags use COALESCE(updated_at, created_at), matching the coalesced value the mirror stores.+ - ``order_by``: full ClickHouse ORDER BY tuple, and with it the engine's dedup key. Contains+ ``key`` (optionally behind a leading locality column such as ``organization_id`` for teams)+ so same-row versions land in the same part. Anything that changes between versions of a row+ must stay out of it, or those versions stop collapsing.+ - ``select_columns``: Postgres columns to pull, in mirror order.+ - ``jsonb_text_cast``: columns to select as ``col::text`` rather than parsed jsonb, so psycopg2+ doesn't parse 30+ fields per row only for the transform to re-serialize them.+ - ``bool_fields`` / ``uuid_fields`` / ``array_fields``: per-table type adaptations the generic+ transform applies (booleans to 0/1, UUIDs to strings, array NULL-coalescing and+ None-filtering).+ - ``ddl``: callable producing the ``CREATE TABLE IF NOT EXISTS`` SQL for the ClickHouse mirror.+ - ``post_transform``: table-specific row fixups applied after the generic type adaptations.+ - ``lookback_seconds``: how far below the mirror's high-watermark the hourly sync rewinds each+ run, to catch rows that committed after their timestamp slot passed the prior watermark.+ Default 86400; a table overrides it when the rewrite cost of a wide overlap outweighs the+ outage backlog a missing run would leave.+ """--class PostgresToClickHouseETLConfig(Config):- """Configuration for the Postgres to ClickHouse ETL job."""-- full_refresh: bool = False- batch_size: int = 10000- max_execution_time: int = 3600---@dataclass-class ETLState:- """Track the state of the ETL process."""-+ key: tuple[str, ...]+ watermark_column: str+ order_by: str+ select_columns: list[str]+ ddl: Callable[[], str]+ jsonb_text_cast: set[str] = field(default_factory=set)+ bool_fields: list[str] = field(default_factory=list)+ uuid_fields: list[str] = field(default_factory=list)+ array_fields: list[str] = field(default_factory=list)+ watermark_expr: Optional[str] = None+ post_transform: Optional[Callable[[dict], dict]] = None+ lookback_seconds: int = 86400++ def select_clause(self) -> str:+ return ", ".join(f"{col}::text AS {col}" if col in self.jsonb_text_cast else col for col in self.select_columns)++ def build_incremental_query(self, table_name: str, last_sync: Optional[datetime]) -> tuple[str, list[Any]]:+ """SELECT everything past the watermark, for the op-based hourly sync."""+ if last_sync is None:+ return self._sql(table_name, ""), []+ return self._sql(table_name, f"WHERE {self._watermark()} > %s"), [last_sync]++ def build_partition_query(self, table_name: str, start: datetime, end: datetime) -> tuple[str, list[Any]]:+ """SELECT one fixed time window, for the asset path's per-hour backfill partitions."""+ watermark = self._watermark()+ return self._sql(table_name, f"WHERE {watermark} >= %s AND {watermark} < %s"), [start, end]++ def _watermark(self) -> str:+ return self.watermark_expr or self.watermark_column++ def _sql(self, table_name: str, where: str) -> str:+ parts = [f"SELECT {self.select_clause()} FROM {table_name}"]+ if where:+ parts.append(where)+ parts.append(f"ORDER BY {self._watermark()} ASC")+ return " ".join(parts)+++@frozen+class IncrementalState:last_sync_timestamp: Optional[datetime] = Nonerows_synced: int = 0- errors: list[str] = dataclass_field(default_factory=list)---# Define retry policy for transient failures-etl_retry_policy = RetryPolicy(- max_retries=3,- delay=60,- backoff=dagster.Backoff.EXPONENTIAL,- jitter=dagster.Jitter.PLUS_MINUS,-)def get_postgres_connection():- """Get a connection to the Postgres database."""- # Get database config from Django settingsdb_config = settings.DATABASES["default"]-return psycopg2.connect(host=db_config["HOST"],port=db_config["PORT"],@@ -75,8 +139,72 @@ def get_postgres_connection():)-def get_organization_table_sql() -> str:- """Get SQL for creating the organization table."""+def _normalize_filters(filters: Any) -> dict[str, Any]:+ """``filters`` arrives as a dict (psycopg2-parsed jsonb) or a string (mocked rows); normalize to a dict."""+ if isinstance(filters, str):+ try:+ filters = json.loads(filters)+ except (TypeError, ValueError):+ return {}+ return filters if isinstance(filters, dict) else {}+++# ----- posthog_organization -----++_ORG_COLS = [+ "id",+ "name",+ "slug",+ "logo_media_id",+ "created_at",+ "updated_at",+ "session_cookie_age",+ "is_member_join_email_enabled",+ "is_ai_data_processing_approved",+ "enforce_2fa",+ "members_can_invite",+ "members_can_use_personal_api_keys",+ "allow_publicly_shared_resources",+ "plugins_access_level",+ "for_internal_metrics",+ "default_experiment_stats_method",+ "is_hipaa",+ "customer_id",+ "available_product_features",+ "usage",+ "never_drop_data",+ "customer_trust_scores",+ "setup_section_2_completed",+ "personalization",+ "domain_whitelist",+ "is_platform",+]++_ORG_BOOL_FIELDS = [+ "is_member_join_email_enabled",+ "is_ai_data_processing_approved",+ "enforce_2fa",+ "members_can_invite",+ "members_can_use_personal_api_keys",+ "allow_publicly_shared_resources",+ "for_internal_metrics",+ "is_hipaa",+ "never_drop_data",+ "setup_section_2_completed",+ "is_platform",+]++# available_product_features is ArrayField(JSONField()), not JSONField. Excluded from the cast+# so psycopg2 parses the list and json.dumps round-trips the elements to valid JSON; `jsonb[]::text`+# renders Postgres array literal syntax (`{"{\"key\": \"val\"}"}`), which JSONExtract* cannot read.+_ORG_JSONB_TEXT_CAST = {+ "usage",+ "customer_trust_scores",+ "personalization",+}+++def _organization_ddl() -> str:return """CREATE TABLE IF NOT EXISTS models.posthog_organization (id UUID,@@ -113,8 +241,147 @@ def get_organization_table_sql() -> str:"""-def get_team_table_sql() -> str:- """Get SQL for creating the team table."""+# ----- posthog_team -----++_TEAM_COLS = [+ "id",+ "uuid",+ "organization_id",+ "parent_team_id",+ "project_id",+ "api_token",+ "app_urls",+ "name",+ "created_at",+ "updated_at",+ "anonymize_ips",+ "completed_snippet_onboarding",+ "has_completed_onboarding_for",+ "onboarding_tasks",+ "ingested_event",+ "autocapture_opt_out",+ "autocapture_web_vitals_opt_in",+ "autocapture_web_vitals_allowed_metrics",+ "autocapture_exceptions_opt_in",+ "autocapture_exceptions_errors_to_ignore",+ "person_processing_opt_out",+ "secret_api_token",+ "secret_api_token_backup",+ "session_recording_opt_in",+ "session_recording_sample_rate",+ "session_recording_minimum_duration_milliseconds",+ "session_recording_linked_flag",+ "session_recording_network_payload_capture_config",+ "session_recording_masking_config",+ "session_recording_url_trigger_config",+ "session_recording_url_blocklist_config",+ "session_recording_event_trigger_config",+ "session_recording_trigger_match_type_config",+ "session_replay_config",+ "survey_config",+ "capture_console_log_opt_in",+ "capture_performance_opt_in",+ "capture_dead_clicks",+ "surveys_opt_in",+ "heatmaps_opt_in",+ "flags_persistence_default",+ "feature_flag_confirmation_enabled",+ "feature_flag_confirmation_message",+ "session_recording_version",+ "signup_token",+ "is_demo",+ "access_control",+ "week_start_day",+ "inject_web_apps",+ "test_account_filters",+ "test_account_filters_default_checked",+ "path_cleaning_filters",+ "timezone",+ "data_attributes",+ "person_display_name_properties",+ "live_events_columns",+ "recording_domains",+ "human_friendly_comparison_periods",+ "cookieless_server_hash_mode",+ "primary_dashboard_id",+ "default_data_theme",+ "extra_settings",+ "modifiers",+ "correlation_config",+ "session_recording_retention_period_days",+ "plugins_opt_in",+ "opt_out_capture",+ "event_names",+ "event_names_with_usage",+ "event_properties",+ "event_properties_with_usage",+ "event_properties_numerical",+ "external_data_workspace_id",+ "external_data_workspace_last_synced_at",+ "api_query_rate_limit",+ "revenue_tracking_config",+ "drop_events_older_than",+ "base_currency",+]++_TEAM_BOOL_FIELDS = [+ "anonymize_ips",+ "completed_snippet_onboarding",+ "ingested_event",+ "autocapture_opt_out",+ "autocapture_web_vitals_opt_in",+ "autocapture_exceptions_opt_in",+ "person_processing_opt_out",+ "session_recording_opt_in",+ "capture_console_log_opt_in",+ "capture_performance_opt_in",+ "capture_dead_clicks",+ "surveys_opt_in",+ "heatmaps_opt_in",+ "flags_persistence_default",+ "feature_flag_confirmation_enabled",+ "is_demo",+ "access_control",+ "inject_web_apps",+ "test_account_filters_default_checked",+ "human_friendly_comparison_periods",+ "plugins_opt_in",+ "opt_out_capture",+]++# session_recording_url_trigger_config, session_recording_url_blocklist_config, and+# session_recording_event_trigger_config are ArrayField(JSONField()) / ArrayField(TextField()), not+# JSONField. Excluded from the cast so psycopg2 parses the list and json.dumps round-trips the+# elements to valid JSON; `::text` on an array renders Postgres array literal syntax, which+# JSONExtract* cannot read.+_TEAM_JSONB_TEXT_CAST = {+ "has_completed_onboarding_for",+ "onboarding_tasks",+ "autocapture_web_vitals_allowed_metrics",+ "autocapture_exceptions_errors_to_ignore",+ "session_recording_linked_flag",+ "session_recording_network_payload_capture_config",+ "session_recording_masking_config",+ "session_replay_config",+ "survey_config",+ "test_account_filters",+ "path_cleaning_filters",+ "data_attributes",+ "extra_settings",+ "modifiers",+ "correlation_config",+ "event_names",+ "event_names_with_usage",+ "event_properties",+ "event_properties_with_usage",+ "event_properties_numerical",+ "revenue_tracking_config",+}++_TEAM_ARRAY_FIELDS = ["app_urls", "person_display_name_properties", "live_events_columns", "recording_domains"]+++def _team_ddl() -> str:return """CREATE TABLE IF NOT EXISTS models.posthog_team (id Int64,@@ -193,7 +460,7 @@ def get_team_table_sql() -> str:external_data_workspace_last_synced_at Nullable(DateTime64(6)),api_query_rate_limit Nullable(String),revenue_tracking_config Nullable(String), -- JSON stored as String- drop_events_older_than Nullable(Int64), -- Store duration as seconds+ drop_events_older_than Nullable(Int64), -- stored as seconds (Django interval → total_seconds())base_currency Nullable(String),_inserted_at DateTime64(6) DEFAULT now64(6))@@ -203,249 +470,213 @@ def get_team_table_sql() -> str:"""-def create_database_if_not_exists(context: Optional[Union[OpExecutionContext, AssetExecutionContext]] = None) -> None:- """Create the models database in ClickHouse if it doesn't exist on all nodes."""- if context:- context.log.info("Creating database 'models' if it doesn't exist...")- create_db_sql = "CREATE DATABASE IF NOT EXISTS models"-- try:- # Use cluster API to create database on all nodes- cluster = get_cluster()- cluster.map_all_hosts(Query(create_db_sql)).result()- if context:- context.log.info("Database 'models' created/verified successfully on all nodes")- except Exception as e:- if context:- context.log.exception(f"Error creating database: {e}")- raise-+def _finalize_team_row(row: dict) -> dict:+ if row.get("drop_events_older_than") is not None:+ row["drop_events_older_than"] = int(row["drop_events_older_than"].total_seconds())+ return row-def create_clickhouse_tables(- context: Optional[Union[OpExecutionContext, AssetExecutionContext]] = None, force_recreate: bool = False-) -> None:- """Create the organization and team tables in ClickHouse on all nodes.- Args:- context: Execution context for logging- force_recreate: If True, drop and recreate tables even if they exist+# ----- posthog_featureflag -----++# last_called_at is deliberately excluded: it has its own bulk-update writer that bypasses auto_now,+# so a mirrored column would be permanently stale. See .notes/feature-flag-mirror-design.md.+_FEATURE_FLAG_COLS = [+ "id",+ "team_id",+ "key",+ "name",+ "filters",+ "deleted",+ "active",+ "archived",+ "version",+ "ensure_experience_continuity",+ "usage_dashboard_id",+ "has_enriched_analytics",+ "is_remote_configuration",+ "has_encrypted_payloads",+ "evaluation_runtime",+ "bucketing_identifier",+ "created_by_id",+ "created_at",+ "updated_at",+]++_FEATURE_FLAG_BOOL_FIELDS = [+ "deleted",+ "active",+ "archived",+ "ensure_experience_continuity",+ "has_enriched_analytics",+ "is_remote_configuration",+ "has_encrypted_payloads",+]++# ReplacingMergeTree collapses rows sharing the full ORDER BY tuple, so the tuple is identity only:+# adding updated_at would give every edit its own sort key and the mirror would keep every version.+_FEATURE_FLAG_ORDER_BY = "(team_id, id)"++# updated_at is NULL until a flag's first edit, so Postgres-side filtering and ordering fall back+# to created_at. The transform applies the same coalesce before insert, so the mirror's watermark+# read and this expression always agree.+_FEATURE_FLAG_WATERMARK_EXPR = "COALESCE(updated_at, created_at)"+++def _feature_flag_ddl() -> str:+ return f"""+ CREATE TABLE IF NOT EXISTS models.posthog_featureflag (+ id Int64,+ team_id Int64,+ key String,+ name String,+ filters String, -- JSON serialized+ deleted UInt8,+ active UInt8,+ archived UInt8,+ version Nullable(Int32),+ ensure_experience_continuity Nullable(UInt8),+ usage_dashboard_id Nullable(Int64),+ has_enriched_analytics Nullable(UInt8),+ is_remote_configuration Nullable(UInt8),+ has_encrypted_payloads Nullable(UInt8),+ evaluation_runtime Nullable(String),+ bucketing_identifier Nullable(String),+ created_by_id Nullable(Int32),+ created_at DateTime64(6),+ updated_at DateTime64(6),+ _inserted_at DateTime64(6) DEFAULT now64(6)+ )+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog_featureflag', '{{shard}}-{{replica}}', updated_at)+ ORDER BY {_FEATURE_FLAG_ORDER_BY}+ SETTINGS index_granularity = 8192"""- # First ensure the database exists- create_database_if_not_exists(context)- # Get cluster for executing commands on all nodes- cluster = get_cluster()- # Only drop tables if explicitly requested (e.g., schema changes)- if force_recreate:- if context:- context.log.info("Force recreate requested, dropping existing tables...")- try:- # Use Query class to drop tables on all nodes- cluster.map_all_hosts(Query("DROP TABLE IF EXISTS models.posthog_organization")).result()- cluster.map_all_hosts(Query("DROP TABLE IF EXISTS models.posthog_team")).result()- if context:- context.log.info("Dropped existing tables on all nodes")- except Exception as e:- if context:- context.log.warning(f"Error dropping tables (may not exist): {e}")-- # Create tables if they don't exist on all nodes- # The IF NOT EXISTS clause ensures we don't error if tables already exist- if context:- context.log.info("Creating posthog_organization table if it doesn't exist...")- try:- cluster.map_all_hosts(Query(get_organization_table_sql())).result()- if context:- context.log.info("Created/verified posthog_organization table on all nodes")- except Exception as e:- if context:- context.log.exception(f"Error creating organization table: {e}")- raise-- if context:- context.log.info("Creating posthog_team table if it doesn't exist...")- try:- cluster.map_all_hosts(Query(get_team_table_sql())).result()- if context:- context.log.info("Created/verified posthog_team table on all nodes")- except Exception as e:- if context:- context.log.exception(f"Error creating team table: {e}")- raise+def _finalize_feature_flag_row(row: dict) -> dict:+ # Normalizing guarantees a non-null JSON object for the non-Nullable String column, even when+ # the source value is NULL or unparseable.+ filters_dict = _normalize_filters(row.get("filters"))+ payloads = filters_dict.get("payloads")+ if isinstance(payloads, dict) and payloads:+ # Rotate-through-update commands (e.g. reencrypt_flag_payloads) bypass auto_now, so the+ # incremental mirror never sees a rotation. Substituting ciphertext with the API redaction+ # sentinel keeps the variant-key shape intact without persisting ciphertext in ClickHouse.+ filters_dict = {**filters_dict, "payloads": dict.fromkeys(payloads, REDACTED_PAYLOAD_VALUE)}+ row["filters"] = json.dumps(filters_dict)+ # Watermark column must never be NULL (it's in ORDER BY and the high-watermark read); a brand-new+ # flag hasn't been edited yet, so fall back to created_at. Makes updated_at non-null in the mirror.+ if row.get("updated_at") is None:+ row["updated_at"] = row.get("created_at")+ return row-def fetch_organizations_in_batches(conn, last_sync: Optional[datetime] = None, batch_size: int = 10000):- """Fetch organizations from Postgres in batches to avoid memory issues.+# ----- TABLE_CONFIGS -----++TABLE_CONFIGS: dict[str, TableConfig] = {+ "posthog_organization": TableConfig(+ key=("id",),+ watermark_column="updated_at",+ order_by="(id, updated_at)",+ select_columns=_ORG_COLS,+ jsonb_text_cast=_ORG_JSONB_TEXT_CAST,+ bool_fields=_ORG_BOOL_FIELDS,+ uuid_fields=["id", "logo_media_id"],+ array_fields=["domain_whitelist"],+ ddl=_organization_ddl,+ ),+ "posthog_team": TableConfig(+ key=("id",),+ watermark_column="updated_at",+ order_by="(organization_id, id, updated_at)",+ select_columns=_TEAM_COLS,+ jsonb_text_cast=_TEAM_JSONB_TEXT_CAST,+ bool_fields=_TEAM_BOOL_FIELDS,+ uuid_fields=["uuid", "organization_id"],+ array_fields=_TEAM_ARRAY_FIELDS,+ ddl=_team_ddl,+ post_transform=_finalize_team_row,+ ),+ # Identity is (team_id, id), not (team_id, key): soft-delete renames key with a :deleted:<id>+ # suffix, and id is what survives that rename.+ "posthog_featureflag": TableConfig(+ key=("team_id", "id"),+ watermark_column="updated_at",+ watermark_expr=_FEATURE_FLAG_WATERMARK_EXPR,+ order_by=_FEATURE_FLAG_ORDER_BY,+ select_columns=_FEATURE_FLAG_COLS,+ bool_fields=_FEATURE_FLAG_BOOL_FIELDS,+ # Flags re-emit the largest mirror, so one hourly cycle of overlap is enough; orgs and+ # teams keep the outsized 24h outage window from the default.+ ddl=_feature_flag_ddl,+ post_transform=_finalize_feature_flag_row,+ lookback_seconds=3600,+ ),+}- Yields batches of organization records.- """- # Use unique cursor name to avoid conflicts with concurrent runs- cursor_name = f"organizations_cursor_{uuid.uuid4().hex[:8]}"- cursor = conn.cursor(name=cursor_name) # Named cursor for server-side processing- try:- query = """- SELECT- id,- name,- slug,- logo_media_id,- created_at,- updated_at,- session_cookie_age,- is_member_join_email_enabled,- is_ai_data_processing_approved,- enforce_2fa,- members_can_invite,- members_can_use_personal_api_keys,- allow_publicly_shared_resources,- plugins_access_level,- for_internal_metrics,- default_experiment_stats_method,- is_hipaa,- customer_id,- available_product_features,- usage,- never_drop_data,- customer_trust_scores,- setup_section_2_completed,- personalization,- domain_whitelist,- is_platform- FROM posthog_organization- """-- params = []- if last_sync:- query += " WHERE updated_at > %s"- params.append(last_sync)-- query += " ORDER BY updated_at ASC"-- cursor.execute(query, params)- cursor.itersize = batch_size # Configure batch size for server-side cursor-- while True:- batch = cursor.fetchmany(batch_size)- if not batch:- break- yield batch- finally:- cursor.close()+class PostgresToClickHouseETLConfig(Config):+ full_refresh: bool = False+ batch_size: int = 10000+ # Fallback overlap for tables whose TableConfig leaves lookback_seconds at its default. A+ # table's own lookback_seconds (posthog_featureflag) wins over this when set non-default.+ backward_lookback_seconds: int = 86400-def fetch_organizations(conn, last_sync: Optional[datetime] = None, batch_size: int = 10000) -> list[dict]:- """Fetch all organizations from Postgres (legacy function for compatibility)."""- rows = []- for batch in fetch_organizations_in_batches(conn, last_sync, batch_size):- rows.extend(batch)- return rows+etl_retry_policy = RetryPolicy(+ max_retries=3,+ delay=60,+ backoff=dagster.Backoff.EXPONENTIAL,+ jitter=dagster.Jitter.PLUS_MINUS,+)-def fetch_teams_in_batches(conn, last_sync: Optional[datetime] = None, batch_size: int = 10000):- """Fetch teams from Postgres in batches to avoid memory issues.+def create_database_if_not_exists(context: Optional[Union[OpExecutionContext, AssetExecutionContext]] = None) -> None:+ if context:+ context.log.info("Creating database 'models' if it doesn't exist...")+ cluster = get_cluster()+ cluster.map_all_hosts(Query("CREATE DATABASE IF NOT EXISTS models")).result()- Yields batches of team records.- """- # Use unique cursor name to avoid conflicts with concurrent runs- cursor_name = f"teams_cursor_{uuid.uuid4().hex[:8]}"- cursor = conn.cursor(name=cursor_name) # Named cursor for server-side processing+def create_clickhouse_tables(+ context: Optional[Union[OpExecutionContext, AssetExecutionContext]] = None, force_recreate: bool = False+) -> None:+ create_database_if_not_exists(context)+ cluster = get_cluster()+ if force_recreate:+ for table_name in TABLE_CONFIGS:+ cluster.map_all_hosts(Query(f"DROP TABLE IF EXISTS models.{table_name}")).result()+ for table_name, cfg in TABLE_CONFIGS.items():+ if context:+ context.log.info(f"Creating models.{table_name} if it doesn't exist...")+ cluster.map_all_hosts(Query(cfg.ddl())).result()+++def transform_row(table_name: str, row: dict) -> dict:+ """Adapt one Postgres row dict for the ClickHouse mirror, in place."""+ cfg = TABLE_CONFIGS[table_name]+ for f in cfg.uuid_fields:+ if row.get(f) is not None:+ row[f] = str(row[f])+ for f in cfg.bool_fields:+ if row.get(f) is not None:+ row[f] = 1 if row[f] else 0+ for f in cfg.array_fields:+ if row.get(f) is None:+ row[f] = []+ elif isinstance(row[f], list):+ row[f] = [v for v in row[f] if v is not None]+ return cfg.post_transform(row) if cfg.post_transform else row+++def fetch_rows_in_batches(conn, table_name: str, last_sync: Optional[datetime], batch_size: int = 10000):+ """Yield batches from Postgres, incrementally filtered on the table's watermark expression."""+ cfg = TABLE_CONFIGS[table_name]+ query, params = cfg.build_incremental_query(table_name, last_sync)++ cursor = conn.cursor(name=f"{table_name}_cursor_{uuid.uuid4().hex[:8]}")try:- query = """- SELECT- id,- uuid,- organization_id,- parent_team_id,- project_id,- api_token,- app_urls,- name,- created_at,- updated_at,- anonymize_ips,- completed_snippet_onboarding,- has_completed_onboarding_for,- onboarding_tasks,- ingested_event,- autocapture_opt_out,- autocapture_web_vitals_opt_in,- autocapture_web_vitals_allowed_metrics,- autocapture_exceptions_opt_in,- autocapture_exceptions_errors_to_ignore,- person_processing_opt_out,- secret_api_token,- secret_api_token_backup,- session_recording_opt_in,- session_recording_sample_rate,- session_recording_minimum_duration_milliseconds,- session_recording_linked_flag,- session_recording_network_payload_capture_config,- session_recording_masking_config,- session_recording_url_trigger_config,- session_recording_url_blocklist_config,- session_recording_event_trigger_config,- session_recording_trigger_match_type_config,- session_replay_config,- survey_config,- capture_console_log_opt_in,- capture_performance_opt_in,- capture_dead_clicks,- surveys_opt_in,- heatmaps_opt_in,- flags_persistence_default,- feature_flag_confirmation_enabled,- feature_flag_confirmation_message,- session_recording_version,- signup_token,- is_demo,- access_control,- week_start_day,- inject_web_apps,- test_account_filters,- test_account_filters_default_checked,- path_cleaning_filters,- timezone,- data_attributes,- person_display_name_properties,- live_events_columns,- recording_domains,- human_friendly_comparison_periods,- cookieless_server_hash_mode,- primary_dashboard_id,- default_data_theme,- extra_settings,- modifiers,- correlation_config,- session_recording_retention_period_days,- plugins_opt_in,- opt_out_capture,- event_names,- event_names_with_usage,- event_properties,- event_properties_with_usage,- event_properties_numerical,- external_data_workspace_id,- external_data_workspace_last_synced_at,- api_query_rate_limit,- revenue_tracking_config,- drop_events_older_than,- base_currency- FROM posthog_team- """-- params = []- if last_sync:- query += " WHERE updated_at > %s"- params.append(last_sync)-- query += " ORDER BY updated_at ASC"-cursor.execute(query, params)- cursor.itersize = batch_size # Configure batch size for server-side cursor-+ cursor.itersize = batch_sizewhile True:batch = cursor.fetchmany(batch_size)if not batch:@@ -455,381 +686,119 @@ def fetch_teams_in_batches(conn, last_sync: Optional[datetime] = None, batch_sizcursor.close()-def fetch_teams(conn, last_sync: Optional[datetime] = None, batch_size: int = 10000) -> list[dict]:- """Fetch all teams from Postgres (legacy function for compatibility)."""- rows = []- for batch in fetch_teams_in_batches(conn, last_sync, batch_size):- rows.extend(batch)- return rows---def handle_array_fields(row: dict, array_fields: list[str]) -> None:- """Handle array fields that might be None or contain None elements.-- Args:- row: The data row to process (modified in place)- array_fields: List of field names that should be arrays- """- for field_name in array_fields:- if row.get(field_name) is None:- row[field_name] = []- elif isinstance(row[field_name], list):- # Filter out None values from the array- row[field_name] = [item for item in row[field_name] if item is not None]---def transform_organization_row(row: dict) -> dict:- """Transform a Postgres organization row for ClickHouse insertion."""- # Convert UUID fields to strings for ClickHouse- uuid_fields = ["id", "logo_media_id"]- for field_name in uuid_fields:- if row.get(field_name) is not None:- row[field_name] = str(row[field_name])-- # Convert JSON fields to strings- json_fields = ["available_product_features", "usage", "customer_trust_scores", "personalization"]-- for field in json_fields:- if row.get(field) is not None:- row[field] = json.dumps(row[field])-- # Convert boolean fields to UInt8- bool_fields = [- "is_member_join_email_enabled",- "is_ai_data_processing_approved",- "enforce_2fa",- "members_can_invite",- "members_can_use_personal_api_keys",- "allow_publicly_shared_resources",- "for_internal_metrics",- "is_hipaa",- "never_drop_data",- "setup_section_2_completed",- "is_platform",- ]-- for field in bool_fields:- if row.get(field) is not None:- row[field] = 1 if row[field] else 0-- # Handle array fields- handle_array_fields(row, ["domain_whitelist"])-- return row---def transform_team_row(row: dict) -> dict:- """Transform a Postgres team row for ClickHouse insertion."""- # Convert UUID fields to strings for ClickHouse- uuid_fields = ["uuid", "organization_id"]- for field_name in uuid_fields:- if row.get(field_name) is not None:- row[field_name] = str(row[field_name])-- # Convert JSON fields to strings- json_fields = [- "has_completed_onboarding_for",- "onboarding_tasks",- "autocapture_web_vitals_allowed_metrics",- "autocapture_exceptions_errors_to_ignore",- "session_recording_linked_flag",- "session_recording_network_payload_capture_config",- "session_recording_masking_config",- "session_recording_url_trigger_config",- "session_recording_url_blocklist_config",- "session_recording_event_trigger_config",- "session_replay_config",- "survey_config",- "test_account_filters",- "path_cleaning_filters",- "data_attributes",- "extra_settings",- "modifiers",- "correlation_config",- "event_names",- "event_names_with_usage",- "event_properties",- "event_properties_with_usage",- "event_properties_numerical",- "revenue_tracking_config",- ]-- for field in json_fields:- if row.get(field) is not None:- row[field] = json.dumps(row[field])-- # Convert boolean fields to UInt8- bool_fields = [- "anonymize_ips",- "completed_snippet_onboarding",- "ingested_event",- "autocapture_opt_out",- "autocapture_web_vitals_opt_in",- "autocapture_exceptions_opt_in",- "person_processing_opt_out",- "session_recording_opt_in",- "capture_console_log_opt_in",- "capture_performance_opt_in",- "capture_dead_clicks",- "surveys_opt_in",- "heatmaps_opt_in",- "flags_persistence_default",- "feature_flag_confirmation_enabled",- "is_demo",- "access_control",- "inject_web_apps",- "test_account_filters_default_checked",- "human_friendly_comparison_periods",- "plugins_opt_in",- "opt_out_capture",- ]-- for field in bool_fields:- if row.get(field) is not None:- row[field] = 1 if row[field] else 0-- # Convert timedelta to seconds- if row.get("drop_events_older_than") is not None:- row["drop_events_older_than"] = int(row["drop_events_older_than"].total_seconds())-- # Handle array fields- handle_array_fields(row, ["app_urls", "person_display_name_properties", "live_events_columns", "recording_domains"])-- return row---def insert_organizations_to_clickhouse(organizations: list[dict], batch_size: int = 10000) -> int:- """Insert organizations into ClickHouse."""- if not organizations:+def insert_rows_to_clickhouse(table_name: str, rows: list[dict], batch_size: int = 10000) -> int:+ if not rows:return 0+ cfg = TABLE_CONFIGS[table_name]+ transformed = [transform_row(table_name, dict(r)) for r in rows]- # Transform the data- transformed = [transform_organization_row(org) for org in organizations]-- # Prepare data for insertion- columns = list(transformed[0].keys())+ insert_sql = f"INSERT INTO models.{table_name} ({', '.join(cfg.select_columns)}) VALUES"- # Insert in batchestotal_inserted = 0for i in range(0, len(transformed), batch_size):batch = transformed[i : i + batch_size]-- # ClickHouse requires passing data as list of tuples- data = [tuple(row.get(col) for col in columns) for row in batch]-- query = f"INSERT INTO models.posthog_organization ({', '.join(columns)}) VALUES"-- sync_execute(query, data, with_column_types=False)+ # row[col], not row.get(col): a missing configured column is a bug (transform drift, config+ # typo), and a KeyError naming the column beats inserting NULL into a required field.+ data = [tuple(row[col] for col in cfg.select_columns) for row in batch]+ sync_execute(insert_sql, data, with_column_types=False)total_inserted += len(batch)-return total_inserted-def insert_teams_to_clickhouse(teams: list[dict], batch_size: int = 10000) -> int:- """Insert teams into ClickHouse."""- if not teams:- return 0-- # Transform the data- transformed = [transform_team_row(team) for team in teams]-- # Prepare data for insertion- columns = list(transformed[0].keys())-- # Insert in batches- total_inserted = 0- for i in range(0, len(transformed), batch_size):- batch = transformed[i : i + batch_size]-- # ClickHouse requires passing data as list of tuples- data = [tuple(row.get(col) for col in columns) for row in batch]-- query = f"INSERT INTO models.posthog_team ({', '.join(columns)}) VALUES"-- sync_execute(query, data, with_column_types=False)- total_inserted += len(batch)-- return total_inserted---@op(retry_policy=etl_retry_policy)-def sync_organizations(- context: OpExecutionContext,- config: PostgresToClickHouseETLConfig,-) -> ETLState:- """Sync organizations from Postgres to ClickHouse."""+def _sync_table(+ context: OpExecutionContext, config: PostgresToClickHouseETLConfig, table_name: str+) -> IncrementalState:with tags_context(product=Product.WAREHOUSE, feature=Feature.DATA_MODELING):- state = ETLState()-- context.log.info(f"Starting organization sync (full_refresh={config.full_refresh})")+ cfg = TABLE_CONFIGS[table_name]+ context.log.info(f"Starting {table_name} sync (full_refresh={config.full_refresh})")- # Create tables if they don't existcreate_clickhouse_tables(context)- # Get last sync timestamp from ClickHouse (if incremental)- last_sync = None+ last_sync: Optional[datetime] = Noneif not config.full_refresh:- result = sync_execute("SELECT max(updated_at) FROM models.posthog_organization")+ # nosemgrep: clickhouse-fstring-param-audit - table_name is a TABLE_CONFIGS key from the job config allowlist; watermark_column is code-controlled+ result = sync_execute(f"SELECT max({cfg.watermark_column}) FROM models.{table_name}")if result and result[0][0]:- last_sync = result[0][0]- context.log.info(f"Last sync timestamp for organizations: {last_sync}")-- # If full refresh, truncate the table- if config.full_refresh:- context.log.info("Full refresh requested, truncating posthog_organization table...")+ lookback = cfg.lookback_seconds if cfg.lookback_seconds != 86400 else config.backward_lookback_seconds+ last_sync = result[0][0] - timedelta(seconds=lookback)+ context.log.info(f"Last sync for {table_name}: {last_sync}")+ else:+ context.log.info(f"Full refresh: truncating models.{table_name}")try:- sync_execute("TRUNCATE TABLE models.posthog_organization")- context.log.info("Truncated posthog_organization table for full refresh")+ # nosemgrep: clickhouse-fstring-param-audit - table_name is a TABLE_CONFIGS key from the job config allowlist+ sync_execute(f"TRUNCATE TABLE models.{table_name}")except Exception as e:- context.log.warning(f"Could not truncate table (may not exist yet): {e}")- # Table might not exist, continue as it will be created+ context.log.warning(f"Could not truncate (may not exist): {e}")- # Connect to Postgres and fetch/insert data in streaming batchespg_conn = get_postgres_connection()try:total_rows = 0- last_updated = Nonebatch_num = 0-- # Process data in streaming fashion to avoid memory issues- for batch in fetch_organizations_in_batches(pg_conn, last_sync=last_sync, batch_size=config.batch_size):+ watermark: Optional[datetime] = None+ for batch in fetch_rows_in_batches(pg_conn, table_name, last_sync, config.batch_size):batch_num += 1- if batch:- context.log.info(f"Processing batch {batch_num} with {len(batch)} organizations")-- # Insert this batch into ClickHouse- rows_inserted = insert_organizations_to_clickhouse(batch, batch_size=config.batch_size)- total_rows += rows_inserted-- # Track the latest timestamp for state- batch_last_updated = max(org["updated_at"] for org in batch)- if last_updated is None or batch_last_updated > last_updated:- last_updated = batch_last_updated-- context.log.info(f"Inserted batch {batch_num} ({rows_inserted} rows). Total so far: {total_rows}")-- state.rows_synced = total_rows- state.last_sync_timestamp = last_updated- context.log.info(f"Completed sync: inserted {total_rows} organizations into ClickHouse")-- except Exception as e:- state.errors.append(f"Error syncing organizations: {str(e)}")- context.log.exception(f"Error syncing organizations: {str(e)}")- raise+ rows_inserted = insert_rows_to_clickhouse(table_name, batch, batch_size=config.batch_size)+ total_rows += rows_inserted+ batch_max = max(+ (row[cfg.watermark_column] for row in batch if row.get(cfg.watermark_column) is not None),+ default=None,+ )+ if batch_max is not None and (watermark is None or batch_max > watermark):+ watermark = batch_max+ context.log.info(f"Batch {batch_num}: +{rows_inserted} → models.{table_name} (total {total_rows})")+ context.log.info(f"Completed {table_name} sync: {total_rows} rows")finally:pg_conn.close()- # Add metadata- context.add_output_metadata(- {- "rows_synced": MetadataValue.int(state.rows_synced),- "last_sync_timestamp": MetadataValue.text(- str(state.last_sync_timestamp) if state.last_sync_timestamp else "N/A"- ),- "full_refresh": MetadataValue.bool(config.full_refresh),- }- )-- return state---@op(retry_policy=etl_retry_policy)-def sync_teams(- context: OpExecutionContext,- config: PostgresToClickHouseETLConfig,-) -> ETLState:- """Sync teams from Postgres to ClickHouse."""- with tags_context(product=Product.WAREHOUSE, feature=Feature.DATA_MODELING):- state = ETLState()-- context.log.info(f"Starting team sync (full_refresh={config.full_refresh})")+ return IncrementalState(last_sync_timestamp=watermark, rows_synced=total_rows)- # Create tables if they don't exist- create_clickhouse_tables(context)- # Get last sync timestamp from ClickHouse (if incremental)- last_sync = None- if not config.full_refresh:- result = sync_execute("SELECT max(updated_at) FROM models.posthog_team")- if result and result[0][0]:- last_sync = result[0][0]- context.log.info(f"Last sync timestamp for teams: {last_sync}")-- # If full refresh, truncate the table- if config.full_refresh:- context.log.info("Full refresh requested, truncating posthog_team table...")- try:- sync_execute("TRUNCATE TABLE models.posthog_team")- context.log.info("Truncated posthog_team table for full refresh")- except Exception as e:- context.log.warning(f"Could not truncate table (may not exist yet): {e}")- # Table might not exist, continue as it will be created-- # Connect to Postgres and fetch/insert data in streaming batches- pg_conn = get_postgres_connection()- try:- total_rows = 0- last_updated = None- batch_num = 0-- # Process data in streaming fashion to avoid memory issues- for batch in fetch_teams_in_batches(pg_conn, last_sync=last_sync, batch_size=config.batch_size):- batch_num += 1- if batch:- context.log.info(f"Processing batch {batch_num} with {len(batch)} teams")-- # Insert this batch into ClickHouse- rows_inserted = insert_teams_to_clickhouse(batch, batch_size=config.batch_size)- total_rows += rows_inserted+def _sync_metadata(context: OpExecutionContext, state: IncrementalState, config: PostgresToClickHouseETLConfig) -> None:+ context.add_output_metadata(+ {+ "rows_synced": MetadataValue.int(state.rows_synced),+ "last_sync_timestamp": MetadataValue.text(+ str(state.last_sync_timestamp) if state.last_sync_timestamp else "N/A"+ ),+ "full_refresh": MetadataValue.bool(config.full_refresh),+ }+ )- # Track the latest timestamp for state- batch_last_updated = max(team["updated_at"] for team in batch)- if last_updated is None or batch_last_updated > last_updated:- last_updated = batch_last_updated- context.log.info(f"Inserted batch {batch_num} ({rows_inserted} rows). Total so far: {total_rows}")+@op(retry_policy=etl_retry_policy)+def sync_organizations(context: OpExecutionContext, config: PostgresToClickHouseETLConfig) -> IncrementalState:+ state = _sync_table(context, config, "posthog_organization")+ _sync_metadata(context, state, config)+ return state- state.rows_synced = total_rows- state.last_sync_timestamp = last_updated- context.log.info(f"Completed sync: inserted {total_rows} teams into ClickHouse")- except Exception as e:- state.errors.append(f"Error syncing teams: {str(e)}")- context.log.exception(f"Error syncing teams: {str(e)}")- raise- finally:- pg_conn.close()+@op(retry_policy=etl_retry_policy)+def sync_teams(context: OpExecutionContext, config: PostgresToClickHouseETLConfig) -> IncrementalState:+ state = _sync_table(context, config, "posthog_team")+ _sync_metadata(context, state, config)+ return state- # Add metadata- context.add_output_metadata(- {- "rows_synced": MetadataValue.int(state.rows_synced),- "last_sync_timestamp": MetadataValue.text(- str(state.last_sync_timestamp) if state.last_sync_timestamp else "N/A"- ),- "full_refresh": MetadataValue.bool(config.full_refresh),- }- )- return state+@op(retry_policy=etl_retry_policy)+def sync_feature_flags(context: OpExecutionContext, config: PostgresToClickHouseETLConfig) -> IncrementalState:+ state = _sync_table(context, config, "posthog_featureflag")+ _sync_metadata(context, state, config)+ return state@opdef verify_sync(context: OpExecutionContext,- org_state: ETLState,- team_state: ETLState,+ org_state: IncrementalState,+ team_state: IncrementalState,+ feature_flag_state: IncrementalState,) -> dict[str, Any]:- """Verify the sync was successful by checking row counts."""with tags_context(product=Product.WAREHOUSE, feature=Feature.DATA_MODELING):- # Get counts from ClickHouse- org_count_result = sync_execute("SELECT count(*) FROM models.posthog_organization")- team_count_result = sync_execute("SELECT count(*) FROM models.posthog_team")-- org_count = org_count_result[0][0] if org_count_result else 0- team_count = team_count_result[0][0] if team_count_result else 0+ org_count = sync_execute("SELECT count() FROM models.posthog_organization")[0][0]+ team_count = sync_execute("SELECT count() FROM models.posthog_team")[0][0]+ flag_count = sync_execute("SELECT count() FROM models.posthog_featureflag")[0][0]- verification = {+ counts = {"organizations": {"clickhouse_count": org_count,"rows_synced": org_state.rows_synced,@@ -840,249 +809,88 @@ def verify_sync("rows_synced": team_state.rows_synced,"last_sync": str(team_state.last_sync_timestamp) if team_state.last_sync_timestamp else None,},- "success": len(org_state.errors) == 0 and len(team_state.errors) == 0,+ "feature_flags": {+ "clickhouse_count": flag_count,+ "rows_synced": feature_flag_state.rows_synced,+ "last_sync": str(feature_flag_state.last_sync_timestamp)+ if feature_flag_state.last_sync_timestamp+ else None,+ },}-- context.log.info(f"Verification results: {verification}")-+ context.log.info(f"Verification: {counts}")context.add_output_metadata({"org_count": MetadataValue.int(org_count),"team_count": MetadataValue.int(team_count),- "success": MetadataValue.bool(bool(verification["success"])),+ "feature_flag_count": MetadataValue.int(flag_count),})-- return verification+ return counts-# Define the hourly partition-hourly_partition = HourlyPartitionsDefinition(- start_date="2024-01-01-00:00",- timezone="UTC",-)+hourly_partition = HourlyPartitionsDefinition(start_date="2024-01-01-00:00", timezone="UTC")-@job(- tags={"owner": JobOwners.TEAM_CLICKHOUSE.value},- partitions_def=hourly_partition,-)+@job(tags={"owner": JobOwners.TEAM_CLICKHOUSE.value}, partitions_def=hourly_partition)def postgres_to_clickhouse_etl_job():- """Hourly ETL job to sync organization and team data from Postgres to ClickHouse."""org_state = sync_organizations()team_state = sync_teams()- verify_sync(org_state, team_state)+ flag_state = sync_feature_flags()+ verify_sync(org_state, team_state, flag_state)-# Asset-based approach (alternative/additional to ops)-@asset(- retry_policy=etl_retry_policy,- partitions_def=hourly_partition,- backfill_policy=BackfillPolicy(max_partitions_per_run=24), # Allow up to 24 hours backfill at once+postgres_to_clickhouse_hourly_schedule = ScheduleDefinition(+ job=postgres_to_clickhouse_etl_job,+ cron_schedule="0 * * * *",+ name="postgres_to_clickhouse_hourly",+ execution_timezone="UTC",)-def organizations_in_clickhouse(- context: AssetExecutionContext,-) -> None:- """Asset representing organizations data in ClickHouse."""- with tags_context(product=Product.WAREHOUSE, feature=Feature.DATA_MODELING):- config = PostgresToClickHouseETLConfig(full_refresh=False)-- # Create tables if they don't exist- create_clickhouse_tables(context)- # Determine the time window for this partition- partition_key = context.partition_key- # Hourly partition key format: "2024-01-01-14:00"- partition_datetime = datetime.strptime(partition_key, "%Y-%m-%d-%H:%M")- start_time = partition_datetime- end_time = partition_datetime + timedelta(hours=1)- # Connect to Postgres and fetch data for this partition+def _sync_asset_partition(context: AssetExecutionContext, table_name: str) -> None:+ with tags_context(product=Product.WAREHOUSE, feature=Feature.DATA_MODELING):+ config = PostgresToClickHouseETLConfig()+ create_clickhouse_tables(context)+ # partition_time_window raises the moment the run covers a multi-partition range; the+ # backfill policy allows up to 24 partitions per run, so taking it off the context+ # (rather than context.partition_key) is what makes range backfills actually work.+ window = context.partition_time_window+ start_time, end_time = window.start, window.end+ cfg = TABLE_CONFIGS[table_name]+ query, params = cfg.build_partition_query(table_name, start_time, end_time)pg_conn = get_postgres_connection()try:cursor = pg_conn.cursor()- cursor.execute(- """- SELECT- id,- name,- slug,- logo_media_id,- created_at,- updated_at,- session_cookie_age,- is_member_join_email_enabled,- is_ai_data_processing_approved,- enforce_2fa,- members_can_invite,- members_can_use_personal_api_keys,- allow_publicly_shared_resources,- plugins_access_level,- for_internal_metrics,- default_experiment_stats_method,- is_hipaa,- customer_id,- available_product_features,- usage,- never_drop_data,- customer_trust_scores,- setup_section_2_completed,- personalization,- domain_whitelist,- is_platform- FROM posthog_organization- WHERE updated_at >= %s AND updated_at < %s- ORDER BY updated_at ASC- """,- (start_time, end_time),- )-- organizations = cursor.fetchall()- context.log.info(f"Fetched {len(organizations)} organizations for partition {partition_key}")-- # Insert into ClickHouse- if organizations:- rows_inserted = insert_organizations_to_clickhouse(organizations, batch_size=config.batch_size)- context.log.info(f"Inserted {rows_inserted} organizations into ClickHouse")-+ cursor.execute(query, params)+ rows = cursor.fetchall()+ context.log.info(f"Fetched {len(rows)} {table_name} rows for partition window {start_time}..{end_time}")+ if rows:+ inserted = insert_rows_to_clickhouse(table_name, rows, batch_size=config.batch_size)+ context.log.info(f"Inserted {inserted} rows into models.{table_name}")cursor.close()-finally:pg_conn.close()-@asset(- retry_policy=etl_retry_policy,- partitions_def=hourly_partition,- backfill_policy=BackfillPolicy(max_partitions_per_run=24), # Allow up to 24 hours backfill at once-)-def teams_in_clickhouse(- context: AssetExecutionContext,-) -> None:- """Asset representing teams data in ClickHouse."""- with tags_context(product=Product.WAREHOUSE, feature=Feature.DATA_MODELING):- config = PostgresToClickHouseETLConfig(full_refresh=False)-- # Create tables if they don't exist- create_clickhouse_tables(context)-- # Determine the time window for this partition- partition_key = context.partition_key- # Hourly partition key format: "2024-01-01-14:00"- partition_datetime = datetime.strptime(partition_key, "%Y-%m-%d-%H:%M")- start_time = partition_datetime- end_time = partition_datetime + timedelta(hours=1)+def _hourly_backfill_asset(name: str, table_name: str):+ """Build a partitioned asset that mirrors one UTC hour of ``table_name`` per materialization.- # Connect to Postgres and fetch data for this partition- pg_conn = get_postgres_connection()- try:- cursor = pg_conn.cursor()- cursor.execute(- """- SELECT- id,- uuid,- organization_id,- parent_team_id,- project_id,- api_token,- app_urls,- name,- created_at,- updated_at,- anonymize_ips,- completed_snippet_onboarding,- has_completed_onboarding_for,- onboarding_tasks,- ingested_event,- autocapture_opt_out,- autocapture_web_vitals_opt_in,- autocapture_web_vitals_allowed_metrics,- autocapture_exceptions_opt_in,- autocapture_exceptions_errors_to_ignore,- person_processing_opt_out,- secret_api_token,- secret_api_token_backup,- session_recording_opt_in,- session_recording_sample_rate,- session_recording_minimum_duration_milliseconds,- session_recording_linked_flag,- session_recording_network_payload_capture_config,- session_recording_masking_config,- session_recording_url_trigger_config,- session_recording_url_blocklist_config,- session_recording_event_trigger_config,- session_recording_trigger_match_type_config,- session_replay_config,- survey_config,- capture_console_log_opt_in,- capture_performance_opt_in,- capture_dead_clicks,- surveys_opt_in,- heatmaps_opt_in,- flags_persistence_default,- feature_flag_confirmation_enabled,- feature_flag_confirmation_message,- session_recording_version,- signup_token,- is_demo,- access_control,- week_start_day,- inject_web_apps,- test_account_filters,- test_account_filters_default_checked,- path_cleaning_filters,- timezone,- data_attributes,- person_display_name_properties,- live_events_columns,- recording_domains,- human_friendly_comparison_periods,- cookieless_server_hash_mode,- primary_dashboard_id,- default_data_theme,- extra_settings,- modifiers,- correlation_config,- session_recording_retention_period_days,- plugins_opt_in,- opt_out_capture,- event_names,- event_names_with_usage,- event_properties,- event_properties_with_usage,- event_properties_numerical,- external_data_workspace_id,- external_data_workspace_last_synced_at,- api_query_rate_limit,- revenue_tracking_config,- drop_events_older_than,- base_currency- FROM posthog_team- WHERE updated_at >= %s AND updated_at < %s- ORDER BY updated_at ASC- """,- (start_time, end_time),- )-- teams = cursor.fetchall()- context.log.info(f"Fetched {len(teams)} teams for partition {partition_key}")-- # Insert into ClickHouse- if teams:- rows_inserted = insert_teams_to_clickhouse(teams, batch_size=config.batch_size)- context.log.info(f"Inserted {rows_inserted} teams into ClickHouse")+ Manual escape hatch alongside the scheduled hourly job: materialize a partition range from the+ Dagster UI to re-sync a known time window (for example after an incident or a missed run).+ """- cursor.close()+ @asset(+ name=name,+ retry_policy=etl_retry_policy,+ partitions_def=hourly_partition,+ backfill_policy=BackfillPolicy(max_partitions_per_run=24),+ )+ def _backfill(context: AssetExecutionContext) -> None:+ _sync_asset_partition(context, table_name)- finally:- pg_conn.close()+ return _backfill-# Create an hourly schedule for the job-postgres_to_clickhouse_hourly_schedule = ScheduleDefinition(- job=postgres_to_clickhouse_etl_job,- cron_schedule="0 * * * *", # Run at the top of every hour- name="postgres_to_clickhouse_hourly",- execution_timezone="UTC",-)+organizations_in_clickhouse = _hourly_backfill_asset("organizations_in_clickhouse", "posthog_organization")+teams_in_clickhouse = _hourly_backfill_asset("teams_in_clickhouse", "posthog_team")+feature_flags_in_clickhouse = _hourly_backfill_asset("feature_flags_in_clickhouse", "posthog_featureflag")diff --git a/posthog/dags/tests/test_postgres_to_clickhouse_etl.py b/posthog/dags/tests/test_postgres_to_clickhouse_etl.pyindex 72d0c545c7ad..f8e73bea21c6 100644--- a/posthog/dags/tests/test_postgres_to_clickhouse_etl.py+++ b/posthog/dags/tests/test_postgres_to_clickhouse_etl.py@@ -1,78 +1,102 @@-"""Tests for the Postgres to ClickHouse ETL pipeline."""+"""Tests for the table-driven Postgres to ClickHouse ETL pipeline."""import jsonfrom datetime import datetime, timedeltafrom decimal import Decimalimport pytest-from freezegun import freeze_timefrom unittest.mock import MagicMock, patch-from dagster import build_op_context+from dagster import build_asset_context, build_op_context+from parameterized import parameterizedfrom posthog.dags.postgres_to_clickhouse_etl import (- ETLState,+ TABLE_CONFIGS,+ IncrementalState,+ PostgresToClickHouseETLConfig,+ _sync_table,create_clickhouse_tables,- fetch_organizations,- fetch_teams,- insert_organizations_to_clickhouse,- insert_teams_to_clickhouse,+ feature_flags_in_clickhouse,+ fetch_rows_in_batches,+ insert_rows_to_clickhouse,organizations_in_clickhouse,postgres_to_clickhouse_etl_job,postgres_to_clickhouse_hourly_schedule,- sync_organizations,- sync_teams,teams_in_clickhouse,- transform_organization_row,- transform_team_row,+ transform_row,verify_sync,)-class TestTransformations:- """Test data transformation functions."""+def _config(**overrides) -> PostgresToClickHouseETLConfig:+ base: dict = {+ "full_refresh": False,+ "batch_size": 10000,+ "backward_lookback_seconds": 86400,+ }+ base.update(overrides)+ return PostgresToClickHouseETLConfig(**base)+++def _flag_row(**overrides):+ row = {+ "id": 7,+ "team_id": 42,+ "key": "new-checkout",+ "name": "New checkout flow",+ "filters": {"groups": []},+ "deleted": False,+ "active": True,+ "archived": False,+ "version": 3,+ "ensure_experience_continuity": False,+ "has_enriched_analytics": True,+ "is_remote_configuration": False,+ "has_encrypted_payloads": False,+ "evaluation_runtime": "server",+ "bucketing_identifier": "distinct_id",+ "created_by_id": 11,+ "usage_dashboard_id": None,+ "created_at": datetime(2025, 3, 1, 12, 0, 0),+ "updated_at": None,+ }+ row.update(overrides)+ return row++class TestTransformations:def test_transform_organization_row(self):- """Test organization row transformation."""import uuidtest_uuid = uuid.uuid4()-row = {"id": test_uuid,"name": "Test Org",- "slug": "test-org","logo_media_id": uuid.uuid4(),"is_member_join_email_enabled": True,"is_hipaa": False,- "available_product_features": [{"key": "feature1", "name": "Feature 1"}],- "usage": {"events": {"usage": 1000}},- "personalization": {"role": "engineer"},+ "available_product_features": '[{"key": "feature1"}]', # ::text on the PG side+ "usage": '{"events": 1000}',+ "personalization": '{"role": "engineer"}',"domain_whitelist": ["example.com"],}- transformed = transform_organization_row(row)+ transformed = transform_row("posthog_organization", row)- # Check UUID conversionsassert transformed["id"] == str(test_uuid)assert isinstance(transformed["logo_media_id"], str)-- # Check boolean conversionsassert transformed["is_member_join_email_enabled"] == 1assert transformed["is_hipaa"] == 0-- # Check JSON field conversions- assert transformed["available_product_features"] == json.dumps([{"key": "feature1", "name": "Feature 1"}])- assert transformed["usage"] == json.dumps({"events": {"usage": 1000}})- assert transformed["personalization"] == json.dumps({"role": "engineer"})+ # ::text columns pass through untouched — no parse-then-redump.+ assert transformed["available_product_features"] == row["available_product_features"]+ assert transformed["usage"] == row["usage"]+ assert transformed["domain_whitelist"] == ["example.com"]def test_transform_team_row(self):- """Test team row transformation."""import uuidteam_uuid = uuid.uuid4()org_uuid = uuid.uuid4()-row = {"id": 1,"uuid": team_uuid,@@ -80,460 +104,511 @@ class TestTransformations:"name": "Test Team","anonymize_ips": True,"session_recording_opt_in": False,- "test_account_filters": [{"key": "email", "value": "[email protected]"}],- "drop_events_older_than": timedelta(days=30),+ "test_account_filters": '[{"key": "email", "value": "[email protected]"}]',"app_urls": ["https://app.example.com"],"person_display_name_properties": None,"session_recording_sample_rate": Decimal("0.50"),+ "drop_events_older_than": timedelta(days=30),}- transformed = transform_team_row(row)+ transformed = transform_row("posthog_team", row)- # Check UUID conversionsassert transformed["uuid"] == str(team_uuid)assert transformed["organization_id"] == str(org_uuid)-- # Check boolean conversionsassert transformed["anonymize_ips"] == 1assert transformed["session_recording_opt_in"] == 0+ assert transformed["test_account_filters"] == row["test_account_filters"]+ assert transformed["app_urls"] == ["https://app.example.com"]+ assert transformed["person_display_name_properties"] == []+ assert transformed["session_recording_sample_rate"] == Decimal("0.50")+ assert transformed["drop_events_older_than"] == 30 * 24 * 60 * 60- # Check JSON field conversion- assert transformed["test_account_filters"] == json.dumps([{"key": "email", "value": "[email protected]"}])+ def test_transform_feature_flag_row_null_updated_at_coalesces_to_created_at(self):+ # updated_at is NULL until a flag's first edit; the mirror must not store NULL because the+ # watermark read depends on it.+ created = datetime(2025, 3, 1, 12, 0, 0)+ row = _flag_row(created_at=created, updated_at=None)- # Check timedelta conversion- assert transformed["drop_events_older_than"] == 30 * 24 * 60 * 60 # 30 days in seconds+ transformed = transform_row("posthog_featureflag", row)- # Check array field handling- assert transformed["app_urls"] == ["https://app.example.com"]- assert transformed["person_display_name_properties"] == []+ assert transformed["updated_at"] == created- # Check decimal remains unchanged- assert transformed["session_recording_sample_rate"] == Decimal("0.50")+ def test_transform_feature_flag_row_serializes_filters(self):+ original_filters = {+ "groups": [{"properties": [{"key": "email", "value": "@posthog.com", "type": "person"}]}],+ "multivariate": {"variants": [{"key": "control"}, {"key": "test"}]},+ }+ row = _flag_row(filters=original_filters)+ transformed = transform_row("posthog_featureflag", row)-class TestDatabaseOperations:- """Test database operation functions."""+ # transform mutates the row in place (filters becomes a JSON string), so parse it back and compare to the original dict.+ assert json.loads(transformed["filters"]) == original_filters+ assert transformed["deleted"] == 0+ assert transformed["active"] == 1- @patch("posthog.dags.postgres_to_clickhouse_etl.psycopg2.connect")- def test_fetch_organizations(self, mock_connect):- """Test fetching organizations from Postgres."""- # Mock both named cursor and regular cursor- mock_named_cursor = MagicMock()- mock_named_cursor.fetchmany.side_effect = [[{"id": 1, "name": "Org 1", "updated_at": datetime.now()}], []]+ def test_transform_feature_flag_row_unparseable_filters_falls_back_to_empty_dict(self):+ transformed = transform_row("posthog_featureflag", _flag_row(filters="not json"))- mock_regular_cursor = MagicMock()- mock_regular_cursor.fetchmany.side_effect = [[{"id": 1, "name": "Org 1", "updated_at": datetime.now()}], []]+ assert transformed["filters"] == "{}"- mock_conn = MagicMock()+ def test_transform_feature_flag_row_redacts_payload_ciphertext(self):+ # Rotation commands update filters.payloads without touching updated_at, so the incremental+ # mirror never sees a rotation. Substituting ciphertext with the redaction sentinel keeps the+ # variant-key shape intact without mirroring ciphertext after a key is retired.+ from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE- # Return named cursor when name is provided, regular cursor otherwise- def cursor_side_effect(name=None):- if name:- return mock_named_cursor- return mock_regular_cursor-- mock_conn.cursor.side_effect = cursor_side_effect- mock_connect.return_value = mock_conn-- # Test without last_sync- orgs = fetch_organizations(mock_conn)- assert len(orgs) == 1- assert orgs[0]["name"] == "Org 1"-- # Verify query was called correctly on named cursor- mock_named_cursor.execute.assert_called_once()- call_args = mock_named_cursor.execute.call_args[0]- assert "SELECT" in call_args[0]- assert "FROM posthog_organization" in call_args[0]- assert "WHERE updated_at >" not in call_args[0]-- @patch("posthog.dags.postgres_to_clickhouse_etl.psycopg2.connect")- def test_fetch_organizations_incremental(self, mock_connect):- """Test fetching organizations incrementally."""- mock_named_cursor = MagicMock()- mock_named_cursor.fetchmany.side_effect = [[{"id": 2, "name": "Org 2", "updated_at": datetime.now()}], []]+ row = _flag_row(+ filters={+ "groups": [],+ "payloads": {"control": "gAAAAABkp8G8_example_ciphertext", "test": "gAAAAABkp8G8_another"},+ },+ has_encrypted_payloads=True,+ )- mock_conn = MagicMock()- mock_conn.cursor.return_value = mock_named_cursor- mock_connect.return_value = mock_conn-- last_sync = datetime.now() - timedelta(days=1)- _ = fetch_organizations(mock_conn, last_sync=last_sync)-- # Verify incremental query on named cursor- mock_named_cursor.execute.assert_called_once()- call_args = mock_named_cursor.execute.call_args[0]- assert "WHERE updated_at > %s" in call_args[0]- assert call_args[1] == [last_sync]-- @patch("posthog.dags.postgres_to_clickhouse_etl.psycopg2.connect")- def test_fetch_teams(self, mock_connect):- """Test fetching teams from Postgres."""- mock_named_cursor = MagicMock()- mock_named_cursor.fetchmany.side_effect = [- [{"id": 1, "name": "Team 1", "organization_id": 1, "updated_at": datetime.now()}],- [],- ]- mock_conn = MagicMock()- mock_conn.cursor.return_value = mock_named_cursor- mock_connect.return_value = mock_conn+ transformed = transform_row("posthog_featureflag", row)- teams = fetch_teams(mock_conn)- assert len(teams) == 1- assert teams[0]["name"] == "Team 1"+ mirrored = json.loads(transformed["filters"])+ assert mirrored["payloads"] == {+ "control": REDACTED_PAYLOAD_VALUE,+ "test": REDACTED_PAYLOAD_VALUE,+ }- @patch("posthog.dags.postgres_to_clickhouse_etl.get_cluster")- def test_create_clickhouse_tables(self, mock_get_cluster):- """Test ClickHouse table creation."""- # Mock the cluster and its methods- mock_cluster = MagicMock()- mock_futures_map = MagicMock()- mock_futures_map.result.return_value = {}- mock_cluster.map_all_hosts.return_value = mock_futures_map- mock_get_cluster.return_value = mock_cluster+ def test_transform_feature_flag_row_leaves_empty_payload_dict_alone(self):+ transformed = transform_row("posthog_featureflag", _flag_row(filters={"groups": [], "payloads": {}}))- create_clickhouse_tables()+ mirrored = json.loads(transformed["filters"])+ assert mirrored["payloads"] == {}- # Should have called map_all_hosts for:- # 1. CREATE DATABASE IF NOT EXISTS models- # 2. CREATE TABLE posthog_organization- # 3. CREATE TABLE posthog_team- assert mock_cluster.map_all_hosts.call_count == 3+ def test_transform_row_unknown_table_raises(self):+ with pytest.raises(KeyError):+ transform_row("posthog_nonexistent", {})- # Extract the Query objects from the calls- calls = [call[0][0].query for call in mock_cluster.map_all_hosts.call_args_list]- # Check database creation- assert any("CREATE DATABASE IF NOT EXISTS models" in call for call in calls)+class TestTableDdl:+ def test_organization_ddl(self):+ sql = TABLE_CONFIGS["posthog_organization"].ddl()+ assert "models.posthog_organization" in sql+ assert "ReplicatedReplacingMergeTree" in sql- # Check table creation with ReplicatedReplacingMergeTree- assert any(- "CREATE TABLE IF NOT EXISTS models.posthog_organization" in call and "ReplicatedReplacingMergeTree" in call- for call in calls- )- assert any(- "CREATE TABLE IF NOT EXISTS models.posthog_team" in call and "ReplicatedReplacingMergeTree" in call- for call in calls- )+ def test_team_ddl(self):+ sql = TABLE_CONFIGS["posthog_team"].ddl()+ assert "models.posthog_team" in sql+ assert "ReplicatedReplacingMergeTree" in sql- @patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")- def test_insert_organizations_to_clickhouse(self, mock_sync_execute):- """Test inserting organizations into ClickHouse."""- organizations = [- {- "id": 1,- "uuid": "uuid1",- "name": "Org 1",- "slug": "org-1",- "is_member_join_email_enabled": True,- "available_product_features": [{"key": "feature1"}],- "usage": {"events": 1000},- "personalization": {},- "domain_whitelist": [],- "created_at": datetime.now(),- "updated_at": datetime.now(),- },- {- "id": 2,- "uuid": "uuid2",- "name": "Org 2",- "slug": "org-2",- "is_member_join_email_enabled": False,- "available_product_features": None,- "usage": None,- "personalization": {},- "domain_whitelist": [],- "created_at": datetime.now(),- "updated_at": datetime.now(),- },- ]+ def test_feature_flag_ddl_shape(self):+ sql = TABLE_CONFIGS["posthog_featureflag"].ddl()+ assert "models.posthog_featureflag" in sql+ assert "ReplicatedReplacingMergeTree" in sql+ assert "key String" in sql+ assert "filters String" in sql+ # Identity alone, so ReplacingMergeTree collapses a flag's versions instead of keeping one+ # row per edit. id rather than key because tombstones rename key; see the TableConfig note.+ assert "ORDER BY (team_id, id)" in sql+ # updated_at as the version column, so the newest Postgres state wins even when a backfill+ # re-inserts an older window after the hourly sync.+ assert "'{shard}-{replica}', updated_at)" in sql- rows_inserted = insert_organizations_to_clickhouse(organizations, batch_size=10)- assert rows_inserted == 2- assert mock_sync_execute.call_count == 1+class TestFetchRowsInBatches:+ def _conn_yielding(self, batches):+ mock_cursor = MagicMock()+ mock_cursor.fetchmany.side_effect = [*batches, []]+ mock_conn = MagicMock()+ mock_conn.cursor.return_value = mock_cursor+ return mock_conn, mock_cursor++ def test_no_incremental_filter_for_full_refresh(self):+ conn, cursor = self._conn_yielding([[{"id": 1}]])+ list(fetch_rows_in_batches(conn, "posthog_organization", None, batch_size=100))++ sql = cursor.execute.call_args[0][0]+ assert "FROM posthog_organization" in sql+ assert "WHERE" not in sql++ def test_incremental_filter_uses_watermark_column(self):+ conn, cursor = self._conn_yielding([[{"id": 1}]])+ list(fetch_rows_in_batches(conn, "posthog_organization", datetime(2024, 1, 1), batch_size=100))++ sql, params = cursor.execute.call_args[0]+ assert "WHERE updated_at > %s" in sql+ assert params == [datetime(2024, 1, 1)]++ def test_feature_flag_incremental_catches_updated_and_created_rows(self):+ # A flag's first edit sets updated_at; creation sets created_at and leaves updated_at NULL.+ # The COALESCE watermark must pick up either one moving into the window.+ conn, cursor = self._conn_yielding([[{"id": 1}]])+ list(fetch_rows_in_batches(conn, "posthog_featureflag", datetime(2024, 1, 1), batch_size=100))++ sql, params = cursor.execute.call_args[0]+ assert "WHERE COALESCE(updated_at, created_at) > %s" in sql+ assert "ORDER BY COALESCE(updated_at, created_at) ASC" in sql+ assert params == [datetime(2024, 1, 1)]++ def test_jsonb_columns_selected_as_text_to_skip_parse(self):+ """Org/team JSON columns go over the wire as text so psycopg2 doesn't parse them only to re-serialize."""+ conn, cursor = self._conn_yielding([[{"id": 1}]])+ list(fetch_rows_in_batches(conn, "posthog_team", None, batch_size=100))++ sql = cursor.execute.call_args[0][0]+ assert "test_account_filters::text AS test_account_filters" in sql++ def test_flag_filters_not_cast_to_text(self):+ conn, cursor = self._conn_yielding([[{"id": 1}]])+ list(fetch_rows_in_batches(conn, "posthog_featureflag", None, batch_size=100))++ sql = cursor.execute.call_args[0][0]+ assert "filters::text" not in sql+ assert " filters" in sql++ def test_named_server_side_cursor_used(self):+ conn, _ = self._conn_yielding([[{"id": 1}]])+ list(fetch_rows_in_batches(conn, "posthog_organization", None, batch_size=100))+ assert conn.cursor.call_args[1].get("name") is not None+++def _org_row(**overrides):+ """A full org row, as the SELECT always returns every configured column."""+ row = dict.fromkeys(TABLE_CONFIGS["posthog_organization"].select_columns)+ row.update(+ {+ "id": 1,+ "name": "Org",+ "is_member_join_email_enabled": True,+ "available_product_features": "[]",+ "created_at": datetime(2024, 1, 1),+ "updated_at": datetime(2024, 1, 2),+ }+ )+ row.update(overrides)+ return row- # Verify INSERT statement- call_args = mock_sync_execute.call_args[0]- assert "INSERT INTO models.posthog_organization" in call_args[0]+class TestInsertRowsToClickHouse:@patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")- def test_insert_teams_to_clickhouse(self, mock_sync_execute):- """Test inserting teams into ClickHouse."""- teams = [- {- "id": 1,- "uuid": "team-uuid1",- "organization_id": 1,- "name": "Team 1",- "anonymize_ips": True,- "test_account_filters": [{"key": "test"}],- "app_urls": ["https://example.com"],- "drop_events_older_than": timedelta(days=7),- "created_at": datetime.now(),- "updated_at": datetime.now(),- }- ]+ def test_empty_rows_returns_zero(self, mock_sync_execute):+ assert insert_rows_to_clickhouse("posthog_organization", [], batch_size=10) == 0+ mock_sync_execute.assert_not_called()- rows_inserted = insert_teams_to_clickhouse(teams, batch_size=10)+ @patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")+ def test_insert_targets_models_db_with_parameterized_values(self, mock_sync_execute):+ n = insert_rows_to_clickhouse("posthog_organization", [_org_row()], batch_size=10)- assert rows_inserted == 1- assert mock_sync_execute.call_count == 1+ assert n == 1+ call = mock_sync_execute.call_args[0]+ assert "INSERT INTO models.posthog_organization" in call[0]+ assert "VALUES" in call[0]+ # Data is passed as a separate argument, not inlined into SQL text — lets the driver's+ # columnar writer handle arrays / datetimes / strings with embedded quotes.+ assert call[1] is not None+ @patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")+ def test_insert_raises_on_missing_configured_column(self, mock_sync_execute):+ # A row missing a configured column is a bug upstream (transform drift, config typo);+ # the insert must raise naming the column, not silently write NULL into a required field.+ row = _org_row()+ del row["id"]-class TestOps:- """Test Dagster ops."""+ with pytest.raises(KeyError, match="id"):+ insert_rows_to_clickhouse("posthog_organization", [row], batch_size=10)+ mock_sync_execute.assert_not_called()@patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")- @patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")- @patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")- def test_sync_organizations_op(self, mock_create_tables, mock_get_pg_conn, mock_sync_execute):- """Test the sync_organizations op."""- # Mock ClickHouse last sync query- mock_sync_execute.return_value = [[datetime(2024, 1, 1)]]+ def test_insert_batches_by_batch_size(self, mock_sync_execute):+ rows = [_org_row(id=i, name=f"Org {i}") for i in range(25)]- # Mock Postgres connection and data- mock_pg_conn = MagicMock()- mock_get_pg_conn.return_value = mock_pg_conn+ n = insert_rows_to_clickhouse("posthog_organization", rows, batch_size=10)- with (- patch("posthog.dags.postgres_to_clickhouse_etl.fetch_organizations_in_batches") as mock_fetch,- patch("posthog.dags.postgres_to_clickhouse_etl.insert_organizations_to_clickhouse") as mock_insert,- ):- # Mock the generator to yield one batch- mock_fetch.return_value = iter([[{"id": 1, "name": "Org 1", "updated_at": datetime(2024, 1, 2)}]])- mock_insert.return_value = 1+ assert n == 25+ assert mock_sync_execute.call_count == 3- # Create context and run op- context = build_op_context(- config={- "full_refresh": False,- "batch_size": 10000,- "max_execution_time": 3600,- }- )- result = sync_organizations(context)+class TestCreateClickHouseTables:+ @patch("posthog.dags.postgres_to_clickhouse_etl.get_cluster")+ def test_creates_database_plus_three_tables(self, mock_get_cluster):+ mock_cluster = MagicMock()+ mock_futures = MagicMock()+ mock_futures.result.return_value = {}+ mock_cluster.map_all_hosts.return_value = mock_futures+ mock_get_cluster.return_value = mock_cluster- assert isinstance(result, ETLState)- assert result.rows_synced == 1- assert result.last_sync_timestamp == datetime(2024, 1, 2)- assert len(result.errors) == 0+ create_clickhouse_tables()++ assert mock_cluster.map_all_hosts.call_count == 4 # 1 DB + 3 tables+ sqls = [call[0][0].query for call in mock_cluster.map_all_hosts.call_args_list]+ assert any("CREATE DATABASE IF NOT EXISTS models" in sql for sql in sqls)+ for table in ("posthog_organization", "posthog_team", "posthog_featureflag"):+ assert any(f"models.{table}" in sql and "ReplicatedReplacingMergeTree" in sql for sql in sqls)- # Verify calls- mock_create_tables.assert_called_once()- mock_fetch.assert_called_once()- mock_insert.assert_called_once()+class TestSyncTable:@patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")@patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")@patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")- def test_sync_teams_op(self, mock_create_tables, mock_get_pg_conn, mock_sync_execute):- """Test the sync_teams op."""- # Mock ClickHouse last sync query- mock_sync_execute.return_value = [[None]]-- # Mock Postgres connection- mock_pg_conn = MagicMock()- mock_get_pg_conn.return_value = mock_pg_conn-+ def test_incremental_advances_watermark_to_latest_seen_row(+ self, mock_create_tables, mock_get_pg, mock_sync_execute+ ):+ mock_sync_execute.side_effect = [+ [[None]], # first-run watermark read on an empty mirror+ None, # INSERT+ ]+ mock_get_pg.return_value = MagicMock()with (- patch("posthog.dags.postgres_to_clickhouse_etl.fetch_teams_in_batches") as mock_fetch,- patch("posthog.dags.postgres_to_clickhouse_etl.insert_teams_to_clickhouse") as mock_insert,+ patch("posthog.dags.postgres_to_clickhouse_etl.fetch_rows_in_batches") as mock_fetch,+ patch("posthog.dags.postgres_to_clickhouse_etl.insert_rows_to_clickhouse") as mock_insert,):- # Mock the generator to yield one batchmock_fetch.return_value = iter(- [[{"id": 1, "name": "Team 1", "organization_id": 1, "updated_at": datetime(2024, 1, 2)}]]+ [[{"id": 1, "updated_at": datetime(2024, 1, 2)}, {"id": 2, "updated_at": datetime(2024, 1, 3)}]])- mock_insert.return_value = 1+ mock_insert.return_value = 2+ context = build_op_context()- # Create context and run op- context = build_op_context(- config={- "full_refresh": False,- "batch_size": 10000,- "max_execution_time": 3600,- }- )-- result = sync_teams(context)+ state = _sync_table(context, _config(backward_lookback_seconds=0), "posthog_organization")- assert isinstance(result, ETLState)- assert result.rows_synced == 1- assert result.last_sync_timestamp == datetime(2024, 1, 2)- assert len(result.errors) == 0+ assert isinstance(state, IncrementalState)+ assert state.rows_synced == 2+ assert state.last_sync_timestamp == datetime(2024, 1, 3)+ mock_insert.assert_called_once()@patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")- def test_verify_sync_op(self, mock_sync_execute):- """Test the verify_sync op."""- # Mock ClickHouse counts- mock_sync_execute.side_effect = [- [[100]], # organization count- [[150]], # team count- ]-- # Create states- org_state = ETLState(rows_synced=10, last_sync_timestamp=datetime.now())- team_state = ETLState(rows_synced=15, last_sync_timestamp=datetime.now())+ @patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")+ @patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")+ def test_incremental_watermark_wraps_back_by_lookback_window(+ self, mock_create_tables, mock_get_pg, mock_sync_execute+ ):+ """The PG query is invoked with (mirror high-watermark − backward_lookback_seconds), not the raw watermark."""+ mock_sync_execute.return_value = [[datetime(2024, 3, 10, 12, 0, 0)]]+ mock_get_pg.return_value = MagicMock()+ with (+ patch("posthog.dags.postgres_to_clickhouse_etl.fetch_rows_in_batches") as mock_fetch,+ patch("posthog.dags.postgres_to_clickhouse_etl.insert_rows_to_clickhouse"),+ ):+ mock_fetch.return_value = iter([])+ context = build_op_context()- context = build_op_context()- result = verify_sync(context, org_state, team_state)+ _sync_table(context, _config(backward_lookback_seconds=3600), "posthog_organization")- assert result["success"] is True- assert result["organizations"]["clickhouse_count"] == 100- assert result["teams"]["clickhouse_count"] == 150- assert result["organizations"]["rows_synced"] == 10- assert result["teams"]["rows_synced"] == 15+ mock_fetch.assert_called_once()+ # fetch_rows_in_batches(conn, table_name, last_sync, batch_size) — third positional arg.+ last_sync_arg = mock_fetch.call_args[0][2]+ assert last_sync_arg == datetime(2024, 3, 10, 11, 0, 0)- @patch("posthog.dags.postgres_to_clickhouse_etl.get_cluster")@patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")@patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")@patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")- def test_sync_organizations_full_refresh(- self, mock_create_tables, mock_get_pg_conn, mock_sync_execute, mock_get_cluster- ):- """Test sync_organizations with full refresh."""-- mock_pg_conn = MagicMock()- mock_get_pg_conn.return_value = mock_pg_conn-+ def test_flags_use_per_table_lookback_not_job_config(self, mock_create_tables, mock_get_pg, mock_sync_execute):+ """posthog_featureflag's watermark wraps by its TableConfig lookback even when the job-level lookback is 0."""+ mock_sync_execute.return_value = [[datetime(2024, 3, 10, 12, 0, 0)]]+ mock_get_pg.return_value = MagicMock()with (- patch("posthog.dags.postgres_to_clickhouse_etl.fetch_organizations_in_batches") as mock_fetch,- patch("posthog.dags.postgres_to_clickhouse_etl.insert_organizations_to_clickhouse") as mock_insert,+ patch("posthog.dags.postgres_to_clickhouse_etl.fetch_rows_in_batches") as mock_fetch,+ patch("posthog.dags.postgres_to_clickhouse_etl.insert_rows_to_clickhouse"),):- # Mock the generator to yield no batchesmock_fetch.return_value = iter([])- mock_insert.return_value = 0-- context = build_op_context(- config={- "full_refresh": True,- "batch_size": 10000,- "max_execution_time": 3600,- }- )+ context = build_op_context()- result = sync_organizations(context)+ _sync_table(context, _config(backward_lookback_seconds=0), "posthog_featureflag")- # Verify truncate was called for full refresh- mock_sync_execute.assert_any_call("TRUNCATE TABLE models.posthog_organization")+ last_sync_arg = mock_fetch.call_args[0][2]+ assert last_sync_arg == datetime(2024, 3, 10, 12, 0, 0) - timedelta(+ seconds=TABLE_CONFIGS["posthog_featureflag"].lookback_seconds+ )- assert result.rows_synced == 0- assert len(result.errors) == 0+ def test_flags_lookback_defaults_to_one_hour(self):+ """Flags re-emit one hourly cycle; orgs and teams keep the 24h outage window."""+ assert TABLE_CONFIGS["posthog_featureflag"].lookback_seconds == 3600+ assert TABLE_CONFIGS["posthog_organization"].lookback_seconds == 86400+ assert TABLE_CONFIGS["posthog_team"].lookback_seconds == 86400+ @patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")+ @patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")+ @patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")+ def test_full_refresh_truncates_table(self, mock_create_tables, mock_get_pg, mock_sync_execute):+ mock_sync_execute.return_value = None+ mock_get_pg.return_value = MagicMock()+ with (+ patch("posthog.dags.postgres_to_clickhouse_etl.fetch_rows_in_batches") as mock_fetch,+ patch("posthog.dags.postgres_to_clickhouse_etl.insert_rows_to_clickhouse"),+ ):+ mock_fetch.return_value = iter([])+ context = build_op_context()++ state = _sync_table(context, _config(full_refresh=True), "posthog_team")-class TestErrorHandling:- """Test error handling in the ETL pipeline."""+ assert state.rows_synced == 0+ mock_sync_execute.assert_any_call("TRUNCATE TABLE models.posthog_team")@patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")@patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")@patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")- def test_sync_organizations_handles_errors(self, mock_create_tables, mock_get_pg_conn, mock_sync_execute):- """Test that sync_organizations handles errors properly."""-- # Mock the max(updated_at) query to return None- mock_sync_execute.return_value = [[None]]+ def test_empty_postgres_result_leaves_watermark_state_empty(+ self, mock_create_tables, mock_get_pg, mock_sync_execute+ ):+ """Watermark state comes only from this run's PG rows; the stored mirror watermark is a hint, not state."""+ mock_sync_execute.return_value = [[datetime(2024, 1, 1)]]+ mock_get_pg.return_value = MagicMock()+ with (+ patch("posthog.dags.postgres_to_clickhouse_etl.fetch_rows_in_batches") as mock_fetch,+ patch("posthog.dags.postgres_to_clickhouse_etl.insert_rows_to_clickhouse"),+ ):+ mock_fetch.return_value = iter([])+ context = build_op_context()- mock_pg_conn = MagicMock()- mock_get_pg_conn.return_value = mock_pg_conn+ state = _sync_table(context, _config(), "posthog_team")- with patch("posthog.dags.postgres_to_clickhouse_etl.fetch_organizations_in_batches") as mock_fetch:- mock_fetch.side_effect = Exception("Database connection failed")+ assert state.last_sync_timestamp is None+ assert state.rows_synced == 0- context = build_op_context(- config={- "full_refresh": False,- "batch_size": 10000,- "max_execution_time": 3600,- }- )+ @patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")+ @patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")+ @patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")+ def test_errors_close_postgres_connection(self, mock_sync_execute, mock_create_tables, mock_get_pg):+ mock_sync_execute.return_value = [[None]]+ mock_pg = MagicMock()+ mock_get_pg.return_value = mock_pg- with pytest.raises(Exception, match="Database connection failed"):- sync_organizations(context)+ with patch("posthog.dags.postgres_to_clickhouse_etl.fetch_rows_in_batches") as mock_fetch:+ mock_fetch.side_effect = Exception("connection lost")+ context = build_op_context()- # Verify connection was closed even on error- mock_pg_conn.close.assert_called_once()+ with pytest.raises(Exception, match="connection lost"):+ _sync_table(context, _config(), "posthog_organization")+ mock_pg.close.assert_called_once()-class TestPartitioning:- """Test partitioning and scheduling."""+ @patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")+ @patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")+ @patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")+ def test_feature_flag_watermark_skips_null_updated_at_in_mixed_batch(+ self, mock_create_tables, mock_get_pg, mock_sync_execute+ ):+ """A batch mixing edited and never-edited flags must not crash max() and must advance to the edited flag."""+ mock_sync_execute.side_effect = [+ [[None]],+ None,+ ]+ mock_get_pg.return_value = MagicMock()+ edited_at = datetime(2025, 4, 15, 10, 0, 0)+ with (+ patch("posthog.dags.postgres_to_clickhouse_etl.fetch_rows_in_batches") as mock_fetch,+ patch("posthog.dags.postgres_to_clickhouse_etl.insert_rows_to_clickhouse") as mock_insert,+ ):+ mock_fetch.return_value = iter(+ [+ [+ {"id": 7, "team_id": 42, "created_at": datetime(2025, 3, 1), "updated_at": None},+ {"id": 8, "team_id": 42, "created_at": datetime(2025, 3, 2), "updated_at": edited_at},+ ]+ ]+ )+ mock_insert.return_value = 2+ context = build_op_context()- def test_hourly_partition_definition(self):- """Test that the job has hourly partitions."""- assert postgres_to_clickhouse_etl_job.partitions_def is not None- partitions = postgres_to_clickhouse_etl_job.partitions_def.get_partition_keys()+ state = _sync_table(context, _config(backward_lookback_seconds=0), "posthog_featureflag")- # Check that partitions are hourly- # Get first two partition keys and verify they're 1 hour apart- first_partition = partitions[0]- second_partition = partitions[1]+ assert state.rows_synced == 2+ assert state.last_sync_timestamp == edited_at- # Parse the partition keys (format: "2024-01-01-00:00")- first_dt = datetime.strptime(first_partition, "%Y-%m-%d-%H:%M")- second_dt = datetime.strptime(second_partition, "%Y-%m-%d-%H:%M")+ @patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")+ @patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")+ @patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")+ def test_feature_flag_watermark_stays_empty_for_all_null_batch(+ self, mock_create_tables, mock_get_pg, mock_sync_execute+ ):+ """A batch of only never-edited flags still syncs rows but reports no watermark for the run."""+ mock_sync_execute.side_effect = [+ [[None]],+ None,+ ]+ mock_get_pg.return_value = MagicMock()+ with (+ patch("posthog.dags.postgres_to_clickhouse_etl.fetch_rows_in_batches") as mock_fetch,+ patch("posthog.dags.postgres_to_clickhouse_etl.insert_rows_to_clickhouse") as mock_insert,+ ):+ mock_fetch.return_value = iter(+ [[{"id": 7, "team_id": 42, "created_at": datetime(2025, 3, 1), "updated_at": None}]]+ )+ mock_insert.return_value = 1+ context = build_op_context()- assert (second_dt - first_dt).total_seconds() == 3600 # 1 hour in seconds+ state = _sync_table(context, _config(backward_lookback_seconds=0), "posthog_featureflag")- def test_hourly_schedule(self):- """Test the hourly schedule configuration."""- assert postgres_to_clickhouse_hourly_schedule.cron_schedule == "0 * * * *"- assert postgres_to_clickhouse_hourly_schedule.execution_timezone == "UTC"- assert postgres_to_clickhouse_hourly_schedule.job_name == postgres_to_clickhouse_etl_job.name+ assert state.rows_synced == 1+ assert state.last_sync_timestamp is None- @freeze_time("2024-01-15 14:00:00")- def test_schedule_execution_time(self):- """Test that schedule runs at the correct time."""- from datetime import datetime- # The cron schedule is "0 * * * *" which means at minute 0 of every hour- assert postgres_to_clickhouse_hourly_schedule.cron_schedule == "0 * * * *"+class TestVerifySync:+ @patch("posthog.dags.postgres_to_clickhouse_etl.sync_execute")+ def test_reports_all_three_tables(self, mock_sync_execute):+ mock_sync_execute.side_effect = [[[100]], [[150]], [[42]]]- # Verify the schedule would run at the top of the hour- # In real usage, this would trigger at 14:00:00- frozen_time = datetime(2024, 1, 15, 14, 0, 0)- assert frozen_time.minute == 0- assert frozen_time.second == 0+ org = IncrementalState(rows_synced=10, last_sync_timestamp=datetime(2024, 1, 1))+ team = IncrementalState(rows_synced=15, last_sync_timestamp=datetime(2024, 1, 1))+ flag = IncrementalState(rows_synced=42, last_sync_timestamp=datetime(2024, 1, 1))- def test_backfill_policy(self):- """Test backfill policy for assets."""- # Check organizations asset- assert organizations_in_clickhouse.partitions_def is not None- assert organizations_in_clickhouse.backfill_policy is not None- assert organizations_in_clickhouse.backfill_policy.max_partitions_per_run == 24+ result = verify_sync(build_op_context(), org, team, flag)- # Check teams asset- assert teams_in_clickhouse.partitions_def is not None- assert teams_in_clickhouse.backfill_policy is not None- assert teams_in_clickhouse.backfill_policy.max_partitions_per_run == 24+ assert result["organizations"]["clickhouse_count"] == 100+ assert result["teams"]["clickhouse_count"] == 150+ assert result["feature_flags"]["clickhouse_count"] == 42- @patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection")- @patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables")- def test_asset_hourly_window(self, mock_create_tables, mock_get_pg_conn):- """Test that assets process correct hourly time windows."""- from dagster import build_asset_context- mock_pg_conn = MagicMock()- mock_cursor = MagicMock()- mock_cursor.fetchall.return_value = []- mock_pg_conn.cursor.return_value = mock_cursor- mock_get_pg_conn.return_value = mock_pg_conn+class TestDagsterWiring:+ def test_hourly_job_defers_to_three_sync_ops_and_verifies(self):+ assert postgres_to_clickhouse_etl_job is not None+ node_names = {node.name for node in postgres_to_clickhouse_etl_job.graph.nodes}+ assert {"sync_organizations", "sync_teams", "sync_feature_flags", "verify_sync"} <= node_names- # Test with a specific partition key- partition_key = "2024-01-15-14:00"- context = build_asset_context(partition_key=partition_key)+ def test_hourly_schedule_wires_to_etl_job(self):+ assert postgres_to_clickhouse_hourly_schedule.job_name == postgres_to_clickhouse_etl_job.name+ assert postgres_to_clickhouse_hourly_schedule.cron_schedule == "0 * * * *"+ assert postgres_to_clickhouse_hourly_schedule.execution_timezone == "UTC"- # Run the asset- organizations_in_clickhouse(context)+ @parameterized.expand(+ [+ ("organizations", organizations_in_clickhouse),+ ("teams", teams_in_clickhouse),+ ("feature_flags", feature_flags_in_clickhouse),+ ]+ )+ def test_backfill_assets_are_hourly_partitioned(self, _name, backfill_asset):+ assert backfill_asset.partitions_def is not None+ assert backfill_asset.backfill_policy is not None+ assert backfill_asset.backfill_policy.max_partitions_per_run == 24++ @parameterized.expand(+ [+ (+ "organizations",+ organizations_in_clickhouse,+ "WHERE updated_at >= %s AND updated_at < %s",+ ),+ # Never-edited flags have NULL updated_at in Postgres; a plain-column window would skip them.+ (+ "feature_flags",+ feature_flags_in_clickhouse,+ "WHERE COALESCE(updated_at, created_at) >= %s AND COALESCE(updated_at, created_at) < %s",+ ),+ ]+ )+ def test_asset_window_query_filters_on_watermark_bounds(self, _name, backfill_asset, expected_where):+ mock_pg = MagicMock()+ cur = MagicMock()+ cur.fetchall.return_value = []+ mock_pg.cursor.return_value = cur- # Verify the query was for the correct time window- mock_cursor.execute.assert_called_once()- call_args = mock_cursor.execute.call_args[0]- query = call_args[0]- params = call_args[1]+ with (+ patch("posthog.dags.postgres_to_clickhouse_etl.get_postgres_connection", return_value=mock_pg),+ patch("posthog.dags.postgres_to_clickhouse_etl.create_clickhouse_tables"),+ ):+ ctx = build_asset_context(partition_key="2024-01-15-14:00")+ backfill_asset(ctx)- assert "WHERE updated_at >= %s AND updated_at < %s" in query+ sql, params = cur.execute.call_args[0]+ assert expected_where in sql+ assert params[0].replace(tzinfo=None).isoformat() == "2024-01-15T14:00:00"+ assert params[1].replace(tzinfo=None).isoformat() == "2024-01-15T15:00:00"- # Check the time window parameters- start_time, end_time = params- assert start_time == datetime(2024, 1, 15, 14, 0)- assert end_time == datetime(2024, 1, 15, 15, 0) # One hour later+ def test_backward_lookback_default_is_one_day(self):+ """Job-level lookback stays at 86400 as the fallback for orgs and teams; flags override on TableConfig."""+ assert _config().backward_lookback_seconds == 86400diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 99982e880fbb..9561ecbd23b9 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -17,7 +17,6 @@1 posthog/clickhouse/property_groups.py1 posthog/clickhouse/test/test_explain.py1 posthog/dags/common/resources.py-1 posthog/dags/postgres_to_clickhouse_etl.py1 posthog/dags/tests/test_events_backfill_to_duckling.py1 posthog/dags/tests/test_property_definitions.py1 posthog/errors.py