Skip to content

: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.

fix(cdp): delete destination debug logs from aux log_entries_data (#121325)

Bryan Ciaraldi0c44ce31614a
diff --git a/posthog/clickhouse/client/migration_tools.py b/posthog/clickhouse/client/migration_tools.py
index ee9a97cf3611..c9733b070609 100644
--- a/posthog/clickhouse/client/migration_tools.py
+++ b/posthog/clickhouse/client/migration_tools.py
@@ -29,7 +29,7 @@ def get_migrations_cluster() -> ClickhouseCluster:
)
-def _collapses_to_all_nodes() -> bool:
+def collapses_to_all_nodes() -> bool:
return (settings.E2E_TESTING or not run_mode().is_deployed_cloud) and not settings.MULTINODE_CLICKHOUSE
@@ -81,7 +81,7 @@ def run_sql_with_exceptions(
# Store original node_roles for validation purposes before debug override
original_node_roles = node_roles_list
- if _collapses_to_all_nodes():
+ if collapses_to_all_nodes():
# In E2E tests, debug mode and hobby deployments, we run migrations on ALL nodes
# because we don't have different ClickHouse topologies yet in Docker.
# MULTINODE_CLICKHOUSE opts back into role-based routing so the smoke-test
@@ -94,7 +94,7 @@ def run_sql_with_exceptions(
query = Query(sql)
if sharded and is_alter_on_replicated_table:
- is_local_or_test = _collapses_to_all_nodes()
+ is_local_or_test = collapses_to_all_nodes()
single_role = node_roles_list[0] if len(node_roles_list) == 1 else None
assert is_local_or_test or (single_role is not None and single_role in DATA_NODE_ROLES), (
"When running migrations on sharded tables, node_roles must be exactly one of "
diff --git a/products/cdp/backend/management/commands/clean_destination_secrets.py b/products/cdp/backend/management/commands/clean_destination_secrets.py
index a9a037dee7e1..e7539feda977 100644
--- a/products/cdp/backend/management/commands/clean_destination_secrets.py
+++ b/products/cdp/backend/management/commands/clean_destination_secrets.py
@@ -16,7 +16,8 @@ from typing import Any, Optional
from django.core.management.base import BaseCommand, CommandError
-from posthog.clickhouse.log_entries import LOG_ENTRIES_SHARDED_TABLE
+from posthog.clickhouse.log_entries import LOG_ENTRIES_DATA_TABLE
+from posthog.settings import CLICKHOUSE_AUX_CLUSTER
from products.cdp.backend.services.destination_activity_logs import (
ActivityLogScope,
@@ -89,8 +90,9 @@ class Command(BaseCommand):
delete_debug_logs(scope, functions)
self.stdout.write(
"debug-logs: delete submitted. Watch progress with: "
- f"SELECT is_done, parts_to_do, latest_fail_reason FROM system.mutations "
- f"WHERE table = '{LOG_ENTRIES_SHARDED_TABLE}' ORDER BY create_time DESC LIMIT 5"
+ f"SELECT hostName(), is_done, parts_to_do, latest_fail_reason "
+ f"FROM clusterAllReplicas('{CLICKHOUSE_AUX_CLUSTER}', system.mutations) "
+ f"WHERE table = '{LOG_ENTRIES_DATA_TABLE}' ORDER BY create_time DESC LIMIT 5"
)
def _activity_logs(self, scope: ActivityLogScope, commit: bool) -> None:
diff --git a/products/cdp/backend/services/destination_debug_logs.py b/products/cdp/backend/services/destination_debug_logs.py
index 8590417dc37d..06c509792fc5 100644
--- a/products/cdp/backend/services/destination_debug_logs.py
+++ b/products/cdp/backend/services/destination_debug_logs.py
@@ -12,16 +12,18 @@ and to lines older than the cutoff the operator passes, so redacted lines writte
after the fix are never touched.
"""
+import re
from datetime import datetime
from typing import Any, Optional
from django.db.models import Q
-from posthog.clickhouse.client.execute import sync_execute
-from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE
-from posthog.clickhouse.log_entries import LOG_ENTRIES_SHARDED_TABLE, LOG_ENTRIES_TABLE
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.execute import default_settings, sync_execute
+from posthog.clickhouse.client.migration_tools import collapses_to_all_nodes, get_migrations_cluster
+from posthog.clickhouse.log_entries import LOG_ENTRIES_DATA_TABLE, LOG_ENTRIES_TABLE
from posthog.dataclasses import frozen
-from posthog.settings import CLICKHOUSE_DATABASE
+from posthog.settings import CLICKHOUSE_AUX_CLUSTER, CLICKHOUSE_DATABASE
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -31,6 +33,9 @@ DESTINATION_TEMPLATE_PREFIXES = ("segment-", "native-")
# sanitizer renders as `<name>, {...json...}`.
DEBUG_LOG_PREFIXES = ("config, {", "options, {", "headers, {", "requestExtension, {", "fetchOptions, {")
+# The cluster, database and table arguments of a Distributed engine, as `system.tables.engine_full` renders them.
+DISTRIBUTED_TARGET = re.compile(r"^Distributed\('([^']*)', '([^']*)', '([^']*)'")
+
@frozen
class DebugLogScope:
@@ -99,25 +104,44 @@ def count_debug_logs(scope: DebugLogScope, functions: list[tuple[int, str]]) ->
)
-def _data_table() -> str:
- # Production holds the rows in `sharded_log_entries`; the test schema has no such table.
+def _log_entries_reads_aux() -> bool:
+ # Deployed regions and fresh environments read `log_entries` through a Distributed table over
+ # `log_entries_data` on the aux cluster. The test schema keeps the rows in a local `log_entries` MergeTree.
rows = sync_execute(
- "SELECT count() FROM system.tables WHERE database = %(database)s AND name = %(name)s",
- {"database": CLICKHOUSE_DATABASE, "name": LOG_ENTRIES_SHARDED_TABLE},
+ "SELECT engine_full FROM system.tables WHERE database = %(database)s AND name = %(name)s",
+ {"database": CLICKHOUSE_DATABASE, "name": LOG_ENTRIES_TABLE},
+ )
+ engine_full = rows[0][0] if rows else ""
+ if not engine_full.startswith("Distributed("):
+ return False
+ target = DISTRIBUTED_TARGET.match(engine_full)
+ if target and target.groups() == (CLICKHOUSE_AUX_CLUSTER, CLICKHOUSE_DATABASE, LOG_ENTRIES_DATA_TABLE):
+ return True
+ # Deleting from aux while reads come from elsewhere would leave the lines readable, so refuse.
+ raise RuntimeError(
+ f"`{LOG_ENTRIES_TABLE}` reads {engine_full}, not `{LOG_ENTRIES_DATA_TABLE}` on the aux cluster. Nothing was deleted."
)
- return LOG_ENTRIES_SHARDED_TABLE if rows[0][0] else LOG_ENTRIES_TABLE
def delete_debug_logs(scope: DebugLogScope, functions: list[tuple[int, str]], wait: bool = False) -> None:
if not functions:
return
+ args = _args(scope, functions)
# Waiting on every replica outlasts the client timeout in production, so it runs asynchronously.
+ delete_settings = {"lightweight_deletes_sync": 2 if wait else 0}
+ if not _log_entries_reads_aux():
+ # nosemgrep: clickhouse-fstring-param-audit - only constants are interpolated; scope and functions are bound parameters
+ sync_execute(f"DELETE FROM {LOG_ENTRIES_TABLE} WHERE {_predicate()}", args, settings=delete_settings)
+ return
# nosemgrep: clickhouse-fstring-param-audit - only constants are interpolated; scope and functions are bound parameters
- sync_execute(
- f"""
- DELETE FROM {_data_table()} {ON_CLUSTER_CLAUSE()}
- WHERE {_predicate()}
- """,
- _args(scope, functions),
- settings={"lightweight_deletes_sync": 2 if wait else 0},
- )
+ sql = f"DELETE FROM {LOG_ENTRIES_DATA_TABLE} WHERE {_predicate()}"
+ if collapses_to_all_nodes():
+ # Single-node installs hold `log_entries_data` on the one node, which carries no aux role.
+ sync_execute(sql, args, settings=delete_settings)
+ return
+ # The aux cluster is a single shard: one host runs the delete and replication carries it.
+ # The raw client skips sync_execute's defaults, and a region-wide function list needs their larger max_query_size.
+ client_settings = {**default_settings(), **delete_settings}
+ get_migrations_cluster().any_host_by_role(
+ lambda client: client.execute(sql, args, settings=client_settings), NodeRole.AUX
+ ).result()
diff --git a/products/cdp/backend/test/test_destination_debug_logs.py b/products/cdp/backend/test/test_destination_debug_logs.py
index 8b03516e921a..460478510812 100644
--- a/products/cdp/backend/test/test_destination_debug_logs.py
+++ b/products/cdp/backend/test/test_destination_debug_logs.py
@@ -1,18 +1,26 @@
from datetime import UTC, datetime, timedelta
+import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from unittest.mock import MagicMock, patch
-from posthog.clickhouse.client.execute import sync_execute
-from posthog.clickhouse.log_entries import INSERT_LOG_ENTRY_SQL
+from parameterized import parameterized
+
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.execute import default_settings, sync_execute
+from posthog.clickhouse.log_entries import INSERT_LOG_ENTRY_SQL, LOG_ENTRIES_DATA_TABLE, LOG_ENTRIES_TABLE
+from posthog.settings import CLICKHOUSE_AUX_CLUSTER, CLICKHOUSE_DATABASE
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.services.destination_debug_logs import (
DebugLogScope,
+ _log_entries_reads_aux,
count_debug_logs,
delete_debug_logs,
find_destination_functions,
)
+MODULE = "products.cdp.backend.services.destination_debug_logs"
CUTOFF = datetime(2026, 9, 18, 10, 0, 0, tzinfo=UTC)
BEFORE = CUTOFF - timedelta(days=1)
AFTER = CUTOFF + timedelta(hours=1)
@@ -31,10 +39,12 @@ class TestDestinationDebugLogs(ClickhouseTestMixin, BaseTest):
team=self.team, name="hog", type="destination", template_id="template-webhook", hog=""
)
- def _insert(self, function: HogFunction, level: str, message: str, timestamp: datetime) -> None:
+ def _insert(
+ self, function: HogFunction, level: str, message: str, timestamp: datetime, table: str = LOG_ENTRIES_TABLE
+ ) -> None:
# The table is a ReplacingMergeTree keyed on the timestamp, so every row needs its own.
sync_execute(
- INSERT_LOG_ENTRY_SQL,
+ INSERT_LOG_ENTRY_SQL.replace(f"INSERT INTO {LOG_ENTRIES_TABLE} ", f"INSERT INTO {table} "),
{
"team_id": function.team_id,
"log_source": "hog_function",
@@ -46,9 +56,9 @@ class TestDestinationDebugLogs(ClickhouseTestMixin, BaseTest):
},
)
- def _remaining(self) -> set[tuple[str, str]]:
+ def _remaining(self, table: str = LOG_ENTRIES_TABLE) -> set[tuple[str, str]]:
rows = sync_execute(
- "SELECT log_source_id, message FROM log_entries WHERE team_id = %(team_id)s", {"team_id": self.team.pk}
+ f"SELECT log_source_id, message FROM {table} WHERE team_id = %(team_id)s", {"team_id": self.team.pk}
)
return {(function_id, message) for function_id, message in rows}
@@ -84,3 +94,59 @@ class TestDestinationDebugLogs(ClickhouseTestMixin, BaseTest):
assert self._remaining() == {(str(function.id), message) for function, _, message, _ in kept}
assert count_debug_logs(scope, functions).lines == 0
+
+ def test_deletes_from_aux_data_table_on_an_aux_host(self) -> None:
+ scope = DebugLogScope(before=CUTOFF, team_id=self.team.pk)
+ functions = [(self.team.pk, str(self.segment.id))]
+ cluster = MagicMock()
+ client = MagicMock()
+ cluster.any_host_by_role.side_effect = lambda fn, role: MagicMock(result=lambda: fn(client))
+
+ with (
+ patch(f"{MODULE}._log_entries_reads_aux", return_value=True),
+ patch(f"{MODULE}.collapses_to_all_nodes", return_value=False),
+ patch(f"{MODULE}.get_migrations_cluster", return_value=cluster),
+ ):
+ delete_debug_logs(scope, functions)
+
+ assert cluster.any_host_by_role.call_args.args[1] == NodeRole.AUX
+ sql, args = client.execute.call_args.args
+ assert sql.startswith(f"DELETE FROM {LOG_ENTRIES_DATA_TABLE} WHERE")
+ assert args["functions"] == functions
+ settings = client.execute.call_args.kwargs["settings"]
+ assert settings["lightweight_deletes_sync"] == 0
+ assert settings["max_query_size"] == default_settings()["max_query_size"]
+
+ def test_deletes_from_aux_data_table_on_the_local_node_when_topology_collapses(self) -> None:
+ doomed = (self.segment, 'config, {"apiKey":"key-1234567890"}')
+ kept = (self.segment, "endpoint, https://api.example.com/track")
+ for i, (function, message) in enumerate([doomed, kept]):
+ self._insert(function, "debug", message, BEFORE + timedelta(seconds=i), table=LOG_ENTRIES_DATA_TABLE)
+
+ scope = DebugLogScope(before=CUTOFF, team_id=self.team.pk)
+ with (
+ patch(f"{MODULE}._log_entries_reads_aux", return_value=True),
+ patch(f"{MODULE}.collapses_to_all_nodes", return_value=True),
+ ):
+ delete_debug_logs(scope, [(self.team.pk, str(self.segment.id))], wait=True)
+
+ assert self._remaining(table=LOG_ENTRIES_DATA_TABLE) == {(str(kept[0].id), kept[1])}
+
+ @parameterized.expand(
+ [
+ ("local MergeTree", "ReplacingMergeTree(_timestamp) ORDER BY team_id", False),
+ (
+ "aux reader",
+ f"Distributed('{CLICKHOUSE_AUX_CLUSTER}', '{CLICKHOUSE_DATABASE}', 'log_entries_data')",
+ True,
+ ),
+ ]
+ )
+ def test_detects_whether_log_entries_reads_aux(self, _name: str, engine_full: str, expected: bool) -> None:
+ with patch(f"{MODULE}.sync_execute", return_value=[(engine_full,)]):
+ assert _log_entries_reads_aux() is expected
+
+ def test_refuses_when_log_entries_reads_another_table(self) -> None:
+ engine_full = f"Distributed('posthog', '{CLICKHOUSE_DATABASE}', 'sharded_log_entries', rand())"
+ with patch(f"{MODULE}.sync_execute", return_value=[(engine_full,)]), pytest.raises(RuntimeError):
+ _log_entries_reads_aux()