diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 20333882b5..25563d0329 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -1940,6 +1940,7 @@ class ArrowScan: _table_metadata: TableMetadata _io: FileIO _projected_schema: Schema + _row_filter_schema: Schema _bound_row_filter: BooleanExpression _case_sensitive: bool _limit: int | None @@ -1951,6 +1952,7 @@ class ArrowScan: _table_metadata: Current table metadata of the Iceberg table _io: PyIceberg FileIO implementation from which to fetch the io properties _projected_schema: Iceberg Schema to project onto the data files + _row_filter_schema: Iceberg Schema the row filter is bound to _bound_row_filter: Schema bound row expression to filter the data with _case_sensitive: Case sensitivity when looking up column names _limit: Limit the number of records. @@ -1968,11 +1970,13 @@ def __init__( limit: int | None = None, *, dictionary_columns: tuple[str, ...] = (), + row_filter_schema: Schema | None = None, ) -> None: self._table_metadata = table_metadata self._io = io self._projected_schema = projected_schema - self._bound_row_filter = bind(table_metadata.schema(), row_filter, case_sensitive=case_sensitive) + self._row_filter_schema = row_filter_schema if row_filter_schema is not None else table_metadata.schema() + self._bound_row_filter = bind(self._row_filter_schema, row_filter, case_sensitive=case_sensitive) self._case_sensitive = case_sensitive self._limit = limit self._downcast_ns_timestamp_to_us = Config().get_bool(DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE) @@ -1981,7 +1985,8 @@ def __init__( @property def _projected_field_ids(self) -> set[int]: """Set of field IDs that should be projected from the data files.""" - schema = self._table_metadata.schema() + # The filter's field IDs come from the schema it is bound to, which a time-travel scan takes from the snapshot + schema = self._row_filter_schema filter_field_ids = extract_field_ids(self._bound_row_filter) # A list or map cannot be projected by its own ID, so a filter on one reads its nested fields instead nested_field_ids = prune_columns( diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index a8fcdb16e6..1c611631b0 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -66,7 +66,7 @@ from pyiceberg.table.metadata import INITIAL_SEQUENCE_NUMBER, TableMetadata from pyiceberg.table.metadata_columns import project_schema, split_selected_fields from pyiceberg.table.name_mapping import NameMapping -from pyiceberg.table.refs import MAIN_BRANCH, SnapshotRef +from pyiceberg.table.refs import MAIN_BRANCH, SnapshotRef, SnapshotRefType from pyiceberg.table.snapshots import ( Operation, Snapshot, @@ -2211,6 +2211,9 @@ def __init__( self.limit = limit self.encryption_manager = encryption_manager + def _scan_schema(self) -> Schema: + return self.table_metadata.schema() + @abstractmethod def plan_files(self) -> Iterable[ScanTask]: ... @@ -2292,6 +2295,7 @@ class TableScan(BaseScan): """A base class for table scans targeting a single snapshot.""" snapshot_id: int | None + _branch_name: str | None catalog: Catalog | None table_identifier: Identifier | None table_config: Properties @@ -2310,6 +2314,8 @@ def __init__( table_identifier: Identifier | None = None, table_config: Properties = EMPTY_DICT, encryption_manager: EncryptionManager | None = None, + *, + _branch_name: str | None = None, ): super().__init__( table_metadata=table_metadata, @@ -2322,6 +2328,7 @@ def __init__( encryption_manager=encryption_manager, ) self.snapshot_id = snapshot_id + self._branch_name = _branch_name self.catalog = catalog self.table_identifier = table_identifier self.table_config = table_config @@ -2331,9 +2338,9 @@ def snapshot(self) -> Snapshot | None: return self.table_metadata.snapshot_by_id(self.snapshot_id) return self.table_metadata.current_snapshot() - def projection(self) -> Schema: + def _scan_schema(self) -> Schema: current_schema = self.table_metadata.schema() - if self.snapshot_id is not None: + if self.snapshot_id is not None and self._branch_name is None: snapshot = self.table_metadata.snapshot_by_id(self.snapshot_id) if snapshot is not None: if snapshot.schema_id is not None: @@ -2345,14 +2352,23 @@ def projection(self) -> Schema: warnings.warn(f"Metadata does not contain schema with id: {snapshot.schema_id}", stacklevel=2) else: raise ValueError(f"Snapshot not found: {self.snapshot_id}") + return current_schema + + def projection(self) -> Schema: + current_schema = self._scan_schema() return project_schema(current_schema, self.selected_fields, self.case_sensitive, self.table_metadata.format_version) def use_ref(self: S, name: str) -> S: + """Select a branch using the table schema or a tag using its snapshot schema.""" if self.snapshot_id is not None: raise ValueError(f"Cannot override ref, already set snapshot id={self.snapshot_id}") if snapshot := self.table_metadata.snapshot_by_name(name): - return self.update(snapshot_id=snapshot.snapshot_id) + ref = self.table_metadata.refs[name] + return self.update( + snapshot_id=snapshot.snapshot_id, + _branch_name=name if ref.snapshot_ref_type == SnapshotRefType.BRANCH else None, + ) raise ValueError(f"Cannot scan unknown ref={name}") @@ -2514,6 +2530,7 @@ def _to_arrow_via_file_scan_tasks( scan.case_sensitive, scan.limit, dictionary_columns=dictionary_columns, + row_filter_schema=scan._scan_schema(), ).to_table(tasks) @@ -2534,6 +2551,7 @@ def _to_arrow_batch_reader_via_file_scan_tasks( scan.case_sensitive, scan.limit, dictionary_columns=dictionary_columns, + row_filter_schema=scan._scan_schema(), ).to_record_batches(tasks) if dictionary_columns: @@ -2563,6 +2581,7 @@ def _manifest_planner(self) -> ManifestGroupPlanner: row_filter=self.row_filter, case_sensitive=self.case_sensitive, options=self.options, + schema=self._scan_schema(), ) @cached_property @@ -2699,6 +2718,7 @@ def count(self) -> int: projected_schema=self.projection(), row_filter=self.row_filter, case_sensitive=self.case_sensitive, + row_filter_schema=self._scan_schema(), ) tbl = arrow_scan.to_table([task]) res += len(tbl) @@ -2905,6 +2925,7 @@ class ManifestGroupPlanner: row_filter: BooleanExpression case_sensitive: bool options: Properties + schema: Schema def __init__( self, @@ -2913,6 +2934,7 @@ def __init__( row_filter: str | BooleanExpression = ALWAYS_TRUE, case_sensitive: bool = True, options: Properties = EMPTY_DICT, + schema: Schema | None = None, _ignore_residuals: bool = False, ): self.table_metadata = table_metadata @@ -2920,6 +2942,7 @@ def __init__( self.row_filter = _parse_row_filter(row_filter) self.case_sensitive = case_sensitive self.options = options + self.schema = schema if schema is not None else table_metadata.schema() # Set when the planned data files are read in full, as in a rewrite. Residuals are then always true, and delete # files are kept even if their bounds cannot match the row filter, as no residual drops the rows they delete. self._ignore_residuals = _ignore_residuals @@ -2986,9 +3009,7 @@ def plan_files( delete_index = DeleteFileIndex() residual_evaluators: dict[int, ResidualEvaluator] = KeyDefaultDict(self._build_residual_evaluator) - referenced_field_ids = extract_field_ids( - bind(self.table_metadata.schema(), self.row_filter, case_sensitive=self.case_sensitive) - ) + referenced_field_ids = extract_field_ids(bind(self.schema, self.row_filter, case_sensitive=self.case_sensitive)) partition_specs = self.table_metadata.specs() residual_cache_key_positions: dict[int, tuple[int, ...]] = KeyDefaultDict( lambda spec_id: tuple( @@ -3048,16 +3069,16 @@ def residual_for(data_file: DataFile) -> BooleanExpression: ] def _build_partition_projection(self, spec_id: int) -> BooleanExpression: - project = inclusive_projection(self.table_metadata.schema(), self.table_metadata.specs()[spec_id], self.case_sensitive) + project = inclusive_projection(self.schema, self.table_metadata.specs()[spec_id], self.case_sensitive) return project(self.row_filter) def _build_manifest_evaluator(self, spec_id: int) -> Callable[[ManifestFile], bool]: spec = self.table_metadata.specs()[spec_id] - return manifest_evaluator(spec, self.table_metadata.schema(), self.partition_filters[spec_id], self.case_sensitive) + return manifest_evaluator(spec, self.schema, self.partition_filters[spec_id], self.case_sensitive) def _build_partition_evaluator(self, spec_id: int) -> Callable[[DataFile], bool]: spec = self.table_metadata.specs()[spec_id] - partition_type = spec.partition_type(self.table_metadata.schema()) + partition_type = spec.partition_type(self.schema) partition_schema = Schema(*partition_type.fields) partition_expr = self.partition_filters[spec_id] evaluator = expression_evaluator(partition_schema, partition_expr, self.case_sensitive) @@ -3067,7 +3088,7 @@ def _build_partition_evaluator(self, spec_id: int) -> Callable[[DataFile], bool] return lambda data_file: evaluator(data_file.partition) def _build_metrics_evaluator(self) -> Callable[[DataFile], bool]: - schema = self.table_metadata.schema() + schema = self.schema include_empty_files = strtobool(self.options.get("include_empty_files", "false")) # Metrics evaluators keep file-specific state local to each call, so one @@ -3088,7 +3109,7 @@ def _build_residual_evaluator(self, spec_id: int) -> ResidualEvaluator: spec=spec, expr=self.row_filter, case_sensitive=self.case_sensitive, - schema=self.table_metadata.schema(), + schema=self.schema, ) @staticmethod diff --git a/pyiceberg/table/inspect.py b/pyiceberg/table/inspect.py index 4feba3d532..618303c5a7 100644 --- a/pyiceberg/table/inspect.py +++ b/pyiceberg/table/inspect.py @@ -403,7 +403,7 @@ def partitions( io=self.tbl.io, row_filter=row_filter, case_sensitive=case_sensitive, - snapshot_id=snapshot.snapshot_id, + snapshot_id=snapshot_id, encryption_manager=self.tbl.encryption_manager, ) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 439405d121..d260bb47dc 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -1510,6 +1510,20 @@ def test_identity_transform_column_projection(tmp_path: str, catalog: InMemoryCa ).to_arrow() == pa.table({"other_field": ["bar"]}) assert table.scan(row_filter="partition_id = 1 AND other_field = 'bar'", selected_fields=("other_field",)).count() == 1 + snapshot = table.current_snapshot() + assert snapshot is not None + with table.update_schema() as update: + update.rename_column("partition_id", "renamed_partition_id") + + scan = table.scan( + snapshot_id=snapshot.snapshot_id, + row_filter="partition_id = 1 AND other_field = 'bar'", + selected_fields=("other_field",), + ) + assert scan.to_arrow() == pa.table({"other_field": ["bar"]}) + assert scan.to_arrow_batch_reader().read_all().to_pydict() == {"other_field": ["bar"]} + assert scan.count() == 1 + @pytest.mark.parametrize( "partition_field_type, arrow_partition_type, partition_value, row_filter", @@ -6662,10 +6676,9 @@ def test_to_arrow_batch_reader_preserves_dictionary_columns(tmpdir: str) -> None # RecordBatchReader.cast(target_schema) was called with a plain schema, silently converting # dictionary arrays back to their value type so to_arrow_batch_reader(dictionary_columns=...) # .read_all() returned plain strings instead of dictionary-encoded arrays. - from pyiceberg.expressions import AlwaysTrue from pyiceberg.io.pyarrow import PyArrowFileIO from pyiceberg.partitioning import PartitionSpec - from pyiceberg.table import FileScanTask, _to_arrow_batch_reader_via_file_scan_tasks + from pyiceberg.table import DataScan, FileScanTask, _to_arrow_batch_reader_via_file_scan_tasks from pyiceberg.table.metadata import TableMetadataV2 arrow_schema = pa.schema( @@ -6693,17 +6706,9 @@ def test_to_arrow_batch_reader_preserves_dictionary_columns(tmpdir: str) -> None partition_specs=[PartitionSpec()], ) - class _MockScan: - def __init__(self) -> None: - self.table_metadata = table_metadata - self.io = PyArrowFileIO() - self.row_filter = AlwaysTrue() - self.case_sensitive = True - self.limit = None - tasks = [FileScanTask(data_file)] result = _to_arrow_batch_reader_via_file_scan_tasks( - _MockScan(), # type: ignore[arg-type] + DataScan(table_metadata=table_metadata, io=PyArrowFileIO()), iceberg_schema, tasks, dictionary_columns=("label",), diff --git a/tests/table/test_init.py b/tests/table/test_init.py index 547ca94fc9..7d0747e5b4 100644 --- a/tests/table/test_init.py +++ b/tests/table/test_init.py @@ -21,6 +21,7 @@ from pathlib import Path from typing import Any +import pyarrow as pa import pytest from pydantic import BaseModel, TypeAdapter, ValidationError from pytest_lazy_fixtures import lf @@ -444,6 +445,135 @@ def test_table_scan_projection_unknown_column(table_v2: Table) -> None: assert "Could not find column: 'a'" in str(exc_info.value) +def test_time_travel_row_filter_after_drop_and_readd(catalog: Catalog, arrow_table_simple: pa.Table) -> None: + catalog.create_namespace("default") + table = catalog.create_table("default.readded_column", schema=arrow_table_simple.schema) + table.append(arrow_table_simple) + snapshot = table.current_snapshot() + assert snapshot is not None + table.manage_snapshots().create_tag(snapshot.snapshot_id, "before_schema_change").commit() + + with table.update_schema() as update: + update.delete_column("bar") + with table.update_schema() as update: + update.add_column("bar", IntegerType()) + + for scan in ( + table.scan(snapshot_id=snapshot.snapshot_id, row_filter="bar >= 2"), + table.scan(row_filter="BAR >= 2", case_sensitive=False).use_ref("before_schema_change"), + ): + for selected_fields in (("*",), ("foo",)): + projected_scan = scan.select(*selected_fields) + expected = arrow_table_simple.slice(1) + if selected_fields != ("*",): + expected = expected.select(selected_fields) + assert projected_scan.to_arrow().to_pydict() == expected.to_pydict() + assert projected_scan.to_arrow_batch_reader().read_all().to_pydict() == expected.to_pydict() + assert projected_scan.count() == 2 + + for current_scan in (table.scan(row_filter="bar >= 2"), table.incremental_append_scan(row_filter="bar >= 2")): + assert current_scan.to_arrow().num_rows == 0 + assert current_scan.to_arrow_batch_reader().read_all().num_rows == 0 + assert table.scan(row_filter="bar >= 2").count() == 0 + assert table.scan(row_filter="bar IS NULL").count() == 3 + + +def test_branch_row_filter_after_drop_and_readd(catalog: Catalog, arrow_table_simple: pa.Table) -> None: + catalog.create_namespace("default") + table = catalog.create_table("default.branch_column_replacement", schema=arrow_table_simple.schema) + table.append(arrow_table_simple) + snapshot = table.current_snapshot() + assert snapshot is not None + table.manage_snapshots().create_branch(snapshot.snapshot_id, "audit").create_tag(snapshot.snapshot_id, "before").commit() + + with table.update_schema() as update: + update.delete_column("bar") + with table.update_schema() as update: + update.add_column("bar", IntegerType()) + + expected = {"foo": ["a", "b", "c"], "baz": [True, False, True], "bar": [None, None, None]} + for branch in (MAIN_BRANCH, "audit"): + scan = table.scan().use_ref(branch) + filtered = scan.with_case_sensitive(False).filter("BAR >= 2").select("foo") + assert filtered.to_arrow().to_pydict() == {"foo": []} + assert filtered.to_arrow_batch_reader().read_all().to_pydict() == {"foo": []} + assert filtered.count() == 0 + assert scan.projection() == table.schema() + assert scan.to_arrow().to_pydict() == expected + assert scan.to_arrow_batch_reader().read_all().to_pydict() == expected + assert scan.filter("bar IS NULL").count() == 3 + + for scan in (table.scan(snapshot_id=snapshot.snapshot_id), table.scan().use_ref("before")): + assert scan.to_arrow().to_pydict() == arrow_table_simple.to_pydict() + assert scan.filter("bar >= 2").select("foo").to_arrow().to_pydict() == {"foo": ["b", "c"]} + + +def test_branch_row_filter_after_column_rename(catalog: Catalog, arrow_table_simple: pa.Table) -> None: + catalog.create_namespace("default") + table = catalog.create_table("default.branch_column_rename", schema=arrow_table_simple.schema) + table.append(arrow_table_simple) + snapshot = table.current_snapshot() + assert snapshot is not None + table.manage_snapshots().create_branch(snapshot.snapshot_id, "audit").commit() + with table.update_schema() as update: + update.rename_column("bar", "score") + + for branch in (MAIN_BRANCH, "audit"): + scan = table.scan().use_ref(branch) + filtered = scan.with_case_sensitive(False).filter("SCORE >= 2").select("foo") + assert filtered.to_arrow().to_pydict() == {"foo": ["b", "c"]} + assert filtered.to_arrow_batch_reader().read_all().to_pydict() == {"foo": ["b", "c"]} + assert filtered.count() == 2 + assert scan.projection() == table.schema() + assert scan.to_arrow().to_pydict() == {"foo": ["a", "b", "c"], "score": [1, 2, 3], "baz": [True, False, True]} + with pytest.raises(ValueError, match="Could not find field with name bar"): + scan.filter("bar >= 2").to_arrow() + + +def test_time_travel_row_filter_after_partition_column_rename(catalog: Catalog, arrow_table_simple: pa.Table) -> None: + catalog.create_namespace("default") + table = catalog.create_table("default.renamed_partition_column", schema=arrow_table_simple.schema) + with table.update_spec() as update: + update.add_identity("baz") + table.append(arrow_table_simple) + snapshot = table.current_snapshot() + assert snapshot is not None + with table.update_schema() as update: + update.rename_column("baz", "enabled") + update.add_column("added", IntegerType()) + + scan = table.scan(snapshot_id=snapshot.snapshot_id, row_filter="baz = false", selected_fields=("foo",)) + tasks = list(scan.plan_files()) + assert len(tasks) == 1 + assert tasks[0].residual == AlwaysTrue() + assert scan.to_arrow().to_pydict() == {"foo": ["b"]} + assert scan.to_arrow_batch_reader().read_all().to_pydict() == {"foo": ["b"]} + assert scan.count() == 1 + + for column, row_filter in (("enabled", "enabled = false"), ("added", "added = 1")): + with pytest.raises(ValueError, match=f"Could not find field with name {column}"): + table.scan(snapshot_id=snapshot.snapshot_id, row_filter=row_filter).to_arrow() + assert table.scan(row_filter="enabled = false", selected_fields=("foo",)).to_arrow().to_pydict() == {"foo": ["b"]} + + +def test_delete_after_column_rename_uses_current_schema(catalog: Catalog, arrow_table_simple: pa.Table) -> None: + catalog.create_namespace("default") + for branch in (MAIN_BRANCH, "audit"): + table = catalog.create_table(f"default.delete_after_rename_{branch}", schema=arrow_table_simple.schema) + table.append(arrow_table_simple) + snapshot = table.current_snapshot() + assert snapshot is not None + if branch != MAIN_BRANCH: + table.manage_snapshots().create_branch(snapshot.snapshot_id, branch).commit() + with table.update_schema() as update: + update.rename_column("bar", "score") + + table.delete("score >= 2", branch=branch) + assert table.scan().use_ref(branch).to_arrow().to_pydict() == {"foo": ["a"], "score": [1], "baz": [True]} + if branch != MAIN_BRANCH: + assert table.scan().count() == 3 + + def test_table_scan_projection_row_lineage_columns(table_v3: Table) -> None: projection_schema = table_v3.scan().select("x", "_row_id", "_last_updated_sequence_number").projection() assert projection_schema == Schema( diff --git a/tests/table/test_inspect.py b/tests/table/test_inspect.py index e507b62f71..6614609e1a 100644 --- a/tests/table/test_inspect.py +++ b/tests/table/test_inspect.py @@ -76,6 +76,26 @@ def test_inspect_entries_and_files_render_null_bound(catalog: InMemoryCatalog) - assert files_metrics["upper_bound"] is None +def test_partitions_row_filter_after_column_rename(catalog: InMemoryCatalog) -> None: + schema = Schema(NestedField(1, "category", StringType())) + table = catalog.create_table( + "default.renamed_partition", + schema=schema, + partition_spec=PartitionSpec(PartitionField(1, 1000, IdentityTransform(), "category")), + ) + table.append(pa.table({"category": ["a", "b", "a"]})) + snapshot = table.current_snapshot() + assert snapshot is not None + with table.update_schema() as update: + update.rename_column("category", "cat") + + current = table.inspect.partitions(row_filter="cat = 'a'") + historical = table.inspect.partitions(snapshot_id=snapshot.snapshot_id, row_filter="category = 'a'") + expected = [{"partition": {"category": "a"}, "record_count": 2}] + assert current.select(["partition", "record_count"]).to_pylist() == expected + assert historical.select(["partition", "record_count"]).to_pylist() == expected + + def test_inspect_entries_and_files_with_data_file_without_metrics(catalog: InMemoryCatalog) -> None: # column_sizes and the other metric maps are optional in a data file schema = Schema(NestedField(1, "x", LongType(), required=False)) diff --git a/tests/table/test_upsert.py b/tests/table/test_upsert.py index 4291c18a55..4b80b5d7c0 100644 --- a/tests/table/test_upsert.py +++ b/tests/table/test_upsert.py @@ -427,6 +427,64 @@ def test_upsert_into_empty_table(catalog: Catalog) -> None: assert upd.rows_inserted == 4 +def test_upsert_uses_current_schema_after_join_column_change(catalog: Catalog) -> None: + for drop_existing in (False, True): + for branch in ("main", "audit", None): + original = pa.table({"value": [1, 2]}) + if drop_existing: + original = original.append_column("key", pa.array(["old", "keep"])) + table = catalog.create_table(f"default.changed_join_column_{drop_existing}_{branch}", schema=original.schema) + table.append(original) + snapshot = table.current_snapshot() + assert snapshot is not None + if branch == "audit": + table.manage_snapshots().create_branch(snapshot.snapshot_id, branch).commit() + if drop_existing: + with table.update_schema() as update: + update.delete_column("key") + with table.update_schema() as update: + update.add_column("key", StringType()) + + result = table.upsert(pa.table({"value": [3], "key": ["old"]}), join_cols=["key"], branch=branch) + assert_upsert_result(result, expected_updated=0, expected_inserted=1) + scan = table.scan(snapshot_id=table.snapshots()[-1].snapshot_id) if branch is None else table.scan().use_ref(branch) + assert sorted(scan.to_arrow().to_pylist(), key=lambda row: row["value"]) == [ + {"value": 1, "key": None}, + {"value": 2, "key": None}, + {"value": 3, "key": "old"}, + ] + if branch != "main": + assert table.metadata.current_snapshot_id == snapshot.snapshot_id + assert table.scan().count() == 2 + + +def test_upsert_projects_staged_schema_for_matched_rows(catalog: Catalog) -> None: + for branch in ("main", "audit"): + original = pa.table({"id": [1, 2], "value": [10, 20]}) + table = catalog.create_table(f"default.staged_upsert_schema_{branch}", schema=original.schema) + table.append(original) + snapshot = table.current_snapshot() + assert snapshot is not None + if branch == "audit": + table.manage_snapshots().create_branch(snapshot.snapshot_id, branch).commit() + + with table.transaction() as transaction: + with transaction.update_schema() as update: + update.add_column("note", StringType()) + result = transaction.upsert( + pa.table({"id": [1], "value": [11], "note": ["updated"]}), join_cols=["id"], branch=branch + ) + assert_upsert_result(result, expected_updated=1, expected_inserted=0) + + assert sorted(table.scan().use_ref(branch).to_arrow().to_pylist(), key=lambda row: row["id"]) == [ + {"id": 1, "value": 11, "note": "updated"}, + {"id": 2, "value": 20, "note": None}, + ] + if branch != "main": + assert table.metadata.current_snapshot_id == snapshot.snapshot_id + assert table.scan().to_arrow()["value"].to_pylist() == [10, 20] + + def test_create_match_filter_single_condition() -> None: """ Test create_match_filter with a composite key where the source yields exactly one unique key.