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(warehouse-sources): return frozen dataclasses instead of tuples (#83143)

Arno Hillen73711e22c407
diff --git a/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py b/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py
index 2cf9731ce41c..69419c71259e 100644
--- a/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py
+++ b/products/warehouse_sources/backend/management/commands/validate_cdc_buffer.py
@@ -43,6 +43,7 @@ from products.warehouse_sources.backend.models.external_data_schema import Exter
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_COMPANION_SUFFIX
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
+ BufferFileSpan,
get_buffer_prefix,
parse_buffer_file_name,
)
@@ -145,7 +146,7 @@ class Command(BaseCommand):
entries = ls_result.values() if isinstance(ls_result, dict) else ls_result
violations: list[str] = []
- named: list[tuple[str, tuple[int, int, int]]] = []
+ named: list[tuple[str, BufferFileSpan]] = []
for entry in entries:
if entry.get("type") == "directory":
continue
@@ -165,12 +166,12 @@ class Command(BaseCommand):
named.sort(key=lambda item: item[0].rsplit("/", 1)[-1])
row_sum = 0
prev_end: int | None = None
- for key, (start_seq, end_seq, _file_index) in named:
- if start_seq > end_seq:
+ for key, span in named:
+ if span.start_seq > span.end_seq:
violations.append(f"{schema.name}: inverted range in {key}")
- if prev_end is not None and start_seq < prev_end:
+ if prev_end is not None and span.start_seq < prev_end:
violations.append(f"{schema.name}: overlapping range in {key} (starts before previous end {prev_end})")
- prev_end = end_seq
+ prev_end = span.end_seq
# A failed shadow write can leave a truncated object; report it as a
# violation instead of crashing the whole validation run.
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index 4499c1e26ea2..6925b6e1a165 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -45,6 +45,7 @@ from posthog.hogql.direct_sql.capability import direct_capable_source_types
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
+from posthog.dataclasses import frozen
from posthog.event_usage import EventSource, get_event_source, is_wizard_self_driving_program, report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.models.integration import Integration
@@ -288,10 +289,16 @@ def _add_name_variants(target: set[str], name: str) -> None:
target.add(normalised)
-def get_nonsensitive_and_sensitive_field_names(fields: list[FieldType]) -> tuple[set[str], set[str]]:
+@frozen
+class FieldSensitivitySplit:
+ nonsensitive: set[str]
+ sensitive: set[str]
+
+
+def get_nonsensitive_and_sensitive_field_names(fields: list[FieldType]) -> FieldSensitivitySplit:
"""Classify source config field names as nonsensitive or sensitive.
- Returns (nonsensitive, sensitive) sets of field names, flattened across all nesting levels.
+ Returns the field-name sets flattened across all nesting levels.
"""
nonsensitive: set[str] = set()
sensitive: set[str] = set()
@@ -308,14 +315,14 @@ def get_nonsensitive_and_sensitive_field_names(fields: list[FieldType]) -> tuple
_add_name_variants(nonsensitive, field.name)
for option in field.options:
if option.fields:
- ns, s = get_nonsensitive_and_sensitive_field_names(option.fields)
- nonsensitive.update(ns)
- sensitive.update(s)
+ nested = get_nonsensitive_and_sensitive_field_names(option.fields)
+ nonsensitive.update(nested.nonsensitive)
+ sensitive.update(nested.sensitive)
elif isinstance(field, SourceFieldSwitchGroupConfig):
_add_name_variants(nonsensitive, field.name)
- ns, s = get_nonsensitive_and_sensitive_field_names(field.fields)
- nonsensitive.update(ns)
- sensitive.update(s)
+ nested = get_nonsensitive_and_sensitive_field_names(field.fields)
+ nonsensitive.update(nested.nonsensitive)
+ sensitive.update(nested.sensitive)
elif isinstance(field, SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig):
# The selected account/property is a plain identifier (e.g. Bing Ads account_id,
# GSC site_url), not a secret — keep it so the form can prefill on edit.
@@ -327,7 +334,7 @@ def get_nonsensitive_and_sensitive_field_names(fields: list[FieldType]) -> tuple
nonsensitive.update({"host", "port", "username", "auth", "auth_type", "require_tls"})
sensitive.update({"password", "passphrase", "private_key"})
- return nonsensitive, sensitive
+ return FieldSensitivitySplit(nonsensitive=nonsensitive, sensitive=sensitive)
# Config metadata keys that are always safe to include in nested dicts
@@ -919,9 +926,9 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
try:
source_type_model = ExternalDataSourceType(instance.source_type)
source = SourceRegistry.get_source(source_type_model)
- nonsensitive, sensitive = get_nonsensitive_and_sensitive_field_names(source.get_source_config.fields)
+ split = get_nonsensitive_and_sensitive_field_names(source.get_source_config.fields)
# CDC fields aren't form fields but are non-secret operational config the UI needs.
- nonsensitive = nonsensitive | _CDC_EXPOSED_JOB_INPUT_KEYS
+ nonsensitive = split.nonsensitive | _CDC_EXPOSED_JOB_INPUT_KEYS
except (ValueError, KeyError):
representation["job_inputs"] = {}
return representation
@@ -941,7 +948,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
if "require_tls" not in tunnel:
tunnel["require_tls"] = {"enabled": True}
- representation["job_inputs"] = strip_sensitive_from_dict(job_inputs, nonsensitive, sensitive)
+ representation["job_inputs"] = strip_sensitive_from_dict(job_inputs, nonsensitive, split.sensitive)
return representation
def get_last_run_at(self, instance: ExternalDataSource) -> str | None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
index d575f98caed8..fa1d97ea086a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/buffer.py
@@ -47,6 +47,8 @@ import pyarrow.parquet as pq
import posthoganalytics
from structlog.types import FilteringBoundLogger
+from posthog.dataclasses import frozen
+
from products.data_warehouse.backend.facade.api import get_s3_client
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import (
@@ -112,8 +114,15 @@ def build_buffer_file_name(start_seq: int, end_seq: int, file_index: int) -> str
return f"{start_seq:0{_SEQ_WIDTH}d}-{end_seq:0{_SEQ_WIDTH}d}-{file_index:0{_INDEX_WIDTH}d}.parquet"
-def parse_buffer_file_name(file_name: str) -> tuple[int, int, int] | None:
- """Parse `{start}-{end}-{index}.parquet` → (start_seq, end_seq, file_index).
+@frozen
+class BufferFileSpan:
+ start_seq: int
+ end_seq: int
+ file_index: int
+
+
+def parse_buffer_file_name(file_name: str) -> BufferFileSpan | None:
+ """Parse `{start}-{end}-{index}.parquet` into the batch's position span.
Returns None for names that don't match the contract (foreign files are
ignored, never treated as buffer data).
@@ -121,7 +130,11 @@ def parse_buffer_file_name(file_name: str) -> tuple[int, int, int] | None:
match = _FILE_NAME_RE.fullmatch(file_name)
if match is None:
return None
- return int(match.group(1)), int(match.group(2)), int(match.group(3))
+ return BufferFileSpan(
+ start_seq=int(match.group(1)),
+ end_seq=int(match.group(2)),
+ file_index=int(match.group(3)),
+ )
@dataclass(frozen=True, slots=True)
@@ -225,8 +238,7 @@ class CDCBufferWriter:
parsed = parse_buffer_file_name(key.rsplit("/", 1)[-1])
if parsed is None:
continue
- start_seq, _end_seq, _file_index = parsed
- if start_seq >= restart_seq:
+ if parsed.start_seq >= restart_seq:
with suppress(Exception):
self._s3.rm(key)
removed += 1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py
index d402e658c646..690e78b0cda5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffer.py
@@ -10,6 +10,7 @@ import pyarrow.parquet as pq
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN
from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import (
+ BufferFileSpan,
CDCBufferWriter,
build_buffer_file_name,
get_buffer_prefix,
@@ -20,7 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import
class TestBufferFileName:
def test_roundtrip(self):
name = build_buffer_file_name(256, 512, 3)
- assert parse_buffer_file_name(name) == (256, 512, 3)
+ assert parse_buffer_file_name(name) == BufferFileSpan(start_seq=256, end_seq=512, file_index=3)
def test_rejects_foreign_names(self):
assert parse_buffer_file_name("part-0000.parquet") is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/partitioning.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/partitioning.py
index 710fbf5b9cde..3dae113ee029 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/partitioning.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/partitioning.py
@@ -10,6 +10,7 @@ import pyarrow.compute as pc
from dateutil import parser
from structlog.types import FilteringBoundLogger
+from posthog.dataclasses import frozen
from posthog.sync import database_sync_to_async_pool
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import normalize_column_name
@@ -80,24 +81,36 @@ async def setup_partitioning(
)
if partition_result is not None:
- pa_table, partition_mode, partition_format, updated_partition_keys = partition_result
+ pa_table = partition_result.table
if (
not schema.partitioning_enabled
- or schema.partition_mode != partition_mode
- or schema.partition_format != partition_format
- or schema.partitioning_keys != updated_partition_keys
+ or schema.partition_mode != partition_result.partition_mode
+ or schema.partition_format != partition_result.partition_format
+ or schema.partitioning_keys != partition_result.partition_keys
):
logger.debug(
- f"Setting partitioning_enabled on schema with: partition_keys={partition_keys}. partition_count={partition_count}. partition_mode={partition_mode}. partition_format={partition_format}"
+ f"Setting partitioning_enabled on schema with: partition_keys={partition_keys}. partition_count={partition_count}. partition_mode={partition_result.partition_mode}. partition_format={partition_result.partition_format}"
)
await database_sync_to_async_pool(schema.set_partitioning_enabled)(
- updated_partition_keys, partition_count, partition_size, partition_mode, partition_format
+ partition_result.partition_keys,
+ partition_count,
+ partition_size,
+ partition_result.partition_mode,
+ partition_result.partition_format,
)
return pa_table
+@frozen
+class PartitionedTable:
+ table: pa.Table
+ partition_mode: PartitionMode
+ partition_format: PartitionFormat | None
+ partition_keys: list[str]
+
+
def append_partition_key_to_table(
table: pa.Table,
partition_count: Optional[int],
@@ -106,7 +119,7 @@ def append_partition_key_to_table(
partition_mode: PartitionMode | None,
partition_format: PartitionFormat | None,
logger: FilteringBoundLogger,
-) -> None | tuple[pa.Table, PartitionMode, PartitionFormat | None, list[str]]:
+) -> PartitionedTable | None:
"""
Partitions the pyarrow table via one of three methods:
- md5: Hashes the primary keys into a fixed number of buckets, the least efficient method of partitioning
@@ -250,4 +263,9 @@ def append_partition_key_to_table(
new_column = pa.array(partition_array, type=pa.string())
- return table.append_column(PARTITION_KEY, new_column), mode, partition_format, normalized_partition_keys
+ return PartitionedTable(
+ table=table.append_column(PARTITION_KEY, new_column),
+ partition_mode=mode,
+ partition_format=partition_format,
+ partition_keys=normalized_partition_keys,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
index 74822fb2df4b..cf9bfa3a6a1e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
@@ -807,13 +807,13 @@ async def _rewrite_into_temp(
if result is None:
raise RepartitionUnpartitionableError(f"No supported partition mode for keys={target.partition_keys}")
- partitioned_table, used_mode, used_format, used_keys = result
+ partitioned_table = result.table
if resolved is None:
resolved = dataclasses.replace(
target,
- partition_mode=used_mode,
- partition_format=used_format,
- partition_keys=used_keys,
+ partition_mode=result.partition_mode,
+ partition_format=result.partition_format,
+ partition_keys=result.partition_keys,
)
# Align each batch against the live table's own declared schema before writing. Without
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
index 80a68f1435c2..280e11f9d367 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
@@ -1214,9 +1214,8 @@ def test_append_partition_key_numerical_handles_null_key():
)
assert result is not None
- partitioned_table, mode, _, _ = result
- assert mode == "numerical"
- assert partitioned_table.column(PARTITION_KEY).to_pylist() == ["1", "2", "null", "4"]
+ assert result.partition_mode == "numerical"
+ assert result.table.column(PARTITION_KEY).to_pylist() == ["1", "2", "null", "4"]
def test_append_partition_key_numerical_handles_non_int_key():
@@ -1237,9 +1236,8 @@ def test_append_partition_key_numerical_handles_non_int_key():
)
assert result is not None
- partitioned_table, mode, _, _ = result
- assert mode == "numerical"
- assert partitioned_table.column(PARTITION_KEY).to_pylist() == ["2", "0", "null"]
+ assert result.partition_mode == "numerical"
+ assert result.table.column(PARTITION_KEY).to_pylist() == ["2", "0", "null"]
def _mock_schema(**overrides: Any) -> MagicMock:
@@ -1583,9 +1581,8 @@ def test_append_partition_key_datetime_string_column(value, expected):
)
assert result is not None
- partitioned_table, mode, _, _ = result
- assert mode == "datetime"
- assert partitioned_table.column(PARTITION_KEY).to_pylist() == [expected]
+ assert result.partition_mode == "datetime"
+ assert result.table.column(PARTITION_KEY).to_pylist() == [expected]
@pytest.mark.parametrize(
@@ -1671,9 +1668,8 @@ def test_append_partition_key_missing_column_buckets_into_fallback(
)
assert result is not None
- partitioned_table, resolved_mode, _, _ = result
- assert resolved_mode == mode
- assert partitioned_table.column(PARTITION_KEY).to_pylist() == [expected, expected, expected]
+ assert result.partition_mode == mode
+ assert result.table.column(PARTITION_KEY).to_pylist() == [expected, expected, expected]
def test_billing_limit_exception_is_non_reportable_error():
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
index c74f3c267798..77d46df0b6f9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
@@ -87,8 +87,7 @@ def _write_month_partitioned(path: str, rows: list[tuple[int, datetime.datetime]
)
result = append_partition_key_to_table(table, None, None, ["created_at"], "datetime", "month", logger)
assert result is not None
- partitioned, *_ = result
- deltalake.write_deltalake(path, partitioned, partition_by=PARTITION_KEY)
+ deltalake.write_deltalake(path, result.table, partition_by=PARTITION_KEY)
return deltalake.DeltaTable(path)
@@ -419,9 +418,8 @@ class TestSelectCoarsenTarget:
table, None, None, ["created_at"], "datetime", partition_format, logger
)
assert result is not None
- partitioned, *_ = result
sizes: dict[str | None, int] = {}
- for key in partitioned.column(PARTITION_KEY).to_pylist():
+ for key in result.table.column(PARTITION_KEY).to_pylist():
sizes[key] = sizes.get(key, 0) + 1
return sizes
@@ -446,9 +444,8 @@ class TestSelectCoarsenTarget:
table, None, None, ["created_at"], "datetime", partition_format, logger
)
assert result is not None
- partitioned, *_ = result
sizes: dict[str | None, int] = {}
- for key in partitioned.column(PARTITION_KEY).to_pylist():
+ for key in result.table.column(PARTITION_KEY).to_pylist():
sizes[key] = sizes.get(key, 0) + 1
return sizes
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index 8c419b266aeb..d84b29d5b9d0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -301,23 +301,23 @@ def _apply_partitioning(
)
if partition_result is not None:
- pa_table, partition_mode, partition_format, updated_partition_keys = partition_result
+ pa_table = partition_result.table
if (
not schema.partitioning_enabled
- or schema.partition_mode != partition_mode
- or schema.partition_format != partition_format
- or schema.partitioning_keys != updated_partition_keys
+ or schema.partition_mode != partition_result.partition_mode
+ or schema.partition_format != partition_result.partition_format
+ or schema.partitioning_keys != partition_result.partition_keys
):
logger.debug(
- f"Setting partitioning_enabled on schema with: partition_keys={partition_keys}. partition_count={export_signal.partition_count}. partition_mode={partition_mode}. partition_format={partition_format}"
+ f"Setting partitioning_enabled on schema with: partition_keys={partition_keys}. partition_count={export_signal.partition_count}. partition_mode={partition_result.partition_mode}. partition_format={partition_result.partition_format}"
)
schema.set_partitioning_enabled(
- updated_partition_keys,
+ partition_result.partition_keys,
export_signal.partition_count,
export_signal.partition_size,
- partition_mode,
- partition_format,
+ partition_result.partition_mode,
+ partition_result.partition_format,
)
return pa_table
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py
index f7d9eac7ec5c..dea02ea91e8d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py
@@ -8,6 +8,8 @@ from typing import Any, Optional
from requests import Request, Response
from requests.exceptions import HTTPError
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.anthropic.settings import (
ANTHROPIC_ENDPOINTS,
USAGE_GROUP_BY_FALLBACKS,
@@ -342,25 +344,34 @@ def _claude_code_start_day(db_incremental_field_last_value: Any) -> date:
return _parse_iso_date(str(value))
-def _claude_code_actor_dims(item: dict[str, Any]) -> tuple[Any, str | None, str | None, str | None, str | None]:
+@frozen
+class ClaudeCodeActor:
+ date: Any
+ actor_type: str | None
+ email: str | None
+ api_key_name: str | None
+ terminal_type: str | None
+
+
+def _claude_code_actor_dims(item: dict[str, Any]) -> ClaudeCodeActor:
"""Pull the shared (date, actor, terminal) dimensions every Claude Code row carries.
`actor` is either a user (`email_address`) or an API actor (`api_key_name`); surface both as flat
columns so the grain is queryable without unpacking a nested object.
"""
actor = item.get("actor") or {}
- return (
- item.get("date"),
- actor.get("type"),
- actor.get("email_address"),
- actor.get("api_key_name"),
- item.get("terminal_type"),
+ return ClaudeCodeActor(
+ date=item.get("date"),
+ actor_type=actor.get("type"),
+ email=actor.get("email_address"),
+ api_key_name=actor.get("api_key_name"),
+ terminal_type=item.get("terminal_type"),
)
def _flatten_claude_code_core(item: dict[str, Any]) -> dict[str, Any]:
"""One row per (day, actor): Claude Code core productivity metrics and tool-action counts."""
- date_value, actor_type, actor_email, actor_api_key_name, terminal_type = _claude_code_actor_dims(item)
+ dims = _claude_code_actor_dims(item)
core = item.get("core_metrics") or {}
lines_of_code = core.get("lines_of_code") or {}
tool_actions = item.get("tool_actions") or {}
@@ -375,14 +386,14 @@ def _flatten_claude_code_core(item: dict[str, Any]) -> dict[str, Any]:
notebook_edit_accepted, notebook_edit_rejected = _tool("notebook_edit_tool")
return {
- "id": _row_id(date_value, actor_type, actor_email, actor_api_key_name, terminal_type),
- "date": date_value,
+ "id": _row_id(dims.date, dims.actor_type, dims.email, dims.api_key_name, dims.terminal_type),
+ "date": dims.date,
"organization_id": item.get("organization_id"),
- "actor_type": actor_type,
- "actor_email_address": actor_email,
- "actor_api_key_name": actor_api_key_name,
+ "actor_type": dims.actor_type,
+ "actor_email_address": dims.email,
+ "actor_api_key_name": dims.api_key_name,
"customer_type": item.get("customer_type"),
- "terminal_type": terminal_type,
+ "terminal_type": dims.terminal_type,
"num_sessions": core.get("num_sessions"),
"lines_of_code_added": lines_of_code.get("added"),
"lines_of_code_removed": lines_of_code.get("removed"),
@@ -406,7 +417,7 @@ def _flatten_claude_code_models(item: dict[str, Any]) -> list[dict[str, Any]]:
and commits (per day) — keeping them in one table would either duplicate the core metrics across a
day's models or bury the per-model cost in a nested column.
"""
- date_value, actor_type, actor_email, actor_api_key_name, terminal_type = _claude_code_actor_dims(item)
+ dims = _claude_code_actor_dims(item)
rows: list[dict[str, Any]] = []
for entry in item.get("model_breakdown") or []:
model = entry.get("model")
@@ -414,14 +425,14 @@ def _flatten_claude_code_models(item: dict[str, Any]) -> list[dict[str, Any]]:
estimated_cost = entry.get("estimated_cost") or {}
rows.append(
{
- "id": _row_id(date_value, actor_type, actor_email, actor_api_key_name, terminal_type, model),
- "date": date_value,
+ "id": _row_id(dims.date, dims.actor_type, dims.email, dims.api_key_name, dims.terminal_type, model),
+ "date": dims.date,
"organization_id": item.get("organization_id"),
- "actor_type": actor_type,
- "actor_email_address": actor_email,
- "actor_api_key_name": actor_api_key_name,
+ "actor_type": dims.actor_type,
+ "actor_email_address": dims.email,
+ "actor_api_key_name": dims.api_key_name,
"customer_type": item.get("customer_type"),
- "terminal_type": terminal_type,
+ "terminal_type": dims.terminal_type,
"model": model,
"input_tokens": tokens.get("input"),
"output_tokens": tokens.get("output"),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
index 97d5db656490..a4369590799e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
@@ -24,6 +24,7 @@ from psycopg.adapt import Loader
from psycopg.pq import TransactionStatus
from structlog.types import FilteringBoundLogger
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
@@ -604,6 +605,13 @@ class RedshiftColumn(Column):
return pa.field(self.name, arrow_type, nullable=self.nullable)
+@frozen
+class DisplayNameIndex:
+ display_by_pair: dict[tuple[str, str], str]
+ schemas: list[str]
+ bare_tables: list[str]
+
+
class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycopg.Connection, Any]):
# `psycopg.Cursor` does not satisfy `_CursorLike` (its `execute`
# signature uses `params` instead of `args`, and accepts `Query`
@@ -734,7 +742,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
return result
selected_schema = normalize_namespace(config.schema)
- display_by_pair, schemas, bare_tables = self._index_display_names(tables, selected_schema)
+ index = self._index_display_names(tables, selected_schema)
try:
with conn.cursor() as cursor:
@@ -749,7 +757,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
WHERE tc.table_schema = ANY({schemas})
AND tc.table_name = ANY({names})
AND tc.constraint_type = 'PRIMARY KEY'
- """).format(schemas=sql.Literal(schemas), names=sql.Literal(bare_tables))
+ """).format(schemas=sql.Literal(index.schemas), names=sql.Literal(index.bare_tables))
)
rows = cursor.fetchall()
except Exception as e:
@@ -758,7 +766,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
pks: dict[str, list[str]] = collections.defaultdict(list)
for table_schema, table_name, column_name in rows:
- display = display_by_pair.get((table_schema, table_name))
+ display = index.display_by_pair.get((table_schema, table_name))
if display is not None:
pks[display].append(column_name)
for display, pk_cols in pks.items():
@@ -766,9 +774,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
return result
@staticmethod
- def _index_display_names(
- tables: list[str], selected_schema: Optional[str]
- ) -> tuple[dict[tuple[str, str], str], list[str], list[str]]:
+ def _index_display_names(tables: list[str], selected_schema: Optional[str]) -> DisplayNameIndex:
"""Map `(schema, table)` → display key, plus the distinct schemas and bare table names.
Lets a single batch query (`schema = ANY(...) AND table = ANY(...)`) cover both the
@@ -787,7 +793,9 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
continue
display_by_pair[(schema, table)] = display
schemas.add(schema)
- return display_by_pair, sorted(schemas), sorted(bare_tables)
+ return DisplayNameIndex(
+ display_by_pair=display_by_pair, schemas=sorted(schemas), bare_tables=sorted(bare_tables)
+ )
def get_row_counts(
self,
@@ -807,7 +815,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
return {}
selected_schema = normalize_namespace(config.schema)
- display_by_pair, schemas, bare_tables = self._index_display_names(tables, selected_schema)
+ index = self._index_display_names(tables, selected_schema)
result: dict[str, int | None] = {}
try:
@@ -816,7 +824,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(1000 * 30)) # 30 secs
)
- params: dict = {"schemas": schemas, "names": bare_tables}
+ params: dict = {"schemas": index.schemas, "names": index.bare_tables}
cursor.execute(
"""
SELECT schema, "table" AS table_name, tbl_rows AS row_count
@@ -826,7 +834,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
params,
)
for schema_name, table_name, row_count in cursor.fetchall():
- display = display_by_pair.get((schema_name, table_name))
+ display = index.display_by_pair.get((schema_name, table_name))
if display is not None:
result[display] = int(row_count)
@@ -837,7 +845,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
view_pairs = [
(schema_name, view_name)
for schema_name, view_name in cursor.fetchall()
- if (schema_name, view_name) in display_by_pair
+ if (schema_name, view_name) in index.display_by_pair
]
if view_pairs:
@@ -854,7 +862,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
]
cursor.execute(sql.SQL(" UNION ALL ").join(view_counts))
for schema_name, table_name, row_count in cursor.fetchall():
- display = display_by_pair.get((schema_name, table_name))
+ display = index.display_by_pair.get((schema_name, table_name))
if display is not None:
result[display] = int(row_count)
except Exception:
@@ -892,7 +900,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
return {}
selected_schema = normalize_namespace(config.schema)
- display_by_pair, schemas, bare_tables = self._index_display_names(tables, selected_schema)
+ index = self._index_display_names(tables, selected_schema)
result: dict[str, set[str]] = {table: set() for table in tables}
try:
@@ -904,7 +912,7 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
# path. Documented behavior: docs.aws.amazon.com/redshift/latest/dg/r_PG_TABLE_DEF.html
cursor.execute(
sql.SQL("SET search_path TO {schemas}").format(
- schemas=sql.SQL(", ").join(sql.Identifier(schema) for schema in schemas)
+ schemas=sql.SQL(", ").join(sql.Identifier(schema) for schema in index.schemas)
)
)
cursor.execute(
@@ -914,14 +922,14 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
WHERE schemaname = ANY({schemas})
AND tablename = ANY({names})
AND sortkey != 0
- """).format(schemas=sql.Literal(schemas), names=sql.Literal(bare_tables))
+ """).format(schemas=sql.Literal(index.schemas), names=sql.Literal(index.bare_tables))
)
# Group rows by display name so we can classify compound vs interleaved
# before deciding which columns count as indexed. Negative sortkey
# values are the marker Redshift uses for interleaved sortkeys.
rows_by_display: dict[str, list[tuple[str, int]]] = {}
for schema_name, table_name, column_name, sortkey_value in cursor.fetchall():
- display = display_by_pair.get((schema_name, table_name))
+ display = index.display_by_pair.get((schema_name, table_name))
if display is None:
continue
rows_by_display.setdefault(display, []).append((column_name, sortkey_value))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/source.py
index 141600844b20..0ceeb9914676 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/source.py
@@ -1,3 +1,4 @@
+from dataclasses import field
from typing import TYPE_CHECKING, Optional, cast
if TYPE_CHECKING:
@@ -14,6 +15,8 @@ from posthog.schema import (
SourceFieldSwitchGroupConfig,
)
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
FieldType,
ResumableSource,
@@ -44,6 +47,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.slac
from products.warehouse_sources.backend.types import ExternalDataSourceType
+@frozen
+class SlackAccess:
+ """Resolved Slack credentials: the token, the user scoping private-channel discovery,
+ and the id keying the per-workspace channel-list cache."""
+
+ access_token: str = field(repr=False) # secret: keep out of repr/logs
+ authed_user_id: str | None
+ cache_id: str
+
+
@SourceRegistry.register
class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], WebhookSource[SlackSourceConfig], OAuthMixin):
api_docs_url = "https://api.slack.com/web"
@@ -73,12 +86,9 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhook
def _get_authed_user_id(integration: "Integration") -> str | None:
return (integration.config or {}).get("authed_user", {}).get("id")
- def _resolve_access_token(self, config: SlackSourceConfig, team_id: int) -> tuple[str, str | None, str]:
+ def _resolve_access_token(self, config: SlackSourceConfig, team_id: int) -> SlackAccess:
"""Resolve credentials, preferring the bring-your-own bot token.
- Returns ``(access_token, authed_user_id, cache_id)``. ``authed_user_id`` scopes private-channel
- discovery to a single user; ``cache_id`` keys the per-workspace channel-list cache.
-
- A ``slack_access_token`` means the customer's own Slack app. The token is stored on the
source itself, so it stays within Slack's API terms for internal apps. ``auth.test`` gives
the token's own user id and a hash of the token keys the cache. This is the only path new
@@ -89,7 +99,11 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhook
"""
if config.slack_access_token:
access_token = config.slack_access_token
- return access_token, auth_test_user_id(access_token), manual_cache_id(access_token)
+ return SlackAccess(
+ access_token=access_token,
+ authed_user_id=auth_test_user_id(access_token),
+ cache_id=manual_cache_id(access_token),
+ )
if not config.slack_integration_id:
raise ValueError("Slack access token not found")
@@ -98,7 +112,11 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhook
oauth_token = integration.access_token
if not oauth_token:
raise ValueError("Slack access token not found")
- return oauth_token, self._get_authed_user_id(integration), str(integration.id)
+ return SlackAccess(
+ access_token=oauth_token,
+ authed_user_id=self._get_authed_user_id(integration),
+ cache_id=str(integration.id),
+ )
def create_webhook(
self, config: SlackSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
@@ -287,13 +305,15 @@ Prefer a manifest? Paste this when creating the app — it wires the request URL
for name, endpoint_config in ENDPOINTS.items()
]
- access_token, authed_user, cache_id = self._resolve_access_token(config, team_id)
+ access = self._resolve_access_token(config, team_id)
# Only the bring-your-own path can auto-join — the legacy shared app lacks channels:join.
# Joining is idempotent and only touches public channels the bot isn't in, so running it on
# each discovery/refresh also picks up channels created since the last pass.
if config.slack_access_token and config.join_public_channels and config.join_public_channels.enabled:
- join_public_channels(access_token, cache_id, authed_user)
- channels = get_channels(cache_id, access_token, authed_user, force_refresh=force_refresh)
+ join_public_channels(access.access_token, access.cache_id, access.authed_user_id)
+ channels = get_channels(
+ access.cache_id, access.access_token, access.authed_user_id, force_refresh=force_refresh
+ )
for ch in channels:
if ch["id"] in ENDPOINTS:
continue
@@ -319,9 +339,9 @@ Prefer a manifest? Paste this when creating the app — it wires the request URL
self, config: SlackSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
) -> tuple[bool, str | None]:
try:
- access_token, _authed_user, _cache_id = self._resolve_access_token(config, team_id)
+ access = self._resolve_access_token(config, team_id)
- is_valid, error_code = validate_slack_credentials(access_token)
+ is_valid, error_code = validate_slack_credentials(access.access_token)
if is_valid:
return True, None
@@ -346,7 +366,7 @@ Prefer a manifest? Paste this when creating the app — it wires the request URL
resumable_source_manager: ResumableSourceManager[SlackResumeConfig],
inputs: SourceInputs,
) -> SourceResponse:
- access_token, authed_user, cache_id = self._resolve_access_token(config, inputs.team_id)
+ access = self._resolve_access_token(config, inputs.team_id)
# For channel schemas, the schema name is the channel ID itself
channel_id = inputs.schema_name if inputs.schema_name not in ENDPOINTS else None
@@ -354,8 +374,8 @@ Prefer a manifest? Paste this when creating the app — it wires the request URL
webhook_source_manager = self.get_webhook_source_manager(inputs)
return slack_source(
- access_token=access_token,
- cache_id=cache_id,
+ access_token=access.access_token,
+ cache_id=access.cache_id,
endpoint=inputs.schema_name,
team_id=inputs.team_id,
job_id=inputs.job_id,
@@ -367,5 +387,5 @@ Prefer a manifest? Paste this when creating the app — it wires the request URL
incremental_field=inputs.incremental_field,
channel_id=channel_id,
webhook_source_manager=webhook_source_manager,
- authed_user=authed_user,
+ authed_user=access.authed_user_id,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/test_slack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/test_slack.py
index a8301dc96882..63ed6611ced5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/test_slack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/test_slack.py
@@ -528,11 +528,11 @@ class TestResolveAccessToken:
patch(f"{self._SOURCE_MODULE}.auth_test_user_id", return_value="UBOT") as mock_auth_test,
patch.object(source, "get_oauth_integration") as mock_get_integration,
):
- access_token, authed_user, cache_id = source._resolve_access_token(config, team_id=1)
+ access = source._resolve_access_token(config, team_id=1)
- assert access_token == "xoxb-abc"
- assert authed_user == "UBOT"
- assert cache_id == manual_cache_id("xoxb-abc")
+ assert access.access_token == "xoxb-abc"
+ assert access.authed_user_id == "UBOT"
+ assert access.cache_id == manual_cache_id("xoxb-abc")
# The bring-your-own path must never touch an Integration row — that's what keeps it
# off the shared PostHog app.
mock_get_integration.assert_not_called()
@@ -542,7 +542,10 @@ class TestResolveAccessToken:
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.slack import (
SlackSourceConfig,
)
- from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackSource
+ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import (
+ SlackAccess,
+ SlackSource,
+ )
config = SlackSourceConfig.from_dict({"slack_integration_id": 42})
source = SlackSource()
@@ -553,9 +556,9 @@ class TestResolveAccessToken:
integration.config = {"authed_user": {"id": "U_INSTALLER"}}
with patch.object(source, "get_oauth_integration", return_value=integration) as mock_get_integration:
- access_token, authed_user, cache_id = source._resolve_access_token(config, team_id=1)
+ access = source._resolve_access_token(config, team_id=1)
- assert (access_token, authed_user, cache_id) == ("token", "U_INSTALLER", "42")
+ assert access == SlackAccess(access_token="token", authed_user_id="U_INSTALLER", cache_id="42")
mock_get_integration.assert_called_once_with(42, 1)
def test_token_takes_precedence_over_a_legacy_integration(self) -> None:
@@ -573,9 +576,9 @@ class TestResolveAccessToken:
patch(f"{self._SOURCE_MODULE}.auth_test_user_id", return_value="UBOT"),
patch.object(source, "get_oauth_integration") as mock_get_integration,
):
- access_token, _authed_user, _cache_id = source._resolve_access_token(config, team_id=1)
+ access = source._resolve_access_token(config, team_id=1)
- assert access_token == "xoxb-new"
+ assert access.access_token == "xoxb-new"
mock_get_integration.assert_not_called()
def test_no_credentials_raises(self) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/tests/test_slack_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/tests/test_slack_source.py
index 6f5593bedfa8..eb86253cb3dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/tests/test_slack_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/tests/test_slack_source.py
@@ -7,7 +7,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack import (
validate_credentials as validate_slack_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackAccess, SlackSource
SOURCE_VALIDATE_PATCH = (
"products.warehouse_sources.backend.temporal.data_imports.sources.slack.source.validate_slack_credentials"
@@ -42,7 +42,11 @@ class TestSlackSourceValidateCredentials:
source = SlackSource()
with (
mock.patch(SOURCE_VALIDATE_PATCH, return_value=mock_result) as mock_validate,
- mock.patch.object(source, "_resolve_access_token", return_value=("token", None, "cache")),
+ mock.patch.object(
+ source,
+ "_resolve_access_token",
+ return_value=SlackAccess(access_token="token", authed_user_id=None, cache_id="cache"),
+ ),
):
result = source.validate_credentials(MagicMock(), team_id=1)
mock_validate.assert_called_once_with("token")
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 61052287c8bb..2b39664ab815 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -8792,11 +8792,11 @@ class TestSensitiveFieldClassification(APIBaseTest):
secret=True,
),
]
- nonsensitive, sensitive = get_nonsensitive_and_sensitive_field_names(fields)
- assert "host" in nonsensitive
- assert "password" in sensitive
- assert "password" not in nonsensitive
- assert "host" not in sensitive
+ split = get_nonsensitive_and_sensitive_field_names(fields)
+ assert "host" in split.nonsensitive
+ assert "password" in split.sensitive
+ assert "password" not in split.nonsensitive
+ assert "host" not in split.sensitive
def test_classifies_file_upload_as_sensitive(self):
fields: list[FieldType] = [
@@ -8807,9 +8807,9 @@ class TestSensitiveFieldClassification(APIBaseTest):
fileFormat=SourceFieldFileUploadJsonFormatConfig(keys=["project_id", "private_key"]),
),
]
- nonsensitive, sensitive = get_nonsensitive_and_sensitive_field_names(fields)
- assert "key_file" in sensitive
- assert "key_file" not in nonsensitive
+ split = get_nonsensitive_and_sensitive_field_names(fields)
+ assert "key_file" in split.sensitive
+ assert "key_file" not in split.nonsensitive
def test_classifies_select_with_nested_password(self):
fields: list[FieldType] = [
@@ -8844,23 +8844,23 @@ class TestSensitiveFieldClassification(APIBaseTest):
],
),
]
- nonsensitive, sensitive = get_nonsensitive_and_sensitive_field_names(fields)
- assert "auth_type" in nonsensitive
- assert "user" in nonsensitive
- assert "password" in sensitive
+ split = get_nonsensitive_and_sensitive_field_names(fields)
+ assert "auth_type" in split.nonsensitive
+ assert "user" in split.nonsensitive
+ assert "password" in split.sensitive
def test_classifies_ssh_tunnel_nested_fields(self):
fields: list[FieldType] = [SourceFieldSSHTunnelConfig(name="ssh_tunnel", label="SSH Tunnel")]
- nonsensitive, sensitive = get_nonsensitive_and_sensitive_field_names(fields)
- assert "ssh_tunnel" in nonsensitive
- assert "host" in nonsensitive
- assert "port" in nonsensitive
- assert "username" in nonsensitive
- assert "auth" in nonsensitive
- assert "auth_type" in nonsensitive
- assert "password" in sensitive
- assert "passphrase" in sensitive
- assert "private_key" in sensitive
+ split = get_nonsensitive_and_sensitive_field_names(fields)
+ assert "ssh_tunnel" in split.nonsensitive
+ assert "host" in split.nonsensitive
+ assert "port" in split.nonsensitive
+ assert "username" in split.nonsensitive
+ assert "auth" in split.nonsensitive
+ assert "auth_type" in split.nonsensitive
+ assert "password" in split.sensitive
+ assert "passphrase" in split.sensitive
+ assert "private_key" in split.sensitive
def test_classifies_secret_flag_as_sensitive_regardless_of_type(self):
fields: list[FieldType] = [
@@ -8881,11 +8881,11 @@ class TestSensitiveFieldClassification(APIBaseTest):
secret=False,
),
]
- nonsensitive, sensitive = get_nonsensitive_and_sensitive_field_names(fields)
- assert "client_private_key" in sensitive
- assert "client_private_key" not in nonsensitive
- assert "namespace" in nonsensitive
- assert "namespace" not in sensitive
+ split = get_nonsensitive_and_sensitive_field_names(fields)
+ assert "client_private_key" in split.sensitive
+ assert "client_private_key" not in split.nonsensitive
+ assert "namespace" in split.nonsensitive
+ assert "namespace" not in split.sensitive
def test_strip_sensitive_from_dict_basic(self):
data = {"host": "localhost", "password": "secret", "unknown_key": "val"}
@@ -8941,9 +8941,9 @@ class TestSensitiveFieldClassification(APIBaseTest):
),
),
]
- nonsensitive, _ = get_nonsensitive_and_sensitive_field_names(fields)
- assert "temporary-dataset" in nonsensitive
- assert "temporary_dataset" in nonsensitive
+ split = get_nonsensitive_and_sensitive_field_names(fields)
+ assert "temporary-dataset" in split.nonsensitive
+ assert "temporary_dataset" in split.nonsensitive
def test_strip_preserves_aliased_switch_group_from_to_dict(self):
"""job_inputs persisted via to_dict() uses snake_case keys even when
@@ -8976,7 +8976,7 @@ class TestSensitiveFieldClassification(APIBaseTest):
),
),
]
- nonsensitive, sensitive = get_nonsensitive_and_sensitive_field_names(fields)
+ split = get_nonsensitive_and_sensitive_field_names(fields)
# Simulate job_inputs as persisted by dataclasses.asdict() (snake_case keys)
persisted_data = {
@@ -8986,7 +8986,7 @@ class TestSensitiveFieldClassification(APIBaseTest):
"temporary_dataset_id": "tmp-dataset",
},
}
- result = strip_sensitive_from_dict(persisted_data, nonsensitive, sensitive)
+ result = strip_sensitive_from_dict(persisted_data, split.nonsensitive, split.sensitive)
assert "temporary_dataset" in result
assert result["temporary_dataset"]["enabled"] is True
assert result["temporary_dataset"]["temporary_dataset_id"] == "tmp-dataset"
@@ -8994,10 +8994,10 @@ class TestSensitiveFieldClassification(APIBaseTest):
def test_all_registered_sources_have_valid_classification(self):
for source in SourceRegistry.get_all_sources().values():
config = source.get_source_config
- nonsensitive, sensitive = get_nonsensitive_and_sensitive_field_names(config.fields)
+ split = get_nonsensitive_and_sensitive_field_names(config.fields)
# No field should appear in both sets
- overlap = nonsensitive & sensitive
+ overlap = split.nonsensitive & split.sensitive
assert not overlap, f"{config.name}: fields in both sets: {overlap}"
def test_password_typed_fields_must_be_marked_secret(self):
@@ -9073,8 +9073,8 @@ class TestSensitiveFieldClassification(APIBaseTest):
all_nonsensitive: set[str] = set()
for source in SourceRegistry.get_all_sources().values():
config = source.get_source_config
- nonsensitive, _ = get_nonsensitive_and_sensitive_field_names(config.fields)
- all_nonsensitive.update(nonsensitive)
+ split = get_nonsensitive_and_sensitive_field_names(config.fields)
+ all_nonsensitive.update(split.nonsensitive)
missing = old_allowed - all_nonsensitive
assert not missing, f"Old allowlist fields not covered by dynamic classification: {missing}"