Repository navigation
fluree ontology from dbt projects and Apache Ossie documents - #2215
Conversation
`fluree ontology from` reads two more semantic-layer sources:
- a dbt project, from one YAML file or the project's directory (every
.yml/.yaml under it; target/ and dbt_packages/ passed over). Semantic
models: primary entities are keys, foreign entities relations to the
semantic model keyed by that entity, dimensions properties (time
dimensions dates or date-times), measures that aggregate a column decimal
properties; counts, metrics and saved queries left out. Model properties
(schema.yml): column descriptions, accepted_values tests as enumerations,
relationships tests and foreign_key constraints as relations, primary_key
constraints (or unique + not_null on id) as keys. A semantic model built
on a model takes its descriptions and accepted values and stands for it.
- an Apache Ossie 0.2 document, YAML or JSON. A semantic model (datasets,
relationships) goes through the shared table model. An ontology is
written as RDF directly, keeping its IRIs: entity types as classes,
binary relationships as properties described by their verbalizations
("A flight uses an aircraft."), unary ones as booleans, wider ones as a
class with a property per role, enumerated value types as a class with
catalog records.
YAML and JSON documents are told apart by what they hold; --input-format
gains dbt and ossie. The summary says "enumeration" rather than
"enumerated column", since Ossie value types are enumerations too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmQVZNYkCgGd38GYUyX
A semantic model still stands for the model it's built on, but the base
model's columns it doesn't use now come along when they carry structure:
a relation (relationships test or foreign_key constraint) or accepted
values. Other leftover columns (audit columns, surrogate keys) stay out and
are counted on stderr. A column counts as used if a semantic model's
entity, dimension or measure names it, including identifiers in an expr,
so a measure's SQL doesn't bring back near-duplicates; a carried key that
a foreign entity already relates is dropped.
Also fixes references to a replaced model: a relationships test naming
ref('fct_orders') now resolves to the semantic model standing for it,
where it used to become a relation with no range.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmQVZNYkCgGd38GYUyX
bplatz
left a comment
There was a problem hiding this comment.
Approving. Please go through the inline comments before merging. Five of them give wrong output on ordinary dbt projects: the carried-relation drop, foreign entities without a range, versioned ref(), the sum/expr: 1 count measure, and YAML files skipped silently. None of these cases (versioned refs, model-level constraints, two relations to one class) has a test, which is how they got through.
| // a carried key that a foreign entity already makes the relation is dropped | ||
| for t in &mut tables { | ||
| let table = t.name.to_lowercase(); | ||
| let entity_targets: HashSet<String> = t | ||
| .columns | ||
| .iter() | ||
| .filter(|c| !carried.contains(&(table.clone(), c.name.to_lowercase()))) | ||
| .filter_map(|c| c.references.as_ref().map(|r| r.to_lowercase())) | ||
| .collect(); | ||
| t.columns.retain(|c| { | ||
| !carried.contains(&(table.clone(), c.name.to_lowercase())) | ||
| || c.references | ||
| .as_ref() | ||
| .is_none_or(|r| !entity_targets.contains(&r.to_lowercase())) | ||
| }); | ||
| } |
There was a problem hiding this comment.
This drops a carried relation whenever any foreign entity targets the same class, not only when the column is the entity's own. Say fct_flights carries origin_airport_id and destination_airport_id (both relationships → dim_airports) and has a foreign entity airport on origin_airport_id. Then destination_airport_id disappears, with nothing counted on stderr. The same happens to referrer_customer_id beside a customer entity. That's exactly the relation the semantic model didn't need, which the PR means to keep. Dropping only the carried column the entity is built from (its expr, else <entity>_id), or adding that column to used, would fix it.
There was a problem hiding this comment.
Good catch, the dedupe-by-target was too blunt. Fixed in 33e25f8: the target dedupe is gone, and a foreign entity's own column (its expr, else <entity>_id) counts as used, so only that column stays out. a_second_relation_to_the_same_class_is_kept is your origin/destination airport case.
| Some("foreign") => table.columns.push(Column { | ||
| name: entity.clone(), | ||
| description, | ||
| references: Some( | ||
| keyed_by | ||
| .get(&entity.to_lowercase()) | ||
| .cloned() | ||
| .unwrap_or_else(|| entity.clone()), | ||
| ), | ||
| ..Column::default() | ||
| }), |
There was a problem hiding this comment.
When no semantic model has this entity as its primary entity, the reference falls back to the entity name (store). That matches no table (stores), so the relation has no range even though class Store exists. This is the common case, since few projects have a semantic model for every dimension table. base_column already has the column's relationships/FK target, so falling back to base_column.references, then to a table whose class_label matches the entity's, would resolve it.
There was a problem hiding this comment.
Fixed in 33e25f8: an entity no semantic model is keyed by now resolves through its column's relationships/FK target, then to a table whose class label matches the entity's (store → stores), and only then falls back to the bare name. Covered by foreign_entities_find_their_table.
| fn ref_name(text: &str) -> String { | ||
| let t = text.trim(); | ||
| let inner = t | ||
| .strip_prefix("ref(") | ||
| .and_then(|r| r.strip_suffix(')')) | ||
| .unwrap_or(t); | ||
| // ref('package', 'model') names the model last | ||
| inner | ||
| .rsplit(',') | ||
| .next() | ||
| .unwrap_or(inner) | ||
| .trim() | ||
| .trim_matches(|c| c == '\'' || c == '"') | ||
| .to_string() | ||
| } |
There was a problem hiding this comment.
rsplit(',') takes the last argument, so ref('dim_customers', v=2) (or version=3) gives v=2. The base model then isn't matched: DimCustomer is emitted beside Customer, and relationships resolve to DimCustomer. source('raw','customers') gives customers'). Taking only the quoted positional arguments (ignoring v=/version=) and handling source() separately would fix both. Model versions: blocks aren't read either.
There was a problem hiding this comment.
Fixed in 33e25f8: ref_name takes the last quoted positional argument and ignores v=/version=, and source('raw','customers') gives the table. Model versions: are read too: the latest version's columns (by latest_version, else the highest v) apply over the model's own, include/exclude included. Covered by versioned_refs_sources_and_versions.
| let agg = text(m, "agg").unwrap_or_default(); | ||
| if !matches!( | ||
| agg.as_str(), | ||
| "sum" | "average" | "min" | "max" | "median" | "percentile" | ||
| ) { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
agg: sum, expr: 1 is MetricFlow's standard count idiom (jaffle-shop's order_count uses it). It passes this check, so it comes out as a decimal "order count" property. The tests use agg: count, which hides it. Skipping measures whose expr is a numeric literal would handle it.
There was a problem hiding this comment.
Fixed in 33e25f8: a measure whose expr is a numeric literal is treated as a count and left out with the others, and the summary now counts measures left out. counting_measures_are_left_out uses jaffle-shop's exact agg: sum, expr: 1 shape.
| fn text(v: &Value, key: &str) -> Option<String> { | ||
| v.get(key) | ||
| .and_then(Value::as_str) | ||
| .map(|s| s.split_whitespace().collect::<Vec<_>>().join(" ")) | ||
| .filter(|s| !s.is_empty()) | ||
| } |
There was a problem hiding this comment.
description: "{{ doc('fct_orders') }}" is copied into rdfs:comment verbatim. Doc blocks are common in larger projects. Resolving {% docs %} blocks from the .md files during the walk, or dropping and counting Jinja-valued descriptions, would avoid shipping template text as a description.
There was a problem hiding this comment.
Went with resolving them, in 33e25f8: when from reads the project directory it collects {% docs %} blocks from the .md files, and {{ doc('name') }} descriptions resolve to them. Anything left with Jinja in it is dropped and counted, never shipped as text. Covered by a unit test and a CLI test on a small project.
| for constraint in list(c, "constraints") { | ||
| match text(constraint, "type").as_deref() { | ||
| Some("primary_key") => table.primary_key.push(column_name.clone()), | ||
| Some("foreign_key") => { | ||
| if let Some(to) = text(constraint, "to") { | ||
| column.references = Some(ref_name(&to)); | ||
| } | ||
| } | ||
| _ => {} | ||
| } | ||
| } |
There was a problem hiding this comment.
Only column-level constraints are read. Model-level constraints: [{type: primary_key, columns: [...]}, {type: foreign_key, columns: [store_id], to: ref('stores')}] is ignored, and store_id is then counted under "left out (no relation or accepted values…)", which isn't true. The pre-1.9 expression: form of a foreign key isn't read either.
There was a problem hiding this comment.
Fixed in 33e25f8: model-level constraints are read (primary_key with columns, foreign_key with columns and to), and so is the pre-1.9 expression: form of a foreign key (stores (id)). model_level_and_pre_1_9_constraints covers both.
| } | ||
| } | ||
| replaced.insert(bt.name.to_lowercase(), name.clone()); | ||
| tables.retain(|t| !t.name.eq_ignore_ascii_case(&bt.name)); |
There was a problem hiding this comment.
dbt keeps models and semantic models in separate name spaces, but here they share one. A semantic model customers (on dim_customers) and an unrelated model customers mint the same Customer IRI, since the emitter's key is table:<name>. The class ends up with two rdfs:comments and the staging model's columns. This retain can also delete an earlier semantic model that shares the base model's name.
There was a problem hiding this comment.
Fixed in 33e25f8: models and semantic models are kept in separate lists, so a semantic model replacing its base only removes it from the models. A model that shares a semantic model's name (and isn't its base) is read as <name>_model, with a note. References from model tests resolve through that mapping. Covered by models_and_semantic_models_are_separate_name_spaces.
| stack.push(path); | ||
| } | ||
| } else if name.ends_with(".yml") || name.ends_with(".yaml") { | ||
| if let Ok(doc) = read_document(&path) { |
There was a problem hiding this comment.
A YAML file that fails to parse is skipped silently, so a whole schema.yml can vanish with exit 0. One real cause: serde-saphyr rejects duplicate keys, which dbt (PyYAML) accepts. A .yml that starts with { or [ also goes to the JSON parser and can be skipped here. I'd report skipped files on stderr, and set serde-saphyr's DuplicateKeyPolicy to last-wins to match dbt.
There was a problem hiding this comment.
Fixed in 33e25f8: files that fail to parse are named on stderr (<path>: skipped, not valid YAML (...)), duplicate keys are last-wins to match dbt, and a .yml/.yaml is always parsed as YAML even when it starts with {. There's a CLI test with a broken file in the project.
| let expand = |iri: &str| -> String { | ||
| match iri.split_once(':') { | ||
| Some((p, local)) if !local.starts_with("//") && prefixes.contains_key(p) => { | ||
| format!("{}{local}", prefixes[p]) | ||
| } | ||
| _ => iri.to_string(), | ||
| } | ||
| }; |
There was a problem hiding this comment.
An IRI with an undeclared prefix or no scheme is written as-is: iri: ex:Airport with no ex prefix becomes <ex:Airport>, and iri: "Gate Thing" becomes a relative IRI containing a space. An error or warning for an undeclared prefix, a missing scheme, or whitespace would catch these.
There was a problem hiding this comment.
Fixed in 33e25f8: an iri with an undeclared prefix (other than the usual schemes), no scheme, or whitespace is reported on stderr and the term is minted under --base instead. Covered by iris_that_arent_are_minted_and_noted.
| } | ||
| continue; | ||
| } | ||
| let parts: Vec<&str> = r.split(" OR ").collect(); |
There was a problem hiding this comment.
quoted() accepts anything that starts and ends with a quote, and OR is matched case-sensitively. So Code == 'A' or Code == 'B' gives one record labelled A' or Code == 'B (at Code/a-or-code-b). Rejecting inner quotes and splitting on OR/IN case-insensitively would fix it.
There was a problem hiding this comment.
Fixed in 33e25f8: OR/IN split case-insensitively, and a quoted value can't contain its own quote character, so your example gives A and B, and malformed ones give nothing. enumerations_in_any_case_and_no_stray_quotes covers both.
…w-ups
The merge brings the typed YAML reading (from_yaml), the emitter rule and
the Genie fixes up; the Snowflake arm reads through the typed reader.
Review follow-ups for dbt:
- A carried base-model relation is dropped only when it is the column a
foreign entity is built from (its expr, else <entity>_id), so
destination_airport_id beside an `airport` entity on origin_airport_id
stays.
- A foreign entity no semantic model is keyed by resolves through its
column's relationships test, then to the model whose name reads as the
entity's (`store` -> `stores`), instead of a relation with no range.
- `ref('m', v=2)` and `source('raw', 't')` name their model/table; a
versioned model takes its latest version's columns (include/exclude).
- `agg: sum, expr: 1` is a count, and left out with the other counts
(counted in the notes).
- `{{ doc('name') }}` descriptions resolve from the project's `{% docs %}`
blocks (its .md files); any Jinja left is dropped and counted, never
kept as text.
- Model-level constraints (primary_key, foreign_key with `to`) and the
pre-1.9 `expression:` form of a foreign key are read.
- Models and semantic models are separate name spaces: a model sharing a
semantic model's name (not its base) is read as `<name>_model`, and a
replaced model is removed from the models only.
- dbt YAML is read into typed fields (values like NO and 007 kept as
written); duplicate keys keep the last value; a .yml is always parsed as
YAML; files that fail to parse are named in the summary, not skipped.
Review follow-ups for Ossie:
- YAML documents go through typed fields too (`document`).
- An `iri` with an undeclared prefix, no scheme or whitespace is reported
and the term minted instead of written as a broken IRI.
- Enumerations split on OR/IN in any case and reject values with a stray
quote inside.
- A JSON-LD document is never read as an Ossie semantic model or ontology.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmQVZNYkCgGd38GYUyX
|
Thanks @bplatz! All ten are fixed in 33e25f8 and replied to inline. You're right that the missing tests are how these got through, so each case you named has one now: |
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmQLwTu67J9hjS5nwrh
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmQLwTu67J9hjS5nwrh
Brings #2247, #2232, #2246, #2248, #2245, #2230, #2205, #2231, #2255, #2219, #2209, #2207, #2190, #2216, #2186, #2215, #2213, #2184, #2210, #2206, #2198, #2187, #2183, #2200, #2193, #2199, #2196 and #2145 into next. Resolutions: - Novelty: main's fact-state trim (a cutoff plus a bounded sweep) and the dictionary's coverage watermark sit on next's graph slots and per-graph OrdMaps. A commit's reification links count toward coverage. Planner stats from segment sums decline under annotations, whose link deltas only the walk counts, and otherwise carry the indexed link counts. - Stats-view identity: the index root's id reaches the snapshot through next's root decoder (`decode` takes the id, as `take_snapshot_metadata` does). `LedgerState::load_record` has a decoding-root form beside `load_decoding_root`. - Transact: #2184's parallel-relationship check runs in next's link cascade, counting the `rdf:reifies` links on the retracted edge that the transaction does not retract itself. Main's bundle `edge_reifiers` is dropped, and `subjects_with_prior_rows` and `enforce_single_target_reifiers` stay deleted. The upsert pre-check takes main's dictionary probe and bounded seek. - Query: geo search resolves the graph's POST tree once at open (pooled graphs keep their filter), an empty manifest when there is none. `branch_or_none` reads the dedicated branch, and the batched joins keep next's pooled lanes. The stats-view key hashes the root id. - Indexer: `apply_dict_novelty` and `compact_forward_streams` take the cycle's compaction budget, so the term dictionary keeps its reserved share. `Prefetched` holds `ContentBytes`. `relocalize_sorted_commit` rewrites next's 20-byte types records. - Disk cache: main's in-flight write registration, with an empty entry still read as crash debris that a write replaces. The process-wide eviction walk stays removed. - Graph import (#2232): fenced CAS and publishes, the seed carries the record's namespace and fence, 32-bit graph ids and next's loaders. An import into a graph of an existing ledger refuses triple terms and edge annotations: the splice merges no triple-term dictionary yet. - Iceberg: `create_iceberg_graph_source` goes with main (a source needs a mapping); the R2RML path keeps next's `model_instance`. - CLI: main's shared import flags without the leaflet flags; `graph import` routes through next's process-wide server routing, and `upload_source_import` serves next's `Destination`. Doc sources read a ledger through the command's open instance. - Tests: sibling ledger ids become distinct names, `genesis_ledger` is awaited, Cypher state dumps include each relationship's `rdf:reifies` link, and the graph-import arena test checks the refusal instead.
Stacked on #2213 (base
feat/ontology-from-semantic-layer, so the diff is just the fourth commit). This rounds out the semantic-layer sources forfluree ontology fromwith dbt and Apache Ossie, which were the last two converters in the plan.dbt.
fluree ontology from ./my_dbt_projectreads every.yml/.yamlunder the directory (skippingtarget/,dbt_packages/,logs/and dot-dirs), or a single file, and takes both kinds of dbt YAML:primary/unique/naturalentity is its key; aforeignentity is a relation to the semantic model whose primary entity has that name (MetricFlow joins on entity names, socustomerrelates to the model keyed bycustomer), labelled with the entity name. Dimensions become properties (atimedimension is a date, or a date-time when its granularity is below a day). Measures that aggregate a column's values (sum,average,min,max,median,percentile) become decimal properties; counts are about rows rather than things, so they're left out with metrics and saved queries.schema.yml). Column descriptions are copied, anaccepted_valuestest makes a column enumerated (so it becomes a class with records, as everywhere else), arelationshipstest orforeign_keyconstraint makes it a relation, and aprimary_keyconstraint, orunique+not_nullonid/<model>_id, makes it the key. Both the pre-1.10 test shape and the newerarguments:shape are read.A semantic model built on a model (
model: ref('fct_orders')) stands for it: it takes the model's column descriptions and accepted values for the columns it uses, and the model isn't emitted a second time. Of the base model's other columns, the ones that carry structure the semantic model lacks (a relation from arelationshipstest orforeign_keyconstraint, oraccepted_values) come along; the rest (audit columns, surrogate keys, columns only a measure'sexpruses) are left out and counted on stderr. A column counts as used if an entity, dimension or measure names it, including any identifier inside anexpr, so a measure likecase when is_gift then amount_cents / 100 enddoesn't bringis_gift/amount_centsback as near-duplicates, and a carried key that a foreign entity already relates is dropped rather than doubled.I had this as a straight "semantic model replaces its base model" at first and wasn't sure about it, so I had two reviewers argue it out, one for replacing and one for a union with the base model. They converged on this middle rule: semantic models are curated for metrics, so a relation they didn't need (a
store_idwith arelationshipstest) is still something documents talk about, but carrying every documented column would bring back most of a wide mart, which is the breadth that costs an extraction model accuracy. They also both caught a real bug, now fixed: arelationshipstest naming a replaced model (ref('fct_orders')) used to come out as a relation with no range, and it now resolves to the semantic model standing for it.Apache Ossie (0.2.0.dev0, the spec in apache/ossie at
core-spec/andontology/), YAML or JSON, read by which layer the document is:datasets,relationships,metrics) is a data dictionary and goes through the same table model as a Snowflake view: fields'description,datatypeandai_contextsynonyms are copied, each relationship is a foreign key from itsfrom_columnsto thetodataset, and metrics are left out;ontology:a list of concepts) is already conceptual, so it's written to RDF directly and keeps the IRIs it declares (iri: schema:Airport, expanded with itsprefixes).EntityTypeconcepts become classes with theirextendsas parents; a binary relationship becomes a property from its concept to the role's concept, or to the XSD datatype itsValueTyperesolves to throughextends; a unary relationship ('{Flight} was diverted') becomes a boolean property; a relationship with three or more roles becomes a class with a property per role. Each relationship is described by itsdescription, or else by its first verbalization rendered as a sentence ('{Flight} uses {Aircraft}'→ "A flight uses an aircraft."), which is exactly the kind of description that helps an extraction model most. A value type whoserequiresenumerates its values (CancelationCode == 'A' OR CancelationCode == 'B') becomes a class with a catalog record per value.derived_by, the otherrequires,identify_byand mapping documents are logic and bindings, not things documents say, so they're left out.Against the spec's own
examples/flights.ontology.yamlthat gives 15 classes, 62 properties and the cancelation codes as 4 records (about 3.5K tokens), andexamples/flights.semantic_model.yamlgives 6 classes and 43 properties; both come back clean fromfluree ontology check. The tests use small synthetic documents rather than copies of those files.Smaller things: YAML and JSON are now told apart by content (Ossie
datasets:/ontology:, dbtsemantic_models:/models:, Snowflaketables:; Genie and Ossie JSON before falling back to JSON-LD),--input-formatgainsdbtandossie, and the stderr summary says "enumeration" rather than "enumerated column", since an Ossie value type is one too. The YAML/JSON parsing lives influree_db_ontology::convert::parse_documentso the CLI doesn't need its own YAML dependency.cargo test -p fluree-db-ontology -p fluree-db-cliandcargo clippy -p fluree-db-ontology -p fluree-db-cli --all-targets --no-depsare clean locally; full CI will run once the stack is rebased onto main.🤖 Generated with Claude Code
https://claude.ai/code/session_016CjYmQVZNYkCgGd38GYUyX