Skip to content

feat(ontology): add gm import-dataplex-glossary for Knowledge Catalog glossaries (issue #612, PR 1) - #613

Merged
caohy1988 merged 4 commits into
GoogleCloudPlatform:mainfrom
seoeunbae:feat/612-import-dataplex-glossary
Nov 28, 2026
Merged

caohy1988 merged 4 commits into
GoogleCloudPlatform:mainfrom
seoeunbae:feat/612-import-dataplex-glossary

Conversation

@seoeunbae

@seoeunbae seoeunbae commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adds gm import-dataplex-glossary <glossary>, a read-only importer next to gm import-owl that turns a Knowledge Catalog (Dataplex) Business Glossary into an ontology.yaml. The glossary becomes the root ontology and SKOS concept scheme, every category and term becomes an abstract entity, and category nesting becomes abstract skos_broader relationships.
  • Entity names are built from the resource kind and resource ID (category_<id> / term_<id>), so the separate category and term ID spaces cannot collide. The raw ID is kept in skos:notation and the full resource name in dataplex:resource.
  • The mapping is a pure function, map_dataplex_glossary(), separate from the thin API wrapper import_dataplex_glossary(). Output is canonical: re-importing an unchanged glossary gives byte-identical YAML and the same compile_fingerprint, whatever order or repetition the API returns pages in.
  • Every category and term must belong to the requested glossary. The project is compared exactly: a project ID and a project number count as one project only when that pair is verified, either because GetGlossary answered a request by one form with a name in the other, or because a Python caller passes it as project_alias. A GetGlossary response without a resource name, or for another glossary, fails before anything is listed.
  • A partial result is never written: unreachable locations or a page that can't be read fail the import, and -o replaces its file atomically.
  • Adds a [dataplex] extra (google-cloud-dataplex>=2.12.0, also in [all]), imported only when the API is called.
  • Entry links (synonyms, related terms, asset definitions) are not part of this PR.

Part of #612.

Motivation

#612 asks for a way to bring an existing Knowledge Catalog Business Glossary into the ontology tooling. The review on that issue suggested a focused first PR for the glossary, categories, terms, labels and hierarchy, with the mapping separated from the API calls and fake-client tests that shuffle and repeat pages, and links and definitions as a later change. This is that first PR. How each review point is handled:

Review point In this PR
lookup_entry_links needs google-cloud-dataplex>=2.17.0; 2.12.0+ is enough for glossary, category and term reads The extra is >=2.12.0 and no link lookup is used. The tests ran against 2.12.0 (the floor) and 2.22.0.
The YAML does not plug into gm compile or OntologyRuntime on its own, and an entity-less binding yields a CREATE PROPERTY GRAPH with no node tables Documented with a worked example that takes a small nested glossary to concept-index rows: a companion binding with no entities, --emit-concept-index --concept-index-table, and dropping the bare CREATE PROPERTY GRAPH <ontology>; header. The header itself is unchanged by this PR.
import-owl does not sanitize names (a collision is an error) and leaves out hierarchy edges whose other end it did not import, so sanitizing, renaming and orphan-parent reporting are new behavior Called out in the docs. The import summary reports the sanitized, hash-suffixed and orphan-parent counts, and tests cover each case.
Q1: what are entity names derived from, what is the sanitizing rule, how are collisions handled Resource kind + resource ID, sanitized to [A-Za-z0-9_]; collisions between resources of the same kind get an order-independent hash suffix (and a deterministic counter if the suffix is taken at every length); the raw ID stays in skos:notation. A category and a term that normalize alike have their own test (see Changes).
Q2: how to report truncated, failed or redacted link lookups Not applicable yet: this PR makes no link lookups, so nothing can be silently truncated. The follow-up that adds links will report those cases explicitly, and will not add a silent per-term cap that would undercut byte-identical output.
Pure mapping, and tests that shuffle and repeat pages map_dataplex_glossary() does no I/O. The tests shuffle and repeat pages and compare the YAML and compile_fingerprint.

Changes

Importer: src/bigquery_ontology/dataplex_glossary_importer.py (new)

  • map_dataplex_glossary(glossary, categories, terms, *, ontology_name=None, project_alias=None) returns (yaml_text, summary). It accepts google-cloud-dataplex messages or any object or dict with the same fields, and does no network I/O and no SDK import. project_alias is the glossary's project under its other form (ID or number) for callers that have verified the pair; without it, the project must match exactly. A different project of the same form (two IDs, or two numbers) is a ValueError.
  • import_dataplex_glossary(glossary_name, *, ontology_name=None, glossary_client=None) calls GetGlossary and checks that the response names the requested glossary before it lists anything: the response must carry a resource name (a missing, blank or non-string name is rejected, with no fallback to the requested name), with the same location and glossary ID, and the same project or that project under its other form. It then lists all categories and terms (all pages) under the glossary's canonical name, with the requested project as project_alias when the response used the other form, and hands them to the mapper.
  • List results: a plain collection of items (even one that also has a pages attribute) is read item by item, and a one-shot pages iterator is read once, so no item is lost or read twice. A result that exposes response fields, as a GAPIC pager does, or whose first page is a List...Response, is read page by page as responses. A page that reports unreachable_locations (even a blank entry), or a response page without its categories or terms field, fails the import instead of returning a partial ontology.
  • API, transport, credential, response-decoding (including client-side ValueErrors such as JSON decode errors) and client-construction failures become DataplexImportError.
  • Mapping:
    • Glossary: root ontology (the glossary ID, or --ontology-name) with description and dataplex:glossary / dataplex:uid annotations.
    • Category or term: abstract entity with description, skos:prefLabel (display name), skos:notation (raw ID), dataplex:resource (resource name) and skos:inScheme.
    • Parent is the glossary: skos:topConceptOf. Parent is a category of the glossary: an abstract skos_broader relationship. Any other parent (an unknown category, another glossary or project, the category itself): dataplex:orphan_parent, counted in the summary. A parent that names the glossary under the other, unverified form of its project is an orphan too, and is counted on its own summary line.
  • Naming: category_<id> / term_<id>, with every character outside [A-Za-z0-9_] replaced by _. Resources of the same kind whose names still collide each get a _<sha256(raw id)[:8]> suffix. If that name is taken, the suffix grows one hex digit at a time up to the full digest, and then a _2, _3, … counter is appended. Names never depend on API order, and a suffix never takes another resource's natural name.
  • Determinism: entities, relationships and annotations are sorted and identical repeated records are deduplicated, so the output does not depend on page order or repetition.
  • Failures (exit 1): a category or term from another project, location or glossary (projects are compared exactly, so two different IDs, two different numbers, or an unverified ID/number pair are different projects); two different records with the same resource ID; a glossary with no categories or terms; a GetGlossary response without a resource name or for another glossary (nothing is listed); and a list page with unreachable locations or without its items. A parent in another project is not a failure; it becomes an orphan.
  • Not imported: the glossary's display_name, the Dataplex resource labels, timestamps, per-record uid, and the glossary's counts and etag.

CLI: src/bigquery_ontology/cli.py

  • gm import-dataplex-glossary <glossary> [--ontology-name NAME] [-o/--out FILE] [--json]. The glossary must be projects/<project>/locations/<location>/glossaries/<id>, where the project is a project number or a lowercase project ID (letters, digits and hyphens, starting with a letter and not ending with a hyphen; legacy domain-scoped IDs such as example.com:my-project included) and the location is a lowercase name such as us-central1 or global. Anything else, such as 123abc, UPPER-project, demo-project- or a::b, exits 2 (cli-usage) before any API call. The summary goes to stderr once the YAML has been written.
  • -o writes a regular file, new or existing, through a temporary file (.gm-import-<random>.tmp) that is created exclusively in the file's real directory and moved into place with os.replace. A failed write or an interrupt leaves an existing file untouched and no temporary file behind.
    • The path is used as typed and its directories are resolved strictly, as opening it would: missing/../out.yaml fails instead of replacing out.yaml, a path ending in / or /. names a directory, and a symlink, dangling or not, is followed to the file it names (a dangling chain is followed as far as open() would follow it: 40 links on Linux).
    • An existing file keeps its permission bits; a new file gets 0o666 minus the umask. The process umask is not changed.
    • A read-only file or a directory is refused (cli-output-error). Descriptor paths (/dev/stdout, /dev/fd/<n>, /proc/self/fd/<n>, ...) and other non-regular files (/dev/null, a named pipe) are written directly.
  • Exit codes: 2 for cli-usage and cli-missing-dependency (extra not installed); 1 for import-validation (including a GetGlossary response without a resource name or for another glossary), import-api-error (including client-side decoding errors, unreachable locations and unreadable pages) and cli-output-error (an OSError while writing stdout or the -o file); 3 for an unexpected internal error, including one raised while writing the output. On failure, --json leaves exactly one JSON document on stderr, including for exit 3 (cli-internal-error). Argument-parsing errors (a missing <glossary> or option value) are reported by the CLI framework in plain text, as for every gm command. Existing commands are unchanged.

Packaging: pyproject.toml gets a dataplex extra, included in all.

Docs: docs/ontology/cli.md (new section 7; the old sections 7 and 8 become 8 and 9), the index row in docs/README.md, a new user-manual section (prerequisites, mapping table, naming and collision table, the glossary-to-concept-index walkthrough, and the differences from import-owl), and CHANGELOG.md.

Tests: tests/bigquery_ontology/test_dataplex_glossary_importer.py (new, 206 tests) and 103 new cases in tests/bigquery_ontology/test_cli.py. They use synthetic glossaries and fake clients only, apart from two tests that build real google-cloud-dataplex messages and pagers and are skipped unless the SDK is installed. A few CLI tests start a child Python process (a broken stdout pipe, and the /dev/stdout, /dev/stderr and /dev/stdin paths); the descriptor tests skip where /dev/fd, /proc or /dev/<stream> don't exist. Highlights:

  • test_shuffled_and_repeated_pages_give_byte_identical_output: identical YAML, compile_fingerprint and concept-index SQL across shuffled and repeated pages.
  • test_category_and_term_normalizing_alike_never_collide, test_same_kind_collisions_get_order_independent_hash_suffixes, test_hash_suffixes_never_steal_a_natural_name and test_hash_suffix_falls_back_to_a_counter_when_every_length_is_taken.
  • Project scope: test_projects_match_exactly_unless_a_verified_alias_is_given, test_record_in_an_unrelated_project_number_is_rejected, test_parent_in_an_unrelated_project_number_stays_an_orphan, the test_project_alias_* tests, test_import_pairs_the_requested_id_with_the_returned_number, test_import_rejects_records_from_a_third_project, test_mismatched_get_glossary_response_is_rejected_before_listing and test_nameless_get_glossary_response_is_rejected_before_listing.
  • List results: test_item_iterable_results_with_plain_pages_are_read_item_by_item, test_single_use_item_pages_are_read_once_without_losing_items, test_unreadable_pages_fail_instead_of_reading_as_empty, test_real_gapic_pagers_are_read_page_by_page, test_unreachable_locations_on_any_page_fail_the_import, test_blank_unreachable_location_markers_still_fail_the_import and test_value_errors_from_the_client_are_api_errors.
  • -o: a failed overwrite keeps the previous file; the file mode, umask and symlinks are kept; a read-only file and a directory are refused; /dev/null, a named pipe and descriptor paths (/dev/fd/<n>, /proc/self/fd/<n>, /dev/stdout, ...) are written through; missing/../out.yaml, a dangling link through a missing directory, a trailing / or /., a symlink loop and -o "" are output errors that leave existing files alone; a dangling symlink chain of 40 links creates its target (this case runs on Linux only) and one of 41 is an output error; the temporary file never reuses a taken name, is staged beside a symlink's target and is removed after an interrupt; the process umask is left alone.
  • Preflight: test_import_dataplex_glossary_bad_project_or_location_is_usage_error and test_domain_scoped_projects_and_standard_locations_are_accepted.
  • --json: one JSON document on stderr for output-write errors (cli-output-error), unexpected errors while writing or importing (cli-internal-error), and a broken stdout pipe.
  • The mapped YAML feeds build_rows, compile_concept_index, OntologyRuntime and LabelSynonymResolver.
  • test_module_never_imports_google_cloud_dataplex_eagerly (an AST check that also catches from google.cloud import dataplex_v1, with its own self-test) and test_real_dataplex_messages_are_supported.

Verification

All inputs are synthetic glossaries and fake clients. Nothing in the tests, and nothing run for this PR, calls Google Cloud.

# importer and CLI tests, no optional extras installed
python -m pytest tests/bigquery_ontology/test_dataplex_glossary_importer.py tests/bigquery_ontology/test_cli.py
# the ontology package and runtime
python -m pytest tests/bigquery_ontology tests/test_ontology_runtime.py
# whole suite, Python 3.13
python -m pytest -n 16 tests/ --ignore=tests/test_dashboards_streamlit.py --ignore=tests/test_dashboards_streamlit_bqca.py --ignore=tests/test_looker_studio_dashboard.py
# CI's formatting step, in check mode
isort --check-only src tests examples scripts dashboards
pyink --check --config pyproject.toml src tests examples scripts dashboards
Check Result
Importer and CLI tests, no extras 346 passed, 10 skipped (8 rdflib tests for import-owl, 2 real-SDK tests)
Same files with google-cloud-dataplex 2.12.0 (the floor) 348 passed, 8 skipped
Same files with google-cloud-dataplex 2.22.0 (latest) 348 passed, 8 skipped
The three runs above on Python 3.10, 3.11, 3.12, 3.13 and 3.14 the same counts on each
tests/bigquery_ontology and tests/test_ontology_runtime.py (no extras), on each of those Python versions 611 passed, 12 skipped
Importer tests under 32 different PYTHONHASHSEEDs 204 passed, 2 skipped under each
Whole suite, Python 3.13 11460 passed, 90 skipped, 17 failed
Formatting: isort, and pyink 25.12.0 (inside CI's >=24.3.0,<26 pin) 459 files unchanged; git diff --check clean

The 17 whole-suite failures are all in tests/test_power_bi_dashboard.py (node binary required for the configurator.mjs tests; Node.js is not installed here), and they are the same 17 tests on an unmodified upstream/main export.

Ad-hoc checks, not part of the PR:

  • The user-manual walkthrough was run end to end with a fake client and the real gm CLI app: import with -o, gm validate, an entity-less binding, gm compile --emit-concept-index --concept-index-table ..., then OntologyRuntime. The documented term_clv snippet matches the generated YAML, and the bare CREATE PROPERTY GRAPH retail; header and two CREATE OR REPLACE TABLE statements appear as described.
  • The repros from the latest review, run as written, fail at 98b8943 and pass now: five nameless GetGlossary responses (None, {}, and a name of None, "" or " "), -o missing/../retail.yaml over an existing retail.yaml, and an item-iterable list client whose pages are plain lists.
  • More than 60 small mutations of the importer (the GetGlossary name check, project matching and list reading) and of the CLI (preflight, exit codes and the -o writer) were each caught by the importer and CLI tests. They included ignoring a blank unreachable_locations entry, reading a page without its items field as empty, dropping O_EXCL or the retry on a taken temporary name, staging the temporary file beside a link instead of beside its target, keeping the temporary file after an interrupt, treating /proc/self/fd/<n> or /dev/stdout as ordinary files, and stopping a dangling symlink chain one link early. Three more changed no observable behavior (the symlink probes and the differential check below give identical results with and without them): two allow a 41st link, which os.stat has already refused by then, and one drops a ./.. check that the directory-name test makes unreachable.
  • A differential check of the -o writer against open(path, "w") over about 7,500 generated layouts and paths (missing and dangling-link directories, .., a trailing / or /., symlink loops, read-only files, directories) ran on each of Python 3.10 to 3.14 on Linux: the outcome and the resulting files were the same in every case. In 111 cases both fail, with a different errno (for example EISDIR from open() and ENOTDIR or ELOOP here).
  • Dangling symlink chains of 1, 2, 39, 40, 41 and 42 links, and paths that spend the budget on directory links plus a dangling tail (totals of 1 to 45 links), behave like open(path, "w") on Linux with Python 3.10 to 3.14: up to 40 links resolve and 41 fail with ELOOP.
  • The tests for descriptor paths, temporary files and pager shapes passed 20 runs in a row, a pytest-xdist run (-n 8) of both modules, and python -X dev with ResourceWarning as an error.
  • pip install --dry-run of the [all] requirement list, with and without google-cloud-dataplex>=2.12.0, resolves to the same protobuf, google-api-core, grpcio and proto-plus versions.

Not verified:

  • No live Dataplex call. The client usage (get_glossary, list_glossary_categories and list_glossary_terms with a request dict, pager iteration through pages) is checked against fake clients and against the real 2.12.0 and 2.22.0 client signatures, message types and pagers, not against the service. The roles/dataplex.catalogViewer statement in the docs comes from the public IAM documentation.
  • The real-SDK tests are skipped wherever the extra is not installed, which includes CI's .[dev,streamlit] install (the same way the rdflib tests skip). They were run by hand on 2.12.0 and 2.22.0 on each Python version.
  • CI's matrix is Python 3.10 to 3.14, and all five ran locally. Only 3.13 used a full development install; 3.10, 3.11, 3.12 and 3.14 ran in minimal virtual environments. The changed Python files also parse with the 3.10 grammar (3.10 is the minimum version) and avoid the f-string forms that need 3.12. The -o tests and the differential check ran on Linux only.
  • The replacement file for -o is a new file: hard links and open handles keep the old content, owner and ACLs are not carried over, and the destination directory must be writable even when the file itself is. gm import-owl -o is unchanged.
  • A list result that creates attributes on demand (a MagicMock, for example) and also has an explicit plain pages attribute is read as GAPIC-style and fails loudly, not silently.
  • The three excluded dashboard modules were not run (plotly and streamlit are not installed here, and tests/test_looker_studio_dashboard.py needs a headless Chrome and hung); none of them imports bigquery_ontology. The rdflib tests, including test_owl_importer.py, were skipped locally; this PR does not change import-owl.
… glossaries (issue GoogleCloudPlatform#612, PR 1)

Add a read-only importer, next to `gm import-owl`, that turns a
Knowledge Catalog (Dataplex) Business Glossary into an ontology.yaml.

Mapping:
- The glossary becomes the root ontology and SKOS concept scheme
  (`dataplex:glossary`, `dataplex:uid`).
- Every category and term becomes an abstract entity with
  `skos:prefLabel` (display name), `skos:notation` (raw resource ID),
  `dataplex:resource` (resource name) and `skos:inScheme`. Children of
  the glossary also get `skos:topConceptOf`.
- A child of a category of the same glossary gets an abstract
  `skos_broader` relationship to it. Any other parent is kept as
  `dataplex:orphan_parent` and counted in the import summary.

Names and determinism:
- Entities are named `category_<id>` or `term_<id>`, so the separate
  category and term ID spaces cannot collide. Characters outside
  [A-Za-z0-9_] become `_`. Names of the same kind that still collide
  each get a `_<sha256(raw id)[:8]>` suffix, independent of API order.
- Output is canonical (entities, relationships and annotations sorted,
  identical repeated records deduplicated), so re-importing an
  unchanged glossary gives byte-identical YAML and the same
  compile_fingerprint, whatever order or repetition the API returns
  pages in.
- Records from another project, location or glossary, conflicting
  records for one resource ID, and empty glossaries fail the import.
  A project ID and a project number count as the same project.

Structure:
- `map_dataplex_glossary()` is a pure function over already-fetched
  records. `import_dataplex_glossary()` is a thin wrapper around
  GetGlossary, ListGlossaryCategories and ListGlossaryTerms.
- New `[dataplex]` extra (google-cloud-dataplex>=2.12.0, also in
  `[all]`), imported only when the API is called.

Not in this change: entry links (synonyms, related terms, asset
definitions). The YAML still needs a companion binding for `gm compile`
and OntologyRuntime; the user manual and docs/ontology/cli.md show the
path from a small nested glossary to concept-index rows, including the
bare CREATE PROPERTY GRAPH header that an entity-less binding produces.
Unlike `gm import-owl`, this importer sanitizes and disambiguates names
and reports orphan parents.

Part of GoogleCloudPlatform#612.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this. The mapper/API split, the shuffled-and-repeated page tests, and the companion-binding walkthrough all hold up well, and the importer and ontology tests pass locally at this head (169 passed / 9 skipped, and 434 passed / 11 skipped for tests/bigquery_ontology plus tests/test_ontology_runtime.py). One thing needs to change before this goes in.

Project ID vs. number matching accepts unrelated projects. _same_project (src/bigquery_ontology/dataplex_glossary_importer.py:210-220) returns true for any pair where one side is numeric and the other isn't. That same check gates record admission (around line 351) and parent resolution (around lines 443-450), so a category or term from a completely different project is accepted as long as one name uses an ID and the other a number. A foreign parent can likewise become a local skos:topConceptOf or skos_broader edge instead of dataplex:orphan_parent. A single project number can't be both project-a and project-b, yet the mapper accepts both:

import pytest
from bigquery_ontology import load_ontology_from_string
from bigquery_ontology.dataplex_glossary_importer import map_dataplex_glossary

def g(p): return f"projects/{p}/locations/us-central1/glossaries/retail"

@pytest.mark.parametrize("pid", ["project-a", "project-b"])
def test_unrelated_numeric_project_record_rejected(pid):
  with pytest.raises(ValueError):
    map_dataplex_glossary({"name": g(pid)}, [],
        [{"name": g("123456789012") + "/terms/foreign", "parent": g("123456789012")}])

@pytest.mark.parametrize("pid", ["project-a", "project-b"])
def test_unrelated_numeric_parent_stays_orphan(pid):
  foreign = g("123456789012") + "/categories/customer"
  y, _ = map_dataplex_glossary({"name": g(pid)},
      [{"name": g(pid) + "/categories/customer", "parent": g(pid)}],
      [{"name": g(pid) + "/terms/churn", "parent": foreign}])
  o = load_ontology_from_string(y)
  assert o.relationships == []
  assert next(e for e in o.entities if e.name == "term_churn").annotations["dataplex:orphan_parent"] == foreign

Both fail at this head. In the API path it's reachable too: import_dataplex_glossary swaps the requested name for the GetGlossary response name before checking scope, so a request by ID that comes back by number then admits records from any other project. Please make the pure mapper require exact project equality unless the caller supplies a verified ID↔number pair, and have the API layer establish that pair from the request/response (and validate the returned location and glossary ID before listing). Foreign records should still be rejected and foreign parents should stay orphans. test_an_id_and_a_number_are_one_project_but_two_of_a_kind_are_not currently locks in the broad rule, so it needs updating too.

Smaller things worth fixing here or in a follow-up:

  • Partial list responses look like success. list(pager) (around lines 830 and 838) drops each page's unreachable_locations, so an import that lost a location still exits 0 with no warning. Iterating pager.pages and failing with DataplexImportError when it's non-empty would close that.
  • A failed -o overwrite destroys the previous file. Path.write_text (cli.py:1078) truncates first, so a mid-write failure leaves a partial file after a cli-output-error. Writing to a temp file in the same directory and then os.replace avoids that.
  • Client-side ValueErrors are reported as validation errors. _call_api re-raises every ValueError, and requests' JSON decode errors and google.auth's MalformedError are both ValueError subclasses, so transport and credential failures come out as import-validation instead of import-api-error.
  • The hash-suffix loop can run out. Lengths 8-64 can all be taken by ordinary natural IDs (a-b, a_b, plus a_b_<sha256("a-b")[:n]> for each n), which raises RuntimeError. A deterministic counter fallback after the full digest would fix it, and the manual's "eight-character suffix" wording should mention that it can grow.
  • --json stderr isn't always one JSON document. The success summary is printed before the output write, and the exit-3 handler prints plain text.
  • Smaller still: resource-name preflight accepts characters like ! in project and location segments, and the AST lazy-import test misses from google.cloud import dataplex_v1.

CI hasn't run yet: the fork workflows are waiting for maintainer approval.

Review follow-up for GoogleCloudPlatform#613.

Project matching:
- `map_dataplex_glossary()` now requires a record's project to equal
  the glossary's exactly. A project ID and a project number count as
  one project only when the caller passes the pair as the new
  `project_alias` argument. Records from another project, location or
  glossary still fail the import, and parents there stay orphans.
- `import_dataplex_glossary()` checks that the GetGlossary response
  names the requested glossary (same location and glossary ID, and the
  same project or that project under its other form) before it lists
  anything, then passes the requested project as the verified
  `project_alias`. A response for another glossary fails with
  `import-validation` and nothing is listed.
- A parent that names the glossary under the other, unverified form of
  its project stays an orphan and is counted on its own summary line.

API results:
- A list page that reports `unreachable_locations` now fails the
  import (`import-api-error`) instead of yielding a partial ontology.
  Pagers are read page by page.
- Client-side `ValueError`s, such as JSON decoding errors and
  malformed credentials, are `import-api-error`, not
  `import-validation`.

Names:
- If the 8-hex-digit hash suffix is taken, it grows up to the full
  SHA-256 digest and then gains a `_2`, `_3`, ... counter, so naming
  cannot run out. It still does not depend on API order.

CLI:
- `-o` replaces a regular file atomically: the YAML goes to a
  temporary file in the same directory and `os.replace` moves it into
  place, so a failed write keeps the previous file. The file's
  permission bits are kept (a new file follows the umask), a symlinked
  destination keeps its link, and a read-only destination is refused.
  A destination that is not a regular file, such as `/dev/null` or a
  named pipe, is written directly.
- The import summary is printed after the `-o` file is written, and an
  unexpected error (exit 3) is reported as one JSON document
  (`cli-internal-error`) with `--json`, so stderr holds exactly one
  JSON document on failure.
- The resource-name check rejects characters such as `!` and `@` in the
  project and location segments. Project IDs (including domain-scoped
  ones such as `example.com:my-project`) and project numbers stay
  valid.

Tests and docs:
- Tests cover each case above, including a record and a parent in an
  unrelated project number, real GAPIC pagers, and the `-o` edge
  cases. The AST check for eager imports now also catches
  `from google.cloud import dataplex_v1`.
- The user manual, docs/ontology/cli.md and CHANGELOG.md describe the
  new behavior.

Part of GoogleCloudPlatform#612.
@seoeunbae

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review. Everything in it is addressed in 98b8943.

Project ID vs. number (blocking)

  • map_dataplex_glossary() now requires exact project equality. A project ID and a project number count as one project only when the pair is verified; Python callers pass the other form of the glossary's project as the new project_alias.
  • import_dataplex_glossary() establishes that pair itself. Before it lists anything, it checks that the GetGlossary response has the requested location and glossary ID and the same project (or that project under its other form), then passes the requested project as project_alias. A response for another glossary fails with import-validation and nothing is listed.
  • Foreign records are still rejected and foreign parents stay dataplex:orphan_parent. A parent that names the glossary under the unverified other form is counted on its own summary line.
  • Your repro tests, run as written, fail at 54df2f0 and pass now. Rewritten forms are in the suite (test_record_in_an_unrelated_project_number_is_rejected and test_parent_in_an_unrelated_project_number_stays_an_orphan). test_an_id_and_a_number_are_one_project_but_two_of_a_kind_are_not is replaced by test_projects_match_exactly_unless_a_verified_alias_is_given, plus tests for the alias, for the pairing in import_dataplex_glossary and for mismatched GetGlossary responses.

Smaller items

  • Partial lists: both list calls read pager.pages, and a non-empty unreachable_locations on any page raises DataplexImportError (import-api-error). One test uses real GAPIC pagers.
  • -o overwrite: the YAML goes to a temporary file in the destination directory and os.replace moves it into place, so a failed write keeps the old file. The file mode is kept (a new file follows the umask), a symlink stays a symlink, a read-only destination is refused, and /dev/null or a named pipe is written directly.
  • Client ValueErrors: _call_api wraps them, so JSON decode and MalformedError failures are import-api-error.
  • Suffix loop: after the full digest, names get a deterministic _2, _3, … counter (order-independent, skipping taken names). The manual and docs/ontology/cli.md now say the suffix can grow.
  • --json: the summary is printed only after the -o write, and the exit-3 handler emits a single cli-internal-error document, so a failure leaves exactly one JSON document on stderr.
  • Preflight and AST test: project and location segments no longer accept characters like ! or @ (domain-scoped IDs such as example.com:my-project and project numbers still pass). The AST check now also catches from google.cloud import dataplex_v1 and has its own self-test.

Verification (at 98b8943)

  • Importer and CLI tests: 229 passed, 10 skipped with no extras; 231 passed, 8 skipped with google-cloud-dataplex 2.12.0 and with 2.22.0. The two real-SDK tests skip in CI, which doesn't install the extra.
  • tests/bigquery_ontology and tests/test_ontology_runtime.py: 494 passed, 12 skipped.
  • Whole suite: 11344 passed, 89 skipped, 17 failed. All 17 are the Node.js-dependent tests in tests/test_power_bi_dashboard.py, and the same 17 fail on an unmodified upstream/main export.
  • isort and pyink 25.12.0 (inside CI's >=24.3.0,<26 pin) are clean; 459 files unchanged.

Caveats: no live Dataplex call was made, and only Python 3.13 was available locally (the changed files were checked statically for 3.10 syntax and API use). The -o replacement is a new file, so hard links and open handles keep the old content, owner and ACLs are not carried over, and the destination directory must be writable. gm import-owl -o is unchanged.

The PR description is updated to match. The fork workflows still need maintainer approval to run.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the quick turnaround. Most of the last round is fixed: exact project matching with verified aliases, foreign records and parents, unreachable pages, client ValueError mapping, the suffix counter, and the lazy-import guard all check out, and tests/bigquery_ontology plus tests/test_ontology_runtime.py pass locally (494 passed, 12 skipped). A few things still need changing before this goes in.

A nameless GetGlossary response still skips identity validation. canonical_name = _field(glossary, "name").strip() or glossary_name (dataplex_glossary_importer.py:1023) falls back to the requested name when the response is None, has no name, or has a blank or non-string one, so the project/location/glossary checks validate the request instead of the response and both list calls go ahead. Please require a non-empty string name and raise before listing when it's missing. test_blank_canonical_name_falls_back_to_the_requested_name locks in the fallback and will need to flip.

import pytest
from bigquery_ontology.dataplex_glossary_importer import import_dataplex_glossary

G = "projects/demo-project/locations/us-central1/glossaries/retail"

class Client:
  def __init__(self, response): self.response, self.calls = response, []
  def get_glossary(self, request=None, **kw):
    self.calls.append("get"); return self.response
  def list_glossary_categories(self, request=None, **kw):
    self.calls.append("categories"); return iter(())
  def list_glossary_terms(self, request=None, **kw):
    self.calls.append("terms")
    return iter(({"name": G + "/terms/churn", "parent": G, "display_name": "Churn"},))

@pytest.mark.parametrize("response", [None, {}, {"name": None}, {"name": ""}, {"name": "   "}])
def test_missing_glossary_identity_is_rejected(response):
  client = Client(response)
  with pytest.raises(ValueError):
    import_dataplex_glossary(G, glossary_client=client)
  assert client.calls == ["get"]

-o with a missing directory plus .. now overwrites the resolved file. A failed stat is treated as a new file (cli.py:965) and path.resolve() (cli.py:971) collapses missing/../retail.yaml to retail.yaml, so a path that can't actually be opened replaces an existing retail.yaml and exits 0. At 54df2f0 the file was kept and the command returned cli-output-error. Resolving the real parent strictly before creating the temp file (and doing the same when following a dangling symlink) would fix it.

Item-iterable list clients can lose a whole page. Any response with a pages attribute is now read page by page (dataplex_glossary_importer.py:915), and a page without a named categories/terms field contributes nothing (:932). A client that satisfies the iterable-of-items protocol but stores pages as plain lists loses all its categories, and the import succeeds with orphaned terms; this worked at the previous head. Please keep plain item iteration for non-GAPIC clients, or raise on a page shape you can't read rather than treating it as empty.

Smaller things, here or in a follow-up:

  • An unexpected exception from _write_text_atomically escapes the exit-3 / cli-internal-error path, since output handling only catches OSError (cli.py:1158-1179). Stdout write failures and parser errors under --json also still produce non-JSON stderr.
  • unreachable_locations=[" "] is stripped to nothing before the presence check (:922), so a non-empty partial marker reads as a complete result.
  • Project preflight still accepts strings like 123abc, UPPER-project, demo-project- and a::b.
  • Writing to /dev/fd/<n> backed by a regular file now takes the replace branch and fails; descriptor paths should be written through.
  • Creating a new output calls os.umask(0) (cli.py:944), which briefly clears the mask for the whole process.
  • The test module docstring (test_dataplex_glossary_importer.py:23-26) still says an ID and a number are one project.
Second review follow-up for GoogleCloudPlatform#613.

GetGlossary:
- A response without a usable resource name (None, no `name`, or a
  blank or non-string one) now fails with `import-validation` before
  anything is listed. It no longer falls back to the requested name,
  which made the project, location and glossary checks validate the
  request instead of the response.

List results:
- A list result is read item by item unless it is GAPIC-style: it
  exposes response fields itself, or its first page has the items
  field or `unreachable_locations`. Clients that iterate their items
  but keep `pages` as plain lists (or empty, or None) no longer lose
  them, and a one-shot `pages` iterator is read once.
- A GAPIC-style result with a page that lacks its items field now
  fails with `import-api-error` instead of reading as empty.
- Any `unreachable_locations` entry fails the import, including a
  blank one.

-o destination:
- The path is used as typed. Directories are resolved strictly, so
  `missing/../out.yaml` fails instead of replacing `out.yaml`, a path
  ending in `/` or `/.` names a directory, and a symlink, dangling or
  not, is followed to the file it names, as far as `open()` would
  follow it (40 links on Linux).
- The temporary file is created exclusively (`O_CREAT|O_EXCL`) in the
  target's real directory and removed on any failure, an interrupt
  included. A new file gets 0o666 minus the umask from `open()`, so
  the process umask is no longer touched.
- Descriptor paths such as `/dev/stdout`, `/dev/fd/<n>` and
  `/proc/self/fd/<n>` are written through, like other non-regular
  files, instead of being replaced.

Output and exit codes:
- An OSError while writing stdout or the `-o` file is a
  `cli-output-error` (exit 1). Any other error raised while writing
  is a `cli-internal-error` (exit 3, one JSON document with `--json`).
- Argument-parsing errors keep the CLI framework's plain-text format
  under `--json`, as for every `gm` command; the CLI reference now
  says so.

Resource names:
- The glossary name check takes a project number or a lowercase
  project ID (letters, digits and hyphens, starting with a letter and
  not ending with a hyphen; legacy `example.com:my-project` stays
  valid) and a lowercase location. `123abc`, `UPPER-project`,
  `demo-project-` and `a::b` exit 2 before any API call.

Tests and docs:
- Tests cover each case above, including real GAPIC pagers (skipped
  when google-cloud-dataplex is not installed) and descriptor paths.
  The test module docstring now describes exact project matching.
- The user manual, docs/ontology/cli.md and CHANGELOG.md describe the
  new behavior.

Part of GoogleCloudPlatform#612.
@seoeunbae

Copy link
Copy Markdown
Contributor Author

Thanks for the second pass. The three blocking items and the smaller ones are addressed in 6ae0f61.

Nameless GetGlossary response (blocking)

  • import_dataplex_glossary() now requires a non-empty string name in the response. A response of None or {}, or with a name that is None, "", whitespace or not a string, raises ValueError before either list call (import-validation, exit 1 from the CLI). The fallback to the requested name is gone.
  • test_nameless_get_glossary_response_is_rejected_before_listing is your repro, parametrized over those responses and asserting that only get_glossary was called; it replaces test_blank_canonical_name_falls_back_to_the_requested_name. The CLI side is test_import_dataplex_glossary_nameless_response_exits_1.

-o with a missing directory plus .. (blocking)

  • The output path is no longer normalized. It is used as typed and its directories are resolved strictly, as open() does, so missing/../retail.yaml is a cli-output-error and an existing retail.yaml is left alone. A dangling symlink is followed the same way, hop by hop, as far as open() would (40 links on Linux; a loop is an output error too), and a path ending in / or /. names a directory instead of collapsing into the file before it.
  • Tests include test_import_dataplex_glossary_missing_directory_before_dotdot_fails, ..._dangling_link_through_missing_dir_fails, ..._dangling_link_to_a_directory_path_fails, ..._file_path_named_as_a_directory_is_kept, ..._output_symlink_loop_is_an_output_error and ..._dangling_link_chain_is_limited_to_forty_links. I also compared the outcome with open(path, "w") over about 7,500 generated layouts and paths on each of Python 3.10 to 3.14: the outcome is the same everywhere (111 cases fail in both, with a different errno).

Item-iterable list clients (blocking)

  • A list result is read as GAPIC responses only when it looks like a pager: it exposes response fields itself, or its first page has categories / terms or unreachable_locations. Anything else is read item by item, so a client that iterates its items but keeps pages as plain lists (or empty, or None) loses nothing, and a one-shot pages iterator is read once.
  • A response-style result with a page that has no categories / terms now raises DataplexImportError (import-api-error) instead of reading as empty, and unreachable_locations on any page still fails the import. Pinned by test_item_iterable_results_with_plain_pages_are_read_item_by_item, test_single_use_item_pages_are_read_once_without_losing_items and test_unreadable_pages_fail_instead_of_reading_as_empty; test_real_gapic_pagers_are_read_page_by_page uses real pagers (skipped when the SDK isn't installed).
  • Your three repros, run as written, fail at 98b8943 and pass now.

Smaller items

  • Output errors: an OSError while writing stdout or the -o file is cli-output-error (exit 1); anything else raised while writing is cli-internal-error (exit 3, one JSON document with --json). The summary is printed after the YAML is written. Parser errors, such as a missing <glossary>, are raised by the CLI framework before the command runs, so under --json they stay plain text, as for every gm command; docs/ontology/cli.md now says so.
  • Blank unreachable marker: unreachable_locations=[" "], or any entry on any page, fails the import.
  • Preflight: a project is a number or a lowercase ID (letters, digits and hyphens, starting with a letter, no trailing hyphen; example.com:my-project still passes) and a location is lowercase. 123abc, UPPER-project, demo-project- and a::b exit 2 before any API call.
  • Descriptor paths: /dev/stdout, /dev/stderr, /dev/stdin, /dev/fd/<n>, /proc/self/fd/<n>, /proc/thread-self/fd/<n> and /proc/<pid>/fd/<n> (redundant slashes included) are written through to the open file, like /dev/null and named pipes.
  • umask: no os.umask call is left. The temporary file is created with O_CREAT | O_EXCL and 0o666 (0o600 when replacing a file), so open() applies the umask itself, and a replaced file gets its old permission bits before the swap.
  • Test docstring: it now describes exact project matching.

Verification (at 6ae0f61)

  • Importer and CLI tests: 346 passed, 10 skipped with no extras; 348 passed, 8 skipped with google-cloud-dataplex 2.12.0 and with 2.22.0. The same counts on Python 3.10 to 3.14.
  • tests/bigquery_ontology and tests/test_ontology_runtime.py: 611 passed, 12 skipped.
  • Whole suite: 11460 passed, 90 skipped, 17 failed. All 17 are the Node.js-dependent tests in tests/test_power_bi_dashboard.py, and the same 17 fail on an unmodified upstream/main export.
  • isort and pyink 25.12.0 (inside CI's >=24.3.0,<26 pin) are clean; 459 files unchanged.

Caveats: no live Dataplex call was made. Python 3.10, 3.11, 3.12 and 3.14 ran in minimal environments, not CI's full install, and the -o tests ran on Linux only. The -o replacement is a new file, so hard links and open handles keep the old content, owner and ACLs are not carried over, and the directory must be writable.

The PR description is updated to match. The fork workflows still need maintainer approval to run.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the thorough update! The earlier concerns (the nameless GetGlossary response, output path handling, page handling, and the project/location preflight checks) all look addressed, and the new tests cover them well. I noted a couple of smaller page-handling cases in a follow-up issue: #617

@caohy1988
caohy1988 merged commit af78423 into GoogleCloudPlatform:main Nov 28, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants