Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.linkedin.datahub.graphql.types.common.mappers.DocumentationMapper;
import com.linkedin.datahub.graphql.types.common.mappers.InstitutionalMemoryMapper;
import com.linkedin.datahub.graphql.types.common.mappers.OwnershipMapper;
import com.linkedin.datahub.graphql.types.common.mappers.StringMapMapper;
import com.linkedin.datahub.graphql.types.common.mappers.util.SystemMetadataUtils;
import com.linkedin.datahub.graphql.types.common.mappers.util.UnknownEnumValues;
import com.linkedin.datahub.graphql.types.domain.DomainAssociationMapper;
Expand Down Expand Up @@ -421,6 +422,9 @@ private static com.linkedin.datahub.graphql.generated.OkfProperties mapOkfProper
.map(DocumentMapper::mapOkfStamp)
.collect(java.util.stream.Collectors.toList()));
}
if (properties.hasExtensions()) {
result.setExtensions(StringMapMapper.map(null, properties.getExtensions()));
}
result.setRaw(properties.getRaw());
result.setFrontmatter(parseOkfFrontmatter(properties.getRaw()));
if (properties.hasRevision()) {
Expand Down
7 changes: 7 additions & 0 deletions datahub-graphql-core/src/main/resources/documents.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,13 @@ type OkfProperties {
"""
verified: [OkfStamp!]

"""
Producer extensions: the frontmatter keys that no other field maps, such as x-domain or audience, keyed as written.
Scalars are strings, a list of scalars is joined with ", ", and nested objects become dotted keys (x-team.lead) up to three levels.
Searchable and filterable as key=value through the okfExtensions field.
"""
extensions: [StringMapEntry!]

"""
The frontmatter keys as a JSON object, parsed from `raw` when read
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1402,6 +1402,9 @@ public void testMapDocumentWithOkfProperties() {
.setStaleAfter(LAST_OBSERVED_TIME)
.setGenerated(generated)
.setVerified(new OkfStampArray(java.util.List.of(verified)))
.setExtensions(
new com.linkedin.data.template.StringMap(
java.util.Map.of("audience", "analysts", "reviewed", "2026-01-01")))
.setRaw(raw)
.setRevision(revision);
addAspectToResponse(entityResponse, OKF_PROPERTIES_ASPECT_NAME, properties);
Expand All @@ -1425,6 +1428,13 @@ public void testMapDocumentWithOkfProperties() {
assertEquals(mapped.getVerified().get(0).getBy(), "human:alice");
assertEquals(mapped.getVerified().get(0).getAt(), INGESTION_TIME);
assertEquals(mapped.getFrontmatter(), frontmatter);
assertEquals(
mapped.getExtensions().stream()
.collect(
java.util.stream.Collectors.toMap(
com.linkedin.datahub.graphql.generated.StringMapEntry::getKey,
com.linkedin.datahub.graphql.generated.StringMapEntry::getValue)),
java.util.Map.of("audience", "analysts", "reviewed", "2026-01-01"));
assertEquals(mapped.getRaw(), raw);
assertNotNull(mapped.getRevision());
assertEquals(mapped.getRevision().getRef(), "main");
Expand Down Expand Up @@ -1475,6 +1485,7 @@ public void testMapDocumentWithOptionalOkfFieldsUnset() {
assertNull(mapped.getDeclaredId());
assertNull(mapped.getStatus());
assertNull(mapped.getStaleAfter());
assertNull(mapped.getExtensions());
assertNull(mapped.getGenerated().getAt());
assertNull(mapped.getVerified().get(0).getAt());
assertNull(mapped.getRevision().getRef());
Expand Down
10 changes: 10 additions & 0 deletions metadata-ingestion/docs/sources/github/github-documents_post.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ The file location is the bundle location followed by its root path and `conceptI

GraphQL exposes a read-only, nullable `okfProperties.frontmatter` field containing the keys as a JSON object parsed from `raw` when read. It returns null if parsing fails. Dates remain strings. Ingestion validates JSON-compatible YAML values, rejecting duplicate keys, non-string keys, anchors, and aliases, but stores no JSON copy. Frontmatter blocks are limited to 64 KiB, including delimiters. Unsafe or oversized frontmatter is imported as plain text with a parse warning. Unknown keys remain in `raw`.

Keys that none of the mappings above use are producer extensions: `x-domain: finance` in OKF 0.3, which prefixes custom keys with `x-`, or `domain: finance` in earlier bundles. `x-datahub-id`, `x-datahub-owners` and `x-datahub-glossary_terms` are reserved as OKF 0.3 spellings of the mapped keys they name, so they are never extensions. Extensions are also copied to `okfProperties.extensions`, a string map that search indexes, keyed as written:

- A string, number, or boolean is stored as text: `true`, `2`, `0.5`. Dates are strings already.
- A list of scalars is joined with `, `, so `audience: [analysts, engineers]` is stored as `analysts, engineers`.
- A nested object is flattened into dotted keys, up to three levels: `x-team: {lead: alice}` is stored as `x-team.lead` = `alice`. Deeper values are left out. If a flattened key matches a key written with dots, the first in the file is kept.
- Lists that contain objects, lists, or nulls, and null or empty values, are left out: an empty value counts as absent. They stay in `raw` and in `frontmatter`.
- At most 50 keys per concept are kept, in frontmatter order. A key longer than 100 characters or containing `=`, and a value longer than 1,000 characters, are left out. Each file with keys left out for these limits, nested too deeply or colliding, produces one warning and adds to `okf_extensions_dropped`.

Search indexes each entry as `key=value` in the `okfExtensions` field, the same way as `customProperties`. To find concepts by an extension, filter on `okfExtensions` with the value `x-domain=finance` (or `domain=finance` for a bare key). `EQUAL` is exact and case-sensitive, `IEQUAL` ignores case, and a list matches only its whole joined value. `START_WITH` with `x-domain=` finds concepts that declare the key. Extension words are also matched by full-text search. GraphQL returns the map as `okfProperties.extensions`, a list of key-value entries. Concepts imported before this field existed get it on their next import.

Status strings are kept as written, including unknown values. An omitted status remains unset in the aspect. OKF consumers can apply the spec's implicit `stable` default. Timestamps require ISO 8601 datetimes with an explicit offset and are stored as epoch milliseconds. An invalid timestamp produces a warning and leaves the typed timestamp null. Its original value stays in raw YAML. `generated.by` and `verified[].by` retain the producer's actor strings. A single `verified` object is normalized to a one-element list.

`index.md` and `log.md` are reserved at every level inside a bundle. They remain imported documents and receive no concept aspect or native OKF mapping, even if they contain `type`. All index and log files retain their full text, including frontmatter. Files outside bundles, non-Markdown files, and files without `type` retain their original text. Malformed concept frontmatter is also imported verbatim with a warning.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
is_okf_concept,
)
from datahub.ingestion.source.repository_documents.okf_metadata import (
parse_extensions,
parse_stamp,
parse_status,
parse_timestamp,
Expand All @@ -39,7 +40,7 @@
from datahub.metadata.urns import Urn
from datahub.specific.document import DocumentPatchBuilder

MAPPING_VERSION = "6"
MAPPING_VERSION = "7"
# The frontmatter keys whose values are references to other entities.
OkfReferenceKey = Literal["owners", "tags", "glossary_terms"]

Expand All @@ -54,6 +55,17 @@
"type": "subTypes",
**{str(key): target for key, target in REFERENCE_MAPPINGS.items()},
}
# Keys with their own okfProperties field. With NATIVE_MAPPINGS and the
# aliases below, everything else is a producer extension and goes to
# okfProperties.extensions.
OKF_PROPERTY_KEYS = frozenset(
{"id", "description", "status", "stale_after", "generated", "verified"}
)
# OKF 0.3 spellings of mapped keys, accepted as aliases.
MAPPED_KEY_ALIASES = frozenset(
{"x-datahub-id", "x-datahub-owners", "x-datahub-glossary_terms"}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: These aliases are removed from searchable extensions but never mapped to their canonical fields, so x-datahub-id, x-datahub-owners, and x-datahub-glossary_terms are silently lost from derived metadata. Normalize the aliases before typed mapping or make the typed mapping read both spellings while retaining the exclusion from extensions.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/src/datahub/ingestion/source/repository_documents/okf_mapping.py, line 66:

<comment>These aliases are removed from searchable extensions but never mapped to their canonical fields, so `x-datahub-id`, `x-datahub-owners`, and `x-datahub-glossary_terms` are silently lost from derived metadata. Normalize the aliases before typed mapping or make the typed mapping read both spellings while retaining the exclusion from extensions.</comment>

<file context>
@@ -54,6 +55,17 @@
+)
+# OKF 0.3 spellings of mapped keys, accepted as aliases.
+MAPPED_KEY_ALIASES = frozenset(
+    {"x-datahub-id", "x-datahub-owners", "x-datahub-glossary_terms"}
+)
+MAPPED_KEYS = OKF_PROPERTY_KEYS | frozenset(NATIVE_MAPPINGS) | MAPPED_KEY_ALIASES
</file context>

)
MAPPED_KEYS = OKF_PROPERTY_KEYS | frozenset(NATIVE_MAPPINGS) | MAPPED_KEY_ALIASES
EMAIL_PATTERN = re.compile(r"[^\s@]+@[^\s@]+\.[^\s@]+")


Expand Down Expand Up @@ -197,6 +209,9 @@ def unresolved(key: str, message: Optional[str] = None) -> None:
else None
),
verified=parse_verified(values, path=file_path, report=report),
extensions=parse_extensions(
values, mapped_keys=MAPPED_KEYS, path=file_path, report=report
),
raw=frontmatter.raw,
revision=revision,
),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
from datetime import datetime
from typing import Dict, List, Optional
from typing import AbstractSet, Dict, List, Optional, Tuple

from datahub.ingestion.source.repository_documents.report import (
RepositoryDocumentsSourceReport,
Expand Down Expand Up @@ -79,3 +80,128 @@ def parse_verified(
if stamp is not None:
stamps.append(stamp)
return stamps or None


# Caps on okfProperties.extensions, which is indexed for search. They keep a
# document's search entry small; anything left out stays in raw.
MAX_EXTENSION_KEYS = 50
# Key segments kept when nested objects are flattened: x-team.lead.email.
MAX_EXTENSION_DEPTH = 3
MAX_EXTENSION_KEY_LENGTH = 100
MAX_EXTENSION_VALUE_LENGTH = 1000
EXTENSION_LIST_SEPARATOR = ", "


def _scalar_text(value: object) -> Optional[str]:
"""A scalar frontmatter value as text, or None when it is not a scalar."""
if isinstance(value, str):
return value
# bool before int: bool is a subclass of int. JSON spells it true/false.
if isinstance(value, (bool, int, float)):
return json.dumps(value)
return None


def _extension_text(value: object) -> Optional[str]:
"""The indexed text of a scalar, or of a list of scalars joined with
``EXTENSION_LIST_SEPARATOR``. None for nulls, objects, lists with an
object, list or null item, and empty values: empty counts as absent."""
text: Optional[str]
if isinstance(value, list):
items = [_scalar_text(item) for item in value]
if any(item is None for item in items):
return None
text = EXTENSION_LIST_SEPARATOR.join(
item for item in items if item and item.strip()
)
else:
text = _scalar_text(value)
return text if text and text.strip() else None


def _has_value(value: object) -> bool:
"""Whether a value too deep to index holds anything that would be indexed."""
if isinstance(value, dict):
return any(_has_value(child) for child in value.values())
return _extension_text(value) is not None


def _flatten_extension(
key: str,
value: object,
depth: int,
entries: List[Tuple[str, str]],
dropped: List[str],
) -> None:
"""Append ``(dotted key, text)`` for a value, descending into nested
objects up to ``MAX_EXTENSION_DEPTH`` key segments."""
if isinstance(value, dict):
for child_key, child in value.items():
if depth >= MAX_EXTENSION_DEPTH:
if _has_value(child):
dropped.append(f"{key}.{child_key}")
else:
_flatten_extension(
f"{key}.{child_key}", child, depth + 1, entries, dropped
)
return
text = _extension_text(value)
if text is not None:
entries.append((key, text))


def parse_extensions(
values: Dict[str, object],
*,
mapped_keys: AbstractSet[str],
path: str,
report: RepositoryDocumentsSourceReport,
) -> Optional[Dict[str, str]]:
"""The frontmatter keys that ``mapped_keys`` does not cover, as strings for
okfProperties.extensions, or None when there are none.

Keys are kept as written, including an ``x-`` prefix. Nested objects are
flattened into dotted keys (``x-team.lead``) up to ``MAX_EXTENSION_DEPTH``
segments. Nulls, empty values and lists that hold objects, lists or nulls
are left out silently: they remain in raw and in the GraphQL frontmatter.
Entries nested too deeply or over the caps, and keys containing ``=``
(search indexes each entry as ``key=value``), are left out with one warning
per file.
"""
entries: List[Tuple[str, str]] = []
dropped: List[str] = []
for key, value in values.items():
if key not in mapped_keys:
_flatten_extension(key, value, 1, entries, dropped)
extensions: Dict[str, str] = {}
for key, text in entries:
if key in extensions:
# A literal dotted key and a flattened one can coincide; the first
# wins and the other is reported.
dropped.append(key)
continue
if (
len(extensions) >= MAX_EXTENSION_KEYS
or "=" in key
or not key.strip()
or len(key) > MAX_EXTENSION_KEY_LENGTH
or len(text) > MAX_EXTENSION_VALUE_LENGTH
):
dropped.append(key)
continue
extensions[key] = text
if dropped:
report.okf_extensions_dropped += len(dropped)
report.warning(
title="OKF extension keys not indexed",
message=(
"Some frontmatter keys exceed the limits for searchable OKF "
f"extensions (at most {MAX_EXTENSION_KEYS} keys, nested up to "
f"{MAX_EXTENSION_DEPTH} levels, keys up to "
f"{MAX_EXTENSION_KEY_LENGTH} characters without '=', values up "
f"to {MAX_EXTENSION_VALUE_LENGTH} characters). They remain in "
"okfProperties.raw but are not searchable."
),
context=f"path={path}, keys={', '.join(dropped)}",
)
return extensions or None
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class RepositoryDocumentsSourceReport(StaleEntityRemovalSourceReport):
okf_parse_errors: int = 0
okf_unresolved_values: int = 0
okf_invalid_values: int = 0
okf_extensions_dropped: int = 0
okf_unversioned_index_files: int = 0
repositories_imported: int = 0
repositories_failed: LossyList[str] = field(default_factory=LossyList)
Expand Down
Loading
Loading