Skip to content

fix(ontology): SKOS traversal and topConceptOf parity in OntologyRuntime - #579

Merged
caohy1988 merged 2 commits into
GoogleCloudPlatform:mainfrom
seoeunbae:fix/ontology-runtime-skos-parity
Nov 6, 2026
Merged

caohy1988 merged 2 commits into
GoogleCloudPlatform:mainfrom
seoeunbae:fix/ontology-runtime-skos-parity

Conversation

@seoeunbae

Copy link
Copy Markdown
Contributor

Summary

  • OntologyRuntime.broader(), narrower() and related() now also read relationships: skos_broader and skos_related, the edges gm import-owl emits for SKOS taxonomies, and skos_narrower, for hand-authored ontologies. They used to read only skos:* entity annotations, so on an imported taxonomy they returned () for every concept.
  • schemes_for() and in_scheme() count skos:topConceptOf as scheme membership. The concept-index emission already applies that rule, so a top concept used to be missing from the in-memory answer but present in a scheme filter over the emitted rows.
  • Blank annotation values are dropped the way the emission drops them, and narrower() returns () for a name the ontology does not declare, like the other accessors.

Motivation

gm import-owl maps SKOS edges to abstract relationships, not annotations (docs/ontology/owl-import.md §19.3): skos:broader and skos:narrower triples both become a child → parent skos_broader relationship, and each skos:related pair becomes one skos_related relationship with its endpoints sorted by name. skos:inScheme and skos:topConceptOf become annotations that hold the full scheme IRI. docs/entity_resolution_primitives.md §6 lists skos_broader → rt.broader() / rt.narrower() as the intended consumption path, but the runtime reader added in #154 never looked at relationships.

Context: SKOS import landed in #62, the concept-index emission (including the skos:topConceptOf rule) in #92, and the runtime reader in #154.

Reproduction on main (4c78565) and on this branch: import the five-concept taxonomy that _SKOS_TAXONOMY_TTL in tests/test_ontology_runtime.py holds, with gm import-owl taxonomy.ttl --include-namespace 'http://example.com/taxonomy#' -o taxonomy.yaml, then build an OntologyRuntime from the result. :Banking is a top concept only, :InvestmentBanking has skos:broader :Banking and skos:related :RetailBanking, and :WealthManagement has skos:narrower :InvestmentBanking.

Call on the imported ontology main this branch
broader("skos_InvestmentBanking") () ("skos_Banking", "skos_WealthManagement")
broader("skos_RetailBanking") () ("skos_Banking",)
narrower("skos_Banking") () ("skos_InvestmentBanking", "skos_RetailBanking")
narrower("skos_WealthManagement") () ("skos_InvestmentBanking",)
related("skos_RetailBanking") () ("skos_InvestmentBanking",)
schemes_for("skos_Banking") (top concept only) () ("http://example.com/taxonomy#BankingScheme",)
in_scheme("http://example.com/taxonomy#BankingScheme") ("skos_InvestmentBanking", "skos_Payments", "skos_RetailBanking") ("skos_Banking", "skos_InvestmentBanking", "skos_Payments", "skos_RetailBanking")

Changes

  • src/bigquery_agent_analytics/ontology_runtime.py
    • broader() / narrower() read the entity's own annotation, other entities' inverse annotation (skos:narrower / skos:broader), skos_broader relationships and skos_narrower relationships; the colon forms (skos:broader, skos:narrower) of the relationship names are read too. narrower() is the exact inverse of broader(): for declared entities, B in broader(A) iff A in narrower(B).
    • related() also reads skos_related relationships at either endpoint, because the importer orders the endpoints by name. The skos:related annotation stays directional, as before.
    • schemes_for() / in_scheme() take the union of skos:inScheme and skos:topConceptOf, in first-seen order, without duplicates.
    • _all_string_values() drops empty strings, as concept_index._as_list does, so a blank value never surfaces as an entity, scheme, label or notation. New helper _entity_annotation_values().
    • broader(), narrower() and related() de-duplicate their results in first-seen order.
  • docs/ontology_runtime_reader.md: accessor table updated, a new "SKOS traversal sources" section, and the test inventory (the stale TestRoundOneFindings count of 11 is corrected to its 13 tests, and the 15 new tests are listed).
  • tests/test_ontology_runtime.py: new TestSkosParity (15 tests) with a frozen gm import-owl output, the Turtle it came from, and helpers. The tests compare schemes_for() / in_scheme() / labels_for() / notations_for() entity by entity with concept_index.build_rows(), and check the hierarchy accessors against every way of stating an edge, including the inverse invariant. test_import_owl_round_trip re-imports the Turtle and pins the frozen YAML to the importer's current output. It uses pytest.importorskip("rdflib"), so it is skipped without the [owl] extra; the other TestSkosParity tests need no extra.

Behavior changes a reviewer should know about:

  1. narrower(name) returns () when the ontology does not declare name. It used to return the entities whose skos:broader annotation listed name, declared or not. broader(), related() and schemes_for() already returned () for undeclared names. broader() still returns the targets that a declared entity's annotation names, even if a target is undeclared.
  2. labels_for() no longer returns blank skos:prefLabel / skos:altLabel / skos:hiddenLabel / skos:notation values. synonyms are returned as declared, because the emission writes them as declared.
  3. related() includes skos_related relationships, so it returns more than before on imported ontologies.

Not changed: no signature or return type changes; traversal stays one hop (broader() is not transitive); and the SKOS mapping predicates (skos:broadMatch, skos:narrowMatch, skos:relatedMatch, ...) stay separate from skos:broader / skos:narrower / skos:related, as in the importer.

Cost: there is no precomputed adjacency index, so broader(), narrower() and related() scan the entity and relationship lists on each call. On a synthetic 4,000-concept taxonomy with 4,799 relationships that is about 0.2 → 1.6 ms for broader(), 0.5 → 1.1 ms for narrower() and 0.1 → 0.5 ms for related(). in_scheme() already takes about 0.4 s at that size and is unchanged.

Verification

Only synthetic ontologies and Turtle fixtures are used (the example.com taxonomy above); nothing here calls GCP or BigQuery.

  • pytest tests/test_ontology_runtime.py → 69 passed, 1 skipped. The skip is test_import_owl_round_trip, which needs the [owl] extra.
  • With rdflib installed: pytest tests/test_ontology_runtime.py tests/bigquery_ontology/test_concept_index.py tests/bigquery_ontology/test_owl_importer.py → 175 passed.
  • Catch test: this branch's tests/test_ontology_runtime.py run against main's ontology_runtime.py → 15 failed, 55 passed. The 15 failures are exactly TestSkosParity.
  • pytest tests/bigquery_ontology tests/test_ontology_runtime.py tests/test_ontology_runtime_live.py → 397 passed, 1 skipped on this branch and 382 passed, 1 skipped on main. The difference is the 15 new tests; the skip is the opt-in live BigQuery test.
  • Full suite, pytest -n 20 on Python 3.13 with rdflib installed and the two headless-Chrome tests in tests/test_looker_studio_dashboard.py deselected: 10571 passed, 71 skipped, 17 failed, 2 errors. The same 17 tests fail and the same 2 files error on main, so they are not caused by this change. The 17 failures are in tests/test_power_bi_dashboard.py and need Node.js, which is not installed here. The 2 errors are collection errors in tests/test_dashboards_streamlit.py and tests/test_dashboards_streamlit_bqca.py, because the streamlit extra (streamlit, plotly) is not installed here.
  • The reproduction table above comes from running gm import-owl and then the runtime on main and on this branch.
  • Ad-hoc randomized differential check, not part of this PR: 1,500 random ontologies against concept_index.build_rows(), 1,500 against a hierarchy oracle that also checks the inverse invariant, and 300 random Turtle graphs through import_owl against a SKOS-semantics oracle. There are 0 mismatches on this branch and 24,740 on main.
  • The Format check from .github/workflows/ci.yml (isort and pyink --config pyproject.toml over src/, tests/, examples/, scripts/ and dashboards/, then git diff --exit-code), run with pyink 25.12.0, which is inside CI's >=24.3.0,<26 range, leaves all 429 files unchanged. git diff --check is clean.
  • Tests were run on Python 3.13 only. The two changed .py files also parse as Python 3.10, the oldest in the CI matrix, and vermin reports the same minimum version (3.9) for them as on main.
OntologyRuntime.broader(), narrower() and related() only read the
skos:broader / skos:narrower / skos:related entity annotations, but
`gm import-owl` turns those triples into abstract skos_broader and
skos_related relationships. On an imported SKOS taxonomy the three
traversals therefore returned () for every concept, even though the
entity-resolution RFC maps skos_broader to rt.broader() /
rt.narrower().

schemes_for() / in_scheme() only read skos:inScheme, while the
concept-index emission (_entity_schemes) also counts
skos:topConceptOf, so a top concept was missing from the in-memory
scheme answer but present in a scheme filter over the emitted rows.

- broader() / narrower() read the entity's own annotation, other
  entities' inverse annotation, skos_broader relationships and
  hand-authored skos_narrower relationships (colon-form names too).
  narrower() is the exact inverse of broader() for declared entities.
- related() also reads skos_related relationships at either endpoint
  (the importer sorts the endpoints by name). The annotation stays
  directional as before.
- schemes_for() / in_scheme() union skos:inScheme and
  skos:topConceptOf, de-duplicated in first-seen order.
- Blank annotation values are dropped, as the concept-index emission
  does (_as_list), so "" never surfaces as an entity, scheme, label
  or notation. labels_for() now skips blank skos:prefLabel /
  skos:altLabel / skos:hiddenLabel values; synonyms stay as declared,
  as the emission writes them.
- The four traversal / scheme accessors return () for undeclared
  names; narrower() previously walked annotations for names the
  ontology doesn't declare.

Tests cover each edge form, the inverse invariant, both related
endpoints, scheme, label and notation parity against
concept_index.build_rows(), and an import-owl round trip (the frozen
import output always runs; the live import runs when rdflib is
installed). docs/ontology_runtime_reader.md documents the traversal
sources, the scheme membership rule and the blank-value handling.

@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.

Independent review 1 of 2 at 22c5d569

P0=0 P1=0 P2=0 NIT=0
VERDICT: CLEAN @ 22c5d56

Findings: None retained. No introduced correctness or contract defect was established in the three-file diff against merge base 594863851e62a08d7b5032ca5a4aa29ca4282c85.

The following rejection criteria were recorded before reading the diff:

  1. Traversal must handle the documented annotation and relationship forms, orientation, aliases, duplicates, and undeclared names, while preserving the broader/narrower inverse invariant for declared entities.
  2. Scheme membership and empty annotation filtering must agree with the concept-index emission rules without removing valid values or changing synonym handling.
  3. The relevant tests must pass at the pinned head, and the new regression tests must fail against the pre-change runtime.

Verification summary:

Commands below ran from wt-reviewer; paths are shown relative to that directory. Test runs used PYTHONDONTWRITEBYTECODE=1, PYTEST_DISABLE_PLUGIN_AUTOLOAD=1, and a TMPDIR inside the permitted scratch directory. The test runner also confines pytest caches and temporary files to scratch. No repository source was replaced for baseline testing: an import hook loads only ontology_runtime.py from the merge-base copy and verifies its loaded location.

Command/check Exit Result
python3 -m pytest -o addopts='' -o cache_dir=../scratch/pytest-cache --basetemp=../scratch/pytest-head tests/test_ontology_runtime.py tests/bigquery_ontology/test_concept_index.py tests/bigquery_ontology/test_owl_importer.py -q 0 175 passed, including the optional Turtle import round trip.
python3 ../scratch/run_pytest.py base tests/test_ontology_runtime.py -q --tb=short 1, expected 15 failed, 55 passed. Every failure is a new TestSkosParity case; all original tests pass. Failures are behavior assertions, not collection or dependency errors.
python3 ../scratch/run_pytest.py head ../scratch/test_review_edges.py -q --tb=short 0 4 passed. Includes 200 seeded hierarchy cases and 100 seeded emission-parity cases.
python3 ../scratch/run_pytest.py base ../scratch/test_review_edges.py -q --tb=short 1, expected 4 failed, demonstrating that the supplemental checks also detect the pre-change behavior.
git diff --check 594863851e62a08d7b5032ca5a4aa29ca4282c85 HEAD 0 No whitespace errors.
`git diff 5948638 HEAD | cmp - ../the PR diff 0 Supplied diff exactly matches the checkout diff. The escaped pipe here denotes the shell pipeline.
Python AST parse of both changed Python files with feature_version=(3, 10); test-method inventory 0 Both parse; 70 runtime tests, including 15 parity tests and 13 existing regression tests, matching the updated documentation.
git status --short, git diff --exit-code, git rev-parse HEAD 0 Clean checkout; head remains the requested SHA.

Evidence: focused test log, baseline regression log, supplemental checks, head supplemental log, baseline supplemental log, and baseline import runner.

The supplemental checks use loader-validated ontologies with abstract and bound concrete entities. They exercise mixed-source ordering, duplicate suppression, blank values, undeclared annotation targets, case sensitivity, cycles and self-edges, both relationship aliases, and an independent expected edge set. They also verify one-hop behavior, exclusion of mapping/transitive predicates, directional related annotations, scheme membership, labels, notation display values, whitespace and Unicode preservation, and unchanged blank-synonym behavior.

All pytest runs produced one configuration warning because plugin autoload was disabled and asyncio_mode was consequently unrecognized. The selected tests are synchronous; no tests were skipped or left uncollected in these runs.

Limits: execution used Python 3.13. Python 3.10 syntax parsing is not an execution test. The full repository suite, live BigQuery access, author-reported performance timings, and compatibility after merging the 39 newer main commits were not independently verified. The verdict applies to the pinned head. The new per-call entity/relationship scans are disclosed in the PR; no performance threshold was supplied.

Positives: traversal follows the importer's actual child-to-parent normalization and symmetric relationship representation. Scheme membership uses the same union and empty-string semantics as emission. The documentation clearly distinguishes directional annotations from symmetric related relationships and explains the undeclared-name behavior change. Every new regression test was observed failing on the pre-change runtime and passing on the reviewed head.

@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.

Independent review 2 of 2 at 22c5d569

P0=0 P1=0 P2=1 NIT=0
VERDICT: CLEAN @ 22c5d56

Findings

P2 | Important | The import round-trip guard does not pin the complete frozen fixture

ROOT CAUSE: tests/test_ontology_runtime.py:2079 compares _skos_shape() results rather than the imported ontology with the frozen ontology. The helper at tests/test_ontology_runtime.py:1719 retains entity names, five traversal/scheme annotation keys, and relationship endpoints, but ignores synonyms, SKOS label and notation annotations, descriptions, abstract flags, and other model fields. Consequently, meaningful importer drift can leave both the frozen-fixture test and the round-trip test green. This also makes the “pins the frozen YAML” statements at tests/test_ontology_runtime.py:2065 and docs/ontology_runtime_reader.md:190 stronger than the implemented check.

SUGGESTED FIX: Compare the loaded models directly:

assert imported == load_ontology_from_string(_IMPORTED_SKOS_TAXONOMY_YAML)

Comparing parsed YAML mappings would also cover the complete semantic fixture. If only the reduced shape is intentionally stable, narrow the test and documentation claims instead and add explicit coverage for the frozen labels that the runtime consumes.

PROVING TEST: In a scratch copy, I changed only the frozen skos_Banking synonym from Banking to Stale Banking. The submitted round-trip test still passed (exit 0), demonstrating the missed drift. Replacing the shape comparison with direct model equality made that stale-fixture case fail (exit 1), while the same direct equality check passed against the unmodified head importer and fixture.

Verification summary

  • pytest -p no:cacheprovider tests/test_ontology_runtime.py — exit 0; 70 collected and 70 passed, including the RDF round trip.
  • pytest -p no:cacheprovider tests/test_ontology_runtime.py tests/bigquery_ontology/test_concept_index.py tests/bigquery_ontology/test_owl_importer.py — exit 0; 175 collected and 175 passed.
  • pytest -p no:cacheprovider tests/bigquery_ontology tests/test_ontology_runtime.py tests/test_ontology_runtime_live.py — exit 0; 398 collected, 397 passed, and the opt-in live BigQuery test skipped. No live BigQuery verification was performed.
  • From scratch, using the head test module with an archived merge-base src: pytest -c pytest.ini -p no:cacheprovider test_ontology_runtime_head.py -q --tb=line — exit 1 as expected; exactly 15 TestSkosParity failures and 55 passes. A separate header check confirmed that the archived merge-base ontology_runtime.py was the module loaded.
  • Independent scratch probes covering 400 seeded randomized ontologies, mixed colon/underscore relationships, inverse annotations, self-loops, duplicate edges, unrelated mapping predicates, unknown names, blank values, scheme emission parity, and the declared-entity inverse invariant — exit 0; 2 tests passed. The second probe also confirmed that the unmodified imported and frozen models are currently exactly equal.
  • pyink --check src/bigquery_agent_analytics/ontology_runtime.py tests/test_ontology_runtime.py, isort --check-only on the same files, and git diff --check 594863851e62a08d7b5032ca5a4aa29ca4282c85..HEAD — combined exit 0.
  • The checkout remained clean; all reproductions and mutations were confined to scratch.

Positives

  • The implementation follows the importer’s actual child-to-parent skos_broader normalization and endpoint-sorted skos_related representation. Relationship and annotation sources are deduplicated without changing one-hop semantics.
  • topConceptOf membership, blank-value filtering, undeclared-name behavior, and the declared-entity broader/narrower inverse invariant matched independent oracle checks and concept-index emission in the exercised cases.
@caohy1988
caohy1988 merged commit 674973b into GoogleCloudPlatform:main Nov 6, 2026
15 checks passed
@caohy1988 caohy1988 mentioned this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants