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.

feat(managed-warehouse): tag duckgres connections with application_name (#83351)

Eric Duongde77e27393f0
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index e02d7f6c450f..03f84c5e5170 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -398,6 +398,7 @@ def _connect_duckgres(
target.team_id,
organization_id=target.organization_id,
service_credential=service_credential,
+ application_name="events-backfill",
)
conn = psycopg.connect(
conninfo,
diff --git a/products/managed_warehouse/backend/client.py b/products/managed_warehouse/backend/client.py
index 46e01d3d353c..a4feed4d0ca3 100644
--- a/products/managed_warehouse/backend/client.py
+++ b/products/managed_warehouse/backend/client.py
@@ -41,6 +41,7 @@ def make_duckgres_conninfo(
*,
organization_id: str | None = None,
service_credential: ServiceCredential | None = None,
+ application_name: str = "posthog",
) -> str:
"""Build a psycopg conninfo for a team's duckgres server.
@@ -58,6 +59,13 @@ def make_duckgres_conninfo(
Service credentials are only mintable for a provisioned production
warehouse, so dev-mode is rejected loudly rather than silently
downgraded to root.
+
+ ``application_name`` is forwarded to duckgres as a standard libpq startup
+ param and echoed into its analytics events, so callers should pass a
+ caller-identifying slug (e.g. ``"ducklake-register"``) instead of relying
+ on the ``"posthog"`` default — that default only distinguishes PostHog's
+ own connections in aggregate from customer clients (psql, their own
+ application_name).
"""
from products.managed_warehouse.backend.common import _duckgres_dev_config, _get_org_id_for_team
@@ -80,6 +88,7 @@ def make_duckgres_conninfo(
sslcert="/tmp/no.txt",
sslkey="/tmp/no.txt",
sslrootcert="/tmp/no.txt",
+ application_name=application_name,
)
if is_dev_mode():
@@ -97,6 +106,7 @@ def make_duckgres_conninfo(
sslcert="/tmp/no.txt",
sslkey="/tmp/no.txt",
sslrootcert="/tmp/no.txt",
+ application_name=application_name,
)
@@ -298,7 +308,7 @@ def execute_ducklake_query(
assert sql is not None
- conninfo = make_duckgres_conninfo(team_id, organization_id=organization_id)
+ conninfo = make_duckgres_conninfo(team_id, organization_id=organization_id, application_name="endpoints-shadow")
_connect_start = time.monotonic()
with psycopg.connect(conninfo) as conn:
connect_ms = (time.monotonic() - _connect_start) * 1000
@@ -368,7 +378,7 @@ def execute_ducklake_create_table(
safe_schema = sanitize_ducklake_identifier(schema_name, default_prefix="shadow")
safe_table = sanitize_ducklake_identifier(table_name, default_prefix="model")
qualified = psql.Identifier(safe_schema, safe_table)
- conninfo = make_duckgres_conninfo(team_id, organization_id=organization_id)
+ conninfo = make_duckgres_conninfo(team_id, organization_id=organization_id, application_name="materialization")
# capture previous table size before replacing — best-effort, don't block materialization
previous_file_size_bytes = _calculate_table_size(conninfo, safe_schema, safe_table)
with psycopg.connect(conninfo) as conn:
diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.py
index 604d7d819b27..e885894b4a07 100644
--- a/products/managed_warehouse/backend/facade/client.py
+++ b/products/managed_warehouse/backend/facade/client.py
@@ -53,11 +53,13 @@ def make_duckgres_conninfo(
*,
organization_id: str | None = None,
service_credential: ServiceCredential | None = None,
+ application_name: str = "posthog",
) -> str:
return client.make_duckgres_conninfo(
team_id,
organization_id=organization_id,
service_credential=service_credential,
+ application_name=application_name,
)
diff --git a/products/managed_warehouse/backend/storage.py b/products/managed_warehouse/backend/storage.py
index 119facf66a2d..274f0482a4f3 100644
--- a/products/managed_warehouse/backend/storage.py
+++ b/products/managed_warehouse/backend/storage.py
@@ -771,8 +771,13 @@ def create_staging_read_secret(conn: psycopg.Connection, catalog_bucket: str) ->
)
-def connect_to_duckgres(server: DuckgresServer) -> psycopg.Connection:
- """Open a psycopg connection to a duckgres server."""
+def connect_to_duckgres(server: DuckgresServer, *, application_name: str = "posthog") -> psycopg.Connection:
+ """Open a psycopg connection to a duckgres server.
+
+ ``application_name`` is a caller-identifying slug echoed into duckgres's
+ analytics events, so callers should pass one instead of relying on the
+ ``"posthog"`` default.
+ """
return psycopg.connect(
host=server.host,
port=server.port,
@@ -780,6 +785,7 @@ def connect_to_duckgres(server: DuckgresServer) -> psycopg.Connection:
user=server.username,
password=server.password,
autocommit=True,
+ application_name=application_name,
)
diff --git a/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py
index edb4c03bde04..6af92bfcc02b 100644
--- a/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py
+++ b/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py
@@ -511,7 +511,7 @@ def _copy_data_imports_via_duckgres(
schema = inputs.model.ducklake_schema_name
table = f"{schema}.{inputs.model.ducklake_table_name}"
- with connect_to_duckgres(server) as conn:
+ with connect_to_duckgres(server, application_name="ducklake-copy") as conn:
setup_duckgres_session(conn)
create_staging_read_secret(conn, bucket)
logger.info(
@@ -701,7 +701,7 @@ def _verify_data_imports_ducklake_copy_via_duckgres(
inputs=inputs,
)
- with connect_to_duckgres(server) as conn:
+ with connect_to_duckgres(server, application_name="ducklake-copy") as conn:
setup_duckgres_session(conn)
create_staging_read_secret(conn, urlparse(inputs.model.staging_uri).netloc)
return _run_data_imports_verification_checks(
diff --git a/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py
index 29a3a1b063a0..e6a67451eff1 100644
--- a/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py
+++ b/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py
@@ -524,7 +524,7 @@ def _copy_data_modeling_via_duckgres(inputs: DuckLakeCopyActivityInputs, logger)
schema = inputs.model.schema_name
table = f"{schema}.{inputs.model.table_name}"
- with connect_to_duckgres(server) as conn:
+ with connect_to_duckgres(server, application_name="ducklake-copy-modeling") as conn:
setup_duckgres_session(conn)
create_staging_read_secret(conn, bucket)
logger.info(
diff --git a/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py
index 0347a16383ef..d2e25674ef32 100644
--- a/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py
+++ b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py
@@ -548,7 +548,8 @@ def _should_publish_prepared_generation(inputs: DuckLakeRegisterDataImportsActiv
@contextlib.contextmanager
def _connect_to_duckgres_for_team(team_id: int) -> Iterator[psycopg.Connection]:
if is_dev_mode():
- with psycopg.connect(make_duckgres_conninfo(team_id), autocommit=True) as conn:
+ conninfo = make_duckgres_conninfo(team_id, application_name="ducklake-register")
+ with psycopg.connect(conninfo, autocommit=True) as conn:
yield conn
return
@@ -556,7 +557,7 @@ def _connect_to_duckgres_for_team(team_id: int) -> Iterator[psycopg.Connection]:
server = get_duckgres_server_for_organization(organization_id)
if server is None:
raise ApplicationError(f"No DuckgresServer configured for team {team_id}", non_retryable=True)
- with connect_to_duckgres(server) as conn:
+ with connect_to_duckgres(server, application_name="ducklake-register") as conn:
yield conn
diff --git a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
index 501b7164a70b..d6fd244abab9 100644
--- a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
+++ b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
@@ -183,7 +183,9 @@ def test_copy_activity_uses_s3_copy_and_local_duckgres_postgres_connection(monke
monkeypatch.setattr(registration_module, "get_s3_client", lambda: s3)
monkeypatch.setattr(registration_module, "_prepared_generation_is_current", lambda inputs: True)
monkeypatch.setattr(registration_module, "is_dev_mode", lambda: True)
- monkeypatch.setattr(registration_module, "make_duckgres_conninfo", lambda team_id: "postgresql://duckgres")
+ monkeypatch.setattr(
+ registration_module, "make_duckgres_conninfo", lambda team_id, **kwargs: "postgresql://duckgres"
+ )
conn = MagicMock()
conn.__enter__ = MagicMock(return_value=conn)
diff --git a/products/managed_warehouse/backend/tests/test_client.py b/products/managed_warehouse/backend/tests/test_client.py
index 25182028b7ed..659804e43d4d 100644
--- a/products/managed_warehouse/backend/tests/test_client.py
+++ b/products/managed_warehouse/backend/tests/test_client.py
@@ -3,6 +3,7 @@ from unittest import mock
from django.apps import apps
+from parameterized import parameterized
from psycopg import sql as psql
from posthog.schema import HogQLQuery, HogQLVariable
@@ -12,7 +13,9 @@ from products.managed_warehouse.backend.client import (
_configure_s3_secrets,
_s3_secrets_for_database,
compile_hogql_to_ducklake_sql,
+ execute_ducklake_create_table,
execute_ducklake_query,
+ make_duckgres_conninfo,
)
from products.managed_warehouse.backend.facade.contracts import DuckLakeCompiledQuery
@@ -302,6 +305,20 @@ class TestDuckgresShadowCompilation:
assert kwargs.get("user") is None
+class TestMakeDuckgresConninfoApplicationName:
+ @parameterized.expand(
+ [
+ ("default", {}, "posthog"),
+ ("explicit_override", {"application_name": "ducklake-register"}, "ducklake-register"),
+ ]
+ )
+ def test_application_name_on_org_root_path(self, _name, kwargs, expected):
+ with mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=True):
+ conninfo = make_duckgres_conninfo(1, **kwargs)
+
+ assert f"application_name={expected}" in conninfo
+
+
class TestExecuteDuckLakeQuery:
def test_rejects_both_sql_and_query(self):
with pytest.raises(ValueError, match="not both"):
@@ -403,3 +420,25 @@ class TestExecuteDuckLakeQuery:
mock_config_for_org.assert_called_once_with("org-456")
assert result.results == [[1]]
+ # Lets duckgres analytics tell this shadow-query caller apart from the
+ # materialization path and from customer connections.
+ conninfo = mock_psycopg.connect.call_args.args[0]
+ assert "application_name=endpoints-shadow" in conninfo
+
+
+class TestExecuteDuckLakeCreateTable:
+ @mock.patch("products.managed_warehouse.backend.client.psycopg")
+ @mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=True)
+ def test_uses_materialization_application_name(self, _mock_dev_mode, mock_psycopg):
+ mock_cursor = mock.MagicMock()
+ mock_cursor.fetchone.return_value = (0,)
+ mock_conn = mock.MagicMock()
+ mock_conn.cursor.return_value.__enter__ = mock.Mock(return_value=mock_cursor)
+ mock_conn.cursor.return_value.__exit__ = mock.Mock(return_value=False)
+ mock_psycopg.connect.return_value.__enter__ = mock.Mock(return_value=mock_conn)
+ mock_psycopg.connect.return_value.__exit__ = mock.Mock(return_value=False)
+
+ execute_ducklake_create_table(1, "SELECT 1", "shadow", "model")
+
+ conninfo = mock_psycopg.connect.call_args_list[0].args[0]
+ assert "application_name=materialization" in conninfo
diff --git a/products/managed_warehouse/backend/tests/test_client_service_credentials.py b/products/managed_warehouse/backend/tests/test_client_service_credentials.py
index 26fdb768a774..851f732aaba1 100644
--- a/products/managed_warehouse/backend/tests/test_client_service_credentials.py
+++ b/products/managed_warehouse/backend/tests/test_client_service_credentials.py
@@ -48,6 +48,24 @@ class TestMakeDuckgresConninfoWithServiceCredential:
assert "port=443" in conninfo
assert "dbname=ducklake" in conninfo
assert "sslmode=require" in conninfo
+ # Untagged callers still get the default so duckgres can tell them apart
+ # from customer clients (psql, their own application_name).
+ assert "application_name=posthog" in conninfo
+
+ @mock.patch(
+ "products.managed_warehouse.backend.client.get_duckgres_config_for_org",
+ side_effect=AssertionError("DuckgresServer row must not be consulted on the service-credential path"),
+ )
+ @mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=False)
+ def test_application_name_is_forwarded_on_service_credential_path(self, _dev, _config):
+ conninfo = make_duckgres_conninfo(
+ 7,
+ organization_id="org-1",
+ service_credential=_credential("minted-plaintext", credential_id="svc_0123456789abcdef01234567"),
+ application_name="ducklake-register",
+ )
+
+ assert "application_name=ducklake-register" in conninfo
@mock.patch(
"products.managed_warehouse.backend.client.get_duckgres_config_for_org",