: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(dags): reset the shadow lane's offsets and lift its replica cap (#114176)
Zach Brown736d99ec7741
diff --git a/posthog/dags/personhog_shadow_drift.py b/posthog/dags/personhog_shadow_drift.pyindex c3da64ec545c..5f41f9943476 100644--- a/posthog/dags/personhog_shadow_drift.py+++ b/posthog/dags/personhog_shadow_drift.py@@ -19,6 +19,7 @@ from typing import Literalimport dagsterimport psycopg2from prometheus_client import CollectorRegistry, Gauge+from pydantic import Fieldfrom posthog.dags.common import JobOwnersfrom posthog.dags.personhog_shadow_lane import (@@ -323,18 +324,20 @@ def _run_category(return DriftCategoryReport(category=category, field_mismatches=field_mismatches, samples=samples, **totals)-def _configure_session(cursor: psycopg2.extensions.cursor) -> None:+def _configure_session(cursor: psycopg2.extensions.cursor, statement_timeout_minutes: int) -> None:cursor.execute("SET application_name = 'dagster_personhog_shadow_drift'")- cursor.execute("SET statement_timeout = '30min'")+ cursor.execute("SET statement_timeout = %s", (f"{statement_timeout_minutes}min",))# work_mem applies per hash node and per parallel worker, and hash joins# get hash_mem_multiplier times it, so a three-join query can reserve# many times this value at once.cursor.execute("SET work_mem = '256MB'")-def compute_shadow_drift(connection: psycopg2.extensions.connection, sample_size: int) -> list[DriftCategoryReport]:+def compute_shadow_drift(+ connection: psycopg2.extensions.connection, sample_size: int, statement_timeout_minutes: int = 30+) -> list[DriftCategoryReport]:with connection.cursor() as cursor:- _configure_session(cursor)+ _configure_session(cursor, statement_timeout_minutes)return [_run_category(cursor, "persons", _PERSON_DRIFT_SQL, _PERSON_SAMPLE_SQL, _person_samples, sample_size),_run_category(@@ -375,11 +378,14 @@ def _format_person_property_detail(team_id: object, person_uuid: object, rows: ldef sample_property_drift(- connection: psycopg2.extensions.connection, persons_limit: int, detail_limit: int+ connection: psycopg2.extensions.connection,+ persons_limit: int,+ detail_limit: int,+ statement_timeout_minutes: int = 30,) -> PropertyDriftSample:detail_rows: list[Mapping[str, object]] = []with connection.cursor() as cursor:- _configure_session(cursor)+ _configure_session(cursor, statement_timeout_minutes)cursor.execute(_PROPERTY_KEY_DRIFT_SQL, {"limit": persons_limit})key_rows = cursor.fetchall()if detail_limit > 0:@@ -478,6 +484,7 @@ class ShadowDriftConfig(dagster.Config):shadow_db_env_var: str = SHADOW_DB_URL_ENV_VARsample_size: int = 10property_diff_sample_size: int = 500+ statement_timeout_minutes: int = Field(default=30, gt=0)@dagster.op@@ -545,12 +552,15 @@ def wait_for_shadow_settle(context: dagster.OpExecutionContext, config: ShadowSe@dagster.op(ins={"settled": dagster.In(dagster.Nothing)})def report_shadow_drift(context: dagster.OpExecutionContext, config: ShadowDriftConfig) -> None:with closing(shadow_db_connection(config.shadow_db_env_var)) as connection:- reports = compute_shadow_drift(connection, config.sample_size)+ reports = compute_shadow_drift(connection, config.sample_size, config.statement_timeout_minutes)persons_report = next(report for report in reports if report.category == "persons")property_drift: PropertyDriftSample | None = Noneif config.property_diff_sample_size > 0 and persons_report.field_mismatches.get("properties", 0) > 0:property_drift = sample_property_drift(- connection, persons_limit=config.property_diff_sample_size, detail_limit=config.sample_size+ connection,+ persons_limit=config.property_diff_sample_size,+ detail_limit=config.sample_size,+ statement_timeout_minutes=config.statement_timeout_minutes,)with pushed_metrics_registry(f"{DRIFT_METRICS_JOB}_{config.shadow_db_env_var}") as registry:diff --git a/posthog/dags/personhog_shadow_lane.py b/posthog/dags/personhog_shadow_lane.pyindex a1420394e748..411466cb4bda 100644--- a/posthog/dags/personhog_shadow_lane.py+++ b/posthog/dags/personhog_shadow_lane.py@@ -1,9 +1,9 @@"""Operate the personhog shadow validation lane.-The shadow lane is a second consumer group on the team 2 events topic whose-worker runs with PERSONS_STORE_MODE=shadow: every person write goes through-both the legacy direct-to-Postgres path and the personhog path, into a-dedicated persons-shadow database. Validation runs compare the two paths'+The shadow lane is a second consumer group on a production ingestion topic,+set in the lane's deployment, whose worker runs with PERSONS_STORE_MODE=shadow:+every person write goes through both the legacy direct-to-Postgres path and+the personhog path, into a dedicated persons-shadow database. Validation runs compare the two paths'tables afterwards, so each run must start from identical (empty) state onboth sides.@@ -15,18 +15,24 @@ The Dagster service account needs get/patch on deployments anddeployments/scale plus list on pods in the lane namespace, and the lane'sArgoCD Applicationsmust ignore Deployment spec.replicas, or ArgoCD self-heal reverts every scale-these jobs apply. Both are charts-side prerequisites.+these jobs apply. Both are charts-side prerequisites. Resetting the lane's+offsets also needs the Kafka bootstrap servers of the lane's cluster in+PERSONHOG_SHADOW_KAFKA_BOOTSTRAP_SERVERS on the Dagster deployment."""import osimport timefrom collections.abc import Callable, Iterable+from concurrent.futures import Futurefrom contextlib import closing+from typing import Any, Protocolfrom urllib.parse import parse_qs, urlparseimport dagsterimport psycopg2import psycopg2.extras+from confluent_kafka import KafkaError, KafkaException+from confluent_kafka.admin import AdminClientfrom kubernetes import (client as k8s_client,config as k8s_config,@@ -41,6 +47,12 @@ SHADOW_NAMESPACE = "ingestion-analytics-team2-shadow"SHADOW_CONSUMER_DEPLOYMENT = "ingestion-analytics-team2-shadow-consumer"SHADOW_PROCESSOR_DEPLOYMENT = "ingestion-analytics-team2-shadow-processor"SHADOW_DB_URL_ENV_VAR = "PERSONS_SHADOW_DB_URL"+SHADOW_CONSUMER_GROUP = "ingestion-analytics-team2-shadow"+SHADOW_KAFKA_BOOTSTRAP_ENV_VAR = "PERSONHOG_SHADOW_KAFKA_BOOTSTRAP_SERVERS"+SHADOW_KAFKA_SECURITY_PROTOCOL_ENV_VAR = "PERSONHOG_SHADOW_KAFKA_SECURITY_PROTOCOL"+# The client library defines these error codes at runtime, but its type stubs omit them.+GROUP_ID_NOT_FOUND: int = KafkaError.GROUP_ID_NOT_FOUND # type: ignore[attr-defined]+NON_EMPTY_GROUP: int = KafkaError.NON_EMPTY_GROUP # type: ignore[attr-defined]START_METRICS_JOB = "personhog_shadow_lane_start"@@ -260,10 +272,10 @@ def read_shadow_write_counter(connection: psycopg2.extensions.connection) -> intclass ShadowLaneStartConfig(dagster.Config):reset_state: bool = False- # Bounded so a typo in run config cannot request enough pods to eat the- # nodepool. The team2 lane peaks at 16 of each.- consumer_replicas: int = Field(default=4, gt=0, le=32)- processor_replicas: int = Field(default=8, gt=0, le=32)+ # Deletes the lane's consumer group, so the lane starts at the end of its topic instead of its committed offsets.+ reset_offsets: bool = False+ consumer_replicas: int = Field(default=4, gt=0, le=512)+ processor_replicas: int = Field(default=8, gt=0, le=512)namespace: str = SHADOW_NAMESPACEconsumer_deployment: str = SHADOW_CONSUMER_DEPLOYMENTprocessor_deployment: str = SHADOW_PROCESSOR_DEPLOYMENT@@ -275,20 +287,26 @@ class ShadowLaneStartConfig(dagster.Config):reset_settle_timeout_seconds: int = 600-def _reset_shadow_state(- context: dagster.OpExecutionContext, config: ShadowLaneStartConfig, apps: k8s_client.AppsV1Api-) -> None:+def _require_lane_stopped(config: ShadowLaneStartConfig, apps: k8s_client.AppsV1Api, option: str, reason: str) -> None:for deployment in (config.consumer_deployment, config.processor_deployment):pods = deployment_pod_count(apps, config.namespace, deployment)if pods > 0:raise dagster.Failure(description=(f"Deployment {deployment} still wants or has {pods} pod(s). "- "A reset while consumers run would leave the two paths inconsistent. "- "Run the stop-and-compare job first, then start with reset_state."+ f"{reason} "+ f"Run the stop-and-compare job first, then start with {option}."))++def _reset_shadow_state(+ context: dagster.OpExecutionContext, config: ShadowLaneStartConfig, apps: k8s_client.AppsV1Api+) -> None:+ _require_lane_stopped(+ config, apps, "reset_state", "A reset while consumers run would leave the two paths inconsistent."+ )+tables = LEGACY_STATE_TABLES + PERSONHOG_STATE_TABLESwith closing(shadow_db_connection(config.shadow_db_env_var)) as connection:connection.autocommit = True@@ -328,6 +346,62 @@ def _reset_shadow_state(context.log.info("Shadow persons database reset complete")+class ConsumerGroupAdmin(Protocol):+ def delete_consumer_groups(self, group_ids: list[str], **kwargs: Any) -> dict[str, Future]: ...+++def shadow_kafka_admin() -> AdminClient:+ bootstrap_servers = os.environ.get(SHADOW_KAFKA_BOOTSTRAP_ENV_VAR)+ if not bootstrap_servers:+ raise dagster.Failure(+ description=(+ f"Environment variable {SHADOW_KAFKA_BOOTSTRAP_ENV_VAR} is not set on the Dagster deployment. "+ "It must hold the bootstrap servers of the Kafka cluster the shadow lane consumes from."+ )+ )+ return AdminClient(+ {+ "bootstrap.servers": bootstrap_servers,+ "security.protocol": os.environ.get(SHADOW_KAFKA_SECURITY_PROTOCOL_ENV_VAR, "SSL"),+ # The wheel's bundled OpenSSL does not read the system CA store unless told to probe for it.+ "ssl.ca.location": "probe",+ }+ )+++def _reset_consumer_offsets(+ context: dagster.OpExecutionContext,+ config: ShadowLaneStartConfig,+ apps: k8s_client.AppsV1Api,+ admin_factory: Callable[[], ConsumerGroupAdmin] = shadow_kafka_admin,+) -> bool:+ """Delete the lane's consumer group, so the next start falls back to the consumer's offset reset policy.++ The ingestion consumer resets to the latest offset when its group has no committed offset, so the lane+ starts at the end of its topic. Returns False when the group did not exist.+ """+ _require_lane_stopped(config, apps, "reset_offsets", "Kafka refuses to delete a consumer group with members.")+ admin = admin_factory()+ future = admin.delete_consumer_groups([SHADOW_CONSUMER_GROUP], request_timeout=30)[SHADOW_CONSUMER_GROUP]+ try:+ future.result()+ except KafkaException as exception:+ error = exception.args[0]+ if error.code() == GROUP_ID_NOT_FOUND:+ context.log.info(f"Consumer group {SHADOW_CONSUMER_GROUP} does not exist, nothing to reset")+ return False+ if error.code() == NON_EMPTY_GROUP:+ raise dagster.Failure(+ description=(+ f"Consumer group {SHADOW_CONSUMER_GROUP} still has members, so Kafka refused to delete it. "+ "Wait for the lane's consumers to leave the group, then retry."+ )+ ) from exception+ raise+ context.log.info(f"Deleted consumer group {SHADOW_CONSUMER_GROUP}; the lane starts from the latest offsets")+ return True++def record_start_gauges(registry: CollectorRegistry, config: ShadowLaneStartConfig, completed_at: float) -> None:Gauge("posthog_personhog_shadow_lane_start_last_success_timestamp_seconds",@@ -341,6 +415,12 @@ def record_start_gauges(registry: CollectorRegistry, config: ShadowLaneStartConf["namespace"],registry=registry,).labels(namespace=config.namespace).set(1 if config.reset_state else 0)+ Gauge(+ "posthog_personhog_shadow_lane_start_reset_offsets",+ "1 when the last start deleted the lane's consumer group first, 0 when it resumed from committed offsets",+ ["namespace"],+ registry=registry,+ ).labels(namespace=config.namespace).set(1 if config.reset_offsets else 0)replicas = Gauge("posthog_personhog_shadow_lane_start_replicas","Replicas the last start requested, by deployment",@@ -358,6 +438,10 @@ def start_shadow_lane(context: dagster.OpExecutionContext, config: ShadowLaneSta_reset_shadow_state(context, config, apps)else:context.log.info("reset_state is false, leaving the shadow persons database untouched")+ if config.reset_offsets:+ _reset_consumer_offsets(context, config, apps)+ else:+ context.log.info("reset_offsets is false, the lane resumes from its committed offsets")targets = [(config.consumer_deployment, config.consumer_replicas),@@ -391,6 +475,7 @@ def start_shadow_lane(context: dagster.OpExecutionContext, config: ShadowLaneStacontext.add_output_metadata({"reset_state": dagster.MetadataValue.bool(config.reset_state),+ "reset_offsets": dagster.MetadataValue.bool(config.reset_offsets),"consumer_replicas": dagster.MetadataValue.int(config.consumer_replicas),"processor_replicas": dagster.MetadataValue.int(config.processor_replicas),}@@ -404,6 +489,7 @@ def personhog_shadow_lane_start_job():Run with default config to resume consuming from the committed offsets.Set ops.start_shadow_lane.config.reset_state to true to truncate bothpaths' tables before starting, which every fresh validation run needs.- The reset refuses to run while the lane has pods.+ Set reset_offsets to true to start from the end of the topic instead.+ Both resets refuse to run while the lane has pods."""start_shadow_lane()diff --git a/posthog/dags/tests/test_personhog_shadow_drift.py b/posthog/dags/tests/test_personhog_shadow_drift.pyindex 4df368eb7739..bcb54f3a1411 100644--- a/posthog/dags/tests/test_personhog_shadow_drift.py+++ b/posthog/dags/tests/test_personhog_shadow_drift.py@@ -32,6 +32,12 @@ def _insert_person(@pytest.mark.persons_db_direct@pytest.mark.django_db(transaction=True)+def _session_statement_timeout(connection: psycopg2.extensions.connection) -> str:+ with connection.cursor() as cursor:+ cursor.execute("SHOW statement_timeout")+ return cursor.fetchone()["statement_timeout"]++def test_compute_shadow_drift_counts_each_category() -> None:connection = psycopg2.connect(persons_db_url(writer=True), cursor_factory=psycopg2.extras.RealDictCursor)connection.autocommit = True@@ -78,11 +84,20 @@ def test_compute_shadow_drift_counts_each_category() -> None:(ph_matched, TEAM_ID, ph_matched, TEAM_ID, ph_tombstoned, TEAM_ID),)- reports = {report.category: report for report in compute_shadow_drift(connection, sample_size=10)}- property_drift = sample_property_drift(connection, persons_limit=500, detail_limit=10)+ reports = {+ report.category: report+ for report in compute_shadow_drift(connection, sample_size=10, statement_timeout_minutes=239)+ }+ compute_timeout = _session_statement_timeout(connection)+ property_drift = sample_property_drift(+ connection, persons_limit=500, detail_limit=10, statement_timeout_minutes=241+ )+ sample_timeout = _session_statement_timeout(connection)finally:connection.close()+ assert (compute_timeout, sample_timeout) == ("239min", "241min")+persons = reports["persons"]assert (persons.legacy_total, persons.personhog_total) == (3, 3)assert (persons.missing_in_personhog, persons.missing_in_legacy, persons.mismatched_rows) == (1, 1, 1)diff --git a/posthog/dags/tests/test_personhog_shadow_lane.py b/posthog/dags/tests/test_personhog_shadow_lane.pyindex 2061695a6a27..f04349bb18c8 100644--- a/posthog/dags/tests/test_personhog_shadow_lane.py+++ b/posthog/dags/tests/test_personhog_shadow_lane.py@@ -1,4 +1,6 @@import uuid+from collections.abc import Callable+from concurrent.futures import Futurefrom types import SimpleNamespaceimport pytest@@ -6,13 +8,20 @@ import pytestimport dagsterimport psycopg2import psycopg2.extras+from confluent_kafka import KafkaError, KafkaExceptionfrom parameterized import parameterizedfrom posthog.dags.personhog_shadow_lane import (+ GROUP_ID_NOT_FOUND,+ NON_EMPTY_GROUP,+ SHADOW_CONSUMER_GROUP,+ SHADOW_KAFKA_BOOTSTRAP_ENV_VAR,ShadowLaneStartConfig,+ _reset_consumer_offsets,_reset_shadow_state,read_shadow_write_counter,require_shadow_dsn,+ shadow_kafka_admin,wait_for_deployments,wait_for_quiescence,)@@ -111,13 +120,94 @@ class _FakeAppsApi:self.desired_replicas = desired_replicasdef read_namespaced_deployment(self, name: str, namespace: str) -> SimpleNamespace:- return SimpleNamespace(spec=SimpleNamespace(replicas=self.desired_replicas))+ return SimpleNamespace(+ spec=SimpleNamespace(replicas=self.desired_replicas, selector=SimpleNamespace(match_labels={"app": name}))+ )+++class _NoPodsCoreApi:+ def list_namespaced_pod(self, namespace: str, label_selector: str) -> SimpleNamespace:+ return SimpleNamespace(items=[])+++def stopped_lane(monkeypatch: pytest.MonkeyPatch) -> _FakeAppsApi:+ monkeypatch.setattr("posthog.dags.personhog_shadow_lane.k8s_client.CoreV1Api", _NoPodsCoreApi)+ return _FakeAppsApi(desired_replicas=0)+++class _FakeKafkaAdmin:+ def __init__(self, error_code: int | None = None) -> None:+ self.error_code = error_code+ self.deleted: list[str] = []++ def delete_consumer_groups(self, group_ids: list[str], **_kwargs: object) -> dict[str, Future]:+ futures: dict[str, Future] = {}+ for group_id in group_ids:+ future: Future = Future()+ if self.error_code is None:+ self.deleted.append(group_id)+ future.set_result(None)+ else:+ future.set_exception(KafkaException(KafkaError(self.error_code)))+ futures[group_id] = future+ return futures++def _no_admin() -> _FakeKafkaAdmin:+ raise AssertionError("the admin client must not be reached while the lane has pods")-def test_reset_refuses_while_lane_wants_pods() -> None:- context = dagster.build_op_context()++ [+ (+ "reset_state",+ lambda context, apps: _reset_shadow_state(context, ShadowLaneStartConfig(reset_state=True), apps),+ ),+ (+ "reset_offsets",+ lambda context, apps: _reset_consumer_offsets(+ context, ShadowLaneStartConfig(reset_offsets=True), apps, _no_admin+ ),+ ),+ ]+)+def test_reset_refuses_while_lane_wants_pods(+ _name: str, reset: Callable[[dagster.OpExecutionContext, _FakeAppsApi], object]+) -> None:with pytest.raises(dagster.Failure, match="stop-and-compare"):- _reset_shadow_state(context, ShadowLaneStartConfig(reset_state=True), _FakeAppsApi(desired_replicas=2))+ reset(dagster.build_op_context(), _FakeAppsApi(desired_replicas=2))+++ "error_code,expected",+ [+ pytest.param(None, True, id="deleted"),+ pytest.param(GROUP_ID_NOT_FOUND, False, id="missing_group"),+ ],+)+def test_offset_reset_deletes_the_consumer_group(+ stopped_lane: _FakeAppsApi, error_code: int | None, expected: bool+) -> None:+ admin = _FakeKafkaAdmin(error_code)+ config = ShadowLaneStartConfig(reset_offsets=True)+ deleted = _reset_consumer_offsets(dagster.build_op_context(), config, stopped_lane, lambda: admin)+ assert deleted == expected+ assert admin.deleted == ([SHADOW_CONSUMER_GROUP] if expected else [])+++def test_offset_reset_fails_while_the_group_has_members(stopped_lane: _FakeAppsApi) -> None:+ admin = _FakeKafkaAdmin(NON_EMPTY_GROUP)+ with pytest.raises(dagster.Failure, match="still has members"):+ _reset_consumer_offsets(+ dagster.build_op_context(), ShadowLaneStartConfig(reset_offsets=True), stopped_lane, lambda: admin+ )+++def test_offset_reset_needs_the_bootstrap_servers(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv(SHADOW_KAFKA_BOOTSTRAP_ENV_VAR, raising=False)+ with pytest.raises(dagster.Failure, match=SHADOW_KAFKA_BOOTSTRAP_ENV_VAR):+ shadow_kafka_admin()@pytest.mark.persons_db_direct