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(data-warehouse): keep BigQuery's temporary dataset visible after save (#82149)

Kyle Swank550cea52cc70
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index d43b747a43e4..08012e63df1c 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -317,17 +317,98 @@ def get_oauth_integration_kinds(fields: list[FieldType]) -> set[str]:
return kinds
-def _add_name_variants(target: set[str], name: str) -> None:
- """Add a field name and its underscore variant to a set.
+def _name_variants(name: str) -> tuple[str, ...]:
+ """The spellings a declared field name can be stored under, declared spelling first.
Source field names may use hyphens (e.g. "temporary-dataset") while
dataclasses.asdict() persists the snake_case field name ("temporary_dataset").
- We need to recognise both forms when classifying persisted job_inputs.
"""
- target.add(name)
normalised = name.replace("-", "_")
- if normalised != name:
- target.add(normalised)
+ return (name,) if normalised == name else (name, normalised)
+
+
+def _add_name_variants(target: set[str], name: str) -> None:
+ """Add a field name and its underscore variant to a set.
+
+ We need to recognise both forms when classifying persisted job_inputs.
+ """
+ target.update(_name_variants(name))
+
+
+def _stored_key(data: Mapping[str, Any], name: str) -> str | None:
+ """The key `data` holds a declared field under, or None when it holds neither spelling.
+
+ Prefers the declared spelling when both are present, matching how config parsing
+ resolves the alias.
+ """
+ return next((key for key in _name_variants(name) if key in data), None)
+
+
+def _stored_value(data: Mapping[str, Any], name: str) -> Any:
+ """The value `data` holds for a declared field under either spelling."""
+ key = _stored_key(data, name)
+ return data[key] if key is not None else None
+
+
+@frozen
+class DeclaredFieldNames:
+ """Declared field names that need special handling when reading or merging job_inputs.
+
+ `hyphenated` are names the source declares with a hyphen. `dataclasses.asdict()` persists
+ the Python attribute name instead, so stored configs can hold either spelling.
+ `switch_groups` are switch-group container names, whose stored value is a nested dict.
+ """
+
+ hyphenated: set[str]
+ switch_groups: set[str]
+
+
+def get_declared_field_names(fields: list[FieldType]) -> DeclaredFieldNames:
+ """Collect hyphenated and switch-group field names, flattened across all nesting levels."""
+ hyphenated: set[str] = set()
+ switch_groups: set[str] = set()
+
+ for field in fields:
+ if "-" in field.name:
+ hyphenated.add(field.name)
+ if isinstance(field, SourceFieldSwitchGroupConfig):
+ switch_groups.add(field.name)
+ nested = get_declared_field_names(field.fields)
+ hyphenated.update(nested.hyphenated)
+ switch_groups.update(nested.switch_groups)
+ elif isinstance(field, SourceFieldSelectConfig):
+ for option in field.options:
+ if option.fields:
+ nested = get_declared_field_names(option.fields)
+ hyphenated.update(nested.hyphenated)
+ switch_groups.update(nested.switch_groups)
+
+ return DeclaredFieldNames(hyphenated=hyphenated, switch_groups=switch_groups)
+
+
+def restore_declared_field_names(data: dict, hyphenated: set[str]) -> dict:
+ """Return a copy of data re-keyed to the names the source config declares.
+
+ A hyphenated field round-trips through `dataclasses.asdict()`, which writes the Python
+ attribute name ("temporary_dataset") rather than the declared one ("temporary-dataset").
+ Clients key off the declared name, so restore it. When both spellings are present the
+ declared one wins, matching how config parsing prefers the alias.
+ """
+ if not hyphenated:
+ return data
+
+ variants = {name.replace("-", "_"): name for name in hyphenated}
+ result: dict = {}
+ for key, value in data.items():
+ declared = variants.get(key)
+ if declared is not None:
+ if declared in data:
+ continue
+ key = declared
+ if isinstance(value, dict):
+ value = restore_declared_field_names(value, hyphenated)
+ result[key] = value
+ return result
@frozen
@@ -455,24 +536,34 @@ _NESTED_AUTH_CONTAINERS = ("auth_method", "auth_type")
_CREATION_ONLY_SECRET_FIELDS = frozenset({"connection_string"})
-def has_preserved_credentials(existing: dict[str, Any], incoming: dict[str, Any], sensitive_fields: set[str]) -> bool:
+def has_preserved_credentials(
+ existing: dict[str, Any],
+ incoming: dict[str, Any],
+ sensitive_fields: set[str],
+ nested_containers: Iterable[str] = _NESTED_AUTH_CONTAINERS,
+) -> bool:
"""True if any stored secret would be reused because the update didn't re-supply it.
- Checks both top-level secret fields and the nested auth containers where sources like
+ Checks both top-level secret fields and the nested containers where sources like
ServiceNow, Stripe and Snowflake keep their credentials. Used to force credential
re-entry when the connection target changes, so a redirected host can't receive a
preserved secret. A secret only counts as preserved when it would survive the merge:
an absent container carries the whole existing block over, a same-selection container
preserves any field the update omits, and a selection switch replaces the block wholesale.
+
+ Switch groups merge the same way, so callers pass their names too. A switch group carries
+ no `selection`, which reads as unchanged and lands on the omitted-field check — the branch
+ that matches how the merge treats them. A group declared with a hyphen can be stored under
+ either spelling, so containers are resolved the same way the merge resolves them.
"""
if any(existing.get(key) and not incoming.get(key) for key in sensitive_fields):
return True
- for container_key in _NESTED_AUTH_CONTAINERS:
- existing_container = existing.get(container_key)
+ for container_key in nested_containers:
+ existing_container = _stored_value(existing, container_key)
if not isinstance(existing_container, dict):
continue
- incoming_container = incoming.get(container_key)
+ incoming_container = _stored_value(incoming, container_key)
if not isinstance(incoming_container, dict):
# Container not re-supplied — the existing secrets carry over wholesale.
if any(existing_container.get(key) for key in sensitive_fields):
@@ -1011,7 +1102,9 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
if "require_tls" not in tunnel:
tunnel["require_tls"] = {"enabled": True}
- representation["job_inputs"] = strip_sensitive_from_dict(job_inputs, nonsensitive, split.sensitive)
+ stripped = strip_sensitive_from_dict(job_inputs, nonsensitive, split.sensitive)
+ declared = get_declared_field_names(source.get_source_config.fields)
+ representation["job_inputs"] = restore_declared_field_names(stripped, declared.hyphenated)
return representation
def get_last_run_at(self, instance: ExternalDataSource) -> str | None:
@@ -1126,6 +1219,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
source_type_model = ExternalDataSourceType(instance.source_type)
source = SourceRegistry.get_source(source_type_model)
sensitive_fields = get_sensitive_field_names(source.get_source_config.fields)
+ declared_field_names = get_declared_field_names(source.get_source_config.fields)
discovered_schemas: list[SourceSchema] | None = None
new_job_inputs = {**existing_job_inputs, **incoming_job_inputs}
@@ -1187,7 +1281,10 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
if connection_host_changed or ssh_tunnel_changed or job_inputs_host_added:
gate_sensitive_fields = sensitive_fields - _CREATION_ONLY_SECRET_FIELDS
preserved_credentials = has_preserved_credentials(
- existing_job_inputs, incoming_job_inputs, gate_sensitive_fields
+ existing_job_inputs,
+ incoming_job_inputs,
+ gate_sensitive_fields,
+ nested_containers=(*_NESTED_AUTH_CONTAINERS, *declared_field_names.switch_groups),
)
if preserved_credentials or preserved_row_backed_credentials:
if ssh_tunnel_changed:
@@ -1225,6 +1322,33 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
merged_container[key] = existing_container[key]
new_job_inputs[container_key] = merged_container
+ # Switch groups are nested containers too. The settings form submits only the fields the
+ # user touched and skips a disabled group's children, so a payload that just flips
+ # `enabled` would otherwise replace the whole stored group and drop a required nested
+ # value that validation then rejects. Switching a group off keeps its stored value —
+ # the user hasn't asked to forget it, and consumers gate on `enabled` before reading it.
+ for group_key in declared_field_names.switch_groups:
+ # A group declared with a hyphen can be stored under either spelling (see
+ # `restore_declared_field_names`), so resolve both sides by declared name.
+ incoming_key = _stored_key(incoming_job_inputs, group_key)
+ if incoming_key is None:
+ continue
+ incoming_group = incoming_job_inputs[incoming_key]
+ if not isinstance(incoming_group, dict):
+ raise ValidationError({"job_inputs": {group_key: "Must be an object."}})
+ existing_group = _stored_value(existing_job_inputs, group_key)
+ if not isinstance(existing_group, dict):
+ continue
+ merged_group = {**existing_group, **incoming_group}
+ # No switch group declares a secret today, but keep the carry-over so one could.
+ for key in sensitive_fields:
+ if existing_group.get(key) and not incoming_group.get(key):
+ merged_group[key] = existing_group[key]
+ # Drop the other spelling so parsing can't see two competing groups.
+ for key in _name_variants(group_key):
+ new_job_inputs.pop(key, None)
+ new_job_inputs[incoming_key] = merged_group
+
incoming_ssh_tunnel = incoming_job_inputs.get("ssh_tunnel")
if existing_ssh_tunnel and incoming_ssh_tunnel is not None:
ssh_tunnel_host_changed = "host" in incoming_ssh_tunnel and incoming_ssh_tunnel[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py
index 3c19aa7f4a20..234e05907dbe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_generated_configs.py
@@ -58,7 +58,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
-def test_bigquery_config():
+# The form submits "temporary-dataset", but dataclasses.asdict() persists "temporary_dataset",
+# so a source that has been saved once is read back under the second spelling.
[email protected]("temporary_dataset_key", ["temporary-dataset", "temporary_dataset"])
+def test_bigquery_config(temporary_dataset_key: str):
config = BigQuerySourceConfig.from_dict(
{
"key_file": {
@@ -69,7 +72,7 @@ def test_bigquery_config():
"token_uri": "token_uri",
},
"dataset_id": "dataset_id",
- "temporary-dataset": {"enabled": False, "temporary_dataset_id": ""},
+ temporary_dataset_key: {"enabled": False, "temporary_dataset_id": ""},
"dataset_project": {"enabled": False, "dataset_project_id": ""},
}
)
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 0047053ed2d3..da58ef335322 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -58,9 +58,12 @@ from products.warehouse_sources.backend.presentation.views.external_data_schema
from products.warehouse_sources.backend.presentation.views.external_data_source import (
INVALID_CREDENTIALS_FALLBACK_MESSAGE,
ExternalDataSourceViewSet,
+ get_declared_field_names,
get_direct_connection_metadata,
get_nonsensitive_and_sensitive_field_names,
get_oauth_integration_kinds,
+ has_preserved_credentials,
+ restore_declared_field_names,
strip_sensitive_from_dict,
)
from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
@@ -9052,6 +9055,40 @@ class TestSensitiveFieldClassification(APIBaseTest):
assert result["temporary_dataset"]["enabled"] is True
assert result["temporary_dataset"]["temporary_dataset_id"] == "tmp-dataset"
+ def test_restore_prefers_the_declared_name_when_both_spellings_are_stored(self):
+ fields: list[FieldType] = [
+ SourceFieldSwitchGroupConfig(
+ name="temporary-dataset",
+ label="Temporary dataset",
+ default=False,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="temporary_dataset_id",
+ label="Dataset ID",
+ placeholder="",
+ required=True,
+ type=SourceFieldInputConfigType.TEXT,
+ secret=False,
+ ),
+ ],
+ ),
+ ),
+ ]
+ declared = get_declared_field_names(fields)
+
+ result = restore_declared_field_names(
+ {
+ "temporary-dataset": {"temporary_dataset_id": "declared"},
+ "temporary_dataset": {"temporary_dataset_id": "persisted"},
+ },
+ declared.hyphenated,
+ )
+
+ assert result["temporary-dataset"]["temporary_dataset_id"] == "declared"
+ assert "temporary_dataset" not in result
+
def test_all_registered_sources_have_valid_classification(self):
for source in SourceRegistry.get_all_sources().values():
config = source.get_source_config
@@ -13179,6 +13216,22 @@ class TestGetDirectConnectionMetadata(SimpleTestCase):
mock_capture.assert_called_once_with(error)
+class TestHasPreservedCredentials(SimpleTestCase):
+ # A group declared with a hyphen is persisted under its underscore variant, so a gate that
+ # only looked up the declared spelling would miss the stored secret and let a host change
+ # through without forcing re-entry.
+ @parameterized.expand([("temporary-dataset",), ("temporary_dataset",)])
+ def test_finds_a_secret_stored_under_either_spelling(self, stored_key: str) -> None:
+ preserved = has_preserved_credentials(
+ {stored_key: {"enabled": True, "api_key": "stored"}},
+ {"host": "new-host"},
+ {"api_key"},
+ nested_containers=("temporary-dataset",),
+ )
+
+ assert preserved is True
+
+
class TestGithubMultiRepoPatch(APIBaseTest):
def _create_github_source(self, job_inputs: dict) -> ExternalDataSource:
return ExternalDataSource.objects.create(
@@ -13327,6 +13380,118 @@ class TestGithubMultiRepoPatch(APIBaseTest):
assert removed_webhook_row.deleted is True or removed_webhook_row.should_sync is False
+class TestBigQuerySwitchGroups(APIBaseTest):
+ def _create_bigquery_source(self, job_inputs: dict[str, Any]) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="BigQuery",
+ created_by=self.user,
+ prefix="bq",
+ job_inputs={
+ "key_file": {
+ "project_id": "project_id",
+ "private_key_id": "private_key_id",
+ "private_key": "private_key",
+ "client_email": "client_email",
+ "token_uri": "token_uri",
+ },
+ "dataset_id": "my_dataset",
+ **job_inputs,
+ },
+ )
+
+ # A source saved since migration 0807 stores "temporary_dataset"; one untouched since stores
+ # "temporary-dataset". The settings form only looks for the declared, hyphenated name.
+ @parameterized.expand([("temporary-dataset",), ("temporary_dataset",)])
+ def test_temporary_dataset_reads_back_under_the_declared_name(self, stored_key: str) -> None:
+ source = self._create_bigquery_source({stored_key: {"enabled": True, "temporary_dataset_id": "tmp_dataset"}})
+
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/")
+ assert response.status_code == status.HTTP_200_OK
+
+ job_inputs = response.json()["job_inputs"]
+ assert job_inputs["temporary-dataset"]["temporary_dataset_id"] == "tmp_dataset"
+ assert job_inputs["temporary-dataset"]["enabled"] == "True"
+ # A leftover second spelling would win the settings form's merge and blank the field.
+ assert "temporary_dataset" not in job_inputs
+
+ @parameterized.expand(
+ [
+ ("temporary-dataset", "temporary_dataset", False, "temporary_dataset_id", "tmp_dataset"),
+ ("use_custom_region", "use_custom_region", False, "region", "us-east1"),
+ ("dataset_project", "dataset_project", True, "dataset_project_id", "other_project"),
+ ]
+ )
+ def test_toggling_a_switch_group_keeps_its_stored_value(
+ self, group_key: str, stored_key: str, enabled: bool, nested_key: str, nested_value: str
+ ) -> None:
+ source = self._create_bigquery_source(
+ {
+ "temporary_dataset": {"enabled": True, "temporary_dataset_id": "tmp_dataset"},
+ "use_custom_region": {"enabled": True, "region": "us-east1"},
+ "dataset_project": {"enabled": False, "dataset_project_id": "other_project"},
+ }
+ )
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.source.BigQuerySource.validate_credentials",
+ return_value=(True, None),
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={"job_inputs": {group_key: {"enabled": enabled}}},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ source.refresh_from_db()
+ config = BigQuerySourceConfig.from_dict(source.job_inputs)
+ group = getattr(config, stored_key)
+ assert group is not None
+ assert group.enabled is enabled
+ assert getattr(group, nested_key) == nested_value
+
+ def test_enabling_a_group_the_source_never_stored_keeps_the_submitted_value(self) -> None:
+ source = self._create_bigquery_source({})
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.source.BigQuerySource.validate_credentials",
+ return_value=(True, None),
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={"job_inputs": {"temporary-dataset": {"enabled": True, "temporary_dataset_id": "first_dataset"}}},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ source.refresh_from_db()
+ config = BigQuerySourceConfig.from_dict(source.job_inputs)
+ assert config.temporary_dataset is not None
+ assert config.temporary_dataset.enabled is True
+ assert config.temporary_dataset.temporary_dataset_id == "first_dataset"
+
+ # Merging a non-dict group would raise a TypeError and surface as a 500.
+ def test_a_switch_group_that_is_not_an_object_is_rejected(self) -> None:
+ source = self._create_bigquery_source(
+ {"temporary_dataset": {"enabled": True, "temporary_dataset_id": "tmp_dataset"}}
+ )
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.source.BigQuerySource.validate_credentials",
+ return_value=(True, None),
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={"job_inputs": {"temporary-dataset": "not-an-object"}},
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+
class TestFanoutParentCreation(APIBaseTest):
"""Source creation places no fan-out constraint on the schema selection: any combination of
parent and child creates, and the run-time gate decides per run whether the child can read