diff --git a/docs/decisions/2026-11-01-openlineage-fields-resolve-against-stored-columns.md b/docs/decisions/2026-11-01-openlineage-fields-resolve-against-stored-columns.md new file mode 100644 index 000000000000..3582ff5c6c11 --- /dev/null +++ b/docs/decisions/2026-11-01-openlineage-fields-resolve-against-stored-columns.md @@ -0,0 +1,41 @@ +# An OpenLineage field resolves through the stored columns, and a column it creates takes the connector's reserved-keyword name + +- **Status:** Accepted +- **Revisions:** v1 2026-11-01 (initial) +- **Deciders:** ccurve1870 +- **Guard:** `OpenLineageMapperTest`, `OpenLineageColumnMapperTest`, `test_openlineage.py::test_get_column_lineage_uses_stored_fqn_of_special_column_names`, `OpenLineageLineageResolutionIT#columnLineage_reachesStoredColumnsOfSpecialFieldNames` +- **Related:** #36788, #35969, #30211 + +## Context +OpenLineage producers report columns as the source names them, so a field can be `a>b` or `c.d`. +Since #30211 a column name cannot hold `::`, `>`, `"` or control characters, and connectors store +keywords in their place (`a__reserved__arrow__b`). A dot stays in the name and is quoted in the FQN +(`"c.d"`). A column FQN built by appending a field to the table FQN therefore misses these columns, +and `LineageRepository.validateLineageDetails` drops the entry without reporting it. Quoting every +dotted field is no answer either: `s.x` also names the child `x` of a struct `s`, and that FQN is +not quoted. + +## Decision +- A column FQN in OpenLineage lineage comes from the stored column, never from the field name + alone. +- On the server (`OpenLineageMapper`), a field resolves against a table's stored columns by the + dotted path of their names: first as sent, then with reserved keywords, and only then as + `.`. Trying it as sent first keeps a column stored with a raw `>` matching. + Datasets that are not tables always use `.`. +- In the connector (`OpenlineageSource._match_column_fqn`), a field matches a fetched column by + case-insensitive name and takes that column's `fullyQualifiedName`. A fetched name has its + reserved characters decoded, so it cannot be used to rebuild the FQN. +- A column created from an event takes `OpenLineageColumnMapper.toStoredName`, which must produce + what `replace_separators` in `custom_basemodel_validation.py` produces: `::`, `>`, `"`, newline, + carriage return and tab become `__reserved__colon__`, `__reserved__arrow__`, + `__reserved__quote__`, `__reserved__newline__`, `__reserved__carriage_return__` and + `__reserved__tab__`. + +## Consequences +- A later metadata ingestion updates a column created from an event instead of adding a second one. +- The keyword list lives in Python and Java, and no test ties the two together: changing one means + changing the other. +- A column literally named `s.x` and the child `x` of a struct `s` in the same table share one + field path, so a field reaches the one that comes later in the table. +- An event with column lineage reads the stored columns of its outputs and of each input it + references, once per event. diff --git a/ingestion/src/metadata/ingestion/source/pipeline/openlineage/metadata.py b/ingestion/src/metadata/ingestion/source/pipeline/openlineage/metadata.py index 062384f8c19d..f03045328aa1 100644 --- a/ingestion/src/metadata/ingestion/source/pipeline/openlineage/metadata.py +++ b/ingestion/src/metadata/ingestion/source/pipeline/openlineage/metadata.py @@ -560,13 +560,20 @@ def _get_by_name_cached(self, entity_class, fqn_str: str, **kwargs): return result @staticmethod - def _match_column_name(table, field_name: str) -> str | None: - """Resolve an OpenLineage field name to the real stored column name, case-insensitively.""" + def _match_column_fqn(table, table_fqn: str, field_name: str) -> str | None: + """ + Resolve an OpenLineage field name to the FQN of the real stored column, case-insensitively. + + The stored FQN cannot be rebuilt from the column name: a fetched name has its reserved + characters decoded (`a>b` is stored as `a__reserved__arrow__b`), and a dot in it is quoted + in the FQN (`"c.d"`). The server silently drops an entry that matches no real column. + A sharded table has no column to fall back to, so an unmatched field resolves to None. + """ lower = field_name.lower() for column in getattr(table, "columns", None) or []: if column.name.root.lower() == lower: - return column.name.root - return None if table and table.tableType == TableType.Sharded else lower + return model_str(column.fullyQualifiedName) + return None if table and table.tableType == TableType.Sharded else f"{table_fqn}.{lower}" def _build_db_service_type_map(self): """Build a map of {service_name: DatabaseServiceType} filtered to configured dbServiceNames.""" @@ -892,16 +899,18 @@ def _get_column_lineage(self, inputs: list, outputs: list) -> dict[str, dict[str if not input_table_fqn: continue input_table_entity = self._get_by_name_cached(Table, input_table_fqn, fields=["columns"]) - output_column = self._match_column_name(output_table_entity, field_name) - input_column = self._match_column_name(input_table_entity, input_field.get("field", "")) + output_column = self._match_column_fqn(output_table_entity, output_table_fqn, field_name) + input_column = self._match_column_fqn( + input_table_entity, input_table_fqn, input_field.get("field", "") + ) if not output_column or not input_column: continue _result.append( # output table, input table, output column, input column ( output_table_fqn, input_table_fqn, - f"{output_table_fqn}.{output_column}", - f"{input_table_fqn}.{input_column}", + output_column, + input_column, ) ) diff --git a/ingestion/tests/unit/topology/pipeline/test_openlineage.py b/ingestion/tests/unit/topology/pipeline/test_openlineage.py index d279f2fe1692..d8eabd0cc4ca 100644 --- a/ingestion/tests/unit/topology/pipeline/test_openlineage.py +++ b/ingestion/tests/unit/topology/pipeline/test_openlineage.py @@ -16,7 +16,7 @@ from metadata.generated.schema.api.lineage.addLineage import AddLineageRequest from metadata.generated.schema.entity.data.pipeline import Pipeline, Task -from metadata.generated.schema.entity.data.table import Table +from metadata.generated.schema.entity.data.table import Table, TableType from metadata.generated.schema.entity.services.connections.metadata.openMetadataConnection import ( OpenMetadataConnection, ) @@ -520,13 +520,16 @@ def test_get_column_lineage_valid_inputs_outputs(self, mock_build_map, mock_get_ self.assertEqual(result, expected) @staticmethod - def _mock_table_with_columns(*column_names): - """Build a lightweight stand-in for a Table entity with the given real column names.""" + def _mock_table_with_columns(table_fqn, fqn_segment_by_name): + """Build a lightweight stand-in for a Table entity with the given real columns. + + Keyed by the name a fetched column carries, with the spelling its FQN stores.""" table = Mock() columns = [] - for column_name in column_names: + for column_name, fqn_segment in fqn_segment_by_name.items(): column = Mock() column.name.root = column_name + column.fullyQualifiedName = FullyQualifiedEntityName(f"{table_fqn}.{fqn_segment}") columns.append(column) table.columns = columns return table @@ -548,8 +551,12 @@ def test_get_column_lineage_matches_stored_column_case( mock_build_map.return_value = { "sqlserver://host:1433/hk_schema.CASE_TEST_SOURCE": "database.schema.case_test_source", } - source_table = self._mock_table_with_columns("first_name", "last_name") - target_table = self._mock_table_with_columns("FIRST_NAME", "LAST_NAME") + source_table = self._mock_table_with_columns( + "database.schema.case_test_source", {"first_name": "first_name", "last_name": "last_name"} + ) + target_table = self._mock_table_with_columns( + "database.schema.case_test_target", {"FIRST_NAME": "FIRST_NAME", "LAST_NAME": "LAST_NAME"} + ) mock_get_by_name_cached.side_effect = lambda entity_class, fqn_str, **kwargs: ( target_table if fqn_str == "database.schema.case_test_target" else source_table ) @@ -608,6 +615,110 @@ def test_get_column_lineage_matches_stored_column_case( } self.assertEqual(result, expected) + @patch("metadata.ingestion.source.pipeline.openlineage.metadata.OpenlineageSource._get_by_name_cached") + @patch("metadata.ingestion.source.pipeline.openlineage.metadata.OpenlineageSource._get_table_fqn") + @patch("metadata.ingestion.source.pipeline.openlineage.metadata.OpenlineageSource._build_ol_name_to_fqn_map") + def test_get_column_lineage_uses_stored_fqn_of_special_column_names( + self, mock_build_map, mock_get_table_fqn, mock_get_by_name_cached + ): + """A column name with a reserved character or a dot is not its FQN segment, so + column lineage has to carry the stored FQN. An entry built as "." + matches no real column and the server silently drops it.""" + fqn_segment_by_name = { + "a>b": "a__reserved__arrow__b", + "c.d": '"c.d"', + "e.>f": '"e.__reserved__arrow__f"', + ".>": '".__reserved__arrow__"', + } + mock_get_table_fqn.side_effect = lambda table_details, namespace=None: f"database.schema.{table_details.name}" + mock_build_map.return_value = {"postgres://host:5432/db.schema.source": "database.schema.source"} + mock_get_by_name_cached.side_effect = lambda entity_class, fqn_str, **kwargs: self._mock_table_with_columns( + fqn_str, fqn_segment_by_name + ) + + outputs = [ + { + "name": "db.schema.target", + "namespace": "postgres://host:5432", + "facets": { + "columnLineage": { + "fields": { + column_name: { + "inputFields": [ + { + "field": column_name, + "namespace": "postgres://host:5432", + "name": "db.schema.source", + } + ] + } + for column_name in fqn_segment_by_name + } + } + }, + } + ] + result = self.open_lineage_source._get_column_lineage([], outputs) + + expected = { + "database.schema.target": { + "database.schema.source": [ + ColumnLineage( + toColumn=f"database.schema.target.{fqn_segment}", + fromColumns=[f"database.schema.source.{fqn_segment}"], + ) + for fqn_segment in fqn_segment_by_name.values() + ], + } + } + self.assertEqual(result, expected) + + @patch("metadata.ingestion.source.pipeline.openlineage.metadata.OpenlineageSource._get_by_name_cached") + @patch("metadata.ingestion.source.pipeline.openlineage.metadata.OpenlineageSource._get_table_fqn") + @patch("metadata.ingestion.source.pipeline.openlineage.metadata.OpenlineageSource._build_ol_name_to_fqn_map") + def test_get_column_lineage_drops_unmatched_field_of_sharded_table( + self, mock_build_map, mock_get_table_fqn, mock_get_by_name_cached + ): + """A sharded table has no column to fall back to, so a field it does not store is + dropped instead of becoming an invented "
." FQN.""" + sharded_source = self._mock_table_with_columns("database.schema.source", {"id": "id"}) + sharded_source.tableType = TableType.Sharded + target = self._mock_table_with_columns("database.schema.target", {"id": "id", "extra": "extra"}) + mock_get_table_fqn.side_effect = lambda table_details, namespace=None: f"database.schema.{table_details.name}" + mock_build_map.return_value = {"bigquery://host/db.schema.source": "database.schema.source"} + mock_get_by_name_cached.side_effect = lambda entity_class, fqn_str, **kwargs: ( + target if fqn_str == "database.schema.target" else sharded_source + ) + + outputs = [ + { + "name": "db.schema.target", + "namespace": "bigquery://host", + "facets": { + "columnLineage": { + "fields": { + column_name: { + "inputFields": [ + {"field": column_name, "namespace": "bigquery://host", "name": "db.schema.source"} + ] + } + for column_name in ("id", "extra") + } + } + }, + } + ] + result = self.open_lineage_source._get_column_lineage([], outputs) + + expected = { + "database.schema.target": { + "database.schema.source": [ + ColumnLineage(toColumn="database.schema.target.id", fromColumns=["database.schema.source.id"]), + ], + } + } + self.assertEqual(result, expected) + @patch("metadata.ingestion.source.pipeline.openlineage.metadata.OpenlineageSource._get_by_name_cached") @patch("metadata.ingestion.source.pipeline.openlineage.metadata.OpenlineageSource._get_table_fqn") @patch("metadata.ingestion.source.pipeline.openlineage.metadata.OpenlineageSource._build_ol_name_to_fqn_map") @@ -669,7 +780,7 @@ def test_get_column_lineage_falls_back_to_lowercase_when_table_entity_unavailabl def test_get_column_lineage_requests_columns_field( self, mock_build_map, mock_get_table_fqn, mock_get_by_name_cached ): - """_match_column_name only works if the fetched Table entity actually + """_match_column_fqn only works if the fetched Table entity actually has its columns populated. Table lookups must explicitly request the 'columns' field rather than relying on whatever the default response happens to include.""" diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenLineageLineageResolutionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenLineageLineageResolutionIT.java index f6e592b04c9c..c897928135c5 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenLineageLineageResolutionIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OpenLineageLineageResolutionIT.java @@ -23,11 +23,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; +import java.util.stream.Collectors; import org.awaitility.Awaitility; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; @@ -105,6 +108,17 @@ public class OpenLineageLineageResolutionIT { new Column().withName("id").withDataType(ColumnDataType.BIGINT), new Column().withName("name").withDataType(ColumnDataType.VARCHAR).withDataLength(255)); + private static final List COLUMNS_WITH_SPECIAL_NAMES = + List.of( + new Column().withName("a__reserved__arrow__b").withDataType(ColumnDataType.INT), + new Column().withName("c.d").withDataType(ColumnDataType.INT), + new Column().withName("e.__reserved__arrow__f").withDataType(ColumnDataType.INT), + new Column() + .withName("s") + .withDataType(ColumnDataType.STRUCT) + .withDataTypeDisplay("struct") + .withChildren(List.of(new Column().withName("x").withDataType(ColumnDataType.INT)))); + private static final String EVENT_TIME = "2024-01-15T10:00:00Z"; private static final long EVENT_TIME_MS = 1705312800000L; private static final List> FIELDS = @@ -1129,6 +1143,55 @@ void kafkaDataset_resolvesToTheTopicOfTheServiceListingItsBroker(TestNamespace n Entity.TOPIC, topic.getFullyQualifiedName(), schemaFqn + "." + outputName)); } + @Test + @Order(30) + @ResourceLock( + value = SharedResourceLocks.OPEN_LINEAGE_SETTINGS, + mode = ResourceAccessMode.READ_WRITE) + void columnLineage_reachesStoredColumnsOfSpecialFieldNames() throws Exception { + String namespace = uniqueDatasetNamespace(); + String inputName = "ol_special_in_" + uniqueSuffix(); + String outputName = "ol_special_out_" + uniqueSuffix(); + String inputDataset = "ecommerce_db.shopify." + inputName; + Table input = + Tables.create() + .name(inputName) + .inSchema(schemaFqn) + .withColumns(COLUMNS_WITH_SPECIAL_NAMES) + .execute(); + + JsonNode response = + withOpenLineageSettings( + autoCreateUnder(namespace), + () -> + send( + completeEvent("ol_special_ns", "ol_special_job_" + uniqueSuffix()) + .addInput(inputDataset, namespace) + .addOutput( + outputWithFieldLineage( + namespace, + "ecommerce_db.shopify." + outputName, + inputDataset, + Map.of("a>b", "a>b", "c.d", "c.d", "e.>f", "e.>f", "x", "s.x"))))); + + assertEquals("success", response.get("status").asText(), response.toString()); + Table output = + SdkClients.adminClient().tables().getByName(schemaFqn + "." + outputName, "columns"); + assertEquals( + Set.of("a__reserved__arrow__b", "c.d", "e.__reserved__arrow__f", "x"), + output.getColumns().stream().map(Column::getName).collect(Collectors.toSet())); + String inputFqn = input.getFullyQualifiedName(); + String outputFqn = output.getFullyQualifiedName(); + assertEquals( + Map.of( + outputFqn + ".a__reserved__arrow__b", List.of(inputFqn + ".a__reserved__arrow__b"), + outputFqn + ".\"c.d\"", List.of(inputFqn + ".\"c.d\""), + outputFqn + ".\"e.__reserved__arrow__f\"", + List.of(inputFqn + ".\"e.__reserved__arrow__f\""), + outputFqn + ".x", List.of(inputFqn + ".s.x")), + fromColumnsByToColumn(fetchOpenLineageEdgeDetails(inputName, outputName))); + } + // ==================================================================================== // Helpers // ==================================================================================== @@ -1214,6 +1277,43 @@ private static Map datasetWithColumns(String namespace, String n "namespace", namespace, "name", name, "facets", Map.of("schema", Map.of("fields", FIELDS))); } + private static Map outputWithFieldLineage( + String namespace, + String name, + String inputDataset, + Map inputFieldByOutputField) { + List> schemaFields = new ArrayList<>(); + Map lineageFields = new HashMap<>(); + inputFieldByOutputField.forEach( + (outputField, inputField) -> { + schemaFields.add(Map.of("name", outputField, "type", "int")); + lineageFields.put( + outputField, + Map.of( + "inputFields", + List.of( + Map.of("namespace", namespace, "name", inputDataset, "field", inputField)))); + }); + return Map.of( + "namespace", + namespace, + "name", + name, + "facets", + Map.of("schema", Map.of("fields", schemaFields)), + "outputFacets", + Map.of("columnLineage", Map.of("fields", lineageFields))); + } + + private static Map fromColumnsByToColumn(Map edgeDetails) { + return ((List) edgeDetails.get("columnsLineage")) + .stream() + .map(Map.class::cast) + .collect( + Collectors.toMap( + entry -> entry.get("toColumn"), entry -> entry.get("fromColumns"))); + } + private static String uniqueDatasetNamespace() { return "postgres://ol-it-" + uniqueSuffix() + ":5432"; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageColumnMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageColumnMapper.java index 9a8558ce7fc4..abf59bbd716b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageColumnMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageColumnMapper.java @@ -13,6 +13,7 @@ package org.openmetadata.service.openlineage; +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import java.util.ArrayList; @@ -34,7 +35,9 @@ * Turns OpenLineage schema-facet fields into columns that pass the same validation as a REST table * create. Sized types that arrive without a size fall back to their unsized family, arrays carry an * element type, and structs carry empty children because the facet does not describe nesting. The - * raw type is kept as the display type, so nothing the producer sent is lost. + * raw type is kept as the display type, so nothing the producer sent is lost. Names are stored the + * way connectors store them, so a later metadata ingestion updates these columns instead of adding + * new ones. */ final class OpenLineageColumnMapper { @@ -42,6 +45,13 @@ final class OpenLineageColumnMapper { private static final Pattern ARRAY_ELEMENT = Pattern.compile("^array\\s*<\\s*([a-z0-9_ ]+)"); private static final Pattern WHITESPACE = Pattern.compile("\\s+"); + private static final String RESERVED_COLON_KEYWORD = "__reserved__colon__"; + private static final String RESERVED_ARROW_KEYWORD = "__reserved__arrow__"; + private static final String RESERVED_QUOTE_KEYWORD = "__reserved__quote__"; + private static final String RESERVED_NEWLINE_KEYWORD = "__reserved__newline__"; + private static final String RESERVED_CARRIAGE_RETURN_KEYWORD = "__reserved__carriage_return__"; + private static final String RESERVED_TAB_KEYWORD = "__reserved__tab__"; + /** Spellings that Spark, Postgres and other producers emit for an OpenMetadata type. */ private static final Map PRODUCER_TYPE_ALIASES = Map.ofEntries( @@ -87,7 +97,10 @@ static List toColumns(DatasetFacets facets) { static Column toColumn(SchemaField field) { String rawType = field.getType() == null ? "" : field.getType().trim(); - Column column = new Column().withName(field.getName()).withDescription(field.getDescription()); + Column column = + new Column() + .withName(toStoredName(field.getName())) + .withDescription(field.getDescription()); if (!rawType.isEmpty()) { column.setDataTypeDisplay(rawType); } @@ -95,6 +108,42 @@ static Column toColumn(SchemaField field) { return column; } + /** + * The table schema refuses these sequences in a column name, so ingestion stores keywords in their + * place. Must stay in step with {@code replace_separators} in {@code + * custom_basemodel_validation.py}, which writes the names this has to match: + * ADR:2026-11-01-openlineage-fields-resolve-against-stored-columns. + */ + static String toStoredName(String fieldName) { + return fieldName + .replace("::", RESERVED_COLON_KEYWORD) + .replace(">", RESERVED_ARROW_KEYWORD) + .replace("\"", RESERVED_QUOTE_KEYWORD) + .replace("\n", RESERVED_NEWLINE_KEYWORD) + .replace("\r", RESERVED_CARRIAGE_RETURN_KEYWORD) + .replace("\t", RESERVED_TAB_KEYWORD); + } + + /** + * Column FQNs by the dotted path a field names them with. An FQN cannot be built from that path: + * a column literally named {@code c.d} is {@code "c.d"} in its FQN, while the child {@code d} of + * a struct {@code c} is {@code c.d}. + */ + static Map fqnsByFieldPath(List columns) { + Map fqnsByFieldPath = new HashMap<>(); + addFqnsByFieldPath(columns, "", fqnsByFieldPath); + return fqnsByFieldPath; + } + + private static void addFqnsByFieldPath( + List columns, String parentPath, Map fqnsByFieldPath) { + for (Column column : listOrEmpty(columns)) { + String path = parentPath + column.getName(); + fqnsByFieldPath.put(path, column.getFullyQualifiedName()); + addFqnsByFieldPath(column.getChildren(), path + ".", fqnsByFieldPath); + } + } + static ColumnDataType toDataType(String lowerCaseType) { return TYPES_BY_NAME.getOrDefault(baseTypeName(lowerCaseType), ColumnDataType.UNKNOWN); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageEntityResolver.java b/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageEntityResolver.java index 72486763dd94..fda3402f9bad 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageEntityResolver.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageEntityResolver.java @@ -35,6 +35,7 @@ import org.openmetadata.schema.api.lineage.openlineage.OpenLineageOutputDataset; import org.openmetadata.schema.entity.data.Container; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.service.Entity; @@ -125,6 +126,17 @@ private EntityReference resolveTableInternal( } } + /** Field names are only matched on tables: other datasets keep the field as the event sent it. */ + public List storedColumns(EntityReference dataset) { + List columns = List.of(); + if (Entity.TABLE.equals(dataset.getType())) { + Table table = + Entity.getEntity(Entity.TABLE, dataset.getId(), Entity.FIELD_COLUMNS, NON_DELETED); + columns = table.getColumns(); + } + return columns; + } + public OpenLineageResolution resolveDataset(OpenLineageInputDataset dataset, String updatedBy) { return resolveDataset( dataset.getNamespace(), dataset.getName(), dataset.getFacets(), updatedBy); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageMapper.java index b855fae1a898..794c7635c3be 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/openlineage/OpenLineageMapper.java @@ -61,6 +61,19 @@ private record OpenLineageName(String namespace, String name) {} private record EdgeDetails( String description, EntityReference pipeline, String sqlQuery, long eventTimeMs) {} + /** + * The stored columns of one dataset, which say how a field is written in a column FQN. A field + * with no stored column keeps its spelling, and the lineage write drops it. + */ + private record DatasetColumns(String datasetFqn, Map fqnsByFieldPath) { + String columnFqn(String field) { + String storedFqn = + fqnsByFieldPath.getOrDefault( + field, fqnsByFieldPath.get(OpenLineageColumnMapper.toStoredName(field))); + return storedFqn != null ? storedFqn : datasetFqn + "." + field; + } + } + private final OpenLineageEntityResolver entityResolver; private final Set allowedEventTypes; @@ -149,12 +162,13 @@ private List buildEdges( EdgeDetails details, Map inputs, Map outputs) { - Map inputNameToFqnMap = buildInputFqnMap(inputs); + Map inputsByName = indexInputsByName(inputs); + Map inputColumns = new HashMap<>(); List lineageRequests = new ArrayList<>(); outputs.forEach( (output, outputRef) -> { List columnLineages = - extractColumnLineage(output, inputNameToFqnMap, outputRef.getFullyQualifiedName()); + extractColumnLineage(output, inputsByName, inputColumns, outputRef); for (EntityReference inputRef : inputs.values()) { List relevantColumnLineage = filterColumnLineageForInput(columnLineages, inputRef.getFullyQualifiedName()); @@ -240,17 +254,21 @@ private static Long parseNominalStartTime(OpenLineageRunEvent event) { return resolved; } - private Map buildInputFqnMap( + private Map indexInputsByName( Map inputs) { - Map map = new HashMap<>(); + Map map = new HashMap<>(); inputs.forEach( (input, ref) -> - map.put( - buildOpenLineageDatasetName(input.getNamespace(), input.getName()), - ref.getFullyQualifiedName())); + map.put(buildOpenLineageDatasetName(input.getNamespace(), input.getName()), ref)); return map; } + private DatasetColumns readColumns(EntityReference dataset) { + return new DatasetColumns( + dataset.getFullyQualifiedName(), + OpenLineageColumnMapper.fqnsByFieldPath(entityResolver.storedColumns(dataset))); + } + private EntityReference resolvePipeline( OpenLineageRunEvent event, List unresolvedJobs) { OpenLineageName job = pipelineJob(event); @@ -306,7 +324,10 @@ private String extractSqlQuery(OpenLineageRunEvent event) { } private List extractColumnLineage( - OpenLineageOutputDataset output, Map inputNameToFqnMap, String outputFqn) { + OpenLineageOutputDataset output, + Map inputsByName, + Map inputColumns, + EntityReference outputRef) { List columnLineages = new ArrayList<>(); @@ -323,6 +344,8 @@ private List extractColumnLineage( return columnLineages; } + DatasetColumns outputColumns = readColumns(outputRef); + Fields fieldsWrapper = columnLineageFacet.getFields(); Map fields = fieldsWrapper.getAdditionalProperties(); for (Map.Entry entry : fields.entrySet()) { @@ -337,19 +360,19 @@ private List extractColumnLineage( for (InputField inputField : fieldInfo.getInputFields()) { String inputOlName = buildOpenLineageDatasetName(inputField.getNamespace(), inputField.getName()); - String inputFqn = inputNameToFqnMap.get(inputOlName); - if (inputFqn != null) { - String columnFqn = inputFqn + "." + inputField.getField(); - fromColumns.add(columnFqn); + EntityReference inputRef = inputsByName.get(inputOlName); + if (inputRef != null) { + DatasetColumns input = + inputColumns.computeIfAbsent(inputOlName, name -> readColumns(inputRef)); + fromColumns.add(input.columnFqn(inputField.getField())); } } if (!fromColumns.isEmpty()) { - String toColumn = outputFqn + "." + outputColumnName; ColumnLineage columnLineage = new ColumnLineage() .withFromColumns(fromColumns) - .withToColumn(toColumn) + .withToColumn(outputColumns.columnFqn(outputColumnName)) .withFunction(fieldInfo.getTransformationDescription()); columnLineages.add(columnLineage); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageColumnMapperTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageColumnMapperTest.java index 7324b105aaa8..e8b3aa3bfb87 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageColumnMapperTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageColumnMapperTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; +import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -111,6 +112,49 @@ void missingTypeIsUnknown() { OpenLineageColumnMapper.toColumn(new SchemaField().withName("c")).getDataType()); } + @Test + void reservedSequencesBecomeTheKeywordsConnectorsStore() { + assertEquals("a__reserved__arrow__b", OpenLineageColumnMapper.toStoredName("a>b")); + assertEquals("a__reserved__colon__b", OpenLineageColumnMapper.toStoredName("a::b")); + assertEquals("a__reserved__quote__b", OpenLineageColumnMapper.toStoredName("a\"b")); + assertEquals("a__reserved__newline__b", OpenLineageColumnMapper.toStoredName("a\nb")); + assertEquals("a__reserved__carriage_return__b", OpenLineageColumnMapper.toStoredName("a\rb")); + assertEquals("a__reserved__tab__b", OpenLineageColumnMapper.toStoredName("a\tb")); + } + + @Test + void namesWithoutReservedSequencesAreStoredUnchanged() { + assertEquals("c.d", OpenLineageColumnMapper.toStoredName("c.d")); + assertEquals("a:b", OpenLineageColumnMapper.toStoredName("a:b")); + } + + @Test + void createdColumnTakesItsStoredName() { + Column column = + OpenLineageColumnMapper.toColumn(new SchemaField().withName("a>b").withType("int")); + + assertEquals("a__reserved__arrow__b", column.getName()); + } + + @Test + void fieldPathsTellADottedNameFromANestedChild() { + Column dotted = new Column().withName("c.d").withFullyQualifiedName("table.\"c.d\""); + Column struct = + new Column() + .withName("s") + .withFullyQualifiedName("table.s") + .withChildren(List.of(new Column().withName("x").withFullyQualifiedName("table.s.x"))); + + assertEquals( + Map.of("c.d", "table.\"c.d\"", "s", "table.s", "s.x", "table.s.x"), + OpenLineageColumnMapper.fqnsByFieldPath(List.of(dotted, struct))); + } + + @Test + void noColumnsGiveNoFieldPaths() { + assertTrue(OpenLineageColumnMapper.fqnsByFieldPath(null).isEmpty()); + } + @Test void everyMappedColumnPassesTableCreateValidation() { List rawTypes = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageEntityResolverTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageEntityResolverTest.java index b7ec45f4cd31..a0144c3e18e7 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageEntityResolverTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageEntityResolverTest.java @@ -24,6 +24,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import static org.openmetadata.schema.type.Include.NON_DELETED; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; @@ -51,6 +52,7 @@ import org.openmetadata.schema.api.lineage.openlineage.UnresolvedReason; import org.openmetadata.schema.entity.data.Container; import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.service.Entity; @@ -63,6 +65,33 @@ class OpenLineageEntityResolverTest { + @Test + void storedColumns_readsTheColumnsOfATable() { + UUID tableId = UUID.randomUUID(); + List columns = List.of(new Column().withName("a__reserved__arrow__b")); + OpenLineageEntityResolver resolver = new OpenLineageEntityResolver(false, "openlineage"); + + try (MockedStatic mockedEntity = mockStatic(Entity.class)) { + mockedEntity + .when(() -> Entity.getEntity(Entity.TABLE, tableId, Entity.FIELD_COLUMNS, NON_DELETED)) + .thenReturn(new Table().withColumns(columns)); + + assertEquals( + columns, + resolver.storedColumns(new EntityReference().withId(tableId).withType(Entity.TABLE))); + } + } + + @Test + void storedColumns_isEmptyForADatasetThatIsNotATable() { + OpenLineageEntityResolver resolver = new OpenLineageEntityResolver(false, "openlineage"); + + assertTrue( + resolver + .storedColumns(new EntityReference().withId(UUID.randomUUID()).withType(Entity.TOPIC)) + .isEmpty()); + } + @Test void resolveTable_nullDataset_returnsNull() { OpenLineageEntityResolver resolver = new OpenLineageEntityResolver(false, "openlineage"); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageMapperTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageMapperTest.java index bf44a9d9be18..b3e95116bfec 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageMapperTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/openlineage/OpenLineageMapperTest.java @@ -47,6 +47,7 @@ import org.openmetadata.schema.api.lineage.openlineage.UnresolvedReason; import org.openmetadata.schema.configuration.OpenLineageEventType; import org.openmetadata.schema.configuration.OpenLineageSettings; +import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.ColumnLineage; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.LineageDetails; @@ -58,6 +59,8 @@ class OpenLineageMapperTest { private OpenLineageMapper mapper; private static final String UPDATED_BY = "test_user"; + private static final String INPUT_FQN = "service.db.schema.input_table"; + private static final String OUTPUT_FQN = "service.db.schema.output_table"; @BeforeEach void setUp() { @@ -755,6 +758,104 @@ void mapRunEvent_columnLineageInDatasetFacets_extractsColumnLineage() { assertEquals("service.db.schema.output_table.dst_col", columnLineages.get(0).getToColumn()); } + @Test + void mapRunEvent_fieldWithReservedCharacter_reachesTheStoredColumn() { + ColumnLineage columnLineage = + columnLineageBetween( + "a>b", + List.of(storedColumn("a__reserved__arrow__b", INPUT_FQN + ".a__reserved__arrow__b")), + "a>b", + List.of(storedColumn("a__reserved__arrow__b", OUTPUT_FQN + ".a__reserved__arrow__b"))); + + assertEquals(OUTPUT_FQN + ".a__reserved__arrow__b", columnLineage.getToColumn()); + assertEquals(List.of(INPUT_FQN + ".a__reserved__arrow__b"), columnLineage.getFromColumns()); + } + + @Test + void mapRunEvent_fieldWithDot_reachesTheQuotedColumn() { + ColumnLineage columnLineage = + columnLineageBetween( + "c.d", + List.of(storedColumn("c.d", INPUT_FQN + ".\"c.d\"")), + "c.d", + List.of(storedColumn("c.d", OUTPUT_FQN + ".\"c.d\""))); + + assertEquals(OUTPUT_FQN + ".\"c.d\"", columnLineage.getToColumn()); + assertEquals(List.of(INPUT_FQN + ".\"c.d\""), columnLineage.getFromColumns()); + } + + @Test + void mapRunEvent_fieldWithDotAndReservedCharacter_reachesTheQuotedStoredColumn() { + String stored = "e.__reserved__arrow__f"; + + ColumnLineage columnLineage = + columnLineageBetween( + "e.>f", + List.of(storedColumn(stored, INPUT_FQN + ".\"" + stored + "\"")), + "e.>f", + List.of(storedColumn(stored, OUTPUT_FQN + ".\"" + stored + "\""))); + + assertEquals(OUTPUT_FQN + ".\"" + stored + "\"", columnLineage.getToColumn()); + assertEquals(List.of(INPUT_FQN + ".\"" + stored + "\""), columnLineage.getFromColumns()); + } + + @Test + void mapRunEvent_dottedPathOfNestedColumn_reachesTheChild() { + Column struct = + storedColumn("s", INPUT_FQN + ".s") + .withChildren(List.of(storedColumn("x", INPUT_FQN + ".s.x"))); + + ColumnLineage columnLineage = columnLineageBetween("s.x", List.of(struct), "target", List.of()); + + assertEquals(List.of(INPUT_FQN + ".s.x"), columnLineage.getFromColumns()); + } + + @Test + void mapRunEvent_columnStoredWithReservedCharacter_keepsItsName() { + ColumnLineage columnLineage = + columnLineageBetween( + "a>b", List.of(storedColumn("a>b", INPUT_FQN + ".a>b")), "target", List.of()); + + assertEquals(List.of(INPUT_FQN + ".a>b"), columnLineage.getFromColumns()); + } + + @Test + void mapRunEvent_fieldWithoutStoredColumn_keepsItsSpelling() { + ColumnLineage columnLineage = + columnLineageBetween("missing.col", List.of(), "target", List.of()); + + assertEquals(OUTPUT_FQN + ".target", columnLineage.getToColumn()); + assertEquals(List.of(INPUT_FQN + ".missing.col"), columnLineage.getFromColumns()); + } + + @Test + void mapRunEvent_severalOutputs_readEachReferencedInputOnce() { + OpenLineageInputDataset referenced = createInputDataset("ns", "schema.referenced"); + OpenLineageInputDataset unreferenced = createInputDataset("ns", "schema.unreferenced"); + OpenLineageOutputDataset first = outputFedBy("schema.first", "schema.referenced", "a", "a"); + OpenLineageOutputDataset second = outputFedBy("schema.second", "schema.referenced", "b", "b"); + OpenLineageRunEvent event = createBaseEvent(EventType.COMPLETE); + event.setInputs(List.of(referenced, unreferenced)); + event.setOutputs(List.of(first, second)); + + EntityReference referencedRef = createEntityReference("i1", "svc.db.schema.referenced"); + EntityReference unreferencedRef = createEntityReference("i2", "svc.db.schema.unreferenced"); + when(entityResolver.resolveDataset(eq(referenced), eq(UPDATED_BY))) + .thenReturn(dataset(referencedRef)); + when(entityResolver.resolveDataset(eq(unreferenced), eq(UPDATED_BY))) + .thenReturn(dataset(unreferencedRef)); + when(entityResolver.resolveDataset(eq(first), eq(UPDATED_BY))) + .thenReturn(dataset(createEntityReference("o1", "svc.db.schema.first"))); + when(entityResolver.resolveDataset(eq(second), eq(UPDATED_BY))) + .thenReturn(dataset(createEntityReference("o2", "svc.db.schema.second"))); + when(entityResolver.resolvePipeline(anyString(), anyString())).thenReturn(pipeline(null)); + + mapper.mapRunEvent(event, UPDATED_BY); + + verify(entityResolver, times(1)).storedColumns(referencedRef); + verify(entityResolver, never()).storedColumns(unreferencedRef); + } + @Test void mapRunEvent_noColumnLineageFacet_noColumnLineageInResult() { OpenLineageRunEvent event = createBaseEvent(EventType.COMPLETE); @@ -788,6 +889,54 @@ private OpenLineageRunEvent createBaseEvent(EventType eventType) { .withJob(new OpenLineageJob().withNamespace("test-namespace").withName("test-job")); } + /** Maps an event with one column-lineage entry over tables holding the given stored columns. */ + private ColumnLineage columnLineageBetween( + String inputField, + List inputColumns, + String outputField, + List outputColumns) { + OpenLineageInputDataset input = createInputDataset("ns", "schema.input_table"); + OpenLineageOutputDataset output = + outputFedBy("schema.output_table", "schema.input_table", inputField, outputField); + OpenLineageRunEvent event = createBaseEvent(EventType.COMPLETE); + event.setInputs(List.of(input)); + event.setOutputs(List.of(output)); + + EntityReference inputRef = createEntityReference("i1", INPUT_FQN); + EntityReference outputRef = createEntityReference("o1", OUTPUT_FQN); + when(entityResolver.resolveDataset(eq(input), eq(UPDATED_BY))).thenReturn(dataset(inputRef)); + when(entityResolver.resolveDataset(eq(output), eq(UPDATED_BY))).thenReturn(dataset(outputRef)); + when(entityResolver.resolvePipeline(anyString(), anyString())).thenReturn(pipeline(null)); + when(entityResolver.storedColumns(inputRef)).thenReturn(inputColumns); + when(entityResolver.storedColumns(outputRef)).thenReturn(outputColumns); + + List result = mapper.mapRunEvent(event, UPDATED_BY).lineageRequests(); + + return result.getFirst().getEdge().getLineageDetails().getColumnsLineage().getFirst(); + } + + private OpenLineageOutputDataset outputFedBy( + String outputName, String inputName, String inputField, String outputField) { + Fields fields = new Fields(); + fields.setAdditionalProperty( + outputField, + new ColumnLineageField() + .withInputFields( + List.of( + new InputField() + .withNamespace("ns") + .withName(inputName) + .withField(inputField)))); + OpenLineageOutputDataset output = createOutputDataset("ns", outputName); + output.setOutputFacets( + new OutputDatasetFacets().withColumnLineage(new ColumnLineageFacet().withFields(fields))); + return output; + } + + private static Column storedColumn(String name, String fullyQualifiedName) { + return new Column().withName(name).withFullyQualifiedName(fullyQualifiedName); + } + private OpenLineageInputDataset createInputDataset(String namespace, String name) { return new OpenLineageInputDataset().withNamespace(namespace).withName(name); }