You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ossie.apache.org by "jbonofre (via GitHub)" <gi...@apache.org> on 2026/10/01 13:35:04 UTC

Re: [PR] Feat(ontology): add Ossie -> RelationalAI converter with formula parsing and reasoner [ossie]

jbonofre commented on code in PR #412:
URL: https://github.com/apache/ossie/pull/412#discussion_r4155734182


##########
converters/ontology/src/ossie_ontology/expr/formula/parser.py:
##########
@@ -0,0 +1,335 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Formula parser. The grammar, precedence table, and AST."""
+
+from __future__ import annotations
+
+import ply.yacc as yacc
+
+from ossie_ontology.model import OntologyComponent, SemanticModel, Concept, Dataset
+from ossie_ontology.expr.model import Expression, BinOp
+from ossie_ontology.expr.formula.model import (
+    Atom,
+    VarHandle,
+    LiteralHandle,
+    Negation,
+    Conjunction,
+    Disjunction,
+    Exists,
+    WhereExpr,
+    AggregationMethod,
+    AggExpr,
+    DotJoinHandle,
+    FactRef,
+    ConceptRefHandle,
+    RelationshipRefHandle,
+    DatasetRefHandle,
+    DatasetFieldHandle,
+)
+from ossie_ontology.expr.formula.lexer import FormulaLexer
+from ossie_ontology.expr.common import AggMethod
+
+
+class FormulaParser:
+    """Formula parser. Constructed against a single `Ontology` (where
+    concepts and relationships live). For mapping formulas, callers pass an
+    additional `SemanticModel` so dataset and field references resolve."""
+
+    _HEAD_VARS_PARAM = "head_vars"
+    _MAPPING_DATASET_PARAM = "mapping_dataset"
+
+    def __init__(self, ontology: OntologyComponent, semantic_model: SemanticModel | None = None):
+        # `write_tables=False, debug=False`: ply's defaults write `parsetab.py`
+        # (~12 KB) and `parser.out` (~85 KB) next to this module, which for an
+        # installed package means into site-packages on first parse — it fails
+        # on a read-only install and dirties container layers. Rebuilding the
+        # LALR tables costs ~4 ms, so there is nothing to cache.
+        self.parser = yacc.yacc(module=self, debug=False, write_tables=False)
+        self.lexer = FormulaLexer()
+        self._ontology = ontology
+        self._semantic_model = semantic_model
+
+    def with_semantic_model(self, semantic_model: SemanticModel) -> FormulaParser:
+        """Returns a parser bound to the same ontology and the given logical
+        model. Useful when iterating over multiple OntologyMappings."""
+        return FormulaParser(self._ontology, semantic_model)
+
+    tokens = FormulaLexer.tokens
+
+    precedence = (
+        ("left", "OR"),
+        ("left", "AND"),
+        ("right", "NOT"),
+        ("nonassoc", "EQUALS", "NOTEQUALS", "GREATER", "GREATEREQ", "LESS", "LESSEQ"),
+        ("left", "LPAREN"),
+        ("left", "DOT"),
+        ("left", "PLUS", "MINUS"),
+        ("left", "TIMES", "DIVIDE"),
+    )
+
+    # ----------------- grammar ------------------------------------------
+
+    def p_goal(self, p):
+        "goal : formula"
+        p[0] = p[1]
+
+    def p_formula_expr(self, p):
+        "formula : expr"
+        p[0] = p[1]
+
+    def p_formula_comp_expr(self, p):
+        "formula : expr comp_op expr"
+        op = BinOp.from_value(p[2])
+        p[0] = Expression(op, p[1], p[3])
+
+    def p_formula_and(self, p):
+        "formula : formula AND formula"
+        p[0] = Conjunction(p[1], p[3])
+
+    def p_formula_or(self, p):
+        "formula : formula OR formula"
+        p[0] = Disjunction(p[1], p[3])
+
+    def p_formula_exists(self, p):
+        "formula : EXISTS LPAREN formula RPAREN"
+        p[0] = Exists(p[3])
+
+    def p_formula_not(self, p):
+        "formula : NOT formula"
+        p[0] = Negation(p[2])
+
+    def p_expr_node_expr(self, p):
+        "expr : node_expr"
+        p[0] = p[1]
+
+    def p_expr_minus_expr(self, p):
+        "expr : MINUS expr %prec NOT"
+        p[0] = Expression(BinOp.MINUS, LiteralHandle(0), p[2])
+
+    def p_expr_agg(self, p):
+        "expr : agg_expr"
+        p[0] = p[1]
+
+    def p_expr_arith(self, p):
+        """
+        expr : expr PLUS expr
+             | expr MINUS expr
+             | expr TIMES expr
+             | expr DIVIDE expr
+        """
+        op = BinOp.from_value(p[2])
+        p[0] = Expression(op, p[1], p[3])
+
+    def p_expr_where(self, p):
+        "expr : expr WHERE LPAREN formula RPAREN"
+        p[0] = WhereExpr(p[1], p[4])
+
+    def p_expr_parenthesized(self, p):
+        "expr : LPAREN expr RPAREN"
+        p[0] = p[2]
+
+    def p_node_expr_literal(self, p):
+        "node_expr : literal"
+        p[0] = p[1]
+
+    def p_node_expr_variable(self, p):
+        "node_expr : ID"
+        mapping_dataset = p.parser.params.get(self._MAPPING_DATASET_PARAM)
+        if mapping_dataset is not None:
+            field = mapping_dataset.field(p[1])
+            if field is not None:
+                p[0] = DatasetFieldHandle(mapping_dataset, field)
+                return
+            handle = self._to_identifier_ref(p[1])
+            if isinstance(handle, VarHandle):
+                raise ValueError(
+                    f"'{p[1]}' is not a field in dataset '{mapping_dataset.name()}' "

Review Comment:
   Same issue: `mapping_dataset` is a `Dataset` (it has `.field()`), and `Dataset.name` is a property, so `mapping_dataset.name()` raises `TypeError`. A typo column name then produces an opaque `TypeError` instead of the intended "'x' is not a field in dataset ..." message. A test for the unknown-column case would catch it.



##########
converters/ontology/src/ossie_ontology/expr/formula/visitor/converter.py:
##########
@@ -0,0 +1,394 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Formula AST -> PyRel rules.
+
+The one module under `ossie_ontology.expr` that imports `relationalai`. It sits
+here rather than with the converter because it is a `GenericFormulaConverter`
+visitor, alongside `collector` and `unbound` — the difference is only what it
+emits. Nothing in the `expr` package imports it, so parsing and validating
+formulas still works with the SDK absent; it is reached solely from
+`ossie_ontology.converter.ossie_to_relationalai`, which the optional
+`relationalai` extra installs.
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from relationalai.util.naming import NameCache
+import relationalai.semantics as pyrel
+from relationalai.semantics import not_
+from relationalai.semantics.frontend.base import Ref, Concept as RAIConcept, CoreConcepts, Chain, \
+    Relationship as RAIRelationship
+
+from ossie_ontology.reasoner import OntologyReasoner
+from ossie_ontology.vendor.relationalai.mappings import ValueMapping
+from ossie_ontology.vendor.relationalai.ontology import OntologyModel
+from ossie_ontology.expr.formula.model import (
+    AggregationMethod,
+    Conjunction,
+    Disjunction,
+    WhereExpr,
+    DatasetFieldHandle,
+    DatasetRefHandle,
+    DotJoinHandle,
+    VarHandle,
+    ConceptRefHandle,
+    RelationshipRefHandle,
+    FactRef,
+    LiteralHandle,
+    Negation,
+    AggExpr,
+    Formula
+)
+from ossie_ontology.expr.formula.visitor import GenericFormulaConverter
+from ossie_ontology.expr import Node
+from ossie_ontology.expr.common import AggMethod as ModelAggMethod
+from ossie_ontology.expr.model import Expression, BinOp
+from ossie_ontology.model import OntologyComponent, Concept, Relationship, Role
+
+# The Ossie aggregation vocabulary, resolved to the pyrel builtins that implement
+# it. This is the only place the two vocabularies meet: `AggMethod` itself is
+# vendor-neutral and lives in `ossie_ontology.expr.common` alongside the grammar
+# that produces it, so nothing in the Ossie layer has to know pyrel exists.
+SEMANTIC_MODEL_TO_PYREL_AGG = {
+    ModelAggMethod.SUM: pyrel.sum,
+    ModelAggMethod.MIN: pyrel.min,
+    ModelAggMethod.MAX: pyrel.max,
+    ModelAggMethod.AVG: pyrel.avg,
+    ModelAggMethod.COUNT: pyrel.count,
+}
+
+class FormulaConverter(GenericFormulaConverter):
+    """FormulaConverter — generates PyRel rules from a Formula."""
+
+    def __init__(
+        self,
+        oc: OntologyComponent,
+        ontology: OntologyModel,
+        reasoner: OntologyReasoner,
+        var_name_cache: NameCache,
+        formula: Formula,
+    ):
+        self._oc = oc
+        self._ontology = ontology
+        self._reasoner = reasoner
+        self._formula = formula
+        self._target_var = formula.formula_target()
+        self._var_name_cache = var_name_cache
+        self._var_refs: dict = {}
+        self._body_statements: list = []
+        var_handles = dict(self._formula.expr_info().var_handles)
+        for var, c in var_handles.items():
+            if c is None:
+                continue
+            pyrel_c = self._ontology.lookup_concept(c.name)
+            assert pyrel_c is not None, f"Concept '{c.name}' not found in ontology"
+            # Name the ref after the formula's own variable. `ref()` with no
+            # name falls back to one derived from the concept, so every
+            # Decimal-typed variable in a formula came out as `number` —
+            # distinct Vars sharing one name. That is invisible while the model
+            # only ever gets compiled (Vars are identified by id), but anything
+            # that renders the metamodel back to source collapses them: the
+            # `net_revenue == extended_price * (1 - discount)` formula
+            # decompiled to `Decimal.number == Decimal.number * (1 - Decimal.number)`.
+            # `_var_name` is NameCache-backed, so these stay unique across formulas.
+            var_name = self._var_name(var)
+            self._var_refs[var_name] = pyrel_c.ref(var_name)
+        self._ontology.base_model().define(self._head()).where(*self._body())
+
+    def _head(self):
+        formula_parent = self._formula.parent
+        if isinstance(formula_parent, Concept):
+            pyrel_concept = self._ontology.lookup_concept(formula_parent.name)
+            assert pyrel_concept is not None, f"Concept '{formula_parent.name}' not found in ontology"
+            if formula_parent.extends:
+                subc = self._ontology.lookup_concept(formula_parent.extends[0].name)
+                return pyrel_concept(subc)
+            else:
+                identifiers = {}
+                # `ref_scheme` returns None for a concept with no identifier
+                # of its own and no supertype to inherit one from — which is
+                # exactly this branch, since `extends` was falsy above. The old
+                # guard re-tested `isinstance(..., Concept)`, already true here,
+                # so the None case reached `for ... in None`.
+                for idt in (self._reasoner.ref_scheme(formula_parent) or ()):
+                    identifiers[idt.name] = self._role_var(idt.last_role)
+                return pyrel_concept.new(**identifiers)
+        else:
+            if isinstance(formula_parent, Relationship):
+                relationship = formula_parent
+                concept = relationship.first_role.player
+            else:
+                assert isinstance(formula_parent, tuple)
+                concept, relationship = formula_parent
+                assert (
+                    self._reasoner.in_subtype_closure(concept, relationship.first_role.player)
+                    or relationship.first_role.player is concept
+                )
+            pyrel_concept = self._ontology.lookup_concept(concept.name)
+            assert pyrel_concept is not None, f"Concept '{concept.name}' not found in ontology"
+            if self._reasoner.is_identifier_relationship(relationship):
+                identifiers = {relationship.name: self._role_var(relationship.last_role)}
+                return pyrel_concept.new(**identifiers)
+            else:
+                args = [self._role_var(r) for r in relationship.roles]
+                return self._pyrel_relationship(relationship, pyrel_concept)(*args)
+
+    def _body(self) -> list:
+        for e in self._formula.expr():
+            result = e.accept(self)
+            if result is not None:
+                self._body_statements.append(result)
+        return self._body_statements
+
+    def visit_varhandle(self, node: VarHandle, parent: Optional[Node]):
+        return self._var_refs[self._var_name(node)]
+
+    def visit_literalhandle(self, node: LiteralHandle, parent: Optional[Node]):
+        return self._target_var[0].accept(self) == node._val if self._target_var and not parent else node._val
+
+    def visit_conceptrefhandle(self, node: ConceptRefHandle, parent: Optional[Node]):
+        return self._ontology.lookup_concept(str(node._concept))
+
+    def visit_relationshiprefhandle(self, node: RelationshipRefHandle, parent: Optional[Node]):
+        rel = node._relationship
+        if self._target_var and parent and isinstance(parent, Expression):
+            rel_args = []
+            for r in rel.roles[:-1]:
+                rel_args.append(self._role_var(r))
+            pyrel_last = self._ontology.lookup_concept(rel.last_role.player.name)
+            assert pyrel_last is not None
+            # Named for the same reason as the var refs above: an unnamed ref
+            # inherits a concept-derived name, so several of these in one
+            # formula become indistinguishable once rendered back to source.
+            var_ref = pyrel_last.ref(self._var_name(f"{rel.name}_{rel.last_role.player.name}"))
+            rel_args.append(var_ref)
+            self._body_statements.append(self._pyrel_relationship(rel)(*rel_args))
+            return var_ref
+        if rel.container:
+            pyrel_concept = self._ontology.lookup_concept(rel.container.name)
+            assert pyrel_concept is not None
+            return pyrel_concept.__getattr__(rel.name)
+        else:
+            return self._ontology.lookup_relationship(rel.name)
+
+    def visit_datasetrefhandle(self, node: DatasetRefHandle, parent: Optional[Node]):
+        return self._ontology.lookup_table(node.name())
+
+    def visit_datasetfieldhandle(self, node: DatasetFieldHandle, parent: Optional[Node]):
+        pass
+
+    def visit_factref(self, node: FactRef, parent: Optional[Node]):
+        handle = node._handle.accept(self, node)
+        args = [arg.accept(self, node) for arg in node._args]
+        return handle(*args)
+
+    def visit_expression(self, node: Expression, parent: Optional[Node]):
+        left, right = node._args
+        pyrel_left = left.accept(self, node)
+        pyrel_right = right.accept(self, node)
+        pyrel_expr = self._apply_operator(pyrel_left, node._op, pyrel_right)
+        if (parent is not None and isinstance(parent, Expression)
+                and parent._op in BinOp.multiplicative_ops
+                and node._op not in BinOp.multiplicative_ops):
+            pyrel_expr = (pyrel_expr)
+        if not self._target_var or parent:
+            return pyrel_expr
+        target = self._target_var[0].accept(self)
+        if target is pyrel_left or target is pyrel_right:
+            return pyrel_expr
+        return target == pyrel_expr
+
+    def visit_aggexpr(self, node: AggExpr, parent: Optional[Node]):
+        pyrel_vars = [var.accept(self, node) for var in node._var_seq]
+        pyrel_body = self._flatten_formula(node._formula, node) if node._formula is not None else []
+        pyrel_per = [var.accept(self, node) for var in node._group_by]
+        pyrel_agg = SEMANTIC_MODEL_TO_PYREL_AGG[ModelAggMethod(node._method._val)]
+        pyrel_expr = pyrel_agg(*pyrel_vars)
+        if pyrel_body:
+            pyrel_expr = pyrel_expr.where(*pyrel_body)
+        if pyrel_per:
+            pyrel_expr = pyrel_expr.per(*pyrel_per)
+        return self._target_var[0].accept(self) == pyrel_expr if self._target_var and not parent else pyrel_expr
+
+    def visit_conjunction(self, node: Conjunction, parent: Optional[Node]):
+        left_result = node.left().accept(self, node)
+        right_result = node.right().accept(self, node)
+        if left_result is not None:
+            self._body_statements.append(left_result)
+        if right_result is not None:
+            self._body_statements.append(right_result)
+
+    def visit_disjunction(self, node: Disjunction, parent: Optional[Node]):
+        raise NotImplementedError("Disjunction (OR) in formula body is not yet supported")
+
+    def visit_whereexpr(self, node: WhereExpr, parent: Optional[Node]):
+        raise NotImplementedError("WHERE expression is not yet supported")
+
+    def visit_negation(self, node: Negation, parent: Optional[Node]):
+        return not_(node._arg.accept(self, node))
+
+    def visit_dotjoinhandle(self, node: DotJoinHandle, parent: Optional[Node]):
+        handle1 = node._handle1.accept(self)
+        if isinstance(node._handle2, DatasetFieldHandle) and self._target_var and not parent:
+            return handle1.__getattr__(str(node._handle2))(self._target_var[0].accept(self))
+        return handle1.__getattr__(str(node._handle2))
+
+    def visit_aggregationmethod(self, node: AggregationMethod, parent: Optional[Node]):
+        pass
+
+    def visit_binop(self, node: BinOp, parent: Optional[Node]):
+        pass
+
+    def _flatten_formula(self, formula_node, parent) -> list:
+        if isinstance(formula_node, Conjunction):
+            return (self._flatten_formula(formula_node.left(), parent)
+                    + self._flatten_formula(formula_node.right(), parent))
+        result = formula_node.accept(self, parent)
+        return [result] if result is not None else []
+
+    def _role_var(self, role: Role) -> RAIConcept | Ref:
+        role_name = role.name 
+        var_key = self._var_name(role_name)
+        if var_key in self._var_refs:
+            return self._var_refs[var_key]
+        pyrel_c = self._ontology.lookup_concept(role_name)
+        assert pyrel_c is not None, f"Concept '{role_name}' not found in ontology"
+        return pyrel_c
+
+    def _var_name(self, var: str | VarHandle) -> str:
+        name = var.name() if isinstance(var, VarHandle) else var
+        return self._var_name_cache.get_name(f"{self._formula.raw_expr}_{name}", name)
+
+    def _pyrel_relationship(self, relationship: Relationship, container: Optional[RAIConcept] = None) -> RAIRelationship | Chain:
+        if container is None:
+            concept = self._ontology.lookup_concept(relationship.first_role.player.name)
+            assert concept is not None, f"Concept '{relationship.first_role.player.name}' not found in ontology"
+        else:
+            concept = container
+        if concept._name in CoreConcepts:
+            rel = self._ontology.lookup_relationship(relationship.name)
+            assert rel is not None, f"Relationship '{relationship.name}' not found in ontology"
+            return rel
+        else:
+            return concept.__getattr__(relationship.name)
+
+class MappingFormulaConverter(GenericFormulaConverter):
+    """Converts a mapping formula AST to a PyRel expression.
+
+    Tables are resolved dynamically from the DatasetField.dataset back-reference rather than requiring a fixed table
+    to be passed in. This allows mapping expressions that span multiple datasets.
+
+    The result of the conversion is available via the `result` attribute after construction.
+    """
+
+    def __init__(self, ontology: OntologyModel, formula: Formula, concept=None):
+        self._ontology = ontology
+        self._concept = concept
+        expr = formula.expr()[0]
+        if isinstance(expr, WhereExpr):
+            self.result = expr.accept(self, None)
+        else:
+            raw = expr.accept(self, None)
+            if self._concept is not None:
+                raw = self._concept(raw)
+            self.result = ValueMapping(raw)
+
+    def visit_datasetfieldhandle(self, node: DatasetFieldHandle, parent):
+        field = node._field
+        dataset = getattr(field, 'dataset', None)
+        if dataset is not None:
+            table = self._ontology.lookup_table(dataset.name())

Review Comment:
   `dataset.name()` is a `@property` (`model.py`), so `dataset.name() ` calls a `str` and raises `TypeError`. Every mapping formula that references a bare dataset column (e.g. `price * qty`) goes through `visit_datasetfieldhandle` and will fail here. `visit_dotjoinhandle` a few lines down uses `dataset.name` without parentheses, so the two visitors disagree. The assert message on line 318 has the same bug.
   
   Please drop the parentheses on both lines, and add a test that converts a formula with a bare column reference.



##########
converters/ontology/src/ossie_ontology/converter/ossie_to_relationalai/converter.py:
##########
@@ -0,0 +1,569 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Ossie -> RelationalAI: an `OssieOntology` becomes a PyRel `OntologyModel`.
+
+Together with `ossie_ontology.expr.formula.visitor.converter` — the formula
+emitter, which stays with its sibling visitors — this package is the only part
+of `ossie_ontology` that imports `relationalai`. Neither is reachable from
+`ossie_ontology/__init__.py`, which is what lets the SDK be an optional extra
+rather than a hard dependency. Install it with:
+
+    pip install "apache-ossie-ontology[relationalai]"
+"""
+from __future__ import annotations
+
+import warnings
+from typing import Any, Callable
+
+from relationalai.util.naming import NameCache
+from ossie_ontology.vendor.relationalai.mappings import EntityMapping
+from ossie_ontology.vendor.relationalai.ontology import OntologyModel
+from ossie_ontology.expr.formula.model import Formula
+from ossie_ontology.expr.formula.visitor.converter import FormulaConverter, MappingFormulaConverter
+from ossie_ontology.reasoner import OntologyReasoner
+from ossie_ontology.model import (
+    Concept,
+    Dataset,
+    DatasetField,
+    LinkMapping,
+    ObjectMapping,
+    SemanticModel,
+    OntologyComponent,
+    OntologyMapping,
+    ReferentMapping,
+    Relationship,
+    OssieOntology,
+)
+import relationalai.semantics as pyrel
+from relationalai.semantics import Concept as RAIConcept
+
+# How a dataset becomes something the model can read. Takes the model being
+# built, the dataset as the Ossie spec declares it, and the column types derived
+# from that spec; returns whatever pyrel construct should stand in for it.
+#
+# The default resolves the dataset's `source` to a warehouse table. Substituting
+# a provider is how a caller reads from somewhere else — from inline CSV, for
+# example, so a test corpus needs no warehouse — without this converter having
+# to know that any such alternative exists.
+TableProvider = Callable[["OntologyModel", Dataset, dict[str, RAIConcept]], Any]
+
+
+def warehouse_table(ontology: "OntologyModel", dataset: Dataset,
+                    schema: dict[str, RAIConcept]) -> Any:
+    """Resolve a dataset to the warehouse table its `source` names.
+
+    The schema is deliberately *not* passed on: pyrel reads the real columns
+    from the table instead. That costs a connection when the model is compiled,
+    but it is the only way to get the column identifiers right — Snowflake folds
+    an unquoted name to upper case, so declaring the spec's `airport_code`
+    yields `AIRPORT_CODE`, which does not address a column created as
+    `"airport_code"`. Only the table itself knows which it is.
+
+    Use :func:`declared_table` where the spec's field names are known to match
+    and a connection is unwanted.
+    """
+    return ontology.base_model().Table(dataset.source)
+
+
+def declared_table(ontology: "OntologyModel", dataset: Dataset,
+                   schema: dict[str, RAIConcept]) -> Any:
+    """Resolve a dataset to its table, declaring the columns from the spec.
+
+    Nothing is read from the warehouse, so conversion and compilation work with
+    no connection — which is what makes an offline test suite possible. The
+    tradeoff is the one :func:`warehouse_table` avoids: the declared identifiers
+    have to match how the table was actually created.
+    """
+    return ontology.base_model().Table(dataset.source, schema=schema)
+
+
+class OssieToRelationalAIConverter:
+
+    @staticmethod
+    def convert(
+        model: OssieOntology,
+        reasoner: OntologyReasoner | None = None,
+        model_cls: type[OntologyModel] = OntologyModel,
+        table_provider: TableProvider = warehouse_table,
+    ) -> OntologyModel:
+        """Convert an OssieOntology into a PyRel model.
+
+        `model_cls` decides what the result is an instance of. The conversion
+        itself only ever touches the plain `OntologyModel` surface, so the
+        default is that class; pass `MeasureOntologyModel` when the caller goes
+        on to ask dimensional measure queries of the result.
+        """
+        ontology = model_cls(model.name)
+        properties_index: dict[str, pyrel.Relationship] = {}
+
+        oc = model.ontology
+        if reasoner is None:
+            reasoner = OntologyReasoner()
+            oc.register(reasoner)
+
+        OssieToRelationalAIConverter._convert_concepts(oc, ontology)
+        OssieToRelationalAIConverter._convert_relationships(oc, ontology, properties_index, reasoner)
+        OssieToRelationalAIConverter._identify_concepts(oc, ontology, properties_index)
+
+        for om in model.ontology_mappings:
+            OssieToRelationalAIConverter._convert_datasets(
+                om.semantic_model, ontology, table_provider
+            )
+
+        # Shared across every ontology_mapping, so a binding declared in two of
+        # them collapses to one creation rule. Insurance rather than a live
+        # saving: every scenario in the corpus has a single ontology_mapping.
+        entity_bindings: dict = {}
+        for om in model.ontology_mappings:
+            OssieToRelationalAIConverter._convert_mappings(
+                om, ontology, properties_index, reasoner, entity_bindings
+            )
+
+        OssieToRelationalAIConverter._convert_formulas(oc, ontology, reasoner)
+
+        return ontology
+
+    @staticmethod
+    def _concept(ontology: OntologyModel, name: str) -> RAIConcept:
+        """The pyrel concept for an Ossie concept name.
+
+        Every concept is created by `_convert_concepts` before any mapping or
+        reading is converted, so a miss means those passes disagree about the
+        ontology. Failing here names the concept; letting the None through
+        surfaces later as an opaque `NoneType has no attribute` from inside
+        pyrel, or binds a null silently.
+        """
+        concept = ontology.lookup_concept(name)
+        assert concept is not None, f"Concept '{name}' not found in the converted ontology"
+        return concept
+
+    # ------------------------------------------------------------------
+    # Datasets
+    # ------------------------------------------------------------------
+
+    @staticmethod
+    def _convert_datasets(sm: SemanticModel, ontology: OntologyModel, table_provider: TableProvider) -> None:
+        for dataset in sm.datasets:
+            schema = OssieToRelationalAIConverter._pyrel_schema(dataset, ontology)
+            ontology.add_table(dataset.name, table_provider(ontology, dataset, schema))
+
+    @staticmethod
+    def _pyrel_schema(dataset: Dataset, ontology: OntologyModel) -> dict:
+        """Column types for *dataset*, taken from the Ossie spec that declares it.
+
+        Handed to the table provider so it can declare the columns up front,
+        which is what keeps the conversion from needing a live warehouse.
+        """
+        schema = {}
+        for fl in dataset.fields:
+            if fl.type is not None:
+                concept = OssieToRelationalAIConverter._concept(ontology, fl.type.name)
+                schema[fl.name] = ontology.get_topmost_parent(concept)
+            else:
+                schema[fl.name] = ontology.lookup_concept("String")
+        return schema
+
+    # ------------------------------------------------------------------
+    # Concepts
+    # ------------------------------------------------------------------
+
+    @staticmethod
+    def _convert_concepts(oc: OntologyComponent, ontology: OntologyModel) -> None:
+        sorted_names = OssieToRelationalAIConverter._sort_dependency_graph(oc.concepts(exclude_builtin=True))
+        for name in sorted_names:
+            concept = oc.lookup_concept(name)
+            if concept and concept.name not in ontology.base_model().concept_index:
+                subtypes = []
+                for parent in concept.extends:
+                    pyrel_parent = ontology.lookup_concept(parent.name)
+                    if pyrel_parent is None:
+                        raise ValueError(f"'{parent.name}' is not declared in the ontology.")
+                    subtypes.append(pyrel_parent)
+                ontology.Concept(concept.name, extends=subtypes)
+
+    # ------------------------------------------------------------------
+    # Relationships
+    # ------------------------------------------------------------------
+
+    @staticmethod
+    def _convert_relationships(oc: OntologyComponent, ontology: OntologyModel, properties_index: dict, reasoner: OntologyReasoner) -> None:
+        for rel in oc.relationships:
+            container = rel.first_role.player
+            if rel.name in pyrel.Concept.RESERVED_NAMES:
+                warnings.warn(
+                    f"Relationship '{rel.full_name}' clashes with Concept reserved name '{rel.name}'",
+                    UserWarning,
+                    stacklevel=2,
+                )
+                continue
+            reading = OssieToRelationalAIConverter._generate_reading(rel, ontology)
+            if reasoner.is_property(rel):
+                pyrel_rel = ontology.Property(reading, short_name=rel.name)
+            else:
+                pyrel_rel = ontology.Relationship(reading, short_name=rel.name)
+            properties_index[rel.full_name] = pyrel_rel
+            if not container.is_builtin:
+                c = ontology.lookup_concept(container.name)
+                c.__setattr__(rel.name, pyrel_rel)
+
+    # ------------------------------------------------------------------
+    # Identifiers
+    # ------------------------------------------------------------------
+
+    @staticmethod
+    def _identify_concepts(oc: OntologyComponent, ontology: OntologyModel, properties_index: dict) -> None:
+        for concept in oc.concepts(exclude_builtin=True):
+            identify_by = concept.identify_by
+            if identify_by:
+                pyrel_concept = OssieToRelationalAIConverter._concept(ontology, concept.name)
+                props = [properties_index[key] for key in identify_by]
+                pyrel_concept.identify_by(*props)
+
+    # ------------------------------------------------------------------
+    # Mappings
+    # ------------------------------------------------------------------
+
+    @staticmethod
+    def _expression_key(expression) -> tuple:
+        """Dataset-qualified identity of a mapping expression.
+
+        A ``DatasetField`` stringifies to the bare column name (``runway_id``),
+        which is *not* unique: att_latest maps ``OFT_Runway`` twice from two
+        different datasets that both have a ``runway_id`` column. Keying on the
+        rendered string alone merges those two bindings and rebinds the second
+        concept mapping's properties onto the first one's dataset. The owning
+        dataset therefore has to be part of the key — by identity, since two
+        distinct datasets may also share a name.
+        """
+        if isinstance(expression, DatasetField):
+            dataset = expression.dataset
+            return ("field", getattr(dataset, "name", None), id(dataset), expression.name)
+        # Formulas render their dataset references inline, so the text is
+        # already qualified.
+        return ("other", str(expression))
+
+    @staticmethod
+    def _object_mapping_key(osi_concept: Concept, om: ObjectMapping) -> tuple:
+        """Identity of the entity binding an ObjectMapping would produce.
+
+        Two object mappings that agree on concept *and* on how the identifier
+        is sourced describe the same set of entities, so they only need one
+        creation rule between them. Everything the identifier is derived from
+        goes into the key: the referent mappings (relationship + expression),
+        or — for the bare-expression form — the expression and the concept it
+        casts to. `_build_entity_binding` also reads ``om.concept`` (the
+        supertype that supplies the ref scheme), so that is part of the key too.
+        """
+        supertype = om.concept.name if om.concept is not None else None
+        if om.referent_mappings:
+            identifier = (
+                "referents",
+                tuple(sorted(
+                    (str(getattr(rm.relationship, "name", rm.relationship)),
+                     OssieToRelationalAIConverter._expression_key(rm.expression))
+                    for rm in om.referent_mappings

Review Comment:
   The docstring says "everything the identifier is derived from goes into the key", but the referents key uses only `rm.relationship.name` and `_expression_key(rm.expression)`. As far as I can tell, a referent with nested `referent_mappings` has `expression=None` and keys as the same `("other", "None")` regardless of its nesting. Two object mappings of the same concept with the same top-level relationship but different nested referents would then get the same key. The second would reuse the first's `EBinding`, and its entities would silently never be created or bound.
   
   Should the key recurse into nested referent mappings? A test with two such mappings would show whether they collide.



##########
converters/ontology/src/ossie_ontology/converter/ossie_to_relationalai/converter.py:
##########
@@ -0,0 +1,569 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Ossie -> RelationalAI: an `OssieOntology` becomes a PyRel `OntologyModel`.
+
+Together with `ossie_ontology.expr.formula.visitor.converter` — the formula
+emitter, which stays with its sibling visitors — this package is the only part
+of `ossie_ontology` that imports `relationalai`. Neither is reachable from
+`ossie_ontology/__init__.py`, which is what lets the SDK be an optional extra
+rather than a hard dependency. Install it with:
+
+    pip install "apache-ossie-ontology[relationalai]"
+"""
+from __future__ import annotations
+
+import warnings
+from typing import Any, Callable
+
+from relationalai.util.naming import NameCache
+from ossie_ontology.vendor.relationalai.mappings import EntityMapping
+from ossie_ontology.vendor.relationalai.ontology import OntologyModel
+from ossie_ontology.expr.formula.model import Formula
+from ossie_ontology.expr.formula.visitor.converter import FormulaConverter, MappingFormulaConverter
+from ossie_ontology.reasoner import OntologyReasoner
+from ossie_ontology.model import (
+    Concept,
+    Dataset,
+    DatasetField,
+    LinkMapping,
+    ObjectMapping,
+    SemanticModel,
+    OntologyComponent,
+    OntologyMapping,
+    ReferentMapping,
+    Relationship,
+    OssieOntology,
+)
+import relationalai.semantics as pyrel
+from relationalai.semantics import Concept as RAIConcept
+
+# How a dataset becomes something the model can read. Takes the model being
+# built, the dataset as the Ossie spec declares it, and the column types derived
+# from that spec; returns whatever pyrel construct should stand in for it.
+#
+# The default resolves the dataset's `source` to a warehouse table. Substituting
+# a provider is how a caller reads from somewhere else — from inline CSV, for
+# example, so a test corpus needs no warehouse — without this converter having
+# to know that any such alternative exists.
+TableProvider = Callable[["OntologyModel", Dataset, dict[str, RAIConcept]], Any]
+
+
+def warehouse_table(ontology: "OntologyModel", dataset: Dataset,
+                    schema: dict[str, RAIConcept]) -> Any:
+    """Resolve a dataset to the warehouse table its `source` names.
+
+    The schema is deliberately *not* passed on: pyrel reads the real columns
+    from the table instead. That costs a connection when the model is compiled,
+    but it is the only way to get the column identifiers right — Snowflake folds
+    an unquoted name to upper case, so declaring the spec's `airport_code`
+    yields `AIRPORT_CODE`, which does not address a column created as
+    `"airport_code"`. Only the table itself knows which it is.
+
+    Use :func:`declared_table` where the spec's field names are known to match
+    and a connection is unwanted.
+    """
+    return ontology.base_model().Table(dataset.source)
+
+
+def declared_table(ontology: "OntologyModel", dataset: Dataset,
+                   schema: dict[str, RAIConcept]) -> Any:
+    """Resolve a dataset to its table, declaring the columns from the spec.
+
+    Nothing is read from the warehouse, so conversion and compilation work with
+    no connection — which is what makes an offline test suite possible. The
+    tradeoff is the one :func:`warehouse_table` avoids: the declared identifiers
+    have to match how the table was actually created.
+    """
+    return ontology.base_model().Table(dataset.source, schema=schema)
+
+
+class OssieToRelationalAIConverter:
+
+    @staticmethod
+    def convert(
+        model: OssieOntology,
+        reasoner: OntologyReasoner | None = None,
+        model_cls: type[OntologyModel] = OntologyModel,
+        table_provider: TableProvider = warehouse_table,
+    ) -> OntologyModel:
+        """Convert an OssieOntology into a PyRel model.
+
+        `model_cls` decides what the result is an instance of. The conversion
+        itself only ever touches the plain `OntologyModel` surface, so the
+        default is that class; pass `MeasureOntologyModel` when the caller goes
+        on to ask dimensional measure queries of the result.
+        """
+        ontology = model_cls(model.name)
+        properties_index: dict[str, pyrel.Relationship] = {}
+
+        oc = model.ontology
+        if reasoner is None:
+            reasoner = OntologyReasoner()
+            oc.register(reasoner)
+
+        OssieToRelationalAIConverter._convert_concepts(oc, ontology)
+        OssieToRelationalAIConverter._convert_relationships(oc, ontology, properties_index, reasoner)
+        OssieToRelationalAIConverter._identify_concepts(oc, ontology, properties_index)
+
+        for om in model.ontology_mappings:
+            OssieToRelationalAIConverter._convert_datasets(
+                om.semantic_model, ontology, table_provider
+            )
+
+        # Shared across every ontology_mapping, so a binding declared in two of
+        # them collapses to one creation rule. Insurance rather than a live
+        # saving: every scenario in the corpus has a single ontology_mapping.
+        entity_bindings: dict = {}
+        for om in model.ontology_mappings:
+            OssieToRelationalAIConverter._convert_mappings(
+                om, ontology, properties_index, reasoner, entity_bindings
+            )
+
+        OssieToRelationalAIConverter._convert_formulas(oc, ontology, reasoner)
+
+        return ontology
+
+    @staticmethod
+    def _concept(ontology: OntologyModel, name: str) -> RAIConcept:
+        """The pyrel concept for an Ossie concept name.
+
+        Every concept is created by `_convert_concepts` before any mapping or
+        reading is converted, so a miss means those passes disagree about the
+        ontology. Failing here names the concept; letting the None through
+        surfaces later as an opaque `NoneType has no attribute` from inside
+        pyrel, or binds a null silently.
+        """
+        concept = ontology.lookup_concept(name)
+        assert concept is not None, f"Concept '{name}' not found in the converted ontology"
+        return concept
+
+    # ------------------------------------------------------------------
+    # Datasets
+    # ------------------------------------------------------------------
+
+    @staticmethod
+    def _convert_datasets(sm: SemanticModel, ontology: OntologyModel, table_provider: TableProvider) -> None:
+        for dataset in sm.datasets:
+            schema = OssieToRelationalAIConverter._pyrel_schema(dataset, ontology)
+            ontology.add_table(dataset.name, table_provider(ontology, dataset, schema))
+
+    @staticmethod
+    def _pyrel_schema(dataset: Dataset, ontology: OntologyModel) -> dict:
+        """Column types for *dataset*, taken from the Ossie spec that declares it.
+
+        Handed to the table provider so it can declare the columns up front,
+        which is what keeps the conversion from needing a live warehouse.
+        """
+        schema = {}
+        for fl in dataset.fields:
+            if fl.type is not None:
+                concept = OssieToRelationalAIConverter._concept(ontology, fl.type.name)
+                schema[fl.name] = ontology.get_topmost_parent(concept)
+            else:
+                schema[fl.name] = ontology.lookup_concept("String")
+        return schema
+
+    # ------------------------------------------------------------------
+    # Concepts
+    # ------------------------------------------------------------------
+
+    @staticmethod
+    def _convert_concepts(oc: OntologyComponent, ontology: OntologyModel) -> None:
+        sorted_names = OssieToRelationalAIConverter._sort_dependency_graph(oc.concepts(exclude_builtin=True))
+        for name in sorted_names:
+            concept = oc.lookup_concept(name)
+            if concept and concept.name not in ontology.base_model().concept_index:
+                subtypes = []
+                for parent in concept.extends:
+                    pyrel_parent = ontology.lookup_concept(parent.name)
+                    if pyrel_parent is None:
+                        raise ValueError(f"'{parent.name}' is not declared in the ontology.")
+                    subtypes.append(pyrel_parent)
+                ontology.Concept(concept.name, extends=subtypes)
+
+    # ------------------------------------------------------------------
+    # Relationships
+    # ------------------------------------------------------------------
+
+    @staticmethod
+    def _convert_relationships(oc: OntologyComponent, ontology: OntologyModel, properties_index: dict, reasoner: OntologyReasoner) -> None:
+        for rel in oc.relationships:
+            container = rel.first_role.player
+            if rel.name in pyrel.Concept.RESERVED_NAMES:

Review Comment:
   When a relationship name is reserved, this warns and (below) skips it, so it never reaches `properties_index`. But `properties_index[...]` is indexed directly later. If any identifier or link mapping uses a skipped relationship, I would expect a `KeyError` rather than the "warn and skip" the warning implies.
   
   Could those lookups use `.get()` and skip with a warning too?



##########
converters/ontology/src/ossie_ontology/vendor/relationalai/mappings.py:
##########
@@ -0,0 +1,385 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from relationalai.semantics import Concept as RAIConcept, Chain
+from relationalai.semantics import Relationship as RAIRelationship
+from relationalai.semantics.frontend.base import Ref
+
+# Given some entity type E. An E *ref* is a Python variable that can be used in
+# a select query or fragment to range over E objects in the graph. For instance,
+# given:
+#
+#    Person = Concept('Person')
+#
+# the Person object that is declared here is a Person ref, as is Person.ref().
+# Because PyRel conflates types with variables, we use refs to mean the type
+# or the variable depending on context.
+
+
+# Given some entity type E. An E *identifier* is an object (Python dictionary) whose:
+#
+#  - keys are the short names of identifying properties (the ref scheme) of E, and
+#  - values take on one of the following two forms depending on whether the "one role"
+#    of the property named by the key is played by:
+#
+#      (1) a value type, in which case the value is a PyRel expression that typically
+#          involves a reference to one or more dataset fields (columns), or
+#      (2) some entity type E', in which case, the value is an EntityMapping that
+#          encapsulates details for looking up references of E'.
+#
+# Identifiers implement "identifier objects" as they are declared using the *identifier*
+# key in an entity or general relationship mapping as proposed in the OSI specification
+# for ontologies document.
+
+
+# Given some entity type E, this abstract class encapsulates the E ref to use when
+# referencing and/or deriving the population of E in the graph, and all details needed
+# to generate the PyRel that makes the E ref usable for schema mapping. The specific
+# details include:
+#
+#  - The E ref itself (self.ref())
+#  - The identifier that will be used to look up E ref objects in PyRel (self.identifier())
+#  - The PyRel fragment that applies the identifier to look up E ref objects(self.lookup())
+#  - Any constraints that might need to appear in a where(...) clause in order for the
+#    use of the E ref to be correct (self.constraints())
+#
+class Eref:
+
+    # Erefs are parameterized by:
+    #
+    #  - the entity type (e) being referenced;
+    #  - the creation context, in which this Eref will be used. Set this flag
+    #    if the context creates new instances of e because it allows us to optimize
+    #    the generated PyRel when looking up instances (using e.to_identity rather
+    #    than e.filter_by).
+    #  - a user supplied E identifier, which may contain nested EntityMaps
+    #
+    def __init__(self, e: RAIConcept, creation_context=False, **identifier):
+        self._entity_type = e
+        self._creation_context = creation_context
+        (self._identifier_obj, self._constraints) = self._normalize_identifier(**identifier)
+
+    # The identifier object (dictionary) that is passed in when we construct an
+    # Eref maps identifying property keys to either PyRel expressions or nested
+    # EntityMappings. But identifier objects must map these keys to PyRel expressions
+    # exclusively (no nested entity mappings).
+    #
+    # This method generates:
+    #   - a proper identifier object (a copy of identifier in which every key that mapped
+    #     to an EntityMapping is replaced with a key that maps to a reference to the entity
+    #     type represented by that mapping, and
+    #  - an array of constraints imposed by any nested EntityMapping in identifier
+    #
+    def _normalize_identifier(self, **identifier):
+        args = {}
+        constraints = []
+
+        for k in identifier:
+            if isinstance(identifier[k], EntityMapping):
+                args[k] = identifier[k].ref()
+                constraints += identifier[k].constraints()
+            elif isinstance(identifier[k], ValueMapping):
+                args[k] = identifier[k].expr()
+                constraints += identifier[k].constraints()
+            else:
+                args[k] = identifier[k]
+
+        return (args, constraints)
+
+    # Constraints on the variables used to populate the ref. These will appear
+    # in the where(...) clause of a rule. Will include any constraints that are
+    # associated with nested entity mappings that are handled when we replace
+    # those nested entity mappings to create self.identifier().
+    #
+    def constraints(self):
+        return self._constraints
+
+    # The entity type being referenced
+    def entity_type(self):
+        return self._entity_type
+
+    # The identifier object (dictionary) used when referencing instances of
+    # this entity type. The object maps identifying properties to PyRel expressions
+    def identifier(self):
+        return self._identifier_obj
+
+    # Generates a PyRel fragment to look up/constrain the objects in the graph that
+    # self.ref() will range over when the fragment is used in a rule or query.
+    #
+    # The creation_context lets us optimize how we look up these objects.
+    #
+    def lookup(self):
+        ref = self.ref()
+        if self._creation_context:
+            # `to_identity` exists on a Concept but not on a Ref, so a creation
+            # context requires the concept itself. That holds today: the only
+            # subclass that swaps in a plain Ref is EntityMapping, which never
+            # creates. Asserting it keeps the coupling visible if that changes.
+            assert isinstance(ref, RAIConcept), "a creation context needs a concept ref"
+            return ref.to_identity(**(self.identifier()), unsafe=True)
+        return ref.filter_by(**(self.identifier()))
+
+    # The reference variable (of type self._entity_type) to use in generated
+    # code. This ref is bound by the self.lookup() atom. This method is
+    # overridden by some subclasses.
+    #
+    # A subclass may hand back a plain `Ref` instead of the concept — see
+    # EntityMapping below — so the declared type covers both.
+    def ref(self) -> RAIConcept | Ref:
+        return self._entity_type
+
+
+# Given some entity type E, this class implements Erefs that range over E objects
+# without populating any concepts or relationships as a side effect. These are used
+# strictly to aid in referencing E objects in larger mapping contexts as we do when
+# we declare nested entity mappings in our OSI proposal (mappings section)
+
+class EntityMapping(Eref):
+
+    def __init__(self, e: RAIConcept, **identifier):
+        super().__init__(e, **identifier)
+        self._ref = e.ref()
+
+    def constraints(self):
+        wc = super().constraints()
+        wc.append(self.lookup())
+        return wc
+
+    def ref(self):
+        return self._ref
+
+    # Additional conditions (PyRel fragments) that constrain this EntityMapping.
+    # These will typically refer to Dataset fields
+    def where(self, expr):
+        self._constraints.append(expr)
+        return self
+
+
+class ValueMapping:
+    def __init__(self, expr):
+        self._constraints = []
+        self._expr = expr
+
+    def constraints(self):
+        return self._constraints
+
+    def expr(self):
+        return self._expr
+
+    # Additional conditions (PyRel fragments) that constrain this ValueMapping.
+    # These will typically refer to Dataset fields
+    def where(self, expr):
+        self._constraints.append(expr)
+        return self
+
+
+class EBinding(Eref):
+
+    # If provided, stype must be a RAIConcept that provides (at least part of)
+    # the identifier
+    def __init__(self, model, e: RAIConcept, stype: RAIConcept|None, **identifier):
+
+        if model.declares_preferred_identifier(e):
+            # e provides a ref scheme
+            super().__init__(e, creation_context=True, **identifier)
+            self._model = model
+
+            where_clauses = self._constraints
+            if len(where_clauses) == 0:
+                self._model.define(e.new(**(self.identifier())))
+            else:
+                self._model.define(e.new(**(self.identifier()))).where(*where_clauses)
+
+        else:
+            # e must inherit its ref scheme
+            if e._name in model._super_type_of:
+                super().__init__(e, **identifier)
+                self._model = model
+
+                if stype is not None:
+                    super_ref = EntityMapping(stype, **identifier)
+                    # The rule that "asserts" the population of self.entity_type()
+                    self._model.where(*(super_ref.constraints())).define(e(super_ref.ref()))
+                # else: Assume the supertype binding is declared elsewhere (e.g., when e is a derived subtype)
+
+            else:
+                raise ValueError(f'Currently no way to bind entity concept {e._name} because it neither declares nor '
+                                 'inherits an identifier')
+
+    #
+    # Declares that a property of this entity type binds to one or more role
+    # values that ultimately refer to fields of this table. Each value can be:
+    #
+    #   1) An arbitrary PyRel expression that references one or more
+    #      fields to produce some value; or
+    #   2) An EntityMapping that declares how to look up an instance of
+    #      some entity type to populate for each row of the table; or
+    #   3) A ValueMapping that carries a PyRel expression together with
+    #      WHERE constraints (e.g. produced by a WHERE-filtered mapping formula).
+    #
+    # Binary relationships take a single expr. Ternary (and higher-arity)
+    # relationships pass the intermediate role value(s) via extra_exprs —
+    # e.g. binds_to(returns, item_ref, amount_expr) for Transaction.returns(Item, Amount).
+    # Passing no expr at all asserts a unary (zero-role) relationship fact.
+    #
+    def binds_to(self, property, *exprs):
+        ref = self.lookup()
+        where_clauses = [ref]
+        where_clauses += self.constraints()
+
+        # Unwrap each role value: extract the PyRel expression and accumulate
+        # any WHERE constraints the value carries (EntityMapping / ValueMapping).
+        def _resolve(e):
+            if isinstance(e, EntityMapping):
+                where_clauses.extend(e.constraints())
+                return e.ref()
+            if isinstance(e, ValueMapping):
+                where_clauses.extend(e.constraints())
+                return e.expr()
+            return e
+
+        vals = [_resolve(e) for e in exprs if e is not None]
+
+        atom = EBinding._property_atom(ref, property, *vals)
+        self._model.where(*where_clauses).define(atom)
+
+        return self
+
+    #
+    # Helper function that declares automates the construction of an EntityMapping
+    # by analyzing the property to determine the concept that plays the target role.
+    # The identifier contains the arguments to that EntityMapping
+    #
+    def binds_to_entity(self, property, **identifier):
+        emap = EntityMapping(self._model._target_role_player(property), **identifier)
+        return self.binds_to(property, emap)
+
+    #
+    # Builds the PyRel atom that populates a property of ref with the given
+    # role values. Accepts zero or more values:
+    #   - zero vals: asserts a unary (boolean) relationship fact
+    #   - one val:   binary relationship (the common case)
+    #   - N vals:    ternary / higher-arity relationship
+    #
+    @staticmethod
+    def _property_atom(ref, property, *vals):
+        attr = ref.__getattr__(property._short_name)
+        return attr(*vals) if vals else attr
+
+
+class JoinPathBinding:
+
+    def __init__(self, model, r: RAIRelationship):
+        self._model = model
+        self._relationship = r
+        self._src_concept = model._source_role_player(r)
+        self._trg_concept = model._target_role_player(r)
+        self._bind_from = None
+        self._bind_to = None
+
+    # Every JoinPathBinding populates the relationship using entity objects that
+    # it locates using entity mappings (emap1 and emap2)
+    #
+    def bind(self, emap1, emap2):
+        where_clauses = emap1.constraints() + emap2.constraints()
+        self._model.where(*where_clauses).define(self._relationship(emap1.ref(), emap2.ref()))
+        return self
+
+    #
+    # Helper function that creates automate construction of EntityMappings
+    # by analyzing the concepts that play the from and to roles of the
+    # relationship being bound
+    #
+
+    def bind_from(self, **ctor_args):
+        from_emap = EntityMapping(self._src_concept, **ctor_args)
+        if self._bind_to is None:
+            self._bind_from = from_emap
+        else:
+            return self.bind(from_emap, self._bind_to)
+        return self
+
+    def bind_to(self, **ctor_args):
+        to_emap = EntityMapping(self._trg_concept, **ctor_args)
+        if self._bind_from is None:
+            self._bind_to = to_emap
+        else:
+            return self.bind(self._bind_from, to_emap)
+        return self
+
+
+class GRBinding:
+
+    # We can initialize a generalized relationship binding with an array
+    # of exprs, any one of which can be either:
+    #
+    #   1) An arbitrary PyRel expression that references one or more
+    #      fields to produce some value; or
+    #   2) An EntityMapping that declares how to look up an instance of
+    #      some entity type to populate for each row of the table
+    #
+    def __init__(self, model, *exprs):
+        self._model = model
+        self._key_constraints = []
+        self._keys = []
+
+        for expr in exprs:
+            if isinstance(expr, EntityMapping):
+                self._key_constraints += expr.constraints()
+                self._keys.append(expr.ref())
+            else:
+                self._keys.append(expr)
+
+    def keys(self):
+        return self._keys
+
+    def bind(self, handle, expr=None, **identifier):
+        r = handle._next if isinstance(handle, Chain) else handle
+        keys = self._keys.copy()
+        where_clauses = self._key_constraints.copy()
+
+        has_extra = expr is not None or len(identifier) > 0
+        self._validate_role_count(r, len(keys) + (1 if has_extra else 0))
+
+        if has_extra:
+            extra_key, extra_constraints = self._resolve_extra_key(expr, identifier)
+            keys.append(extra_key)
+            where_clauses += extra_constraints
+
+        self._model.define(handle(*keys)).where(*where_clauses)
+        return self
+
+    @staticmethod
+    def _validate_role_count(r, expected):
+        if len(r._fields) != expected:
+            raise ValueError(
+                f"Relationship {r} has {len(r._fields)} roles but used in a "
+                f"GRBinding context that expects {expected}")
+
+    def _resolve_extra_key(self, expr, identifier):
+        """Resolve the trailing key/constraints pair from either an explicit
+        expr (EntityMapping / ValueMapping / raw PyRel expression) or
+        **identifier kwargs that synthesize an EntityMapping for the
+        relationship's last role.
+        """
+        if expr is None:
+            expr = EntityMapping(self._model._last_role_player(), **identifier)

Review Comment:
   `OntologyModel._last_role_player(self, r)` takes a required argument, but it's called here with none. `bind(handle, **identifier)` without an `expr` will raise `TypeError`. It also isn't passed the relationship, so it couldn't select the right role even with an argument.
   
   Could you pass the relationship being bound, and cover the no-`expr` path with a test?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ossie.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org