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

[PR] feat(holistics): add a Holistics AML converter [ossie]

tantmd opened a new pull request, #538:
URL: https://github.com/apache/ossie/pull/538

   # Add a Holistics AML converter
   
   Hi, I'm Tan from Holistics. We have been following Ossie from the outside, and we would like to contribute a
   converter between Holistics AML and the Ossie semantic model.
   
   For context. [AML](https://docs.holistics.io/reference/aml) is the language a Holistics semantic layer is
   written in: datasets, models, dimensions, measures and relationships. AQL is its expression language, similar
   to MAQL and DAX.
   
   ## What it does
   
   - `to-ossie` reads the JSON `holistics aml compile` produces, and writes one Ossie semantic model.
   - `to-aml` reads one Ossie semantic model, and writes AML source files.
   
   One AML `Dataset` becomes one Ossie semantic model. Its models become Ossie datasets, its relationships become
   Ossie relationships, and its measures and metrics become Ossie metrics.
   
   This converter also rewrites some Ossie metrics into AQL. An Ossie metric can calculate across datasets, and
   Holistics only allows that in AQL.
   
   This is similar to DAX, and I see that `converters/microsoft` already does the same thing. It turns the
   TPC-DS `customer_lifetime_value` into
   `DIVIDE(SUM('store_sales'[ss_ext_sales_price]), DISTINCTCOUNTNOBLANK('customer'[c_customer_sk]))`. We turn the
   same metric into `sum(store_sales.ss_ext_sales_price) / count_distinct(customer.c_customer_sk)`.
   
   ## Some interop issues
   
   Similar to MAQL and DAX, I do not attempt to convert AQL to Ossie SQL here. An AQL body is stashed under
   `HOLISTICS_AQL` in the `Dialect` enumeration, which the first commit registers, following
   [#351](https://github.com/apache/ossie/pull/351).
   
   AML supports query templating in a `QueryModel`, think a Looker derived table, including params supplied at
   query time. This does not translate cleanly to Ossie, so this converter raises an ERROR when it detects one
   and carries the body unresolved. The forms are `{{ #model }}`, `{{ #model.* }}` and `{% filter(param) %}`. A
   filter block cannot be resolved at conversion time at all, because the param value only exists at query time.
   
   I also noticed that
   [examples/tpcds_semantic_model.yaml](https://github.com/apache/ossie/blob/main/examples/tpcds_semantic_model.yaml)
   uses window functions over dataset fields, for example
   `RANK() OVER (PARTITION BY store.s_store_sk ORDER BY SUM(store_sales.ss_ext_sales_price) DESC)`. I don't think
   this works in most BI vendors. Omni does the substitution and keeps the window:
   `converters/omni/tests/fixtures/tpcds_omni/views/store_sales.view.yaml` carries
   `RANK() OVER (PARTITION BY ${store.s_store_sk} ORDER BY SUM(${store_sales.ss_ext_sales_price}) DESC)`. I
   believe that fails with a group-by error once a query selects it without grouping by those columns.
   
   AQL does support arbitrary window functions, including the case where the query grain does not include the
   field, and composition over them. I could translate these into the equivalent AQL. But
   `core-spec/expression_language.md` says "When, adding the query interface, window functions will be subject to
   where they are allowed", so where one is allowed and what it means at a given grain is not settled yet.
   So this converter raises an ERROR for those instead.
   
   The Power BI converter does much the same. It emits `BLANK()` for all three window metrics in that file. Cube takes the
   mirror case on import with the same reasoning: a measure that "computes over a grain other than the query's" has no
   Ossie expression form.
   
   ## For reviewers
   
   `converters/holistics/README.md` has the command lines and the full option list. The documents under
   `converters/holistics/docs/`:
   
   - [The fixture](https://github.com/tantmd/ossie/blob/holistics-converter/converters/holistics/docs/fixture.md).
     The AML source, how to recompile it, and the shape of the compiled JSON.
   - [Mapping](https://github.com/tantmd/ossie/blob/holistics-converter/converters/holistics/docs/mapping.md).
     Which AML construct becomes which Ossie construct, including relationships and data types.
   - [Expression translation](https://github.com/tantmd/ossie/blob/holistics-converter/converters/holistics/docs/expressions.md).
     What the converter emits for each definition body, and what it leaves untranslated.
   - [Ossie to AML](https://github.com/tantmd/ossie/blob/holistics-converter/converters/holistics/docs/reverse.md).
     The generated file layout, and where a metric lands.
   - [Ossie SQL to AQL](https://github.com/tantmd/ossie/blob/holistics-converter/converters/holistics/docs/aql.md).
     The function table, the raw-SQL call for a function AQL has no name for, and what is dropped instead.
   - [Measures](https://github.com/tantmd/ossie/blob/holistics-converter/converters/holistics/docs/measures.md).
     How `aggregation_type` and a definition body compose into one Ossie metric expression.
   - [The HOLISTICS payload](https://github.com/tantmd/ossie/blob/holistics-converter/converters/holistics/docs/vendor-payload.md).
     Everything carried in `custom_extensions`.
   - [Limitations](https://github.com/tantmd/ossie/blob/holistics-converter/converters/holistics/docs/limitations.md).
     The coverage matrix, and the 24 issue codes with their severities.
   
   
   ## Related Issues
   
   None. No issue precedes this, and the spec change has not been raised on the mailing list. I am happy to open
   one for the dialect member if that is the order you prefer.
   
   ## Checklist
   
   ### Specification
   - [ ] Spec changes are included in `core-spec/` and follow the existing structure
   - [ ] Spec changes have been discussed on the mailing list or in a linked issue (not yet, see above)
   - [ ] Breaking changes to the spec are clearly called out in the summary (there are none; the change adds one
         enumeration member)
   
   ### Ontology
   - [ ] Ontology changes in `ontology/` are consistent with spec changes (not applicable; no ontology change)
   - [ ] New or modified terms are defined and documented (not applicable)
   
   ### Converters
   - [x] Converter logic in `converters/` is updated to reflect spec or ontology changes
   - [x] New converters include tests under the converter's test directory
   - [x] If adding a new converter, `.github/labeler.yml` is updated with the new path
   
   ### Validation
   - [ ] Validation rules in `validation/` are updated if the spec changed
   - [ ] New validation cases are covered by tests
   
   ### Documentation
   - [ ] `docs/` is updated to reflect any user-facing changes
   - [ ] New features or behaviors are documented with examples where appropriate
   - [ ] `CONTRIBUTING.md` is updated if the contribution process changed (not applicable)
   
   ### Examples
   - [ ] `examples/` are added or updated for any new spec constructs or converter support (not applicable; the
         dialect member needs no example, and `examples/tpcds_semantic_model.yaml` is used as a test input
         unchanged)
   
   ### Tests
   - [x] All existing tests pass (121 converter tests, 164 validation tests)
   - [x] New functionality is covered by tests
   
   ### Compliance
   - [x] ASF license headers are present on all new source files (every `.py`, `.md`, `.yml`, `.yaml`, `.aml`,
         `.toml` and `.gitignore`; the two generated files, `uv.lock` and a compiled-JSON fixture, carry none, the
         same as their counterparts in the sibling converters)
   - [x] No third-party dependencies are added without PMC/IPMC approval (`PyYAML`, and `sqlglot>=30.12.0`, which
         `converters/microsoft`, `converters/snowflake` and `converters/nvidia` already pin at the same version)
   - [x] If third-party source code is vendored/copied (not just declared as a dependency), `NOTICE` and/or
         `LICENSE` have been updated per [ASF policy](https://infra.apache.org/licensing-howto.html) (nothing is
         vendored)
   


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


Re: [PR] feat(holistics): add a Holistics AML converter [ossie]

Posted by "tantmd (via GitHub)" <gi...@apache.org>.
tantmd commented on PR #538:
URL: https://github.com/apache/ossie/pull/538#issuecomment-6074364989

   Thanks for the quick review, @jbonofre 🤟 . I've addressed all the issues as fixup commits, one per comment, unsquashed so each reads against its thread. Will squash it later before merging.
   


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


Re: [PR] feat(holistics): add a Holistics AML converter [ossie]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #538:
URL: https://github.com/apache/ossie/pull/538#issuecomment-6053602871

   Thank you for your first contribution to Apache Ossie (incubating)!
   
   A committer will review your PR. In the meantime, please ensure:
   
   - All CI checks pass
   - ASF license headers are present on new source files
   - Tests cover new functionality
   
   No ICLA is required to contribute. If you are elected as a committer in the future, you will need an [Individual Contributor License Agreement (ICLA)](https://www.apache.org/licenses/contributor-agreements.html) on file with the ASF.
   
   **Questions?** Ask in the PR comments or join us on [Slack](https://join.slack.com/t/apache-ossie/shared_invite/zt-42zw4rflt-Gpve8_NFJq7AsdAQTY~SCg).
   
   We appreciate your contribution!


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


Re: [PR] feat(holistics): add a Holistics AML converter [ossie]

Posted by "tantmd (via GitHub)" <gi...@apache.org>.
tantmd commented on code in PR #538:
URL: https://github.com/apache/ossie/pull/538#discussion_r4226599745


##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}
+
+
+class _Reverse:
+    def __init__(
+        self, document: dict[str, Any], data_source_name: str | None, sql_dialect: str
+    ):
+        self.document = document
+        self.sql_dialect = sql_dialect
+        self.issues = IssueLog()
+        self.root_stash = stash.read(document)
+        self.data_source_name = self.root_stash.get("data_source_name") or data_source_name
+        if not self.data_source_name:
+            raise ConversionError(
+                "the document carries no HOLISTICS data_source_name, so one must be "
+                "supplied: pass --data-source-name naming the Holistics connection"
+            )
+
+        #: AML identifier to the Ossie name it was spelled from, so two names
+        #: that collapse onto one spelling fail rather than overwrite.
+        self._renamed: dict[str, str] = {}
+
+        datasets = _named_objects(document.get("datasets"), "datasets")
+        if not datasets:
+            raise ConversionError(
+                "the document declares no datasets, and the specification requires at least one"
+            )
+        for dataset in datasets:
+            _named_objects(dataset.get("fields"), f"datasets[{dataset['name']}].fields")
+        _named_objects(document.get("metrics"), "metrics")
+
+        self.models: list[Model] = []
+        for dataset in datasets:
+            name = dataset["name"]
+            data = stash.read(dataset)
+            self.models.append(
+                Model(
+                    ossie_name=name,
+                    fqn=data.get("fqn") or unflatten(name),
+                    payload=dataset,
+                    stash=data,
+                )
+            )
+        self.by_ossie_name = {m.ossie_name: m for m in self.models}
+
+        taken: dict[str, str] = {}
+        for model in self.models:
+            clash = taken.setdefault(model.aml_fqn, model.ossie_name)
+            if clash != model.ossie_name:
+                raise ConversionError(
+                    f"datasets {clash!r} and {model.ossie_name!r} both spell as the AML "
+                    f"model {model.aml_fqn!r}; rename one of them in Ossie"
+                )
+
+        self.dataset_name = self._dataset_name()
+
+        #: Every metric that belongs on a model, indexed by Ossie metric name,
+        #: alongside the AML measure name it is written as.
+        self.metric_owner: dict[str, Model] = {}
+        self.metric_aml_name: dict[str, str] = {}
+        self.dataset_metrics: list[dict[str, Any]] = []
+        self._metric_payloads: dict[str, dict[str, Any]] = {}
+        self._metric_datasets: dict[str, Any] = {}
+        self._cyclic_metrics: set[str] = set()
+        self._place_metrics()
+
+    # -- placement --------------------------------------------------------
+
+    def _place_metrics(self) -> None:
+        """Decide where each Ossie metric goes: on a model, or on the dataset.
+
+        A stashed `model` settles it. Without one, the expression decides: a
+        body naming exactly one dataset becomes a measure on that model, and a
+        body naming several becomes a dataset-level metric, which is the only
+        AML construct that spans models. A body may also name another metric,
+        and `_scan_for_datasets` covers what that counts as.
+        """
+        metrics = self.document.get("metrics") or []
+        for metric in metrics:
+            name = metric.get("name")
+            self.metric_aml_name[name] = stash.read(metric).get("aml_name") or name
+            self._metric_payloads[name] = metric
+        for metric in metrics:
+            name = metric.get("name")
+            named = self._datasets_named(name) or frozenset()
+            owner = self.by_ossie_name[next(iter(named))] if len(named) == 1 else None
+            if owner is None:
+                self.dataset_metrics.append(metric)
+            else:
+                owner.measures.append(metric)
+                self.metric_owner[name] = owner
+        self._report_metric_cycles()
+
+    def _datasets_named(self, name: str) -> frozenset[str] | None:
+        """The Ossie datasets metric `name` resolves to, or None when that is unknown.
+
+        None covers every reading that cannot put the metric on a single model:
+        an AQL body, Ossie SQL this converter cannot read, and a reference cycle.
+        """
+        resolved = self._metric_datasets.get(name, _UNVISITED)
+        if resolved is _RESOLVING:
+            self._cyclic_metrics.add(name)
+            return None
+        if resolved is not _UNVISITED:
+            return resolved
+        self._metric_datasets[name] = _RESOLVING
+        result = self._scan_for_datasets(name)
+        self._metric_datasets[name] = result
+        return result
+
+    def _scan_for_datasets(self, name: str) -> frozenset[str] | None:
+        """Which datasets one metric body names, directly or through a metric.
+
+        An Ossie metric body may name another metric instead of a column, as
+        `cities__upstream_measure + 1` in `tests/fixtures/ecommerce` does. That
+        body names no dataset of its own, and the datasets the metric it
+        references resolves to stand in for it. Without that substitution a
+        metric built only from other metrics lands on the dataset, where AML
+        takes an AQL body, and the Ossie SQL name it was written with does not
+        resolve.
+        """
+        metric = self._metric_payloads[name]
+        data = stash.read(metric)
+        owner_fqn = data.get("model")
+        if owner_fqn:
+            owner = next((m for m in self.models if m.fqn == owner_fqn), None)
+            if owner is None:
+                raise ConversionError(
+                    f"metric {name!r} is stashed against model {owner_fqn!r}, "
+                    f"which is not a dataset in this document"
+                )
+            return frozenset({owner.ossie_name})
+        available = dialects_of(metric.get("expression"))
+        if AQL_DIALECT in available:
+            return None
+        dialect = next(
+            (d for d in (self.sql_dialect, *PORTABLE_DIALECTS) if d in available), None
+        )
+        if dialect is None:
+            return None
+        try:
+            references = sqlrefs.columns(available[dialect], dialect)
+        except sqlrefs.UnparseableSQL:
+            return None
+        named = {c.table for c in references if c.table in self.by_ossie_name}
+        for reference in references:
+            if reference.table or reference.name not in self._metric_payloads:
+                continue
+            through = self._datasets_named(reference.name)
+            if through is None:
+                return None
+            named |= through
+        return frozenset(named)
+
+    def _report_metric_cycles(self) -> None:
+        for name in sorted(self._cyclic_metrics):
+            self.issues.add(
+                code=ISSUE_METRIC_CYCLE,
+                severity=Severity.ERROR,
+                message=(
+                    f"metric {name!r} references itself through another metric. Holistics "
+                    f"inlines one metric into the body of the next, so a cycle has no warehouse SQL, "
+                    f"and `holistics aml validate` accepts the file without catching it"
+                ),
+                object_ref=name,
+                remedy="break the cycle in Ossie",
+            )
+
+    # -- names ------------------------------------------------------------
+
+    def _dataset_name(self) -> str:
+        """The AML `Dataset` name, moved aside when a model already has it.
+
+        Ossie keeps the semantic model's name and its dataset names in separate
+        namespaces, so a document may use one name for both. Three fixtures in
+        this repository do, including
+        `converters/cube/tests/fixtures/databricks_ossie.yaml`, whose root name
+        and first dataset are both `orders`. AML has one namespace for `Dataset`
+        and `Model`, and rejects the pair with "Duplicated name 'orders'".
+
+        Nothing references the AML dataset name. Models reference each other and
+        relationships reference models, so the dataset is the safe side to move.
+        """
+        name = self.root_stash.get("fqn") or self.document.get("name")
+        if not name:
+            raise ConversionError("the document has no name")
+        spelled = self.name_in_aml(name, str(name))
+        taken = {model.aml_fqn for model in self.models} | {
+            model.aml_name for model in self.models
+        }
+        if spelled not in taken:
+            return spelled
+        candidate, suffix = f"{spelled}_dataset", 2
+        while candidate in taken:
+            candidate, suffix = f"{spelled}_dataset_{suffix}", suffix + 1
+        self.issues.add(
+            code=ISSUE_DATASET_RENAMED,
+            severity=Severity.WARNING,
+            message=(
+                f"a model is already named {spelled!r}, and AML holds Dataset and Model "
+                f"in one namespace, so the dataset is written as {candidate!r}"
+            ),
+            object_ref=str(name),
+            remedy="rename the semantic model or the dataset in Ossie",
+        )
+        return candidate
+
+    def name_in_aml(self, name: str, scope: str) -> str:
+        """An Ossie name as the AML identifier it is written as.
+
+        Lookups elsewhere stay keyed on the Ossie name, because that is what an
+        expression references. Only the output spelling changes, and every site
+        that writes a name goes through here, so a declaration and a reference
+        to it cannot disagree.
+        """
+        spelled = sanitize(name)
+        if spelled != name:
+            previous = self._renamed.setdefault(spelled, name)
+            if previous != name:
+                raise ConversionError(
+                    f"{scope}: {name!r} and {previous!r} both spell as the AML "
+                    f"identifier {spelled!r}; rename one of them in Ossie"
+                )
+            self.issues.add(
+                code=ISSUE_RENAMED,
+                severity=Severity.WARNING,
+                message=(
+                    f"{name!r} is not a legal AML identifier and is written as "
+                    f"{spelled!r}. AML allows letters, digits and underscore, and no "
+                    f"leading digit"
+                ),
+                object_ref=scope,
+                remedy=f"rename it to {spelled!r} in Ossie to keep the two in step",
+            )
+        return spelled
+
+    # -- expressions ------------------------------------------------------
+
+    def pick_body(self, expression: Any, scope: str) -> tuple[str, str]:
+        """The body to write and the dialect it is in, after any rendering.
+
+        AQL wins outright. It came out of AML unchanged and goes back unchanged.
+
+        For Ossie SQL the target is `--sql-dialect`, the warehouse the Holistics
+        connection reads. A body already in that dialect is written as it
+        stands. Otherwise a portable body is rendered into the target with
+        sqlglot, because the alternative is AML that will not run. An expression
+        offering neither has no body this connection can execute, and the
+        converter says so rather than writing Holistics SQL for the wrong warehouse.
+        """
+        available = dialects_of(expression)
+        if AQL_DIALECT in available:
+            return AQL_DIALECT, available[AQL_DIALECT]
+        if self.sql_dialect in available:
+            return self.sql_dialect, available[self.sql_dialect]
+
+        source = next((d for d in PORTABLE_DIALECTS if d in available), None)
+        if source is not None:
+            try:
+                rendered = sqlrefs.transpile(available[source], source, self.sql_dialect)
+            except sqlrefs.UnparseableSQL as exc:
+                self.issues.add(
+                    code=ISSUE_UNPARSEABLE_SQL,
+                    severity=Severity.ERROR,
+                    message=(
+                        f"the {source} body cannot be rendered as {self.sql_dialect} ({exc}), "
+                        f"so it is written unchanged and may not run"
+                    ),
+                    object_ref=scope,
+                    remedy=f"add a {self.sql_dialect} expression, or fix the {source} one",
+                )
+                return source, available[source]
+            self.issues.add(
+                code=ISSUE_TRANSPILED,
+                severity=Severity.WARNING,
+                message=(
+                    f"no {self.sql_dialect} expression, so the {source} one was rendered "
+                    f"into it: {available[source]!r} became {rendered!r}"
+                ),
+                object_ref=scope,
+                remedy=f"add a {self.sql_dialect} expression to keep the body exact",
+            )
+            return self.sql_dialect, rendered
+
+        fallback = next(iter(available))
+        self.issues.add(
+            code=ISSUE_NO_USABLE_DIALECT,
+            severity=Severity.ERROR,
+            message=(
+                f"the expression offers {', '.join(sorted(available))} and the connection "
+                f"reads {self.sql_dialect}, with no portable body to render from, so the "
+                f"{fallback} body is written unchanged and will not run"
+            ),
+            object_ref=scope,
+            remedy=f"add a {self.sql_dialect} or ANSI_SQL expression",
+        )
+        return fallback, available[fallback]
+
+    def definition(self, block: Block, expression: Any, model: Model, scope: str) -> None:
+        """Write a `definition` property for a field or a measure."""
+        dialect, text = self.pick_body(expression, scope)
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+            return
+        block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+
+    def to_aml_sql(self, expression: str, dialect: str, model: Model, scope: str) -> str:
+        """An Ossie SQL expression with its references written as AML interpolation.
+
+        A bare column name does compile as AML, but AQL reads the interpolation
+        to learn which field the body depends on. A body without it loses the
+        query rewriting and the optimisation that link drives, so this restores
+        every reference rather than passing the SQL through.
+        """
+        if dialect in sqlrefs.NOT_SQL or not sqlrefs.AVAILABLE:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body is tagged {dialect!r}, which is not Ossie SQL this converter can "
+                    f"read, so its field references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="supply an ANSI_SQL or warehouse-SQL dialect for this expression",
+            )
+            return expression
+        grouping = sqlrefs.window_grouping(expression, dialect)
+        if grouping:
+            self.issues.add(
+                code=ISSUE_WINDOW_NEEDS_GROUPING,
+                severity=Severity.WARNING,
+                message=(
+                    f"the body has a window function whose frame reads "
+                    f"{', '.join(grouping)}. AML carries it as written, and the warehouse SQL "
+                    f"it generates is valid only for a query that groups by those. A query "
+                    f"that does not, a grand total for one, produces warehouse SQL the "
+                    f"database rejects, and Holistics does not check this at conversion time"
+                ),
+                object_ref=scope,
+                remedy="query it only alongside those fields, or rewrite the body in AQL",
+            )
+        try:
+            return sqlrefs.rewrite(
+                expression, dialect, lambda column: self.to_interpolation(column, model, scope)
+            )
+        except sqlrefs.UnparseableSQL as exc:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"sqlglot cannot read the body as {dialect} ({exc}), so its field "
+                    f"references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="fix the expression, or convert it by hand",
+            )
+            return expression
+
+    def to_interpolation(self, column: sqlrefs.ColumnReference, model: Model, scope: str) -> str:
+        """One Ossie column reference as the AML interpolation it came from."""
+        if not column.table:
+            if column.name in self.metric_aml_name:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Source(column.name).to_aml()
+
+        target = self.by_ossie_name.get(column.table)
+        if target is None:
+            self.issues.add(
+                code=ISSUE_UNKNOWN_QUALIFIER,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body qualifies {column.name!r} with {column.table!r}, which is not "
+                    f"a dataset in this document, so it is left unresolved"
+                ),
+                object_ref=scope,
+                remedy="qualify the reference with a dataset name, or drop the field",
+            )
+            return f"{column.table}.{column.name}"
+        if target is model:
+            # A qualifier naming this model usually names one of its fields. It
+            # can also name a metric this converter put somewhere else, and a
+            # sibling reference to that spells a field the model does not have.
+            if column.name in self.metric_aml_name and self.metric_owner.get(column.name) is not model:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Sibling(self.name_in_aml(column.name, scope)).to_aml()
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body names {column.table}.{column.name}, a field of another dataset. A `@sql` "
+                f"body resolves inside one model, and Holistics rejects this at SQL generation "
+                f"with \"Cannot refer to external field in TableModel/QueryModel\" even though "
+                f"`holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="move the reference into a dimension on its own model, or rewrite the body in AQL",
+        )
+        return interpolation.ModelField(target.aml_fqn, self.name_in_aml(column.name, scope)).to_aml()
+
+    def _measure_reference(self, metric_name: str, model: Model, scope: str) -> str:
+        owner = self.metric_owner.get(metric_name)
+        aml_name = self.metric_aml_name[metric_name]
+        if owner is model:
+            return interpolation.Sibling(self.name_in_aml(aml_name, scope)).to_aml()
+        if owner is None:
+            self.issues.add(
+                code=ISSUE_CROSS_MODEL_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body references the dataset-level metric {metric_name!r}. A `@sql` "
+                    f"body resolves inside one model, so there is no AML spelling for it"
+                ),
+                object_ref=scope,
+                remedy="rewrite the expression in AQL, which does span models",
+            )
+            return metric_name
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body references {metric_name!r}, a measure of model {owner.aml_fqn!r}. A "
+                f"`@sql` body resolves inside one model, and Holistics rejects this at SQL "
+                f"generation with \"Cannot refer to external field in TableModel/QueryModel\" "
+                f"even though `holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="rewrite the expression in AQL, which does span models",
+        )
+        return interpolation.ModelField(owner.aml_fqn, self.name_in_aml(aml_name, scope)).to_aml()
+
+    # -- fields -----------------------------------------------------------
+
+    def aml_type(
+        self, payload: dict[str, Any], data: dict[str, Any], scope: str, model: Model | None = None
+    ) -> str:
+        stashed = data.get("type")
+        if stashed:
+            return stashed
+        datatype = payload.get("datatype")
+        mapped = OSSIE_TO_AML_TYPE.get(datatype) if datatype else None
+        if mapped:
+            return mapped
+        if model is not None and payload["name"] in model.numeric:
+            # A metric aggregates this field with `sum` or `avg`, so it is a
+            # number whatever the document failed to say.
+            return "number"
+        self.issues.add(
+            code=ISSUE_ASSUMED_TYPE,
+            severity=Severity.WARNING,
+            message=(
+                f"AML requires a type and the Ossie datatype is {datatype!r}, "
+                f"so {FALLBACK_TYPE!r} is written"
+            ),
+            object_ref=scope,
+            remedy="set a datatype on the field, or edit the AML type after conversion",
+        )
+        return FALLBACK_TYPE
+
+    def common_properties(
+        self,
+        block: Block,
+        payload: dict[str, Any],
+        data: dict[str, Any],
+        scope: str,
+        model: Model | None = None,
+    ) -> None:
+        block.text("label", data.get("label") or titleize(payload["name"]))
+        block.property("type", quote(self.aml_type(payload, data, scope, model)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+    def dimension(self, model: Model, payload: dict[str, Any], primary_key: set[str]) -> Block:
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        block.flag("primary_key", name in primary_key)
+        return block
+
+    def dataset_dimension(self, model: Model, payload: dict[str, Any]) -> Block:
+        """A field the forward path took from a dataset-level AML dimension."""
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        block.property("model", model.reference)
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        return block
+
+    def measure(self, model: Model, payload: dict[str, Any]) -> Block:
+        """One Ossie metric as a `measure` on its owning model.
+
+        `aggregation_type` and the body compose into one Ossie expression on the
+        way out, so this splits them back apart. When the stashed aggregation
+        does not wrap the whole expression, the expression was edited after the
+        forward path wrote it, and `custom` keeps it whole rather than letting
+        the measure aggregate twice.
+        """
+        metric_name = payload["name"]
+        aml_name = self.metric_aml_name[metric_name]
+        scope = f"{model.ossie_name}.{aml_name}"
+        data = stash.read(payload)
+        block = Block(f"measure {self.name_in_aml(aml_name, scope)}")
+        block.text("label", data.get("label") or titleize(aml_name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        aggregation = data.get("aggregation_type") or CUSTOM_AGGREGATION
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+        else:
+            if aggregation in AGGREGATIONS:
+                inner = strip_aggregation(aggregation, text)
+                if inner is None:
+                    self.issues.add(
+                        code=ISSUE_AGGREGATION_NOT_STRIPPED,
+                        severity=Severity.WARNING,
+                        message=(
+                            f"the stashed aggregation {aggregation!r} does not wrap the whole "
+                            f"expression, so the measure is written as 'custom' with the "
+                            f"expression kept whole"
+                        ),
+                        object_ref=scope,
+                        remedy="check the expression against the aggregation",
+                    )
+                    aggregation = CUSTOM_AGGREGATION
+                else:
+                    text = inner
+            block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+        block.property("aggregation_type", quote(aggregation))
+        block.text("format", data.get("format"))
+        return block
+
+    def as_aql(self, text: str, dialect: str, scope: str) -> str | None:
+        """A dataset-level metric's Ossie SQL body rendered as AQL, or None if it cannot be.
+
+        AML accepts only `@aql` here, so an Ossie SQL body either becomes AQL or has no
+        AML form at all. `aql.translate` is a name map over functions this
+        converter has paired with an AQL equivalent. Anything outside that table
+        raises `Untranslatable`, and the metric is dropped with an ERROR.
+        """
+        try:
+            rendered, numeric = aql.translate(
+                text, dialect, lambda table, column: self.aql_reference(table, column, scope)
+            )
+        except aql.Untranslatable as exc:
+            self.issues.add(
+                code=ISSUE_METRIC_NOT_TRANSLATED,
+                severity=Severity.ERROR,
+                message=(
+                    f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                    f"converter did not translate this {dialect} body, and the metric is "
+                    f"dropped. {exc}"
+                ),
+                object_ref=scope,
+                remedy="rewrite the metric in AQL, or scope it to a single dataset",
+            )
+            return None
+        self.issues.add(
+            code=ISSUE_RENDERED_AS_AQL,
+            severity=Severity.WARNING,
+            message=(
+                f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                f"{dialect} expression was rendered as AQL: {text!r} became {rendered!r}"
+            ),
+            object_ref=scope,
+            remedy="check the AQL against the Ossie SQL it came from",
+        )
+        for table, column in numeric:
+            target = self.by_ossie_name.get(table)
+            if target is not None:
+                target.numeric.add(self.name_in_aml(column, scope))
+        return rendered
+
+    def aql_reference(self, table: str, column: str, scope: str) -> str:
+        """One column of an Ossie SQL metric body as the AQL reference it becomes.
+
+        AQL names a field `model.field`, which is the shape the Ossie expression
+        already uses, so this maps the Ossie dataset name onto the AML model
+        name and keeps the field name.
+
+        An Ossie SQL body may name a warehouse column the document does not declare as
+        a field. `SUM(orders.subtotal) / COUNT(DISTINCT customers.customer_id)`
+        in `converters/nvidia/tests/fixtures/sales.ossie.yaml` is one: `orders`
+        declares no `subtotal`. Ossie SQL resolves that against the table, and AQL
+        does not, answering `Field `subtotal` not found in model `orders``. So
+        the column becomes a hidden dimension on that model, and the AQL
+        reference points at it.
+        """
+        if not table:
+            # An unqualified name that is a metric is a metric reference, which
+            # AQL takes: a dataset-level one by its bare name, and a measure by
+            # the model that holds it.
+            if column in self.metric_aml_name:
+                referenced = self.name_in_aml(self.metric_aml_name[column], scope)
+                owner = self.metric_owner.get(column)
+                return referenced if owner is None else f"{owner.aml_fqn}.{referenced}"
+            raise aql.Untranslatable(
+                f"{column!r} names no dataset, and a metric spanning models has no single "
+                f"model to resolve it against."
+            )
+        target = self.by_ossie_name.get(table)
+        if target is None:
+            raise aql.Untranslatable(f"{table!r} is not a dataset in this document.")
+        name = self.name_in_aml(column, scope)
+        declared = {
+            field["name"] for field in target.payload.get("fields") or []
+        } | {self.metric_aml_name[m["name"]] for m in target.measures}
+        if name not in declared and name not in target.borrowed:
+            target.borrowed.append(name)
+            self.issues.add(
+                code=ISSUE_BORROWED_COLUMN,
+                severity=Severity.WARNING,
+                message=(
+                    f"the metric reads {table}.{column}, which the dataset does not declare "
+                    f"as a field. AQL resolves a reference against declared fields only, so "
+                    f"{column!r} is added to model {target.aml_fqn!r} as a hidden dimension "
+                    f"over the column of that name"
+                ),
+                object_ref=scope,
+                remedy=f"declare {column!r} as a field of {table!r} in Ossie",
+            )
+        return f"{target.aml_fqn}.{name}"
+
+    def dataset_metric(self, payload: dict[str, Any]) -> Block | None:
+        """One Ossie metric as a dataset-level AML `metric`.
+
+        AML accepts only an `@aql` body here. The compiler rejects `@sql` with
+        "Incompatible property 'definition' of 'Metric'", so a cross-model
+        metric carrying Ossie SQL has no AML form at all.
+        """
+        name = payload["name"]
+        scope = name
+        data = stash.read(payload)
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        if dialect != AQL_DIALECT:
+            rendered = self.as_aql(text, dialect, scope)
+            if rendered is None:
+                return None
+            text = rendered
+        block = Block(f"metric {self.name_in_aml(name, scope)}")
+        block.text("label", data.get("label") or titleize(name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+        block.heredoc("definition", "aql", text)
+        block.text("format", data.get("format"))
+        return block
+
+    # -- models -----------------------------------------------------------
+
+    def model_file(self, model: Model) -> str:
+        payload = model.payload
+        data = model.stash
+        scope = model.ossie_name
+        is_query = data.get("aml_type") == "QueryModel" or (
+            "aml_type" not in data and bool(interpolation.query_forms_used(payload.get("source", "")))
+        )
+        source = payload.get("source", "")
+        if "aml_type" not in data and not is_query:
+            is_query = _looks_like_query(source)
+
+        block = Block(f"Model {model.aml_name}")
+        block.property("type", quote("query" if is_query else "table"))
+        block.text("label", data.get("label") or titleize(model.aml_name))
+        block.text("description", payload.get("description"))
+        block.text("data_source_name", data.get("data_source_name") or self.data_source_name)
+        if is_query:
+            referenced = _models_referenced(source)
+            if referenced:
+                block.property("models", f"[{', '.join(sorted(referenced))}]")
+            block.blank()
+            block.heredoc("query", "sql", source)
+        else:
+            block.text("table_name", data.get("table_name") or source)
+
+        for param in data.get("param") or []:
+            block.blank()
+            param_block = block.block(f"param {self.name_in_aml(param['name'], scope)}")
+            param_block.text("label", param.get("label") or titleize(param["name"]))
+            param_block.property("type", quote(param.get("type") or FALLBACK_TYPE))
+
+        persistence = data.get("persistence")
+        if persistence:
+            block.blank()
+            _write_persistence(block, persistence)
+
+        primary_key = set(payload.get("primary_key") or [])
+        for field in payload.get("fields") or []:
+            if stash.read(field).get("scope") == "dataset":
+                continue
+            block.blank()
+            block.lines.append(self.dimension(model, field, primary_key))
+
+        for metric in model.measures:
+            block.blank()
+            block.lines.append(self.measure(model, metric))
+
+        for column in model.borrowed:
+            block.blank()
+            borrowed = block.block(f"dimension {column}")
+            borrowed.text("label", titleize(column))
+            borrowed.property("type", quote(FALLBACK_TYPE_FOR_BORROWED))
+            borrowed.flag("hidden", True)
+            borrowed.heredoc("definition", "sql", interpolation.Source(column).to_aml())
+
+        owner = data.get("owner") or self.root_stash.get("owner")
+        if owner:
+            block.blank()
+            block.text("owner", owner)
+        return amlgen.document(block, license_header=True)
+
+    # -- dataset ----------------------------------------------------------
+
+    def relationship(self, payload: dict[str, Any]) -> str:
+        data = stash.read(payload)
+        kind = data.get("type", "many_to_one")
+        active = "true" if data.get("active", True) else "false"
+        from_model = self.by_ossie_name.get(payload.get("from"))
+        to_model = self.by_ossie_name.get(payload.get("to"))
+        if from_model is None or to_model is None:
+            missing = payload.get("from") if from_model is None else payload.get("to")
+            raise ConversionError(
+                f"relationship {payload.get('name')!r} names dataset {missing!r}, "
+                f"which is not in this document"
+            )
+        from_columns = payload.get("from_columns") or []
+        to_columns = payload.get("to_columns") or []
+
+        if len(from_columns) == 1 and kind in ("many_to_one", "one_to_one"):
+            operator = ">" if kind == "many_to_one" else "-"
+            return (
+                f"relationship({from_model.reference}.{from_columns[0]} {operator} "
+                f"{to_model.reference}.{to_columns[0]}, {active})"
+            )
+
+        config = Block("RelationshipConfig")
+        rel = config.block("EqualityRelationship")
+        rel.header = "rel: EqualityRelationship"
+        rel.property("type", quote(kind))
+        rel.property("from", _field_ref(from_model.aml_name, from_columns[0]))
+        rel.property("to", _field_ref(to_model.aml_name, to_columns[0]))
+        for from_column, to_column in zip(from_columns[1:], to_columns[1:]):

Review Comment:
   fixed in 62d626d



##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}
+
+
+class _Reverse:
+    def __init__(
+        self, document: dict[str, Any], data_source_name: str | None, sql_dialect: str
+    ):
+        self.document = document
+        self.sql_dialect = sql_dialect
+        self.issues = IssueLog()
+        self.root_stash = stash.read(document)
+        self.data_source_name = self.root_stash.get("data_source_name") or data_source_name
+        if not self.data_source_name:
+            raise ConversionError(
+                "the document carries no HOLISTICS data_source_name, so one must be "
+                "supplied: pass --data-source-name naming the Holistics connection"
+            )
+
+        #: AML identifier to the Ossie name it was spelled from, so two names
+        #: that collapse onto one spelling fail rather than overwrite.
+        self._renamed: dict[str, str] = {}
+
+        datasets = _named_objects(document.get("datasets"), "datasets")
+        if not datasets:
+            raise ConversionError(
+                "the document declares no datasets, and the specification requires at least one"
+            )
+        for dataset in datasets:
+            _named_objects(dataset.get("fields"), f"datasets[{dataset['name']}].fields")
+        _named_objects(document.get("metrics"), "metrics")
+
+        self.models: list[Model] = []
+        for dataset in datasets:
+            name = dataset["name"]
+            data = stash.read(dataset)
+            self.models.append(
+                Model(
+                    ossie_name=name,
+                    fqn=data.get("fqn") or unflatten(name),
+                    payload=dataset,
+                    stash=data,
+                )
+            )
+        self.by_ossie_name = {m.ossie_name: m for m in self.models}
+
+        taken: dict[str, str] = {}
+        for model in self.models:
+            clash = taken.setdefault(model.aml_fqn, model.ossie_name)
+            if clash != model.ossie_name:
+                raise ConversionError(
+                    f"datasets {clash!r} and {model.ossie_name!r} both spell as the AML "
+                    f"model {model.aml_fqn!r}; rename one of them in Ossie"
+                )
+
+        self.dataset_name = self._dataset_name()
+
+        #: Every metric that belongs on a model, indexed by Ossie metric name,
+        #: alongside the AML measure name it is written as.
+        self.metric_owner: dict[str, Model] = {}
+        self.metric_aml_name: dict[str, str] = {}
+        self.dataset_metrics: list[dict[str, Any]] = []
+        self._metric_payloads: dict[str, dict[str, Any]] = {}
+        self._metric_datasets: dict[str, Any] = {}
+        self._cyclic_metrics: set[str] = set()
+        self._place_metrics()
+
+    # -- placement --------------------------------------------------------
+
+    def _place_metrics(self) -> None:
+        """Decide where each Ossie metric goes: on a model, or on the dataset.
+
+        A stashed `model` settles it. Without one, the expression decides: a
+        body naming exactly one dataset becomes a measure on that model, and a
+        body naming several becomes a dataset-level metric, which is the only
+        AML construct that spans models. A body may also name another metric,
+        and `_scan_for_datasets` covers what that counts as.
+        """
+        metrics = self.document.get("metrics") or []
+        for metric in metrics:
+            name = metric.get("name")
+            self.metric_aml_name[name] = stash.read(metric).get("aml_name") or name
+            self._metric_payloads[name] = metric
+        for metric in metrics:
+            name = metric.get("name")
+            named = self._datasets_named(name) or frozenset()
+            owner = self.by_ossie_name[next(iter(named))] if len(named) == 1 else None
+            if owner is None:
+                self.dataset_metrics.append(metric)
+            else:
+                owner.measures.append(metric)
+                self.metric_owner[name] = owner
+        self._report_metric_cycles()
+
+    def _datasets_named(self, name: str) -> frozenset[str] | None:
+        """The Ossie datasets metric `name` resolves to, or None when that is unknown.
+
+        None covers every reading that cannot put the metric on a single model:
+        an AQL body, Ossie SQL this converter cannot read, and a reference cycle.
+        """
+        resolved = self._metric_datasets.get(name, _UNVISITED)
+        if resolved is _RESOLVING:
+            self._cyclic_metrics.add(name)
+            return None
+        if resolved is not _UNVISITED:
+            return resolved
+        self._metric_datasets[name] = _RESOLVING
+        result = self._scan_for_datasets(name)
+        self._metric_datasets[name] = result
+        return result
+
+    def _scan_for_datasets(self, name: str) -> frozenset[str] | None:
+        """Which datasets one metric body names, directly or through a metric.
+
+        An Ossie metric body may name another metric instead of a column, as
+        `cities__upstream_measure + 1` in `tests/fixtures/ecommerce` does. That
+        body names no dataset of its own, and the datasets the metric it
+        references resolves to stand in for it. Without that substitution a
+        metric built only from other metrics lands on the dataset, where AML
+        takes an AQL body, and the Ossie SQL name it was written with does not
+        resolve.
+        """
+        metric = self._metric_payloads[name]
+        data = stash.read(metric)
+        owner_fqn = data.get("model")
+        if owner_fqn:
+            owner = next((m for m in self.models if m.fqn == owner_fqn), None)
+            if owner is None:
+                raise ConversionError(
+                    f"metric {name!r} is stashed against model {owner_fqn!r}, "
+                    f"which is not a dataset in this document"
+                )
+            return frozenset({owner.ossie_name})
+        available = dialects_of(metric.get("expression"))
+        if AQL_DIALECT in available:
+            return None
+        dialect = next(
+            (d for d in (self.sql_dialect, *PORTABLE_DIALECTS) if d in available), None
+        )
+        if dialect is None:
+            return None
+        try:
+            references = sqlrefs.columns(available[dialect], dialect)
+        except sqlrefs.UnparseableSQL:
+            return None
+        named = {c.table for c in references if c.table in self.by_ossie_name}
+        for reference in references:
+            if reference.table or reference.name not in self._metric_payloads:
+                continue
+            through = self._datasets_named(reference.name)
+            if through is None:
+                return None
+            named |= through
+        return frozenset(named)
+
+    def _report_metric_cycles(self) -> None:
+        for name in sorted(self._cyclic_metrics):
+            self.issues.add(
+                code=ISSUE_METRIC_CYCLE,
+                severity=Severity.ERROR,
+                message=(
+                    f"metric {name!r} references itself through another metric. Holistics "
+                    f"inlines one metric into the body of the next, so a cycle has no warehouse SQL, "
+                    f"and `holistics aml validate` accepts the file without catching it"
+                ),
+                object_ref=name,
+                remedy="break the cycle in Ossie",
+            )
+
+    # -- names ------------------------------------------------------------
+
+    def _dataset_name(self) -> str:
+        """The AML `Dataset` name, moved aside when a model already has it.
+
+        Ossie keeps the semantic model's name and its dataset names in separate
+        namespaces, so a document may use one name for both. Three fixtures in
+        this repository do, including
+        `converters/cube/tests/fixtures/databricks_ossie.yaml`, whose root name
+        and first dataset are both `orders`. AML has one namespace for `Dataset`
+        and `Model`, and rejects the pair with "Duplicated name 'orders'".
+
+        Nothing references the AML dataset name. Models reference each other and
+        relationships reference models, so the dataset is the safe side to move.
+        """
+        name = self.root_stash.get("fqn") or self.document.get("name")
+        if not name:
+            raise ConversionError("the document has no name")
+        spelled = self.name_in_aml(name, str(name))
+        taken = {model.aml_fqn for model in self.models} | {
+            model.aml_name for model in self.models
+        }
+        if spelled not in taken:
+            return spelled
+        candidate, suffix = f"{spelled}_dataset", 2
+        while candidate in taken:
+            candidate, suffix = f"{spelled}_dataset_{suffix}", suffix + 1
+        self.issues.add(
+            code=ISSUE_DATASET_RENAMED,
+            severity=Severity.WARNING,
+            message=(
+                f"a model is already named {spelled!r}, and AML holds Dataset and Model "
+                f"in one namespace, so the dataset is written as {candidate!r}"
+            ),
+            object_ref=str(name),
+            remedy="rename the semantic model or the dataset in Ossie",
+        )
+        return candidate
+
+    def name_in_aml(self, name: str, scope: str) -> str:
+        """An Ossie name as the AML identifier it is written as.
+
+        Lookups elsewhere stay keyed on the Ossie name, because that is what an
+        expression references. Only the output spelling changes, and every site
+        that writes a name goes through here, so a declaration and a reference
+        to it cannot disagree.
+        """
+        spelled = sanitize(name)
+        if spelled != name:
+            previous = self._renamed.setdefault(spelled, name)
+            if previous != name:
+                raise ConversionError(
+                    f"{scope}: {name!r} and {previous!r} both spell as the AML "
+                    f"identifier {spelled!r}; rename one of them in Ossie"
+                )
+            self.issues.add(
+                code=ISSUE_RENAMED,
+                severity=Severity.WARNING,
+                message=(
+                    f"{name!r} is not a legal AML identifier and is written as "
+                    f"{spelled!r}. AML allows letters, digits and underscore, and no "
+                    f"leading digit"
+                ),
+                object_ref=scope,
+                remedy=f"rename it to {spelled!r} in Ossie to keep the two in step",
+            )
+        return spelled
+
+    # -- expressions ------------------------------------------------------
+
+    def pick_body(self, expression: Any, scope: str) -> tuple[str, str]:
+        """The body to write and the dialect it is in, after any rendering.
+
+        AQL wins outright. It came out of AML unchanged and goes back unchanged.
+
+        For Ossie SQL the target is `--sql-dialect`, the warehouse the Holistics
+        connection reads. A body already in that dialect is written as it
+        stands. Otherwise a portable body is rendered into the target with
+        sqlglot, because the alternative is AML that will not run. An expression
+        offering neither has no body this connection can execute, and the
+        converter says so rather than writing Holistics SQL for the wrong warehouse.
+        """
+        available = dialects_of(expression)
+        if AQL_DIALECT in available:
+            return AQL_DIALECT, available[AQL_DIALECT]
+        if self.sql_dialect in available:
+            return self.sql_dialect, available[self.sql_dialect]
+
+        source = next((d for d in PORTABLE_DIALECTS if d in available), None)
+        if source is not None:
+            try:
+                rendered = sqlrefs.transpile(available[source], source, self.sql_dialect)
+            except sqlrefs.UnparseableSQL as exc:
+                self.issues.add(
+                    code=ISSUE_UNPARSEABLE_SQL,
+                    severity=Severity.ERROR,
+                    message=(
+                        f"the {source} body cannot be rendered as {self.sql_dialect} ({exc}), "
+                        f"so it is written unchanged and may not run"
+                    ),
+                    object_ref=scope,
+                    remedy=f"add a {self.sql_dialect} expression, or fix the {source} one",
+                )
+                return source, available[source]
+            self.issues.add(
+                code=ISSUE_TRANSPILED,
+                severity=Severity.WARNING,
+                message=(
+                    f"no {self.sql_dialect} expression, so the {source} one was rendered "
+                    f"into it: {available[source]!r} became {rendered!r}"
+                ),
+                object_ref=scope,
+                remedy=f"add a {self.sql_dialect} expression to keep the body exact",
+            )
+            return self.sql_dialect, rendered
+
+        fallback = next(iter(available))
+        self.issues.add(
+            code=ISSUE_NO_USABLE_DIALECT,
+            severity=Severity.ERROR,
+            message=(
+                f"the expression offers {', '.join(sorted(available))} and the connection "
+                f"reads {self.sql_dialect}, with no portable body to render from, so the "
+                f"{fallback} body is written unchanged and will not run"
+            ),
+            object_ref=scope,
+            remedy=f"add a {self.sql_dialect} or ANSI_SQL expression",
+        )
+        return fallback, available[fallback]
+
+    def definition(self, block: Block, expression: Any, model: Model, scope: str) -> None:
+        """Write a `definition` property for a field or a measure."""
+        dialect, text = self.pick_body(expression, scope)
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+            return
+        block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+
+    def to_aml_sql(self, expression: str, dialect: str, model: Model, scope: str) -> str:
+        """An Ossie SQL expression with its references written as AML interpolation.
+
+        A bare column name does compile as AML, but AQL reads the interpolation
+        to learn which field the body depends on. A body without it loses the
+        query rewriting and the optimisation that link drives, so this restores
+        every reference rather than passing the SQL through.
+        """
+        if dialect in sqlrefs.NOT_SQL or not sqlrefs.AVAILABLE:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body is tagged {dialect!r}, which is not Ossie SQL this converter can "
+                    f"read, so its field references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="supply an ANSI_SQL or warehouse-SQL dialect for this expression",
+            )
+            return expression
+        grouping = sqlrefs.window_grouping(expression, dialect)
+        if grouping:
+            self.issues.add(
+                code=ISSUE_WINDOW_NEEDS_GROUPING,
+                severity=Severity.WARNING,
+                message=(
+                    f"the body has a window function whose frame reads "
+                    f"{', '.join(grouping)}. AML carries it as written, and the warehouse SQL "
+                    f"it generates is valid only for a query that groups by those. A query "
+                    f"that does not, a grand total for one, produces warehouse SQL the "
+                    f"database rejects, and Holistics does not check this at conversion time"
+                ),
+                object_ref=scope,
+                remedy="query it only alongside those fields, or rewrite the body in AQL",
+            )
+        try:
+            return sqlrefs.rewrite(
+                expression, dialect, lambda column: self.to_interpolation(column, model, scope)
+            )
+        except sqlrefs.UnparseableSQL as exc:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"sqlglot cannot read the body as {dialect} ({exc}), so its field "
+                    f"references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="fix the expression, or convert it by hand",
+            )
+            return expression
+
+    def to_interpolation(self, column: sqlrefs.ColumnReference, model: Model, scope: str) -> str:
+        """One Ossie column reference as the AML interpolation it came from."""
+        if not column.table:
+            if column.name in self.metric_aml_name:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Source(column.name).to_aml()
+
+        target = self.by_ossie_name.get(column.table)
+        if target is None:
+            self.issues.add(
+                code=ISSUE_UNKNOWN_QUALIFIER,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body qualifies {column.name!r} with {column.table!r}, which is not "
+                    f"a dataset in this document, so it is left unresolved"
+                ),
+                object_ref=scope,
+                remedy="qualify the reference with a dataset name, or drop the field",
+            )
+            return f"{column.table}.{column.name}"
+        if target is model:
+            # A qualifier naming this model usually names one of its fields. It
+            # can also name a metric this converter put somewhere else, and a
+            # sibling reference to that spells a field the model does not have.
+            if column.name in self.metric_aml_name and self.metric_owner.get(column.name) is not model:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Sibling(self.name_in_aml(column.name, scope)).to_aml()
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body names {column.table}.{column.name}, a field of another dataset. A `@sql` "
+                f"body resolves inside one model, and Holistics rejects this at SQL generation "
+                f"with \"Cannot refer to external field in TableModel/QueryModel\" even though "
+                f"`holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="move the reference into a dimension on its own model, or rewrite the body in AQL",
+        )
+        return interpolation.ModelField(target.aml_fqn, self.name_in_aml(column.name, scope)).to_aml()
+
+    def _measure_reference(self, metric_name: str, model: Model, scope: str) -> str:
+        owner = self.metric_owner.get(metric_name)
+        aml_name = self.metric_aml_name[metric_name]
+        if owner is model:
+            return interpolation.Sibling(self.name_in_aml(aml_name, scope)).to_aml()
+        if owner is None:
+            self.issues.add(
+                code=ISSUE_CROSS_MODEL_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body references the dataset-level metric {metric_name!r}. A `@sql` "
+                    f"body resolves inside one model, so there is no AML spelling for it"
+                ),
+                object_ref=scope,
+                remedy="rewrite the expression in AQL, which does span models",
+            )
+            return metric_name
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body references {metric_name!r}, a measure of model {owner.aml_fqn!r}. A "
+                f"`@sql` body resolves inside one model, and Holistics rejects this at SQL "
+                f"generation with \"Cannot refer to external field in TableModel/QueryModel\" "
+                f"even though `holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="rewrite the expression in AQL, which does span models",
+        )
+        return interpolation.ModelField(owner.aml_fqn, self.name_in_aml(aml_name, scope)).to_aml()
+
+    # -- fields -----------------------------------------------------------
+
+    def aml_type(
+        self, payload: dict[str, Any], data: dict[str, Any], scope: str, model: Model | None = None
+    ) -> str:
+        stashed = data.get("type")
+        if stashed:
+            return stashed
+        datatype = payload.get("datatype")
+        mapped = OSSIE_TO_AML_TYPE.get(datatype) if datatype else None
+        if mapped:
+            return mapped
+        if model is not None and payload["name"] in model.numeric:
+            # A metric aggregates this field with `sum` or `avg`, so it is a
+            # number whatever the document failed to say.
+            return "number"
+        self.issues.add(
+            code=ISSUE_ASSUMED_TYPE,
+            severity=Severity.WARNING,
+            message=(
+                f"AML requires a type and the Ossie datatype is {datatype!r}, "
+                f"so {FALLBACK_TYPE!r} is written"
+            ),
+            object_ref=scope,
+            remedy="set a datatype on the field, or edit the AML type after conversion",
+        )
+        return FALLBACK_TYPE
+
+    def common_properties(
+        self,
+        block: Block,
+        payload: dict[str, Any],
+        data: dict[str, Any],
+        scope: str,
+        model: Model | None = None,
+    ) -> None:
+        block.text("label", data.get("label") or titleize(payload["name"]))
+        block.property("type", quote(self.aml_type(payload, data, scope, model)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+    def dimension(self, model: Model, payload: dict[str, Any], primary_key: set[str]) -> Block:
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        block.flag("primary_key", name in primary_key)
+        return block
+
+    def dataset_dimension(self, model: Model, payload: dict[str, Any]) -> Block:
+        """A field the forward path took from a dataset-level AML dimension."""
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        block.property("model", model.reference)
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        return block
+
+    def measure(self, model: Model, payload: dict[str, Any]) -> Block:
+        """One Ossie metric as a `measure` on its owning model.
+
+        `aggregation_type` and the body compose into one Ossie expression on the
+        way out, so this splits them back apart. When the stashed aggregation
+        does not wrap the whole expression, the expression was edited after the
+        forward path wrote it, and `custom` keeps it whole rather than letting
+        the measure aggregate twice.
+        """
+        metric_name = payload["name"]
+        aml_name = self.metric_aml_name[metric_name]
+        scope = f"{model.ossie_name}.{aml_name}"
+        data = stash.read(payload)
+        block = Block(f"measure {self.name_in_aml(aml_name, scope)}")
+        block.text("label", data.get("label") or titleize(aml_name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        aggregation = data.get("aggregation_type") or CUSTOM_AGGREGATION
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+        else:
+            if aggregation in AGGREGATIONS:
+                inner = strip_aggregation(aggregation, text)
+                if inner is None:
+                    self.issues.add(
+                        code=ISSUE_AGGREGATION_NOT_STRIPPED,
+                        severity=Severity.WARNING,
+                        message=(
+                            f"the stashed aggregation {aggregation!r} does not wrap the whole "
+                            f"expression, so the measure is written as 'custom' with the "
+                            f"expression kept whole"
+                        ),
+                        object_ref=scope,
+                        remedy="check the expression against the aggregation",
+                    )
+                    aggregation = CUSTOM_AGGREGATION
+                else:
+                    text = inner
+            block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+        block.property("aggregation_type", quote(aggregation))
+        block.text("format", data.get("format"))
+        return block
+
+    def as_aql(self, text: str, dialect: str, scope: str) -> str | None:
+        """A dataset-level metric's Ossie SQL body rendered as AQL, or None if it cannot be.
+
+        AML accepts only `@aql` here, so an Ossie SQL body either becomes AQL or has no
+        AML form at all. `aql.translate` is a name map over functions this
+        converter has paired with an AQL equivalent. Anything outside that table
+        raises `Untranslatable`, and the metric is dropped with an ERROR.
+        """
+        try:
+            rendered, numeric = aql.translate(
+                text, dialect, lambda table, column: self.aql_reference(table, column, scope)
+            )
+        except aql.Untranslatable as exc:
+            self.issues.add(
+                code=ISSUE_METRIC_NOT_TRANSLATED,
+                severity=Severity.ERROR,
+                message=(
+                    f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                    f"converter did not translate this {dialect} body, and the metric is "
+                    f"dropped. {exc}"
+                ),
+                object_ref=scope,
+                remedy="rewrite the metric in AQL, or scope it to a single dataset",
+            )
+            return None
+        self.issues.add(
+            code=ISSUE_RENDERED_AS_AQL,
+            severity=Severity.WARNING,
+            message=(
+                f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                f"{dialect} expression was rendered as AQL: {text!r} became {rendered!r}"
+            ),
+            object_ref=scope,
+            remedy="check the AQL against the Ossie SQL it came from",
+        )
+        for table, column in numeric:
+            target = self.by_ossie_name.get(table)
+            if target is not None:
+                target.numeric.add(self.name_in_aml(column, scope))
+        return rendered
+
+    def aql_reference(self, table: str, column: str, scope: str) -> str:
+        """One column of an Ossie SQL metric body as the AQL reference it becomes.
+
+        AQL names a field `model.field`, which is the shape the Ossie expression
+        already uses, so this maps the Ossie dataset name onto the AML model
+        name and keeps the field name.
+
+        An Ossie SQL body may name a warehouse column the document does not declare as
+        a field. `SUM(orders.subtotal) / COUNT(DISTINCT customers.customer_id)`
+        in `converters/nvidia/tests/fixtures/sales.ossie.yaml` is one: `orders`
+        declares no `subtotal`. Ossie SQL resolves that against the table, and AQL
+        does not, answering `Field `subtotal` not found in model `orders``. So
+        the column becomes a hidden dimension on that model, and the AQL
+        reference points at it.
+        """
+        if not table:
+            # An unqualified name that is a metric is a metric reference, which
+            # AQL takes: a dataset-level one by its bare name, and a measure by
+            # the model that holds it.
+            if column in self.metric_aml_name:
+                referenced = self.name_in_aml(self.metric_aml_name[column], scope)
+                owner = self.metric_owner.get(column)
+                return referenced if owner is None else f"{owner.aml_fqn}.{referenced}"
+            raise aql.Untranslatable(
+                f"{column!r} names no dataset, and a metric spanning models has no single "
+                f"model to resolve it against."
+            )
+        target = self.by_ossie_name.get(table)
+        if target is None:
+            raise aql.Untranslatable(f"{table!r} is not a dataset in this document.")
+        name = self.name_in_aml(column, scope)
+        declared = {
+            field["name"] for field in target.payload.get("fields") or []
+        } | {self.metric_aml_name[m["name"]] for m in target.measures}
+        if name not in declared and name not in target.borrowed:
+            target.borrowed.append(name)
+            self.issues.add(
+                code=ISSUE_BORROWED_COLUMN,
+                severity=Severity.WARNING,
+                message=(
+                    f"the metric reads {table}.{column}, which the dataset does not declare "
+                    f"as a field. AQL resolves a reference against declared fields only, so "
+                    f"{column!r} is added to model {target.aml_fqn!r} as a hidden dimension "
+                    f"over the column of that name"
+                ),
+                object_ref=scope,
+                remedy=f"declare {column!r} as a field of {table!r} in Ossie",
+            )
+        return f"{target.aml_fqn}.{name}"
+
+    def dataset_metric(self, payload: dict[str, Any]) -> Block | None:
+        """One Ossie metric as a dataset-level AML `metric`.
+
+        AML accepts only an `@aql` body here. The compiler rejects `@sql` with
+        "Incompatible property 'definition' of 'Metric'", so a cross-model
+        metric carrying Ossie SQL has no AML form at all.
+        """
+        name = payload["name"]
+        scope = name
+        data = stash.read(payload)
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        if dialect != AQL_DIALECT:
+            rendered = self.as_aql(text, dialect, scope)
+            if rendered is None:
+                return None
+            text = rendered
+        block = Block(f"metric {self.name_in_aml(name, scope)}")
+        block.text("label", data.get("label") or titleize(name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+        block.heredoc("definition", "aql", text)
+        block.text("format", data.get("format"))
+        return block
+
+    # -- models -----------------------------------------------------------
+
+    def model_file(self, model: Model) -> str:
+        payload = model.payload
+        data = model.stash
+        scope = model.ossie_name
+        is_query = data.get("aml_type") == "QueryModel" or (
+            "aml_type" not in data and bool(interpolation.query_forms_used(payload.get("source", "")))
+        )
+        source = payload.get("source", "")
+        if "aml_type" not in data and not is_query:
+            is_query = _looks_like_query(source)
+
+        block = Block(f"Model {model.aml_name}")
+        block.property("type", quote("query" if is_query else "table"))
+        block.text("label", data.get("label") or titleize(model.aml_name))
+        block.text("description", payload.get("description"))
+        block.text("data_source_name", data.get("data_source_name") or self.data_source_name)
+        if is_query:
+            referenced = _models_referenced(source)
+            if referenced:
+                block.property("models", f"[{', '.join(sorted(referenced))}]")
+            block.blank()
+            block.heredoc("query", "sql", source)
+        else:
+            block.text("table_name", data.get("table_name") or source)
+
+        for param in data.get("param") or []:
+            block.blank()
+            param_block = block.block(f"param {self.name_in_aml(param['name'], scope)}")
+            param_block.text("label", param.get("label") or titleize(param["name"]))
+            param_block.property("type", quote(param.get("type") or FALLBACK_TYPE))
+
+        persistence = data.get("persistence")
+        if persistence:
+            block.blank()
+            _write_persistence(block, persistence)
+
+        primary_key = set(payload.get("primary_key") or [])
+        for field in payload.get("fields") or []:
+            if stash.read(field).get("scope") == "dataset":
+                continue
+            block.blank()
+            block.lines.append(self.dimension(model, field, primary_key))
+
+        for metric in model.measures:
+            block.blank()
+            block.lines.append(self.measure(model, metric))
+
+        for column in model.borrowed:
+            block.blank()
+            borrowed = block.block(f"dimension {column}")
+            borrowed.text("label", titleize(column))
+            borrowed.property("type", quote(FALLBACK_TYPE_FOR_BORROWED))
+            borrowed.flag("hidden", True)
+            borrowed.heredoc("definition", "sql", interpolation.Source(column).to_aml())
+
+        owner = data.get("owner") or self.root_stash.get("owner")
+        if owner:
+            block.blank()
+            block.text("owner", owner)
+        return amlgen.document(block, license_header=True)
+
+    # -- dataset ----------------------------------------------------------
+
+    def relationship(self, payload: dict[str, Any]) -> str:

Review Comment:
   fixed in 17c2dbf



##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}
+
+
+class _Reverse:
+    def __init__(
+        self, document: dict[str, Any], data_source_name: str | None, sql_dialect: str
+    ):
+        self.document = document
+        self.sql_dialect = sql_dialect
+        self.issues = IssueLog()
+        self.root_stash = stash.read(document)
+        self.data_source_name = self.root_stash.get("data_source_name") or data_source_name
+        if not self.data_source_name:
+            raise ConversionError(
+                "the document carries no HOLISTICS data_source_name, so one must be "
+                "supplied: pass --data-source-name naming the Holistics connection"
+            )
+
+        #: AML identifier to the Ossie name it was spelled from, so two names
+        #: that collapse onto one spelling fail rather than overwrite.
+        self._renamed: dict[str, str] = {}
+
+        datasets = _named_objects(document.get("datasets"), "datasets")
+        if not datasets:
+            raise ConversionError(
+                "the document declares no datasets, and the specification requires at least one"
+            )
+        for dataset in datasets:
+            _named_objects(dataset.get("fields"), f"datasets[{dataset['name']}].fields")
+        _named_objects(document.get("metrics"), "metrics")
+
+        self.models: list[Model] = []
+        for dataset in datasets:
+            name = dataset["name"]
+            data = stash.read(dataset)
+            self.models.append(
+                Model(
+                    ossie_name=name,
+                    fqn=data.get("fqn") or unflatten(name),
+                    payload=dataset,
+                    stash=data,
+                )
+            )
+        self.by_ossie_name = {m.ossie_name: m for m in self.models}
+
+        taken: dict[str, str] = {}
+        for model in self.models:
+            clash = taken.setdefault(model.aml_fqn, model.ossie_name)
+            if clash != model.ossie_name:
+                raise ConversionError(
+                    f"datasets {clash!r} and {model.ossie_name!r} both spell as the AML "
+                    f"model {model.aml_fqn!r}; rename one of them in Ossie"
+                )
+
+        self.dataset_name = self._dataset_name()
+
+        #: Every metric that belongs on a model, indexed by Ossie metric name,
+        #: alongside the AML measure name it is written as.
+        self.metric_owner: dict[str, Model] = {}
+        self.metric_aml_name: dict[str, str] = {}
+        self.dataset_metrics: list[dict[str, Any]] = []
+        self._metric_payloads: dict[str, dict[str, Any]] = {}
+        self._metric_datasets: dict[str, Any] = {}
+        self._cyclic_metrics: set[str] = set()
+        self._place_metrics()
+
+    # -- placement --------------------------------------------------------
+
+    def _place_metrics(self) -> None:
+        """Decide where each Ossie metric goes: on a model, or on the dataset.
+
+        A stashed `model` settles it. Without one, the expression decides: a
+        body naming exactly one dataset becomes a measure on that model, and a
+        body naming several becomes a dataset-level metric, which is the only
+        AML construct that spans models. A body may also name another metric,
+        and `_scan_for_datasets` covers what that counts as.
+        """
+        metrics = self.document.get("metrics") or []
+        for metric in metrics:
+            name = metric.get("name")
+            self.metric_aml_name[name] = stash.read(metric).get("aml_name") or name
+            self._metric_payloads[name] = metric
+        for metric in metrics:
+            name = metric.get("name")
+            named = self._datasets_named(name) or frozenset()
+            owner = self.by_ossie_name[next(iter(named))] if len(named) == 1 else None
+            if owner is None:
+                self.dataset_metrics.append(metric)
+            else:
+                owner.measures.append(metric)
+                self.metric_owner[name] = owner
+        self._report_metric_cycles()
+
+    def _datasets_named(self, name: str) -> frozenset[str] | None:
+        """The Ossie datasets metric `name` resolves to, or None when that is unknown.
+
+        None covers every reading that cannot put the metric on a single model:
+        an AQL body, Ossie SQL this converter cannot read, and a reference cycle.
+        """
+        resolved = self._metric_datasets.get(name, _UNVISITED)
+        if resolved is _RESOLVING:
+            self._cyclic_metrics.add(name)
+            return None
+        if resolved is not _UNVISITED:
+            return resolved
+        self._metric_datasets[name] = _RESOLVING
+        result = self._scan_for_datasets(name)
+        self._metric_datasets[name] = result
+        return result
+
+    def _scan_for_datasets(self, name: str) -> frozenset[str] | None:
+        """Which datasets one metric body names, directly or through a metric.
+
+        An Ossie metric body may name another metric instead of a column, as
+        `cities__upstream_measure + 1` in `tests/fixtures/ecommerce` does. That
+        body names no dataset of its own, and the datasets the metric it
+        references resolves to stand in for it. Without that substitution a
+        metric built only from other metrics lands on the dataset, where AML
+        takes an AQL body, and the Ossie SQL name it was written with does not
+        resolve.
+        """
+        metric = self._metric_payloads[name]
+        data = stash.read(metric)
+        owner_fqn = data.get("model")
+        if owner_fqn:
+            owner = next((m for m in self.models if m.fqn == owner_fqn), None)
+            if owner is None:
+                raise ConversionError(
+                    f"metric {name!r} is stashed against model {owner_fqn!r}, "
+                    f"which is not a dataset in this document"
+                )
+            return frozenset({owner.ossie_name})
+        available = dialects_of(metric.get("expression"))
+        if AQL_DIALECT in available:
+            return None
+        dialect = next(
+            (d for d in (self.sql_dialect, *PORTABLE_DIALECTS) if d in available), None
+        )
+        if dialect is None:
+            return None
+        try:
+            references = sqlrefs.columns(available[dialect], dialect)
+        except sqlrefs.UnparseableSQL:
+            return None
+        named = {c.table for c in references if c.table in self.by_ossie_name}
+        for reference in references:
+            if reference.table or reference.name not in self._metric_payloads:
+                continue
+            through = self._datasets_named(reference.name)
+            if through is None:
+                return None
+            named |= through
+        return frozenset(named)
+
+    def _report_metric_cycles(self) -> None:
+        for name in sorted(self._cyclic_metrics):
+            self.issues.add(
+                code=ISSUE_METRIC_CYCLE,
+                severity=Severity.ERROR,
+                message=(
+                    f"metric {name!r} references itself through another metric. Holistics "
+                    f"inlines one metric into the body of the next, so a cycle has no warehouse SQL, "
+                    f"and `holistics aml validate` accepts the file without catching it"
+                ),
+                object_ref=name,
+                remedy="break the cycle in Ossie",
+            )
+
+    # -- names ------------------------------------------------------------
+
+    def _dataset_name(self) -> str:
+        """The AML `Dataset` name, moved aside when a model already has it.
+
+        Ossie keeps the semantic model's name and its dataset names in separate
+        namespaces, so a document may use one name for both. Three fixtures in
+        this repository do, including
+        `converters/cube/tests/fixtures/databricks_ossie.yaml`, whose root name
+        and first dataset are both `orders`. AML has one namespace for `Dataset`
+        and `Model`, and rejects the pair with "Duplicated name 'orders'".
+
+        Nothing references the AML dataset name. Models reference each other and
+        relationships reference models, so the dataset is the safe side to move.
+        """
+        name = self.root_stash.get("fqn") or self.document.get("name")
+        if not name:
+            raise ConversionError("the document has no name")
+        spelled = self.name_in_aml(name, str(name))
+        taken = {model.aml_fqn for model in self.models} | {
+            model.aml_name for model in self.models
+        }
+        if spelled not in taken:
+            return spelled
+        candidate, suffix = f"{spelled}_dataset", 2
+        while candidate in taken:
+            candidate, suffix = f"{spelled}_dataset_{suffix}", suffix + 1
+        self.issues.add(
+            code=ISSUE_DATASET_RENAMED,
+            severity=Severity.WARNING,
+            message=(
+                f"a model is already named {spelled!r}, and AML holds Dataset and Model "
+                f"in one namespace, so the dataset is written as {candidate!r}"
+            ),
+            object_ref=str(name),
+            remedy="rename the semantic model or the dataset in Ossie",
+        )
+        return candidate
+
+    def name_in_aml(self, name: str, scope: str) -> str:
+        """An Ossie name as the AML identifier it is written as.
+
+        Lookups elsewhere stay keyed on the Ossie name, because that is what an
+        expression references. Only the output spelling changes, and every site
+        that writes a name goes through here, so a declaration and a reference
+        to it cannot disagree.
+        """
+        spelled = sanitize(name)
+        if spelled != name:
+            previous = self._renamed.setdefault(spelled, name)
+            if previous != name:
+                raise ConversionError(
+                    f"{scope}: {name!r} and {previous!r} both spell as the AML "
+                    f"identifier {spelled!r}; rename one of them in Ossie"
+                )
+            self.issues.add(
+                code=ISSUE_RENAMED,
+                severity=Severity.WARNING,
+                message=(
+                    f"{name!r} is not a legal AML identifier and is written as "
+                    f"{spelled!r}. AML allows letters, digits and underscore, and no "
+                    f"leading digit"
+                ),
+                object_ref=scope,
+                remedy=f"rename it to {spelled!r} in Ossie to keep the two in step",
+            )
+        return spelled
+
+    # -- expressions ------------------------------------------------------
+
+    def pick_body(self, expression: Any, scope: str) -> tuple[str, str]:
+        """The body to write and the dialect it is in, after any rendering.
+
+        AQL wins outright. It came out of AML unchanged and goes back unchanged.
+
+        For Ossie SQL the target is `--sql-dialect`, the warehouse the Holistics
+        connection reads. A body already in that dialect is written as it
+        stands. Otherwise a portable body is rendered into the target with
+        sqlglot, because the alternative is AML that will not run. An expression
+        offering neither has no body this connection can execute, and the
+        converter says so rather than writing Holistics SQL for the wrong warehouse.
+        """
+        available = dialects_of(expression)
+        if AQL_DIALECT in available:
+            return AQL_DIALECT, available[AQL_DIALECT]
+        if self.sql_dialect in available:
+            return self.sql_dialect, available[self.sql_dialect]
+
+        source = next((d for d in PORTABLE_DIALECTS if d in available), None)
+        if source is not None:
+            try:
+                rendered = sqlrefs.transpile(available[source], source, self.sql_dialect)
+            except sqlrefs.UnparseableSQL as exc:
+                self.issues.add(
+                    code=ISSUE_UNPARSEABLE_SQL,
+                    severity=Severity.ERROR,
+                    message=(
+                        f"the {source} body cannot be rendered as {self.sql_dialect} ({exc}), "
+                        f"so it is written unchanged and may not run"
+                    ),
+                    object_ref=scope,
+                    remedy=f"add a {self.sql_dialect} expression, or fix the {source} one",
+                )
+                return source, available[source]
+            self.issues.add(
+                code=ISSUE_TRANSPILED,
+                severity=Severity.WARNING,
+                message=(
+                    f"no {self.sql_dialect} expression, so the {source} one was rendered "
+                    f"into it: {available[source]!r} became {rendered!r}"
+                ),
+                object_ref=scope,
+                remedy=f"add a {self.sql_dialect} expression to keep the body exact",
+            )
+            return self.sql_dialect, rendered
+
+        fallback = next(iter(available))
+        self.issues.add(
+            code=ISSUE_NO_USABLE_DIALECT,
+            severity=Severity.ERROR,
+            message=(
+                f"the expression offers {', '.join(sorted(available))} and the connection "
+                f"reads {self.sql_dialect}, with no portable body to render from, so the "
+                f"{fallback} body is written unchanged and will not run"
+            ),
+            object_ref=scope,
+            remedy=f"add a {self.sql_dialect} or ANSI_SQL expression",
+        )
+        return fallback, available[fallback]
+
+    def definition(self, block: Block, expression: Any, model: Model, scope: str) -> None:
+        """Write a `definition` property for a field or a measure."""
+        dialect, text = self.pick_body(expression, scope)
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+            return
+        block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+
+    def to_aml_sql(self, expression: str, dialect: str, model: Model, scope: str) -> str:
+        """An Ossie SQL expression with its references written as AML interpolation.
+
+        A bare column name does compile as AML, but AQL reads the interpolation
+        to learn which field the body depends on. A body without it loses the
+        query rewriting and the optimisation that link drives, so this restores
+        every reference rather than passing the SQL through.
+        """
+        if dialect in sqlrefs.NOT_SQL or not sqlrefs.AVAILABLE:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body is tagged {dialect!r}, which is not Ossie SQL this converter can "
+                    f"read, so its field references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="supply an ANSI_SQL or warehouse-SQL dialect for this expression",
+            )
+            return expression
+        grouping = sqlrefs.window_grouping(expression, dialect)
+        if grouping:
+            self.issues.add(
+                code=ISSUE_WINDOW_NEEDS_GROUPING,
+                severity=Severity.WARNING,
+                message=(
+                    f"the body has a window function whose frame reads "
+                    f"{', '.join(grouping)}. AML carries it as written, and the warehouse SQL "
+                    f"it generates is valid only for a query that groups by those. A query "
+                    f"that does not, a grand total for one, produces warehouse SQL the "
+                    f"database rejects, and Holistics does not check this at conversion time"
+                ),
+                object_ref=scope,
+                remedy="query it only alongside those fields, or rewrite the body in AQL",
+            )
+        try:
+            return sqlrefs.rewrite(
+                expression, dialect, lambda column: self.to_interpolation(column, model, scope)
+            )
+        except sqlrefs.UnparseableSQL as exc:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"sqlglot cannot read the body as {dialect} ({exc}), so its field "
+                    f"references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="fix the expression, or convert it by hand",
+            )
+            return expression
+
+    def to_interpolation(self, column: sqlrefs.ColumnReference, model: Model, scope: str) -> str:
+        """One Ossie column reference as the AML interpolation it came from."""
+        if not column.table:
+            if column.name in self.metric_aml_name:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Source(column.name).to_aml()
+
+        target = self.by_ossie_name.get(column.table)
+        if target is None:
+            self.issues.add(
+                code=ISSUE_UNKNOWN_QUALIFIER,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body qualifies {column.name!r} with {column.table!r}, which is not "
+                    f"a dataset in this document, so it is left unresolved"
+                ),
+                object_ref=scope,
+                remedy="qualify the reference with a dataset name, or drop the field",
+            )
+            return f"{column.table}.{column.name}"
+        if target is model:
+            # A qualifier naming this model usually names one of its fields. It
+            # can also name a metric this converter put somewhere else, and a
+            # sibling reference to that spells a field the model does not have.
+            if column.name in self.metric_aml_name and self.metric_owner.get(column.name) is not model:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Sibling(self.name_in_aml(column.name, scope)).to_aml()
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body names {column.table}.{column.name}, a field of another dataset. A `@sql` "
+                f"body resolves inside one model, and Holistics rejects this at SQL generation "
+                f"with \"Cannot refer to external field in TableModel/QueryModel\" even though "
+                f"`holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="move the reference into a dimension on its own model, or rewrite the body in AQL",
+        )
+        return interpolation.ModelField(target.aml_fqn, self.name_in_aml(column.name, scope)).to_aml()
+
+    def _measure_reference(self, metric_name: str, model: Model, scope: str) -> str:
+        owner = self.metric_owner.get(metric_name)
+        aml_name = self.metric_aml_name[metric_name]
+        if owner is model:
+            return interpolation.Sibling(self.name_in_aml(aml_name, scope)).to_aml()
+        if owner is None:
+            self.issues.add(
+                code=ISSUE_CROSS_MODEL_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body references the dataset-level metric {metric_name!r}. A `@sql` "
+                    f"body resolves inside one model, so there is no AML spelling for it"
+                ),
+                object_ref=scope,
+                remedy="rewrite the expression in AQL, which does span models",
+            )
+            return metric_name
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body references {metric_name!r}, a measure of model {owner.aml_fqn!r}. A "
+                f"`@sql` body resolves inside one model, and Holistics rejects this at SQL "
+                f"generation with \"Cannot refer to external field in TableModel/QueryModel\" "
+                f"even though `holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="rewrite the expression in AQL, which does span models",
+        )
+        return interpolation.ModelField(owner.aml_fqn, self.name_in_aml(aml_name, scope)).to_aml()
+
+    # -- fields -----------------------------------------------------------
+
+    def aml_type(
+        self, payload: dict[str, Any], data: dict[str, Any], scope: str, model: Model | None = None
+    ) -> str:
+        stashed = data.get("type")
+        if stashed:
+            return stashed
+        datatype = payload.get("datatype")
+        mapped = OSSIE_TO_AML_TYPE.get(datatype) if datatype else None
+        if mapped:
+            return mapped
+        if model is not None and payload["name"] in model.numeric:
+            # A metric aggregates this field with `sum` or `avg`, so it is a
+            # number whatever the document failed to say.
+            return "number"
+        self.issues.add(
+            code=ISSUE_ASSUMED_TYPE,
+            severity=Severity.WARNING,
+            message=(
+                f"AML requires a type and the Ossie datatype is {datatype!r}, "
+                f"so {FALLBACK_TYPE!r} is written"
+            ),
+            object_ref=scope,
+            remedy="set a datatype on the field, or edit the AML type after conversion",
+        )
+        return FALLBACK_TYPE
+
+    def common_properties(
+        self,
+        block: Block,
+        payload: dict[str, Any],
+        data: dict[str, Any],
+        scope: str,
+        model: Model | None = None,
+    ) -> None:
+        block.text("label", data.get("label") or titleize(payload["name"]))
+        block.property("type", quote(self.aml_type(payload, data, scope, model)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+    def dimension(self, model: Model, payload: dict[str, Any], primary_key: set[str]) -> Block:
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        block.flag("primary_key", name in primary_key)
+        return block
+
+    def dataset_dimension(self, model: Model, payload: dict[str, Any]) -> Block:
+        """A field the forward path took from a dataset-level AML dimension."""
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        block.property("model", model.reference)
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        return block
+
+    def measure(self, model: Model, payload: dict[str, Any]) -> Block:
+        """One Ossie metric as a `measure` on its owning model.
+
+        `aggregation_type` and the body compose into one Ossie expression on the
+        way out, so this splits them back apart. When the stashed aggregation
+        does not wrap the whole expression, the expression was edited after the
+        forward path wrote it, and `custom` keeps it whole rather than letting
+        the measure aggregate twice.
+        """
+        metric_name = payload["name"]
+        aml_name = self.metric_aml_name[metric_name]
+        scope = f"{model.ossie_name}.{aml_name}"
+        data = stash.read(payload)
+        block = Block(f"measure {self.name_in_aml(aml_name, scope)}")
+        block.text("label", data.get("label") or titleize(aml_name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        aggregation = data.get("aggregation_type") or CUSTOM_AGGREGATION
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+        else:
+            if aggregation in AGGREGATIONS:
+                inner = strip_aggregation(aggregation, text)
+                if inner is None:
+                    self.issues.add(
+                        code=ISSUE_AGGREGATION_NOT_STRIPPED,
+                        severity=Severity.WARNING,
+                        message=(
+                            f"the stashed aggregation {aggregation!r} does not wrap the whole "
+                            f"expression, so the measure is written as 'custom' with the "
+                            f"expression kept whole"
+                        ),
+                        object_ref=scope,
+                        remedy="check the expression against the aggregation",
+                    )
+                    aggregation = CUSTOM_AGGREGATION
+                else:
+                    text = inner
+            block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+        block.property("aggregation_type", quote(aggregation))
+        block.text("format", data.get("format"))
+        return block
+
+    def as_aql(self, text: str, dialect: str, scope: str) -> str | None:
+        """A dataset-level metric's Ossie SQL body rendered as AQL, or None if it cannot be.
+
+        AML accepts only `@aql` here, so an Ossie SQL body either becomes AQL or has no
+        AML form at all. `aql.translate` is a name map over functions this
+        converter has paired with an AQL equivalent. Anything outside that table
+        raises `Untranslatable`, and the metric is dropped with an ERROR.
+        """
+        try:
+            rendered, numeric = aql.translate(
+                text, dialect, lambda table, column: self.aql_reference(table, column, scope)
+            )
+        except aql.Untranslatable as exc:
+            self.issues.add(
+                code=ISSUE_METRIC_NOT_TRANSLATED,
+                severity=Severity.ERROR,
+                message=(
+                    f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                    f"converter did not translate this {dialect} body, and the metric is "
+                    f"dropped. {exc}"
+                ),
+                object_ref=scope,
+                remedy="rewrite the metric in AQL, or scope it to a single dataset",
+            )
+            return None
+        self.issues.add(
+            code=ISSUE_RENDERED_AS_AQL,
+            severity=Severity.WARNING,
+            message=(
+                f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                f"{dialect} expression was rendered as AQL: {text!r} became {rendered!r}"
+            ),
+            object_ref=scope,
+            remedy="check the AQL against the Ossie SQL it came from",
+        )
+        for table, column in numeric:
+            target = self.by_ossie_name.get(table)
+            if target is not None:
+                target.numeric.add(self.name_in_aml(column, scope))
+        return rendered
+
+    def aql_reference(self, table: str, column: str, scope: str) -> str:
+        """One column of an Ossie SQL metric body as the AQL reference it becomes.
+
+        AQL names a field `model.field`, which is the shape the Ossie expression
+        already uses, so this maps the Ossie dataset name onto the AML model
+        name and keeps the field name.
+
+        An Ossie SQL body may name a warehouse column the document does not declare as
+        a field. `SUM(orders.subtotal) / COUNT(DISTINCT customers.customer_id)`
+        in `converters/nvidia/tests/fixtures/sales.ossie.yaml` is one: `orders`
+        declares no `subtotal`. Ossie SQL resolves that against the table, and AQL
+        does not, answering `Field `subtotal` not found in model `orders``. So
+        the column becomes a hidden dimension on that model, and the AQL
+        reference points at it.
+        """
+        if not table:
+            # An unqualified name that is a metric is a metric reference, which
+            # AQL takes: a dataset-level one by its bare name, and a measure by
+            # the model that holds it.
+            if column in self.metric_aml_name:
+                referenced = self.name_in_aml(self.metric_aml_name[column], scope)
+                owner = self.metric_owner.get(column)
+                return referenced if owner is None else f"{owner.aml_fqn}.{referenced}"
+            raise aql.Untranslatable(
+                f"{column!r} names no dataset, and a metric spanning models has no single "
+                f"model to resolve it against."
+            )
+        target = self.by_ossie_name.get(table)
+        if target is None:
+            raise aql.Untranslatable(f"{table!r} is not a dataset in this document.")
+        name = self.name_in_aml(column, scope)
+        declared = {
+            field["name"] for field in target.payload.get("fields") or []
+        } | {self.metric_aml_name[m["name"]] for m in target.measures}
+        if name not in declared and name not in target.borrowed:

Review Comment:
   fixed in e35d98e



##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}

Review Comment:
   fixed in 11d898e



##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}
+
+
+class _Reverse:
+    def __init__(
+        self, document: dict[str, Any], data_source_name: str | None, sql_dialect: str
+    ):
+        self.document = document
+        self.sql_dialect = sql_dialect
+        self.issues = IssueLog()
+        self.root_stash = stash.read(document)
+        self.data_source_name = self.root_stash.get("data_source_name") or data_source_name
+        if not self.data_source_name:
+            raise ConversionError(
+                "the document carries no HOLISTICS data_source_name, so one must be "
+                "supplied: pass --data-source-name naming the Holistics connection"
+            )
+
+        #: AML identifier to the Ossie name it was spelled from, so two names
+        #: that collapse onto one spelling fail rather than overwrite.
+        self._renamed: dict[str, str] = {}
+
+        datasets = _named_objects(document.get("datasets"), "datasets")
+        if not datasets:
+            raise ConversionError(
+                "the document declares no datasets, and the specification requires at least one"
+            )
+        for dataset in datasets:
+            _named_objects(dataset.get("fields"), f"datasets[{dataset['name']}].fields")
+        _named_objects(document.get("metrics"), "metrics")
+
+        self.models: list[Model] = []
+        for dataset in datasets:
+            name = dataset["name"]
+            data = stash.read(dataset)
+            self.models.append(
+                Model(
+                    ossie_name=name,
+                    fqn=data.get("fqn") or unflatten(name),
+                    payload=dataset,
+                    stash=data,
+                )
+            )
+        self.by_ossie_name = {m.ossie_name: m for m in self.models}
+
+        taken: dict[str, str] = {}
+        for model in self.models:
+            clash = taken.setdefault(model.aml_fqn, model.ossie_name)
+            if clash != model.ossie_name:
+                raise ConversionError(
+                    f"datasets {clash!r} and {model.ossie_name!r} both spell as the AML "
+                    f"model {model.aml_fqn!r}; rename one of them in Ossie"
+                )
+
+        self.dataset_name = self._dataset_name()
+
+        #: Every metric that belongs on a model, indexed by Ossie metric name,
+        #: alongside the AML measure name it is written as.
+        self.metric_owner: dict[str, Model] = {}
+        self.metric_aml_name: dict[str, str] = {}
+        self.dataset_metrics: list[dict[str, Any]] = []
+        self._metric_payloads: dict[str, dict[str, Any]] = {}
+        self._metric_datasets: dict[str, Any] = {}
+        self._cyclic_metrics: set[str] = set()
+        self._place_metrics()
+
+    # -- placement --------------------------------------------------------
+
+    def _place_metrics(self) -> None:
+        """Decide where each Ossie metric goes: on a model, or on the dataset.
+
+        A stashed `model` settles it. Without one, the expression decides: a
+        body naming exactly one dataset becomes a measure on that model, and a
+        body naming several becomes a dataset-level metric, which is the only
+        AML construct that spans models. A body may also name another metric,
+        and `_scan_for_datasets` covers what that counts as.
+        """
+        metrics = self.document.get("metrics") or []
+        for metric in metrics:
+            name = metric.get("name")
+            self.metric_aml_name[name] = stash.read(metric).get("aml_name") or name
+            self._metric_payloads[name] = metric
+        for metric in metrics:
+            name = metric.get("name")
+            named = self._datasets_named(name) or frozenset()
+            owner = self.by_ossie_name[next(iter(named))] if len(named) == 1 else None
+            if owner is None:
+                self.dataset_metrics.append(metric)
+            else:
+                owner.measures.append(metric)
+                self.metric_owner[name] = owner
+        self._report_metric_cycles()
+
+    def _datasets_named(self, name: str) -> frozenset[str] | None:
+        """The Ossie datasets metric `name` resolves to, or None when that is unknown.
+
+        None covers every reading that cannot put the metric on a single model:
+        an AQL body, Ossie SQL this converter cannot read, and a reference cycle.
+        """
+        resolved = self._metric_datasets.get(name, _UNVISITED)
+        if resolved is _RESOLVING:
+            self._cyclic_metrics.add(name)
+            return None
+        if resolved is not _UNVISITED:
+            return resolved
+        self._metric_datasets[name] = _RESOLVING
+        result = self._scan_for_datasets(name)
+        self._metric_datasets[name] = result
+        return result
+
+    def _scan_for_datasets(self, name: str) -> frozenset[str] | None:
+        """Which datasets one metric body names, directly or through a metric.
+
+        An Ossie metric body may name another metric instead of a column, as
+        `cities__upstream_measure + 1` in `tests/fixtures/ecommerce` does. That
+        body names no dataset of its own, and the datasets the metric it
+        references resolves to stand in for it. Without that substitution a
+        metric built only from other metrics lands on the dataset, where AML
+        takes an AQL body, and the Ossie SQL name it was written with does not
+        resolve.
+        """
+        metric = self._metric_payloads[name]
+        data = stash.read(metric)
+        owner_fqn = data.get("model")
+        if owner_fqn:
+            owner = next((m for m in self.models if m.fqn == owner_fqn), None)
+            if owner is None:
+                raise ConversionError(
+                    f"metric {name!r} is stashed against model {owner_fqn!r}, "
+                    f"which is not a dataset in this document"
+                )
+            return frozenset({owner.ossie_name})
+        available = dialects_of(metric.get("expression"))
+        if AQL_DIALECT in available:
+            return None
+        dialect = next(
+            (d for d in (self.sql_dialect, *PORTABLE_DIALECTS) if d in available), None
+        )
+        if dialect is None:
+            return None
+        try:
+            references = sqlrefs.columns(available[dialect], dialect)
+        except sqlrefs.UnparseableSQL:
+            return None
+        named = {c.table for c in references if c.table in self.by_ossie_name}
+        for reference in references:
+            if reference.table or reference.name not in self._metric_payloads:
+                continue
+            through = self._datasets_named(reference.name)
+            if through is None:
+                return None
+            named |= through
+        return frozenset(named)
+
+    def _report_metric_cycles(self) -> None:
+        for name in sorted(self._cyclic_metrics):
+            self.issues.add(
+                code=ISSUE_METRIC_CYCLE,
+                severity=Severity.ERROR,
+                message=(
+                    f"metric {name!r} references itself through another metric. Holistics "
+                    f"inlines one metric into the body of the next, so a cycle has no warehouse SQL, "
+                    f"and `holistics aml validate` accepts the file without catching it"
+                ),
+                object_ref=name,
+                remedy="break the cycle in Ossie",
+            )
+
+    # -- names ------------------------------------------------------------
+
+    def _dataset_name(self) -> str:
+        """The AML `Dataset` name, moved aside when a model already has it.
+
+        Ossie keeps the semantic model's name and its dataset names in separate
+        namespaces, so a document may use one name for both. Three fixtures in
+        this repository do, including
+        `converters/cube/tests/fixtures/databricks_ossie.yaml`, whose root name
+        and first dataset are both `orders`. AML has one namespace for `Dataset`
+        and `Model`, and rejects the pair with "Duplicated name 'orders'".
+
+        Nothing references the AML dataset name. Models reference each other and
+        relationships reference models, so the dataset is the safe side to move.
+        """
+        name = self.root_stash.get("fqn") or self.document.get("name")
+        if not name:
+            raise ConversionError("the document has no name")
+        spelled = self.name_in_aml(name, str(name))
+        taken = {model.aml_fqn for model in self.models} | {
+            model.aml_name for model in self.models
+        }
+        if spelled not in taken:
+            return spelled
+        candidate, suffix = f"{spelled}_dataset", 2
+        while candidate in taken:
+            candidate, suffix = f"{spelled}_dataset_{suffix}", suffix + 1
+        self.issues.add(
+            code=ISSUE_DATASET_RENAMED,
+            severity=Severity.WARNING,
+            message=(
+                f"a model is already named {spelled!r}, and AML holds Dataset and Model "
+                f"in one namespace, so the dataset is written as {candidate!r}"
+            ),
+            object_ref=str(name),
+            remedy="rename the semantic model or the dataset in Ossie",
+        )
+        return candidate
+
+    def name_in_aml(self, name: str, scope: str) -> str:
+        """An Ossie name as the AML identifier it is written as.
+
+        Lookups elsewhere stay keyed on the Ossie name, because that is what an
+        expression references. Only the output spelling changes, and every site
+        that writes a name goes through here, so a declaration and a reference
+        to it cannot disagree.
+        """
+        spelled = sanitize(name)
+        if spelled != name:
+            previous = self._renamed.setdefault(spelled, name)
+            if previous != name:
+                raise ConversionError(
+                    f"{scope}: {name!r} and {previous!r} both spell as the AML "
+                    f"identifier {spelled!r}; rename one of them in Ossie"
+                )
+            self.issues.add(
+                code=ISSUE_RENAMED,
+                severity=Severity.WARNING,
+                message=(
+                    f"{name!r} is not a legal AML identifier and is written as "
+                    f"{spelled!r}. AML allows letters, digits and underscore, and no "
+                    f"leading digit"
+                ),
+                object_ref=scope,
+                remedy=f"rename it to {spelled!r} in Ossie to keep the two in step",
+            )
+        return spelled
+
+    # -- expressions ------------------------------------------------------
+
+    def pick_body(self, expression: Any, scope: str) -> tuple[str, str]:
+        """The body to write and the dialect it is in, after any rendering.
+
+        AQL wins outright. It came out of AML unchanged and goes back unchanged.
+
+        For Ossie SQL the target is `--sql-dialect`, the warehouse the Holistics
+        connection reads. A body already in that dialect is written as it
+        stands. Otherwise a portable body is rendered into the target with
+        sqlglot, because the alternative is AML that will not run. An expression
+        offering neither has no body this connection can execute, and the
+        converter says so rather than writing Holistics SQL for the wrong warehouse.
+        """
+        available = dialects_of(expression)
+        if AQL_DIALECT in available:
+            return AQL_DIALECT, available[AQL_DIALECT]
+        if self.sql_dialect in available:
+            return self.sql_dialect, available[self.sql_dialect]
+
+        source = next((d for d in PORTABLE_DIALECTS if d in available), None)
+        if source is not None:
+            try:
+                rendered = sqlrefs.transpile(available[source], source, self.sql_dialect)
+            except sqlrefs.UnparseableSQL as exc:
+                self.issues.add(
+                    code=ISSUE_UNPARSEABLE_SQL,
+                    severity=Severity.ERROR,
+                    message=(
+                        f"the {source} body cannot be rendered as {self.sql_dialect} ({exc}), "
+                        f"so it is written unchanged and may not run"
+                    ),
+                    object_ref=scope,
+                    remedy=f"add a {self.sql_dialect} expression, or fix the {source} one",
+                )
+                return source, available[source]
+            self.issues.add(
+                code=ISSUE_TRANSPILED,
+                severity=Severity.WARNING,
+                message=(
+                    f"no {self.sql_dialect} expression, so the {source} one was rendered "
+                    f"into it: {available[source]!r} became {rendered!r}"
+                ),
+                object_ref=scope,
+                remedy=f"add a {self.sql_dialect} expression to keep the body exact",
+            )
+            return self.sql_dialect, rendered
+
+        fallback = next(iter(available))
+        self.issues.add(
+            code=ISSUE_NO_USABLE_DIALECT,
+            severity=Severity.ERROR,
+            message=(
+                f"the expression offers {', '.join(sorted(available))} and the connection "
+                f"reads {self.sql_dialect}, with no portable body to render from, so the "
+                f"{fallback} body is written unchanged and will not run"
+            ),
+            object_ref=scope,
+            remedy=f"add a {self.sql_dialect} or ANSI_SQL expression",
+        )
+        return fallback, available[fallback]
+
+    def definition(self, block: Block, expression: Any, model: Model, scope: str) -> None:
+        """Write a `definition` property for a field or a measure."""
+        dialect, text = self.pick_body(expression, scope)
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+            return
+        block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+
+    def to_aml_sql(self, expression: str, dialect: str, model: Model, scope: str) -> str:
+        """An Ossie SQL expression with its references written as AML interpolation.
+
+        A bare column name does compile as AML, but AQL reads the interpolation
+        to learn which field the body depends on. A body without it loses the
+        query rewriting and the optimisation that link drives, so this restores
+        every reference rather than passing the SQL through.
+        """
+        if dialect in sqlrefs.NOT_SQL or not sqlrefs.AVAILABLE:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body is tagged {dialect!r}, which is not Ossie SQL this converter can "
+                    f"read, so its field references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="supply an ANSI_SQL or warehouse-SQL dialect for this expression",
+            )
+            return expression
+        grouping = sqlrefs.window_grouping(expression, dialect)
+        if grouping:
+            self.issues.add(
+                code=ISSUE_WINDOW_NEEDS_GROUPING,
+                severity=Severity.WARNING,
+                message=(
+                    f"the body has a window function whose frame reads "
+                    f"{', '.join(grouping)}. AML carries it as written, and the warehouse SQL "
+                    f"it generates is valid only for a query that groups by those. A query "
+                    f"that does not, a grand total for one, produces warehouse SQL the "
+                    f"database rejects, and Holistics does not check this at conversion time"
+                ),
+                object_ref=scope,
+                remedy="query it only alongside those fields, or rewrite the body in AQL",
+            )
+        try:
+            return sqlrefs.rewrite(
+                expression, dialect, lambda column: self.to_interpolation(column, model, scope)
+            )
+        except sqlrefs.UnparseableSQL as exc:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"sqlglot cannot read the body as {dialect} ({exc}), so its field "
+                    f"references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="fix the expression, or convert it by hand",
+            )
+            return expression
+
+    def to_interpolation(self, column: sqlrefs.ColumnReference, model: Model, scope: str) -> str:
+        """One Ossie column reference as the AML interpolation it came from."""
+        if not column.table:
+            if column.name in self.metric_aml_name:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Source(column.name).to_aml()
+
+        target = self.by_ossie_name.get(column.table)
+        if target is None:
+            self.issues.add(
+                code=ISSUE_UNKNOWN_QUALIFIER,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body qualifies {column.name!r} with {column.table!r}, which is not "
+                    f"a dataset in this document, so it is left unresolved"
+                ),
+                object_ref=scope,
+                remedy="qualify the reference with a dataset name, or drop the field",
+            )
+            return f"{column.table}.{column.name}"
+        if target is model:
+            # A qualifier naming this model usually names one of its fields. It
+            # can also name a metric this converter put somewhere else, and a
+            # sibling reference to that spells a field the model does not have.
+            if column.name in self.metric_aml_name and self.metric_owner.get(column.name) is not model:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Sibling(self.name_in_aml(column.name, scope)).to_aml()
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body names {column.table}.{column.name}, a field of another dataset. A `@sql` "
+                f"body resolves inside one model, and Holistics rejects this at SQL generation "
+                f"with \"Cannot refer to external field in TableModel/QueryModel\" even though "
+                f"`holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="move the reference into a dimension on its own model, or rewrite the body in AQL",
+        )
+        return interpolation.ModelField(target.aml_fqn, self.name_in_aml(column.name, scope)).to_aml()
+
+    def _measure_reference(self, metric_name: str, model: Model, scope: str) -> str:
+        owner = self.metric_owner.get(metric_name)
+        aml_name = self.metric_aml_name[metric_name]
+        if owner is model:
+            return interpolation.Sibling(self.name_in_aml(aml_name, scope)).to_aml()
+        if owner is None:
+            self.issues.add(
+                code=ISSUE_CROSS_MODEL_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body references the dataset-level metric {metric_name!r}. A `@sql` "
+                    f"body resolves inside one model, so there is no AML spelling for it"
+                ),
+                object_ref=scope,
+                remedy="rewrite the expression in AQL, which does span models",
+            )
+            return metric_name
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body references {metric_name!r}, a measure of model {owner.aml_fqn!r}. A "
+                f"`@sql` body resolves inside one model, and Holistics rejects this at SQL "
+                f"generation with \"Cannot refer to external field in TableModel/QueryModel\" "
+                f"even though `holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="rewrite the expression in AQL, which does span models",
+        )
+        return interpolation.ModelField(owner.aml_fqn, self.name_in_aml(aml_name, scope)).to_aml()
+
+    # -- fields -----------------------------------------------------------
+
+    def aml_type(
+        self, payload: dict[str, Any], data: dict[str, Any], scope: str, model: Model | None = None
+    ) -> str:
+        stashed = data.get("type")
+        if stashed:
+            return stashed
+        datatype = payload.get("datatype")
+        mapped = OSSIE_TO_AML_TYPE.get(datatype) if datatype else None
+        if mapped:
+            return mapped
+        if model is not None and payload["name"] in model.numeric:
+            # A metric aggregates this field with `sum` or `avg`, so it is a
+            # number whatever the document failed to say.
+            return "number"
+        self.issues.add(
+            code=ISSUE_ASSUMED_TYPE,
+            severity=Severity.WARNING,
+            message=(
+                f"AML requires a type and the Ossie datatype is {datatype!r}, "
+                f"so {FALLBACK_TYPE!r} is written"
+            ),
+            object_ref=scope,
+            remedy="set a datatype on the field, or edit the AML type after conversion",
+        )
+        return FALLBACK_TYPE
+
+    def common_properties(
+        self,
+        block: Block,
+        payload: dict[str, Any],
+        data: dict[str, Any],
+        scope: str,
+        model: Model | None = None,
+    ) -> None:
+        block.text("label", data.get("label") or titleize(payload["name"]))
+        block.property("type", quote(self.aml_type(payload, data, scope, model)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+    def dimension(self, model: Model, payload: dict[str, Any], primary_key: set[str]) -> Block:
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        block.flag("primary_key", name in primary_key)
+        return block
+
+    def dataset_dimension(self, model: Model, payload: dict[str, Any]) -> Block:
+        """A field the forward path took from a dataset-level AML dimension."""
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        block.property("model", model.reference)
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        return block
+
+    def measure(self, model: Model, payload: dict[str, Any]) -> Block:
+        """One Ossie metric as a `measure` on its owning model.
+
+        `aggregation_type` and the body compose into one Ossie expression on the
+        way out, so this splits them back apart. When the stashed aggregation
+        does not wrap the whole expression, the expression was edited after the
+        forward path wrote it, and `custom` keeps it whole rather than letting
+        the measure aggregate twice.
+        """
+        metric_name = payload["name"]
+        aml_name = self.metric_aml_name[metric_name]
+        scope = f"{model.ossie_name}.{aml_name}"
+        data = stash.read(payload)
+        block = Block(f"measure {self.name_in_aml(aml_name, scope)}")
+        block.text("label", data.get("label") or titleize(aml_name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        aggregation = data.get("aggregation_type") or CUSTOM_AGGREGATION
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+        else:
+            if aggregation in AGGREGATIONS:
+                inner = strip_aggregation(aggregation, text)
+                if inner is None:
+                    self.issues.add(
+                        code=ISSUE_AGGREGATION_NOT_STRIPPED,
+                        severity=Severity.WARNING,
+                        message=(
+                            f"the stashed aggregation {aggregation!r} does not wrap the whole "
+                            f"expression, so the measure is written as 'custom' with the "
+                            f"expression kept whole"
+                        ),
+                        object_ref=scope,
+                        remedy="check the expression against the aggregation",
+                    )
+                    aggregation = CUSTOM_AGGREGATION
+                else:
+                    text = inner
+            block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+        block.property("aggregation_type", quote(aggregation))
+        block.text("format", data.get("format"))
+        return block
+
+    def as_aql(self, text: str, dialect: str, scope: str) -> str | None:
+        """A dataset-level metric's Ossie SQL body rendered as AQL, or None if it cannot be.
+
+        AML accepts only `@aql` here, so an Ossie SQL body either becomes AQL or has no
+        AML form at all. `aql.translate` is a name map over functions this
+        converter has paired with an AQL equivalent. Anything outside that table
+        raises `Untranslatable`, and the metric is dropped with an ERROR.
+        """
+        try:
+            rendered, numeric = aql.translate(
+                text, dialect, lambda table, column: self.aql_reference(table, column, scope)
+            )
+        except aql.Untranslatable as exc:
+            self.issues.add(
+                code=ISSUE_METRIC_NOT_TRANSLATED,
+                severity=Severity.ERROR,
+                message=(
+                    f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                    f"converter did not translate this {dialect} body, and the metric is "
+                    f"dropped. {exc}"
+                ),
+                object_ref=scope,
+                remedy="rewrite the metric in AQL, or scope it to a single dataset",
+            )
+            return None
+        self.issues.add(
+            code=ISSUE_RENDERED_AS_AQL,
+            severity=Severity.WARNING,
+            message=(
+                f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                f"{dialect} expression was rendered as AQL: {text!r} became {rendered!r}"
+            ),
+            object_ref=scope,
+            remedy="check the AQL against the Ossie SQL it came from",
+        )
+        for table, column in numeric:
+            target = self.by_ossie_name.get(table)
+            if target is not None:
+                target.numeric.add(self.name_in_aml(column, scope))
+        return rendered
+
+    def aql_reference(self, table: str, column: str, scope: str) -> str:
+        """One column of an Ossie SQL metric body as the AQL reference it becomes.
+
+        AQL names a field `model.field`, which is the shape the Ossie expression
+        already uses, so this maps the Ossie dataset name onto the AML model
+        name and keeps the field name.
+
+        An Ossie SQL body may name a warehouse column the document does not declare as
+        a field. `SUM(orders.subtotal) / COUNT(DISTINCT customers.customer_id)`
+        in `converters/nvidia/tests/fixtures/sales.ossie.yaml` is one: `orders`
+        declares no `subtotal`. Ossie SQL resolves that against the table, and AQL
+        does not, answering `Field `subtotal` not found in model `orders``. So
+        the column becomes a hidden dimension on that model, and the AQL
+        reference points at it.
+        """
+        if not table:
+            # An unqualified name that is a metric is a metric reference, which
+            # AQL takes: a dataset-level one by its bare name, and a measure by
+            # the model that holds it.
+            if column in self.metric_aml_name:
+                referenced = self.name_in_aml(self.metric_aml_name[column], scope)
+                owner = self.metric_owner.get(column)
+                return referenced if owner is None else f"{owner.aml_fqn}.{referenced}"
+            raise aql.Untranslatable(
+                f"{column!r} names no dataset, and a metric spanning models has no single "
+                f"model to resolve it against."
+            )
+        target = self.by_ossie_name.get(table)
+        if target is None:
+            raise aql.Untranslatable(f"{table!r} is not a dataset in this document.")
+        name = self.name_in_aml(column, scope)
+        declared = {
+            field["name"] for field in target.payload.get("fields") or []
+        } | {self.metric_aml_name[m["name"]] for m in target.measures}
+        if name not in declared and name not in target.borrowed:
+            target.borrowed.append(name)
+            self.issues.add(
+                code=ISSUE_BORROWED_COLUMN,
+                severity=Severity.WARNING,
+                message=(
+                    f"the metric reads {table}.{column}, which the dataset does not declare "
+                    f"as a field. AQL resolves a reference against declared fields only, so "
+                    f"{column!r} is added to model {target.aml_fqn!r} as a hidden dimension "
+                    f"over the column of that name"
+                ),
+                object_ref=scope,
+                remedy=f"declare {column!r} as a field of {table!r} in Ossie",
+            )
+        return f"{target.aml_fqn}.{name}"
+
+    def dataset_metric(self, payload: dict[str, Any]) -> Block | None:
+        """One Ossie metric as a dataset-level AML `metric`.
+
+        AML accepts only an `@aql` body here. The compiler rejects `@sql` with
+        "Incompatible property 'definition' of 'Metric'", so a cross-model
+        metric carrying Ossie SQL has no AML form at all.
+        """
+        name = payload["name"]
+        scope = name
+        data = stash.read(payload)
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        if dialect != AQL_DIALECT:
+            rendered = self.as_aql(text, dialect, scope)
+            if rendered is None:
+                return None
+            text = rendered
+        block = Block(f"metric {self.name_in_aml(name, scope)}")
+        block.text("label", data.get("label") or titleize(name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+        block.heredoc("definition", "aql", text)
+        block.text("format", data.get("format"))
+        return block
+
+    # -- models -----------------------------------------------------------
+
+    def model_file(self, model: Model) -> str:
+        payload = model.payload
+        data = model.stash
+        scope = model.ossie_name
+        is_query = data.get("aml_type") == "QueryModel" or (
+            "aml_type" not in data and bool(interpolation.query_forms_used(payload.get("source", "")))
+        )
+        source = payload.get("source", "")
+        if "aml_type" not in data and not is_query:
+            is_query = _looks_like_query(source)
+
+        block = Block(f"Model {model.aml_name}")
+        block.property("type", quote("query" if is_query else "table"))
+        block.text("label", data.get("label") or titleize(model.aml_name))
+        block.text("description", payload.get("description"))
+        block.text("data_source_name", data.get("data_source_name") or self.data_source_name)
+        if is_query:
+            referenced = _models_referenced(source)
+            if referenced:
+                block.property("models", f"[{', '.join(sorted(referenced))}]")
+            block.blank()
+            block.heredoc("query", "sql", source)
+        else:
+            block.text("table_name", data.get("table_name") or source)
+
+        for param in data.get("param") or []:
+            block.blank()
+            param_block = block.block(f"param {self.name_in_aml(param['name'], scope)}")
+            param_block.text("label", param.get("label") or titleize(param["name"]))
+            param_block.property("type", quote(param.get("type") or FALLBACK_TYPE))
+
+        persistence = data.get("persistence")
+        if persistence:
+            block.blank()
+            _write_persistence(block, persistence)
+
+        primary_key = set(payload.get("primary_key") or [])
+        for field in payload.get("fields") or []:
+            if stash.read(field).get("scope") == "dataset":
+                continue
+            block.blank()
+            block.lines.append(self.dimension(model, field, primary_key))
+
+        for metric in model.measures:
+            block.blank()
+            block.lines.append(self.measure(model, metric))
+
+        for column in model.borrowed:
+            block.blank()
+            borrowed = block.block(f"dimension {column}")
+            borrowed.text("label", titleize(column))
+            borrowed.property("type", quote(FALLBACK_TYPE_FOR_BORROWED))
+            borrowed.flag("hidden", True)
+            borrowed.heredoc("definition", "sql", interpolation.Source(column).to_aml())
+
+        owner = data.get("owner") or self.root_stash.get("owner")
+        if owner:
+            block.blank()
+            block.text("owner", owner)
+        return amlgen.document(block, license_header=True)
+
+    # -- dataset ----------------------------------------------------------
+
+    def relationship(self, payload: dict[str, Any]) -> str:
+        data = stash.read(payload)
+        kind = data.get("type", "many_to_one")
+        active = "true" if data.get("active", True) else "false"
+        from_model = self.by_ossie_name.get(payload.get("from"))
+        to_model = self.by_ossie_name.get(payload.get("to"))
+        if from_model is None or to_model is None:
+            missing = payload.get("from") if from_model is None else payload.get("to")
+            raise ConversionError(
+                f"relationship {payload.get('name')!r} names dataset {missing!r}, "
+                f"which is not in this document"
+            )
+        from_columns = payload.get("from_columns") or []
+        to_columns = payload.get("to_columns") or []
+
+        if len(from_columns) == 1 and kind in ("many_to_one", "one_to_one"):
+            operator = ">" if kind == "many_to_one" else "-"
+            return (
+                f"relationship({from_model.reference}.{from_columns[0]} {operator} "
+                f"{to_model.reference}.{to_columns[0]}, {active})"
+            )
+
+        config = Block("RelationshipConfig")
+        rel = config.block("EqualityRelationship")
+        rel.header = "rel: EqualityRelationship"
+        rel.property("type", quote(kind))
+        rel.property("from", _field_ref(from_model.aml_name, from_columns[0]))
+        rel.property("to", _field_ref(to_model.aml_name, to_columns[0]))
+        for from_column, to_column in zip(from_columns[1:], to_columns[1:]):
+            on = rel.block("on")
+            on.property("from", _field_ref(from_model.aml_name, from_column))
+            on.property("to", _field_ref(to_model.aml_name, to_column))
+        config.property("active", active)
+        return config.render(2).lstrip()
+
+    def dataset_file(self) -> tuple[str, str]:
+        name = self.dataset_name
+        block = Block(f"Dataset {name}")
+        block.text(
+            "label",
+            self.root_stash.get("label") or titleize(self.document.get("name") or name),
+        )
+        block.text("description", self.document.get("description"))
+        block.text("data_source_name", self.data_source_name)
+        block.blank()
+        block.property("models", amlgen.array([m.reference for m in self.models]))
+        block.blank()
+        block.property(
+            "relationships",
+            amlgen.array(
+                [self.relationship(r) for r in self.document.get("relationships") or []]
+            ),
+        )
+
+        for model in self.models:
+            for field in model.payload.get("fields") or []:
+                if stash.read(field).get("scope") == "dataset":
+                    block.blank()
+                    block.lines.append(self.dataset_dimension(model, field))
+
+        for metric in self.dataset_metrics:
+            written = self.dataset_metric(metric)
+            if written is not None:
+                block.blank()
+                block.lines.append(written)
+
+        owner = self.root_stash.get("owner")
+        if owner:
+            block.blank()
+            block.text("owner", owner)
+        return f"{name}.dataset.aml", amlgen.document(block, license_header=True)
+
+    def run(self) -> Result:
+        # The dataset file is rendered first because its metrics decide which
+        # columns each model has to borrow, and a model file has to carry those
+        # as dimensions. The output order is unchanged: models, then dataset.
+        dataset = self.dataset_file()
+        files = [(m.path, self.model_file(m)) for m in self.models]
+        files.append(dataset)
+        return Result(files, self.issues)
+
+
+def _field_ref(model_name: str, column: str) -> str:
+    return f"FieldRef {{ model: {quote(model_name)}, field: {quote(column)} }}"
+
+
+def _write_persistence(block: Block, persistence: dict[str, Any]) -> None:
+    """The stashed persistence object as its AML block.
+
+    `__type__` names the block, and every key the compiler added for its own
+    bookkeeping starts and ends with `__`, so those are skipped.
+    """
+    kind = persistence.get("__type__") or "FullPersistence"
+    child = block.block(f"persistence: {kind}")
+    for key, value in persistence.items():
+        if key.startswith("__"):
+            continue

Review Comment:
   fixed in 6937306



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


Re: [PR] feat(holistics): add a Holistics AML converter [ossie]

Posted by "jbonofre (via GitHub)" <gi...@apache.org>.
jbonofre merged PR #538:
URL: https://github.com/apache/ossie/pull/538


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


Re: [PR] feat(holistics): add a Holistics AML converter [ossie]

Posted by "jbonofre (via GitHub)" <gi...@apache.org>.
jbonofre commented on code in PR #538:
URL: https://github.com/apache/ossie/pull/538#discussion_r4226531989


##########
converters/holistics/tests/test_cross_vendor.py:
##########
@@ -0,0 +1,137 @@
+# 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.
+
+"""Every Ossie document in this repository, converted to AML.
+
+The reverse path's whole job is reading documents this converter did not write,
+and the snapshot fixtures cannot cover that: one of them this converter produced
+and the other is a single example. The sweep found two defects the fixtures
+missed, both of them crashes rather than bad output.
+
+`examples/flights.semantic_model.yaml` is named `Flights semantic model`. Ossie
+allows any non-empty string, and AML allows letters, digits and underscore, so
+the conversion raised instead of renaming.
+
+Three fixtures use one name for the semantic model and for a dataset inside it,
+including `converters/cube/tests/fixtures/databricks_ossie.yaml`, where both are
+`orders`. Ossie keeps the two in separate namespaces and AML does not, so the
+generated AML failed to compile with "Duplicated name 'orders'".
+
+Adding a fixture elsewhere in the repository extends this test with no edit
+here, which is the point. apache/ossie#352 asked the Solid converter for the
+same sweep.
+"""
+from __future__ import annotations
+
+import subprocess
+from collections import Counter
+from pathlib import Path
+
+import pytest
+
+import snapshots
+from ossie_holistics import _yaml, ossie_to_aml, sqlrefs
+from test_snapshots import HOLISTICS_CLI, needs_cli
+
+#: Any `data_source_name`. These documents have no Holistics connection behind
+#: them, and the value only has to be present for the AML to compile.
+PROBE_CONNECTION = "probe"
+
+
+def _target_dialect(document) -> str:
+    """The SQL dialect most of a document's expressions already use.
+
+    An operator converting one of these would name the warehouse the Holistics
+    connection reads. Picking the document's own majority dialect is the closest
+    stand-in, and it keeps the sweep testing the conversion rather than testing
+    sqlglot's rendering.
+    """
+    counts = Counter()
+    for dataset in document.get("datasets") or []:
+        for field in dataset.get("fields") or []:
+            for entry in (field.get("expression") or {}).get("dialects") or []:
+                counts[entry.get("dialect")] += 1
+    for name, _ in counts.most_common():
+        if name in sqlrefs.SQLGLOT_DIALECT:
+            return name
+    return "ANSI_SQL"
+
+
+def _foreign_ossie_documents() -> list[Path]:
+    """Every flat Ossie document outside this converter's own directory.
+
+    A flat document carries `version` and `datasets` at the root. That is the
+    shape `main` moved to, and the heuristic apache/ossie#352 settled on after
+    the wrapped `semantic_model:` list went away.
+    """
+    found = []
+    roots = [snapshots.REPO_ROOT / "converters", snapshots.REPO_ROOT / "examples"]
+    for root in roots:
+        for path in sorted(root.rglob("*.yaml")):
+            if snapshots.CONVERTER_ROOT in path.parents or ".venv" in path.parts:
+                continue
+            try:
+                document = _yaml.load(path.read_text(encoding="utf-8"))
+            except Exception:  # noqa: BLE001 - a malformed sibling fixture is not our failure
+                continue
+            if isinstance(document, dict) and document.get("version") and "datasets" in document:
+                found.append(path)
+    return found
+
+
+FOREIGN = _foreign_ossie_documents()
+
+
+def _ids(paths: list[Path]) -> list[str]:
+    return [str(p.relative_to(snapshots.REPO_ROOT)) for p in paths]
+
+
+def test_the_sweep_finds_documents():
+    """A heuristic that silently matches nothing would pass every test below."""
+    assert len(FOREIGN) >= 20, _ids(FOREIGN)

Review Comment:
   CI failed here with `assert 18 >= 20`.
   
   Recent commit `f4fa4e6` on `main` removed the Databricks Python converter (#531), which deleted 3 fixture files (`fixtureA_ossie.yaml`, `fixtureB_ossie.yaml`, `tpcds_ossie.yaml`), reducinig the total count of foreign flat Ossie documents from 21 down to 18.
   
   Could we adjust the threshold to `>= 18` (or `>= 15`)?
   
   Also, in `_foreign_ossie_documents()`, we should filter out `"target" in path.parts` alongside `.venv`. Otherwise, Maven build artifacts (`target/test-classes/`) present in local checkouts are counted as fixtures and can mask this threshold difference locally.



##########
python/src/ossie/models.py:
##########
@@ -35,6 +35,7 @@ class OssieDialect(str, Enum):
     SIGMA = "SIGMA"
     THOUGHTSPOT = "THOUGHTSPOT"
     DAX = "DAX"
+    HOLISTICS_AQL = "HOLISTICS_AQL"

Review Comment:
   Registering `HOLISTICS_AQL` in `OssieDialect` triggered CI failures in the Hex converter (`converters/hex`), which was recently merged in #381 
   
   1. `ty check` fails at `converters/hex/src/ossie_hex/ossie_to_hex/load_ossie_dialect_expression.py:118` because Hex does exhaustive pattern matching over `OssieDialect` and calls `assert_never(ossie_dialect)` on unhandled members.
   2. `tests/cli/test_cli_export.py:226` in Hex fails its snapshot comparison between `holistics_aql` is dynamically added to the `--dialect` CLI choices.
   
   When introducing a new dialect to `OssieDialect`, `_to_sqlglot_dialect` in `converters/hex` and its CLI test snapshot will need to be updated as well.



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


Re: [PR] feat(holistics): add a Holistics AML converter [ossie]

Posted by "jbonofre (via GitHub)" <gi...@apache.org>.
jbonofre commented on code in PR #538:
URL: https://github.com/apache/ossie/pull/538#discussion_r4220561433


##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}
+
+
+class _Reverse:
+    def __init__(
+        self, document: dict[str, Any], data_source_name: str | None, sql_dialect: str
+    ):
+        self.document = document
+        self.sql_dialect = sql_dialect
+        self.issues = IssueLog()
+        self.root_stash = stash.read(document)
+        self.data_source_name = self.root_stash.get("data_source_name") or data_source_name
+        if not self.data_source_name:
+            raise ConversionError(
+                "the document carries no HOLISTICS data_source_name, so one must be "
+                "supplied: pass --data-source-name naming the Holistics connection"
+            )
+
+        #: AML identifier to the Ossie name it was spelled from, so two names
+        #: that collapse onto one spelling fail rather than overwrite.
+        self._renamed: dict[str, str] = {}
+
+        datasets = _named_objects(document.get("datasets"), "datasets")
+        if not datasets:
+            raise ConversionError(
+                "the document declares no datasets, and the specification requires at least one"
+            )
+        for dataset in datasets:
+            _named_objects(dataset.get("fields"), f"datasets[{dataset['name']}].fields")
+        _named_objects(document.get("metrics"), "metrics")
+
+        self.models: list[Model] = []
+        for dataset in datasets:
+            name = dataset["name"]
+            data = stash.read(dataset)
+            self.models.append(
+                Model(
+                    ossie_name=name,
+                    fqn=data.get("fqn") or unflatten(name),
+                    payload=dataset,
+                    stash=data,
+                )
+            )
+        self.by_ossie_name = {m.ossie_name: m for m in self.models}
+
+        taken: dict[str, str] = {}
+        for model in self.models:
+            clash = taken.setdefault(model.aml_fqn, model.ossie_name)
+            if clash != model.ossie_name:
+                raise ConversionError(
+                    f"datasets {clash!r} and {model.ossie_name!r} both spell as the AML "
+                    f"model {model.aml_fqn!r}; rename one of them in Ossie"
+                )
+
+        self.dataset_name = self._dataset_name()
+
+        #: Every metric that belongs on a model, indexed by Ossie metric name,
+        #: alongside the AML measure name it is written as.
+        self.metric_owner: dict[str, Model] = {}
+        self.metric_aml_name: dict[str, str] = {}
+        self.dataset_metrics: list[dict[str, Any]] = []
+        self._metric_payloads: dict[str, dict[str, Any]] = {}
+        self._metric_datasets: dict[str, Any] = {}
+        self._cyclic_metrics: set[str] = set()
+        self._place_metrics()
+
+    # -- placement --------------------------------------------------------
+
+    def _place_metrics(self) -> None:
+        """Decide where each Ossie metric goes: on a model, or on the dataset.
+
+        A stashed `model` settles it. Without one, the expression decides: a
+        body naming exactly one dataset becomes a measure on that model, and a
+        body naming several becomes a dataset-level metric, which is the only
+        AML construct that spans models. A body may also name another metric,
+        and `_scan_for_datasets` covers what that counts as.
+        """
+        metrics = self.document.get("metrics") or []
+        for metric in metrics:
+            name = metric.get("name")
+            self.metric_aml_name[name] = stash.read(metric).get("aml_name") or name
+            self._metric_payloads[name] = metric
+        for metric in metrics:
+            name = metric.get("name")
+            named = self._datasets_named(name) or frozenset()
+            owner = self.by_ossie_name[next(iter(named))] if len(named) == 1 else None
+            if owner is None:
+                self.dataset_metrics.append(metric)
+            else:
+                owner.measures.append(metric)
+                self.metric_owner[name] = owner
+        self._report_metric_cycles()
+
+    def _datasets_named(self, name: str) -> frozenset[str] | None:
+        """The Ossie datasets metric `name` resolves to, or None when that is unknown.
+
+        None covers every reading that cannot put the metric on a single model:
+        an AQL body, Ossie SQL this converter cannot read, and a reference cycle.
+        """
+        resolved = self._metric_datasets.get(name, _UNVISITED)
+        if resolved is _RESOLVING:
+            self._cyclic_metrics.add(name)
+            return None
+        if resolved is not _UNVISITED:
+            return resolved
+        self._metric_datasets[name] = _RESOLVING
+        result = self._scan_for_datasets(name)
+        self._metric_datasets[name] = result
+        return result
+
+    def _scan_for_datasets(self, name: str) -> frozenset[str] | None:
+        """Which datasets one metric body names, directly or through a metric.
+
+        An Ossie metric body may name another metric instead of a column, as
+        `cities__upstream_measure + 1` in `tests/fixtures/ecommerce` does. That
+        body names no dataset of its own, and the datasets the metric it
+        references resolves to stand in for it. Without that substitution a
+        metric built only from other metrics lands on the dataset, where AML
+        takes an AQL body, and the Ossie SQL name it was written with does not
+        resolve.
+        """
+        metric = self._metric_payloads[name]
+        data = stash.read(metric)
+        owner_fqn = data.get("model")
+        if owner_fqn:
+            owner = next((m for m in self.models if m.fqn == owner_fqn), None)
+            if owner is None:
+                raise ConversionError(
+                    f"metric {name!r} is stashed against model {owner_fqn!r}, "
+                    f"which is not a dataset in this document"
+                )
+            return frozenset({owner.ossie_name})
+        available = dialects_of(metric.get("expression"))
+        if AQL_DIALECT in available:
+            return None
+        dialect = next(
+            (d for d in (self.sql_dialect, *PORTABLE_DIALECTS) if d in available), None
+        )
+        if dialect is None:
+            return None
+        try:
+            references = sqlrefs.columns(available[dialect], dialect)
+        except sqlrefs.UnparseableSQL:
+            return None
+        named = {c.table for c in references if c.table in self.by_ossie_name}
+        for reference in references:
+            if reference.table or reference.name not in self._metric_payloads:
+                continue
+            through = self._datasets_named(reference.name)
+            if through is None:
+                return None
+            named |= through
+        return frozenset(named)
+
+    def _report_metric_cycles(self) -> None:
+        for name in sorted(self._cyclic_metrics):
+            self.issues.add(
+                code=ISSUE_METRIC_CYCLE,
+                severity=Severity.ERROR,
+                message=(
+                    f"metric {name!r} references itself through another metric. Holistics "
+                    f"inlines one metric into the body of the next, so a cycle has no warehouse SQL, "
+                    f"and `holistics aml validate` accepts the file without catching it"
+                ),
+                object_ref=name,
+                remedy="break the cycle in Ossie",
+            )
+
+    # -- names ------------------------------------------------------------
+
+    def _dataset_name(self) -> str:
+        """The AML `Dataset` name, moved aside when a model already has it.
+
+        Ossie keeps the semantic model's name and its dataset names in separate
+        namespaces, so a document may use one name for both. Three fixtures in
+        this repository do, including
+        `converters/cube/tests/fixtures/databricks_ossie.yaml`, whose root name
+        and first dataset are both `orders`. AML has one namespace for `Dataset`
+        and `Model`, and rejects the pair with "Duplicated name 'orders'".
+
+        Nothing references the AML dataset name. Models reference each other and
+        relationships reference models, so the dataset is the safe side to move.
+        """
+        name = self.root_stash.get("fqn") or self.document.get("name")
+        if not name:
+            raise ConversionError("the document has no name")
+        spelled = self.name_in_aml(name, str(name))
+        taken = {model.aml_fqn for model in self.models} | {
+            model.aml_name for model in self.models
+        }
+        if spelled not in taken:
+            return spelled
+        candidate, suffix = f"{spelled}_dataset", 2
+        while candidate in taken:
+            candidate, suffix = f"{spelled}_dataset_{suffix}", suffix + 1
+        self.issues.add(
+            code=ISSUE_DATASET_RENAMED,
+            severity=Severity.WARNING,
+            message=(
+                f"a model is already named {spelled!r}, and AML holds Dataset and Model "
+                f"in one namespace, so the dataset is written as {candidate!r}"
+            ),
+            object_ref=str(name),
+            remedy="rename the semantic model or the dataset in Ossie",
+        )
+        return candidate
+
+    def name_in_aml(self, name: str, scope: str) -> str:
+        """An Ossie name as the AML identifier it is written as.
+
+        Lookups elsewhere stay keyed on the Ossie name, because that is what an
+        expression references. Only the output spelling changes, and every site
+        that writes a name goes through here, so a declaration and a reference
+        to it cannot disagree.
+        """
+        spelled = sanitize(name)
+        if spelled != name:
+            previous = self._renamed.setdefault(spelled, name)
+            if previous != name:
+                raise ConversionError(
+                    f"{scope}: {name!r} and {previous!r} both spell as the AML "
+                    f"identifier {spelled!r}; rename one of them in Ossie"
+                )
+            self.issues.add(
+                code=ISSUE_RENAMED,
+                severity=Severity.WARNING,
+                message=(
+                    f"{name!r} is not a legal AML identifier and is written as "
+                    f"{spelled!r}. AML allows letters, digits and underscore, and no "
+                    f"leading digit"
+                ),
+                object_ref=scope,
+                remedy=f"rename it to {spelled!r} in Ossie to keep the two in step",
+            )
+        return spelled
+
+    # -- expressions ------------------------------------------------------
+
+    def pick_body(self, expression: Any, scope: str) -> tuple[str, str]:
+        """The body to write and the dialect it is in, after any rendering.
+
+        AQL wins outright. It came out of AML unchanged and goes back unchanged.
+
+        For Ossie SQL the target is `--sql-dialect`, the warehouse the Holistics
+        connection reads. A body already in that dialect is written as it
+        stands. Otherwise a portable body is rendered into the target with
+        sqlglot, because the alternative is AML that will not run. An expression
+        offering neither has no body this connection can execute, and the
+        converter says so rather than writing Holistics SQL for the wrong warehouse.
+        """
+        available = dialects_of(expression)
+        if AQL_DIALECT in available:
+            return AQL_DIALECT, available[AQL_DIALECT]
+        if self.sql_dialect in available:
+            return self.sql_dialect, available[self.sql_dialect]
+
+        source = next((d for d in PORTABLE_DIALECTS if d in available), None)
+        if source is not None:
+            try:
+                rendered = sqlrefs.transpile(available[source], source, self.sql_dialect)
+            except sqlrefs.UnparseableSQL as exc:
+                self.issues.add(
+                    code=ISSUE_UNPARSEABLE_SQL,
+                    severity=Severity.ERROR,
+                    message=(
+                        f"the {source} body cannot be rendered as {self.sql_dialect} ({exc}), "
+                        f"so it is written unchanged and may not run"
+                    ),
+                    object_ref=scope,
+                    remedy=f"add a {self.sql_dialect} expression, or fix the {source} one",
+                )
+                return source, available[source]
+            self.issues.add(
+                code=ISSUE_TRANSPILED,
+                severity=Severity.WARNING,
+                message=(
+                    f"no {self.sql_dialect} expression, so the {source} one was rendered "
+                    f"into it: {available[source]!r} became {rendered!r}"
+                ),
+                object_ref=scope,
+                remedy=f"add a {self.sql_dialect} expression to keep the body exact",
+            )
+            return self.sql_dialect, rendered
+
+        fallback = next(iter(available))
+        self.issues.add(
+            code=ISSUE_NO_USABLE_DIALECT,
+            severity=Severity.ERROR,
+            message=(
+                f"the expression offers {', '.join(sorted(available))} and the connection "
+                f"reads {self.sql_dialect}, with no portable body to render from, so the "
+                f"{fallback} body is written unchanged and will not run"
+            ),
+            object_ref=scope,
+            remedy=f"add a {self.sql_dialect} or ANSI_SQL expression",
+        )
+        return fallback, available[fallback]
+
+    def definition(self, block: Block, expression: Any, model: Model, scope: str) -> None:
+        """Write a `definition` property for a field or a measure."""
+        dialect, text = self.pick_body(expression, scope)
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+            return
+        block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+
+    def to_aml_sql(self, expression: str, dialect: str, model: Model, scope: str) -> str:
+        """An Ossie SQL expression with its references written as AML interpolation.
+
+        A bare column name does compile as AML, but AQL reads the interpolation
+        to learn which field the body depends on. A body without it loses the
+        query rewriting and the optimisation that link drives, so this restores
+        every reference rather than passing the SQL through.
+        """
+        if dialect in sqlrefs.NOT_SQL or not sqlrefs.AVAILABLE:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body is tagged {dialect!r}, which is not Ossie SQL this converter can "
+                    f"read, so its field references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="supply an ANSI_SQL or warehouse-SQL dialect for this expression",
+            )
+            return expression
+        grouping = sqlrefs.window_grouping(expression, dialect)
+        if grouping:
+            self.issues.add(
+                code=ISSUE_WINDOW_NEEDS_GROUPING,
+                severity=Severity.WARNING,
+                message=(
+                    f"the body has a window function whose frame reads "
+                    f"{', '.join(grouping)}. AML carries it as written, and the warehouse SQL "
+                    f"it generates is valid only for a query that groups by those. A query "
+                    f"that does not, a grand total for one, produces warehouse SQL the "
+                    f"database rejects, and Holistics does not check this at conversion time"
+                ),
+                object_ref=scope,
+                remedy="query it only alongside those fields, or rewrite the body in AQL",
+            )
+        try:
+            return sqlrefs.rewrite(
+                expression, dialect, lambda column: self.to_interpolation(column, model, scope)
+            )
+        except sqlrefs.UnparseableSQL as exc:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"sqlglot cannot read the body as {dialect} ({exc}), so its field "
+                    f"references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="fix the expression, or convert it by hand",
+            )
+            return expression
+
+    def to_interpolation(self, column: sqlrefs.ColumnReference, model: Model, scope: str) -> str:
+        """One Ossie column reference as the AML interpolation it came from."""
+        if not column.table:
+            if column.name in self.metric_aml_name:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Source(column.name).to_aml()
+
+        target = self.by_ossie_name.get(column.table)
+        if target is None:
+            self.issues.add(
+                code=ISSUE_UNKNOWN_QUALIFIER,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body qualifies {column.name!r} with {column.table!r}, which is not "
+                    f"a dataset in this document, so it is left unresolved"
+                ),
+                object_ref=scope,
+                remedy="qualify the reference with a dataset name, or drop the field",
+            )
+            return f"{column.table}.{column.name}"
+        if target is model:
+            # A qualifier naming this model usually names one of its fields. It
+            # can also name a metric this converter put somewhere else, and a
+            # sibling reference to that spells a field the model does not have.
+            if column.name in self.metric_aml_name and self.metric_owner.get(column.name) is not model:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Sibling(self.name_in_aml(column.name, scope)).to_aml()
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body names {column.table}.{column.name}, a field of another dataset. A `@sql` "
+                f"body resolves inside one model, and Holistics rejects this at SQL generation "
+                f"with \"Cannot refer to external field in TableModel/QueryModel\" even though "
+                f"`holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="move the reference into a dimension on its own model, or rewrite the body in AQL",
+        )
+        return interpolation.ModelField(target.aml_fqn, self.name_in_aml(column.name, scope)).to_aml()
+
+    def _measure_reference(self, metric_name: str, model: Model, scope: str) -> str:
+        owner = self.metric_owner.get(metric_name)
+        aml_name = self.metric_aml_name[metric_name]
+        if owner is model:
+            return interpolation.Sibling(self.name_in_aml(aml_name, scope)).to_aml()
+        if owner is None:
+            self.issues.add(
+                code=ISSUE_CROSS_MODEL_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body references the dataset-level metric {metric_name!r}. A `@sql` "
+                    f"body resolves inside one model, so there is no AML spelling for it"
+                ),
+                object_ref=scope,
+                remedy="rewrite the expression in AQL, which does span models",
+            )
+            return metric_name
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body references {metric_name!r}, a measure of model {owner.aml_fqn!r}. A "
+                f"`@sql` body resolves inside one model, and Holistics rejects this at SQL "
+                f"generation with \"Cannot refer to external field in TableModel/QueryModel\" "
+                f"even though `holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="rewrite the expression in AQL, which does span models",
+        )
+        return interpolation.ModelField(owner.aml_fqn, self.name_in_aml(aml_name, scope)).to_aml()
+
+    # -- fields -----------------------------------------------------------
+
+    def aml_type(
+        self, payload: dict[str, Any], data: dict[str, Any], scope: str, model: Model | None = None
+    ) -> str:
+        stashed = data.get("type")
+        if stashed:
+            return stashed
+        datatype = payload.get("datatype")
+        mapped = OSSIE_TO_AML_TYPE.get(datatype) if datatype else None
+        if mapped:
+            return mapped
+        if model is not None and payload["name"] in model.numeric:
+            # A metric aggregates this field with `sum` or `avg`, so it is a
+            # number whatever the document failed to say.
+            return "number"
+        self.issues.add(
+            code=ISSUE_ASSUMED_TYPE,
+            severity=Severity.WARNING,
+            message=(
+                f"AML requires a type and the Ossie datatype is {datatype!r}, "
+                f"so {FALLBACK_TYPE!r} is written"
+            ),
+            object_ref=scope,
+            remedy="set a datatype on the field, or edit the AML type after conversion",
+        )
+        return FALLBACK_TYPE
+
+    def common_properties(
+        self,
+        block: Block,
+        payload: dict[str, Any],
+        data: dict[str, Any],
+        scope: str,
+        model: Model | None = None,
+    ) -> None:
+        block.text("label", data.get("label") or titleize(payload["name"]))
+        block.property("type", quote(self.aml_type(payload, data, scope, model)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+    def dimension(self, model: Model, payload: dict[str, Any], primary_key: set[str]) -> Block:
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        block.flag("primary_key", name in primary_key)
+        return block
+
+    def dataset_dimension(self, model: Model, payload: dict[str, Any]) -> Block:
+        """A field the forward path took from a dataset-level AML dimension."""
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        block.property("model", model.reference)
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        return block
+
+    def measure(self, model: Model, payload: dict[str, Any]) -> Block:
+        """One Ossie metric as a `measure` on its owning model.
+
+        `aggregation_type` and the body compose into one Ossie expression on the
+        way out, so this splits them back apart. When the stashed aggregation
+        does not wrap the whole expression, the expression was edited after the
+        forward path wrote it, and `custom` keeps it whole rather than letting
+        the measure aggregate twice.
+        """
+        metric_name = payload["name"]
+        aml_name = self.metric_aml_name[metric_name]
+        scope = f"{model.ossie_name}.{aml_name}"
+        data = stash.read(payload)
+        block = Block(f"measure {self.name_in_aml(aml_name, scope)}")
+        block.text("label", data.get("label") or titleize(aml_name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        aggregation = data.get("aggregation_type") or CUSTOM_AGGREGATION
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+        else:
+            if aggregation in AGGREGATIONS:
+                inner = strip_aggregation(aggregation, text)
+                if inner is None:
+                    self.issues.add(
+                        code=ISSUE_AGGREGATION_NOT_STRIPPED,
+                        severity=Severity.WARNING,
+                        message=(
+                            f"the stashed aggregation {aggregation!r} does not wrap the whole "
+                            f"expression, so the measure is written as 'custom' with the "
+                            f"expression kept whole"
+                        ),
+                        object_ref=scope,
+                        remedy="check the expression against the aggregation",
+                    )
+                    aggregation = CUSTOM_AGGREGATION
+                else:
+                    text = inner
+            block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+        block.property("aggregation_type", quote(aggregation))
+        block.text("format", data.get("format"))
+        return block
+
+    def as_aql(self, text: str, dialect: str, scope: str) -> str | None:
+        """A dataset-level metric's Ossie SQL body rendered as AQL, or None if it cannot be.
+
+        AML accepts only `@aql` here, so an Ossie SQL body either becomes AQL or has no
+        AML form at all. `aql.translate` is a name map over functions this
+        converter has paired with an AQL equivalent. Anything outside that table
+        raises `Untranslatable`, and the metric is dropped with an ERROR.
+        """
+        try:
+            rendered, numeric = aql.translate(
+                text, dialect, lambda table, column: self.aql_reference(table, column, scope)
+            )
+        except aql.Untranslatable as exc:
+            self.issues.add(
+                code=ISSUE_METRIC_NOT_TRANSLATED,
+                severity=Severity.ERROR,
+                message=(
+                    f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                    f"converter did not translate this {dialect} body, and the metric is "
+                    f"dropped. {exc}"
+                ),
+                object_ref=scope,
+                remedy="rewrite the metric in AQL, or scope it to a single dataset",
+            )
+            return None
+        self.issues.add(
+            code=ISSUE_RENDERED_AS_AQL,
+            severity=Severity.WARNING,
+            message=(
+                f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                f"{dialect} expression was rendered as AQL: {text!r} became {rendered!r}"
+            ),
+            object_ref=scope,
+            remedy="check the AQL against the Ossie SQL it came from",
+        )
+        for table, column in numeric:
+            target = self.by_ossie_name.get(table)
+            if target is not None:
+                target.numeric.add(self.name_in_aml(column, scope))
+        return rendered
+
+    def aql_reference(self, table: str, column: str, scope: str) -> str:
+        """One column of an Ossie SQL metric body as the AQL reference it becomes.
+
+        AQL names a field `model.field`, which is the shape the Ossie expression
+        already uses, so this maps the Ossie dataset name onto the AML model
+        name and keeps the field name.
+
+        An Ossie SQL body may name a warehouse column the document does not declare as
+        a field. `SUM(orders.subtotal) / COUNT(DISTINCT customers.customer_id)`
+        in `converters/nvidia/tests/fixtures/sales.ossie.yaml` is one: `orders`
+        declares no `subtotal`. Ossie SQL resolves that against the table, and AQL
+        does not, answering `Field `subtotal` not found in model `orders``. So
+        the column becomes a hidden dimension on that model, and the AQL
+        reference points at it.
+        """
+        if not table:
+            # An unqualified name that is a metric is a metric reference, which
+            # AQL takes: a dataset-level one by its bare name, and a measure by
+            # the model that holds it.
+            if column in self.metric_aml_name:
+                referenced = self.name_in_aml(self.metric_aml_name[column], scope)
+                owner = self.metric_owner.get(column)
+                return referenced if owner is None else f"{owner.aml_fqn}.{referenced}"
+            raise aql.Untranslatable(
+                f"{column!r} names no dataset, and a metric spanning models has no single "
+                f"model to resolve it against."
+            )
+        target = self.by_ossie_name.get(table)
+        if target is None:
+            raise aql.Untranslatable(f"{table!r} is not a dataset in this document.")
+        name = self.name_in_aml(column, scope)
+        declared = {
+            field["name"] for field in target.payload.get("fields") or []
+        } | {self.metric_aml_name[m["name"]] for m in target.measures}
+        if name not in declared and name not in target.borrowed:
+            target.borrowed.append(name)
+            self.issues.add(
+                code=ISSUE_BORROWED_COLUMN,
+                severity=Severity.WARNING,
+                message=(
+                    f"the metric reads {table}.{column}, which the dataset does not declare "
+                    f"as a field. AQL resolves a reference against declared fields only, so "
+                    f"{column!r} is added to model {target.aml_fqn!r} as a hidden dimension "
+                    f"over the column of that name"
+                ),
+                object_ref=scope,
+                remedy=f"declare {column!r} as a field of {table!r} in Ossie",
+            )
+        return f"{target.aml_fqn}.{name}"
+
+    def dataset_metric(self, payload: dict[str, Any]) -> Block | None:
+        """One Ossie metric as a dataset-level AML `metric`.
+
+        AML accepts only an `@aql` body here. The compiler rejects `@sql` with
+        "Incompatible property 'definition' of 'Metric'", so a cross-model
+        metric carrying Ossie SQL has no AML form at all.
+        """
+        name = payload["name"]
+        scope = name
+        data = stash.read(payload)
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        if dialect != AQL_DIALECT:
+            rendered = self.as_aql(text, dialect, scope)
+            if rendered is None:
+                return None
+            text = rendered
+        block = Block(f"metric {self.name_in_aml(name, scope)}")
+        block.text("label", data.get("label") or titleize(name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+        block.heredoc("definition", "aql", text)
+        block.text("format", data.get("format"))
+        return block
+
+    # -- models -----------------------------------------------------------
+
+    def model_file(self, model: Model) -> str:
+        payload = model.payload
+        data = model.stash
+        scope = model.ossie_name
+        is_query = data.get("aml_type") == "QueryModel" or (
+            "aml_type" not in data and bool(interpolation.query_forms_used(payload.get("source", "")))
+        )
+        source = payload.get("source", "")
+        if "aml_type" not in data and not is_query:
+            is_query = _looks_like_query(source)
+
+        block = Block(f"Model {model.aml_name}")
+        block.property("type", quote("query" if is_query else "table"))
+        block.text("label", data.get("label") or titleize(model.aml_name))
+        block.text("description", payload.get("description"))
+        block.text("data_source_name", data.get("data_source_name") or self.data_source_name)
+        if is_query:
+            referenced = _models_referenced(source)
+            if referenced:
+                block.property("models", f"[{', '.join(sorted(referenced))}]")
+            block.blank()
+            block.heredoc("query", "sql", source)
+        else:
+            block.text("table_name", data.get("table_name") or source)
+
+        for param in data.get("param") or []:
+            block.blank()
+            param_block = block.block(f"param {self.name_in_aml(param['name'], scope)}")
+            param_block.text("label", param.get("label") or titleize(param["name"]))
+            param_block.property("type", quote(param.get("type") or FALLBACK_TYPE))
+
+        persistence = data.get("persistence")
+        if persistence:
+            block.blank()
+            _write_persistence(block, persistence)
+
+        primary_key = set(payload.get("primary_key") or [])
+        for field in payload.get("fields") or []:
+            if stash.read(field).get("scope") == "dataset":
+                continue
+            block.blank()
+            block.lines.append(self.dimension(model, field, primary_key))
+
+        for metric in model.measures:
+            block.blank()
+            block.lines.append(self.measure(model, metric))
+
+        for column in model.borrowed:
+            block.blank()
+            borrowed = block.block(f"dimension {column}")
+            borrowed.text("label", titleize(column))
+            borrowed.property("type", quote(FALLBACK_TYPE_FOR_BORROWED))
+            borrowed.flag("hidden", True)
+            borrowed.heredoc("definition", "sql", interpolation.Source(column).to_aml())
+
+        owner = data.get("owner") or self.root_stash.get("owner")
+        if owner:
+            block.blank()
+            block.text("owner", owner)
+        return amlgen.document(block, license_header=True)
+
+    # -- dataset ----------------------------------------------------------
+
+    def relationship(self, payload: dict[str, Any]) -> str:

Review Comment:
   `aml_to_ossie.py` stashes `direction`, `nullable`, `rlp_propagation` and `where`, but this function reads only `type` and `active` from the stash. A Holistics -> Ossie -> Holistics round trip therefore drops all four. `where` matters most: the join filter disappears and the join silently widens.
   
   Could these be read back from the stash? If the loss is intentional, it should emit a warning on this path and be documented in `limitations.md`.



##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}

Review Comment:
   `(expression or {}).get(...)` and `entry.get(...)` assume mappings. A string `expression` or a non-mapping dialect entry raises `AttributeError`. `_named_objects` already guards the other collections, so a `ConversionError` here would be consistent.



##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}
+
+
+class _Reverse:
+    def __init__(
+        self, document: dict[str, Any], data_source_name: str | None, sql_dialect: str
+    ):
+        self.document = document
+        self.sql_dialect = sql_dialect
+        self.issues = IssueLog()
+        self.root_stash = stash.read(document)
+        self.data_source_name = self.root_stash.get("data_source_name") or data_source_name
+        if not self.data_source_name:
+            raise ConversionError(
+                "the document carries no HOLISTICS data_source_name, so one must be "
+                "supplied: pass --data-source-name naming the Holistics connection"
+            )
+
+        #: AML identifier to the Ossie name it was spelled from, so two names
+        #: that collapse onto one spelling fail rather than overwrite.
+        self._renamed: dict[str, str] = {}
+
+        datasets = _named_objects(document.get("datasets"), "datasets")
+        if not datasets:
+            raise ConversionError(
+                "the document declares no datasets, and the specification requires at least one"
+            )
+        for dataset in datasets:
+            _named_objects(dataset.get("fields"), f"datasets[{dataset['name']}].fields")
+        _named_objects(document.get("metrics"), "metrics")
+
+        self.models: list[Model] = []
+        for dataset in datasets:
+            name = dataset["name"]
+            data = stash.read(dataset)
+            self.models.append(
+                Model(
+                    ossie_name=name,
+                    fqn=data.get("fqn") or unflatten(name),
+                    payload=dataset,
+                    stash=data,
+                )
+            )
+        self.by_ossie_name = {m.ossie_name: m for m in self.models}
+
+        taken: dict[str, str] = {}
+        for model in self.models:
+            clash = taken.setdefault(model.aml_fqn, model.ossie_name)
+            if clash != model.ossie_name:
+                raise ConversionError(
+                    f"datasets {clash!r} and {model.ossie_name!r} both spell as the AML "
+                    f"model {model.aml_fqn!r}; rename one of them in Ossie"
+                )
+
+        self.dataset_name = self._dataset_name()
+
+        #: Every metric that belongs on a model, indexed by Ossie metric name,
+        #: alongside the AML measure name it is written as.
+        self.metric_owner: dict[str, Model] = {}
+        self.metric_aml_name: dict[str, str] = {}
+        self.dataset_metrics: list[dict[str, Any]] = []
+        self._metric_payloads: dict[str, dict[str, Any]] = {}
+        self._metric_datasets: dict[str, Any] = {}
+        self._cyclic_metrics: set[str] = set()
+        self._place_metrics()
+
+    # -- placement --------------------------------------------------------
+
+    def _place_metrics(self) -> None:
+        """Decide where each Ossie metric goes: on a model, or on the dataset.
+
+        A stashed `model` settles it. Without one, the expression decides: a
+        body naming exactly one dataset becomes a measure on that model, and a
+        body naming several becomes a dataset-level metric, which is the only
+        AML construct that spans models. A body may also name another metric,
+        and `_scan_for_datasets` covers what that counts as.
+        """
+        metrics = self.document.get("metrics") or []
+        for metric in metrics:
+            name = metric.get("name")
+            self.metric_aml_name[name] = stash.read(metric).get("aml_name") or name
+            self._metric_payloads[name] = metric
+        for metric in metrics:
+            name = metric.get("name")
+            named = self._datasets_named(name) or frozenset()
+            owner = self.by_ossie_name[next(iter(named))] if len(named) == 1 else None
+            if owner is None:
+                self.dataset_metrics.append(metric)
+            else:
+                owner.measures.append(metric)
+                self.metric_owner[name] = owner
+        self._report_metric_cycles()
+
+    def _datasets_named(self, name: str) -> frozenset[str] | None:
+        """The Ossie datasets metric `name` resolves to, or None when that is unknown.
+
+        None covers every reading that cannot put the metric on a single model:
+        an AQL body, Ossie SQL this converter cannot read, and a reference cycle.
+        """
+        resolved = self._metric_datasets.get(name, _UNVISITED)
+        if resolved is _RESOLVING:
+            self._cyclic_metrics.add(name)
+            return None
+        if resolved is not _UNVISITED:
+            return resolved
+        self._metric_datasets[name] = _RESOLVING
+        result = self._scan_for_datasets(name)
+        self._metric_datasets[name] = result
+        return result
+
+    def _scan_for_datasets(self, name: str) -> frozenset[str] | None:
+        """Which datasets one metric body names, directly or through a metric.
+
+        An Ossie metric body may name another metric instead of a column, as
+        `cities__upstream_measure + 1` in `tests/fixtures/ecommerce` does. That
+        body names no dataset of its own, and the datasets the metric it
+        references resolves to stand in for it. Without that substitution a
+        metric built only from other metrics lands on the dataset, where AML
+        takes an AQL body, and the Ossie SQL name it was written with does not
+        resolve.
+        """
+        metric = self._metric_payloads[name]
+        data = stash.read(metric)
+        owner_fqn = data.get("model")
+        if owner_fqn:
+            owner = next((m for m in self.models if m.fqn == owner_fqn), None)
+            if owner is None:
+                raise ConversionError(
+                    f"metric {name!r} is stashed against model {owner_fqn!r}, "
+                    f"which is not a dataset in this document"
+                )
+            return frozenset({owner.ossie_name})
+        available = dialects_of(metric.get("expression"))
+        if AQL_DIALECT in available:
+            return None
+        dialect = next(
+            (d for d in (self.sql_dialect, *PORTABLE_DIALECTS) if d in available), None
+        )
+        if dialect is None:
+            return None
+        try:
+            references = sqlrefs.columns(available[dialect], dialect)
+        except sqlrefs.UnparseableSQL:
+            return None
+        named = {c.table for c in references if c.table in self.by_ossie_name}
+        for reference in references:
+            if reference.table or reference.name not in self._metric_payloads:
+                continue
+            through = self._datasets_named(reference.name)
+            if through is None:
+                return None
+            named |= through
+        return frozenset(named)
+
+    def _report_metric_cycles(self) -> None:
+        for name in sorted(self._cyclic_metrics):
+            self.issues.add(
+                code=ISSUE_METRIC_CYCLE,
+                severity=Severity.ERROR,
+                message=(
+                    f"metric {name!r} references itself through another metric. Holistics "
+                    f"inlines one metric into the body of the next, so a cycle has no warehouse SQL, "
+                    f"and `holistics aml validate` accepts the file without catching it"
+                ),
+                object_ref=name,
+                remedy="break the cycle in Ossie",
+            )
+
+    # -- names ------------------------------------------------------------
+
+    def _dataset_name(self) -> str:
+        """The AML `Dataset` name, moved aside when a model already has it.
+
+        Ossie keeps the semantic model's name and its dataset names in separate
+        namespaces, so a document may use one name for both. Three fixtures in
+        this repository do, including
+        `converters/cube/tests/fixtures/databricks_ossie.yaml`, whose root name
+        and first dataset are both `orders`. AML has one namespace for `Dataset`
+        and `Model`, and rejects the pair with "Duplicated name 'orders'".
+
+        Nothing references the AML dataset name. Models reference each other and
+        relationships reference models, so the dataset is the safe side to move.
+        """
+        name = self.root_stash.get("fqn") or self.document.get("name")
+        if not name:
+            raise ConversionError("the document has no name")
+        spelled = self.name_in_aml(name, str(name))
+        taken = {model.aml_fqn for model in self.models} | {
+            model.aml_name for model in self.models
+        }
+        if spelled not in taken:
+            return spelled
+        candidate, suffix = f"{spelled}_dataset", 2
+        while candidate in taken:
+            candidate, suffix = f"{spelled}_dataset_{suffix}", suffix + 1
+        self.issues.add(
+            code=ISSUE_DATASET_RENAMED,
+            severity=Severity.WARNING,
+            message=(
+                f"a model is already named {spelled!r}, and AML holds Dataset and Model "
+                f"in one namespace, so the dataset is written as {candidate!r}"
+            ),
+            object_ref=str(name),
+            remedy="rename the semantic model or the dataset in Ossie",
+        )
+        return candidate
+
+    def name_in_aml(self, name: str, scope: str) -> str:
+        """An Ossie name as the AML identifier it is written as.
+
+        Lookups elsewhere stay keyed on the Ossie name, because that is what an
+        expression references. Only the output spelling changes, and every site
+        that writes a name goes through here, so a declaration and a reference
+        to it cannot disagree.
+        """
+        spelled = sanitize(name)
+        if spelled != name:
+            previous = self._renamed.setdefault(spelled, name)
+            if previous != name:
+                raise ConversionError(
+                    f"{scope}: {name!r} and {previous!r} both spell as the AML "
+                    f"identifier {spelled!r}; rename one of them in Ossie"
+                )
+            self.issues.add(
+                code=ISSUE_RENAMED,
+                severity=Severity.WARNING,
+                message=(
+                    f"{name!r} is not a legal AML identifier and is written as "
+                    f"{spelled!r}. AML allows letters, digits and underscore, and no "
+                    f"leading digit"
+                ),
+                object_ref=scope,
+                remedy=f"rename it to {spelled!r} in Ossie to keep the two in step",
+            )
+        return spelled
+
+    # -- expressions ------------------------------------------------------
+
+    def pick_body(self, expression: Any, scope: str) -> tuple[str, str]:
+        """The body to write and the dialect it is in, after any rendering.
+
+        AQL wins outright. It came out of AML unchanged and goes back unchanged.
+
+        For Ossie SQL the target is `--sql-dialect`, the warehouse the Holistics
+        connection reads. A body already in that dialect is written as it
+        stands. Otherwise a portable body is rendered into the target with
+        sqlglot, because the alternative is AML that will not run. An expression
+        offering neither has no body this connection can execute, and the
+        converter says so rather than writing Holistics SQL for the wrong warehouse.
+        """
+        available = dialects_of(expression)
+        if AQL_DIALECT in available:
+            return AQL_DIALECT, available[AQL_DIALECT]
+        if self.sql_dialect in available:
+            return self.sql_dialect, available[self.sql_dialect]
+
+        source = next((d for d in PORTABLE_DIALECTS if d in available), None)
+        if source is not None:
+            try:
+                rendered = sqlrefs.transpile(available[source], source, self.sql_dialect)
+            except sqlrefs.UnparseableSQL as exc:
+                self.issues.add(
+                    code=ISSUE_UNPARSEABLE_SQL,
+                    severity=Severity.ERROR,
+                    message=(
+                        f"the {source} body cannot be rendered as {self.sql_dialect} ({exc}), "
+                        f"so it is written unchanged and may not run"
+                    ),
+                    object_ref=scope,
+                    remedy=f"add a {self.sql_dialect} expression, or fix the {source} one",
+                )
+                return source, available[source]
+            self.issues.add(
+                code=ISSUE_TRANSPILED,
+                severity=Severity.WARNING,
+                message=(
+                    f"no {self.sql_dialect} expression, so the {source} one was rendered "
+                    f"into it: {available[source]!r} became {rendered!r}"
+                ),
+                object_ref=scope,
+                remedy=f"add a {self.sql_dialect} expression to keep the body exact",
+            )
+            return self.sql_dialect, rendered
+
+        fallback = next(iter(available))
+        self.issues.add(
+            code=ISSUE_NO_USABLE_DIALECT,
+            severity=Severity.ERROR,
+            message=(
+                f"the expression offers {', '.join(sorted(available))} and the connection "
+                f"reads {self.sql_dialect}, with no portable body to render from, so the "
+                f"{fallback} body is written unchanged and will not run"
+            ),
+            object_ref=scope,
+            remedy=f"add a {self.sql_dialect} or ANSI_SQL expression",
+        )
+        return fallback, available[fallback]
+
+    def definition(self, block: Block, expression: Any, model: Model, scope: str) -> None:
+        """Write a `definition` property for a field or a measure."""
+        dialect, text = self.pick_body(expression, scope)
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+            return
+        block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+
+    def to_aml_sql(self, expression: str, dialect: str, model: Model, scope: str) -> str:
+        """An Ossie SQL expression with its references written as AML interpolation.
+
+        A bare column name does compile as AML, but AQL reads the interpolation
+        to learn which field the body depends on. A body without it loses the
+        query rewriting and the optimisation that link drives, so this restores
+        every reference rather than passing the SQL through.
+        """
+        if dialect in sqlrefs.NOT_SQL or not sqlrefs.AVAILABLE:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body is tagged {dialect!r}, which is not Ossie SQL this converter can "
+                    f"read, so its field references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="supply an ANSI_SQL or warehouse-SQL dialect for this expression",
+            )
+            return expression
+        grouping = sqlrefs.window_grouping(expression, dialect)
+        if grouping:
+            self.issues.add(
+                code=ISSUE_WINDOW_NEEDS_GROUPING,
+                severity=Severity.WARNING,
+                message=(
+                    f"the body has a window function whose frame reads "
+                    f"{', '.join(grouping)}. AML carries it as written, and the warehouse SQL "
+                    f"it generates is valid only for a query that groups by those. A query "
+                    f"that does not, a grand total for one, produces warehouse SQL the "
+                    f"database rejects, and Holistics does not check this at conversion time"
+                ),
+                object_ref=scope,
+                remedy="query it only alongside those fields, or rewrite the body in AQL",
+            )
+        try:
+            return sqlrefs.rewrite(
+                expression, dialect, lambda column: self.to_interpolation(column, model, scope)
+            )
+        except sqlrefs.UnparseableSQL as exc:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"sqlglot cannot read the body as {dialect} ({exc}), so its field "
+                    f"references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="fix the expression, or convert it by hand",
+            )
+            return expression
+
+    def to_interpolation(self, column: sqlrefs.ColumnReference, model: Model, scope: str) -> str:
+        """One Ossie column reference as the AML interpolation it came from."""
+        if not column.table:
+            if column.name in self.metric_aml_name:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Source(column.name).to_aml()
+
+        target = self.by_ossie_name.get(column.table)
+        if target is None:
+            self.issues.add(
+                code=ISSUE_UNKNOWN_QUALIFIER,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body qualifies {column.name!r} with {column.table!r}, which is not "
+                    f"a dataset in this document, so it is left unresolved"
+                ),
+                object_ref=scope,
+                remedy="qualify the reference with a dataset name, or drop the field",
+            )
+            return f"{column.table}.{column.name}"
+        if target is model:
+            # A qualifier naming this model usually names one of its fields. It
+            # can also name a metric this converter put somewhere else, and a
+            # sibling reference to that spells a field the model does not have.
+            if column.name in self.metric_aml_name and self.metric_owner.get(column.name) is not model:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Sibling(self.name_in_aml(column.name, scope)).to_aml()
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body names {column.table}.{column.name}, a field of another dataset. A `@sql` "
+                f"body resolves inside one model, and Holistics rejects this at SQL generation "
+                f"with \"Cannot refer to external field in TableModel/QueryModel\" even though "
+                f"`holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="move the reference into a dimension on its own model, or rewrite the body in AQL",
+        )
+        return interpolation.ModelField(target.aml_fqn, self.name_in_aml(column.name, scope)).to_aml()
+
+    def _measure_reference(self, metric_name: str, model: Model, scope: str) -> str:
+        owner = self.metric_owner.get(metric_name)
+        aml_name = self.metric_aml_name[metric_name]
+        if owner is model:
+            return interpolation.Sibling(self.name_in_aml(aml_name, scope)).to_aml()
+        if owner is None:
+            self.issues.add(
+                code=ISSUE_CROSS_MODEL_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body references the dataset-level metric {metric_name!r}. A `@sql` "
+                    f"body resolves inside one model, so there is no AML spelling for it"
+                ),
+                object_ref=scope,
+                remedy="rewrite the expression in AQL, which does span models",
+            )
+            return metric_name
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body references {metric_name!r}, a measure of model {owner.aml_fqn!r}. A "
+                f"`@sql` body resolves inside one model, and Holistics rejects this at SQL "
+                f"generation with \"Cannot refer to external field in TableModel/QueryModel\" "
+                f"even though `holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="rewrite the expression in AQL, which does span models",
+        )
+        return interpolation.ModelField(owner.aml_fqn, self.name_in_aml(aml_name, scope)).to_aml()
+
+    # -- fields -----------------------------------------------------------
+
+    def aml_type(
+        self, payload: dict[str, Any], data: dict[str, Any], scope: str, model: Model | None = None
+    ) -> str:
+        stashed = data.get("type")
+        if stashed:
+            return stashed
+        datatype = payload.get("datatype")
+        mapped = OSSIE_TO_AML_TYPE.get(datatype) if datatype else None
+        if mapped:
+            return mapped
+        if model is not None and payload["name"] in model.numeric:
+            # A metric aggregates this field with `sum` or `avg`, so it is a
+            # number whatever the document failed to say.
+            return "number"
+        self.issues.add(
+            code=ISSUE_ASSUMED_TYPE,
+            severity=Severity.WARNING,
+            message=(
+                f"AML requires a type and the Ossie datatype is {datatype!r}, "
+                f"so {FALLBACK_TYPE!r} is written"
+            ),
+            object_ref=scope,
+            remedy="set a datatype on the field, or edit the AML type after conversion",
+        )
+        return FALLBACK_TYPE
+
+    def common_properties(
+        self,
+        block: Block,
+        payload: dict[str, Any],
+        data: dict[str, Any],
+        scope: str,
+        model: Model | None = None,
+    ) -> None:
+        block.text("label", data.get("label") or titleize(payload["name"]))
+        block.property("type", quote(self.aml_type(payload, data, scope, model)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+    def dimension(self, model: Model, payload: dict[str, Any], primary_key: set[str]) -> Block:
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        block.flag("primary_key", name in primary_key)
+        return block
+
+    def dataset_dimension(self, model: Model, payload: dict[str, Any]) -> Block:
+        """A field the forward path took from a dataset-level AML dimension."""
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        block.property("model", model.reference)
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        return block
+
+    def measure(self, model: Model, payload: dict[str, Any]) -> Block:
+        """One Ossie metric as a `measure` on its owning model.
+
+        `aggregation_type` and the body compose into one Ossie expression on the
+        way out, so this splits them back apart. When the stashed aggregation
+        does not wrap the whole expression, the expression was edited after the
+        forward path wrote it, and `custom` keeps it whole rather than letting
+        the measure aggregate twice.
+        """
+        metric_name = payload["name"]
+        aml_name = self.metric_aml_name[metric_name]
+        scope = f"{model.ossie_name}.{aml_name}"
+        data = stash.read(payload)
+        block = Block(f"measure {self.name_in_aml(aml_name, scope)}")
+        block.text("label", data.get("label") or titleize(aml_name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        aggregation = data.get("aggregation_type") or CUSTOM_AGGREGATION
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+        else:
+            if aggregation in AGGREGATIONS:
+                inner = strip_aggregation(aggregation, text)
+                if inner is None:
+                    self.issues.add(
+                        code=ISSUE_AGGREGATION_NOT_STRIPPED,
+                        severity=Severity.WARNING,
+                        message=(
+                            f"the stashed aggregation {aggregation!r} does not wrap the whole "
+                            f"expression, so the measure is written as 'custom' with the "
+                            f"expression kept whole"
+                        ),
+                        object_ref=scope,
+                        remedy="check the expression against the aggregation",
+                    )
+                    aggregation = CUSTOM_AGGREGATION
+                else:
+                    text = inner
+            block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+        block.property("aggregation_type", quote(aggregation))
+        block.text("format", data.get("format"))
+        return block
+
+    def as_aql(self, text: str, dialect: str, scope: str) -> str | None:
+        """A dataset-level metric's Ossie SQL body rendered as AQL, or None if it cannot be.
+
+        AML accepts only `@aql` here, so an Ossie SQL body either becomes AQL or has no
+        AML form at all. `aql.translate` is a name map over functions this
+        converter has paired with an AQL equivalent. Anything outside that table
+        raises `Untranslatable`, and the metric is dropped with an ERROR.
+        """
+        try:
+            rendered, numeric = aql.translate(
+                text, dialect, lambda table, column: self.aql_reference(table, column, scope)
+            )
+        except aql.Untranslatable as exc:
+            self.issues.add(
+                code=ISSUE_METRIC_NOT_TRANSLATED,
+                severity=Severity.ERROR,
+                message=(
+                    f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                    f"converter did not translate this {dialect} body, and the metric is "
+                    f"dropped. {exc}"
+                ),
+                object_ref=scope,
+                remedy="rewrite the metric in AQL, or scope it to a single dataset",
+            )
+            return None
+        self.issues.add(
+            code=ISSUE_RENDERED_AS_AQL,
+            severity=Severity.WARNING,
+            message=(
+                f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                f"{dialect} expression was rendered as AQL: {text!r} became {rendered!r}"
+            ),
+            object_ref=scope,
+            remedy="check the AQL against the Ossie SQL it came from",
+        )
+        for table, column in numeric:
+            target = self.by_ossie_name.get(table)
+            if target is not None:
+                target.numeric.add(self.name_in_aml(column, scope))
+        return rendered
+
+    def aql_reference(self, table: str, column: str, scope: str) -> str:
+        """One column of an Ossie SQL metric body as the AQL reference it becomes.
+
+        AQL names a field `model.field`, which is the shape the Ossie expression
+        already uses, so this maps the Ossie dataset name onto the AML model
+        name and keeps the field name.
+
+        An Ossie SQL body may name a warehouse column the document does not declare as
+        a field. `SUM(orders.subtotal) / COUNT(DISTINCT customers.customer_id)`
+        in `converters/nvidia/tests/fixtures/sales.ossie.yaml` is one: `orders`
+        declares no `subtotal`. Ossie SQL resolves that against the table, and AQL
+        does not, answering `Field `subtotal` not found in model `orders``. So
+        the column becomes a hidden dimension on that model, and the AQL
+        reference points at it.
+        """
+        if not table:
+            # An unqualified name that is a metric is a metric reference, which
+            # AQL takes: a dataset-level one by its bare name, and a measure by
+            # the model that holds it.
+            if column in self.metric_aml_name:
+                referenced = self.name_in_aml(self.metric_aml_name[column], scope)
+                owner = self.metric_owner.get(column)
+                return referenced if owner is None else f"{owner.aml_fqn}.{referenced}"
+            raise aql.Untranslatable(
+                f"{column!r} names no dataset, and a metric spanning models has no single "
+                f"model to resolve it against."
+            )
+        target = self.by_ossie_name.get(table)
+        if target is None:
+            raise aql.Untranslatable(f"{table!r} is not a dataset in this document.")
+        name = self.name_in_aml(column, scope)
+        declared = {
+            field["name"] for field in target.payload.get("fields") or []
+        } | {self.metric_aml_name[m["name"]] for m in target.measures}
+        if name not in declared and name not in target.borrowed:
+            target.borrowed.append(name)
+            self.issues.add(
+                code=ISSUE_BORROWED_COLUMN,
+                severity=Severity.WARNING,
+                message=(
+                    f"the metric reads {table}.{column}, which the dataset does not declare "
+                    f"as a field. AQL resolves a reference against declared fields only, so "
+                    f"{column!r} is added to model {target.aml_fqn!r} as a hidden dimension "
+                    f"over the column of that name"
+                ),
+                object_ref=scope,
+                remedy=f"declare {column!r} as a field of {table!r} in Ossie",
+            )
+        return f"{target.aml_fqn}.{name}"
+
+    def dataset_metric(self, payload: dict[str, Any]) -> Block | None:
+        """One Ossie metric as a dataset-level AML `metric`.
+
+        AML accepts only an `@aql` body here. The compiler rejects `@sql` with
+        "Incompatible property 'definition' of 'Metric'", so a cross-model
+        metric carrying Ossie SQL has no AML form at all.
+        """
+        name = payload["name"]
+        scope = name
+        data = stash.read(payload)
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        if dialect != AQL_DIALECT:
+            rendered = self.as_aql(text, dialect, scope)
+            if rendered is None:
+                return None
+            text = rendered
+        block = Block(f"metric {self.name_in_aml(name, scope)}")
+        block.text("label", data.get("label") or titleize(name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+        block.heredoc("definition", "aql", text)
+        block.text("format", data.get("format"))
+        return block
+
+    # -- models -----------------------------------------------------------
+
+    def model_file(self, model: Model) -> str:
+        payload = model.payload
+        data = model.stash
+        scope = model.ossie_name
+        is_query = data.get("aml_type") == "QueryModel" or (
+            "aml_type" not in data and bool(interpolation.query_forms_used(payload.get("source", "")))
+        )
+        source = payload.get("source", "")
+        if "aml_type" not in data and not is_query:
+            is_query = _looks_like_query(source)
+
+        block = Block(f"Model {model.aml_name}")
+        block.property("type", quote("query" if is_query else "table"))
+        block.text("label", data.get("label") or titleize(model.aml_name))
+        block.text("description", payload.get("description"))
+        block.text("data_source_name", data.get("data_source_name") or self.data_source_name)
+        if is_query:
+            referenced = _models_referenced(source)
+            if referenced:
+                block.property("models", f"[{', '.join(sorted(referenced))}]")
+            block.blank()
+            block.heredoc("query", "sql", source)
+        else:
+            block.text("table_name", data.get("table_name") or source)
+
+        for param in data.get("param") or []:
+            block.blank()
+            param_block = block.block(f"param {self.name_in_aml(param['name'], scope)}")
+            param_block.text("label", param.get("label") or titleize(param["name"]))
+            param_block.property("type", quote(param.get("type") or FALLBACK_TYPE))
+
+        persistence = data.get("persistence")
+        if persistence:
+            block.blank()
+            _write_persistence(block, persistence)
+
+        primary_key = set(payload.get("primary_key") or [])
+        for field in payload.get("fields") or []:
+            if stash.read(field).get("scope") == "dataset":
+                continue
+            block.blank()
+            block.lines.append(self.dimension(model, field, primary_key))
+
+        for metric in model.measures:
+            block.blank()
+            block.lines.append(self.measure(model, metric))
+
+        for column in model.borrowed:
+            block.blank()
+            borrowed = block.block(f"dimension {column}")
+            borrowed.text("label", titleize(column))
+            borrowed.property("type", quote(FALLBACK_TYPE_FOR_BORROWED))
+            borrowed.flag("hidden", True)
+            borrowed.heredoc("definition", "sql", interpolation.Source(column).to_aml())
+
+        owner = data.get("owner") or self.root_stash.get("owner")
+        if owner:
+            block.blank()
+            block.text("owner", owner)
+        return amlgen.document(block, license_header=True)
+
+    # -- dataset ----------------------------------------------------------
+
+    def relationship(self, payload: dict[str, Any]) -> str:
+        data = stash.read(payload)
+        kind = data.get("type", "many_to_one")
+        active = "true" if data.get("active", True) else "false"
+        from_model = self.by_ossie_name.get(payload.get("from"))
+        to_model = self.by_ossie_name.get(payload.get("to"))
+        if from_model is None or to_model is None:
+            missing = payload.get("from") if from_model is None else payload.get("to")
+            raise ConversionError(
+                f"relationship {payload.get('name')!r} names dataset {missing!r}, "
+                f"which is not in this document"
+            )
+        from_columns = payload.get("from_columns") or []
+        to_columns = payload.get("to_columns") or []
+
+        if len(from_columns) == 1 and kind in ("many_to_one", "one_to_one"):
+            operator = ">" if kind == "many_to_one" else "-"
+            return (
+                f"relationship({from_model.reference}.{from_columns[0]} {operator} "
+                f"{to_model.reference}.{to_columns[0]}, {active})"
+            )
+
+        config = Block("RelationshipConfig")
+        rel = config.block("EqualityRelationship")
+        rel.header = "rel: EqualityRelationship"
+        rel.property("type", quote(kind))
+        rel.property("from", _field_ref(from_model.aml_name, from_columns[0]))
+        rel.property("to", _field_ref(to_model.aml_name, to_columns[0]))
+        for from_column, to_column in zip(from_columns[1:], to_columns[1:]):
+            on = rel.block("on")
+            on.property("from", _field_ref(from_model.aml_name, from_column))
+            on.property("to", _field_ref(to_model.aml_name, to_column))
+        config.property("active", active)
+        return config.render(2).lstrip()
+
+    def dataset_file(self) -> tuple[str, str]:
+        name = self.dataset_name
+        block = Block(f"Dataset {name}")
+        block.text(
+            "label",
+            self.root_stash.get("label") or titleize(self.document.get("name") or name),
+        )
+        block.text("description", self.document.get("description"))
+        block.text("data_source_name", self.data_source_name)
+        block.blank()
+        block.property("models", amlgen.array([m.reference for m in self.models]))
+        block.blank()
+        block.property(
+            "relationships",
+            amlgen.array(
+                [self.relationship(r) for r in self.document.get("relationships") or []]
+            ),
+        )
+
+        for model in self.models:
+            for field in model.payload.get("fields") or []:
+                if stash.read(field).get("scope") == "dataset":
+                    block.blank()
+                    block.lines.append(self.dataset_dimension(model, field))
+
+        for metric in self.dataset_metrics:
+            written = self.dataset_metric(metric)
+            if written is not None:
+                block.blank()
+                block.lines.append(written)
+
+        owner = self.root_stash.get("owner")
+        if owner:
+            block.blank()
+            block.text("owner", owner)
+        return f"{name}.dataset.aml", amlgen.document(block, license_header=True)
+
+    def run(self) -> Result:
+        # The dataset file is rendered first because its metrics decide which
+        # columns each model has to borrow, and a model file has to carry those
+        # as dimensions. The output order is unchanged: models, then dataset.
+        dataset = self.dataset_file()
+        files = [(m.path, self.model_file(m)) for m in self.models]
+        files.append(dataset)
+        return Result(files, self.issues)
+
+
+def _field_ref(model_name: str, column: str) -> str:
+    return f"FieldRef {{ model: {quote(model_name)}, field: {quote(column)} }}"
+
+
+def _write_persistence(block: Block, persistence: dict[str, Any]) -> None:
+    """The stashed persistence object as its AML block.
+
+    `__type__` names the block, and every key the compiler added for its own
+    bookkeeping starts and ends with `__`, so those are skipped.
+    """
+    kind = persistence.get("__type__") or "FullPersistence"
+    child = block.block(f"persistence: {kind}")
+    for key, value in persistence.items():
+        if key.startswith("__"):
+            continue

Review Comment:
   `str(value).lower()` turns a list or dict into Python repr text (`['a']`), which isn't valid AML, and `None` into `none`.
   
   Could we handle bool, number, string, list and mapping explicitly, and raise on anything else?



##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}
+
+
+class _Reverse:
+    def __init__(
+        self, document: dict[str, Any], data_source_name: str | None, sql_dialect: str
+    ):
+        self.document = document
+        self.sql_dialect = sql_dialect
+        self.issues = IssueLog()
+        self.root_stash = stash.read(document)
+        self.data_source_name = self.root_stash.get("data_source_name") or data_source_name
+        if not self.data_source_name:
+            raise ConversionError(
+                "the document carries no HOLISTICS data_source_name, so one must be "
+                "supplied: pass --data-source-name naming the Holistics connection"
+            )
+
+        #: AML identifier to the Ossie name it was spelled from, so two names
+        #: that collapse onto one spelling fail rather than overwrite.
+        self._renamed: dict[str, str] = {}
+
+        datasets = _named_objects(document.get("datasets"), "datasets")
+        if not datasets:
+            raise ConversionError(
+                "the document declares no datasets, and the specification requires at least one"
+            )
+        for dataset in datasets:
+            _named_objects(dataset.get("fields"), f"datasets[{dataset['name']}].fields")
+        _named_objects(document.get("metrics"), "metrics")
+
+        self.models: list[Model] = []
+        for dataset in datasets:
+            name = dataset["name"]
+            data = stash.read(dataset)
+            self.models.append(
+                Model(
+                    ossie_name=name,
+                    fqn=data.get("fqn") or unflatten(name),
+                    payload=dataset,
+                    stash=data,
+                )
+            )
+        self.by_ossie_name = {m.ossie_name: m for m in self.models}
+
+        taken: dict[str, str] = {}
+        for model in self.models:
+            clash = taken.setdefault(model.aml_fqn, model.ossie_name)
+            if clash != model.ossie_name:
+                raise ConversionError(
+                    f"datasets {clash!r} and {model.ossie_name!r} both spell as the AML "
+                    f"model {model.aml_fqn!r}; rename one of them in Ossie"
+                )
+
+        self.dataset_name = self._dataset_name()
+
+        #: Every metric that belongs on a model, indexed by Ossie metric name,
+        #: alongside the AML measure name it is written as.
+        self.metric_owner: dict[str, Model] = {}
+        self.metric_aml_name: dict[str, str] = {}
+        self.dataset_metrics: list[dict[str, Any]] = []
+        self._metric_payloads: dict[str, dict[str, Any]] = {}
+        self._metric_datasets: dict[str, Any] = {}
+        self._cyclic_metrics: set[str] = set()
+        self._place_metrics()
+
+    # -- placement --------------------------------------------------------
+
+    def _place_metrics(self) -> None:
+        """Decide where each Ossie metric goes: on a model, or on the dataset.
+
+        A stashed `model` settles it. Without one, the expression decides: a
+        body naming exactly one dataset becomes a measure on that model, and a
+        body naming several becomes a dataset-level metric, which is the only
+        AML construct that spans models. A body may also name another metric,
+        and `_scan_for_datasets` covers what that counts as.
+        """
+        metrics = self.document.get("metrics") or []
+        for metric in metrics:
+            name = metric.get("name")
+            self.metric_aml_name[name] = stash.read(metric).get("aml_name") or name
+            self._metric_payloads[name] = metric
+        for metric in metrics:
+            name = metric.get("name")
+            named = self._datasets_named(name) or frozenset()
+            owner = self.by_ossie_name[next(iter(named))] if len(named) == 1 else None
+            if owner is None:
+                self.dataset_metrics.append(metric)
+            else:
+                owner.measures.append(metric)
+                self.metric_owner[name] = owner
+        self._report_metric_cycles()
+
+    def _datasets_named(self, name: str) -> frozenset[str] | None:
+        """The Ossie datasets metric `name` resolves to, or None when that is unknown.
+
+        None covers every reading that cannot put the metric on a single model:
+        an AQL body, Ossie SQL this converter cannot read, and a reference cycle.
+        """
+        resolved = self._metric_datasets.get(name, _UNVISITED)
+        if resolved is _RESOLVING:
+            self._cyclic_metrics.add(name)
+            return None
+        if resolved is not _UNVISITED:
+            return resolved
+        self._metric_datasets[name] = _RESOLVING
+        result = self._scan_for_datasets(name)
+        self._metric_datasets[name] = result
+        return result
+
+    def _scan_for_datasets(self, name: str) -> frozenset[str] | None:
+        """Which datasets one metric body names, directly or through a metric.
+
+        An Ossie metric body may name another metric instead of a column, as
+        `cities__upstream_measure + 1` in `tests/fixtures/ecommerce` does. That
+        body names no dataset of its own, and the datasets the metric it
+        references resolves to stand in for it. Without that substitution a
+        metric built only from other metrics lands on the dataset, where AML
+        takes an AQL body, and the Ossie SQL name it was written with does not
+        resolve.
+        """
+        metric = self._metric_payloads[name]
+        data = stash.read(metric)
+        owner_fqn = data.get("model")
+        if owner_fqn:
+            owner = next((m for m in self.models if m.fqn == owner_fqn), None)
+            if owner is None:
+                raise ConversionError(
+                    f"metric {name!r} is stashed against model {owner_fqn!r}, "
+                    f"which is not a dataset in this document"
+                )
+            return frozenset({owner.ossie_name})
+        available = dialects_of(metric.get("expression"))
+        if AQL_DIALECT in available:
+            return None
+        dialect = next(
+            (d for d in (self.sql_dialect, *PORTABLE_DIALECTS) if d in available), None
+        )
+        if dialect is None:
+            return None
+        try:
+            references = sqlrefs.columns(available[dialect], dialect)
+        except sqlrefs.UnparseableSQL:
+            return None
+        named = {c.table for c in references if c.table in self.by_ossie_name}
+        for reference in references:
+            if reference.table or reference.name not in self._metric_payloads:
+                continue
+            through = self._datasets_named(reference.name)
+            if through is None:
+                return None
+            named |= through
+        return frozenset(named)
+
+    def _report_metric_cycles(self) -> None:
+        for name in sorted(self._cyclic_metrics):
+            self.issues.add(
+                code=ISSUE_METRIC_CYCLE,
+                severity=Severity.ERROR,
+                message=(
+                    f"metric {name!r} references itself through another metric. Holistics "
+                    f"inlines one metric into the body of the next, so a cycle has no warehouse SQL, "
+                    f"and `holistics aml validate` accepts the file without catching it"
+                ),
+                object_ref=name,
+                remedy="break the cycle in Ossie",
+            )
+
+    # -- names ------------------------------------------------------------
+
+    def _dataset_name(self) -> str:
+        """The AML `Dataset` name, moved aside when a model already has it.
+
+        Ossie keeps the semantic model's name and its dataset names in separate
+        namespaces, so a document may use one name for both. Three fixtures in
+        this repository do, including
+        `converters/cube/tests/fixtures/databricks_ossie.yaml`, whose root name
+        and first dataset are both `orders`. AML has one namespace for `Dataset`
+        and `Model`, and rejects the pair with "Duplicated name 'orders'".
+
+        Nothing references the AML dataset name. Models reference each other and
+        relationships reference models, so the dataset is the safe side to move.
+        """
+        name = self.root_stash.get("fqn") or self.document.get("name")
+        if not name:
+            raise ConversionError("the document has no name")
+        spelled = self.name_in_aml(name, str(name))
+        taken = {model.aml_fqn for model in self.models} | {
+            model.aml_name for model in self.models
+        }
+        if spelled not in taken:
+            return spelled
+        candidate, suffix = f"{spelled}_dataset", 2
+        while candidate in taken:
+            candidate, suffix = f"{spelled}_dataset_{suffix}", suffix + 1
+        self.issues.add(
+            code=ISSUE_DATASET_RENAMED,
+            severity=Severity.WARNING,
+            message=(
+                f"a model is already named {spelled!r}, and AML holds Dataset and Model "
+                f"in one namespace, so the dataset is written as {candidate!r}"
+            ),
+            object_ref=str(name),
+            remedy="rename the semantic model or the dataset in Ossie",
+        )
+        return candidate
+
+    def name_in_aml(self, name: str, scope: str) -> str:
+        """An Ossie name as the AML identifier it is written as.
+
+        Lookups elsewhere stay keyed on the Ossie name, because that is what an
+        expression references. Only the output spelling changes, and every site
+        that writes a name goes through here, so a declaration and a reference
+        to it cannot disagree.
+        """
+        spelled = sanitize(name)
+        if spelled != name:
+            previous = self._renamed.setdefault(spelled, name)
+            if previous != name:
+                raise ConversionError(
+                    f"{scope}: {name!r} and {previous!r} both spell as the AML "
+                    f"identifier {spelled!r}; rename one of them in Ossie"
+                )
+            self.issues.add(
+                code=ISSUE_RENAMED,
+                severity=Severity.WARNING,
+                message=(
+                    f"{name!r} is not a legal AML identifier and is written as "
+                    f"{spelled!r}. AML allows letters, digits and underscore, and no "
+                    f"leading digit"
+                ),
+                object_ref=scope,
+                remedy=f"rename it to {spelled!r} in Ossie to keep the two in step",
+            )
+        return spelled
+
+    # -- expressions ------------------------------------------------------
+
+    def pick_body(self, expression: Any, scope: str) -> tuple[str, str]:
+        """The body to write and the dialect it is in, after any rendering.
+
+        AQL wins outright. It came out of AML unchanged and goes back unchanged.
+
+        For Ossie SQL the target is `--sql-dialect`, the warehouse the Holistics
+        connection reads. A body already in that dialect is written as it
+        stands. Otherwise a portable body is rendered into the target with
+        sqlglot, because the alternative is AML that will not run. An expression
+        offering neither has no body this connection can execute, and the
+        converter says so rather than writing Holistics SQL for the wrong warehouse.
+        """
+        available = dialects_of(expression)
+        if AQL_DIALECT in available:
+            return AQL_DIALECT, available[AQL_DIALECT]
+        if self.sql_dialect in available:
+            return self.sql_dialect, available[self.sql_dialect]
+
+        source = next((d for d in PORTABLE_DIALECTS if d in available), None)
+        if source is not None:
+            try:
+                rendered = sqlrefs.transpile(available[source], source, self.sql_dialect)
+            except sqlrefs.UnparseableSQL as exc:
+                self.issues.add(
+                    code=ISSUE_UNPARSEABLE_SQL,
+                    severity=Severity.ERROR,
+                    message=(
+                        f"the {source} body cannot be rendered as {self.sql_dialect} ({exc}), "
+                        f"so it is written unchanged and may not run"
+                    ),
+                    object_ref=scope,
+                    remedy=f"add a {self.sql_dialect} expression, or fix the {source} one",
+                )
+                return source, available[source]
+            self.issues.add(
+                code=ISSUE_TRANSPILED,
+                severity=Severity.WARNING,
+                message=(
+                    f"no {self.sql_dialect} expression, so the {source} one was rendered "
+                    f"into it: {available[source]!r} became {rendered!r}"
+                ),
+                object_ref=scope,
+                remedy=f"add a {self.sql_dialect} expression to keep the body exact",
+            )
+            return self.sql_dialect, rendered
+
+        fallback = next(iter(available))
+        self.issues.add(
+            code=ISSUE_NO_USABLE_DIALECT,
+            severity=Severity.ERROR,
+            message=(
+                f"the expression offers {', '.join(sorted(available))} and the connection "
+                f"reads {self.sql_dialect}, with no portable body to render from, so the "
+                f"{fallback} body is written unchanged and will not run"
+            ),
+            object_ref=scope,
+            remedy=f"add a {self.sql_dialect} or ANSI_SQL expression",
+        )
+        return fallback, available[fallback]
+
+    def definition(self, block: Block, expression: Any, model: Model, scope: str) -> None:
+        """Write a `definition` property for a field or a measure."""
+        dialect, text = self.pick_body(expression, scope)
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+            return
+        block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+
+    def to_aml_sql(self, expression: str, dialect: str, model: Model, scope: str) -> str:
+        """An Ossie SQL expression with its references written as AML interpolation.
+
+        A bare column name does compile as AML, but AQL reads the interpolation
+        to learn which field the body depends on. A body without it loses the
+        query rewriting and the optimisation that link drives, so this restores
+        every reference rather than passing the SQL through.
+        """
+        if dialect in sqlrefs.NOT_SQL or not sqlrefs.AVAILABLE:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body is tagged {dialect!r}, which is not Ossie SQL this converter can "
+                    f"read, so its field references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="supply an ANSI_SQL or warehouse-SQL dialect for this expression",
+            )
+            return expression
+        grouping = sqlrefs.window_grouping(expression, dialect)
+        if grouping:
+            self.issues.add(
+                code=ISSUE_WINDOW_NEEDS_GROUPING,
+                severity=Severity.WARNING,
+                message=(
+                    f"the body has a window function whose frame reads "
+                    f"{', '.join(grouping)}. AML carries it as written, and the warehouse SQL "
+                    f"it generates is valid only for a query that groups by those. A query "
+                    f"that does not, a grand total for one, produces warehouse SQL the "
+                    f"database rejects, and Holistics does not check this at conversion time"
+                ),
+                object_ref=scope,
+                remedy="query it only alongside those fields, or rewrite the body in AQL",
+            )
+        try:
+            return sqlrefs.rewrite(
+                expression, dialect, lambda column: self.to_interpolation(column, model, scope)
+            )
+        except sqlrefs.UnparseableSQL as exc:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"sqlglot cannot read the body as {dialect} ({exc}), so its field "
+                    f"references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="fix the expression, or convert it by hand",
+            )
+            return expression
+
+    def to_interpolation(self, column: sqlrefs.ColumnReference, model: Model, scope: str) -> str:
+        """One Ossie column reference as the AML interpolation it came from."""
+        if not column.table:
+            if column.name in self.metric_aml_name:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Source(column.name).to_aml()
+
+        target = self.by_ossie_name.get(column.table)
+        if target is None:
+            self.issues.add(
+                code=ISSUE_UNKNOWN_QUALIFIER,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body qualifies {column.name!r} with {column.table!r}, which is not "
+                    f"a dataset in this document, so it is left unresolved"
+                ),
+                object_ref=scope,
+                remedy="qualify the reference with a dataset name, or drop the field",
+            )
+            return f"{column.table}.{column.name}"
+        if target is model:
+            # A qualifier naming this model usually names one of its fields. It
+            # can also name a metric this converter put somewhere else, and a
+            # sibling reference to that spells a field the model does not have.
+            if column.name in self.metric_aml_name and self.metric_owner.get(column.name) is not model:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Sibling(self.name_in_aml(column.name, scope)).to_aml()
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body names {column.table}.{column.name}, a field of another dataset. A `@sql` "
+                f"body resolves inside one model, and Holistics rejects this at SQL generation "
+                f"with \"Cannot refer to external field in TableModel/QueryModel\" even though "
+                f"`holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="move the reference into a dimension on its own model, or rewrite the body in AQL",
+        )
+        return interpolation.ModelField(target.aml_fqn, self.name_in_aml(column.name, scope)).to_aml()
+
+    def _measure_reference(self, metric_name: str, model: Model, scope: str) -> str:
+        owner = self.metric_owner.get(metric_name)
+        aml_name = self.metric_aml_name[metric_name]
+        if owner is model:
+            return interpolation.Sibling(self.name_in_aml(aml_name, scope)).to_aml()
+        if owner is None:
+            self.issues.add(
+                code=ISSUE_CROSS_MODEL_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body references the dataset-level metric {metric_name!r}. A `@sql` "
+                    f"body resolves inside one model, so there is no AML spelling for it"
+                ),
+                object_ref=scope,
+                remedy="rewrite the expression in AQL, which does span models",
+            )
+            return metric_name
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body references {metric_name!r}, a measure of model {owner.aml_fqn!r}. A "
+                f"`@sql` body resolves inside one model, and Holistics rejects this at SQL "
+                f"generation with \"Cannot refer to external field in TableModel/QueryModel\" "
+                f"even though `holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="rewrite the expression in AQL, which does span models",
+        )
+        return interpolation.ModelField(owner.aml_fqn, self.name_in_aml(aml_name, scope)).to_aml()
+
+    # -- fields -----------------------------------------------------------
+
+    def aml_type(
+        self, payload: dict[str, Any], data: dict[str, Any], scope: str, model: Model | None = None
+    ) -> str:
+        stashed = data.get("type")
+        if stashed:
+            return stashed
+        datatype = payload.get("datatype")
+        mapped = OSSIE_TO_AML_TYPE.get(datatype) if datatype else None
+        if mapped:
+            return mapped
+        if model is not None and payload["name"] in model.numeric:
+            # A metric aggregates this field with `sum` or `avg`, so it is a
+            # number whatever the document failed to say.
+            return "number"
+        self.issues.add(
+            code=ISSUE_ASSUMED_TYPE,
+            severity=Severity.WARNING,
+            message=(
+                f"AML requires a type and the Ossie datatype is {datatype!r}, "
+                f"so {FALLBACK_TYPE!r} is written"
+            ),
+            object_ref=scope,
+            remedy="set a datatype on the field, or edit the AML type after conversion",
+        )
+        return FALLBACK_TYPE
+
+    def common_properties(
+        self,
+        block: Block,
+        payload: dict[str, Any],
+        data: dict[str, Any],
+        scope: str,
+        model: Model | None = None,
+    ) -> None:
+        block.text("label", data.get("label") or titleize(payload["name"]))
+        block.property("type", quote(self.aml_type(payload, data, scope, model)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+    def dimension(self, model: Model, payload: dict[str, Any], primary_key: set[str]) -> Block:
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        block.flag("primary_key", name in primary_key)
+        return block
+
+    def dataset_dimension(self, model: Model, payload: dict[str, Any]) -> Block:
+        """A field the forward path took from a dataset-level AML dimension."""
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        block.property("model", model.reference)
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        return block
+
+    def measure(self, model: Model, payload: dict[str, Any]) -> Block:
+        """One Ossie metric as a `measure` on its owning model.
+
+        `aggregation_type` and the body compose into one Ossie expression on the
+        way out, so this splits them back apart. When the stashed aggregation
+        does not wrap the whole expression, the expression was edited after the
+        forward path wrote it, and `custom` keeps it whole rather than letting
+        the measure aggregate twice.
+        """
+        metric_name = payload["name"]
+        aml_name = self.metric_aml_name[metric_name]
+        scope = f"{model.ossie_name}.{aml_name}"
+        data = stash.read(payload)
+        block = Block(f"measure {self.name_in_aml(aml_name, scope)}")
+        block.text("label", data.get("label") or titleize(aml_name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        aggregation = data.get("aggregation_type") or CUSTOM_AGGREGATION
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+        else:
+            if aggregation in AGGREGATIONS:
+                inner = strip_aggregation(aggregation, text)
+                if inner is None:
+                    self.issues.add(
+                        code=ISSUE_AGGREGATION_NOT_STRIPPED,
+                        severity=Severity.WARNING,
+                        message=(
+                            f"the stashed aggregation {aggregation!r} does not wrap the whole "
+                            f"expression, so the measure is written as 'custom' with the "
+                            f"expression kept whole"
+                        ),
+                        object_ref=scope,
+                        remedy="check the expression against the aggregation",
+                    )
+                    aggregation = CUSTOM_AGGREGATION
+                else:
+                    text = inner
+            block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+        block.property("aggregation_type", quote(aggregation))
+        block.text("format", data.get("format"))
+        return block
+
+    def as_aql(self, text: str, dialect: str, scope: str) -> str | None:
+        """A dataset-level metric's Ossie SQL body rendered as AQL, or None if it cannot be.
+
+        AML accepts only `@aql` here, so an Ossie SQL body either becomes AQL or has no
+        AML form at all. `aql.translate` is a name map over functions this
+        converter has paired with an AQL equivalent. Anything outside that table
+        raises `Untranslatable`, and the metric is dropped with an ERROR.
+        """
+        try:
+            rendered, numeric = aql.translate(
+                text, dialect, lambda table, column: self.aql_reference(table, column, scope)
+            )
+        except aql.Untranslatable as exc:
+            self.issues.add(
+                code=ISSUE_METRIC_NOT_TRANSLATED,
+                severity=Severity.ERROR,
+                message=(
+                    f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                    f"converter did not translate this {dialect} body, and the metric is "
+                    f"dropped. {exc}"
+                ),
+                object_ref=scope,
+                remedy="rewrite the metric in AQL, or scope it to a single dataset",
+            )
+            return None
+        self.issues.add(
+            code=ISSUE_RENDERED_AS_AQL,
+            severity=Severity.WARNING,
+            message=(
+                f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                f"{dialect} expression was rendered as AQL: {text!r} became {rendered!r}"
+            ),
+            object_ref=scope,
+            remedy="check the AQL against the Ossie SQL it came from",
+        )
+        for table, column in numeric:
+            target = self.by_ossie_name.get(table)
+            if target is not None:
+                target.numeric.add(self.name_in_aml(column, scope))
+        return rendered
+
+    def aql_reference(self, table: str, column: str, scope: str) -> str:
+        """One column of an Ossie SQL metric body as the AQL reference it becomes.
+
+        AQL names a field `model.field`, which is the shape the Ossie expression
+        already uses, so this maps the Ossie dataset name onto the AML model
+        name and keeps the field name.
+
+        An Ossie SQL body may name a warehouse column the document does not declare as
+        a field. `SUM(orders.subtotal) / COUNT(DISTINCT customers.customer_id)`
+        in `converters/nvidia/tests/fixtures/sales.ossie.yaml` is one: `orders`
+        declares no `subtotal`. Ossie SQL resolves that against the table, and AQL
+        does not, answering `Field `subtotal` not found in model `orders``. So
+        the column becomes a hidden dimension on that model, and the AQL
+        reference points at it.
+        """
+        if not table:
+            # An unqualified name that is a metric is a metric reference, which
+            # AQL takes: a dataset-level one by its bare name, and a measure by
+            # the model that holds it.
+            if column in self.metric_aml_name:
+                referenced = self.name_in_aml(self.metric_aml_name[column], scope)
+                owner = self.metric_owner.get(column)
+                return referenced if owner is None else f"{owner.aml_fqn}.{referenced}"
+            raise aql.Untranslatable(
+                f"{column!r} names no dataset, and a metric spanning models has no single "
+                f"model to resolve it against."
+            )
+        target = self.by_ossie_name.get(table)
+        if target is None:
+            raise aql.Untranslatable(f"{table!r} is not a dataset in this document.")
+        name = self.name_in_aml(column, scope)
+        declared = {
+            field["name"] for field in target.payload.get("fields") or []
+        } | {self.metric_aml_name[m["name"]] for m in target.measures}
+        if name not in declared and name not in target.borrowed:
+            target.borrowed.append(name)
+            self.issues.add(
+                code=ISSUE_BORROWED_COLUMN,
+                severity=Severity.WARNING,
+                message=(
+                    f"the metric reads {table}.{column}, which the dataset does not declare "
+                    f"as a field. AQL resolves a reference against declared fields only, so "
+                    f"{column!r} is added to model {target.aml_fqn!r} as a hidden dimension "
+                    f"over the column of that name"
+                ),
+                object_ref=scope,
+                remedy=f"declare {column!r} as a field of {table!r} in Ossie",
+            )
+        return f"{target.aml_fqn}.{name}"
+
+    def dataset_metric(self, payload: dict[str, Any]) -> Block | None:
+        """One Ossie metric as a dataset-level AML `metric`.
+
+        AML accepts only an `@aql` body here. The compiler rejects `@sql` with
+        "Incompatible property 'definition' of 'Metric'", so a cross-model
+        metric carrying Ossie SQL has no AML form at all.
+        """
+        name = payload["name"]
+        scope = name
+        data = stash.read(payload)
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        if dialect != AQL_DIALECT:
+            rendered = self.as_aql(text, dialect, scope)
+            if rendered is None:
+                return None
+            text = rendered
+        block = Block(f"metric {self.name_in_aml(name, scope)}")
+        block.text("label", data.get("label") or titleize(name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+        block.heredoc("definition", "aql", text)
+        block.text("format", data.get("format"))
+        return block
+
+    # -- models -----------------------------------------------------------
+
+    def model_file(self, model: Model) -> str:
+        payload = model.payload
+        data = model.stash
+        scope = model.ossie_name
+        is_query = data.get("aml_type") == "QueryModel" or (
+            "aml_type" not in data and bool(interpolation.query_forms_used(payload.get("source", "")))
+        )
+        source = payload.get("source", "")
+        if "aml_type" not in data and not is_query:
+            is_query = _looks_like_query(source)
+
+        block = Block(f"Model {model.aml_name}")
+        block.property("type", quote("query" if is_query else "table"))
+        block.text("label", data.get("label") or titleize(model.aml_name))
+        block.text("description", payload.get("description"))
+        block.text("data_source_name", data.get("data_source_name") or self.data_source_name)
+        if is_query:
+            referenced = _models_referenced(source)
+            if referenced:
+                block.property("models", f"[{', '.join(sorted(referenced))}]")
+            block.blank()
+            block.heredoc("query", "sql", source)
+        else:
+            block.text("table_name", data.get("table_name") or source)
+
+        for param in data.get("param") or []:
+            block.blank()
+            param_block = block.block(f"param {self.name_in_aml(param['name'], scope)}")
+            param_block.text("label", param.get("label") or titleize(param["name"]))
+            param_block.property("type", quote(param.get("type") or FALLBACK_TYPE))
+
+        persistence = data.get("persistence")
+        if persistence:
+            block.blank()
+            _write_persistence(block, persistence)
+
+        primary_key = set(payload.get("primary_key") or [])
+        for field in payload.get("fields") or []:
+            if stash.read(field).get("scope") == "dataset":
+                continue
+            block.blank()
+            block.lines.append(self.dimension(model, field, primary_key))
+
+        for metric in model.measures:
+            block.blank()
+            block.lines.append(self.measure(model, metric))
+
+        for column in model.borrowed:
+            block.blank()
+            borrowed = block.block(f"dimension {column}")
+            borrowed.text("label", titleize(column))
+            borrowed.property("type", quote(FALLBACK_TYPE_FOR_BORROWED))
+            borrowed.flag("hidden", True)
+            borrowed.heredoc("definition", "sql", interpolation.Source(column).to_aml())
+
+        owner = data.get("owner") or self.root_stash.get("owner")
+        if owner:
+            block.blank()
+            block.text("owner", owner)
+        return amlgen.document(block, license_header=True)
+
+    # -- dataset ----------------------------------------------------------
+
+    def relationship(self, payload: dict[str, Any]) -> str:
+        data = stash.read(payload)
+        kind = data.get("type", "many_to_one")
+        active = "true" if data.get("active", True) else "false"
+        from_model = self.by_ossie_name.get(payload.get("from"))
+        to_model = self.by_ossie_name.get(payload.get("to"))
+        if from_model is None or to_model is None:
+            missing = payload.get("from") if from_model is None else payload.get("to")
+            raise ConversionError(
+                f"relationship {payload.get('name')!r} names dataset {missing!r}, "
+                f"which is not in this document"
+            )
+        from_columns = payload.get("from_columns") or []
+        to_columns = payload.get("to_columns") or []
+
+        if len(from_columns) == 1 and kind in ("many_to_one", "one_to_one"):
+            operator = ">" if kind == "many_to_one" else "-"
+            return (
+                f"relationship({from_model.reference}.{from_columns[0]} {operator} "
+                f"{to_model.reference}.{to_columns[0]}, {active})"
+            )
+
+        config = Block("RelationshipConfig")
+        rel = config.block("EqualityRelationship")
+        rel.header = "rel: EqualityRelationship"
+        rel.property("type", quote(kind))
+        rel.property("from", _field_ref(from_model.aml_name, from_columns[0]))
+        rel.property("to", _field_ref(to_model.aml_name, to_columns[0]))
+        for from_column, to_column in zip(from_columns[1:], to_columns[1:]):

Review Comment:
   When `from_columns` is empty or missing, `len(from_columns) == 1` is false and execution falls through to `from_columns[0]`, which raises `IndexError`. `to_columns[0]` does the same. The CLI catches only `ConversionError` and `OSError`, so `to-aml` exits with a traceback.
   
   The `zip(from_columns[1:], to_columns[1:])` also silently truncates when the lists differ in length, so a three-column key with two target columns emits a two-column join.
   
   Could we require equal, non-zero lengths up front and raise `ConversionError` naming the relationship?



##########
converters/holistics/src/ossie_holistics/ossie_to_aml.py:
##########
@@ -0,0 +1,1041 @@
+# 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.
+
+"""One Apache Ossie semantic model to a set of AML source files.
+
+`convert` returns `(relative path, text)` pairs rather than writing them, so the
+CLI owns every filesystem decision and a test can read the output without a
+temporary directory.
+
+The layout is one dataset file plus one model file per Ossie dataset:
+
+    <dataset>.dataset.aml
+    orders.model.aml                      an Ossie dataset named orders
+    modules/reporting/calendar.model.aml  an Ossie dataset named reporting__calendar
+
+The input file layout is lost on the way in. The compiled JSON the forward path
+reads records which models a dataset holds and not which file each came from, so
+the layout is already gone by the time a document reaches Ossie. AML accepts any
+arrangement, so the generator picks the one above.
+
+Four AML properties are required and have no Ossie field: `label` and `type` on
+every dimension and measure, and `data_source_name` and `relationships` on the
+dataset. A stashed value wins. Otherwise `label` is derived from the name the
+way AML itself derives it, `type` from `datatype`, and `data_source_name` from
+the `--data-source-name` argument.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field as dataclass_field
+from typing import Any
+
+from . import amlgen, aql, interpolation, sqlrefs, stash
+from .amlgen import Block, quote, sanitize, titleize
+from .datatypes import AGGREGATIONS, CUSTOM_AGGREGATION, OSSIE_TO_AML_TYPE, strip_aggregation
+from .errors import ConversionError
+from .issues import IssueLog, Severity
+
+AQL_DIALECT = "HOLISTICS_AQL"
+
+ISSUE_CROSS_MODEL_SQL = "HOLISTICS_CROSS_MODEL_SQL_BODY"
+ISSUE_UNPARSEABLE_SQL = "HOLISTICS_UNPARSEABLE_SQL"
+ISSUE_UNKNOWN_QUALIFIER = "HOLISTICS_UNKNOWN_QUALIFIER"
+ISSUE_METRIC_NOT_TRANSLATED = "HOLISTICS_METRIC_SQL_NOT_TRANSLATED_TO_AQL"
+ISSUE_ASSUMED_TYPE = "HOLISTICS_ASSUMED_TYPE"
+ISSUE_AGGREGATION_NOT_STRIPPED = "HOLISTICS_AGGREGATION_NOT_STRIPPED"
+ISSUE_RENAMED = "HOLISTICS_NAME_NOT_SPELLABLE_IN_AML"
+ISSUE_DATASET_RENAMED = "HOLISTICS_DATASET_NAME_COLLIDES_WITH_MODEL"
+ISSUE_TRANSPILED = "HOLISTICS_EXPRESSION_RENDERED_INTO_TARGET_DIALECT"
+ISSUE_NO_USABLE_DIALECT = "HOLISTICS_NO_USABLE_DIALECT"
+ISSUE_RENDERED_AS_AQL = "HOLISTICS_METRIC_RENDERED_AS_AQL"
+ISSUE_BORROWED_COLUMN = "HOLISTICS_UNDECLARED_COLUMN_ADDED_AS_DIMENSION"
+ISSUE_WINDOW_NEEDS_GROUPING = "HOLISTICS_WINDOW_FUNCTION_NEEDS_A_GROUPING"
+ISSUE_METRIC_CYCLE = "HOLISTICS_METRIC_REFERENCE_CYCLE"
+
+#: Placement markers for `_datasets_named`. A metric that finds one still marked
+#: `_RESOLVING` closed a reference cycle, which no single model can hold.
+_UNVISITED = object()
+_RESOLVING = object()
+
+#: The AML type written for a field whose Ossie `datatype` is absent.
+FALLBACK_TYPE = "text"
+
+#: The AML type for a column borrowed into a model by an AQL metric. Ossie
+#: declares nothing about it, and every borrowed column so far is an aggregate's
+#: argument, so `number` is the reading that lets the metric compile.
+FALLBACK_TYPE_FOR_BORROWED = "number"
+
+
+class Result:
+    def __init__(self, files: list[tuple[str, str]], issues: IssueLog):
+        self.files = files
+        self.issues = issues
+
+
+@dataclass
+class Model:
+    """One Ossie dataset, as the AML model it will be written as."""
+
+    ossie_name: str
+    fqn: str
+    payload: dict[str, Any]
+    stash: dict[str, Any]
+    measures: list[dict[str, Any]] = dataclass_field(default_factory=list)
+    #: Columns an AQL metric needed that the dataset does not declare as a
+    #: field. Each becomes a hidden dimension so the AQL reference resolves.
+    borrowed: list[str] = dataclass_field(default_factory=list)
+    #: Fields an AQL metric aggregates numerically. The metric is evidence of
+    #: the type when the Ossie document declares no `datatype`.
+    numeric: set[str] = dataclass_field(default_factory=set)
+
+    @property
+    def segments(self) -> list[str]:
+        return [sanitize(part) for part in self.fqn.split("::")]
+
+    @property
+    def aml_fqn(self) -> str:
+        return "::".join(self.segments)
+
+    @property
+    def aml_name(self) -> str:
+        return self.segments[-1]
+
+    @property
+    def path(self) -> str:
+        parts = self.segments
+        if len(parts) == 1:
+            return f"{parts[0]}.model.aml"
+        return "/".join(["modules", *parts[:-1], f"{parts[-1]}.model.aml"])
+
+    @property
+    def reference(self) -> str:
+        """How the dataset block names this model. Dots, not `::`."""
+        return ".".join(self.segments)
+
+
+def unflatten(name: str) -> str:
+    """An Ossie dataset name as an AML module path.
+
+    The forward path writes `reporting::calendar` as `reporting__calendar`, so
+    this reverses that. A stashed `fqn` wins over this rule, because it records
+    where the module boundaries actually were rather than inferring them.
+    """
+    return name.replace("__", "::")
+
+
+#: The dialects a portable body may be written in. Every sibling converter that
+#: reads Ossie treats `OSSIE_SQL_2026` as an `ANSI_SQL` equivalent, including
+#: Snowflake's `_extract_expression` and Cube's `pick_expression`.
+PORTABLE_DIALECTS = ("ANSI_SQL", "OSSIE_SQL_2026")
+
+
+def _named_objects(container: Any, where: str) -> list[dict[str, Any]]:
+    """`container` as a list of named mappings, or a `ConversionError` saying why.
+
+    A document this converter did not write is parsed at the boundary rather
+    than indexed into. Without this, `datasets` given as a mapping raised
+    `AttributeError: 'str' object has no attribute 'get'` and a field with no
+    `name` raised `KeyError`, neither of which the CLI catches, so a malformed
+    document produced a traceback instead of a message. apache/ossie#297 and
+    apache/ossie#407 both asked a sibling converter for the same guard.
+    """
+    if container is None:
+        return []
+    if not isinstance(container, list):
+        raise ConversionError(
+            f"{where} is {type(container).__name__}, and the specification defines it as a list"
+        )
+    for index, member in enumerate(container):
+        if not isinstance(member, dict):
+            raise ConversionError(
+                f"{where}[{index}] is {type(member).__name__}, and must be a mapping"
+            )
+        name = member.get("name")
+        if not isinstance(name, str) or not name:
+            raise ConversionError(f"{where}[{index}] has no name")
+    return container
+
+
+def dialects_of(expression: Any) -> dict[str, str]:
+    dialects = (expression or {}).get("dialects") or []
+    if not dialects:
+        raise ConversionError("expression has no dialects")
+    return {entry.get("dialect", "ANSI_SQL"): entry.get("expression", "") for entry in dialects}
+
+
+class _Reverse:
+    def __init__(
+        self, document: dict[str, Any], data_source_name: str | None, sql_dialect: str
+    ):
+        self.document = document
+        self.sql_dialect = sql_dialect
+        self.issues = IssueLog()
+        self.root_stash = stash.read(document)
+        self.data_source_name = self.root_stash.get("data_source_name") or data_source_name
+        if not self.data_source_name:
+            raise ConversionError(
+                "the document carries no HOLISTICS data_source_name, so one must be "
+                "supplied: pass --data-source-name naming the Holistics connection"
+            )
+
+        #: AML identifier to the Ossie name it was spelled from, so two names
+        #: that collapse onto one spelling fail rather than overwrite.
+        self._renamed: dict[str, str] = {}
+
+        datasets = _named_objects(document.get("datasets"), "datasets")
+        if not datasets:
+            raise ConversionError(
+                "the document declares no datasets, and the specification requires at least one"
+            )
+        for dataset in datasets:
+            _named_objects(dataset.get("fields"), f"datasets[{dataset['name']}].fields")
+        _named_objects(document.get("metrics"), "metrics")
+
+        self.models: list[Model] = []
+        for dataset in datasets:
+            name = dataset["name"]
+            data = stash.read(dataset)
+            self.models.append(
+                Model(
+                    ossie_name=name,
+                    fqn=data.get("fqn") or unflatten(name),
+                    payload=dataset,
+                    stash=data,
+                )
+            )
+        self.by_ossie_name = {m.ossie_name: m for m in self.models}
+
+        taken: dict[str, str] = {}
+        for model in self.models:
+            clash = taken.setdefault(model.aml_fqn, model.ossie_name)
+            if clash != model.ossie_name:
+                raise ConversionError(
+                    f"datasets {clash!r} and {model.ossie_name!r} both spell as the AML "
+                    f"model {model.aml_fqn!r}; rename one of them in Ossie"
+                )
+
+        self.dataset_name = self._dataset_name()
+
+        #: Every metric that belongs on a model, indexed by Ossie metric name,
+        #: alongside the AML measure name it is written as.
+        self.metric_owner: dict[str, Model] = {}
+        self.metric_aml_name: dict[str, str] = {}
+        self.dataset_metrics: list[dict[str, Any]] = []
+        self._metric_payloads: dict[str, dict[str, Any]] = {}
+        self._metric_datasets: dict[str, Any] = {}
+        self._cyclic_metrics: set[str] = set()
+        self._place_metrics()
+
+    # -- placement --------------------------------------------------------
+
+    def _place_metrics(self) -> None:
+        """Decide where each Ossie metric goes: on a model, or on the dataset.
+
+        A stashed `model` settles it. Without one, the expression decides: a
+        body naming exactly one dataset becomes a measure on that model, and a
+        body naming several becomes a dataset-level metric, which is the only
+        AML construct that spans models. A body may also name another metric,
+        and `_scan_for_datasets` covers what that counts as.
+        """
+        metrics = self.document.get("metrics") or []
+        for metric in metrics:
+            name = metric.get("name")
+            self.metric_aml_name[name] = stash.read(metric).get("aml_name") or name
+            self._metric_payloads[name] = metric
+        for metric in metrics:
+            name = metric.get("name")
+            named = self._datasets_named(name) or frozenset()
+            owner = self.by_ossie_name[next(iter(named))] if len(named) == 1 else None
+            if owner is None:
+                self.dataset_metrics.append(metric)
+            else:
+                owner.measures.append(metric)
+                self.metric_owner[name] = owner
+        self._report_metric_cycles()
+
+    def _datasets_named(self, name: str) -> frozenset[str] | None:
+        """The Ossie datasets metric `name` resolves to, or None when that is unknown.
+
+        None covers every reading that cannot put the metric on a single model:
+        an AQL body, Ossie SQL this converter cannot read, and a reference cycle.
+        """
+        resolved = self._metric_datasets.get(name, _UNVISITED)
+        if resolved is _RESOLVING:
+            self._cyclic_metrics.add(name)
+            return None
+        if resolved is not _UNVISITED:
+            return resolved
+        self._metric_datasets[name] = _RESOLVING
+        result = self._scan_for_datasets(name)
+        self._metric_datasets[name] = result
+        return result
+
+    def _scan_for_datasets(self, name: str) -> frozenset[str] | None:
+        """Which datasets one metric body names, directly or through a metric.
+
+        An Ossie metric body may name another metric instead of a column, as
+        `cities__upstream_measure + 1` in `tests/fixtures/ecommerce` does. That
+        body names no dataset of its own, and the datasets the metric it
+        references resolves to stand in for it. Without that substitution a
+        metric built only from other metrics lands on the dataset, where AML
+        takes an AQL body, and the Ossie SQL name it was written with does not
+        resolve.
+        """
+        metric = self._metric_payloads[name]
+        data = stash.read(metric)
+        owner_fqn = data.get("model")
+        if owner_fqn:
+            owner = next((m for m in self.models if m.fqn == owner_fqn), None)
+            if owner is None:
+                raise ConversionError(
+                    f"metric {name!r} is stashed against model {owner_fqn!r}, "
+                    f"which is not a dataset in this document"
+                )
+            return frozenset({owner.ossie_name})
+        available = dialects_of(metric.get("expression"))
+        if AQL_DIALECT in available:
+            return None
+        dialect = next(
+            (d for d in (self.sql_dialect, *PORTABLE_DIALECTS) if d in available), None
+        )
+        if dialect is None:
+            return None
+        try:
+            references = sqlrefs.columns(available[dialect], dialect)
+        except sqlrefs.UnparseableSQL:
+            return None
+        named = {c.table for c in references if c.table in self.by_ossie_name}
+        for reference in references:
+            if reference.table or reference.name not in self._metric_payloads:
+                continue
+            through = self._datasets_named(reference.name)
+            if through is None:
+                return None
+            named |= through
+        return frozenset(named)
+
+    def _report_metric_cycles(self) -> None:
+        for name in sorted(self._cyclic_metrics):
+            self.issues.add(
+                code=ISSUE_METRIC_CYCLE,
+                severity=Severity.ERROR,
+                message=(
+                    f"metric {name!r} references itself through another metric. Holistics "
+                    f"inlines one metric into the body of the next, so a cycle has no warehouse SQL, "
+                    f"and `holistics aml validate` accepts the file without catching it"
+                ),
+                object_ref=name,
+                remedy="break the cycle in Ossie",
+            )
+
+    # -- names ------------------------------------------------------------
+
+    def _dataset_name(self) -> str:
+        """The AML `Dataset` name, moved aside when a model already has it.
+
+        Ossie keeps the semantic model's name and its dataset names in separate
+        namespaces, so a document may use one name for both. Three fixtures in
+        this repository do, including
+        `converters/cube/tests/fixtures/databricks_ossie.yaml`, whose root name
+        and first dataset are both `orders`. AML has one namespace for `Dataset`
+        and `Model`, and rejects the pair with "Duplicated name 'orders'".
+
+        Nothing references the AML dataset name. Models reference each other and
+        relationships reference models, so the dataset is the safe side to move.
+        """
+        name = self.root_stash.get("fqn") or self.document.get("name")
+        if not name:
+            raise ConversionError("the document has no name")
+        spelled = self.name_in_aml(name, str(name))
+        taken = {model.aml_fqn for model in self.models} | {
+            model.aml_name for model in self.models
+        }
+        if spelled not in taken:
+            return spelled
+        candidate, suffix = f"{spelled}_dataset", 2
+        while candidate in taken:
+            candidate, suffix = f"{spelled}_dataset_{suffix}", suffix + 1
+        self.issues.add(
+            code=ISSUE_DATASET_RENAMED,
+            severity=Severity.WARNING,
+            message=(
+                f"a model is already named {spelled!r}, and AML holds Dataset and Model "
+                f"in one namespace, so the dataset is written as {candidate!r}"
+            ),
+            object_ref=str(name),
+            remedy="rename the semantic model or the dataset in Ossie",
+        )
+        return candidate
+
+    def name_in_aml(self, name: str, scope: str) -> str:
+        """An Ossie name as the AML identifier it is written as.
+
+        Lookups elsewhere stay keyed on the Ossie name, because that is what an
+        expression references. Only the output spelling changes, and every site
+        that writes a name goes through here, so a declaration and a reference
+        to it cannot disagree.
+        """
+        spelled = sanitize(name)
+        if spelled != name:
+            previous = self._renamed.setdefault(spelled, name)
+            if previous != name:
+                raise ConversionError(
+                    f"{scope}: {name!r} and {previous!r} both spell as the AML "
+                    f"identifier {spelled!r}; rename one of them in Ossie"
+                )
+            self.issues.add(
+                code=ISSUE_RENAMED,
+                severity=Severity.WARNING,
+                message=(
+                    f"{name!r} is not a legal AML identifier and is written as "
+                    f"{spelled!r}. AML allows letters, digits and underscore, and no "
+                    f"leading digit"
+                ),
+                object_ref=scope,
+                remedy=f"rename it to {spelled!r} in Ossie to keep the two in step",
+            )
+        return spelled
+
+    # -- expressions ------------------------------------------------------
+
+    def pick_body(self, expression: Any, scope: str) -> tuple[str, str]:
+        """The body to write and the dialect it is in, after any rendering.
+
+        AQL wins outright. It came out of AML unchanged and goes back unchanged.
+
+        For Ossie SQL the target is `--sql-dialect`, the warehouse the Holistics
+        connection reads. A body already in that dialect is written as it
+        stands. Otherwise a portable body is rendered into the target with
+        sqlglot, because the alternative is AML that will not run. An expression
+        offering neither has no body this connection can execute, and the
+        converter says so rather than writing Holistics SQL for the wrong warehouse.
+        """
+        available = dialects_of(expression)
+        if AQL_DIALECT in available:
+            return AQL_DIALECT, available[AQL_DIALECT]
+        if self.sql_dialect in available:
+            return self.sql_dialect, available[self.sql_dialect]
+
+        source = next((d for d in PORTABLE_DIALECTS if d in available), None)
+        if source is not None:
+            try:
+                rendered = sqlrefs.transpile(available[source], source, self.sql_dialect)
+            except sqlrefs.UnparseableSQL as exc:
+                self.issues.add(
+                    code=ISSUE_UNPARSEABLE_SQL,
+                    severity=Severity.ERROR,
+                    message=(
+                        f"the {source} body cannot be rendered as {self.sql_dialect} ({exc}), "
+                        f"so it is written unchanged and may not run"
+                    ),
+                    object_ref=scope,
+                    remedy=f"add a {self.sql_dialect} expression, or fix the {source} one",
+                )
+                return source, available[source]
+            self.issues.add(
+                code=ISSUE_TRANSPILED,
+                severity=Severity.WARNING,
+                message=(
+                    f"no {self.sql_dialect} expression, so the {source} one was rendered "
+                    f"into it: {available[source]!r} became {rendered!r}"
+                ),
+                object_ref=scope,
+                remedy=f"add a {self.sql_dialect} expression to keep the body exact",
+            )
+            return self.sql_dialect, rendered
+
+        fallback = next(iter(available))
+        self.issues.add(
+            code=ISSUE_NO_USABLE_DIALECT,
+            severity=Severity.ERROR,
+            message=(
+                f"the expression offers {', '.join(sorted(available))} and the connection "
+                f"reads {self.sql_dialect}, with no portable body to render from, so the "
+                f"{fallback} body is written unchanged and will not run"
+            ),
+            object_ref=scope,
+            remedy=f"add a {self.sql_dialect} or ANSI_SQL expression",
+        )
+        return fallback, available[fallback]
+
+    def definition(self, block: Block, expression: Any, model: Model, scope: str) -> None:
+        """Write a `definition` property for a field or a measure."""
+        dialect, text = self.pick_body(expression, scope)
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+            return
+        block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+
+    def to_aml_sql(self, expression: str, dialect: str, model: Model, scope: str) -> str:
+        """An Ossie SQL expression with its references written as AML interpolation.
+
+        A bare column name does compile as AML, but AQL reads the interpolation
+        to learn which field the body depends on. A body without it loses the
+        query rewriting and the optimisation that link drives, so this restores
+        every reference rather than passing the SQL through.
+        """
+        if dialect in sqlrefs.NOT_SQL or not sqlrefs.AVAILABLE:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body is tagged {dialect!r}, which is not Ossie SQL this converter can "
+                    f"read, so its field references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="supply an ANSI_SQL or warehouse-SQL dialect for this expression",
+            )
+            return expression
+        grouping = sqlrefs.window_grouping(expression, dialect)
+        if grouping:
+            self.issues.add(
+                code=ISSUE_WINDOW_NEEDS_GROUPING,
+                severity=Severity.WARNING,
+                message=(
+                    f"the body has a window function whose frame reads "
+                    f"{', '.join(grouping)}. AML carries it as written, and the warehouse SQL "
+                    f"it generates is valid only for a query that groups by those. A query "
+                    f"that does not, a grand total for one, produces warehouse SQL the "
+                    f"database rejects, and Holistics does not check this at conversion time"
+                ),
+                object_ref=scope,
+                remedy="query it only alongside those fields, or rewrite the body in AQL",
+            )
+        try:
+            return sqlrefs.rewrite(
+                expression, dialect, lambda column: self.to_interpolation(column, model, scope)
+            )
+        except sqlrefs.UnparseableSQL as exc:
+            self.issues.add(
+                code=ISSUE_UNPARSEABLE_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"sqlglot cannot read the body as {dialect} ({exc}), so its field "
+                    f"references cannot be restored and AQL cannot see them"
+                ),
+                object_ref=scope,
+                remedy="fix the expression, or convert it by hand",
+            )
+            return expression
+
+    def to_interpolation(self, column: sqlrefs.ColumnReference, model: Model, scope: str) -> str:
+        """One Ossie column reference as the AML interpolation it came from."""
+        if not column.table:
+            if column.name in self.metric_aml_name:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Source(column.name).to_aml()
+
+        target = self.by_ossie_name.get(column.table)
+        if target is None:
+            self.issues.add(
+                code=ISSUE_UNKNOWN_QUALIFIER,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body qualifies {column.name!r} with {column.table!r}, which is not "
+                    f"a dataset in this document, so it is left unresolved"
+                ),
+                object_ref=scope,
+                remedy="qualify the reference with a dataset name, or drop the field",
+            )
+            return f"{column.table}.{column.name}"
+        if target is model:
+            # A qualifier naming this model usually names one of its fields. It
+            # can also name a metric this converter put somewhere else, and a
+            # sibling reference to that spells a field the model does not have.
+            if column.name in self.metric_aml_name and self.metric_owner.get(column.name) is not model:
+                return self._measure_reference(column.name, model, scope)
+            return interpolation.Sibling(self.name_in_aml(column.name, scope)).to_aml()
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body names {column.table}.{column.name}, a field of another dataset. A `@sql` "
+                f"body resolves inside one model, and Holistics rejects this at SQL generation "
+                f"with \"Cannot refer to external field in TableModel/QueryModel\" even though "
+                f"`holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="move the reference into a dimension on its own model, or rewrite the body in AQL",
+        )
+        return interpolation.ModelField(target.aml_fqn, self.name_in_aml(column.name, scope)).to_aml()
+
+    def _measure_reference(self, metric_name: str, model: Model, scope: str) -> str:
+        owner = self.metric_owner.get(metric_name)
+        aml_name = self.metric_aml_name[metric_name]
+        if owner is model:
+            return interpolation.Sibling(self.name_in_aml(aml_name, scope)).to_aml()
+        if owner is None:
+            self.issues.add(
+                code=ISSUE_CROSS_MODEL_SQL,
+                severity=Severity.ERROR,
+                message=(
+                    f"the body references the dataset-level metric {metric_name!r}. A `@sql` "
+                    f"body resolves inside one model, so there is no AML spelling for it"
+                ),
+                object_ref=scope,
+                remedy="rewrite the expression in AQL, which does span models",
+            )
+            return metric_name
+        self.issues.add(
+            code=ISSUE_CROSS_MODEL_SQL,
+            severity=Severity.ERROR,
+            message=(
+                f"the body references {metric_name!r}, a measure of model {owner.aml_fqn!r}. A "
+                f"`@sql` body resolves inside one model, and Holistics rejects this at SQL "
+                f"generation with \"Cannot refer to external field in TableModel/QueryModel\" "
+                f"even though `holistics aml validate` accepts the file"
+            ),
+            object_ref=scope,
+            remedy="rewrite the expression in AQL, which does span models",
+        )
+        return interpolation.ModelField(owner.aml_fqn, self.name_in_aml(aml_name, scope)).to_aml()
+
+    # -- fields -----------------------------------------------------------
+
+    def aml_type(
+        self, payload: dict[str, Any], data: dict[str, Any], scope: str, model: Model | None = None
+    ) -> str:
+        stashed = data.get("type")
+        if stashed:
+            return stashed
+        datatype = payload.get("datatype")
+        mapped = OSSIE_TO_AML_TYPE.get(datatype) if datatype else None
+        if mapped:
+            return mapped
+        if model is not None and payload["name"] in model.numeric:
+            # A metric aggregates this field with `sum` or `avg`, so it is a
+            # number whatever the document failed to say.
+            return "number"
+        self.issues.add(
+            code=ISSUE_ASSUMED_TYPE,
+            severity=Severity.WARNING,
+            message=(
+                f"AML requires a type and the Ossie datatype is {datatype!r}, "
+                f"so {FALLBACK_TYPE!r} is written"
+            ),
+            object_ref=scope,
+            remedy="set a datatype on the field, or edit the AML type after conversion",
+        )
+        return FALLBACK_TYPE
+
+    def common_properties(
+        self,
+        block: Block,
+        payload: dict[str, Any],
+        data: dict[str, Any],
+        scope: str,
+        model: Model | None = None,
+    ) -> None:
+        block.text("label", data.get("label") or titleize(payload["name"]))
+        block.property("type", quote(self.aml_type(payload, data, scope, model)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+    def dimension(self, model: Model, payload: dict[str, Any], primary_key: set[str]) -> Block:
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        block.flag("primary_key", name in primary_key)
+        return block
+
+    def dataset_dimension(self, model: Model, payload: dict[str, Any]) -> Block:
+        """A field the forward path took from a dataset-level AML dimension."""
+        name = payload["name"]
+        scope = f"{model.ossie_name}.{name}"
+        data = stash.read(payload)
+        block = Block(f"dimension {self.name_in_aml(name, scope)}")
+        block.property("model", model.reference)
+        self.common_properties(block, payload, data, scope, model)
+        self.definition(block, payload.get("expression"), model, scope)
+        block.text("format", data.get("format"))
+        return block
+
+    def measure(self, model: Model, payload: dict[str, Any]) -> Block:
+        """One Ossie metric as a `measure` on its owning model.
+
+        `aggregation_type` and the body compose into one Ossie expression on the
+        way out, so this splits them back apart. When the stashed aggregation
+        does not wrap the whole expression, the expression was edited after the
+        forward path wrote it, and `custom` keeps it whole rather than letting
+        the measure aggregate twice.
+        """
+        metric_name = payload["name"]
+        aml_name = self.metric_aml_name[metric_name]
+        scope = f"{model.ossie_name}.{aml_name}"
+        data = stash.read(payload)
+        block = Block(f"measure {self.name_in_aml(aml_name, scope)}")
+        block.text("label", data.get("label") or titleize(aml_name))
+        block.property("type", quote(self.aml_type(payload, data, scope)))
+        block.text("description", payload.get("description"))
+        block.flag("hidden", bool(data.get("hidden")))
+
+        dialect, text = self.pick_body(payload.get("expression"), scope)
+        aggregation = data.get("aggregation_type") or CUSTOM_AGGREGATION
+        if dialect == AQL_DIALECT:
+            block.heredoc("definition", "aql", text)
+        else:
+            if aggregation in AGGREGATIONS:
+                inner = strip_aggregation(aggregation, text)
+                if inner is None:
+                    self.issues.add(
+                        code=ISSUE_AGGREGATION_NOT_STRIPPED,
+                        severity=Severity.WARNING,
+                        message=(
+                            f"the stashed aggregation {aggregation!r} does not wrap the whole "
+                            f"expression, so the measure is written as 'custom' with the "
+                            f"expression kept whole"
+                        ),
+                        object_ref=scope,
+                        remedy="check the expression against the aggregation",
+                    )
+                    aggregation = CUSTOM_AGGREGATION
+                else:
+                    text = inner
+            block.heredoc("definition", "sql", self.to_aml_sql(text, dialect, model, scope))
+        block.property("aggregation_type", quote(aggregation))
+        block.text("format", data.get("format"))
+        return block
+
+    def as_aql(self, text: str, dialect: str, scope: str) -> str | None:
+        """A dataset-level metric's Ossie SQL body rendered as AQL, or None if it cannot be.
+
+        AML accepts only `@aql` here, so an Ossie SQL body either becomes AQL or has no
+        AML form at all. `aql.translate` is a name map over functions this
+        converter has paired with an AQL equivalent. Anything outside that table
+        raises `Untranslatable`, and the metric is dropped with an ERROR.
+        """
+        try:
+            rendered, numeric = aql.translate(
+                text, dialect, lambda table, column: self.aql_reference(table, column, scope)
+            )
+        except aql.Untranslatable as exc:
+            self.issues.add(
+                code=ISSUE_METRIC_NOT_TRANSLATED,
+                severity=Severity.ERROR,
+                message=(
+                    f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                    f"converter did not translate this {dialect} body, and the metric is "
+                    f"dropped. {exc}"
+                ),
+                object_ref=scope,
+                remedy="rewrite the metric in AQL, or scope it to a single dataset",
+            )
+            return None
+        self.issues.add(
+            code=ISSUE_RENDERED_AS_AQL,
+            severity=Severity.WARNING,
+            message=(
+                f"the metric sits on the dataset, where AML accepts only an AQL body. The "
+                f"{dialect} expression was rendered as AQL: {text!r} became {rendered!r}"
+            ),
+            object_ref=scope,
+            remedy="check the AQL against the Ossie SQL it came from",
+        )
+        for table, column in numeric:
+            target = self.by_ossie_name.get(table)
+            if target is not None:
+                target.numeric.add(self.name_in_aml(column, scope))
+        return rendered
+
+    def aql_reference(self, table: str, column: str, scope: str) -> str:
+        """One column of an Ossie SQL metric body as the AQL reference it becomes.
+
+        AQL names a field `model.field`, which is the shape the Ossie expression
+        already uses, so this maps the Ossie dataset name onto the AML model
+        name and keeps the field name.
+
+        An Ossie SQL body may name a warehouse column the document does not declare as
+        a field. `SUM(orders.subtotal) / COUNT(DISTINCT customers.customer_id)`
+        in `converters/nvidia/tests/fixtures/sales.ossie.yaml` is one: `orders`
+        declares no `subtotal`. Ossie SQL resolves that against the table, and AQL
+        does not, answering `Field `subtotal` not found in model `orders``. So
+        the column becomes a hidden dimension on that model, and the AQL
+        reference points at it.
+        """
+        if not table:
+            # An unqualified name that is a metric is a metric reference, which
+            # AQL takes: a dataset-level one by its bare name, and a measure by
+            # the model that holds it.
+            if column in self.metric_aml_name:
+                referenced = self.name_in_aml(self.metric_aml_name[column], scope)
+                owner = self.metric_owner.get(column)
+                return referenced if owner is None else f"{owner.aml_fqn}.{referenced}"
+            raise aql.Untranslatable(
+                f"{column!r} names no dataset, and a metric spanning models has no single "
+                f"model to resolve it against."
+            )
+        target = self.by_ossie_name.get(table)
+        if target is None:
+            raise aql.Untranslatable(f"{table!r} is not a dataset in this document.")
+        name = self.name_in_aml(column, scope)
+        declared = {
+            field["name"] for field in target.payload.get("fields") or []
+        } | {self.metric_aml_name[m["name"]] for m in target.measures}
+        if name not in declared and name not in target.borrowed:

Review Comment:
   `declared` is built from `field["name"]` (Ossie names) plus `self.metric_aml_name[...]` (AML names), but it is compared against `name = self.name_in_aml(column, scope)` (sanitized). A declared field whose Ossie name is not a legal AML identifier then looks undeclared. That adds a spurious hidden dimension and a `BORROWED_COLUMN` warning.
   
   Should `declared` hold sanitized names throughout?



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


Re: [PR] feat(holistics): add a Holistics AML converter [ossie]

Posted by "tantmd (via GitHub)" <gi...@apache.org>.
tantmd commented on code in PR #538:
URL: https://github.com/apache/ossie/pull/538#discussion_r4226600616


##########
python/src/ossie/models.py:
##########
@@ -35,6 +35,7 @@ class OssieDialect(str, Enum):
     SIGMA = "SIGMA"
     THOUGHTSPOT = "THOUGHTSPOT"
     DAX = "DAX"
+    HOLISTICS_AQL = "HOLISTICS_AQL"

Review Comment:
   fixed in 848471a



##########
converters/holistics/tests/test_cross_vendor.py:
##########
@@ -0,0 +1,137 @@
+# 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.
+
+"""Every Ossie document in this repository, converted to AML.
+
+The reverse path's whole job is reading documents this converter did not write,
+and the snapshot fixtures cannot cover that: one of them this converter produced
+and the other is a single example. The sweep found two defects the fixtures
+missed, both of them crashes rather than bad output.
+
+`examples/flights.semantic_model.yaml` is named `Flights semantic model`. Ossie
+allows any non-empty string, and AML allows letters, digits and underscore, so
+the conversion raised instead of renaming.
+
+Three fixtures use one name for the semantic model and for a dataset inside it,
+including `converters/cube/tests/fixtures/databricks_ossie.yaml`, where both are
+`orders`. Ossie keeps the two in separate namespaces and AML does not, so the
+generated AML failed to compile with "Duplicated name 'orders'".
+
+Adding a fixture elsewhere in the repository extends this test with no edit
+here, which is the point. apache/ossie#352 asked the Solid converter for the
+same sweep.
+"""
+from __future__ import annotations
+
+import subprocess
+from collections import Counter
+from pathlib import Path
+
+import pytest
+
+import snapshots
+from ossie_holistics import _yaml, ossie_to_aml, sqlrefs
+from test_snapshots import HOLISTICS_CLI, needs_cli
+
+#: Any `data_source_name`. These documents have no Holistics connection behind
+#: them, and the value only has to be present for the AML to compile.
+PROBE_CONNECTION = "probe"
+
+
+def _target_dialect(document) -> str:
+    """The SQL dialect most of a document's expressions already use.
+
+    An operator converting one of these would name the warehouse the Holistics
+    connection reads. Picking the document's own majority dialect is the closest
+    stand-in, and it keeps the sweep testing the conversion rather than testing
+    sqlglot's rendering.
+    """
+    counts = Counter()
+    for dataset in document.get("datasets") or []:
+        for field in dataset.get("fields") or []:
+            for entry in (field.get("expression") or {}).get("dialects") or []:
+                counts[entry.get("dialect")] += 1
+    for name, _ in counts.most_common():
+        if name in sqlrefs.SQLGLOT_DIALECT:
+            return name
+    return "ANSI_SQL"
+
+
+def _foreign_ossie_documents() -> list[Path]:
+    """Every flat Ossie document outside this converter's own directory.
+
+    A flat document carries `version` and `datasets` at the root. That is the
+    shape `main` moved to, and the heuristic apache/ossie#352 settled on after
+    the wrapped `semantic_model:` list went away.
+    """
+    found = []
+    roots = [snapshots.REPO_ROOT / "converters", snapshots.REPO_ROOT / "examples"]
+    for root in roots:
+        for path in sorted(root.rglob("*.yaml")):
+            if snapshots.CONVERTER_ROOT in path.parents or ".venv" in path.parts:
+                continue
+            try:
+                document = _yaml.load(path.read_text(encoding="utf-8"))
+            except Exception:  # noqa: BLE001 - a malformed sibling fixture is not our failure
+                continue
+            if isinstance(document, dict) and document.get("version") and "datasets" in document:
+                found.append(path)
+    return found
+
+
+FOREIGN = _foreign_ossie_documents()
+
+
+def _ids(paths: list[Path]) -> list[str]:
+    return [str(p.relative_to(snapshots.REPO_ROOT)) for p in paths]
+
+
+def test_the_sweep_finds_documents():
+    """A heuristic that silently matches nothing would pass every test below."""
+    assert len(FOREIGN) >= 20, _ids(FOREIGN)

Review Comment:
   deleted in b4e8dd8
   
   That test was for catching bugs during development. It is a bit overzealous, and it breaks on changes to other converters, so I have deleted it.



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


Re: [PR] feat(holistics): add a Holistics AML converter [ossie]

Posted by "tantmd (via GitHub)" <gi...@apache.org>.
tantmd commented on PR #538:
URL: https://github.com/apache/ossie/pull/538#issuecomment-6074700577

   Thanks for the quick turnaround and the thorough review, much appreciated. I've also opened [apache/ossie-website#37](https://github.com/apache/ossie-website/pull/37) to add Holistics to the ecosystem grid. Would you mind reviewing that one too?


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