Repository navigation
feat(mdcode): OWL/SHACL import and BigQuery Graph fixes for semantic models - #468
lluiscanet wants to merge 62 commits into
Conversation
…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
…ms and entry links; SKOS import
… query guide commits to one reading
… 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.
…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.
… the fixed importer
…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.
…e (TIMESTAMP columns typed DateTime)
… 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.
…cl-semantic-model
vgoyal5
left a comment
There was a problem hiding this comment.
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): passnpm run build(build:libts,build:cli,build:tool): passnpm test: 4,561 pass, 0 fail (libts28+94,gcp47,semantic3,849,tool543)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
mainatbd2c43b(#671) and is now 35 commits behindmain(266bf973) with 18 conflicting files (CONFLICTING/DIRTY). - Merge commit
d4658a5cappears to have accidentally stripped ~1,630+ lines of JSDoc and invariant comments across core files (plus reformatted unrelated OKF code incommands.tsthat conflicts with #664 and #682):src/libts/semantic/resolve_profiles.ts:579→29comment lines (-95%)src/libts/semantic/loader.ts:999→542comment lines (-450+)src/libts/semantic/deploy_knowledge_catalog.ts:593→284comment lines (-300+)src/tool/commands.ts:460→336comment lines (reformatting unrelatedinit/extractOkfRootMetadata/ OKFpush)
- Rebasing onto current
mainalso 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, andcontract_tests.tsall still treat concrete supertypes as node tables;shared_labels.tsoverlaps with #584's intersection logic. - #698 (keep field descriptions verbatim):
bigquery.tsandvalidate.tsfoldlabel/Time dimension./unitTrailerback intoOPTIONS(description)instead ofOPTIONS(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).
- #584 (leaf-only node tables & narrowed ancestor labels):
2. Blocking findings (details left inline)
- Knowledge Catalog overwrite & stale link deletion (
deploy_knowledge_catalog.ts:357-373):syncBigQueryCatalogGroundingre-emitssemantic-entityentries from the pruned, single-profile deployment model whenconstraintRatesis 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@bigquerybinding links as "stale". --prune-glossarydeletes newly published resources (glossary_publish.ts:280-294):listAll()usesdp._get(...)directly (returning canonical project-number resource names), whileplan.termNames/categoryNamesuse string project IDs (projects/<project-id>/...). On project IDs,has()is alwaysfalseandprune()deletes every term and category it just published.- 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),parseOwlHeaderisn't wrapped intry/catch(non-Turtle content leaks in parse errors), and there are no file-count/size caps. - SQL injection / escaping gaps (
bind/scan.ts,bind/hydrate.ts,validate_bigquery.ts,node_views.ts,metric_slices.ts): Unvalidated--locationinterpolated in backticks;q()strips`without escaping\;table()turns any whitespacedataSourceinto raw subquery SQL(${src});sqlStringinvalidate_bigquery.tsomits\rescaping (andbind/hydrate.tsomits\n/\r/\t). - External view overwrite risk (
vocabulary.ts:70-77, 158-183,node_views.ts:289-320):generatesVocabularyViewmatchesvocab_<entity>regardless of project/dataset, allowingCREATE OR REPLACE VIEWto overwrite a table/view outside the deployment target. Default-on unprefixed node views andedge_<snake_case>views also lack ownership/collision checks and pre-deploy dry-runs. - Unbounded BigQuery query costs & cyclic recursive CTE (
gcp/bigquery.ts,constraint_enforcement.ts:524,contract_tests.ts:421-429): NomaximumBytesBilledsupport anywhere; every livepushwith enforced constraints fires unboundedPromise.allover full-tableratesSqlqueries;closureTestusesWITH RECURSIVE ... UNION ALLup tok = 10with no cycle guard (O(d^10)). hydration.constraints: enforcecorrectness (constraint_enforcement.ts:178-193, 249-250, 337):sh:inspelling repair ignores bothgateandonViolation(mutating rows outside defined entities and underwarn/escalate);textual(undefined)fails view compilation on untyped non-string columns; gatedreject+requiredexcludes rows from the base entity view;ratesSqldenominator is un-gated (COUNT(*)).- Sibling-field breakage & vendor SQL smuggling (
node_views.ts:677-681): Default-onnode_viewsdoes not splice sibling-field expressions (unlikegraph_ddl.ts), breaking computed fields whose column names differ. Eight BigQuery modules also fall back to?? fieldBinding(f), leaking untranspiled non-BigQueryimportedExpressionSQL into BigQuery DDL. kcmd push --strict-profile --validate-onlyregression (commands.ts:937-949):if (options.strictProfile && !options.validateOnly)silently skips the gate under--validate-only(contradictingmain.tshelp text,profiling.md, and67038667prior to the merge).profileGatealso omits the deployment'sprojectandlocation, so non-US datasets silently fail-open as "unverified".- Corrupt vanilla Ossie (
0.2.0.dev0) YAML (tool/bind.ts:211-234):upsertModelDeploymentparsescustom_extensions[].datainto an object and writes it back withoutJSON.stringify(...), failingloader.ts's strictdata: z.string()schema (and silently wipesg.dataon parse errors). owl/definitions.tsinverted SQL & emptyoneOf(definitions.ts:306-379): Qualifiedmax 0/exact 0restrictions returnIS NULLbefore checkinge.filler(silently compiling e.g.inStage max 0 {Stage_Won}tostage IS NULL). Emptyowl:oneOf ()emits illegalIN (); length facets don't validate integers (NaN);notOfignores SQL 3-valued logic onNULL.--prune-unboundgaps (prune.ts:99-166, 214-222): Leaves danglingmodel.metricsandviasteps, drops tableless vocabularies (Entity.members), and matches pruned names across English constraint prose via raw regex (mentionsAnycollides with common words likevalue,name,type,in,has,only,OWL).- Case-insensitive collisions & invalid identifiers (
converters/owl/to_ir.ts:345-670):loader.tsenforces case-insensitive uniqueness andIN_SQLidentifiers, while the OWL importer deduplicates case-sensitively and emits raw local names (e.g. hyphens likeline-item), crashingloadSemanticModels.
3. Major follow-ups (good to fix as part of splitting)
- 120 KiB aspect headroom: Merge
d4658a5cremoved V1.part-Nchunking, whilesemantic-extensionsdouble-JSON-encodesglossaryandmembersinto a single aspect checked against120 * 1024with 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;listAllsilentlybreaks on non-200; semantic-link error fallback swallows401/403/429/5xx; numeric project IDs skipnumbers.set(project, project)at L62;modelLabelValuetruncates to 63 chars without a hash suffix (risking cross-model--prune-glossarycollisions). - Description trailer round-trip & 2,000-char limit:
hydration_kc.ts:41-43uses\S+?which breaks on space-separated ISO timestamps accepted byhydration.ts:51-52;glossary.ts:339-360strips user prose starting withFormula:/Also called:/Source:anywhere indefinition;validate.ts:240-263validates description length before trailers are appended; explicitOpaquedatatypes always round-trip toundefined. kcmd bindoverwrites & scan limits: Writes<model>.yamland profile files beforecheckProfilevalidation; fixedbind_report.md/bind_scan.jsonpaths clobber across multi-doc runs;renderProfileYaml(bind/report.ts:306) drops models2..N;normalizeSqlruns N full-table scans per query;scanSqlpacks all tables/columns into oneTO_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 emptyLEFT JOIN ... ON;sh:inbreaks on apostrophes; constant temporal bounds useSAFE_CAST(silently evaluating malformed bounds to 0 violations);contract_tests.tscompares deployed hydrated node views against raw unhydrated base tables. (Also notecommands.ts:3082profile({cwd})ignorescwdwhen buildingoutDir.)metric_composition.ts&metric_slices.ts:COUNTIF(c)rewritten toSUM(CASE ...)returnsNULLinstead of0on empty groups;conjuncts()breaks multi-tokenBETWEEN ... AND; missesCOUNT(DISTINCT(x));metric_slices.ts:896missesquoteIfReserved(local);__aggcollision silently reuses an unrelated user metric at L703.derived_relationships.ts&sql_expr_utils.ts:derived_relationships.tsignoresr.association, lacksfrom/tocolumn length check, and double-rewrites entity names liken0/n1inrewriteFilter.scanIdentifiers/mapOutsideStringLiteralsdon't skip SQL comments (--,#,/* */) or handle raw strings (r'...').- OWL/SHACL edge cases &
cac--no-coverage:joinEncodedEdgesruns beforeapplyOwlVocabularies/detachVocabularyParents; last-winsnew Map(...)mismatches first-wins emission on duplicatelocalNames;owl/coverage.ts:516-593still reports K2propertyChainAxiomand K3oneOfasdropped;cac's.option('--no-coverage')defaultsoptions.coveragetotrue, bypassing theBoolean(options.out)guard; empty numeric literals parse as0(Number("") === 0);skos:relatedtargeting aConceptSchemeemits a category ID interm.related; subclassmaxCardinality 1suppresses superclassFunctionalProperty; 4 dropped SHACL constructs falsely reportcompiled. - Bundle note: Eager top-level imports in
src/tool/main.tsgrow the public gatedbuild/ts/kcmd/cli.jsbundle from1.12 MB(84 modules) to1.48 MB(120 modules). Not introduced by this PR (already eager onmain), 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:
- Shared SQL quoting + Core IR/Loader extensions (K1/K2/K3/K7): unified BigQuery quoting +
maximumBytesBilledingcp/bigquery.ts,defined_entities,vocabulary,derived_relationships,units_history— reconciled cleanly with #584, #680, #692, #698. - Multi-file OWL & SHACL importers + coverage + pruning:
converters/owl/*,converters/shacl/*,converters/coverage.ts,prune.ts. - 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). - Metric graphs (
GRAPH_EXPAND) & composite measures:metric_slices.ts,metric_composition.ts,--no-metric-graphs. - Read-only BigQuery tooling (
validate,profile,test,bind):validate_bigquery.ts,profile_bigquery.ts,contract_tests.ts,bind/*,tool/bind.ts. - 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()); |
There was a problem hiding this comment.
Blocking: syncBigQueryCatalogGrounding receives bqDeployedModels from commands.ts:989-1005, where each plan.model has already run applyProfile(), pruneUnavailable(), and single-deployment filtering.
- When
constraintRatesis non-empty,writeEntry(cat, opts, entry, new Map())rewritessemantic-entityentries using that pruned, single-profile model (anddeleteMissingAspects=true), overwriting the logical model pushed in Phase 1 — wiping unbound fields, other profiles' bindings/hydration, and breakingkcmd pull. - With 2+ BigQuery deployments in
bqDeployedModels, each loop iteration passes only that deployment'sbindingLinkstofindStaleBindingLinks, deleting the previous deployment's@bigquerybinding links as stale. - Both
writeEntry(...)(L360) anddeleteEntryLinks(...)(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; |
There was a problem hiding this comment.
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)]; |
There was a problem hiding this comment.
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 ann3syntax error that can leak a snippet of its contents.fs.statSyncfollows symlinks withoutfs.realpathSynccontainment checks, andsegment(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`; |
There was a problem hiding this comment.
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, '')}\``; |
There was a problem hiding this comment.
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))); |
There was a problem hiding this comment.
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) { | |||
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 SQLIN (). length/minLength/maxLength(L415–420) interpolateNumber(value.value)without integer validation (can emitNaN).notOf(NOT (expr)) misses SQL 3-valued logic onNULLcolumns (excluding rows that OWLcomplementOfincludes).
| const constraints: Constraint[] = []; | ||
| const prunedConstraints: string[] = []; | ||
| for (const c of model.constraints ?? []) { | ||
| if (mentionsGone(`${c.judgment ?? ''}\n${c.description ?? ''}`)) { |
There was a problem hiding this comment.
Blocking: A few gaps in --prune-unbound:
mentionsAnyprose 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.- Metrics are never pruned (L133–137): Dangling
metric.entity/authoredEntityreferences survive pruning and failloadSemanticModels. - Tableless vocabularies (
Entity.members) are pruned away (L67–90): They intentionally have nosource:, so--prune-unbounddrops every vocabulary and edge pointing to it. - Derived
viachains (L99–114): Relationships with pruned intermediate hops stay behind with danglingviasteps.
| const edges = parts.length === 1 ? | ||
| parts[0] : | ||
| `SELECT DISTINCT src, dst\nFROM (\n${indent(parts.join('\nUNION ALL\n'))}\n)`; | ||
| const closure = [ |
There was a problem hiding this comment.
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.
Summary
This PR makes
kcmdcompile 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 bykcmd 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 profileandkcmd testcheck the model against the bound data, read-only.Core Capabilities Added
Multi-File OWL & SHACL Ingestion (
kcmd owl import,kcmd shacl import)owl:importsacross modular files; never fetches over the network.kcmd:abstractoverrides).--coveragewrites what each construct became (compiled, hinted, dropped);--prune-unboundkeeps only what a binding uses.Defined Classes as Membership Properties
owl:equivalentClassexpressions decidable on one row into SQL predicates and booleanis<Class>properties on the base node table.Derived Relationships & Property Chains
owl:propertyChainAxiomintovia:relationships, deployed asedge_<relationship>views of distinct key pairs.Controlled Vocabularies & Enumerations
kcmd pushgeneratesvocab_<entity>views and edge views that match recorded codes case-insensitively.In-Warehouse Constraint Validation (
kcmd validate --target bigquery)--publishrecords 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).Automatic Metric Graph Slicing & Composite Measures
kcmd:Metricindividuals as metrics.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.MEASUREper aggregate (<metric>__agg<N>), recombined withSAFE_DIVIDE(AGG(…), AGG(…)).<metric>__measurewhen the metric's name is also a column of its node table: BigQuery accepts such a measure, then fails every query on the graph.Units, Scale, Grain & History
unit/scaleand entitygrain/history, read from OWL unit annotations, carried as parseable description paragraphs in BigQuery and Knowledge Catalog, and read back by pull.BigQuery Data Profiler & Claim Verification (
kcmd profile,kcmd push --strict-profile)Business Glossary Publishing (
kcmd glossary push)Model Contract Testing (
kcmd test --target bigquery)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.Binding Discovery & Hydration (
kcmd bind)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.grain,resolve,normalize(proposed off until confirmed) andderive_from, plusconstraints: enforce(13).--accept-reviewconfirms;--from-catalogbinds the governed model pulled from Knowledge Catalog;--enforce-constraintswritesconstraints: enforceon every entity whose node view applies or reports a rule.<model>.profiles/<profile>.yamlandbind_report.md, which explains every decision.kcmd pushreads each bound entity through a generated node view: modeled columns only (plus_warningswhere constraints are enforced), one row per key, hydration applied. The graph, edges, measures and metric graphs all read the views.Lossless Catalog Round-Trip & Agent Grounding
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_contextreturns only description and schema, so push ends each description withRead 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 overGRAPH_EXPAND) on metrics, andContents:(every metric and entity) on the model anchor. Pull drops all five, since they are derived.@bigquerynode-view entry and graph-node entry, written when the entry group is in the data's region (entry links cannot cross regions).Consumption-Time Constraint Enforcement (
hydration.constraints: enforce,kcmd bind --enforce-constraints)on_violation: arejectrule about a value withholds it (NULL); arejectrule about the record (a required field, any rule on the key) excludes the row;warn/escalateserve the row as stored._warningscolumn (ARRAY<STRING>); the graph,GRAPH_EXPAND, GQL and measures read the served values.sh:inserves 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.sh:class/ OWLonly, functional properties) and class disjointness are reported, never applied; a rule no query can measure is skipped with a push warning.Constraints:paragraph on the entity's entry, betweenRelationships:andHydration:; pull drops it.Large File Copy Chunking with Protobuf Headroom
<filename>.part-<n>), sized with 2,048-byte headroom to guarantee that Dataplex server-sideprotobuf.Structserialization wire overhead never exceeds the 120 KiB limit.kcmd pull, parts are joined in order, restoring the original source file byte-for-byte.Testing & Validation
GoogleCloudPlatform/knowledge-catalogmain(commitaf3b85b), with all merge conflicts resolved and zero regressions.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.