: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(personhog): add lifecycle saga tables and is_deleted columns (#74124)
José Sequeira97d3086f21bd
diff --git a/posthog/models/person/person.py b/posthog/models/person/person.pyindex ab7e98fb3f66..5a164a9ac780 100644--- a/posthog/models/person/person.py+++ b/posthog/models/person/person.py@@ -193,6 +193,10 @@ class Person(models.Model):# Updated by ingestion pipeline when processing eventslast_seen_at = models.DateTimeField(null=True, blank=True)+ # Soft-delete tombstone: deleted persons keep their row (version bumped,+ # properties cleared) so re-created keys revive above the ClickHouse tombstone+ is_deleted = models.BooleanField(default=False, db_default=False)+# Has an index on properties -> email from migration 0121, (team_id, id DESC) from migration 0164objects = PersonManager()@@ -435,6 +439,10 @@ class PersonDistinctId(models.Model):# current version of the id, used to sync with ClickHouse and collapse rows correctly for new clickhouse tableversion = models.BigIntegerField(null=True, blank=True)+ # Soft-delete tombstone: kept so a re-created distinct id conflicts with its+ # tombstone and takes the revival path instead of restarting at version 0+ is_deleted = models.BooleanField(default=False, db_default=False)+class Meta:# migrations managed via rust/persons_migrationsmanaged = Falsediff --git a/rust/persons_migrations/20260727000001_add_lifecycle_op_tables.sql b/rust/persons_migrations/20260727000001_add_lifecycle_op_tables.sqlnew file mode 100644index 000000000000..594792ee3896--- /dev/null+++ b/rust/persons_migrations/20260727000001_add_lifecycle_op_tables.sql@@ -0,0 +1,56 @@+-- Lifecycle-manager saga state tables.+--+-- Every person-destroying operation (merge, delete) runs as a durable saga:+-- one lifecycle_op row per operation (current step, lease, frozen request,+-- recorded outcome) and one lifecycle_op_person row per person the operation+-- touches (the claim, plus everything captured about the person before it is+-- destroyed). Living on the same primary as the person rows lets each PG step+-- commit its work and its step advance in one transaction.+--+-- SAFE: creates new empty tables and indexes only; takes no locks on+-- existing tables. This migration is idempotent and safe to re-run.++CREATE TABLE IF NOT EXISTS lifecycle_op (+ op_id UUID PRIMARY KEY, -- caller-supplied (event uuid / GDPR job id)+ op_type TEXT NOT NULL CHECK (op_type IN ('merge', 'delete')),+ team_id INTEGER NOT NULL,+ step TEXT NOT NULL,+ attempt INTEGER NOT NULL DEFAULT 0, -- sweeper takeovers; alert above a threshold+ lease_expires_at TIMESTAMP WITH TIME ZONE, -- the expiry is the lock; owner identity goes to logs+ request JSONB NOT NULL, -- frozen caller request+ outcome JSONB, -- per-person outcomes; the recorded answer for op_id retries+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),+ completed_at TIMESTAMP WITH TIME ZONE+);++-- Sweeper scan: incomplete ops whose lease has expired.+CREATE INDEX IF NOT EXISTS lifecycle_op_sweep ON lifecycle_op (lease_expires_at)+ WHERE completed_at IS NULL;++-- Garbage collection: completed ops past retention.+CREATE INDEX IF NOT EXISTS lifecycle_op_gc ON lifecycle_op (completed_at)+ WHERE completed_at IS NOT NULL;++CREATE TABLE IF NOT EXISTS lifecycle_op_person (+ op_id UUID NOT NULL REFERENCES lifecycle_op (op_id) ON DELETE CASCADE,+ team_id INTEGER NOT NULL,+ person_id BIGINT NOT NULL,+ person_uuid UUID NOT NULL,+ role TEXT NOT NULL, -- target | source (merge) | victim (delete)+ ordinal INTEGER, -- pair order: property precedence (merge sources only)+ status TEXT NOT NULL, -- marked | sealed | deleted | cleared (target)+ -- | skipped_conflict | skipped_identified+ -- | skipped_move_limit+ sealed JSONB, -- frozen at the fence: version, created_at,+ -- is_identified, properties (merge only)+ moved JSONB, -- written by the flip/tombstone TX, in the same+ -- commit that repoints or tombstones the rows:+ -- [(distinct_id, new_version), ...]+ PRIMARY KEY (op_id, person_id)+);++-- The mark: at most one live op may claim a person.+-- Inserting a row is marking; a unique violation IS the conflict.+CREATE UNIQUE INDEX IF NOT EXISTS lifecycle_op_person_mark+ ON lifecycle_op_person (team_id, person_id)+ WHERE status IN ('marked', 'sealed');diff --git a/rust/persons_migrations/20260727000002_add_is_deleted_to_person_tables.sql b/rust/persons_migrations/20260727000002_add_is_deleted_to_person_tables.sqlnew file mode 100644index 000000000000..9a2b5624d95a--- /dev/null+++ b/rust/persons_migrations/20260727000002_add_is_deleted_to_person_tables.sql@@ -0,0 +1,36 @@+-- Soft-delete tombstones for persons and distinct id mappings.+--+-- Person deletion (and merge source destruction) tombstones rows instead of+-- deleting them: is_deleted = true, version bumped past the sealed version,+-- properties cleared. Keeping the row means the Postgres tombstone carries the+-- same version as the ClickHouse tombstone, and re-creation of a previously+-- deleted key becomes a revival upsert (version bumped above the tombstone)+-- instead of an insert restarting at version 0 that loses to the ClickHouse+-- tombstone forever.+--+-- The unique index on (team_id, distinct_id) intentionally stays total+-- (tombstoned rows included) so a re-created distinct id conflicts with its+-- tombstone and takes the revival path.+--+-- SAFE: ADD COLUMN with a constant default is metadata-only on PG 11++-- (stored as attmissingval; existing rows synthesize the value at read time)+-- — no table rewrite, no backfill, no NOT NULL validation scan, regardless of+-- table size. The remaining hazard is the brief ACCESS EXCLUSIVE lock: on a+-- hot table the danger is queueing for it behind a long-running query while+-- everything else queues behind us. lock_timeout bounds that wait; on timeout+-- the per-file transaction aborts, nothing is recorded, and the next+-- migration run retries this idempotent file.++SET LOCAL lock_timeout = '2s';++ALTER TABLE posthog_person+ ADD COLUMN IF NOT EXISTS is_deleted BOOLEAN NOT NULL DEFAULT false;++ALTER TABLE posthog_persondistinctid+ ADD COLUMN IF NOT EXISTS is_deleted BOOLEAN NOT NULL DEFAULT false;++-- The writer's validation target mirrors posthog_person (minus is_user_id),+-- and the leader's PG fallback reads whichever of the two is configured, so+-- both must carry the column.+ALTER TABLE personhog_person_tmp+ ADD COLUMN IF NOT EXISTS is_deleted BOOLEAN NOT NULL DEFAULT false;