: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(ingestion): add dagster job to stop the shadow lane and report drift (#106931)
Nick Bestb327b0ebf5d6
diff --git a/posthog/dags/locations/ingestion.py b/posthog/dags/locations/ingestion.pyindex ee63abdd5b7c..deb2cf018228 100644--- a/posthog/dags/locations/ingestion.py+++ b/posthog/dags/locations/ingestion.py@@ -7,6 +7,7 @@ from posthog.dags import (ingestion_assets,person_property_reconciliation,persondistinctids_without_person_cleanup,+ personhog_shadow_drift,personhog_shadow_lane,persons_new_backfill,persons_without_distinct_ids_cleanup,@@ -24,6 +25,7 @@ defs = dagster.Definitions(distinct_id_usage.distinct_id_usage_monitoring,person_property_reconciliation.person_property_reconciliation_job,persondistinctids_without_person_cleanup.persondistinctids_without_person_cleanup_job,+ personhog_shadow_drift.personhog_shadow_lane_stop_and_compare_job,personhog_shadow_lane.personhog_shadow_lane_start_job,persons_new_backfill.persons_new_backfill_job,persons_without_distinct_ids_cleanup.persons_without_distinct_ids_cleanup_job,diff --git a/posthog/dags/personhog_shadow_drift.py b/posthog/dags/personhog_shadow_drift.pynew file mode 100644index 000000000000..b48fab3bb222--- /dev/null+++ b/posthog/dags/personhog_shadow_drift.py@@ -0,0 +1,398 @@+"""Stop the personhog shadow lane and measure drift between the two write paths.++The job scales the lane's consumers to zero, waits for every in-flight write+to land (the personhog writer keeps draining its changelog backlog after the+consumers stop), then compares the legacy tables against the personhog tmp+tables in the shadow persons database and reports drift per category.++It never resets the database: after the run an operator can connect directly+and inspect the exact rows behind every reported number. A fresh validation+run starts with personhog_shadow_lane_start_job and reset_state=true.+"""++import time+from collections.abc import Callable, Mapping+from contextlib import closing++import dagster+import psycopg2++from posthog.dags.common import JobOwners+from posthog.dags.personhog_shadow_lane import (+ SHADOW_CONSUMER_DEPLOYMENT,+ SHADOW_DB_URL_ENV_VAR,+ SHADOW_NAMESPACE,+ SHADOW_PROCESSOR_DEPLOYMENT,+ apps_api,+ deployment_pod_count,+ read_shadow_write_counter,+ scale_deployment,+ shadow_db_connection,+ wait_for_deployments,+ wait_for_quiescence,+)+from posthog.dataclasses import frozen+++@frozen+class DriftCategoryReport:+ category: str+ legacy_total: int+ personhog_total: int+ missing_in_personhog: int+ missing_in_legacy: int+ # Matched keys where at least one compared field differs. Field-level+ # counts overlap on a row, so this is counted separately in SQL.+ mismatched_rows: int+ field_mismatches: dict[str, int]+ samples: list[str]++ @property+ def compared_keys(self) -> int:+ # Legacy keys plus the keys only personhog has: the union of both sides.+ return self.legacy_total + self.missing_in_legacy++ @property+ def drifted_rows(self) -> int:+ return self.missing_in_personhog + self.missing_in_legacy + self.mismatched_rows++ @property+ def drift_pct(self) -> float:+ if self.compared_keys == 0:+ return 0.0+ return 100.0 * self.drifted_rows / self.compared_keys+++# Each category is a pair of queries over the same two CTEs: one aggregates+# the counts, the other lists sample rows. They share the CTE prefix and the+# mismatch condition so the samples always explain the counts.+#+# Both paths see the same deletions but record them differently: the legacy+# path deletes rows, personhog tombstones them with is_deleted. Every+# comparison filters is_deleted on both sides so a tombstone against a+# deleted row does not read as drift.+# The join hashes one whole side, so carrying properties through it costs+# memory proportional to the documents. jsonb text output is canonical+# (sorted keys, no duplicates, fixed whitespace), so hashing it shrinks+# each row to 32 bytes. This is stricter than jsonb equality: numeric+# formatting differences (1 vs 1.0) hash differently but compare equal+# as jsonb, so they count as drift here.+_PERSON_SIDES = """+WITH legacy AS (+ SELECT team_id, uuid, md5(properties::text) AS properties_hash, is_identified, created_at, version+ FROM posthog_person WHERE NOT is_deleted+), personhog AS (+ SELECT team_id, uuid, md5(properties::text) AS properties_hash, is_identified, created_at, version+ FROM personhog_person_tmp WHERE NOT is_deleted+)+"""++# version differences are reported per field but excluded from+# mismatched_rows: version counts how many writes a row took, so a benign+# difference in update batching shifts it without any end-state divergence.+_PERSON_ROW_DIFFERS = """(+ l.properties_hash IS DISTINCT FROM p.properties_hash+ OR l.is_identified IS DISTINCT FROM p.is_identified+ OR l.created_at IS DISTINCT FROM p.created_at)"""++_PERSON_DRIFT_SQL = f"""+{_PERSON_SIDES}+SELECT+ (SELECT count(*) FROM legacy) AS legacy_total,+ (SELECT count(*) FROM personhog) AS personhog_total,+ count(*) FILTER (WHERE p.uuid IS NULL) AS missing_in_personhog,+ count(*) FILTER (WHERE l.uuid IS NULL) AS missing_in_legacy,+ count(*) FILTER (WHERE l.uuid IS NOT NULL AND p.uuid IS NOT NULL+ AND l.properties_hash IS DISTINCT FROM p.properties_hash) AS properties,+ count(*) FILTER (WHERE l.uuid IS NOT NULL AND p.uuid IS NOT NULL+ AND l.is_identified IS DISTINCT FROM p.is_identified) AS is_identified,+ count(*) FILTER (WHERE l.uuid IS NOT NULL AND p.uuid IS NOT NULL+ AND l.created_at IS DISTINCT FROM p.created_at) AS created_at,+ count(*) FILTER (WHERE l.uuid IS NOT NULL AND p.uuid IS NOT NULL+ AND l.version IS DISTINCT FROM p.version) AS version,+ count(*) FILTER (WHERE l.uuid IS NOT NULL AND p.uuid IS NOT NULL+ AND {_PERSON_ROW_DIFFERS}) AS mismatched_rows+FROM legacy l+FULL OUTER JOIN personhog p USING (team_id, uuid)+"""++_PERSON_SAMPLE_SQL = f"""+{_PERSON_SIDES}+SELECT team_id, uuid,+ CASE WHEN p.uuid IS NULL THEN 'missing_in_personhog'+ WHEN l.uuid IS NULL THEN 'missing_in_legacy'+ ELSE 'field_mismatch' END AS drift+FROM legacy l+FULL OUTER JOIN personhog p USING (team_id, uuid)+WHERE p.uuid IS NULL OR l.uuid IS NULL OR {_PERSON_ROW_DIFFERS}+LIMIT %(limit)s+"""++_DISTINCT_ID_SIDES = """+WITH legacy AS (+ SELECT d.team_id, d.distinct_id, p.uuid AS person_uuid, d.version+ FROM posthog_persondistinctid d+ JOIN posthog_person p ON p.id = d.person_id AND p.team_id = d.team_id+ WHERE NOT d.is_deleted AND NOT p.is_deleted+), personhog AS (+ SELECT d.team_id, d.distinct_id, p.uuid AS person_uuid, d.version+ FROM personhog_persondistinctid_tmp d+ JOIN personhog_person_tmp p ON p.team_id = d.team_id AND p.id = d.person_id+ WHERE NOT d.is_deleted AND NOT p.is_deleted+)+"""++_DISTINCT_ID_DRIFT_SQL = f"""+{_DISTINCT_ID_SIDES}+SELECT+ (SELECT count(*) FROM legacy) AS legacy_total,+ (SELECT count(*) FROM personhog) AS personhog_total,+ count(*) FILTER (WHERE p.person_uuid IS NULL) AS missing_in_personhog,+ count(*) FILTER (WHERE l.person_uuid IS NULL) AS missing_in_legacy,+ count(*) FILTER (WHERE l.person_uuid IS NOT NULL AND p.person_uuid IS NOT NULL+ AND l.person_uuid <> p.person_uuid) AS mismatched_rows,+ count(*) FILTER (WHERE l.person_uuid IS NOT NULL AND p.person_uuid IS NOT NULL+ AND l.version IS DISTINCT FROM p.version) AS version+FROM legacy l+FULL OUTER JOIN personhog p USING (team_id, distinct_id)+"""++_DISTINCT_ID_SAMPLE_SQL = f"""+{_DISTINCT_ID_SIDES}+SELECT team_id, distinct_id, l.person_uuid AS legacy_person, p.person_uuid AS personhog_person,+ CASE WHEN p.person_uuid IS NULL THEN 'missing_in_personhog'+ WHEN l.person_uuid IS NULL THEN 'missing_in_legacy'+ ELSE 'person_mismatch' END AS drift+FROM legacy l+FULL OUTER JOIN personhog p USING (team_id, distinct_id)+WHERE p.person_uuid IS NULL OR l.person_uuid IS NULL OR l.person_uuid <> p.person_uuid+LIMIT %(limit)s+"""++_HASH_KEY_SIDES = """+WITH legacy AS (+ SELECT h.team_id, p.uuid AS person_uuid, h.feature_flag_key, h.hash_key+ FROM posthog_featureflaghashkeyoverride h+ JOIN posthog_person p ON p.id = h.person_id AND p.team_id = h.team_id+ WHERE NOT p.is_deleted+), personhog AS (+ SELECT h.team_id, p.uuid AS person_uuid, h.feature_flag_key, h.hash_key+ FROM personhog_featureflaghashkeyoverride_tmp h+ JOIN personhog_person_tmp p ON p.team_id = h.team_id AND p.id = h.person_id+ WHERE NOT p.is_deleted+)+"""++_HASH_KEY_DRIFT_SQL = f"""+{_HASH_KEY_SIDES}+SELECT+ (SELECT count(*) FROM legacy) AS legacy_total,+ (SELECT count(*) FROM personhog) AS personhog_total,+ count(*) FILTER (WHERE p.hash_key IS NULL) AS missing_in_personhog,+ count(*) FILTER (WHERE l.hash_key IS NULL) AS missing_in_legacy,+ count(*) FILTER (WHERE l.hash_key IS NOT NULL AND p.hash_key IS NOT NULL+ AND l.hash_key <> p.hash_key) AS mismatched_rows+FROM legacy l+FULL OUTER JOIN personhog p USING (team_id, person_uuid, feature_flag_key)+"""++_HASH_KEY_SAMPLE_SQL = f"""+{_HASH_KEY_SIDES}+SELECT team_id, person_uuid, feature_flag_key,+ CASE WHEN p.hash_key IS NULL THEN 'missing_in_personhog'+ WHEN l.hash_key IS NULL THEN 'missing_in_legacy'+ ELSE 'hash_key_mismatch' END AS drift+FROM legacy l+FULL OUTER JOIN personhog p USING (team_id, person_uuid, feature_flag_key)+WHERE p.hash_key IS NULL OR l.hash_key IS NULL OR l.hash_key <> p.hash_key+LIMIT %(limit)s+"""++# Columns every *_DRIFT_SQL returns. _run_category reports any other column+# as a per-field mismatch count, so a new summary column must be added here.+_TOTAL_COLUMNS = frozenset(+ {"legacy_total", "personhog_total", "missing_in_personhog", "missing_in_legacy", "mismatched_rows"}+)+++def _person_samples(row: Mapping[str, object]) -> str:+ return f"team={row['team_id']} uuid={row['uuid']} {row['drift']}"+++def _distinct_id_samples(row: Mapping[str, object]) -> str:+ return (+ f"team={row['team_id']} distinct_id={row['distinct_id']!r} "+ f"legacy_person={row['legacy_person']} personhog_person={row['personhog_person']} {row['drift']}"+ )+++def _hash_key_samples(row: Mapping[str, object]) -> str:+ return f"team={row['team_id']} person={row['person_uuid']} flag={row['feature_flag_key']} {row['drift']}"+++def _run_category(+ cursor: psycopg2.extensions.cursor,+ category: str,+ drift_sql: str,+ sample_sql: str,+ format_sample: Callable[[Mapping[str, object]], str],+ sample_size: int,+) -> DriftCategoryReport:+ cursor.execute(drift_sql)+ row = cursor.fetchone()+ totals = {key: int(row[key]) for key in _TOTAL_COLUMNS}+ field_mismatches = {key: int(value) for key, value in row.items() if key not in _TOTAL_COLUMNS}+ drifted = totals["missing_in_personhog"] + totals["missing_in_legacy"] + totals["mismatched_rows"]+ samples: list[str] = []+ # The sample query repeats the full join, so skip it when the counts already say it returns nothing.+ if sample_size > 0 and drifted > 0:+ cursor.execute(sample_sql, {"limit": sample_size})+ samples = [format_sample(sample) for sample in cursor.fetchall()]+ return DriftCategoryReport(category=category, field_mismatches=field_mismatches, samples=samples, **totals)+++def compute_shadow_drift(connection: psycopg2.extensions.connection, sample_size: int) -> list[DriftCategoryReport]:+ with connection.cursor() as cursor:+ cursor.execute("SET application_name = 'dagster_personhog_shadow_drift'")+ cursor.execute("SET statement_timeout = '30min'")+ # 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'")+ return [+ _run_category(cursor, "persons", _PERSON_DRIFT_SQL, _PERSON_SAMPLE_SQL, _person_samples, sample_size),+ _run_category(+ cursor,+ "distinct_ids",+ _DISTINCT_ID_DRIFT_SQL,+ _DISTINCT_ID_SAMPLE_SQL,+ _distinct_id_samples,+ sample_size,+ ),+ _run_category(+ cursor,+ "hash_key_overrides",+ _HASH_KEY_DRIFT_SQL,+ _HASH_KEY_SAMPLE_SQL,+ _hash_key_samples,+ sample_size,+ ),+ ]+++class ShadowLaneStopConfig(dagster.Config):+ namespace: str = SHADOW_NAMESPACE+ consumer_deployment: str = SHADOW_CONSUMER_DEPLOYMENT+ processor_deployment: str = SHADOW_PROCESSOR_DEPLOYMENT+ stop_timeout_seconds: int = 600+++class ShadowSettleConfig(dagster.Config):+ shadow_db_env_var: str = SHADOW_DB_URL_ENV_VAR+ poll_seconds: int = 30+ stable_checks: int = 4+ timeout_seconds: int = 3600+++class ShadowDriftConfig(dagster.Config):+ shadow_db_env_var: str = SHADOW_DB_URL_ENV_VAR+ sample_size: int = 10+++def stop_shadow_lane(context: dagster.OpExecutionContext, config: ShadowLaneStopConfig) -> None:+ apps = apps_api()+ deployments = [config.consumer_deployment, config.processor_deployment]+ for deployment in deployments:+ context.log.info(f"Scaling {config.namespace}/{deployment} to 0 replicas")+ scale_deployment(apps, config.namespace, deployment, 0)++ def is_stopped(deployment: str) -> bool:+ if deployment_pod_count(apps, config.namespace, deployment) > 0:+ return False+ context.log.info(f"{deployment} has no pods left")+ return True++ pending = wait_for_deployments(deployments, is_stopped, timeout_seconds=config.stop_timeout_seconds)+ if pending:+ raise dagster.Failure(+ description=f"Pods still running after {config.stop_timeout_seconds}s: {', '.join(sorted(pending))}"+ )++[email protected](ins={"lane_stopped": dagster.In(dagster.Nothing)})+def wait_for_shadow_settle(context: dagster.OpExecutionContext, config: ShadowSettleConfig) -> None:+ """Wait until nothing writes to the shadow persons database any more.++ The consumers are down, but the personhog writer keeps applying its+ changelog backlog. A quiet database cannot be told apart from a stalled+ writer here: if the writer crashed with backlog uncommitted, the counter+ also holds still. Identity creates the person row immediately with+ empty properties, and the writer fills them in later, so a stalled+ writer mostly shows as properties mismatches, not missing_in_personhog.+ Check the writer's health before trusting an unexpectedly large+ properties count.+ """+ with closing(shadow_db_connection(config.shadow_db_env_var)) as connection:+ connection.autocommit = True++ started = time.monotonic()+ try:+ polls = wait_for_quiescence(+ lambda: read_shadow_write_counter(connection),+ poll_seconds=config.poll_seconds,+ stable_checks=config.stable_checks,+ timeout_seconds=config.timeout_seconds,+ on_progress=context.log.info,+ )+ except TimeoutError as timeout:+ raise dagster.Failure(+ description=(+ f"The shadow persons database is still receiving writes after {config.timeout_seconds}s. "+ "The personhog writer may still be draining a large backlog, or something outside the lane "+ "is writing to this database. The consumers stay down; re-run this job to keep waiting."+ )+ ) from timeout++ waited = time.monotonic() - started+ context.log.info(f"Shadow persons database settled after {waited:.0f}s ({polls} polls)")+ context.add_output_metadata({"settle_seconds": dagster.MetadataValue.float(round(waited, 1))})++[email protected](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)++ header = "| category | legacy | personhog | missing in personhog | missing in legacy | mismatched | drift % |"+ separator = "|---|---|---|---|---|---|---|"+ lines = [header, separator]+ metadata: dict[str, dagster.MetadataValue] = {}+ for report in reports:+ lines.append(+ f"| {report.category} | {report.legacy_total} | {report.personhog_total} "+ f"| {report.missing_in_personhog} | {report.missing_in_legacy} "+ f"| {report.mismatched_rows} | {report.drift_pct:.4f} |"+ )+ metadata[f"{report.category}_drift_pct"] = dagster.MetadataValue.float(round(report.drift_pct, 4))+ context.log.info(+ f"[{report.category}] legacy={report.legacy_total} personhog={report.personhog_total} "+ f"missing_in_personhog={report.missing_in_personhog} missing_in_legacy={report.missing_in_legacy} "+ f"mismatched_rows={report.mismatched_rows} drift={report.drift_pct:.4f}% "+ f"field_mismatches={report.field_mismatches}"+ )+ for sample in report.samples:+ context.log.info(f"[{report.category}] drift sample: {sample}")++ metadata["summary"] = dagster.MetadataValue.md("\n".join(lines))+ context.add_output_metadata(metadata)++[email protected](tags={"owner": JobOwners.TEAM_INGESTION.value})+def personhog_shadow_lane_stop_and_compare_job() -> None:+ """Stop the shadow lane, wait for writes to drain, and report drift between the two paths.++ Leaves the shadow persons database untouched so the drift behind the+ report can be inspected over a direct connection afterwards.+ """+ report_shadow_drift(wait_for_shadow_settle(stop_shadow_lane()))diff --git a/posthog/dags/personhog_shadow_lane.py b/posthog/dags/personhog_shadow_lane.pyindex fe5a8f2f2e23..6b13bba79dd4 100644--- a/posthog/dags/personhog_shadow_lane.py+++ b/posthog/dags/personhog_shadow_lane.py@@ -20,7 +20,7 @@ these jobs apply. Both are charts-side prerequisites.import osimport time-from collections.abc import Callable+from collections.abc import Callable, Iterablefrom contextlib import closingfrom urllib.parse import parse_qs, urlparse@@ -55,14 +55,21 @@ LEGACY_STATE_TABLES = ["posthog_group","posthog_grouptypemapping",]-PERSONHOG_STATE_TABLES = [- "personhog_person_tmp",- "personhog_persondistinctid_tmp",- "personhog_featureflaghashkeyoverride_tmp",+# Saga bookkeeping the identity sweeper rewrites on every pass: it garbage-collects+# completed ops past retention and re-claims failing ones. Excluded from the drain+# counter because that activity never stops, and any saga step that changes person+# state also lands in the person, distinct id or override tables.+LIFECYCLE_OP_TABLES = ["lifecycle_op","lifecycle_op_person","lifecycle_op_tmp","lifecycle_op_person_tmp",+]+PERSONHOG_STATE_TABLES = [+ "personhog_person_tmp",+ "personhog_persondistinctid_tmp",+ "personhog_featureflaghashkeyoverride_tmp",+ *LIFECYCLE_OP_TABLES,"person_pg_cleanup_queue","person_tombstone_publish_queue",]@@ -170,6 +177,30 @@ def deployment_ready_replicas(apps: k8s_client.AppsV1Api, namespace: str, name:return deployment.status.ready_replicas or 0+def wait_for_deployments(+ deployments: Iterable[str],+ is_settled: Callable[[str], bool],+ *,+ timeout_seconds: float,+ poll_seconds: float = 10,+ sleep: Callable[[float], None] = time.sleep,+) -> set[str]:+ """Poll each deployment until is_settled accepts it or the deadline passes.++ Returns the deployments still pending at the deadline, so the caller+ decides how to report them.+ """+ deadline = time.monotonic() + timeout_seconds+ pending = set(deployments)+ while pending and time.monotonic() < deadline:+ for deployment in sorted(pending):+ if is_settled(deployment):+ pending.discard(deployment)+ if pending:+ sleep(poll_seconds)+ return pending++def wait_for_quiescence(read_write_counter: Callable[[], int],*,@@ -205,24 +236,20 @@ def wait_for_quiescence(def read_shadow_write_counter(connection: psycopg2.extensions.connection) -> int:- """Sum the whole database's tuple-write counters.+ """Sum the database's tuple-write counters, minus the sweeper's bookkeeping tables.The shadow database serves only the lane, so a stable sum means everywriter has drained; a table allowlist would silently go stale when the- lane gains a table. The connection must be in autocommit so each poll is- its own transaction and reads a fresh pg_stat snapshot instead of the- first transaction's cached one.+ lane gains a table. LIFECYCLE_OP_TABLES are the one exception, because+ the identity sweeper keeps them moving while the lane is stopped. The+ connection must be in autocommit so each poll is its own transaction and+ reads a fresh pg_stat snapshot instead of the first transaction's cached one."""with connection.cursor() as cursor:- # The identity service's lifecycle GC deletes completed lifecycle_op- # rows past retention on a timer, and it keeps running while the lane- # is scaled to zero. After a run longer than the retention window those- # deletes land every sweep, so counting them would never let the wait- # settle. They remove nothing the reset would otherwise keep.cursor.execute(- "SELECT COALESCE(SUM(n_tup_ins + n_tup_upd"- " + CASE WHEN relname LIKE 'lifecycle\\_op%' THEN 0 ELSE n_tup_del END), 0) AS writes"- " FROM pg_stat_user_tables"+ "SELECT COALESCE(SUM(n_tup_ins + n_tup_upd + n_tup_del), 0) AS writes "+ "FROM pg_stat_user_tables WHERE relname != ALL(%(excluded)s)",+ {"excluded": LIFECYCLE_OP_TABLES},)return int(cursor.fetchone()["writes"])@@ -313,21 +340,20 @@ def start_shadow_lane(context: dagster.OpExecutionContext, config: ShadowLaneStacontext.log.info(f"Scaling {config.namespace}/{deployment} to {replicas} replicas")scale_deployment(apps, config.namespace, deployment, replicas)- deadline = time.monotonic() + config.ready_timeout_seconds- pending = dict(targets)- while pending and time.monotonic() < deadline:- for deployment, replicas in list(pending.items()):- ready = deployment_ready_replicas(apps, config.namespace, deployment)- if ready >= replicas:- context.log.info(f"{deployment} is ready with {ready} replica(s)")- del pending[deployment]- if pending:- time.sleep(10)+ wanted = dict(targets)++ def is_ready(deployment: str) -> bool:+ ready = deployment_ready_replicas(apps, config.namespace, deployment)+ if ready < wanted[deployment]:+ return False+ context.log.info(f"{deployment} is ready with {ready} replica(s)")+ return True+ pending = wait_for_deployments(wanted, is_ready, timeout_seconds=config.ready_timeout_seconds)if pending:raise dagster.Failure(description=(- f"Deployments not ready after {config.ready_timeout_seconds}s: {', '.join(pending)}. "+ f"Deployments not ready after {config.ready_timeout_seconds}s: {', '.join(sorted(pending))}. ""The scale was applied; check the pods in the lane namespace."))diff --git a/posthog/dags/tests/test_personhog_shadow_drift.py b/posthog/dags/tests/test_personhog_shadow_drift.pynew file mode 100644index 000000000000..55d9584bf49e--- /dev/null+++ b/posthog/dags/tests/test_personhog_shadow_drift.py@@ -0,0 +1,103 @@+import uuid++import pytest++import psycopg2+import psycopg2.extras++from posthog.dags.personhog_shadow_drift import compute_shadow_drift+from posthog.persons_db import persons_db_url++TEAM_ID = 990000123+CREATED_AT = "2026-01-01T00:00:00+00:00"+++def _insert_person(+ cursor, table: str, person_uuid: uuid.UUID, properties: dict, is_deleted: bool = False, version: int = 1+) -> int:+ cursor.execute(+ f"INSERT INTO {table} (created_at, properties, is_identified, uuid, version, team_id, is_deleted) "+ "VALUES (%s, %s, false, %s, %s, %s, %s) RETURNING id",+ (CREATED_AT, psycopg2.extras.Json(properties), str(person_uuid), version, TEAM_ID, is_deleted),+ )+ return cursor.fetchone()["id"]++[email protected]_db_direct[email protected]_db(transaction=True)+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+ matched = uuid.uuid4()+ legacy_only = uuid.uuid4()+ personhog_only = uuid.uuid4()+ props_differ = uuid.uuid4()+ tombstoned = uuid.uuid4()++ try:+ with connection.cursor() as cursor:+ legacy_matched = _insert_person(cursor, "posthog_person", matched, {"a": 1})+ _insert_person(cursor, "posthog_person", legacy_only, {})+ _insert_person(cursor, "posthog_person", props_differ, {"b": 1})++ ph_matched = _insert_person(cursor, "personhog_person_tmp", matched, {"a": 1}, version=2)+ _insert_person(cursor, "personhog_person_tmp", personhog_only, {})+ ph_props = _insert_person(cursor, "personhog_person_tmp", props_differ, {"b": 2})+ ph_tombstoned = _insert_person(cursor, "personhog_person_tmp", tombstoned, {}, is_deleted=True)++ cursor.execute(+ "INSERT INTO posthog_persondistinctid (distinct_id, version, person_id, team_id) VALUES "+ "('shadow-drift-did-1', 1, %s, %s), ('shadow-drift-did-2', 1, %s, %s)",+ (legacy_matched, TEAM_ID, legacy_matched, TEAM_ID),+ )+ cursor.execute(+ "INSERT INTO personhog_persondistinctid_tmp (distinct_id, version, person_id, team_id) VALUES "+ "('shadow-drift-did-1', 1, %s, %s), ('shadow-drift-did-2', 1, %s, %s), "+ "('shadow-drift-did-3', 1, %s, %s)",+ (ph_matched, TEAM_ID, ph_props, TEAM_ID, ph_tombstoned, TEAM_ID),+ )++ cursor.execute(+ "INSERT INTO posthog_featureflaghashkeyoverride (feature_flag_key, hash_key, person_id, team_id) "+ "VALUES ('flag-1', 'hash-same', %s, %s), ('flag-2', 'hash-legacy', %s, %s)",+ (legacy_matched, TEAM_ID, legacy_matched, TEAM_ID),+ )+ cursor.execute(+ "INSERT INTO personhog_featureflaghashkeyoverride_tmp (feature_flag_key, hash_key, person_id, team_id) "+ "VALUES ('flag-1', 'hash-same', %s, %s), ('flag-2', 'hash-personhog', %s, %s), "+ "('flag-3', 'hash-tombstoned', %s, %s)",+ (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)}+ finally:+ connection.close()++ 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)+ assert persons.field_mismatches == {"properties": 1, "is_identified": 0, "created_at": 0, "version": 1}+ assert persons.drift_pct == 75.0+ assert sorted(sample.rsplit(" ", 1)[1] for sample in persons.samples) == [+ "field_mismatch",+ "missing_in_legacy",+ "missing_in_personhog",+ ]++ distinct_ids = reports["distinct_ids"]+ assert (distinct_ids.legacy_total, distinct_ids.personhog_total) == (2, 2)+ assert (distinct_ids.missing_in_personhog, distinct_ids.missing_in_legacy, distinct_ids.mismatched_rows) == (+ 0,+ 0,+ 1,+ )+ assert distinct_ids.field_mismatches == {"version": 0}+ assert distinct_ids.samples == [+ f"team={TEAM_ID} distinct_id='shadow-drift-did-2' "+ f"legacy_person={matched} personhog_person={props_differ} person_mismatch"+ ]++ hash_keys = reports["hash_key_overrides"]+ assert (hash_keys.legacy_total, hash_keys.personhog_total) == (2, 2)+ assert (hash_keys.missing_in_personhog, hash_keys.missing_in_legacy, hash_keys.mismatched_rows) == (0, 0, 1)+ assert hash_keys.samples == [f"team={TEAM_ID} person={matched} flag=flag-2 hash_key_mismatch"]diff --git a/posthog/dags/tests/test_personhog_shadow_lane.py b/posthog/dags/tests/test_personhog_shadow_lane.pyindex 0a2461378e66..2061695a6a27 100644--- a/posthog/dags/tests/test_personhog_shadow_lane.py+++ b/posthog/dags/tests/test_personhog_shadow_lane.py@@ -1,16 +1,22 @@+import uuidfrom types import SimpleNamespaceimport pytestimport dagster+import psycopg2+import psycopg2.extrasfrom parameterized import parameterizedfrom posthog.dags.personhog_shadow_lane import (ShadowLaneStartConfig,_reset_shadow_state,+ read_shadow_write_counter,require_shadow_dsn,+ wait_for_deployments,wait_for_quiescence,)+from posthog.persons_db import persons_db_urlclass TestRequireShadowDsn:@@ -78,6 +84,28 @@ class TestWaitForQuiescence:)+class TestWaitForDeployments:+ @parameterized.expand(+ [+ ("all_settle", {"consumer": 2, "processor": 1}, 60, set()),+ ("deadline_passed", {"consumer": 0, "processor": 0}, 0, {"consumer", "processor"}),+ ]+ )+ def test_returns_what_is_still_pending(+ self, _name: str, settles_on_check: dict[str, int], timeout_seconds: int, expected_pending: set[str]+ ) -> None:+ checks: dict[str, int] = dict.fromkeys(settles_on_check, 0)++ def is_settled(deployment: str) -> bool:+ checks[deployment] += 1+ return 0 < settles_on_check[deployment] <= checks[deployment]++ pending = wait_for_deployments(+ settles_on_check, is_settled, timeout_seconds=timeout_seconds, sleep=lambda _seconds: None+ )+ assert pending == expected_pending++class _FakeAppsApi:def __init__(self, desired_replicas: int) -> None:self.desired_replicas = desired_replicas@@ -90,3 +118,37 @@ def test_reset_refuses_while_lane_wants_pods() -> None:context = dagster.build_op_context()with pytest.raises(dagster.Failure, match="stop-and-compare"):_reset_shadow_state(context, ShadowLaneStartConfig(reset_state=True), _FakeAppsApi(desired_replicas=2))++[email protected]_db_direct[email protected]_db(transaction=True)+def test_write_counter_ignores_lifecycle_op_tables() -> None:+ connection = psycopg2.connect(persons_db_url(writer=True), cursor_factory=psycopg2.extras.RealDictCursor)+ connection.autocommit = True+ op_id = str(uuid.uuid4())+ person_uuid = str(uuid.uuid4())+ try:+ before = read_shadow_write_counter(connection)++ with connection.cursor() as cursor:+ cursor.execute(+ "INSERT INTO lifecycle_op_tmp (op_id, op_type, team_id, step, request) "+ "VALUES (%s, 'merge', 2, 'start', '{}')",+ (op_id,),+ )+ cursor.execute("DELETE FROM lifecycle_op_tmp WHERE op_id = %s", (op_id,))+ cursor.execute("SELECT pg_stat_force_next_flush()")+ assert read_shadow_write_counter(connection) == before++ with connection.cursor() as cursor:+ cursor.execute(+ "INSERT INTO posthog_person (created_at, properties, is_identified, uuid, version, team_id, is_deleted) "+ "VALUES (now(), '{}', false, %s, 1, 2, false)",+ (person_uuid,),+ )+ cursor.execute("SELECT pg_stat_force_next_flush()")+ assert read_shadow_write_counter(connection) == before + 1+ finally:+ with connection.cursor() as cursor:+ cursor.execute("DELETE FROM posthog_person WHERE uuid = %s", (person_uuid,))+ connection.close()