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.

chore(data-warehouse): route source job_inputs through one store (#124069)

Tom Owers29492b8f89b5
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index 2394f998f6fc..4f964872da7f 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -389,7 +389,7 @@ Guidelines:
Each top-level key in a source's `job_inputs` has one kind. The kind decides where the value is stored. `sources/common/job_input_classification.py` resolves it.
-- **Connection** (the default): a value needed to authenticate or reach the third party. Examples are API keys, tokens, passwords, credential IDs (`aws_access_key_id`, `key_id`), host, port, user, database name, account, tenant or project ids, region, base URLs, the SSH tunnel, TLS certificates and keys, auth-method selects and OAuth `*_integration_id` pointers. Connection values move to an `Integration` row for the source, so do not read them from the model field directly.
+- **Connection** (the default): a value needed to authenticate or reach the third party. Examples are API keys, tokens, passwords, credential IDs (`aws_access_key_id`, `key_id`), host, port, user, database name, account, tenant or project ids, region, base URLs, the SSH tunnel, TLS certificates and keys, auth-method selects and OAuth `*_integration_id` pointers. Connection values move to an `Integration` row for the source, so do not read them from the model field directly. Use `SourceInputsStore` (below).
- **Sync setting**: a value that only chooses what or how to sync. Examples are table or schema selection, a table prefix, start dates, file patterns and formats, delimiters, `repositories` and filters. Set `sync_setting=True` on the field. The flag exists on `SourceFieldInputConfig`, `SourceFieldSelectConfig`, `SourceFieldSwitchGroupConfig` and `SourceFieldOauthAccountSelectConfig`. It is valid only on top-level fields. It does not appear in the API payload or the generated types.
- **Runtime**: state the server writes, not the user. Keys that start with `cdc_` are runtime for every source. For other server-written keys, set `runtime_job_input_keys` on the source class (see `FileUploadSource`).
@@ -400,6 +400,22 @@ Rules:
- Never set `sync_setting=True` on a field that is `secret=True`, a password or a file upload. The invariant test fails otherwise.
- Every new source and every field change needs the audit CSV regenerated (step 6 of the workflow).
+#### Reading and writing `job_inputs`
+
+Read and write a source's `job_inputs` only through `SourceInputsStore` (`products/warehouse_sources/backend/logic/source_inputs.py`). Code outside the product, and code in its presentation layer, imports it from `facade/source_inputs.py`. The store lets the connection fields move to their own storage without a change to your code.
+
+- `SourceInputsStore.load(source)` gives all inputs as a new dict. Use it before `parse_config`.
+- `SourceInputsStore.load_many(sources)` gives the inputs of many sources, keyed by source id. Use it on list paths.
+- `SourceInputsStore.load_settings(source)` gives only the sync settings and runtime keys. It never gives a connection field. Use it for reads such as `schema` or `cdc_*` keys on hot paths.
+- `SourceInputsStore.save(source, inputs)` replaces all inputs and saves them. Use it for a credential write, for example a refreshed token.
+- `SourceInputsStore.assign(source, inputs)` sets the inputs without a save. Use it when you save the model yourself in the same write.
+- `SourceInputsStore.create(inputs=..., **fields)` creates a source.
+- `SourceInputsStore.update_runtime(source, updates, remove=...)` sets or removes runtime keys and saves. It raises `ValueError` for a key that is not a runtime key.
+- In async code, use `aload` and `asave`.
+- `load` raises `UnreadableSourceInputsError` when the stored value is not a mapping. Catch it where the old code accepted a bad value.
+
+The semgrep rule `warehouse-source-inputs-go-through-store` blocks `source.job_inputs` and `job_inputs=` on `ExternalDataSource` outside the store. Tests and migrations can still set the field directly.
+
## Implementing `source_for_pipeline`
Return a `SourceResponse` directly. **Do not** use `dlt_source_to_source_response` for new sources — DLT is being removed.
diff --git a/.semgrep/rules/devex/warehouse-source-inputs-go-through-store.py b/.semgrep/rules/devex/warehouse-source-inputs-go-through-store.py
new file mode 100644
index 000000000000..91e9e29c6db9
--- /dev/null
+++ b/.semgrep/rules/devex/warehouse-source-inputs-go-through-store.py
@@ -0,0 +1,57 @@
+# Test cases for warehouse-source-inputs-go-through-store.
+# ruff: noqa
+
+
+class ExternalDataSource:
+ job_inputs: dict = {}
+ objects = None
+
+
+class SourceInputsStore:
+ pass
+
+
+source = ExternalDataSource()
+queryset = None
+
+# ruleid: warehouse-source-inputs-go-through-store
+password = source.job_inputs["password"]
+
+# ruleid: warehouse-source-inputs-go-through-store
+schema = (source.job_inputs or {}).get("schema")
+
+# ruleid: warehouse-source-inputs-go-through-store
+source.job_inputs = {"host": "db.example.com"}
+
+# ruleid: warehouse-source-inputs-go-through-store
+inputs = getattr(source, "job_inputs", None)
+
+# ruleid: warehouse-source-inputs-go-through-store
+ExternalDataSource.objects.create(team_id=1, job_inputs={"host": "db.example.com"})
+
+# ruleid: warehouse-source-inputs-go-through-store
+new_source = ExternalDataSource(team_id=1, job_inputs={})
+
+# ruleid: warehouse-source-inputs-go-through-store
+queryset.update(job_inputs={})
+
+# ok: warehouse-source-inputs-go-through-store
+inputs = SourceInputsStore.load(source)
+
+# ok: warehouse-source-inputs-go-through-store
+SourceInputsStore.create(inputs={"host": "db.example.com"}, team_id=1)
+
+# ok: warehouse-source-inputs-go-through-store
+ExternalDataSource.objects.only("id", "job_inputs").defer("job_inputs")
+
+# ok: warehouse-source-inputs-go-through-store
+source.save(update_fields=["job_inputs", "updated_at"])
+
+
+def run(job_inputs: dict) -> None:
+ # ok: warehouse-source-inputs-go-through-store
+ parse(job_inputs=job_inputs)
+
+
+def parse(job_inputs: dict) -> dict:
+ return job_inputs
diff --git a/.semgrep/rules/devex/warehouse-source-inputs-go-through-store.yaml b/.semgrep/rules/devex/warehouse-source-inputs-go-through-store.yaml
new file mode 100644
index 000000000000..561c4c969927
--- /dev/null
+++ b/.semgrep/rules/devex/warehouse-source-inputs-go-through-store.yaml
@@ -0,0 +1,44 @@
+rules:
+ - id: warehouse-source-inputs-go-through-store
+ message: |
+ Raw access to `ExternalDataSource.job_inputs`. The field mixes connection credentials, sync
+ settings and runtime state, and the credentials are moving to a separate store. Read and write
+ it only through `SourceInputsStore` (`products/warehouse_sources/backend/logic/source_inputs.py`,
+ or `products/warehouse_sources/backend/facade/source_inputs.py` outside the product):
+ `load` / `load_many` for all inputs, `load_settings` for sync settings and `cdc_*` / upload
+ keys only, `save` / `assign` / `create` for writes, and `update_runtime` for runtime keys.
+
+ String field names in `.only(...)`, `.defer(...)` and `update_fields` are fine. For a genuine
+ exception, add `# nosemgrep: warehouse-source-inputs-go-through-store -- <reason>` on the line.
+ severity: ERROR
+ languages: [python]
+ paths:
+ include:
+ - 'common/**/*.py'
+ - 'ee/**/*.py'
+ - 'posthog/**/*.py'
+ - 'products/**/*.py'
+ exclude:
+ # The store is the only reader and writer of the field.
+ - '/products/warehouse_sources/backend/logic/source_inputs.py'
+ # The model defines the field.
+ - '/products/warehouse_sources/backend/models/external_data_source.py'
+ # ZendeskImportJob has its own unrelated `job_inputs` field.
+ - '/products/conversations/**'
+ - '**/test/**'
+ - '**/tests/**'
+ - '**/test_*.py'
+ - '**/*_test.py'
+ - '**/conftest*.py'
+ - '**/migrations/**'
+ pattern-either:
+ - pattern: $SOURCE.job_inputs
+ - pattern: getattr($SOURCE, "job_inputs", ...)
+ - pattern: setattr($SOURCE, "job_inputs", ...)
+ - pattern: ExternalDataSource(..., job_inputs=$INPUTS, ...)
+ - pattern: ExternalDataSource.$MANAGER.$METHOD(..., job_inputs=$INPUTS, ...)
+ - pattern: $QUERYSET.update(..., job_inputs=$INPUTS, ...)
+ metadata:
+ category: best-practice
+ subcategory:
+ - audit
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 2121779e9c4f..5990f20b4531 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -1982,6 +1982,9 @@ class Database(BaseModel):
DataWarehouseTable,
ExternalDataSource,
)
+ from products.warehouse_sources.backend.facade.source_inputs import ( # noqa: PLC0415 - avoids the model import cycle
+ SourceInputsStore,
+ )
from products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode # noqa: PLC0415
with timings.measure("team", emit_span=True):
@@ -2189,7 +2192,7 @@ class Database(BaseModel):
warehouse_tables: list[DataWarehouseTable] = []
# The virtual builder reads job_inputs (deferred above); hydrate it here so the
# build phase stays query-free.
- _ = virtual_source.job_inputs
+ SourceInputsStore.load(virtual_source)
with timings.measure("select_virtual_schemas", emit_span=True):
# Function-local: keeps the direct-SQL driver imports off the django.setup() path.
from products.data_warehouse.backend.facade.direct_query import ( # noqa: PLC0415
diff --git a/posthog/hogql/direct_sql/adapter.py b/posthog/hogql/direct_sql/adapter.py
index 06f76db0df1d..ba127f0d5883 100644
--- a/posthog/hogql/direct_sql/adapter.py
+++ b/posthog/hogql/direct_sql/adapter.py
@@ -6,6 +6,8 @@ from posthog.hogql.constants import HogQLDialect, HogQLGlobalSettings
from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.timings import HogQLTimings
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
+
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -29,7 +31,7 @@ def parse_direct_source_config(source_impl: _ParseableSource[_ConfigT_co], sourc
it to a clean user-facing error instead.
"""
try:
- return source_impl.parse_config(source.job_inputs or {})
+ return source_impl.parse_config(SourceInputsStore.load(source))
except (TypeError, ValueError) as error:
raise ExposedHogQLError("This source is missing its connection configuration.") from error
diff --git a/posthog/hogql/direct_sql/duckgres_adapter.py b/posthog/hogql/direct_sql/duckgres_adapter.py
index 53ddb2fda413..3277ce8be3da 100644
--- a/posthog/hogql/direct_sql/duckgres_adapter.py
+++ b/posthog/hogql/direct_sql/duckgres_adapter.py
@@ -38,6 +38,7 @@ from posthog.psycopg_helpers import resolve_psycopg_hostaddr_with_timeout
from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseSourceAuth, ServiceCredentialUnavailable
from products.managed_warehouse.backend.facade.sql_editor import resolve_managed_warehouse_postgres_connection
from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore, UnreadableSourceInputsError
if TYPE_CHECKING:
from psycopg.pq.abc import PGresult
@@ -343,9 +344,10 @@ class DuckgresRawAdapter:
if source.team_id != team.pk or not source.is_managed_warehouse_ready:
raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)
- job_inputs = source.job_inputs
- if not isinstance(job_inputs, dict):
- raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)
+ try:
+ job_inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError as error:
+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR) from error
host = job_inputs.get("host")
database = job_inputs.get("database")
diff --git a/products/data_warehouse/backend/clickhouse_helpers.py b/products/data_warehouse/backend/clickhouse_helpers.py
index 6e1ee982df03..9dfd46600220 100644
--- a/products/data_warehouse/backend/clickhouse_helpers.py
+++ b/products/data_warehouse/backend/clickhouse_helpers.py
@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.facade.models import (
clickhouse_column_to_dwh_column,
clickhouse_columns_to_dwh_columns,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
SourceSchema,
extract_available_column_names,
@@ -137,7 +138,7 @@ def reconcile_clickhouse_schemas(
is_direct = source.is_direct_query
source_schema_names = [s.name for s in source_schemas]
- default_database = (source.job_inputs or {}).get("database")
+ default_database = SourceInputsStore.load(source).get("database")
schema_models = {
s.name: s
for s in ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False).select_related(
@@ -258,7 +259,7 @@ def reproject_direct_clickhouse_table(
source_database, source_table_name = get_clickhouse_source_location(
schema_name=schema_row.name,
schema_metadata=schema_row.schema_metadata,
- default_database=(source.job_inputs or {}).get("database"),
+ default_database=SourceInputsStore.load(source).get("database"),
)
return upsert_direct_clickhouse_table(
schema_row.table,
diff --git a/products/data_warehouse/backend/direct_virtual_tables.py b/products/data_warehouse/backend/direct_virtual_tables.py
index 09c8a994cb0c..253160116fc1 100644
--- a/products/data_warehouse/backend/direct_virtual_tables.py
+++ b/products/data_warehouse/backend/direct_virtual_tables.py
@@ -49,6 +49,7 @@ from products.data_warehouse.backend.snowflake_helpers import (
)
from products.warehouse_sources.backend.facade.hogql import hogql_fields_and_structure_for_columns
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.projection import (
filter_dwh_columns_by_enabled_columns,
)
@@ -111,7 +112,7 @@ def build_direct_table_for_schema(schema: "ExternalDataSchema", source: "Externa
catalog, postgres_schema, table_name = get_postgres_source_location(
schema_name=schema.name,
schema_metadata=metadata,
- default_schema=(source.job_inputs or {}).get("schema"),
+ default_schema=SourceInputsStore.load_settings(source).get("schema"),
)
return DirectPostgresTable(
name=schema.name,
@@ -224,7 +225,7 @@ def build_direct_table_for_schema(schema: "ExternalDataSchema", source: "Externa
clickhouse_database, table_name = get_clickhouse_source_location(
schema_name=schema.name,
schema_metadata=metadata,
- default_database=(source.job_inputs or {}).get("database"),
+ default_database=SourceInputsStore.load(source).get("database"),
)
return DirectClickHouseTable(
name=schema.name,
diff --git a/products/data_warehouse/backend/motherduck_helpers.py b/products/data_warehouse/backend/motherduck_helpers.py
index 8d5d78f354f9..e9dad911e5b2 100644
--- a/products/data_warehouse/backend/motherduck_helpers.py
+++ b/products/data_warehouse/backend/motherduck_helpers.py
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.facade.models import (
motherduck_column_to_dwh_column,
motherduck_columns_to_dwh_columns,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
SourceSchema,
extract_available_column_names,
@@ -43,7 +44,7 @@ type MotherDuckSourceLocation = tuple[str | None, str, str] # (database, schema
def get_default_motherduck_catalog(source: ExternalDataSource) -> str | None:
- database = (source.job_inputs or {}).get("database")
+ database = SourceInputsStore.load(source).get("database")
return database if isinstance(database, str) and database.strip() else None
diff --git a/products/data_warehouse/backend/mysql_helpers.py b/products/data_warehouse/backend/mysql_helpers.py
index bc794e01a2c0..a42bf56cc049 100644
--- a/products/data_warehouse/backend/mysql_helpers.py
+++ b/products/data_warehouse/backend/mysql_helpers.py
@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.facade.models import (
mysql_column_to_dwh_column,
mysql_columns_to_dwh_columns,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
SourceSchema,
extract_available_column_names,
@@ -46,7 +47,7 @@ type MySQLSourceLocation = tuple[str, str]
def get_default_mysql_schema(source: ExternalDataSource) -> str | None:
"""The configured MySQL namespace, preserving old rows that predate the explicit `schema` key."""
- job_inputs = source.job_inputs or {}
+ job_inputs = SourceInputsStore.load(source)
if "schema" in job_inputs:
return normalize_namespace(job_inputs.get("schema"))
return normalize_namespace(job_inputs.get("database"))
diff --git a/products/data_warehouse/backend/postgres_helpers.py b/products/data_warehouse/backend/postgres_helpers.py
index 0d469b649144..07280db0e473 100644
--- a/products/data_warehouse/backend/postgres_helpers.py
+++ b/products/data_warehouse/backend/postgres_helpers.py
@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.facade.models import (
postgres_column_to_dwh_column,
postgres_columns_to_dwh_columns,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
SourceSchema,
extract_available_column_names,
@@ -168,7 +169,7 @@ def reconcile_postgres_schemas(
is_direct = source.is_direct_query
source_schema_names = [s.name for s in source_schemas]
- default_schema = (source.job_inputs or {}).get("schema")
+ default_schema = SourceInputsStore.load_settings(source).get("schema")
schema_models = {
s.name: s for s in ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False)
}
@@ -306,7 +307,7 @@ def reproject_direct_postgres_table(
source_catalog, source_schema, source_table_name = get_postgres_source_location(
schema_name=schema_row.name,
schema_metadata=schema_row.schema_metadata,
- default_schema=(source.job_inputs or {}).get("schema"),
+ default_schema=SourceInputsStore.load_settings(source).get("schema"),
)
return upsert_direct_postgres_table(
schema_row.table,
@@ -339,7 +340,7 @@ def rename_postgres_schemas_to_match_source_schemas(
"""
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
- default_schema = (source.job_inputs or {}).get("schema")
+ default_schema = SourceInputsStore.load_settings(source).get("schema")
schema_models = list(
ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False).select_related("table")
)
diff --git a/products/data_warehouse/backend/redshift_helpers.py b/products/data_warehouse/backend/redshift_helpers.py
index 7efabcaa6a37..f8e62cb56a6a 100644
--- a/products/data_warehouse/backend/redshift_helpers.py
+++ b/products/data_warehouse/backend/redshift_helpers.py
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.facade.models import (
postgres_column_to_dwh_column,
postgres_columns_to_dwh_columns,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
SourceSchema,
extract_available_column_names,
@@ -45,14 +46,14 @@ type RedshiftSourceLocation = tuple[str | None, str, str] # (catalog, schema, t
def get_default_redshift_schema(source: ExternalDataSource) -> str | None:
- job_inputs = source.job_inputs or {}
+ job_inputs = SourceInputsStore.load_settings(source)
if "schema" in job_inputs:
return normalize_namespace(job_inputs.get("schema"))
return None
def get_default_redshift_catalog(source: ExternalDataSource) -> str | None:
- database = (source.job_inputs or {}).get("database")
+ database = SourceInputsStore.load(source).get("database")
return database if isinstance(database, str) and database.strip() else None
diff --git a/products/data_warehouse/backend/snowflake_helpers.py b/products/data_warehouse/backend/snowflake_helpers.py
index 46d0c6cc8d0a..362189ee5ae3 100644
--- a/products/data_warehouse/backend/snowflake_helpers.py
+++ b/products/data_warehouse/backend/snowflake_helpers.py
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.facade.models import (
snowflake_column_to_dwh_column,
snowflake_columns_to_dwh_columns,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
SourceSchema,
extract_available_column_names,
@@ -46,14 +47,14 @@ type SnowflakeSourceLocation = tuple[str | None, str, str] # (catalog, schema,
def get_default_snowflake_schema(source: ExternalDataSource) -> str | None:
"""Get the default schema for a Snowflake source, if any."""
- job_inputs = source.job_inputs or {}
+ job_inputs = SourceInputsStore.load_settings(source)
if "schema" in job_inputs:
return normalize_namespace(job_inputs.get("schema"))
return None
def get_default_snowflake_catalog(source: ExternalDataSource) -> str | None:
- database = (source.job_inputs or {}).get("database")
+ database = SourceInputsStore.load(source).get("database")
return database if isinstance(database, str) and database.strip() else None
diff --git a/products/data_warehouse/backend/sql_warehouse_migration.py b/products/data_warehouse/backend/sql_warehouse_migration.py
index 14e1c05caa33..4d806ca85e4b 100644
--- a/products/data_warehouse/backend/sql_warehouse_migration.py
+++ b/products/data_warehouse/backend/sql_warehouse_migration.py
@@ -10,6 +10,7 @@ from __future__ import annotations
from typing import Any
from products.warehouse_sources.backend.facade.models import ExternalDataSource
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
DottedNameParts,
SourceRegistry,
@@ -49,7 +50,7 @@ def is_multi_schema_capable_sql_source(source_type: ExternalDataSourceType | str
def source_namespace_is_blank(source: ExternalDataSource) -> bool:
"""True when the source's `job_inputs.schema` is unset — i.e. it's in multi-schema mode."""
- schema = (source.job_inputs or {}).get("schema")
+ schema = SourceInputsStore.load_settings(source).get("schema")
return not (isinstance(schema, str) and schema.strip())
@@ -180,7 +181,7 @@ def apply_on_refresh(*, source: ExternalDataSource, team_id: int) -> dict[str, s
else:
unqualified_rows.append(row)
- default_schema = normalize_namespace((source.job_inputs or {}).get("schema"))
+ default_schema = normalize_namespace(SourceInputsStore.load_settings(source).get("schema"))
name_substitutions: dict[str, str] = {}
for legacy in unqualified_rows:
diff --git a/products/data_warehouse/backend/temporal/health_checks/webhook_subscription_stale.py b/products/data_warehouse/backend/temporal/health_checks/webhook_subscription_stale.py
index 791bd7dc6eb8..229fb7cfa6f2 100644
--- a/products/data_warehouse/backend/temporal/health_checks/webhook_subscription_stale.py
+++ b/products/data_warehouse/backend/temporal/health_checks/webhook_subscription_stale.py
@@ -9,6 +9,7 @@ from posthog.temporal.health_checks.framework import AlertContent, HealthCheck,
from posthog.temporal.health_checks.models import HealthCheckResult
from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
logger = structlog.get_logger(__name__)
@@ -81,8 +82,6 @@ class WebhookSubscriptionStaleCheck(HealthCheck):
sources: dict[str, ExternalDataSource] = {}
for schema in stale_schemas:
source = schema.source
- if source is None or not source.job_inputs:
- continue
schemas_by_source.setdefault(str(source.pk), []).append(schema)
sources[str(source.pk)] = source
@@ -108,7 +107,10 @@ class WebhookSubscriptionStaleCheck(HealthCheck):
webhook_url = get_webhook_url(hog_function.id)
try:
- config = source_impl.parse_config(source.job_inputs)
+ inputs = SourceInputsStore.load(source)
+ if not inputs:
+ continue
+ config = source_impl.parse_config(inputs)
api_version = source_impl.resolve_api_version(source.api_version)
external = source_impl.get_external_webhook_info(
config, webhook_url, source.team_id, api_version=api_version
diff --git a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py b/products/data_warehouse/backend/test/test_sql_warehouse_migration.py
index 27494cc9ec2c..ca5fc0b0f886 100644
--- a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py
+++ b/products/data_warehouse/backend/test/test_sql_warehouse_migration.py
@@ -78,7 +78,15 @@ class TestMultiSchemaCapability:
]
)
def test_source_namespace_is_blank(self, _name: str, job_inputs: dict[str, Any] | None, expected: bool) -> None:
- assert source_namespace_is_blank(cast(ExternalDataSource, SimpleNamespace(job_inputs=job_inputs))) is expected
+ assert (
+ source_namespace_is_blank(
+ cast(
+ ExternalDataSource,
+ SimpleNamespace(source_type=ExternalDataSourceType.POSTGRES, job_inputs=job_inputs),
+ )
+ )
+ is expected
+ )
class TestDetectSchemaClearTransition:
diff --git a/products/data_warehouse/backend/trino_helpers.py b/products/data_warehouse/backend/trino_helpers.py
index f83a28e87be3..96187384fa7a 100644
--- a/products/data_warehouse/backend/trino_helpers.py
+++ b/products/data_warehouse/backend/trino_helpers.py
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.facade.models import (
trino_column_to_dwh_column,
trino_columns_to_dwh_columns,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
SourceSchema,
extract_available_column_names,
@@ -44,7 +45,7 @@ type TrinoSourceLocation = tuple[str | None, str, str] # (database, schema, tab
def get_default_trino_catalog(source: ExternalDataSource) -> str | None:
- catalog = (source.job_inputs or {}).get("catalog")
+ catalog = SourceInputsStore.load(source).get("catalog")
return catalog if isinstance(catalog, str) and catalog.strip() else None
diff --git a/products/engineering_analytics/backend/logic/job_logs/coordinator.py b/products/engineering_analytics/backend/logic/job_logs/coordinator.py
index d42e8d14b73c..afe4335fd32d 100644
--- a/products/engineering_analytics/backend/logic/job_logs/coordinator.py
+++ b/products/engineering_analytics/backend/logic/job_logs/coordinator.py
@@ -48,6 +48,7 @@ from products.engineering_analytics.backend.logic.queries._test_spans import rer
from products.engineering_analytics.backend.logic.sources import depot_source_job_attempts_table
from products.engineering_analytics.backend.logic.views.depot_ci import depot_github_run_id, depot_id_to_int
from products.warehouse_sources.backend.facade.models import ExternalDataSource
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
logger = structlog.get_logger(__name__)
@@ -159,7 +160,11 @@ def _discover_jobs_with_diagnostics(cutoff_iso: str) -> list[dict[str, Any]]:
eligible_sources = 0
skipped_sources = 0
for source in _live_sources(ExternalDataSourceType.GITHUB):
- params = _github_source_params(source.job_inputs)
+ try:
+ inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
+ continue
+ params = _github_source_params(inputs)
prefix = source.prefix or ""
if params is None or not _PREFIX.match(prefix):
continue
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index a07593b61c79..db3af1551a43 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -39,6 +39,7 @@ from products.engineering_analytics.backend.facade.contracts import (
from products.engineering_analytics.backend.logic.views import depot_ci, workflow_jobs
from products.engineering_analytics.backend.logic.views.source_schema import OPTIONAL_WORKFLOW_RUNS_COLUMNS
from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.facade.sources import github_schema_repo_endpoint
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
@@ -372,7 +373,10 @@ def resolve_trunk_quarantined_tests_source(
if table is None or table.deleted or not _IDENTIFIER.match(table.name):
continue
# job_inputs is an EncryptedJSONField and can hold any JSON shape.
- inputs = source.job_inputs if isinstance(source.job_inputs, dict) else {}
+ try:
+ inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
+ inputs = {}
resolved = TrunkQuarantineSource(table=table.name, org_url_slug=inputs.get("org_url_slug") or None)
owner, name = inputs.get("repo_owner") or "", inputs.get("repo_name") or ""
if f"{owner}/{name}".lower() == repository.lower():
@@ -511,8 +515,9 @@ def _source_repository(source: ExternalDataSource) -> str:
(list/str) would crash the ``.get`` below — guard it the same way ``job_logs.coordinator``
does, since this resolves for every engineering_analytics endpoint.
"""
- job_inputs = source.job_inputs
- if not isinstance(job_inputs, dict):
+ try:
+ job_inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
return ""
return str(job_inputs.get("repository") or "").strip()
@@ -526,8 +531,9 @@ def _configured_repositories(source: ExternalDataSource) -> list[str]:
dropped case-insensitively (GitHub full names are case-insensitive). ``job_inputs`` is an
``EncryptedJSONField`` that can hold any JSON value, so a non-dict yields no repos.
"""
- job_inputs = source.job_inputs
- if not isinstance(job_inputs, dict):
+ try:
+ job_inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
return []
repositories = job_inputs.get("repositories")
# An empty `repositories` list means "unset" — the sync-side parser falls back to the single
@@ -614,7 +620,10 @@ def depot_source_api_token(team: Team, source_id: str) -> str | None:
"""The Depot organization API token a team's Depot source syncs with, or None."""
source = _accessible_sources(team, ExternalDataSourceType.DEPOT, None).filter(id=source_id).first()
# job_inputs is an EncryptedJSONField and can hold any JSON shape.
- inputs = source.job_inputs if source is not None and isinstance(source.job_inputs, dict) else {}
+ try:
+ inputs = SourceInputsStore.load(source) if source is not None else {}
+ except UnreadableSourceInputsError:
+ inputs = {}
api_token = inputs.get("api_token")
return api_token if isinstance(api_token, str) and api_token else None
diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
index ad10a05218d8..e7af0b0906f1 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -79,6 +79,7 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSource,
get_or_create_datawarehouse_credential,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.types import (
DataWarehouseTableFormat,
ExternalDataSourceStatus,
@@ -1520,21 +1521,22 @@ class Command(BaseCommand):
) -> ExternalDataSource:
source = ExternalDataSource.objects.filter(team=team, source_id=source_id, source_type=source_type).first()
if source is None:
- return ExternalDataSource.objects.create(
+ return SourceInputsStore.create(
team=team,
source_id=source_id,
connection_id=source_id,
status=ExternalDataSourceStatus.COMPLETED,
source_type=source_type,
prefix=prefix,
- job_inputs=dict(job_inputs),
+ inputs=dict(job_inputs),
)
update_fields = []
if source.prefix != prefix:
source.prefix = prefix
update_fields.append("prefix")
- if any((source.job_inputs or {}).get(key) != value for key, value in job_inputs.items()):
- source.job_inputs = {**(source.job_inputs or {}), **job_inputs}
+ inputs = SourceInputsStore.load(source)
+ if any(inputs.get(key) != value for key, value in job_inputs.items()):
+ SourceInputsStore.assign(source, {**inputs, **job_inputs})
update_fields.append("job_inputs")
if update_fields:
source.save(update_fields=[*update_fields, "updated_at"])
diff --git a/products/managed_warehouse/backend/logic/connection.py b/products/managed_warehouse/backend/logic/connection.py
index f0dc808ecbf4..0718693bf3ed 100644
--- a/products/managed_warehouse/backend/logic/connection.py
+++ b/products/managed_warehouse/backend/logic/connection.py
@@ -51,6 +51,7 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSchema,
ExternalDataSource,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.facade.source_management import SourceRegistry, SourceSchema
from products.warehouse_sources.backend.facade.types import (
ExternalDataSourceAccessMethod,
@@ -163,7 +164,7 @@ def _set_dynamic_source_auth(source: ExternalDataSource, *, lifecycle_generation
source.access_method = ExternalDataSourceAccessMethod.DIRECT
source.direct_query_enabled = True
source.connection_metadata = _dynamic_source_metadata(lifecycle_generation=lifecycle_generation)
- source.job_inputs = {}
+ SourceInputsStore.assign(source, {})
source.deleted = False
source.deleted_at = None
source.save(
@@ -265,14 +266,14 @@ def _ensure_managed_source_locked(
if tombstoned_legacy is not None:
return _set_dynamic_source_auth(tombstoned_legacy, lifecycle_generation=lifecycle_generation)
- return ExternalDataSource.objects.create(
+ return SourceInputsStore.create(
source_id=str(uuid4()),
connection_id=str(uuid4()),
destination_id=str(uuid4()),
team_id=team_id,
status=ExternalDataSourceStatus.RUNNING,
source_type=ExternalDataSourceType.POSTGRES,
- job_inputs={},
+ inputs={},
prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
description=MANAGED_WAREHOUSE_SOURCE_DESCRIPTION,
access_method=ExternalDataSourceAccessMethod.DIRECT,
@@ -493,7 +494,7 @@ def _discover_postgres_schemas(
"password": dynamic_connection.password,
}
if dynamic_connection is not None
- else dict(source.job_inputs or {})
+ else SourceInputsStore.load(source)
)
config = source_impl.parse_config(source_config)
return source_impl.get_schemas(
@@ -557,9 +558,13 @@ def update_managed_warehouse_root_password(*, organization_id: str | UUID, passw
MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,
}:
continue
- if source.job_inputs != config:
- source.job_inputs = config
- source.save(update_fields=["job_inputs", "updated_at"])
+ try:
+ current = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
+ # Malformed legacy inputs are replaced with the valid config, not left to block rotation.
+ current = None
+ if current != config:
+ SourceInputsStore.save(source, config)
def soft_delete_managed_warehouse_sources(*, organization_id: str | UUID, expected_generation: int) -> None:
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 9b55d6c2c35c..59c5f03044ad 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -899,11 +899,9 @@ warehouse_sources.ExternalDataSource products.data_warehouse.backend.presentatio
warehouse_sources.ExternalDataSource products.engineering_analytics.backend.logic.job_logs.coordinator instance-many(select_related) 1
warehouse_sources.ExternalDataSource products.engineering_analytics.backend.logic.sources instance-many(order_by) 1
warehouse_sources.ExternalDataSource products.engineering_analytics.backend.management.commands.seed_engineering_analytics instance-single 1
-warehouse_sources.ExternalDataSource products.engineering_analytics.backend.management.commands.seed_engineering_analytics write(create) 1
warehouse_sources.ExternalDataSource products.engineering_analytics.backend.tasks.tasks instance-many(distinct) 1
warehouse_sources.ExternalDataSource products.managed_warehouse.backend.logic.connection instance-many(exclude) 1
warehouse_sources.ExternalDataSource products.managed_warehouse.backend.logic.connection instance-many(filter) 1
-warehouse_sources.ExternalDataSource products.managed_warehouse.backend.logic.connection write(create) 1
warehouse_sources.ExternalDataSource products.marketing_analytics.backend.demo.health write(create) 1
warehouse_sources.ExternalDataSource products.marketing_analytics.backend.demo.health write(update) 1
warehouse_sources.ExternalDataSource products.marketing_analytics.backend.hogql_queries.adapters.factory instance-many(filter) 1
diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.py
index 2a81abd78987..d1bc206fe376 100644
--- a/products/warehouse_sources/backend/facade/contracts.py
+++ b/products/warehouse_sources/backend/facade/contracts.py
@@ -28,6 +28,11 @@ class UnsupportedSyncTypeError(ValueError):
"""The stored sync type is not a mode PostHog can run."""
+class UnreadableSourceInputsError(ValueError):
+ """A source's stored inputs do not decode to a mapping. The message never holds the value, because the
+ value can hold credentials."""
+
+
class UndecryptedConfigError(ValueError):
"""Raised when a config value reaches conversion still Fernet-encrypted.
diff --git a/products/warehouse_sources/backend/facade/source_inputs.py b/products/warehouse_sources/backend/facade/source_inputs.py
new file mode 100644
index 000000000000..71b62f53d438
--- /dev/null
+++ b/products/warehouse_sources/backend/facade/source_inputs.py
@@ -0,0 +1,24 @@
+"""Source inputs wiring for other products and for this product's presentation layer.
+
+Code outside the logic layer reads and writes a source's ``job_inputs`` only through this class, never
+through the model field. Each method delegates to the store in ``logic/source_inputs.py``.
+"""
+
+from products.warehouse_sources.backend.facade.contracts import UnreadableSourceInputsError
+from products.warehouse_sources.backend.logic import source_inputs as _store
+
+
+class SourceInputsStore:
+ load = staticmethod(_store.SourceInputsStore.load)
+ load_many = staticmethod(_store.SourceInputsStore.load_many)
+ load_settings = staticmethod(_store.SourceInputsStore.load_settings)
+ stored_as_string = staticmethod(_store.SourceInputsStore.stored_as_string)
+ assign = staticmethod(_store.SourceInputsStore.assign)
+ save = staticmethod(_store.SourceInputsStore.save)
+ create = staticmethod(_store.SourceInputsStore.create)
+ update_runtime = staticmethod(_store.SourceInputsStore.update_runtime)
+ aload = staticmethod(_store.SourceInputsStore.aload)
+ asave = staticmethod(_store.SourceInputsStore.asave)
+
+
+__all__ = ["SourceInputsStore", "UnreadableSourceInputsError"]
diff --git a/products/warehouse_sources/backend/file_upload_sources.py b/products/warehouse_sources/backend/file_upload_sources.py
index 196cc273008a..2286008c633f 100644
--- a/products/warehouse_sources/backend/file_upload_sources.py
+++ b/products/warehouse_sources/backend/file_upload_sources.py
@@ -40,6 +40,7 @@ from products.warehouse_sources.backend.file_uploads import (
UploadLocation,
parse_hosted_upload,
)
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.external_data_destination import (
ExternalDataSourceDestination,
get_or_create_warehouse_destination,
@@ -192,7 +193,7 @@ def create_source_for_upload(
job_inputs: dict[str, Any],
connection_metadata: dict[str, Any] | None = None,
) -> ExternalDataSource:
- source = ExternalDataSource.objects.create(
+ source = SourceInputsStore.create(
source_id=str(uuid.uuid4()),
connection_id=str(uuid.uuid4()),
destination_id=str(uuid.uuid4()),
@@ -200,7 +201,7 @@ def create_source_for_upload(
status=ExternalDataSource.Status.RUNNING,
source_type=file_upload_source().source_type,
api_version=file_upload_source().default_version,
- job_inputs=job_inputs,
+ inputs=job_inputs,
description=f"Uploaded file for {table.name}"[:400],
access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
created_by=table.created_by,
@@ -331,10 +332,11 @@ def replace_file_upload(schema: ExternalDataSchema, upload: UploadedFile, read_s
if latest_job is not None and latest_job.status == ExternalDataJobStatus.RUNNING:
raise FileUploadSourceError("A sync of this table is running. Replace the file once it finishes.")
try:
- current: HostedUpload | None = upload_from_job_inputs(source.team_id, source.job_inputs)
+ current: HostedUpload | None = upload_from_job_inputs(
+ source.team_id, SourceInputsStore.load_settings(source)
+ )
except InvalidUploadError:
current = None
- source.job_inputs = {**(source.job_inputs or {}), **upload_job_inputs(upload, schema.name)}
now = timezone.now()
recorded = {entry.upload for entry in superseded_uploads(source)}
replaced: list[HostedUpload] = [old for old in (current, _file_read_in_place(schema)) if old is not None]
@@ -343,7 +345,9 @@ def replace_file_upload(schema: ExternalDataSchema, upload: UploadedFile, read_s
source.connection_metadata = connection_metadata_with_superseded(
source, SupersededUpload(upload=old, superseded_at=now)
)
- source.save(update_fields=["job_inputs", "connection_metadata", "updated_at"])
+ SourceInputsStore.update_runtime(
+ source, upload_job_inputs(upload, schema.name), extra_update_fields=("connection_metadata", "updated_at")
+ )
previous = TableDefinition.from_schema_metadata(schema.name, schema.schema_metadata)
# Keep the column naming the table already has, so queries written against it keep working.
diff --git a/products/warehouse_sources/backend/github_warehouse_repos.py b/products/warehouse_sources/backend/github_warehouse_repos.py
index 7e727b1a2a36..e9af39014b7f 100644
--- a/products/warehouse_sources/backend/github_warehouse_repos.py
+++ b/products/warehouse_sources/backend/github_warehouse_repos.py
@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.facade.models import (
)
from products.warehouse_sources.backend.facade.source_management import GithubSource, GithubSourceConfig, SourceRegistry
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore, UnreadableSourceInputsError
logger = structlog.get_logger(__name__)
@@ -62,10 +63,14 @@ def github_source_credential(*, team_id: int, source_id: str) -> GitHubSourceCre
return None
# ``job_inputs`` is an ``EncryptedJSONField`` that can hold any JSON value, and a half-written
# source is a normal state, so an unreadable config is no reason to fail the consumer.
- if not isinstance(source.job_inputs, dict):
+ try:
+ inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
+ return None
+ if not inputs:
return None
try:
- config = GithubSourceConfig.from_dict(source.job_inputs)
+ config = GithubSourceConfig.from_dict(inputs)
except Exception:
logger.warning("github_source_credential_config_unreadable", source_id=str(source.pk))
return None
diff --git a/products/warehouse_sources/backend/logic/__init__.py b/products/warehouse_sources/backend/logic/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/logic/source_inputs.py b/products/warehouse_sources/backend/logic/source_inputs.py
new file mode 100644
index 000000000000..cf79de4565c2
--- /dev/null
+++ b/products/warehouse_sources/backend/logic/source_inputs.py
@@ -0,0 +1,190 @@
+"""The only code that reads or writes ``ExternalDataSource.job_inputs``.
+
+``job_inputs`` holds connection fields, sync settings and runtime state in one blob. Callers go
+through ``SourceInputsStore`` so that the storage of each part can change without a change to the
+callers. A semgrep rule (`warehouse-source-inputs-go-through-store`) blocks raw access elsewhere.
+"""
+
+import json
+from collections.abc import Iterable, Mapping, Sequence
+from typing import TYPE_CHECKING, Any
+from uuid import UUID
+
+from posthog.sync import database_sync_to_async_pool
+
+from products.warehouse_sources.backend.facade.contracts import UnreadableSourceInputsError
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_input_classification import (
+ SplitJobInputs,
+ )
+
+DEFAULT_EXTRA_UPDATE_FIELDS: tuple[str, ...] = ("updated_at",)
+
+
+class SourceInputsStore:
+ @staticmethod
+ def load(source: ExternalDataSource) -> dict[str, Any]:
+ """All inputs of the source: connection fields, sync settings and runtime state.
+
+ The result is a new dict, so a change to it has no effect until a write method saves it.
+ """
+ return _decode(source.job_inputs)
+
+ @staticmethod
+ def load_many(sources: Iterable[ExternalDataSource]) -> dict[UUID, dict[str, Any]]:
+ """`load` for each source, keyed by source id. Use it on list paths, so that a later
+ storage can fetch all sources in one batch.
+
+ A source whose inputs do not decode is left out, so one bad row does not fail a whole list.
+ A caller that needs that source calls `load` and handles the error.
+ """
+ loaded: dict[UUID, dict[str, Any]] = {}
+ for source in sources:
+ try:
+ loaded[source.id] = _decode(source.job_inputs)
+ except UnreadableSourceInputsError:
+ continue
+ return loaded
+
+ @staticmethod
+ def load_settings(source: ExternalDataSource) -> dict[str, Any]:
+ """Only the sync settings and runtime state of the source, never a connection field.
+
+ Use it for reads such as the default ``schema`` or the ``cdc_*`` keys. The result does not
+ need the connection storage, so it stays cheap on hot paths.
+ """
+ inputs = _decode(source.job_inputs)
+ try:
+ split = _split(source.source_type, inputs)
+ except ValueError:
+ # An unknown source type declares no settings. Every key except the runtime prefixes is then a
+ # connection field, which is the safe side for a reader that must not see credentials.
+ return {key: value for key, value in inputs.items() if _has_runtime_prefix(key)}
+ return {**split.settings, **split.runtime}
+
+ @staticmethod
+ def stored_as_string(source: ExternalDataSource) -> bool:
+ """True when the inputs were stored as one JSON string instead of a mapping.
+
+ EncryptedJSONField encrypts a string value whole, so such a row reads back as a string on every
+ read. A caller can rewrite it once as a mapping with `save`.
+ """
+ return isinstance(source.job_inputs, str)
+
+ @staticmethod
+ def assign(source: ExternalDataSource, inputs: Mapping[str, Any]) -> None:
+ """Stage all inputs on the source without a database write. The caller must save the model.
+
+ Use it when the caller saves the model for other reasons too, for example a DRF serializer
+ update, so that the source row gets one write.
+ """
+ source.job_inputs = dict(inputs)
+
+ @staticmethod
+ def save(
+ source: ExternalDataSource,
+ inputs: Mapping[str, Any],
+ *,
+ extra_update_fields: Sequence[str] = DEFAULT_EXTRA_UPDATE_FIELDS,
+ ) -> None:
+ """Replace all inputs of the source and save them."""
+ SourceInputsStore.assign(source, inputs)
+ source.save(update_fields=["job_inputs", *extra_update_fields])
+
+ @staticmethod
+ def create(*, inputs: Mapping[str, Any], **fields: Any) -> ExternalDataSource:
+ """Create a source with these inputs in one insert. ``fields`` are the other model fields."""
+ source = ExternalDataSource(**fields)
+ SourceInputsStore.assign(source, inputs)
+ source.save(force_insert=True)
+ return source
+
+ @staticmethod
+ def update_runtime(
+ source: ExternalDataSource,
+ updates: Mapping[str, Any] | None = None,
+ *,
+ remove: Iterable[str] = (),
+ extra_update_fields: Sequence[str] = DEFAULT_EXTRA_UPDATE_FIELDS,
+ ) -> dict[str, Any]:
+ """Set and remove runtime keys (``cdc_*``, file upload keys) and save. Returns all inputs.
+
+ A runtime write never touches a connection field. A key that is not a runtime key of the source
+ raises ValueError, because a credential written here would skip the connection storage.
+ """
+ updates = dict(updates or {})
+ remove = list(remove)
+ _check_runtime_keys(source.source_type, [*updates, *remove])
+
+ inputs = _decode(source.job_inputs)
+ inputs.update(updates)
+ for key in remove:
+ inputs.pop(key, None)
+ SourceInputsStore.save(source, inputs, extra_update_fields=extra_update_fields)
+ return inputs
+
+ @staticmethod
+ async def aload(source: ExternalDataSource) -> dict[str, Any]:
+ return await database_sync_to_async_pool(SourceInputsStore.load)(source)
+
+ @staticmethod
+ async def asave(
+ source: ExternalDataSource,
+ inputs: Mapping[str, Any],
+ *,
+ extra_update_fields: Sequence[str] = DEFAULT_EXTRA_UPDATE_FIELDS,
+ ) -> None:
+ await database_sync_to_async_pool(SourceInputsStore.save)(
+ source, inputs, extra_update_fields=extra_update_fields
+ )
+
+
+def _decode(raw: Any) -> dict[str, Any]:
+ if raw is None:
+ return {}
+ if isinstance(raw, Mapping):
+ return dict(raw)
+ if not isinstance(raw, str):
+ raise UnreadableSourceInputsError(f"job_inputs is a {type(raw).__name__}, expected a mapping")
+ try:
+ decoded = json.loads(raw)
+ except ValueError as e:
+ raise UnreadableSourceInputsError("job_inputs is a string that does not decode as JSON") from e
+ if not isinstance(decoded, Mapping):
+ raise UnreadableSourceInputsError(f"job_inputs decoded to a {type(decoded).__name__}, expected a mapping")
+ return dict(decoded)
+
+
+def _split(source_type: str, inputs: Mapping[str, Any]) -> "SplitJobInputs":
+ # noqa below: the classification loads the source registry and the generated source configs. The
+ # store sits on the model import path (HogQL database build, managed warehouse checks), so it loads
+ # them only when a settings read or a runtime write needs them.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_input_classification import ( # noqa: PLC0415
+ split_job_inputs,
+ )
+
+ return split_job_inputs(ExternalDataSourceType(source_type), inputs)
+
+
+def _has_runtime_prefix(key: str) -> bool:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_input_classification import ( # noqa: PLC0415
+ RUNTIME_KEY_PREFIXES,
+ )
+
+ return key.startswith(RUNTIME_KEY_PREFIXES)
+
+
+def _check_runtime_keys(source_type: str, keys: Iterable[str]) -> None:
+ keys = list(keys)
+ if not keys:
+ return
+ try:
+ split = _split(source_type, dict.fromkeys(keys))
+ non_runtime = sorted({*split.connection, *split.settings})
+ except ValueError:
+ non_runtime = sorted(key for key in keys if not _has_runtime_prefix(key))
+ if non_runtime:
+ raise ValueError(f"Not runtime keys for a {source_type} source: {', '.join(non_runtime)}")
diff --git a/products/warehouse_sources/backend/management/commands/backfill_mongodb_server_versions.py b/products/warehouse_sources/backend/management/commands/backfill_mongodb_server_versions.py
index 95f7d45226ef..b3edd5961b87 100644
--- a/products/warehouse_sources/backend/management/commands/backfill_mongodb_server_versions.py
+++ b/products/warehouse_sources/backend/management/commands/backfill_mongodb_server_versions.py
@@ -13,6 +13,7 @@ from django.core.management.base import BaseCommand, CommandParser
import structlog
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -117,14 +118,22 @@ class Command(BaseCommand):
# A source with no stored credentials has nothing to connect with, and reaching one costs a
# full server-selection timeout, so drop those before probing rather than counting them as
# failures.
- return [source for source in sources if source.job_inputs]
+ configured_sources: list[ExternalDataSource] = []
+ for source in sources:
+ try:
+ if not SourceInputsStore.load(source):
+ continue
+ except UnreadableSourceInputsError:
+ pass
+ configured_sources.append(source)
+ return configured_sources
def _probe(self, source_impl: Any, source: ExternalDataSource) -> dict[str, Any] | None:
# An unreachable or misconfigured cluster is the common case here, not an exception worth
# stopping for: this command's whole purpose is to survey a population that includes broken
# sources, so a failure is logged and the survey continues.
try:
- config = source_impl.parse_config(source.job_inputs)
+ config = source_impl.parse_config(SourceInputsStore.load(source))
metadata = source_impl.get_server_metadata(config, source.team_id)
except Exception as error:
logger.warning(
diff --git a/products/warehouse_sources/backend/management/commands/repin_stripe_webhook_api_version.py b/products/warehouse_sources/backend/management/commands/repin_stripe_webhook_api_version.py
index 8f4613c78e03..ec2c84a91fea 100644
--- a/products/warehouse_sources/backend/management/commands/repin_stripe_webhook_api_version.py
+++ b/products/warehouse_sources/backend/management/commands/repin_stripe_webhook_api_version.py
@@ -9,6 +9,7 @@ from posthog.dataclasses import frozen
from products.cdp.backend.facade.models import HogFunction
from products.data_warehouse.backend.facade.api import get_webhook_url, store_webhook_extra_inputs
from products.warehouse_sources.backend.facade.source_management import SourceRegistry
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.stripe import StripeSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSource
@@ -124,14 +125,17 @@ class Command(BaseCommand):
inputs__source_id__value=str(source_model.id),
deleted=False,
).first()
- if hog_function is None or not source_model.job_inputs:
+ if hog_function is None:
continue
- webhook_url = get_webhook_url(str(hog_function.id))
- target_api_version = source.resolve_api_version(source_model.api_version)
-
try:
- config = source.parse_config(source_model.job_inputs)
+ inputs = SourceInputsStore.load(source_model)
+ if not inputs:
+ continue
+
+ webhook_url = get_webhook_url(str(hog_function.id))
+ target_api_version = source.resolve_api_version(source_model.api_version)
+ config = source.parse_config(inputs)
info = source.get_external_webhook_info(config, webhook_url, source_model.team_id)
except Exception as e:
self.stdout.write(
diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.py
index 8c9fe91be80f..0507d6d6b3f8 100644
--- a/products/warehouse_sources/backend/models/external_data_source.py
+++ b/products/warehouse_sources/backend/models/external_data_source.py
@@ -198,8 +198,14 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
)
def _has_valid_managed_warehouse_connection_inputs(self, *, expected_user: str | None = None) -> bool:
- job_inputs = self.job_inputs
- if not isinstance(job_inputs, dict):
+ from products.warehouse_sources.backend.logic.source_inputs import ( # noqa: PLC0415 - the store imports this model
+ SourceInputsStore,
+ UnreadableSourceInputsError,
+ )
+
+ try:
+ job_inputs = SourceInputsStore.load(self)
+ except UnreadableSourceInputsError:
return False
port = job_inputs.get("port")
@@ -251,18 +257,26 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
@property
def is_dynamic_managed_warehouse(self) -> bool:
- metadata = self.connection_metadata
- return (
- self.is_managed_warehouse
- and self.direct_query_enabled
- and isinstance(metadata, dict)
- and metadata.get("credential_kind") == MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND
- and isinstance(metadata.get("lifecycle_generation"), int)
- and not isinstance(metadata.get("lifecycle_generation"), bool)
- and metadata["lifecycle_generation"] >= 0
- and self.job_inputs == {}
+ from products.warehouse_sources.backend.logic.source_inputs import ( # noqa: PLC0415 - the store imports this model
+ SourceInputsStore,
+ UnreadableSourceInputsError,
)
+ metadata = self.connection_metadata
+ try:
+ return (
+ self.is_managed_warehouse
+ and self.direct_query_enabled
+ and isinstance(metadata, dict)
+ and metadata.get("credential_kind") == MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND
+ and isinstance(metadata.get("lifecycle_generation"), int)
+ and not isinstance(metadata.get("lifecycle_generation"), bool)
+ and metadata["lifecycle_generation"] >= 0
+ and SourceInputsStore.load(self) == {}
+ )
+ except UnreadableSourceInputsError:
+ return False
+
@property
def managed_warehouse_sql_mode(self) -> ManagedWarehouseSQLMode:
# Accepted interim contract for the default-off rollout: provisioning already exposes organization-root
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index d99a27a9c167..bed2ecc563d5 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -1086,6 +1086,9 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
DIRECT_TRINO_SCHEMA_OPTION,
DIRECT_TRINO_TABLE_OPTION,
)
+ from products.warehouse_sources.backend.logic.source_inputs import ( # noqa: PLC0415 - the store imports this model package
+ SourceInputsStore,
+ )
columns = self.columns or {}
@@ -1110,7 +1113,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
postgres_schema = (
self.options.get(DIRECT_POSTGRES_SCHEMA_OPTION)
if isinstance(self.options.get(DIRECT_POSTGRES_SCHEMA_OPTION), str)
- else (self.external_data_source.job_inputs or {}).get("schema", "public")
+ else SourceInputsStore.load_settings(self.external_data_source).get("schema", "public")
)
postgres_table_name = (
self.options.get(DIRECT_POSTGRES_TABLE_OPTION)
@@ -1129,7 +1132,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
)
if self.external_data_source and self.external_data_source.is_direct_mysql:
- job_inputs = self.external_data_source.job_inputs or {}
+ job_inputs = SourceInputsStore.load(self.external_data_source)
mysql_schema = (
self.options.get(DIRECT_MYSQL_SCHEMA_OPTION)
if isinstance(self.options.get(DIRECT_MYSQL_SCHEMA_OPTION), str)
@@ -1150,7 +1153,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
)
if self.external_data_source and self.external_data_source.is_direct_snowflake:
- job_inputs = self.external_data_source.job_inputs or {}
+ job_inputs = SourceInputsStore.load(self.external_data_source)
snowflake_catalog = (
self.options.get(DIRECT_SNOWFLAKE_CATALOG_OPTION)
if isinstance(self.options.get(DIRECT_SNOWFLAKE_CATALOG_OPTION), str)
@@ -1179,7 +1182,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
if self.external_data_source and self.external_data_source.is_direct_redshift:
# Redshift is a Postgres fork and reuses DirectPostgresTable's schema-qualified,
# double-quoted table-reference rendering (see DirectRedshiftTable).
- job_inputs = self.external_data_source.job_inputs or {}
+ job_inputs = SourceInputsStore.load(self.external_data_source)
redshift_catalog = (
self.options.get(DIRECT_REDSHIFT_CATALOG_OPTION)
if isinstance(self.options.get(DIRECT_REDSHIFT_CATALOG_OPTION), str)
@@ -1212,7 +1215,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
and self.external_data_source.is_direct_query
and self.external_data_source.direct_engine == "motherduck"
):
- job_inputs = self.external_data_source.job_inputs or {}
+ job_inputs = SourceInputsStore.load(self.external_data_source)
motherduck_database = (
self.options.get(DIRECT_MOTHERDUCK_CATALOG_OPTION)
if isinstance(self.options.get(DIRECT_MOTHERDUCK_CATALOG_OPTION), str)
@@ -1244,7 +1247,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
and self.external_data_source.is_direct_query
and (self.external_data_source.direct_engine == "trino" or is_managed_trino_table)
):
- job_inputs = self.external_data_source.job_inputs or {}
+ job_inputs = SourceInputsStore.load(self.external_data_source)
trino_catalog = (
self.options.get(DIRECT_TRINO_CATALOG_OPTION)
if isinstance(self.options.get(DIRECT_TRINO_CATALOG_OPTION), str)
@@ -1280,7 +1283,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
and self.external_data_source.is_direct_query
and self.external_data_source.direct_engine == "clickhouse"
):
- job_inputs = self.external_data_source.job_inputs or {}
+ job_inputs = SourceInputsStore.load(self.external_data_source)
# Every direct-ClickHouse table is discovered from the source's single configured
# database, so the live source config is authoritative. Prefer it over the per-table
# option, which can be stale — e.g. stored as "default" when the source was first synced
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index 8fc90f1ecb9b..bebd98e8810c 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -62,6 +62,7 @@ from products.warehouse_sources.backend.facade.models import (
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.facade.pipelines import finish_row_tracking
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.facade.source_management import (
BUFFER_LANE,
CDC_RESET_PENDING_KEY,
@@ -1719,7 +1720,11 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
def _is_webhook_only_schema(self, schema: ExternalDataSchema) -> bool:
source = schema.source
- if not source.job_inputs:
+ try:
+ source_inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
+ return False
+ if not source_inputs:
return False
try:
source_type = ExternalDataSourceType(source.source_type)
@@ -1727,7 +1732,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
except Exception:
return False
try:
- config = source_impl.parse_config(source.job_inputs)
+ config = source_impl.parse_config(source_inputs)
source_schemas = source_impl.get_schemas(
config,
schema.team_id,
@@ -1743,12 +1748,16 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
materialized view, PG13+). Runs discovery so a raw PATCH can't enable xmin on a table that
has no physical `xmin` (plain views, foreign tables, partitioned parents)."""
source = schema.source
- if not source.job_inputs:
+ try:
+ source_inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
+ return False
+ if not source_inputs:
return False
try:
source_type = ExternalDataSourceType(source.source_type)
source_impl = SourceRegistry.get_source(source_type)
- config = source_impl.parse_config(source.job_inputs)
+ config = source_impl.parse_config(source_inputs)
source_schemas = source_impl.get_schemas(
config,
schema.team_id,
@@ -1791,7 +1800,8 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
def _maybe_create_webhook(self, schema: ExternalDataSchema) -> None:
source = schema.source
- if not source.job_inputs:
+ source_inputs = SourceInputsStore.load(source)
+ if not source_inputs:
return
try:
@@ -1805,7 +1815,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
return
try:
- config = source_impl.parse_config(source.job_inputs)
+ config = source_impl.parse_config(source_inputs)
except (UndecryptedConfigError, ConfigValueError) as e:
raise ValidationError(UNREADABLE_SOURCE_CONFIG_ERROR) from e
# Source pin only: webhook-sync schemas cannot carry a schema-level override (validate()
@@ -1903,7 +1913,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers
_, db_schema, source_table_name = get_postgres_source_location(
schema_name=instance.name,
schema_metadata=instance.schema_metadata,
- default_schema=(source.job_inputs or {}).get("schema"),
+ default_schema=SourceInputsStore.load_settings(source).get("schema"),
)
newly_set_to_cdc = (
@@ -2152,7 +2162,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
_, db_schema, source_table_name = get_postgres_source_location(
schema_name=instance.name,
schema_metadata=instance.schema_metadata,
- default_schema=(source.job_inputs or {}).get("schema"),
+ default_schema=SourceInputsStore.load_settings(source).get("schema"),
)
adapter.remove_table(source, db_schema, source_table_name)
except Exception:
@@ -2462,7 +2472,8 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
instance: ExternalDataSchema = self.get_object()
source: ExternalDataSource = instance.source
- if not source.job_inputs:
+ source_inputs = SourceInputsStore.load(source)
+ if not source_inputs:
return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": "Missing job inputs"})
if not source.source_type:
@@ -2472,7 +2483,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
new_source = SourceRegistry.get_source(source_type_enum)
try:
- config = new_source.parse_config(source.job_inputs)
+ config = new_source.parse_config(source_inputs)
except (UndecryptedConfigError, ConfigValueError):
return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": UNREADABLE_SOURCE_CONFIG_ERROR})
@@ -2550,7 +2561,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# job_inputs is an EncryptedJSONField: booleans round-trip as "True"/"False"
# strings, so bool(...) would treat "False" as truthy. str_to_bool decodes both.
- source_cdc_enabled = str_to_bool(source.job_inputs.get("cdc_enabled"))
+ source_cdc_enabled = str_to_bool(SourceInputsStore.load_settings(source).get("cdc_enabled"))
source_impl = SourceRegistry.get_source(ExternalDataSourceType(source.source_type))
cdc_available = schema.supports_cdc if is_cdc_enabled_for_team(self.team) and source_cdc_enabled else None
# xmin is source-capability-gated, mirroring the database_schema endpoint.
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py b/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py
index 39c9478a7363..3b11bf4c09ea 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSource,
update_sync_type_config_keys,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
DEFAULT_LAG_CRITICAL_THRESHOLD_MB,
DEFAULT_LAG_WARNING_THRESHOLD_MB,
@@ -143,8 +144,8 @@ class ExternalDataSourceCDCMixin(base.ExternalDataSourceViewSetBase):
resource_keys=sorted(resource_fields.keys()),
)
- job_inputs = dict(source_model.job_inputs or {})
- job_inputs.update(
+ SourceInputsStore.update_runtime(
+ source_model,
{
"cdc_enabled": True,
"cdc_auto_drop_slot": payload.get("cdc_auto_drop_slot", True),
@@ -154,11 +155,9 @@ class ExternalDataSourceCDCMixin(base.ExternalDataSourceViewSetBase):
"cdc_lag_critical_threshold_mb": payload.get(
"cdc_lag_critical_threshold_mb", DEFAULT_LAG_CRITICAL_THRESHOLD_MB
),
- }
+ **resource_fields,
+ },
)
- job_inputs.update(resource_fields)
- source_model.job_inputs = job_inputs
- source_model.save(update_fields=["job_inputs", "updated_at"])
return None
@extend_schema(
@@ -298,7 +297,7 @@ class ExternalDataSourceCDCMixin(base.ExternalDataSourceViewSetBase):
data={"message": "cdc_management_mode must be 'posthog' or 'self_managed'."},
)
- schema_hint = (instance.job_inputs or {}).get("schema") or "public"
+ schema_hint = SourceInputsStore.load_settings(instance).get("schema") or "public"
try:
prereq_errors = adapter.validate_prerequisites(
instance,
@@ -374,7 +373,7 @@ class ExternalDataSourceCDCMixin(base.ExternalDataSourceViewSetBase):
)
# Validate prerequisites server-side — never trust a client-only check.
- schema_hint = (instance.job_inputs or {}).get("schema") or "public"
+ schema_hint = SourceInputsStore.load_settings(instance).get("schema") or "public"
try:
prereq_errors = adapter.validate_prerequisites(
instance,
@@ -559,12 +558,10 @@ class ExternalDataSourceCDCMixin(base.ExternalDataSourceViewSetBase):
# Clear ALL cdc_* keys from job_inputs — leaving stale engine identifiers
# behind (e.g. `cdc_consistent_point`) would corrupt resume tracking if
# CDC is later re-enabled.
- job_inputs = dict(instance.job_inputs or {})
- for key in list(job_inputs.keys()):
- if key.startswith("cdc_"):
- job_inputs.pop(key, None)
- instance.job_inputs = job_inputs
- instance.save(update_fields=["job_inputs", "updated_at"])
+ SourceInputsStore.update_runtime(
+ instance,
+ remove=[key for key in SourceInputsStore.load_settings(instance) if key.startswith("cdc_")],
+ )
for schema in history_schemas:
report_history_toggled(
@@ -777,7 +774,7 @@ class ExternalDataSourceCDCMixin(base.ExternalDataSourceViewSetBase):
data={"message": "CDC is not enabled on this source."},
)
- job_inputs = dict(instance.job_inputs or {})
+ job_inputs = SourceInputsStore.load_settings(instance)
updates: dict[str, Any] = {}
if "cdc_auto_drop_slot" in request.data:
@@ -810,9 +807,7 @@ class ExternalDataSourceCDCMixin(base.ExternalDataSourceViewSetBase):
if not updates:
return Response(status=status.HTTP_200_OK, data={"success": True, "unchanged": True})
- job_inputs.update(updates)
- instance.job_inputs = job_inputs
- instance.save(update_fields=["job_inputs", "updated_at"])
+ SourceInputsStore.update_runtime(instance, updates)
return Response(status=status.HTTP_200_OK, data={"success": True})
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py
index 8dee8bf21267..03586a5738f4 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSource,
ExternalDataSourceDestination,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind, ExternalDataSourceType
from products.warehouse_sources.backend.presentation.views.destination_links import (
DestinationLinkSerializer,
@@ -82,9 +83,20 @@ class ExternalDataSourceConnectionMetadataSerializer(serializers.Serializer):
)
+class _DefaultSchemaField(serializers.CharField):
+ def to_representation(self, value: Any) -> Any:
+ # `source="*"` passes the whole ExternalDataSource, not a string.
+ try:
+ schema = SourceInputsStore.load_settings(value).get("schema")
+ except UnreadableSourceInputsError:
+ # One unreadable row must not fail the whole connections list.
+ return None
+ return None if schema is None else str(schema)
+
+
class ExternalDataSourceConnectionOptionSerializer(serializers.ModelSerializer):
- schema_name = serializers.CharField(
- source="job_inputs.schema",
+ schema_name = _DefaultSchemaField(
+ source="*",
read_only=True,
allow_null=True,
help_text="Default database schema used to group tables in the SQL editor.",
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
index 2706f6ee8ac6..a15374e4b534 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py
@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldSSHTunnelConfig,
SourceFieldSwitchGroupConfig,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.facade.source_management import (
DATABASE_HOST_NOT_ALLOWED_GUIDANCE,
AnySource,
@@ -489,8 +490,9 @@ def _collect_secret_values(data: Any, sensitive: set[str], into: set[str]) -> No
def get_error_redaction_values(source: ExternalDataSource) -> frozenset[str]:
"""The stored secret values of a source, to mask wherever they appear in its error messages."""
- job_inputs = source.job_inputs
- if not isinstance(job_inputs, dict):
+ try:
+ job_inputs = SourceInputsStore.load(source)
+ except UnreadableSourceInputsError:
return frozenset()
try:
source_config = SourceRegistry.get_source(ExternalDataSourceType(source.source_type)).get_source_config
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
index 47c2870b60da..7fff1742b50a 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.facade.models import (
discovered_schema_finder,
sync_old_schemas_with_new_schemas,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
AnySource,
ClickHouseSource,
@@ -214,7 +215,8 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
team_id=self.team_id,
source_type=instance.source_type,
)
- if not instance.job_inputs:
+ source_inputs = SourceInputsStore.load(instance)
+ if not source_inputs:
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": "Source has no configuration."},
@@ -223,7 +225,7 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
try:
source_type = ExternalDataSourceType(instance.source_type)
source = base.SourceRegistry.get_source(source_type)
- config = source.parse_config(instance.job_inputs)
+ config = source.parse_config(source_inputs)
# Explicit user action — bypass any cached schema discovery so newly added
# upstream resources (e.g. Slack channels) appear immediately.
schemas = source.get_schemas(
@@ -507,7 +509,7 @@ class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase
source_impl: AnySource | None = None
try:
source_impl = base.SourceRegistry.get_source(ExternalDataSourceType(source.source_type))
- config = source_impl.parse_config(source.job_inputs)
+ config = source_impl.parse_config(SourceInputsStore.load(source))
discovered = source_impl.get_schemas(
config,
self.team_id,
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
index c02deba7422a..2daed80ec0fc 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
@@ -3,11 +3,13 @@
from __future__ import annotations
import uuid
+from collections.abc import Iterable
from datetime import UTC, datetime, timedelta
from typing import Any, cast
+from uuid import UUID
from django.core.exceptions import ValidationError as DjangoValidationError
-from django.db import transaction
+from django.db import models, transaction
from django.db.models import Q
from django.utils import timezone
@@ -47,6 +49,7 @@ from products.warehouse_sources.backend.facade.models import (
get_or_create_warehouse_destination,
sync_old_schemas_with_new_schemas,
)
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.facade.source_management import (
CDC_SEQ_COLUMN,
PREVIEW_DEFAULT_ROWS,
@@ -104,7 +107,20 @@ def _payload_enabled_columns(schema: dict[str, Any]) -> list[str] | None:
return [str(column) for column in payload_enabled_columns if isinstance(column, str)]
+class ExternalDataSourceListSerializer(serializers.ListSerializer):
+ def to_representation(
+ self, data: models.manager.BaseManager[ExternalDataSource] | Iterable[ExternalDataSource]
+ ) -> list[dict[str, Any]]:
+ sources = list(data.all() if isinstance(data, models.manager.BaseManager) else data)
+ child = self.child
+ assert isinstance(child, ExternalDataSourceSerializers)
+ child.preloaded_source_inputs = SourceInputsStore.load_many(sources)
+ return super().to_representation(sources)
+
+
class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializers.ModelSerializer):
+ preloaded_source_inputs: dict[UUID, dict[str, Any]] = {}
+
account_id = serializers.CharField(write_only=True)
client_secret = serializers.CharField(write_only=True)
last_run_at = serializers.SerializerMethodField(read_only=True)
@@ -203,6 +219,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
class Meta:
model = ExternalDataSource
+ list_serializer_class = ExternalDataSourceListSerializer
fields = [
"id",
"created_at",
@@ -251,11 +268,20 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
"connection_warning",
]
+ def _source_inputs(self, instance: ExternalDataSource) -> dict[str, Any]:
+ if instance.id in self.preloaded_source_inputs:
+ return self.preloaded_source_inputs[instance.id]
+ return SourceInputsStore.load(instance)
+
def to_representation(self, instance):
representation = super().to_representation(instance)
- job_inputs = representation.get("job_inputs", {})
- if not isinstance(job_inputs, dict):
+ if "job_inputs" not in representation:
+ return representation
+ try:
+ job_inputs = self._source_inputs(instance)
+ except UnreadableSourceInputsError:
+ representation["job_inputs"] = {}
return representation
# Derive allowed keys dynamically from source config field definitions
@@ -398,7 +424,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
else:
validated_data["prefix"] = instance.prefix
- existing_job_inputs = instance.job_inputs or {}
+ existing_job_inputs = SourceInputsStore.load(instance)
job_inputs_were_submitted = "job_inputs" in validated_data
incoming_job_inputs = validated_data.get("job_inputs", {})
@@ -680,6 +706,8 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
if namespaced_adapter is not None and job_inputs_were_submitted:
old_namespaced_resources = namespaced_adapter.resources_for_job_inputs(existing_job_inputs)
+ if "job_inputs" in validated_data:
+ SourceInputsStore.assign(instance, validated_data.pop("job_inputs"))
updated_source: ExternalDataSource = super().update(instance, validated_data)
cast(Any, updated_source)._connection_warning = connection_warning
@@ -1223,7 +1251,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
return error_response or Response(status=status.HTTP_400_BAD_REQUEST)
source_config = validated_config
- new_source_model = ExternalDataSource.objects.create(
+ new_source_model = SourceInputsStore.create(
source_id=str(uuid.uuid4()),
connection_id=str(uuid.uuid4()),
destination_id=str(uuid.uuid4()),
@@ -1233,7 +1261,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
status="Running",
source_type=source_type_model,
api_version=source.default_version,
- job_inputs=source.serialize_config(source_config),
+ inputs=source.serialize_config(source_config),
prefix=prefix,
description=description,
access_method=access_method,
@@ -1954,16 +1982,18 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
# Best-effort webhook cleanup — soft-deletes are already committed
source_type = ExternalDataSourceType(instance.source_type)
source = base.SourceRegistry.get_source(source_type)
- if isinstance(source, WebhookSource) and instance.job_inputs:
+ if isinstance(source, WebhookSource):
try:
- config = source.parse_config(instance.job_inputs)
- delete_webhook_and_hog_function(
- team=self.team,
- source=source,
- config=config,
- source_id=str(instance.pk),
- api_version=source.resolve_api_version(instance.api_version),
- )
+ source_inputs = SourceInputsStore.load(instance)
+ if source_inputs:
+ config = source.parse_config(source_inputs)
+ delete_webhook_and_hog_function(
+ team=self.team,
+ source=source,
+ config=config,
+ source_id=str(instance.pk),
+ api_version=source.resolve_api_version(instance.api_version),
+ )
except Exception as e:
base.capture_exception(e)
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/webhook_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/webhook_setup.py
index f8a9e1ca04b3..47a10f9c3d32 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/webhook_setup.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/webhook_setup.py
@@ -25,6 +25,7 @@ from products.data_warehouse.backend.facade.api import (
sync_external_data_job_workflow,
)
from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.facade.source_management import (
Config,
ExternalWebhookInfo,
@@ -313,10 +314,11 @@ class ExternalDataSourceWebhookSetupMixin(base.ExternalDataSourceViewSetBase):
"""Ask the source whether this connection can never create the provider-side webhook.
Best-effort: an unparseable config or a source-side failure leaves the button offered,
which is the behavior before the check existed."""
- if not instance.job_inputs:
- return None
try:
- return source.webhook_creation_blocked_reason(source.parse_config(instance.job_inputs), self.team_id)
+ source_inputs = SourceInputsStore.load(instance)
+ if not source_inputs:
+ return None
+ return source.webhook_creation_blocked_reason(source.parse_config(source_inputs), self.team_id)
except Exception as e:
base.capture_exception(e)
return None
@@ -376,19 +378,20 @@ class ExternalDataSourceWebhookSetupMixin(base.ExternalDataSourceViewSetBase):
external_status: ExternalWebhookInfo | None = None
missing_events: list[str] = []
- if instance.job_inputs:
- try:
- config = source.parse_config(instance.job_inputs)
+ try:
+ source_inputs = SourceInputsStore.load(instance)
+ if source_inputs:
+ config = source.parse_config(source_inputs)
external_status = source.get_external_webhook_info(
config, webhook_url, self.team_id, api_version=source.resolve_api_version(instance.api_version)
)
missing_events = self._compute_missing_webhook_events(source, config, instance, external_status)
- except Exception as e:
- base.capture_exception(e)
- external_status = ExternalWebhookInfo(
- exists=False,
- error="PostHog couldn't read this source's webhook to check its status. Check the source's credentials, then reload.",
- )
+ except Exception as e:
+ base.capture_exception(e)
+ external_status = ExternalWebhookInfo(
+ exists=False,
+ error="PostHog couldn't read this source's webhook to check its status. Check the source's credentials, then reload.",
+ )
schema_mapping = {}
if hog_function.inputs:
@@ -427,7 +430,8 @@ class ExternalDataSourceWebhookSetupMixin(base.ExternalDataSourceViewSetBase):
def create_webhook(self, request: Request, *args: Any, **kwargs: Any) -> Response:
instance: ExternalDataSource = self.get_object()
- if not instance.job_inputs:
+ source_inputs = SourceInputsStore.load(instance)
+ if not source_inputs:
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": "Source has no configuration"},
@@ -449,7 +453,7 @@ class ExternalDataSourceWebhookSetupMixin(base.ExternalDataSourceViewSetBase):
effective_api_version = source.resolve_api_version(instance.api_version)
try:
- config = source.parse_config(instance.job_inputs)
+ config = source.parse_config(source_inputs)
source_schemas = source.get_schemas(config, self.team_id, api_version=effective_api_version)
except ValidationError as e:
return Response(
@@ -522,7 +526,8 @@ class ExternalDataSourceWebhookSetupMixin(base.ExternalDataSourceViewSetBase):
def update_webhook_inputs(self, request: Request, *args: Any, **kwargs: Any) -> Response:
instance: ExternalDataSource = self.get_object()
- if not instance.job_inputs:
+ source_inputs = SourceInputsStore.load(instance)
+ if not source_inputs:
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": "Source has no configuration"},
@@ -577,7 +582,7 @@ class ExternalDataSourceWebhookSetupMixin(base.ExternalDataSourceViewSetBase):
)
try:
- config = source.parse_config(instance.job_inputs)
+ config = source.parse_config(source_inputs)
except ValidationError as e:
return Response(
status=status.HTTP_400_BAD_REQUEST,
@@ -644,7 +649,8 @@ class ExternalDataSourceWebhookSetupMixin(base.ExternalDataSourceViewSetBase):
},
)
- if not instance.job_inputs:
+ source_inputs = SourceInputsStore.load(instance)
+ if not source_inputs:
# No config means we can't call the external API, but we can still
# clean up the HogFunction.
try:
@@ -666,7 +672,7 @@ class ExternalDataSourceWebhookSetupMixin(base.ExternalDataSourceViewSetBase):
)
try:
- config = source.parse_config(instance.job_inputs)
+ config = source.parse_config(source_inputs)
except Exception as e:
base.capture_exception(e)
return Response(
diff --git a/products/warehouse_sources/backend/self_managed_migration.py b/products/warehouse_sources/backend/self_managed_migration.py
index 6ce92bc85008..2e98e718b70e 100644
--- a/products/warehouse_sources/backend/self_managed_migration.py
+++ b/products/warehouse_sources/backend/self_managed_migration.py
@@ -56,6 +56,7 @@ from products.warehouse_sources.backend.file_uploads import (
TABLE_FORMAT_TO_FILE_FORMAT,
HostedUpload,
)
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
from products.warehouse_sources.backend.models.external_data_destination import (
ExternalDataSourceDestination,
@@ -168,7 +169,7 @@ class _TablePlan:
source: ObjectStorageSource[Any] | FileUploadSource
schema_metadata: dict[str, Any]
- job_inputs: dict[str, Any] = dataclasses.field(repr=False)
+ inputs: dict[str, Any] = dataclasses.field(repr=False)
# Tables with the same group key and credential share one source.
group_key: str
description: str
@@ -286,7 +287,7 @@ class _Planner:
return _TablePlan(
source=source,
schema_metadata=definition.schema_metadata(),
- job_inputs=job_inputs,
+ inputs=job_inputs,
group_key=location.group_key,
description=f"Self-managed tables in {location.bucket}",
bucket=location.bucket,
@@ -318,7 +319,7 @@ class _Planner:
return _TablePlan(
source=source,
schema_metadata=schema_metadata,
- job_inputs=pending_upload_job_inputs(upload_format, table.name),
+ inputs=pending_upload_job_inputs(upload_format, table.name),
group_key=f"upload/{table.pk}",
description=f"Uploaded file for {table.name}"[:400],
shares_source=False,
@@ -554,7 +555,7 @@ def _find_or_create_source(table: DataWarehouseTable, plan: _TablePlan) -> Exter
"""The group's source for the table's team, credential and bucket. Runs under the group lock."""
if not plan.shares_source:
return create_source_for_upload(
- table, plan.job_inputs, connection_metadata={MIGRATION_MARKER_KEY: {"group_key": plan.group_key}}
+ table, plan.inputs, connection_metadata={MIGRATION_MARKER_KEY: {"group_key": plan.group_key}}
)
existing = (
ExternalDataSource.objects.filter(
@@ -569,7 +570,7 @@ def _find_or_create_source(table: DataWarehouseTable, plan: _TablePlan) -> Exter
)
if existing is not None:
return existing
- source = ExternalDataSource.objects.create(
+ source = SourceInputsStore.create(
prefix=_free_prefix(table.team_id, plan),
source_id=str(uuid.uuid4()),
connection_id=str(uuid.uuid4()),
@@ -578,7 +579,7 @@ def _find_or_create_source(table: DataWarehouseTable, plan: _TablePlan) -> Exter
status=ExternalDataSource.Status.RUNNING,
source_type=plan.source.source_type,
api_version=plan.source.default_version,
- job_inputs=plan.job_inputs,
+ inputs=plan.inputs,
description=plan.description,
access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
connection_metadata={
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index e40607cbbf0f..d41a78b110a5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -30,6 +30,7 @@ from posthog.temporal.common.heartbeat_sync import HeartbeaterSync
from posthog.temporal.common.shutdown import ShutdownMonitor, WorkerShuttingDownError
from posthog.utils import get_machine_id
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import (
CDC_SNAPSHOT_LANE_KEY,
@@ -640,7 +641,7 @@ class CDCExtractActivity:
def _catalog_names(self, table_names: list[str]) -> dict[str, dict[str, str]]:
"""Group schema names by source namespace, mapping each bare relation name back to its schema name."""
assert self.source is not None
- default_namespace = (self.source.job_inputs or {}).get("schema", "public")
+ default_namespace = SourceInputsStore.load_settings(self.source).get("schema", "public")
names_by_namespace: dict[str, dict[str, str]] = {}
for name in table_names:
namespace, dot, relation = name.partition(".")
@@ -696,7 +697,7 @@ class CDCExtractActivity:
return (removed, dataclasses.replace(current, operation="I"))
def _qualified_table_name(self, schema: ExternalDataSchema) -> str:
- default_schema = (self.source.job_inputs or {}).get("schema") if self.source else None
+ default_schema = SourceInputsStore.load_settings(self.source).get("schema") if self.source else None
return cdc_qualified_table_name(schema, default_schema)
def _build_event_name_map(self) -> dict[str, str]:
@@ -1229,8 +1230,7 @@ class CDCExtractActivity:
self.source, tables=[self._qualified_table_name(s) for s in self.cdc_schemas]
)
- self.source.job_inputs = {**(self.source.job_inputs or {}), **resource_fields}
- self.source.save(update_fields=["job_inputs", "updated_at"])
+ SourceInputsStore.update_runtime(self.source, resource_fields)
# Unpause only after the new slot exists, so no snapshot can run before change
# capture has a consistent point to resume from. Same for the resets still pending: the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
index 86f24d60e8ba..c3f4d6066815 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
@@ -32,6 +32,7 @@ import structlog
from posthog.redis import get_client
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
@@ -152,7 +153,7 @@ def _repair_locked(source: ExternalDataSource) -> int:
for schema_id in all_cdc_schema_ids:
purge_buffer_prefix(source.team_id, str(schema_id), log, strict=True)
- default_schema = (source.job_inputs or {}).get("schema")
+ default_schema = SourceInputsStore.load_settings(source).get("schema")
try:
resource_fields = adapter.recreate_slot(
source, tables=[cdc_qualified_table_name(schema, default_schema) for schema in cdc_schemas]
@@ -167,9 +168,8 @@ def _repair_locked(source: ExternalDataSource) -> int:
raise
raise CDCRepairError(customer_message) from e
- source.job_inputs = {**(source.job_inputs or {}), **resource_fields}
source.status = ExternalDataSource.Status.RUNNING
- source.save(update_fields=["job_inputs", "status", "updated_at"])
+ SourceInputsStore.update_runtime(source, resource_fields, extra_update_fields=("status", "updated_at"))
_resume_schedules(source, reset_now)
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 d6d869f7f772..6b5f56f7969e 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,4 +1,3 @@
-import json
from contextlib import asynccontextmanager
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any, NoReturn
@@ -19,6 +18,7 @@ from posthog.temporal.common.errors import NonReportableError
from posthog.utils import get_machine_id
from products.warehouse_sources.backend.billing import is_in_free_historical_window
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import get_incremental_field_value
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
DUPLICATE_PRIMARY_KEYS_ERROR,
@@ -97,37 +97,14 @@ class UnreadableJobInputsError(Exception):
"""
-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:
- 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.
+ decoded_from_string = SourceInputsStore.stored_as_string(source)
+ try:
+ job_inputs = await SourceInputsStore.aload(source)
+ except UnreadableSourceInputsError:
+ if decoded_from_string:
+ raise NonRetryableException() from UnreadableJobInputsError(UNREADABLE_JOB_INPUTS_MESSAGE)
+ # A value that is not a mapping has no keys to trim. Config parsing reports the invalid value.
return
# A value decoded out of a string is saved even when no key needs trimming, so the row is
@@ -140,7 +117,7 @@ async def trim_source_job_inputs(source: "ExternalDataSource") -> None:
did_update_inputs = True
if did_update_inputs:
- source.job_inputs = job_inputs
+ SourceInputsStore.assign(source, job_inputs)
await database_sync_to_async_pool(source.save)()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py
index 94d02b076d0f..81ecdd7afc96 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py
@@ -16,6 +16,8 @@ from django.utils import timezone
import structlog
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
+
logger = structlog.get_logger(__name__)
if TYPE_CHECKING:
@@ -49,7 +51,7 @@ def history_start_for_schema(
# leave the source on its declared default rather than failing every sync's history resolution.
config = None
try:
- config = source.parse_config(schema.source.job_inputs or {})
+ config = source.parse_config(SourceInputsStore.load(schema.source))
except Exception:
logger.warning("history_window.config_unreadable", source_type=schema.source.source_type)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
index 4ca8edbe214d..127a6fa885ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/custom/source.py
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldInputConfig,
SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.custom_oauth2_integration import (
CustomOAuth2Integration,
get_custom_oauth2_integration,
@@ -874,7 +875,7 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
# first sync's trust-on-first-use claim, closing the window where another create by the same
# user (matching the same unbound row) could adopt it. The guarded filter makes a lost race
# a no-op; sync-time authorization remains the backstop.
- oauth2_integration_id = (source_model.job_inputs or {}).get("auth_oauth2_integration_id")
+ oauth2_integration_id = SourceInputsStore.load(source_model).get("auth_oauth2_integration_id")
if oauth2_integration_id:
CustomOAuth2Integration.objects.for_team(team_id).filter(
id=oauth2_integration_id, external_data_source__isnull=True
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/file_upload/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/file_upload/source.py
index be73103d535b..1a20cc0e9b47 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/file_upload/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/file_upload/source.py
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceConfig,
)
from products.warehouse_sources.backend.file_uploads import InvalidUploadError, UploadLocation
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@@ -234,7 +235,7 @@ class FileUploadSource(SimpleSource[FileUploadInputs]):
def manual_sync_refusal(self, source_model: ExternalDataSource) -> str | None:
# A source the self-managed migration made reads no file until the next upload for its table.
try:
- upload_from_job_inputs(source_model.team_id, source_model.job_inputs)
+ upload_from_job_inputs(source_model.team_id, SourceInputsStore.load_settings(source_model))
except InvalidUploadError:
return "This table syncs when you upload a new file for it. Upload the file to import it."
return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/file_upload/storage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/file_upload/storage.py
index f1dc65531d68..5141fbea96ac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/file_upload/storage.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/file_upload/storage.py
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.file_uploads import (
LegacyUpload,
UploadLocation,
)
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -128,9 +129,9 @@ def upload_in_use(
if exclude_source_id is not None:
sources = sources.exclude(pk=exclude_source_id)
# `job_inputs` is encrypted, so the comparison runs here rather than in the query.
- for other in sources.select_related(None).only("id", "team_id", "job_inputs", "connection_metadata"):
+ for other in sources.select_related(None).only("id", "team_id", "source_type", "job_inputs", "connection_metadata"):
try:
- if upload_from_job_inputs(other.team_id, other.job_inputs) == upload:
+ if upload_from_job_inputs(other.team_id, SourceInputsStore.load_settings(other)) == upload:
return True
except InvalidUploadError:
pass
@@ -187,7 +188,9 @@ def release_superseded_uploads(source_id: str, team_id: int, sync_started_at: da
if not due:
return []
try:
- current: UploadLocation | None = upload_from_job_inputs(source.team_id, source.job_inputs)
+ current: UploadLocation | None = upload_from_job_inputs(
+ source.team_id, SourceInputsStore.load_settings(source)
+ )
except InvalidUploadError:
current = None
source.connection_metadata = _with_superseded(
@@ -220,7 +223,7 @@ def delete_source_uploads(source: ExternalDataSource) -> list[HostedUpload]:
"""Delete the files of a deleted source that nothing else reads."""
uploads: list[HostedUpload] = [entry.upload for entry in superseded_uploads(source)]
try:
- uploads.insert(0, upload_from_job_inputs(source.team_id, source.job_inputs))
+ uploads.insert(0, upload_from_job_inputs(source.team_id, SourceInputsStore.load_settings(source)))
except InvalidUploadError:
pass
deleted: list[HostedUpload] = []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py
index bd09784587a6..7190005b74b5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py
@@ -2,6 +2,7 @@ import requests
import structlog
from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.temporal.data_imports.sources.common import credentials_service
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -115,15 +116,14 @@ def _update_source_job_inputs(source_id: str, access_token: str) -> None:
try:
source = ExternalDataSource.objects.get(id=source_id)
- job_inputs = source.job_inputs or {}
+ job_inputs = SourceInputsStore.load(source)
# Only persist for legacy sources that store credentials directly in job_inputs
if "hubspot_integration_id" in job_inputs:
return
job_inputs["hubspot_secret_key"] = access_token
- source.job_inputs = job_inputs
- source.save(update_fields=["job_inputs"])
+ SourceInputsStore.save(source, job_inputs, extra_update_fields=())
except Exception:
logger.exception("Failed to update job_inputs after HubSpot token refresh", source_id=source_id)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
index 7ae8a92befe2..b9392927d553 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py
@@ -11,6 +11,7 @@ import psycopg
import structlog
from sshtunnel import BaseSSHTunnelForwarderError
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import cdc_error_info
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import HostNotAllowedError
from products.warehouse_sources.backend.temporal.data_imports.sources.common.tls import tls_options
@@ -123,7 +124,7 @@ class PostgresCDCAdapter:
)
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
- inputs = source.job_inputs or {}
+ inputs = SourceInputsStore.load(source)
cdc_config = self.parse_cdc_config(source)
# Two-arg form honors the SSH-tunnel `require_tls` opt-out, matching the management
# path (slot_manager.cdc_pg_connection) so a tunnelled source that opted out of TLS
@@ -417,5 +418,5 @@ class PostgresCDCAdapter:
return cdc_config.publication_name
def _resolve_schema(self, source: ExternalDataSource) -> str:
- raw = (source.job_inputs or {}).get("schema")
+ raw = SourceInputsStore.load_settings(source).get("schema")
return raw.strip() if isinstance(raw, str) and raw.strip() else "public"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
index fef28b5ac11b..9025c00ffbfa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/config.py
@@ -14,8 +14,10 @@ from typing import TYPE_CHECKING, Any
from posthog.utils import str_to_bool
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore, UnreadableSourceInputsError
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import (
CDCConfig,
+ CDCJobInputsUnreadableError,
ManagementMode,
decode_job_inputs,
)
@@ -56,4 +58,8 @@ class PostgresCDCConfig(CDCConfig):
@classmethod
def from_source(cls, source: ExternalDataSource) -> PostgresCDCConfig:
- return cls.from_dict(source.job_inputs)
+ try:
+ inputs = SourceInputsStore.load_settings(source)
+ except UnreadableSourceInputsError as e:
+ raise CDCJobInputsUnreadableError(str(e)) from e
+ return cls.from_dict(inputs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/slot_manager.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/slot_manager.py
index addbda47b05a..81dd50738021 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/slot_manager.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/slot_manager.py
@@ -10,6 +10,8 @@ from typing import TYPE_CHECKING
import psycopg
from psycopg import sql
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
+
if TYPE_CHECKING:
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -31,7 +33,7 @@ def cdc_pg_connection(source: ExternalDataSource, connect_timeout: int = 15) ->
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
source_impl = PostgresSource()
- config = source_impl.parse_config(source.job_inputs or {})
+ config = source_impl.parse_config(SourceInputsStore.load(source))
# Pass `config` so the SSH-tunnel `require_tls` opt-out is honored, matching the main
# pipeline path. Without it SSL is forced on, and a database reached over an SSH tunnel
# that doesn't speak SSL fails with "server does not support SSL, but SSL was required".
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
index 23e6d8c86584..e1c7263c80e0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
@@ -18,6 +18,7 @@ import structlog
import psycopg.errors
from psycopg import sql
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.sources.common.tls import TLSOptions
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.decoder import PgOutputDecoder
@@ -103,7 +104,7 @@ class PgCDCStreamReader:
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSource
source_impl = PostgresSource()
- config = source_impl.parse_config(self._source.job_inputs or {})
+ config = source_impl.parse_config(SourceInputsStore.load(self._source))
tunnel_cm = source_impl.with_ssh_tunnel(config, self._source.team_id)
self._effective_host, self._effective_port = tunnel_cm.__enter__()
self._tunnel_cm = tunnel_cm
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index 9c2403db7e12..3e5f78314798 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -34,6 +34,7 @@ from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.shutdown import DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT, ShutdownMonitor, WorkerShuttingDownError
from posthog.temporal.common.utils import is_stale_connection_read_only_error
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import (
WORKER_RESTART_ERROR_MESSAGE,
@@ -820,7 +821,8 @@ async def _import_data_with_reporting(
)
try:
- config = new_source.parse_config(model.pipeline.job_inputs)
+ stored_inputs = await SourceInputsStore.aload(model.pipeline)
+ config = new_source.parse_config(stored_inputs)
except CredentialsServiceFailure as e:
# A source whose config carries a PostHog-owned credential resolves it here, so a
# failure at this point is ours and not a corrupt `job_inputs`. Route it through the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
index 96f4de00b760..c2b0c1d30766 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/sync_new_schemas.py
@@ -13,6 +13,7 @@ from posthog.temporal.common.errors import NonReportableError
from posthog.temporal.common.logger import get_logger
from products.data_warehouse.backend.facade.api import delete_discover_schemas_schedule
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore
from products.warehouse_sources.backend.models.external_data_schema import (
auto_enable_new_schemas,
sync_old_schemas_with_new_schemas,
@@ -80,13 +81,13 @@ def sync_new_schemas_activity(inputs: SyncNewSchemasActivityInputs) -> None:
return
if SourceRegistry.is_registered(source_type_enum):
- if not source.job_inputs:
- return
-
- new_source = SourceRegistry.get_source(source_type_enum)
-
try:
- config = new_source.parse_config(source.job_inputs)
+ source_inputs = SourceInputsStore.load(source)
+ if not source_inputs:
+ return
+
+ new_source = SourceRegistry.get_source(source_type_enum)
+ config = new_source.parse_config(source_inputs)
except Exception:
# Config parsing is deterministic over the stored `job_inputs`, so a corrupt or
# double-encoded config fails identically on every discovery run - there is nothing
diff --git a/products/warehouse_sources/backend/tests/test_source_inputs.py b/products/warehouse_sources/backend/tests/test_source_inputs.py
new file mode 100644
index 000000000000..7607440aa78b
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_source_inputs.py
@@ -0,0 +1,154 @@
+import json
+from typing import Any
+
+from posthog.test.base import BaseTest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.logic.source_inputs import SourceInputsStore, UnreadableSourceInputsError
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+POSTGRES_INPUTS: dict[str, Any] = {
+ "host": "db.example.com",
+ "port": 5432,
+ "database": "app",
+ "user": "reader",
+ "password": "fake-password",
+ "schema": "public",
+ "cdc_enabled": True,
+ "cdc_slot_name": "posthog_slot",
+}
+
+
+def _source(source_type: str = ExternalDataSourceType.POSTGRES, job_inputs: Any = None) -> ExternalDataSource:
+ return ExternalDataSource(team_id=1, source_type=source_type, job_inputs=job_inputs)
+
+
+class TestSourceInputsStoreReads(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("none", None, {}),
+ ("empty", {}, {}),
+ ("mapping", {"host": "h", "schema": "s"}, {"host": "h", "schema": "s"}),
+ ("json_string", json.dumps({"host": "h"}), {"host": "h"}),
+ ]
+ )
+ def test_load_returns_a_mapping(self, _name: str, stored: Any, expected: dict[str, Any]) -> None:
+ assert SourceInputsStore.load(_source(job_inputs=stored)) == expected
+
+ @parameterized.expand(
+ [
+ ("list", ["not", "a", "mapping"]),
+ ("not_json", "fake-password"),
+ ("blank_string", ""),
+ ("json_list", json.dumps(["a"])),
+ ]
+ )
+ def test_load_raises_without_the_value(self, _name: str, stored: Any) -> None:
+ with self.assertRaises(UnreadableSourceInputsError) as raised:
+ SourceInputsStore.load(_source(job_inputs=stored))
+ assert "fake-password" not in str(raised.exception)
+
+ def test_load_returns_a_copy(self) -> None:
+ source = _source(job_inputs={"host": "h"})
+ SourceInputsStore.load(source)["host"] = "changed"
+ assert SourceInputsStore.load(source) == {"host": "h"}
+
+ def test_load_many_skips_unreadable_sources(self) -> None:
+ good = _source(job_inputs={"host": "h"})
+ bad = _source(job_inputs=["not", "a", "mapping"])
+ assert SourceInputsStore.load_many([good, bad]) == {good.id: {"host": "h"}}
+
+ @parameterized.expand(
+ [
+ (
+ "postgres_keeps_schema_and_cdc",
+ ExternalDataSourceType.POSTGRES,
+ POSTGRES_INPUTS,
+ {"schema": "public", "cdc_enabled": True, "cdc_slot_name": "posthog_slot"},
+ ),
+ (
+ "file_upload_keeps_upload_keys",
+ ExternalDataSourceType.FILEUPLOAD,
+ {"upload_id": "u1", "filename": "a.csv", "file_format": "csv", "schema_name": "a"},
+ {"upload_id": "u1", "filename": "a.csv", "file_format": "csv", "schema_name": "a"},
+ ),
+ (
+ "unknown_type_keeps_only_runtime_prefixes",
+ "NotARealSource",
+ {"schema": "public", "password": "fake-password", "cdc_enabled": True},
+ {"cdc_enabled": True},
+ ),
+ ]
+ )
+ def test_load_settings_never_returns_connection_fields(
+ self, _name: str, source_type: str, stored: dict[str, Any], expected: dict[str, Any]
+ ) -> None:
+ assert SourceInputsStore.load_settings(_source(source_type, stored)) == expected
+
+ @parameterized.expand(
+ [
+ ("connection_key", ExternalDataSourceType.POSTGRES, {"password": "x"}, ()),
+ ("setting_key", ExternalDataSourceType.POSTGRES, {"schema": "x"}, ()),
+ ("removed_connection_key", ExternalDataSourceType.POSTGRES, {}, ("host",)),
+ ("upload_key_on_another_source", ExternalDataSourceType.POSTGRES, {"upload_id": "u1"}, ()),
+ ("unknown_type", "NotARealSource", {"host": "x"}, ()),
+ ]
+ )
+ def test_update_runtime_rejects_non_runtime_keys(
+ self, _name: str, source_type: str, updates: dict[str, Any], remove: tuple[str, ...]
+ ) -> None:
+ source = _source(source_type, dict(POSTGRES_INPUTS))
+ with self.assertRaises(ValueError):
+ SourceInputsStore.update_runtime(source, updates, remove=remove)
+ assert source.job_inputs == POSTGRES_INPUTS
+
+
+# EncryptedJSONField stores each leaf as a string, so a database round trip only keeps string values.
+STORED_POSTGRES_INPUTS: dict[str, str] = {key: str(value) for key, value in POSTGRES_INPUTS.items()}
+
+
+class TestSourceInputsStoreWrites(BaseTest):
+ def _create(self, inputs: dict[str, Any]) -> ExternalDataSource:
+ return SourceInputsStore.create(
+ inputs=inputs,
+ team_id=self.team.pk,
+ source_id="source",
+ connection_id="connection",
+ status="Running",
+ source_type=ExternalDataSourceType.POSTGRES,
+ )
+
+ def test_create_then_save_round_trips(self) -> None:
+ source = self._create(STORED_POSTGRES_INPUTS)
+ assert SourceInputsStore.load(ExternalDataSource.objects.get(pk=source.pk)) == STORED_POSTGRES_INPUTS
+
+ SourceInputsStore.save(source, {**STORED_POSTGRES_INPUTS, "password": "fake-rotated"})
+ assert SourceInputsStore.load(ExternalDataSource.objects.get(pk=source.pk))["password"] == "fake-rotated"
+
+ def test_update_runtime_changes_only_the_given_runtime_keys(self) -> None:
+ source = self._create(STORED_POSTGRES_INPUTS)
+
+ result = SourceInputsStore.update_runtime(
+ source, {"cdc_consistent_point": "0/16B3748"}, remove=["cdc_slot_name", "cdc_absent_key"]
+ )
+
+ expected = {**STORED_POSTGRES_INPUTS, "cdc_consistent_point": "0/16B3748"}
+ del expected["cdc_slot_name"]
+ assert result == expected
+ assert SourceInputsStore.load(ExternalDataSource.objects.get(pk=source.pk)) == expected
+
+ def test_save_rewrites_a_string_value_as_a_mapping(self) -> None:
+ source = self._create({})
+ ExternalDataSource.objects.filter(pk=source.pk).update(job_inputs=json.dumps({"host": "h"}))
+ source.refresh_from_db()
+ assert SourceInputsStore.stored_as_string(source)
+
+ SourceInputsStore.save(source, SourceInputsStore.load(source))
+
+ source.refresh_from_db()
+ assert not SourceInputsStore.stored_as_string(source)
+ assert SourceInputsStore.load(source) == {"host": "h"}