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-imports): recover double-encoded source config strings (#68826)

Tom Owerse28040194e94
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py
index 8bf77384390e..7bf5a3f55a30 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/config.py
@@ -1,3 +1,4 @@
+import json
import types
import typing
import reprlib
@@ -72,7 +73,7 @@ class ConfigProtocol(_Dataclass, typing.Protocol):
"""
@classmethod
- def from_dict(cls: type[_T], d: dict[str, typing.Any]) -> _T: ...
+ def from_dict(cls: type[_T], d: dict[str, typing.Any] | str) -> _T: ...
@classmethod
def validate_dict(cls: type[_T], d: dict[str, typing.Any]) -> tuple[bool, list[str]]: ...
@@ -105,7 +106,7 @@ class Config(ConfigProtocol):
"""
@classmethod
- def from_dict(cls: type[_T], d: dict[str, typing.Any]) -> _T:
+ def from_dict(cls: type[_T], d: dict[str, typing.Any] | str) -> _T:
raise NotImplementedError
@classmethod
@@ -606,12 +607,20 @@ def config(
"""
def wrap(cls: type[_T]) -> type[_T]:
- def from_dict(cls, d: dict[str, typing.Any]):
+ def from_dict(cls, d: dict[str, typing.Any] | str):
+ if isinstance(d, str):
+ # Stored config (an `EncryptedJSONField`) can come back double-encoded: a JSON
+ # string holding the mapping rather than the mapping itself. Recover by decoding
+ # it once so the sync proceeds instead of crashing.
+ try:
+ d = json.loads(d)
+ except json.JSONDecodeError:
+ pass
+
if not isinstance(d, dict):
- # Stored config (e.g. an `EncryptedJSONField`) can occasionally come back as a
- # non-mapping (a double-encoded string). Fail with an actionable message instead
- # of the opaque `TypeError: string indices must be integers` raised when `to_config`
- # tries to index into it.
+ # Anything still not a mapping (a non-object JSON value, bytes, ...) can't build a
+ # config. Fail with an actionable message instead of the opaque
+ # `TypeError: string indices must be integers` raised when `to_config` indexes it.
raise TypeError(f"Cannot build '{cls.__name__}' from {type(d).__name__}; expected a mapping")
if prefix:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py
index bffa26fd51c6..f724f55a725d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_config.py
@@ -1,3 +1,4 @@
+import json
import typing
import pytest
@@ -493,14 +494,16 @@ def test_to_config_scalar_under_nested_config_key(
assert cfg.account_id == expected_account_id
[email protected]("bad_input", ["not a mapping", '{"key_file": {}}', b"bytes", 5, ["a", "b"], None])
[email protected]("bad_input", ["not a mapping", '"scalar"', "[1, 2, 3]", b"bytes", 5, ["a", "b"], None])
def test_from_dict_with_non_mapping_raises_clear_error(bad_input):
"""A non-mapping input must raise an actionable error, not the opaque builtin `TypeError`.
Stored config can come back as a non-mapping (e.g. a double-encoded string from an
`EncryptedJSONField`). Indexing into it deep inside `to_config` raised
`TypeError: string indices must be integers`, which is impossible to triage from the
- source alone. `from_dict` must reject it up front with the config class name in the message.
+ source alone. A string that decodes to a mapping is recovered, but any other shape
+ (unparseable text, or JSON that decodes to a scalar/list) must be rejected up front with
+ the config class name in the message.
"""
@config.config
@@ -517,6 +520,24 @@ def test_from_dict_with_non_mapping_raises_clear_error(bad_input):
SourceConfig.from_dict(bad_input)
+def test_from_dict_recovers_double_encoded_json_string():
+ """A config stored as a JSON string (double-encoded by `EncryptedJSONField`) must be
+ decoded back into a working config instead of crashing the sync with `Cannot build ...`.
+ """
+
+ @config.config
+ class SourceConfig(config.Config):
+ host: str
+ port: int = 0
+
+ config_dict = {"host": "example", "port": 5432}
+
+ cfg = SourceConfig.from_dict(json.dumps(config_dict))
+
+ assert cfg.host == "example"
+ assert cfg.port == 5432
+
+
def test_to_config_optional_config_does_not_retain_unparseable_dict():
# A present-but-unparseable mapping under an `Optional[Config]` field must not leak
# through the `None` arm of the union as a raw dict. Doing so left a typed field