: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
fix(data-warehouse): redirect duckdb extension storage (#83187)
Jovan Sakovicbb8155fb42c6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.pyindex 036ecc35e5d4..5f302bc57963 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/motherduck.py@@ -94,15 +94,16 @@ MOTHERDUCK_ERROR_CLASSES = {# Rows materialized per Arrow batch. Bounds resident memory: DuckDB shares this process.DEFAULT_MOTHERDUCK_FETCH_SIZE = 5_000-# DuckDB otherwise sizes itself against the whole host (80% of RAM, one thread per core), which is-# the wrong budget for a library sharing a worker with the rest of the import pipeline.-#-# `home_directory` overrides where DuckDB persists extensions/secrets, which otherwise defaults to-# `~/.duckdb` — unwritable in a locked-down worker container regardless of who owns the process.+_DUCKDB_HOME = os.path.join(tempfile.gettempdir(), "posthog-duckdb-home")++# DuckDB otherwise sizes itself against the whole host, the wrong budget for a library sharing this+# worker. `extension_directory` needs its own override: `home_directory` doesn't move it, so+# extension autoload would try to create the unwritable `~/.duckdb` in the worker.DUCKDB_LOCAL_CONFIG: dict[str, Any] = {"memory_limit": "2GB","threads": 2,- "home_directory": os.path.join(tempfile.gettempdir(), "posthog-duckdb-home"),+ "home_directory": _DUCKDB_HOME,+ "extension_directory": os.path.join(_DUCKDB_HOME, "extensions"),}# The database name is interpolated into the `md:` connection string, so anything outside this@@ -139,9 +140,13 @@ def connect(access_token: str, database: Optional[str] = None, *, read_only: boowrite statement engine-side regardless of what the token is granted."""connection_string = build_motherduck_connection_string(database, access_token)+ config = dict(DUCKDB_LOCAL_CONFIG)+ # Extension autoload runs as the connection opens, so the store has to exist by then. Creating+ # it also creates the home directory above it.+ os.makedirs(config["extension_directory"], exist_ok=True)log_connection_open(db_host=MOTHERDUCK_SERVICE_HOST, via="vendor_https")try:- return duckdb.connect(connection_string, read_only=read_only, config=dict(DUCKDB_LOCAL_CONFIG))+ return duckdb.connect(connection_string, read_only=read_only, config=config)except duckdb.Error as e:raise MotherDuckConnectionError(translate_motherduck_error(e)) from ediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.pyindex c6f891a48846..fcd40467da72 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/motherduck/tests/test_motherduck.py@@ -17,13 +17,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.motherduckMOTHERDUCK_SYSTEM_DATABASES,MotherDuckImplementation,build_motherduck_connection_string,+ connect,filter_motherduck_incremental_fields,translate_motherduck_error,)from products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.source import MotherduckSourcefrom products.warehouse_sources.backend.types import IncrementalFieldType-_CONNECT_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.motherduck.duckdb.connect"+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.motherduck.motherduck"+_CONNECT_PATH = f"{_MODULE}.duckdb.connect"def _make_config(**overrides) -> MotherduckSourceConfig:@@ -176,13 +178,28 @@ class TestMotherDuck:passmock_connect.return_value.execute.assert_not_called()- def test_connect_uses_a_writable_home_directory(self):- # Regression: DuckDB defaults extension/secrets storage to `~/.duckdb`, which raised- # `IOException: Failed to create directory "/root/.duckdb": Permission denied` in a- # worker container where the real home directory isn't writable.- home_directory = DUCKDB_LOCAL_CONFIG["home_directory"]- os.makedirs(home_directory, exist_ok=True)- assert os.access(home_directory, os.W_OK)+ def test_config_redirects_extension_storage_off_the_home_directory(self):+ # `home_directory` alone leaves extension storage at `~/.duckdb`, so it needs its own key.+ assert DUCKDB_LOCAL_CONFIG["extension_directory"] != DUCKDB_LOCAL_CONFIG["home_directory"]+ assert DUCKDB_LOCAL_CONFIG["extension_directory"].startswith(DUCKDB_LOCAL_CONFIG["home_directory"])++ def test_connect_creates_the_configured_extension_store(self, tmp_path):+ # Regression: extension autoload creates `~/.duckdb` on connect, which raised+ # `Failed to create directory "/root/.duckdb": Permission denied` in a locked-down worker.+ # connect() must create the store it configures, so driving it against a fresh base (rather+ # than pre-making the directories) is what catches a dropped or reordered makedirs.+ base = tmp_path / "duckdb-home"+ config = {+ **DUCKDB_LOCAL_CONFIG,+ "home_directory": str(base),+ "extension_directory": str(base / "extensions"),+ }+ with patch(f"{_MODULE}.DUCKDB_LOCAL_CONFIG", config), patch(_CONNECT_PATH) as mock_connect:+ assert not base.exists()+ connect("md-token", "my_db")+ assert os.path.isdir(config["extension_directory"])+ assert os.access(config["extension_directory"], os.W_OK)+ assert mock_connect.call_args.kwargs["config"]["extension_directory"] == config["extension_directory"]def test_connect_closes_on_exit(self, impl):with patch(_CONNECT_PATH) as mock_connect: