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): decode source job inputs stored as a json string (#104457)

Tom Owers54d04c7fa5a1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index 2aa159564ef0..ead5bb02aa1f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -1,3 +1,4 @@
+import json
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING, Any, NoReturn
@@ -78,20 +79,63 @@ def build_non_retryable_errors_redis_key(team_id: int, source_id: str, run_id: s
NON_RETRYABLE_ERROR_RETRY_LIMIT = 3
+UNREADABLE_JOB_INPUTS_MESSAGE = (
+ "Can't read this source's saved connection settings. Reconnect the source to fix the sync."
+)
+
+
+class UnreadableJobInputsError(Exception):
+ """A stored `job_inputs` value that holds no mapping, so no run of this source can read it.
+
+ Raised as the cause of a `NonRetryableException` because the workflow reads the customer-facing
+ error text off the cause, not off the wrapper.
+ """
+
+
+def _decode_job_inputs(job_inputs: str) -> dict[str, Any]:
+ """Recover the config mapping from a `job_inputs` value stored as a JSON string.
+
+ `EncryptedJSONField` encrypts a mapping value by value, but stringifies and encrypts anything
+ else whole, and its read path hands a scalar straight back without parsing it. So a config
+ written as a JSON string instead of a mapping decodes to that same string on every later read,
+ with the mapping still inside it as plain JSON. `Config.from_dict` recovers such a config the
+ same way, so decoding here keeps the two readers in agreement.
+ """
+ try:
+ decoded = json.loads(job_inputs)
+ except ValueError:
+ # Text that holds no JSON and JSON that holds no mapping leave the caller with the same
+ # unusable config, so both take the branch below.
+ decoded = None
+
+ if not isinstance(decoded, dict):
+ raise NonRetryableException() from UnreadableJobInputsError(UNREADABLE_JOB_INPUTS_MESSAGE)
+
+ return decoded
+
+
async def trim_source_job_inputs(source: "ExternalDataSource") -> None:
- # job_inputs is an EncryptedJSONField, so it can decode to a non-dict (e.g. a bare string)
- # for a malformed source config — nothing to trim key-by-key in that case.
- if not isinstance(source.job_inputs, dict):
+ decoded_from_string = isinstance(source.job_inputs, str)
+ if decoded_from_string:
+ job_inputs = _decode_job_inputs(source.job_inputs)
+ elif isinstance(source.job_inputs, dict):
+ job_inputs = source.job_inputs
+ else:
+ # An unconfigured source (`None`) or any other non-mapping has no keys to trim. The config
+ # parse in the import activity reports an unusable value.
return
- did_update_inputs = False
- for key, value in source.job_inputs.items():
+ # A value decoded out of a string is saved even when no key needs trimming, so the row is
+ # rewritten as a mapping once instead of every run reading the string back.
+ did_update_inputs = decoded_from_string
+ for key, value in job_inputs.items():
if isinstance(value, str):
if value.startswith(" ") or value.endswith(" "):
- source.job_inputs[key] = value.strip()
+ job_inputs[key] = value.strip()
did_update_inputs = True
if did_update_inputs:
+ source.job_inputs = job_inputs
await database_sync_to_async_pool(source.save)()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
index 15f614284320..128824970958 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py
@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.models.oom_event import ExternalDataSche
from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
NON_RETRYABLE_ERROR_RETRY_LIMIT,
+ UNREADABLE_JOB_INPUTS_MESSAGE,
_get_redis,
handle_corrupted_delta_log,
handle_non_retryable_error,
@@ -149,9 +150,6 @@ class TestPersistPrimaryKeys:
class TestTrimSourceJobInputs:
@parameterized.expand(
[
- # A non-empty string decoded out of the EncryptedJSONField used to reach `.items()` and
- # raise AttributeError — it must be skipped, not crash the whole import activity.
- ("bare_string_is_skipped", "not-a-dict"),
("list_is_skipped", ["a", "b"]),
("none_is_skipped", None),
("empty_dict_is_skipped", {}),
@@ -164,6 +162,52 @@ class TestTrimSourceJobInputs:
await trim_source_job_inputs(source)
pool.assert_not_called()
+ @parameterized.expand(
+ [
+ # A config stored as a JSON string decodes back to that string on every read, so it used
+ # to reach `.items()` and raise AttributeError. It must decode to the mapping, and the
+ # row must be rewritten as a mapping even when no value needs trimming, so the next run
+ # reads a mapping.
+ (
+ "padded_value_is_trimmed",
+ '{"host": " db.example.com ", "port": "5432"}',
+ {"host": "db.example.com", "port": "5432"},
+ ),
+ (
+ "unpadded_values_are_still_normalized",
+ '{"host": "db.example.com", "port": "5432"}',
+ {"host": "db.example.com", "port": "5432"},
+ ),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_json_string_job_inputs_is_decoded_and_saved(self, _name: str, job_inputs, expected) -> None:
+ source = MagicMock(job_inputs=job_inputs, save=MagicMock())
+ saved = AsyncMock()
+ with patch(f"{_EXTRACT_MODULE}.database_sync_to_async_pool", return_value=saved):
+ await trim_source_job_inputs(source)
+ assert source.job_inputs == expected
+ saved.assert_awaited_once()
+
+ @parameterized.expand(
+ [
+ # Nothing recovers a mapping from these, and every run fails the same way, so the sync
+ # gives up with an error the customer can act on instead of an AttributeError.
+ ("not_json", "not-a-dict"),
+ ("json_scalar", '"db.example.com"'),
+ ("json_list", "[1, 2]"),
+ ("blank", ""),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_unreadable_string_job_inputs_fails_non_retryably(self, _name: str, job_inputs) -> None:
+ source = MagicMock(job_inputs=job_inputs, save=MagicMock())
+ with patch(f"{_EXTRACT_MODULE}.database_sync_to_async_pool") as pool:
+ with pytest.raises(NonRetryableException) as caught:
+ await trim_source_job_inputs(source)
+ pool.assert_not_called()
+ assert str(caught.value.cause) == UNREADABLE_JOB_INPUTS_MESSAGE
+
@pytest.mark.asyncio
async def test_dict_job_inputs_is_trimmed_and_saved(self) -> None:
source = MagicMock(job_inputs={"host": " example.com ", "port": "5432"}, save=MagicMock())