: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
chore(data-deletion): add an s3 staging location for data deletion (#110816)
Paweł Szczur3fa900431d81
diff --git a/posthog/dags/common/s3_staging.py b/posthog/dags/common/s3_staging.pynew file mode 100644index 000000000000..a8c61a400afa--- /dev/null+++ b/posthog/dags/common/s3_staging.py@@ -0,0 +1,64 @@+"""Locations in S3 that the ClickHouse cluster reads and writes through its ``s3(...)`` table function."""++from django.conf import settings++from posthog.dataclasses import frozen+++@frozen+class S3StagingLocation:+ """A bucket and key prefix that the ClickHouse cluster reaches through ``s3(...)``.++ ``endpoint`` is set for local, dev and test object storage, and it must be an endpoint the+ cluster can reach, which is not always the one the Python process uses. On prod it is empty and+ the cluster reaches the bucket through its attached IAM role.+ """++ bucket: str+ prefix: str+ region: str+ endpoint: str | None++ @classmethod+ def for_dictionaries(cls) -> "S3StagingLocation":+ return cls(+ bucket=settings.DICTIONARY_STAGING_S3_BUCKET,+ prefix=settings.DICTIONARY_STAGING_S3_PREFIX,+ region=settings.DICTIONARY_STAGING_S3_REGION,+ endpoint=settings.DICTIONARY_STAGING_S3_ENDPOINT,+ )++ @classmethod+ def for_data_deletion(cls) -> "S3StagingLocation":+ return cls(+ bucket=settings.DATA_DELETION_STAGING_S3_BUCKET,+ prefix=settings.DATA_DELETION_STAGING_S3_PREFIX,+ region=settings.DATA_DELETION_STAGING_S3_REGION,+ endpoint=settings.DATA_DELETION_STAGING_S3_ENDPOINT,+ )++ def object_key(self, key: str) -> str:+ """The full object key under this location's prefix, for a boto3 client."""+ return f"{self.prefix}/{key}"++ def s3_args(self, key: str, file_format: str, structure: str | None = None) -> str:+ """The argument list for a ClickHouse ``s3(...)`` call over ``key``.++ ``key`` may contain ClickHouse glob or ``{_partition_id}`` placeholders. Credentials are+ emitted only where an endpoint is configured, so no secret is ever interpolated into SQL+ on prod.+ """+ path = self.object_key(key)+ if self.endpoint:+ url = f"{self.endpoint}/{self.bucket}/{path}"+ creds = f"'{settings.OBJECT_STORAGE_ACCESS_KEY_ID}', '{settings.OBJECT_STORAGE_SECRET_ACCESS_KEY}', "+ else:+ url = f"https://{self.bucket}.s3.{self.region}.amazonaws.com/{path}"+ creds = ""+ args = f"'{url}', {creds}'{file_format}'"+ if structure is None:+ return args+ # The structure sits inside a single-quoted SQL literal, so escape the quotes in a type like+ # DateTime64(6, 'UTC') or they terminate the literal early.+ escaped = " ".join(structure.split()).replace("'", "\\'")+ return f"{args}, '{escaped}'"diff --git a/posthog/dags/common/staged_dictionary.py b/posthog/dags/common/staged_dictionary.pyindex d1e8270aea04..b4caa88b7294 100644--- a/posthog/dags/common/staged_dictionary.py+++ b/posthog/dags/common/staged_dictionary.py@@ -15,38 +15,15 @@ from collections.abc import Sequencefrom functools import partialfrom typing import Protocol-from django.conf import settings-import dagsterfrom clickhouse_driver import Clientfrom posthog.clickhouse.client.connection import NodeRolefrom posthog.clickhouse.cluster import ClickhouseCluster+from posthog.dags.common.s3_staging import S3StagingLocationfrom posthog.dataclasses import frozen-def _dictionary_s3_args(key: str, structure: str) -> str:- """Argument list for a ClickHouse ``s3(...)`` call over a staged dictionary payload.-- Credentials are emitted only where an endpoint is configured, which is local, dev and test- object storage. On prod the endpoint is empty and the cluster reaches the bucket through its- attached IAM role, so no secret is ever interpolated into SQL.- """- path = f"{settings.DICTIONARY_STAGING_S3_PREFIX}/{key}"- endpoint = settings.DICTIONARY_STAGING_S3_ENDPOINT- if endpoint:- url = f"{endpoint}/{settings.DICTIONARY_STAGING_S3_BUCKET}/{path}"- creds = f"'{settings.OBJECT_STORAGE_ACCESS_KEY_ID}', '{settings.OBJECT_STORAGE_SECRET_ACCESS_KEY}', "- else:- bucket = settings.DICTIONARY_STAGING_S3_BUCKET- url = f"https://{bucket}.s3.{settings.DICTIONARY_STAGING_S3_REGION}.amazonaws.com/{path}"- creds = ""- # The structure sits inside a single-quoted SQL literal, so escape the quotes in a type like- # DateTime64(6, 'UTC') or they terminate the literal early.- escaped = " ".join(structure.split()).replace("'", "\\'")- return f"'{url}', {creds}'Parquet', '{escaped}'"--@frozenclass StagedDictionary:"""A dictionary's rows copied to one Parquet object, for clusters that share no Keeper.@@ -63,7 +40,7 @@ class StagedDictionary:@propertydef __args(self) -> str:- return _dictionary_s3_args(self.key, self.structure)+ return S3StagingLocation.for_dictionaries().s3_args(self.key, "Parquet", self.structure)@propertydef query(self) -> str:diff --git a/posthog/dags/tests/test_s3_staging.py b/posthog/dags/tests/test_s3_staging.pynew file mode 100644index 000000000000..d2630a39fe36--- /dev/null+++ b/posthog/dags/tests/test_s3_staging.py@@ -0,0 +1,41 @@+from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++from posthog.dags.common.s3_staging import S3StagingLocation+++@override_settings(OBJECT_STORAGE_ACCESS_KEY_ID="test-key-id", OBJECT_STORAGE_SECRET_ACCESS_KEY="test-secret")+class TestS3StagingLocation(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "prod reaches the bucket through the node role, with no keys in SQL",+ None,+ None,+ "'https://bucket.s3.us-east-1.amazonaws.com/staging/a/{_partition_id}.native', 'Native'",+ ),+ (+ "local object storage gets path-style URLs and keys",+ "http://objectstorage:19000",+ None,+ "'http://objectstorage:19000/bucket/staging/a/{_partition_id}.native', "+ "'test-key-id', 'test-secret', 'Native'",+ ),+ (+ "a structure with quoted types stays one SQL literal",+ None,+ "ts DateTime64(6, 'UTC'),\n id UUID",+ "'https://bucket.s3.us-east-1.amazonaws.com/staging/a/{_partition_id}.native', 'Native', "+ "'ts DateTime64(6, \\'UTC\\'), id UUID'",+ ),+ ]+ )+ def test_s3_args(self, _name: str, endpoint: str | None, structure: str | None, expected: str) -> None:+ location = S3StagingLocation(bucket="bucket", prefix="staging", region="us-east-1", endpoint=endpoint)++ args = location.s3_args("a/{_partition_id}.native", "Native", structure)++ self.assertEqual(args, expected)+ if endpoint is None:+ self.assertNotIn("test-secret", args)diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 24d5768a06c1..9ab47f0b7836 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -192,3 +192,20 @@ REPLAY_VISION_BENCHMARK_PREFIX = os.getenv("REPLAY_VISION_BENCHMARK_PREFIX", "re# The labeling suite's benchmark export API (MLHog labeling/replay/EXPORT.md), and a read-scoped `lbl_` token for it.REPLAY_VISION_BENCHMARK_LABELING_URL = os.getenv("REPLAY_VISION_BENCHMARK_LABELING_URL", "")REPLAY_VISION_BENCHMARK_LABELING_TOKEN = os.getenv("REPLAY_VISION_BENCHMARK_LABELING_TOKEN", "")++# Data deletion staging (posthog/dags/data_deletion_requests.py). Property removal copies each+# shard's cleaned rows here before it deletes the originals, so between the delete and the reingest+# these objects are the only copy of those rows. Only the ClickHouse cluster reads and writes them,+# through `s3(...)`: the cleaned data files and the small per-step progress files alike. The Dagster+# process never calls S3 for this flow. Nothing deletes the objects, so infra must expire them+# through the bucket lifecycle policy.+DATA_DELETION_STAGING_S3_BUCKET = os.getenv("DATA_DELETION_STAGING_S3_BUCKET") or OBJECT_STORAGE_BUCKET+DATA_DELETION_STAGING_S3_PREFIX = os.getenv("DATA_DELETION_STAGING_S3_PREFIX", "data_deletion_staging")+DATA_DELETION_STAGING_S3_REGION = os.getenv("DATA_DELETION_STAGING_S3_REGION") or OBJECT_STORAGE_REGION+# Must be an endpoint the ClickHouse cluster can reach; see the IDENTITY_MATCHING_S3_ENDPOINT note above.+if TEST or DEBUG:+ DATA_DELETION_STAGING_S3_ENDPOINT: Optional[str] = (+ os.getenv("DATA_DELETION_STAGING_S3_ENDPOINT", "http://objectstorage:19000") or None+ )+else:+ DATA_DELETION_STAGING_S3_ENDPOINT = os.getenv("DATA_DELETION_STAGING_S3_ENDPOINT", "") or Nonediff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex 908cfa84302d..91b751544c6e 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -756,16 +756,17 @@ _NOT_OUR_STORAGE = (# DATAWAREHOUSE_BUCKET/BUCKET_PATH, so a deployment that points it at a different bucket was# reachable through a table's url_pattern until this line was added.#-# CLICKHOUSE_BACKUPS_BUCKET, DICTIONARY_STAGING_S3_BUCKET, IDENTITY_MATCHING_S3_BUCKET,-# NOTEBOOKS_FRAME_STORE_S3_BUCKET, OBJECT_STORAGE_EXTERNAL_WEB_ANALYTICS_BUCKET, and-# QUERY_LOG_ARCHIVE_EXPORT_S3_BUCKET are here because each is read or written by ClickHouse's own-# `s3(...)` / `BACKUP ... TO S3(...)` with no explicit access key in the query, the same credential-less-# shape the original vulnerability exploited - not because a customer's url_pattern can reach them today.+# CLICKHOUSE_BACKUPS_BUCKET, DATA_DELETION_STAGING_S3_BUCKET, DICTIONARY_STAGING_S3_BUCKET,+# IDENTITY_MATCHING_S3_BUCKET, NOTEBOOKS_FRAME_STORE_S3_BUCKET,+# OBJECT_STORAGE_EXTERNAL_WEB_ANALYTICS_BUCKET, and QUERY_LOG_ARCHIVE_EXPORT_S3_BUCKET are here+# because each is read or written by ClickHouse's own `s3(...)` / `BACKUP ... TO S3(...)` with no+# explicit access key in the query, the same credential-less shape the original vulnerability+# exploited - not because a customer's url_pattern can reach them today.#-# DICTIONARY_STAGING_S3_BUCKET and NOTEBOOKS_FRAME_STORE_S3_BUCKET both fall back to-# OBJECT_STORAGE_BUCKET, so they widen this set only on a deployment that points either one at a-# bucket of its own, which cloud does for frames. Both writers (posthog/dags/common/staged_dictionary.py-# and notebooks' frame_materialize.py) omit credentials whenever their own endpoint setting is empty,+# DATA_DELETION_STAGING_S3_BUCKET, DICTIONARY_STAGING_S3_BUCKET and NOTEBOOKS_FRAME_STORE_S3_BUCKET+# all fall back to OBJECT_STORAGE_BUCKET, so they widen this set only on a deployment that points one+# at a bucket of its own, which cloud does for frames. Every writer (posthog/dags/common/s3_staging.py+# and notebooks' frame_materialize.py) omits credentials whenever its own endpoint setting is empty,# and it is empty on prod, so ClickHouse reaches the object through its node role.## BATCH_EXPORT_INTERNAL_STAGING_BUCKET is the same shape: internal_stage.py's get_s3_function_call@@ -779,6 +780,7 @@ _POSTHOG_OWNED_BUCKET_SETTING_NAMES = ("BUCKET_PATH","BUCKET_URL","CLICKHOUSE_BACKUPS_BUCKET",+ "DATA_DELETION_STAGING_S3_BUCKET","DATAWAREHOUSE_BUCKET","DICTIONARY_STAGING_S3_BUCKET","IDENTITY_MATCHING_S3_BUCKET",