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.

chore(managed-warehouse): observe DuckgresServer access (#83782)

Benjamin Knofe-Vider4f353128c1ea
diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.md
index dfdcc60ac67c..f4ba7260d594 100644
--- a/products/managed_warehouse/backend/README.md
+++ b/products/managed_warehouse/backend/README.md
@@ -1,5 +1,56 @@
# DuckLake copy workflow configuration
+## DuckgresServer retirement telemetry
+
+ORM access to `DuckgresServer` emits the counter
+`warehouse.duckgres.server.model.access`. It has five bounded attributes: `operation`
+(`read`, `create`, `update`, or `delete`), the immediate `accessor_module` and
+`accessor_function`, and the meaningful outer `caller_module` and `caller_function`.
+The outer caller skips shared managed-warehouse configuration gateways so the result
+identifies the business workflow that still depends on the model. Caller names are
+limited to 160 characters. The metric deliberately excludes model fields,
+organization identifiers, connection details, and other customer data.
+
+Use the PostHog Metrics SQL editor to find active callers over a representative
+period:
+
+```sql
+SELECT
+ attributes['operation'] AS operation,
+ attributes['accessor_module'] AS accessor_module,
+ attributes['accessor_function'] AS accessor_function,
+ attributes['caller_module'] AS caller_module,
+ attributes['caller_function'] AS caller_function,
+ sum(value) AS accesses
+FROM posthog.metrics
+WHERE metric_name = 'warehouse.duckgres.server.model.access'
+ AND metric_type = 'counter'
+ AND aggregation_temporality = 'delta'
+ AND timestamp >= now() - INTERVAL 7 DAY
+GROUP BY operation, accessor_module, accessor_function, caller_module, caller_function
+ORDER BY accesses DESC
+```
+
+Reads are recorded through the model's default `objects` manager when a normal
+queryset is evaluated, or when `get`, `count`, `exists`, or `iterator` executes.
+Re-evaluating the same cached queryset does not emit another access. Normal model
+saves and deletes and queryset updates and deletes are also recorded once per ORM
+operation. Normal `async for` queryset evaluation uses `_fetch_all` and is recorded,
+although attribution may become `unknown` across its thread boundary.
+
+This is deliberately a probe of the default manager rather than proof of all model
+use. It does not observe reads through `_base_manager`, reverse one-to-one access,
+`select_related` or `prefetch_related` hydration, raw SQL, `raw()`/`RawQuerySet`, or
+`.aiterator()`. `bulk_create` bypasses the save signals. These paths can construct or
+write `DuckgresServer` instances without incrementing the counter.
+
+Before using an empty result as retirement evidence, confirm that another known
+metric from every relevant service is reaching the same Metrics project. Observe
+for at least one complete schedule window, remove the remaining callers, then
+repeat the query. An empty result cannot prove that the model is unused: a final
+static search for the model, its table, and reverse relation is mandatory before
+removal because telemetry cannot discover dormant or uninstrumented code paths.
+
The DuckLake copy and registration workflows write data into a DuckLake-managed S3 bucket. There are three workflows:
1. **Data Modeling** (`ducklake-copy.data-modeling`) - copies materialized saved query outputs
diff --git a/products/managed_warehouse/backend/model_observability.py b/products/managed_warehouse/backend/model_observability.py
new file mode 100644
index 000000000000..89e5d53153c8
--- /dev/null
+++ b/products/managed_warehouse/backend/model_observability.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+import sys
+from collections.abc import Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar
+from types import FrameType
+from typing import TYPE_CHECKING
+
+from django.db import models
+
+from posthog.dataclasses import frozen
+
+from products.managed_warehouse.backend.metrics import record_counter
+
+if TYPE_CHECKING:
+ from products.managed_warehouse.backend.models import DuckgresServer
+
+
+DUCKGRES_SERVER_ACCESS_METRIC = "warehouse.duckgres.server.model.access"
+
+_access_recording_suppressed: ContextVar[bool] = ContextVar(
+ "duckgres_server_access_recording_suppressed", default=False
+)
+_INTERNAL_CALLER_MODULES = {
+ __name__,
+ "products.managed_warehouse.backend.models",
+}
+_CALLER_GATEWAY_MODULES = {
+ "products.managed_warehouse.backend.common",
+ "products.managed_warehouse.backend.facade.api",
+ "products.managed_warehouse.backend.logic.connection",
+}
+_FRAMEWORK_CALLER_PREFIXES = (
+ "asgiref.",
+ "concurrent.futures.",
+ "django.",
+ "threading",
+)
+_MAX_CALLER_NAME_LENGTH = 160
+
+
+@frozen
+class _CallerAttribution:
+ accessor_module: str
+ accessor_function: str
+ caller_module: str
+ caller_function: str
+
+
+def _caller_name(value: str) -> str:
+ return (value or "unknown")[:_MAX_CALLER_NAME_LENGTH]
+
+
+def _external_callers() -> _CallerAttribution:
+ frame: FrameType | None = sys._getframe(1)
+ accessor: tuple[str, str] | None = None
+ while frame is not None:
+ module = str(frame.f_globals.get("__name__", ""))
+ if module not in _INTERNAL_CALLER_MODULES and not module.startswith(_FRAMEWORK_CALLER_PREFIXES):
+ current = (_caller_name(module), _caller_name(frame.f_code.co_name))
+ accessor = accessor or current
+ if module not in _CALLER_GATEWAY_MODULES:
+ return _CallerAttribution(
+ accessor_module=accessor[0],
+ accessor_function=accessor[1],
+ caller_module=current[0],
+ caller_function=current[1],
+ )
+ frame = frame.f_back
+ unknown = ("unknown", "unknown")
+ accessor = accessor or unknown
+ return _CallerAttribution(
+ accessor_module=accessor[0],
+ accessor_function=accessor[1],
+ caller_module=accessor[0],
+ caller_function=accessor[1],
+ )
+
+
+def record_duckgres_server_access(operation: str) -> None:
+ if _access_recording_suppressed.get():
+ return
+
+ attribution = _external_callers()
+ try:
+ record_counter(
+ DUCKGRES_SERVER_ACCESS_METRIC,
+ 1,
+ {
+ "operation": operation,
+ "accessor_module": attribution.accessor_module,
+ "accessor_function": attribution.accessor_function,
+ "caller_module": attribution.caller_module,
+ "caller_function": attribution.caller_function,
+ },
+ )
+ except Exception:
+ # Access telemetry must never make a model operation fail.
+ pass
+
+
+@contextmanager
+def suppress_duckgres_server_access_recording() -> Iterator[None]:
+ token = _access_recording_suppressed.set(True)
+ try:
+ yield
+ finally:
+ _access_recording_suppressed.reset(token)
+
+
+class DuckgresServerQuerySet(models.QuerySet["DuckgresServer"]):
+ def _fetch_all(self) -> None:
+ if self._result_cache is None:
+ record_duckgres_server_access("read")
+ super()._fetch_all()
+
+ def count(self) -> int:
+ record_duckgres_server_access("read")
+ return super().count()
+
+ def exists(self) -> bool:
+ record_duckgres_server_access("read")
+ return super().exists()
+
+ def iterator(self, chunk_size: int | None = None) -> Iterator[DuckgresServer]:
+ record_duckgres_server_access("read")
+ return super().iterator(chunk_size=chunk_size)
+
+ def update(self, **kwargs: object) -> int:
+ record_duckgres_server_access("update")
+ return super().update(**kwargs)
+
+ def delete(self) -> tuple[int, dict[str, int]]:
+ record_duckgres_server_access("delete")
+ with suppress_duckgres_server_access_recording():
+ return super().delete()
+
+
+DuckgresServerManager = models.Manager.from_queryset(DuckgresServerQuerySet)
diff --git a/products/managed_warehouse/backend/models.py b/products/managed_warehouse/backend/models.py
index f2a8c62d437b..316fdc6923cc 100644
--- a/products/managed_warehouse/backend/models.py
+++ b/products/managed_warehouse/backend/models.py
@@ -1,11 +1,15 @@
from __future__ import annotations
from django.db import models
+from django.db.models.signals import post_delete, post_save
+from django.dispatch import receiver
from posthog.helpers.encrypted_fields import EncryptedTextField
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+from products.managed_warehouse.backend.model_observability import DuckgresServerManager, record_duckgres_server_access
+
class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
"""Per-organization duckgres query server + DuckLake catalog connection details.
@@ -17,6 +21,8 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
too under the ``catalog_*`` fields.
"""
+ objects = DuckgresServerManager()
+
organization = models.OneToOneField(
"posthog.Organization",
on_delete=models.CASCADE,
@@ -68,6 +74,16 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
}
+@receiver(post_save, sender=DuckgresServer, dispatch_uid="observe_duckgres_server_save")
+def _observe_duckgres_server_save(*, created: bool, **kwargs: object) -> None:
+ record_duckgres_server_access("create" if created else "update")
+
+
+@receiver(post_delete, sender=DuckgresServer, dispatch_uid="observe_duckgres_server_delete")
+def _observe_duckgres_server_delete(**kwargs: object) -> None:
+ record_duckgres_server_access("delete")
+
+
class ManagedWarehouseSourceJob(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):
class WorkflowType(models.TextChoices):
COPY = "copy", "Copy"
diff --git a/products/managed_warehouse/backend/tests/test_model_observability.py b/products/managed_warehouse/backend/tests/test_model_observability.py
new file mode 100644
index 000000000000..cf225e526d53
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_model_observability.py
@@ -0,0 +1,208 @@
+import pytest
+from unittest.mock import MagicMock, call, patch
+
+from parameterized import parameterized
+
+from posthog.models import Organization
+
+from products.managed_warehouse.backend import common
+from products.managed_warehouse.backend.facade import api as warehouse_api
+from products.managed_warehouse.backend.logic import connection
+from products.managed_warehouse.backend.model_observability import DUCKGRES_SERVER_ACCESS_METRIC
+from products.managed_warehouse.backend.models import DuckgresServer
+
+
+def _server(organization: Organization, **overrides: object) -> DuckgresServer:
+ return DuckgresServer.objects.create(
+ organization=organization,
+ host="warehouse.example.com",
+ database="ducklake",
+ username="root",
+ password="example-password",
+ **overrides,
+ )
+
+
+def _get_server(server_id: str) -> DuckgresServer:
+ return DuckgresServer.objects.get(id=server_id)
+
+
+def _metric_call(
+ operation: str,
+ accessor_function: str,
+ *,
+ caller_function: str | None = None,
+ accessor_module: str = __name__,
+ caller_module: str = __name__,
+) -> object:
+ return call(
+ DUCKGRES_SERVER_ACCESS_METRIC,
+ 1,
+ {
+ "operation": operation,
+ "accessor_module": accessor_module,
+ "accessor_function": accessor_function,
+ "caller_module": caller_module,
+ "caller_function": caller_function or accessor_function,
+ },
+ )
+
+
+class TestDuckgresServerModelObservability:
+ def test_records_reads_when_the_query_executes_with_the_immediate_external_caller(self) -> None:
+ organization = Organization.objects.create(name="Example organization")
+ server = _server(organization)
+ record_counter = MagicMock()
+
+ with patch("products.managed_warehouse.backend.model_observability.record_counter", record_counter):
+ queryset = DuckgresServer.objects.filter(id=server.id)
+ record_counter.assert_not_called()
+
+ assert list(queryset) == [server]
+ assert list(queryset) == [server]
+ _get_server(str(server.id))
+
+ assert record_counter.call_args_list == [
+ _metric_call("read", "test_records_reads_when_the_query_executes_with_the_immediate_external_caller"),
+ _metric_call("read", "_get_server"),
+ ]
+
+ def test_records_the_real_common_accessor_and_the_business_caller(self) -> None:
+ organization = Organization.objects.create(name="Example organization")
+ server = _server(organization)
+ record_counter = MagicMock()
+
+ with (
+ patch("products.managed_warehouse.backend.common.is_dev_mode", return_value=False),
+ patch("products.managed_warehouse.backend.model_observability.record_counter", record_counter),
+ ):
+ assert common.get_duckgres_server_for_organization(str(organization.id)) == server
+
+ record_counter.assert_called_once_with(
+ DUCKGRES_SERVER_ACCESS_METRIC,
+ 1,
+ {
+ "operation": "read",
+ "accessor_module": "products.managed_warehouse.backend.common",
+ "accessor_function": "get_duckgres_server_for_organization",
+ "caller_module": __name__,
+ "caller_function": "test_records_the_real_common_accessor_and_the_business_caller",
+ },
+ )
+
+ def test_skips_the_facade_when_identifying_the_business_caller(self) -> None:
+ organization = Organization.objects.create(name="Example organization")
+ _server(organization)
+ record_counter = MagicMock()
+
+ with patch("products.managed_warehouse.backend.model_observability.record_counter", record_counter):
+ assert warehouse_api.has_provisioned_warehouse(organization.id)
+
+ record_counter.assert_called_once_with(
+ DUCKGRES_SERVER_ACCESS_METRIC,
+ 1,
+ {
+ "operation": "read",
+ "accessor_module": "products.managed_warehouse.backend.facade.api",
+ "accessor_function": "has_provisioned_warehouse",
+ "caller_module": __name__,
+ "caller_function": "test_skips_the_facade_when_identifying_the_business_caller",
+ },
+ )
+
+ def test_skips_the_connection_gateway_when_identifying_the_business_caller(self) -> None:
+ organization = Organization.objects.create(name="Example organization")
+ _server(organization)
+ record_counter = MagicMock()
+
+ with patch("products.managed_warehouse.backend.model_observability.record_counter", record_counter):
+ connection.update_managed_warehouse_root_password(
+ organization_id=organization.id, password="replacement-password"
+ )
+
+ assert record_counter.call_args_list == [
+ _metric_call(
+ "read",
+ "update_managed_warehouse_root_password",
+ accessor_module="products.managed_warehouse.backend.logic.connection",
+ caller_function="test_skips_the_connection_gateway_when_identifying_the_business_caller",
+ ),
+ _metric_call(
+ "update",
+ "update_managed_warehouse_root_password",
+ accessor_module="products.managed_warehouse.backend.logic.connection",
+ caller_function="test_skips_the_connection_gateway_when_identifying_the_business_caller",
+ ),
+ ]
+
+ @parameterized.expand(["count", "exists", "iterator"])
+ def test_records_query_execution_methods(self, query_operation: str) -> None:
+ organization = Organization.objects.create(name="Example organization")
+ server = _server(organization)
+ record_counter = MagicMock()
+
+ with patch("products.managed_warehouse.backend.model_observability.record_counter", record_counter):
+ queryset = DuckgresServer.objects.filter(id=server.id)
+ result = getattr(queryset, query_operation)()
+ if query_operation == "iterator":
+ assert list(result) == [server]
+ else:
+ assert result
+
+ record_counter.assert_called_once_with(
+ DUCKGRES_SERVER_ACCESS_METRIC,
+ 1,
+ {
+ "operation": "read",
+ "accessor_module": __name__,
+ "accessor_function": "test_records_query_execution_methods",
+ "caller_module": __name__,
+ "caller_function": "test_records_query_execution_methods",
+ },
+ )
+
+ def test_records_create_update_and_delete_once_per_model_operation(self) -> None:
+ organization = Organization.objects.create(name="Example organization")
+ record_counter = MagicMock()
+
+ with patch("products.managed_warehouse.backend.model_observability.record_counter", record_counter):
+ server = _server(organization)
+ server.host = "replacement.example.com"
+ server.save(update_fields=["host"])
+ DuckgresServer.objects.filter(id=server.id).update(port=6543)
+ DuckgresServer.objects.filter(id=server.id).delete()
+
+ assert record_counter.call_args_list == [
+ _metric_call("create", "_server"),
+ _metric_call("update", "test_records_create_update_and_delete_once_per_model_operation"),
+ _metric_call("update", "test_records_create_update_and_delete_once_per_model_operation"),
+ _metric_call("delete", "test_records_create_update_and_delete_once_per_model_operation"),
+ ]
+
+ def test_metrics_failures_do_not_interrupt_model_access(self) -> None:
+ organization = Organization.objects.create(name="Example organization")
+ server = _server(organization)
+ record_counter = MagicMock(side_effect=RuntimeError("metrics unavailable"))
+
+ with patch("products.managed_warehouse.backend.model_observability.record_counter", record_counter):
+ assert DuckgresServer.objects.get(id=server.id) == server
+
+ def test_documents_reads_that_bypass_the_default_manager(self) -> None:
+ organization = Organization.objects.create(name="Example organization")
+ server = _server(organization)
+ organization = Organization.objects.get(id=organization.id)
+ record_counter = MagicMock()
+
+ with patch("products.managed_warehouse.backend.model_observability.record_counter", record_counter):
+ assert DuckgresServer._base_manager.get(id=server.id) == server
+ assert organization.duckgres_server == server
+ assert (
+ Organization.objects.select_related("duckgres_server").get(id=organization.id).duckgres_server == server
+ )
+ assert (
+ Organization.objects.prefetch_related("duckgres_server").get(id=organization.id).duckgres_server
+ == server
+ )
+
+ record_counter.assert_not_called()