Skip to content

feat(mdcode): OWL/SHACL import and BigQuery Graph fixes for semantic models - #468

Open
lluiscanet wants to merge 62 commits into
GoogleCloudPlatform:mainfrom
lluiscanet:feat/mdcode-owl-shacl-semantic-model
Open

lluiscanet wants to merge 62 commits into
GoogleCloudPlatform:mainfrom
lluiscanet:feat/mdcode-owl-shacl-semantic-model

Conversation

@lluiscanet

@lluiscanet lluiscanet commented Sep 29, 2026 •

Copy link
Copy Markdown

Summary

This PR makes kcmd compile an enterprise ontology (OWL 2 modules and SHACL shapes) and a raw BigQuery warehouse into a governed semantic model. The ontology is imported into a semantic model, governed in Knowledge Catalog before anything is bound, bound to the warehouse as it is by kcmd bind (scan, scoring and data profiling, with hydration rules a person confirms), and deployed to BigQuery as deduplicated node views and property graphs with measures; a node view the profile opts in (hydration.constraints: enforce) also applies the model's constraints to the rows it serves. Knowledge Catalog receives everything an agent needs to execute: lossless annotation aspects, description paragraphs naming the node view and graph to read (Read through:), the constraints each node view applies with how often each breaks (Constraints:) and the ready-to-run metric query (Query:), and binding links to the BigQuery assets. kcmd validate, kcmd profile and kcmd test check the model against the bound data, read-only.

Core Capabilities Added

  1. Multi-File OWL & SHACL Ingestion (kcmd owl import, kcmd shacl import)

    • Follows local owl:imports across modular files; never fetches over the network.
    • Translates OWL restrictions, disjointness and functional properties, and SHACL core and property-pair shapes, into judged model constraints with their severity and message.
    • Folds unkeyed equivalent classes into the keyed class; makes keyless classes with subclasses abstract (kcmd:abstract overrides).
    • --coverage writes what each construct became (compiled, hinted, dropped); --prune-unbound keeps only what a binding uses.
  2. Defined Classes as Membership Properties

    • Compiles owl:equivalentClass expressions decidable on one row into SQL predicates and boolean is<Class> properties on the base node table.
    • A definition that needs a join imports as an abstract entity with its definition as instructions and its restrictions as constraints.
  3. Derived Relationships & Property Chains

    • Compiles owl:propertyChainAxiom into via: relationships, deployed as edge_<relationship> views of distinct key pairs.
    • Relationship hierarchies become extra edge labels; declared inverses become inverse edge tables over the same backing table.
  4. Controlled Vocabularies & Enumerations

    • Imports enumerations and named individuals as vocabulary members (code, label, synonyms, definition, order, IRI).
    • kcmd push generates vocab_<entity> views and edge views that match recorded codes case-insensitively.
  5. In-Warehouse Constraint Validation (kcmd validate --target bigquery)

    • One violation-count query and one examples query per imported constraint, plus keys and foreign keys.
    • A report about the stored data; --publish records the results on the entity entries. The node views apply the same rules, compiled by the same code, to the rows a read sees (13).
  6. Automatic Metric Graph Slicing & Composite Measures

    • Imports kcmd:Metric individuals as metrics.
    • Deploys one GRAPH_EXPAND-ready tree per fact entity (<graph>__<fact>_metrics: one root, no convergent paths, at most 10 node tables), with a SQL view fallback for a metric no graph can hold.
    • Splits composite metrics into one MEASURE per aggregate (<metric>__agg<N>), recombined with SAFE_DIVIDE(AGG(…), AGG(…)).
    • Names a measure <metric>__measure when the metric's name is also a column of its node table: BigQuery accepts such a measure, then fails every query on the graph.
  7. Units, Scale, Grain & History

    • Field unit / scale and entity grain / history, read from OWL unit annotations, carried as parseable description paragraphs in BigQuery and Knowledge Catalog, and read back by pull.
  8. BigQuery Data Profiler & Claim Verification (kcmd profile, kcmd push --strict-profile)

    • Checks the model's claims against the bound data: key uniqueness, cardinality and orphans, enum coverage, unit magnitude, scale breaks over time, required nulls. Each claim is verified, unverified or contradicted, with evidence.
  9. Business Glossary Publishing (kcmd glossary push)

    • Publishes a model's glossary (categories, terms, formulas, synonyms) to Knowledge Catalog with definition links to BigQuery columns and semantic entries; imports SKOS concepts as terms; falls back to the node-view column when a semantic entry refuses a link.
  10. Model Contract Testing (kcmd test --target bigquery)

    • Tests generated from the model alone, read-only: is<Class> membership matches the definition; quantified paths over transitive relationships match a recursive SQL closure; every validation query executes. Graph tests without an Enterprise reservation are reported as skipped.
  11. Binding Discovery & Hydration (kcmd bind)

    • Scans INFORMATION_SCHEMA, scores every concrete entity against every table (name, key, field coverage, catalog hit), auto-accepts clear matches, lists candidates for the rest, guards against shadow tables of deprecated classes, and derives table-less entities from a relationship.
    • Profiles the chosen tables and proposes hydration rules from a closed vocabulary: grain, resolve, normalize (proposed off until confirmed) and derive_from, plus constraints: enforce (13). --accept-review confirms; --from-catalog binds the governed model pulled from Knowledge Catalog; --enforce-constraints writes constraints: enforce on every entity whose node view applies or reports a rule.
    • Writes <model>.profiles/<profile>.yaml and bind_report.md, which explains every decision.
    • kcmd push reads each bound entity through a generated node view: modeled columns only (plus _warnings where constraints are enforced), one row per key, hydration applied. The graph, edges, measures and metric graphs all read the views.
  12. Lossless Catalog Round-Trip & Agent Grounding

    • Three annotation aspects provisioned by kcmd init --semantic-model (semantic-ai-context, semantic-expressions, semantic-binding) carry what the built-in templates cannot; with them, a push → pull round trip returns the model unchanged.
    • lookup_context returns only description and schema, so push ends each description with Read through: (node view, graph, node label), Relationships: (every edge, with the join columns between node views) and, where the node view enforces constraints, Constraints: (the rules it applies, with rates) on bound entities, Query: (the metric's measures over GRAPH_EXPAND) on metrics, and Contents: (every metric and entity) on the model anchor. Pull drops all five, since they are derived.
    • Binding links from each bound entity to its @bigquery node-view entry and graph-node entry, written when the entry group is in the data's region (entry links cannot cross regions).
  13. Consumption-Time Constraint Enforcement (hydration.constraints: enforce, kcmd bind --enforce-constraints)

    • A node view the profile opts in applies the model's constraints after the other hydration rules, routed on each rule's on_violation: a reject rule about a value withholds it (NULL); a reject rule about the record (a required field, any rule on the key) excludes the row; warn / escalate serve the row as stored.
    • Every rule a served row breaks is named in a _warnings column (ARRAY<STRING>); the graph, GRAPH_EXPAND, GQL and measures read the served values.
    • sh:in serves a value equal to a member once case and whitespace are ignored in the member's spelling; only a value matching no member breaks the rule.
    • Relationship rules (cardinality, sh:class / OWL only, functional properties) and class disjointness are reported, never applied; a rule no query can measure is skipped with a push warning.
    • After the deploy, push measures how often each rule breaks over the hydrated rows and writes a derived Constraints: paragraph on the entity's entry, between Relationships: and Hydration:; pull drops it.
  14. Large File Copy Chunking with Protobuf Headroom

    • Dataplex limits aspect data to 120 KiB per entry. A large model or profile file that exceeds this limit is transparently split across up to 16 numbered parts (<filename>.part-<n>), sized with 2,048-byte headroom to guarantee that Dataplex server-side protobuf.Struct serialization wire overhead never exceeds the 120 KiB limit.
    • On kcmd pull, parts are joined in order, restoring the original source file byte-for-byte.

Testing & Validation

  • Upstream Merge: Cleanly rebased and merged on latest upstream GoogleCloudPlatform/knowledge-catalog main (commit af3b85b), with all merge conflicts resolved and zero regressions.
  • Unit and integration tests: All semantic and tool tests passing; complete coverage for file copies, hydration, constraint enforcement, OWL/SHACL converters, and BigQuery graph generation.
  • End-to-end verified: Full live execution on Google Cloud (kc-demo-349204): OWL/SHACL import, Knowledge Catalog governance (make govern), warehouse binding with hydration profiling (make bind), BigQuery Graph deployment (make push), and all 10 live demo queries (make demo) verified passing.
  • Agent benchmark: Evaluated across 140 questions and a 50-question sanity sample with multi-judge agreement against baseline.

Lluis Canet added 30 commits September 28, 2026 21:19
…models

Makes kcmd able to take a real, modular OWL ontology plus SHACL shapes and
deploy it to BigQuery Graph and Knowledge Catalog. Squashes 14 changes
(5 fixes, 9 features); new YAML keys are /google-only extensions.

Fixes
- owl import: don't import typed anonymous class expressions (Protégé-style
  `[ a owl:Class ; owl:intersectionOf ... ]`) as bogus `n3-*` entities.
- profiles: allow binding fields a subtype inherits via `extends`.
- bigquery/spanner DDL: emit NO PROPERTIES for empty hierarchy labels, FK
  edges, key-only nodes and field-less junction edges (a missing clause
  defaults to ALL COLUMNS, leaking columns and causing "property has more
  than one definition" deploy errors). Behaviour change: those elements no
  longer expose undeclared columns.
- bigquery DDL: rewrite field references in compound MEASURE operands to the
  bound columns.

OWL import
- Several Turtle files per import; local owl:imports followed transitively
  (ontology IRI must match; unresolved imports warn; no network access).
- owl:equivalentClass/Property -> ai_context.synonyms; owl:deprecated
  (+ rdfs:seeAlso) -> DEPRECATED description + steering instruction;
  transitive/symmetric properties -> relationship instructions.
- Restrictions (cardinality, qualified cardinality, some/all/hasValue),
  functional object properties, owl:disjointWith and owl:AllDisjointClasses
  -> model constraints with plain-English judgments.
- Relationship inheritance: `extends` / `abstract` on relationships
  (extra edge labels), imported from rdfs:subPropertyOf.
- Relationship `inverse:` -> reversed edge table over the same backing table,
  imported from owl:inverseOf.
- Restrictions stated through inverse properties or inside intersection
  conjuncts resolve to the forward relationship.

SHACL import
- New `kcmd shacl import <shapes.ttl...> [--into model.yaml]`: SHACL Core
  (min/maxCount, datatype, pattern, in, numeric ranges, sh:class, severity,
  message) and property pairs (lessThan, lessThanOrEquals, equals, disjoint)
  -> native model constraints. In-place, comment-preserving, idempotent.

Knowledge Catalog
- Publish abstract entities as table-less semantic-entity entries; carry
  `extends`/`abstract` in the description and restore them on pull.

Tests: new unit tests and golden fixtures for every mapping; tsc clean;
test:semantic passes. The only failures are the two tests/tool cases
(push --version / push -v) that also fail on main. Docs updated in
docs/semantic-model/ (owl-import, model_spec, reference, profiles, new
shacl-import page).
…kills-generate, location default

- defined entities (spec 'defined', IR Entity.definition): OWL equivalentClass definitions decidable on one row compile to membership expressions; BigQuery/Spanner lower them to is<Name> BOOLEAN properties on the base node tables; KC push/pull round-trip; validation; string codes match case-insensitively
- skills-generate --mode act|query|both, --extra-scope, --location: generated read/query skill (entity index, per-entity pages, metrics with GRAPH_EXPAND or SQL, model-generated GQL patterns)
- ApiContext: KC_LOCATION, then gcloud compute/region, then global
… import --prune-unbound (proposed)

Every kcmd owl import / kcmd shacl import now prints a per-construct summary and writes coverage.json beside the written model (--coverage <path>, --no-coverage): each construct occurrence with its outcome (compiled | hinted | dropped) and the reason. owl import --prune-unbound [binding] keeps the entities a binding profile binds, their ancestors and the defined entities over them, cascades to relationships, constraints and glossary links, and prints what it removed.
…K1 defined membership, transitive closure, K4 validation queries; extensible registry) (proposed)
…metrics as MEASURE components (K6b), deployed by push and named in the query skill (proposed)
…perty chains render anonymous inverses as inverse(p), not blank-node ids
…st the bound BigQuery data; push --strict-profile

Each claim (keys identify rows, foreign-key relationships are many-to-one or one-to-one and reach a row, sh:in value sets, unit magnitudes across peers, one scale over time unless a proposed 'Regime:' note declares the change, required fields set) becomes a statement -- verified, unverified or contradicted -- with its evidence, settled by one read-only query generated from the model and the binding profile over the rows validate reads. Writes profile.sql/json/md; --strict exits 1 on a contradiction; --publish writes a semantic-profile-results aspect on the entity entries (--dry-run prints the requests); --label tags the query jobs. push --strict-profile runs the same statements before each BigQuery graph deploy and stops on a contradiction.
…wl import --prune-unbound and kcmd test contract tests (proposed)
…c measures (proposed): push flags, deploy output, profile behaviour, query skill
K3: dataset 'members' (code, label, synonyms, definition, order, iri). OWL import maps owl:oneOf classes, classes with owl:NamedIndividual instances and classes annotated 'vocabulary true' (local name) to members (code from kcmd:code / skos:notation / local name 'code', order from local name sortOrder/order); encodedBy gives edges their join columns. BigQuery push generates vocab_<entity> views (code, label, sort_order, definition, iri) before the graph, binds the node table to them, and backs edges into a vocabulary with edge_<rel> views that match codes case-insensitively. KC: Members trailer on the entity description (round-trips codes and labels). Skills: Members section.

K2: relationship 'via' ([r1, ^r2, ...]) + optional 'filter'. OWL import maps owl:propertyChainAxiom (inverse steps, ends inferred from the chain). BigQuery push generates edge_<rel> views with the distinct (source key, target key) pairs over the chain; KC publishes a JOIN schema-join with Derived via/filter trailers; skills document the chain. Docs: model_spec, owl-import, fidelity, skills.
…s: the closure walks every edge table labelled p (abstract relationships too), nodes compare as <node table>:<key>, one quantified path per node-table pair; the graph shape mirrors push's unbound pruning (proposed)
…xtends; vocabularies detached from field-carrying parents

- kcmd:Metric individuals -> metrics[] (expression, description + Unit trailer,
  ai_context synonyms/instructions, attach entity); kcmd: vocabulary terms are
  never entities; a glossary term per metric when a SKOS glossary exists;
  kcmd:Metric coverage rows; metric count in the import summary.
- An inverse-functional property on a category with keyed subclasses stays a
  unique key (no promotion to primary key) and is inherited by concrete
  subclasses.
- A vocabulary does not extend a parent that carries fields (warned; the
  rdfs:subClassOf coverage row is dropped).
…lents, metrics, encodedBy to keyed classes
Profiles (and the extended profile) may set an entity's closed hydration block (grain latest_by|deterministic, normalize divide_by|multiply_by before|after, resolve match key|unique key, derive_from relationship) and mode view|direct; unknown rules/keys are rejected at merge and load. The BigQuery leg reads every bound entity through a generated node view (snake_case entity, modeled fields as snake_case columns) applying those rules; mode: direct opts out (resolve then becomes an edge_<rel> view). Deploy order: node views, vocab views, edge views, graph, metric graphs, metric views; --dry-run/--print list them; node-view failures name the entity. KC entity entries carry a 'Hydration:' trailer that pull restores. Docs: profiles.md, reference.md, fidelity.md.
Lluis Canet added 29 commits October 6, 2026 11:46
…ey imports abstract

The fallback left a concrete, keyless subclass with no rows to bind (a graph
deploy rejects it). Such a class now imports abstract: no node of its own, its
restrictions still become constraints, and its definition rides
ai_context.instructions in Manchester syntax. kcmd:abstract false keeps it
concrete; a class with its own fields or key keeps the subclass import.
…no longer fits

After a vocabulary detaches from its superclass (GeographicRegion no longer an
OrgUnit), inRegion still extended belongsToTerritory, whose range it no longer
fits, and the loader flagged its edges. The importer now drops such a parent
from extends, with a warning; the parent stays the abstract umbrella over the
subproperties that fit.
…ull of a logical model

- bind --from-catalog probes the provisioned annotation aspect types and
  hydrates them, as kcmd pull does (pullModelDocs). Without them the pull
  fell back to the lossy read: no metric expressions (a load error), link-id
  relationship names, abstract relationships dropped.
- A relationship that publishes no schema-join link (abstract, or an
  abstract / column-less endpoint) rides the model entry's relationship
  index whole (appended fields 4-13 on semantic-ai-context's relationship
  record; kcmd init patches an existing type forward). Pull rebuilds it, so
  sub-relationships keep their extends.
- Pull orients a join by the entity name when an endpoint has no data source
  (what the emitter writes then), instead of warning per link.
- No 'no backing data source' warning for an entry carrying annotation
  aspects: the read is lossless, so an empty source is authored.
- Load errors list each problem as 'path: message' instead of zod JSON.
- Tests: govern-style push -> bind --from-catalog yields the local IR and an
  identical profile/report (stubbed catalog); K1 codec round trip of
  unpublished relationships. Docs: bind.md, fidelity.md.
… unpublished relationships, join direction), readable load errors
…cendant binds

BigQuery and Spanner require labels with the same name to expose the same
set of properties. An abstract supertype has no table, so each concrete
descendant rendered its label from its own binding; descendants binding
different subsets of the inherited fields produced differing signatures
and BigQuery rejected the graph (seen live: Organization over ClientAccount,
which binds partyName, and EcosystemPartner, a node derived from a
relationship that carries only its key).

sharedAbstractLabelFields computes, once for both legs, the inherited
fields every carrying table binds; the shared label lists only those and
the rest stay on each binding descendant's DEFAULT LABEL, with a warning
naming the label, the field and the tables that leave it unbound.
…e is as on main

Decision D9: the PR no longer adds a model-specific read-side ("query")
skill to `kcmd skills-generate`; the demo uses one generic agent instead.
The upstream act-mode skill generator, runtime/agent_tools.ts,
runtime/dialect.ts, docs/semantic-model/skills.md and their tests stay,
and now match origin/main exactly.

Deleted (query mode only):
- src/libts/semantic/skills_query.ts
- src/libts/semantic/skills_text.ts
- tests/libts/semantic/skills_query.test.ts

Restored to origin/main:
- src/libts/semantic/skills.ts
- docs/semantic-model/skills.md
- the skills-generate command in src/tool/main.ts: --out, --name,
  --profile, --force (no --mode, --extra-scope, --location or
  --no-metric-graphs; push --no-metric-graphs is unchanged)
- SkillsGenerateOptions, skillsGenerate and stalePages in
  src/tool/commands.ts (skillsGenerate uses ApiContext.default() again)

Helpers removed (they fed only the query skill; no src caller is left):
- derived_relationships.ts: derivedSkillLine
- glossary.ts: SKILL_TERM_CAP, glossaryGuideLine, termSkillLine,
  glossarySkillSection, entityGlossaryLines
- units_history.ts: unitNote, grainHistoryLines
- vocabulary.ts: vocabularySkillLines
- metric_slices.ts: graphExpandExpression

Kept: generatorContext() in commands.ts (validate, test, profile and
glossary push use it; it moved below stalePages and its comment names
those users), MetricGraphPlan.placements (push prints the plan from it)
and renderComposition (the composition API that pairs with
MetricDecomposition.template).

Push warnings that named the skill are reworded:
- metric_slices.ts, a metric with no graph MEASURE and no fallback
  view: "the query skill gives plain SQL for it" -> "query it with plain
  SQL over the bound tables" (2 warnings)
- units_history.ts, a non-Boolean history.current_flag: "the skill
  tells agents to filter on ..." -> "current rows are read as
  '<flag> = TRUE'"

Docs: dropped the query-mode --no-metric-graphs row from reference.md's
skills-generate flags, the "Agent skills" section of glossary.md, and the
query-skill sentences in fidelity.md, model_spec.md and reference.md
(including links to skills.md anchors that no longer exist). Comments in
ir.ts and contract_tests.ts no longer mention skill pages. The tests of
the removed helpers are gone; metric_slices.test.ts renders the AGG
expression with renderComposition directly.
…'s own table

A foreign key into a vocabulary (matched case-insensitively) and a derived
relationship are rendered over generated edge views. GRAPH_EXPAND ignores a
standalone edge table as ambiguous, so a slice that kept such an edge had
the vocabulary as a second root and every GRAPH_EXPAND on it failed live
("The graph has multiple root node tables (3): GeographicRegion,
Opportunity, SalesStage"). The planner no longer follows those edges; the
main graph still walks them.
An entry link may reference only entries of its own region. Live, Dataplex
refuses a link in a 'global' entry group that references a 'us' @bigquery
entry (REFERRED_ENTRY_UNAVAILABLE_IN_ENTRY_LINK_REGION_ERROR), and a link in
'us' that references an entry of a 'global' entry group (entry group not
found). A model published to 'global' over US datasets therefore got one
refused link per bound entity and target.

bindingLinksFor now emits a binding link only when the @bigquery entry is in
the entry group's location, and reports the rest in one warning per region
that names the fix (publish the model to an entry group in the data's
location). The graph-node entry naming (propertyGraphs/<g>/nodes/<Label>,
type bigquery-graph-node) is confirmed live, so its TODO goes.

Docs: reference.md (Binding links), fidelity.md (residual gaps) and the
codelab's 'Consume with an agent' state the same-region requirement.
…/ Query)

lookup_context returns an entry's description and schema, not its aspects or
entry links, so an agent grounding on it never saw a node view, a graph or a
measure. When push knows the physical layout, a bound entity's description now
ends with 'Read through: node view ...; graph ..., node <Label>.' (before
Hydration:) and a metric's with 'Query: SELECT <measures composed as the
expression> FROM GRAPH_EXPAND("<metric graph>")' (or its fallback view).
Both are derived from the model and its BigQuery target; pull drops them, so
the push/pull round trip stays lossless.
BigQuery accepts a graph MEASURE named like a column of the node table's
backing table (won_amount = SUM(wonAmount) over a node view whose column is
won_amount), then fails every query on the graph -- GQL and GRAPH_EXPAND
alike -- with internal error 80038528 (reproduced on a two-row scratch graph:
the same graph with the measure named won_total works). Such a measure is now
named <metric>__measure, with one warning naming the column to read. The
generator records each measure's deployed name, metric placements carry it,
and the catalog's Query: paragraph is planned on the node-view-lowered model
the push deploys, so it always names the measure as deployed.
lookup_context shows neither entry links nor the relationship index, so an
agent grounding on it could not see how entities connect (it concluded that
related entities were unrelated). A bound entity's description now carries
'Relationships: <edge> -> <Entity> (<col> = <col>); <edge> <- <Entity> (...)'
with the join columns of the views both ends are read through, sized to keep
the description within Dataplex's 2,000 characters; pull drops it. Also: the
codelab no longer suggests BQ.SHOW_GRAPH_EXPAND_SCHEMA, which fails on graphs
that have measures.
Dataplex caps entry-link writes per minute and region (300 by default).
A push that writes more links than that in a minute got HTTP 429 on the
rest: a schema-join link failed the push, a binding link was skipped
with a warning (the demo push bound 77 of 78). Both writes now retry a
429 with linear backoff (20 s, 40 s, 60 s) before giving up.

Options linkWriteTries / linkRetryMs let tests run the retry without
sleeping. Tests: a refused write that lands on retry; one refused on
every try still fails with the quota message. Semantic suite 1672/0.
lookup_context returns descriptions only, and the anchor's description
was just the model's own text. An agent whose search matched no metric
or entity grounded on the anchor and found nothing to pick from.

Push now ends the anchor's description with a Contents: paragraph:
every metric, then every entity, by name, sized to the 2,000-character
description cap (a list that does not fit ends "… N more"). It is
written when push publishes for agents (the same gate as Read through:,
Relationships: and Query:), and pull peels it, so the model round-trips
unchanged.

Tests: full list, truncation (metrics kept first), empty model, peel,
published anchor, round trip. Semantic suite 1677/0; tsc clean.
…tion time

A binding profile opts an entity in with the closed hydration rule
`constraints: enforce`. Its node view then applies every rule kcmd validate
can check deterministically (parsed and compiled by the same code), after the
other hydration rules:

- reject, about a value: the failing value is withheld (served as NULL);
- reject, about the record (a required field, or any rule on the key): the
  row is excluded;
- warn / escalate: served as stored;
- every rule a served row breaks is named in a _warnings column;
- an allowed set (sh:in) repairs spelling up to case and whitespace;
- relationship and disjointness rules are reported, never applied.

Push measures how often each rule breaks over the hydrated rows and the
Knowledge Catalog entry carries a derived Constraints: paragraph (pull drops
it). kcmd bind --enforce-constraints writes the rule on every entity whose
view applies or reports one.
…ay node views apply enforced constraints; docs for consumption-time enforcement
…ode views; docs; test for unmeasurable reported rules
…odel's constraints under hydration.constraints: enforce (withhold, exclude, _warnings, sh:in spelling repair; relationship rules reported); rates on the Constraints: paragraph; kcmd bind --enforce-constraints
…e views), consumption-time constraint enforcement, lossless catalog round trip and agent grounding paragraphs, metric graphs and BigQuery graph fixes
Brings in the 38 upstream commits since 22efaa5: multi-dialect expressions,
flavor and inheritance rules, sources and deployment targets as GCP resource
names, binding profile files and named deployments, Knowledge Catalog V2
aspects, file copies, entry and link reconciliation, deploy preflight, and the
shared GoogleSQL graph generator. The PR's features are ported onto them:

- loader and profiles: the Google-flavor keys of the PR (hydration, mode,
  defined, grain, history, members, unit and scale, a relationship's inverse,
  extends, abstract, via and filter, glossary) stay accepted. Entities with no
  table by design (defined, hydration-derived, vocabulary views) need no source
  and are skipped by the completeness checks. The <model>.profiles/ wrapper
  that kcmd bind writes accepts per-entity hydration and mode; profile files
  reject them. Pruning follows upstream and never drops an entity or a
  relationship.
- validate: the concrete-leaf rule exempts abstract relationships, and only a
  table-backed subtype, at any depth, makes its ancestors non-leaves.
- OWL import: a relationship that touches an abstract class is imported as
  abstract, and an abstract class declares no keys; its unique keys flow to
  the concrete subclasses.
- graph: defined entities, shared abstract labels, NO PROPERTIES on every
  edge, relationship hierarchy and inverse edges live in the shared
  graph_ddl.ts; the BigQuery-only parts (measures, metric graphs, vocabulary
  and derived views, grain and history options, the enforcement warning) sit
  behind optional engine hooks.
- Knowledge Catalog: upstream's preflight, reconciliation, file copies and V2
  aspects together with the annotation aspects, the Relationships, Constraints
  and Hydration description paragraphs, junction links and the relationship
  index; reconciliation keeps everything the push writes.
- commands: push, pull, bind, validate, test, profile and glossary run on
  upstream's flow (profileForDocument, resolveStore, preflight).
- tests: fixtures use accepted source forms and named deployments; tests that
  pinned behavior upstream removed assert upstream's.

@vgoyal5 vgoyal5 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 huge amount of work here — the design coverage, docs, and test discipline are impressive. Locally on d4658a5c:

  • npm run compile (tsc --noEmit): pass
  • npm run build (build:libts, build:cli, build:tool): pass
  • npm test: 4,561 pass, 0 fail (libts 28+94, gcp 47, semantic 3,849, tool 543)
  • semantic_cli_gate.test.ts: 50/50 pass (all new commands and flags are properly gated under __KCMD_ENABLE_SEMANTIC__=false)
  • npm run test:semantic-pkg: 4/4 pass (offline install + SPDX SBOM)

Requesting changes because there are a few blocking bugs, heavy drift/conflicts against main, and size/reviewability concerns we should resolve before merging (ideally by rebasing and splitting this into focused PRs).


1. Merge conflicts, comment erasure & drift against main

  • The branch last merged main at bd2c43b (#671) and is now 35 commits behind main (266bf973) with 18 conflicting files (CONFLICTING/DIRTY).
  • Merge commit d4658a5c appears to have accidentally stripped ~1,630+ lines of JSDoc and invariant comments across core files (plus reformatted unrelated OKF code in commands.ts that conflicts with #664 and #682):
    • src/libts/semantic/resolve_profiles.ts: 579 → 29 comment lines (-95%)
    • src/libts/semantic/loader.ts: 999 → 542 comment lines (-450+)
    • src/libts/semantic/deploy_knowledge_catalog.ts: 593 → 284 comment lines (-300+)
    • src/tool/commands.ts: 460 → 336 comment lines (reformatting unrelated init / extractOkfRootMetadata / OKF push)
  • Rebasing onto current main also requires careful reconciliation with recent semantic/push changes so we don't regress them:
    • #584 (leaf-only node tables & narrowed ancestor labels): graph_ddl.ts, bigquery.ts, node_views.ts, defined_entities.ts, metric_slices.ts, validate_bigquery.ts, and contract_tests.ts all still treat concrete supertypes as node tables; shared_labels.ts overlaps with #584's intersection logic.
    • #698 (keep field descriptions verbatim): bigquery.ts and validate.ts fold label / Time dimension. / unitTrailer back into OPTIONS(description) instead of OPTIONS(extensions).
    • #680 (Spanner pre-write graph validation), #695 (skip unchanged Knowledge Catalog entry writes), #689 (statedSources / pruneUnavailable), #693 (grouped deployment-table errors), #687, #690, #692, #694, #696, and #682 (--context-set).

2. Blocking findings (details left inline)

  1. Knowledge Catalog overwrite & stale link deletion (deploy_knowledge_catalog.ts:357-373): syncBigQueryCatalogGrounding re-emits semantic-entity entries from the pruned, single-profile deployment model when constraintRates is non-empty, overwriting the logical entries published in Phase 1 (dropping unbound fields and sibling profile bindings). With 2+ BigQuery deployments, the second pass also deletes the first deployment's @bigquery binding links as "stale".
  2. --prune-glossary deletes newly published resources (glossary_publish.ts:280-294): listAll() uses dp._get(...) directly (returning canonical project-number resource names), while plan.termNames/categoryNames use string project IDs (projects/<project-id>/...). On project IDs, has() is always false and prune() deletes every term and category it just published.
  3. Arbitrary local file read in owl:imports (converters/owl/imports.ts:57-64, 118-128): file: IRIs have no directory confinement or symlink check (fs.realpathSync), parseOwlHeader isn't wrapped in try/catch (non-Turtle content leaks in parse errors), and there are no file-count/size caps.
  4. SQL injection / escaping gaps (bind/scan.ts, bind/hydrate.ts, validate_bigquery.ts, node_views.ts, metric_slices.ts): Unvalidated --location interpolated in backticks; q() strips ` without escaping \; table() turns any whitespace dataSource into raw subquery SQL (${src}); sqlString in validate_bigquery.ts omits \r escaping (and bind/hydrate.ts omits \n/\r/\t).
  5. External view overwrite risk (vocabulary.ts:70-77, 158-183, node_views.ts:289-320): generatesVocabularyView matches vocab_<entity> regardless of project/dataset, allowing CREATE OR REPLACE VIEW to overwrite a table/view outside the deployment target. Default-on unprefixed node views and edge_<snake_case> views also lack ownership/collision checks and pre-deploy dry-runs.
  6. Unbounded BigQuery query costs & cyclic recursive CTE (gcp/bigquery.ts, constraint_enforcement.ts:524, contract_tests.ts:421-429): No maximumBytesBilled support anywhere; every live push with enforced constraints fires unbounded Promise.all over full-table ratesSql queries; closureTest uses WITH RECURSIVE ... UNION ALL up to k = 10 with no cycle guard (O(d^10)).
  7. hydration.constraints: enforce correctness (constraint_enforcement.ts:178-193, 249-250, 337): sh:in spelling repair ignores both gate and onViolation (mutating rows outside defined entities and under warn/escalate); textual(undefined) fails view compilation on untyped non-string columns; gated reject + required excludes rows from the base entity view; ratesSql denominator is un-gated (COUNT(*)).
  8. Sibling-field breakage & vendor SQL smuggling (node_views.ts:677-681): Default-on node_views does not splice sibling-field expressions (unlike graph_ddl.ts), breaking computed fields whose column names differ. Eight BigQuery modules also fall back to ?? fieldBinding(f), leaking untranspiled non-BigQuery importedExpression SQL into BigQuery DDL.
  9. kcmd push --strict-profile --validate-only regression (commands.ts:937-949): if (options.strictProfile && !options.validateOnly) silently skips the gate under --validate-only (contradicting main.ts help text, profiling.md, and 67038667 prior to the merge). profileGate also omits the deployment's project and location, so non-US datasets silently fail-open as "unverified".
  10. Corrupt vanilla Ossie (0.2.0.dev0) YAML (tool/bind.ts:211-234): upsertModelDeployment parses custom_extensions[].data into an object and writes it back without JSON.stringify(...), failing loader.ts's strict data: z.string() schema (and silently wipes g.data on parse errors).
  11. owl/definitions.ts inverted SQL & empty oneOf (definitions.ts:306-379): Qualified max 0 / exact 0 restrictions return IS NULL before checking e.filler (silently compiling e.g. inStage max 0 {Stage_Won} to stage IS NULL). Empty owl:oneOf () emits illegal IN (); length facets don't validate integers (NaN); notOf ignores SQL 3-valued logic on NULL.
  12. --prune-unbound gaps (prune.ts:99-166, 214-222): Leaves dangling model.metrics and via steps, drops tableless vocabularies (Entity.members), and matches pruned names across English constraint prose via raw regex (mentionsAny collides with common words like value, name, type, in, has, only, OWL).
  13. Case-insensitive collisions & invalid identifiers (converters/owl/to_ir.ts:345-670): loader.ts enforces case-insensitive uniqueness and IN_SQL identifiers, while the OWL importer deduplicates case-sensitively and emits raw local names (e.g. hyphens like line-item), crashing loadSemanticModels.

3. Major follow-ups (good to fix as part of splitting)

  • 120 KiB aspect headroom: Merge d4658a5c removed V1 .part-N chunking, while semantic-extensions double-JSON-encodes glossary and members into a single aspect checked against 120 * 1024 with zero protobuf wire-overhead headroom (deploy_knowledge_catalog.ts:526-580).
  • Glossary publish reliability (glossary_publish.ts): Missing HTTP 429 retry backoff on entry-link writes; listAll silently breaks on non-200; semantic-link error fallback swallows 401/403/429/5xx; numeric project IDs skip numbers.set(project, project) at L62; modelLabelValue truncates to 63 chars without a hash suffix (risking cross-model --prune-glossary collisions).
  • Description trailer round-trip & 2,000-char limit: hydration_kc.ts:41-43 uses \S+? which breaks on space-separated ISO timestamps accepted by hydration.ts:51-52; glossary.ts:339-360 strips user prose starting with Formula:/Also called:/Source: anywhere in definition; validate.ts:240-263 validates description length before trailers are appended; explicit Opaque datatypes always round-trip to undefined.
  • kcmd bind overwrites & scan limits: Writes <model>.yaml and profile files before checkProfile validation; fixed bind_report.md/bind_scan.json paths clobber across multi-doc runs; renderProfileYaml (bind/report.ts:306) drops models 2..N; normalizeSql runs N full-table scans per query; scanSql packs all tables/columns into one TO_JSON_STRING(ARRAY_AGG(...)) cell (10 MB BQ cell limit); CSV parser breaks on UTF-8 BOM (\uFEFF) and multi-line quoted fields.
  • validate_bigquery.ts & contract_tests.ts: Derived relationships (rel.via) aren't skipped and generate empty LEFT JOIN ... ON ; sh:in breaks on apostrophes; constant temporal bounds use SAFE_CAST (silently evaluating malformed bounds to 0 violations); contract_tests.ts compares deployed hydrated node views against raw unhydrated base tables. (Also note commands.ts:3082 profile({cwd}) ignores cwd when building outDir.)
  • metric_composition.ts & metric_slices.ts: COUNTIF(c) rewritten to SUM(CASE ...) returns NULL instead of 0 on empty groups; conjuncts() breaks multi-token BETWEEN ... AND; misses COUNT(DISTINCT(x)); metric_slices.ts:896 misses quoteIfReserved(local); __agg collision silently reuses an unrelated user metric at L703.
  • derived_relationships.ts & sql_expr_utils.ts: derived_relationships.ts ignores r.association, lacks from/to column length check, and double-rewrites entity names like n0/n1 in rewriteFilter. scanIdentifiers/mapOutsideStringLiterals don't skip SQL comments (--, #, /* */) or handle raw strings (r'...').
  • OWL/SHACL edge cases & cac --no-coverage: joinEncodedEdges runs before applyOwlVocabularies/detachVocabularyParents; last-wins new Map(...) mismatches first-wins emission on duplicate localNames; owl/coverage.ts:516-593 still reports K2 propertyChainAxiom and K3 oneOf as dropped; cac's .option('--no-coverage') defaults options.coverage to true, bypassing the Boolean(options.out) guard; empty numeric literals parse as 0 (Number("") === 0); skos:related targeting a ConceptScheme emits a category ID in term.related; subclass maxCardinality 1 suppresses superclass FunctionalProperty; 4 dropped SHACL constructs falsely report compiled.
  • Bundle note: Eager top-level imports in src/tool/main.ts grow the public gated build/ts/kcmd/cli.js bundle from 1.12 MB (84 modules) to 1.48 MB (120 modules). Not introduced by this PR (already eager on main), but worth lazy-loading later if we want to trim the published package.

4. Recommended PR Split Plan

At +54,084 / -2,780 across 173 files, rebasing and re-reviewing this as a single PR is going to keep causing painful merge regressions like d4658a5c. Suggest rebasing onto current main (266bf973) and landing in 6 stacked/sequential PRs:

  1. Shared SQL quoting + Core IR/Loader extensions (K1/K2/K3/K7): unified BigQuery quoting + maximumBytesBilled in gcp/bigquery.ts, defined_entities, vocabulary, derived_relationships, units_history — reconciled cleanly with #584, #680, #692, #698.
  2. Multi-file OWL & SHACL importers + coverage + pruning: converters/owl/*, converters/shacl/*, converters/coverage.ts, prune.ts.
  3. Hydration, node views & consumption-time constraint enforcement: hydration.ts, node_views.ts, constraint_enforcement.ts, hydration_kc.ts (aligned with #584 leaf-only node tables).
  4. Metric graphs (GRAPH_EXPAND) & composite measures: metric_slices.ts, metric_composition.ts, --no-metric-graphs.
  5. Read-only BigQuery tooling (validate, profile, test, bind): validate_bigquery.ts, profile_bigquery.ts, contract_tests.ts, bind/*, tool/bind.ts.
  6. Lossless Knowledge Catalog grounding & Business Glossary (glossary push): kc_annotations.ts, kc_closure_env.ts, read_trailers.ts, glossary.ts, glossary_publish.ts (reconciled with #695).

if (constraintRates?.get(model.name)?.size) {
for (const entry of resources.entries) {
if (!entry.entryType?.endsWith('/entryTypes/semantic-entity')) continue;
await writeEntry(cat, opts, entry, new Map());

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.

Blocking: syncBigQueryCatalogGrounding receives bqDeployedModels from commands.ts:989-1005, where each plan.model has already run applyProfile(), pruneUnavailable(), and single-deployment filtering.

  1. When constraintRates is non-empty, writeEntry(cat, opts, entry, new Map()) rewrites semantic-entity entries using that pruned, single-profile model (and deleteMissingAspects=true), overwriting the logical model pushed in Phase 1 — wiping unbound fields, other profiles' bindings/hydration, and breaking kcmd pull.
  2. With 2+ BigQuery deployments in bqDeployedModels, each loop iteration passes only that deployment's bindingLinks to findStaleBindingLinks, deleting the previous deployment's @bigquery binding links as stale.
  3. Both writeEntry(...) (L360) and deleteEntryLinks(...) (L372) discard their {error} returns silently.

Fix: patch only entry_source.description from the unpruned logical model in prepared.emitted (leaving aspects untouched), aggregate bindingLinks per model.name across all BigQuery deployments before computing stale links, and surface returned errors.

x.labels?.[MODEL_LABEL] === modelLabel;
const terms = await listAll(dp, `${plan.glossaryName}/terms`, 'terms');
for (const t of terms) {
if (!ours(t) || plan.termNames.has(t.name)) continue;

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.

Blocking: listAll() calls dp._get(...) directly (bypassing CatalogClient._fixEntry / crm.fixProject), so Dataplex returns canonical project-number resource names (projects/<number>/locations/.../terms/<id>). Meanwhile plan.termNames and plan.categoryNames hold string project-ID paths (projects/<project-id>/...).

Whenever --project is a project ID, plan.termNames.has(t.name) (and plan.categoryNames.has(c.name) at L294) returns false for every resource while ours(t) matches the kcmd labels — so --prune-glossary deletes every term and category it just published.

Also: prune() should abort if any prior create/update failed or listAll() returns a non-200 status (currently L263 silently breaks on error). Recommend normalizing by stripping ^projects/[^/]+/ (or comparing IDs) and adding a unit test with project-number responses.

function candidatePaths(iri: string, importerDir: string): string[] {
if (iri.startsWith('file:')) {
try {
return [fileURLToPath(iri)];

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.

Blocking (security): file: IRIs have zero directory confinement — e.g. owl:imports <file:///etc/passwd> resolves and reads arbitrary local files. In addition:

  • parseOwlHeader(text) at L123 is unguarded (try/catch), so probing a non-Turtle file throws an n3 syntax error that can leak a snippet of its contents.
  • fs.statSync follows symlinks without fs.realpathSync containment checks, and segment (L67) doesn't reject \, ., or ...
  • There is no cap on total imported files or file byte size before fs.readFileSync.

Please reject file: URIs (or confine fs.realpathSync(candidate) strictly inside the importer root directory), deduplicate loadedPaths by realpath, wrap candidate parsing in try/catch, and enforce reasonable file-count / byte-size caps.

* columns in ordinal order, as a JSON array in column `tables`.
*/
export function scanSql(pattern: ScanPattern, location: string): string {
const is = `\`${pattern.project}\`.\`${regionQualifier(location)}\`.INFORMATION_SCHEMA`;

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.

Blocking (security): location (from the CLI --location flag at src/tool/bind.ts:293) is unvalidated and interpolated directly inside backticks (region-${location.toLowerCase()}), as is pattern.project. A value containing ` escapes the identifier and injects arbitrary BigQuery SQL.

Validate location against /^(?:region-)?[a-z][a-z0-9-]*$/i (and validate/escape pattern.project) before constructing scanSql.

findings: ProfileFinding[];
}

const q = (id: string) => `\`${id.replace(/`/g, '')}\``;

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.

Blocking (security): q() strips backticks but does not escape backslashes (\). In BigQuery Standard SQL, a trailing \ inside a backticked identifier (e.g., from an untrusted --scan-file JSON/CSV) escapes the closing `, breaking out into raw SQL.

Also note sqlStringLiteral on L110–112 omits \n, \r, and \t escaping. Prefer a shared, strict BigQuery identifier/string quoting helper.

const local = (f: Field) => stripQualifier(fieldSqlOf(f)!, e.name);
const exprs = new Map<string, string>();
for (const f of e.fields) {
if (p.columns.has(f.name)) exprs.set(f.name, aliased('t', local(f)));

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.

Blocking: lowerNodeViews runs before generatePropertyGraph (on by default) and rewrites every field's expression to its snake_case view column, but tableViewSql never splices sibling-field expressions (unlike graph_ddl.ts). Any computed field referencing a sibling whose physical column name differs emits an unresolved column name in the view SELECT and fails BigQuery compilation.

Related: line 73 (expressionForDialect(f, 'BIGQUERY') ?? fieldBinding(f)) — and 7 other BigQuery modules — fall back to fieldBinding(f), smuggling untranspiled non-BigQuery vendor SQL (importedExpression) into BigQuery DDL. Use strict expressionForDialect(..., 'BIGQUERY') instead.

@@ -918,6 +933,21 @@ async function pushInTwoPhases(
const printed = new Set(locationWarnings);
for (const w of printed) console.warn(`Warning: ${w}`);
if (errors.length) return fail(...errors);

if (options.strictProfile && !options.validateOnly) {

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.

Blocking: This contradicts both src/tool/main.ts help text and docs/semantic-model/profiling.md ("read-only, so it also runs under --validate-only"). It looks like this regression was introduced in merge commit d4658a5c (67038667 previously ran profileGate under --validate-only).

Also, profileGate (L944 / L3219) calls runBigQueryProfile(plan, ctx) without passing the deployment's project or BigQuery dataset location. On non-US datasets (e.g., EU), every query fails with a location mismatch error — and because profileGate treats errored statements as unverified without failing or warning, the gate silently passes (none contradicted).

case 'min':
case 'exact': {
const n = e.restriction === 'some' ? 1 : e.cardinality ?? 1;
if (e.restriction === 'exact' && n === 0)

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.

Blocking: All four 0-cardinality branches (L306–307, L323–325, L364–365, and L374) return IS NULL before checking e.filler. For example, a qualified restriction like NonWonOpportunity ≡ Opportunity ⊓ (inStage max 0 {Stage_Won}) silently compiles to stage IS NULL, dropping every non-null, non-won row.

Also in this file:

  • Empty owl:oneOf () (L285–294, L317–318, L329–330) emits illegal SQL IN ().
  • length/minLength/maxLength (L415–420) interpolate Number(value.value) without integer validation (can emit NaN).
  • notOf (NOT (expr)) misses SQL 3-valued logic on NULL columns (excluding rows that OWL complementOf includes).

const constraints: Constraint[] = [];
const prunedConstraints: string[] = [];
for (const c of model.constraints ?? []) {
if (mentionsGone(`${c.judgment ?? ''}\n${c.description ?? ''}`)) {

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.

Blocking: A few gaps in --prune-unbound:

  1. mentionsAny prose collisions (here & L214–222): Matching pruned entity/relationship names as whole words across generated English constraint sentences silently deletes valid constraints whenever a pruned ontology name overlaps a common English word (e.g. value, name, type, in, has, only, OWL). Track structured references instead.
  2. Metrics are never pruned (L133–137): Dangling metric.entity / authoredEntity references survive pruning and fail loadSemanticModels.
  3. Tableless vocabularies (Entity.members) are pruned away (L67–90): They intentionally have no source:, so --prune-unbound drops every vocabulary and edge pointing to it.
  4. Derived via chains (L99–114): Relationships with pruned intermediate hops stay behind with dangling via steps.

const edges = parts.length === 1 ?
parts[0] :
`SELECT DISTINCT src, dst\nFROM (\n${indent(parts.join('\nUNION ALL\n'))}\n)`;
const closure = [

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.

Blocking (cost/DoS): WITH RECURSIVE ... UNION ALL runs up to k = 10 hops with no cycle/visited-node guard. On cyclic graphs this explodes exponentially (O(d^10)). Please track visited nodes (or use a path array guard) and support maximumBytesBilled on the BigQuery client runner.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants