Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
bad008e
test(compliance): add portability rung M6, date and time scalars
MrBlack1995 Oct 22, 2026
1b121eb
test(compliance): add the FILTER (WHERE ...) form to portability rung M3
MrBlack1995 Oct 22, 2026
8a4e222
test(compliance): add portability rung M4, a cross-dataset metric
MrBlack1995 Oct 22, 2026
19beb20
test(compliance): add portability rung M5, metric-to-metric composition
MrBlack1995 Oct 22, 2026
2753e27
docs(compliance): describe portability rungs M0-M6
MrBlack1995 Oct 22, 2026
3d0bdf9
test(compliance): cover M4-M6 in the identity test, name every elemen…
MrBlack1995 Oct 30, 2026
9276156
test(compliance): carry M5's composition inlined, as the spec requires
MrBlack1995 Oct 30, 2026
4f1aa3d
test(compliance): write M3's CASE form without ELSE 0, as the FILTER …
MrBlack1995 Nov 1, 2026
8d3613a
test(compliance): carry the bare variants as dataset-scoped metrics, …
MrBlack1995 Oct 30, 2026
4f56afe
test(compliance): name manifest elements by the grader's keys; spec s…
MrBlack1995 Nov 2, 2026
eabac45
docs(compliance): point the portability ladder at apache/ossie-conver…
MrBlack1995 Nov 3, 2026
b8993a4
fix(compliance): keep the dataset qualifier on a field two datasets d…
MrBlack1995 Nov 8, 2026
e891100
test(compliance): move the M3-M6 fixtures to spec version 0.3.0.dev0
MrBlack1995 Nov 12, 2026
d2c4643
fix(compliance): resolve a dataset qualifier against the dataset that…
MrBlack1995 Nov 13, 2026
0995481
fix(compliance): treat a returned dataset with an authored dataset's …
MrBlack1995 Nov 17, 2026
639958b
docs(compliance): M5 carries composition inlined, without claiming me…
MrBlack1995 Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions compliance/portability/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@
under the License.
-->

# Portability measurement ladder (M0-M3)
# Portability measurement ladder (M0-M6)

A small set of portable fixtures, and a grader, for measuring how faithfully a
model survives a round-trip through each converter. This is issue #576
(measurements for model portability across converters). The fixtures are the
inputs; `grader/` scores each returned document against its input, element by
element, into the outcome vocabulary in `manifest.yaml`. A thin runner that drives
model survives a round-trip through each converter. This is
apache/ossie-converters#24 (measurements for model portability across
converters; formerly #576 here). The fixtures are the inputs; `grader/` scores
each returned document against its input, element by element, into the outcome
vocabulary in `manifest.yaml`. A thin runner that drives
the converters (modelled on `cube/tools/interop_matrix.py` in apache/ossie-converters)
turns the whole thing into one command; the grader is written to sit behind it.

Expand All @@ -37,7 +38,10 @@ difference in a converter's output localizes to a single construct:
| M0 | baseline | one dataset, one field, one `SUM` metric |
| M1 | a scalar field, no aggregation | `amount * 1.1` calculated column |
| M2 | the core aggregate set | `SUM`, `COUNT`, `COUNT(DISTINCT)`, `AVG`, `MIN`, `MAX` |
| M3 | a filtered aggregate | `SUM(CASE WHEN ... THEN x ELSE 0 END)` |
| M3 | a filtered aggregate | `SUM(CASE WHEN ... THEN x END)` (no `ELSE`, so it equals the `FILTER` form), and the same with `FILTER (WHERE ...)` |
| M4 | a cross-dataset metric | two datasets, a relationship, a model-scoped metric across the join |
| M5 | metric composition | a model-scoped metric built from two others, carried with their expressions inlined (composition through `AGG(dataset.metric)` is not tested by this rung) |
| M6 | date and time scalars | `YEAR`, `DATE_TRUNC`, `DATEDIFF(part, start, end)` |

`manifest.yaml` lists the fixtures, the element each rung exercises, and the
per-element outcome vocabulary the grader assigns (PORTABLE / TAG_PRESERVED,
Expand All @@ -61,10 +65,10 @@ grades the real fixtures all-PORTABLE. See `grader/README.md`.

## Scope and placement

Rungs M4-M8 (relationships and cross-dataset metrics, metric-to-metric
composition, date and time scalars, window and offset functions) are held
pending #354, #591 and #587, and are not in this set.
Rungs M7 and M8 (window and offset functions: time intelligence and
ratio-to-total) are held until the default NULL placement in window `ORDER BY`
is settled (#587), and are not in this set.

Location is a starting point. If these should sit with the interoperability
harness from #348 or elsewhere once that lands, they can move; the fixtures are
self-contained and the manifest paths are relative.
The fixtures measure the specification rather than any one converter, so they
live in this repository; the fixtures are self-contained and the manifest paths
are relative.
23 changes: 18 additions & 5 deletions compliance/portability/grader/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,21 @@

# Portability fidelity grader

`grade.py` is the scoring half of issue #576. Conformance (`validate.py` passing)
is a floor and says nothing about whether a model survived a converter round-trip;
this grader is the fidelity half.
`grade.py` is the scoring half of apache/ossie-converters#24 (formerly #576).
Conformance (`validate.py` passing) is a floor and says nothing about whether a
model survived a converter round-trip; this grader is the fidelity half.

It does not drive the converters. It takes the input document and the document a
converter returned, and diffs them element by element into the outcome vocabulary
in `../manifest.yaml`. A thin runner (modelled on `cube/tools/interop_matrix.py` in
apache/ossie-converters) drives each converter and feeds the
grader, so the measurement table becomes one command.

Elements are metrics and field expressions. A model-scoped metric is keyed by its
name, a dataset-scoped metric (`datasets[].metrics`) and a field by `dataset.name`,
the way the spec references them. A metric a converter moves between the two scopes
with the same expression is graded REWRITTEN (identity not preserved), not PORTABLE.

## Usage

```
Expand All @@ -49,6 +54,12 @@ PLACEHOLDER, ADDED, RELABELED, DROPPED_DIAGNOSED, DROPPED_SILENT, REJECTED.
marked cosmetic, while one it cannot prove equivalent is flagged for review.
Without `sqlglot` the grader still runs and marks every rewrite as needing
review.
- **A qualifier is checked against the model.** Before trees are compared, each
column is resolved to the dataset it names: a bare name in a field expression
or dataset-scoped metric is the element's own dataset, elsewhere it is the one
dataset that declares it. A requalify that names the same dataset is cosmetic;
one that names another dataset (`customers.amount` for `sales.amount`) needs
review.
- **Textual by default, semantic where it can be.** PORTABLE means the converter
returned the same expression it was given (modulo cosmetic whitespace). When
the input has an `OSSIE_SQL_2026` form (`sql`, or the dialect entry when there
Expand All @@ -66,5 +77,7 @@ PLACEHOLDER, ADDED, RELABELED, DROPPED_DIAGNOSED, DROPPED_SILENT, REJECTED.
## Tests

`test_grade.py` has one test per outcome plus an identity check that runs the real
M0-M3 fixtures through a no-op converter and asserts every element grades
PORTABLE. Run with `PYTHONPATH=. pytest test_grade.py`.
M0-M6 fixtures through a no-op converter and asserts every element grades
PORTABLE. Two manifest checks assert that every element the manifest names is found
by kind and name in each variant, and that each primary variant uses the rung's primary
reference form. Run with `PYTHONPATH=. pytest test_grade.py`.
137 changes: 115 additions & 22 deletions compliance/portability/grader/grade.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# specific language governing permissions and limitations
# under the License.

"""Fidelity grader for the portability measurement ladder (issue #576).
"""Fidelity grader for the portability measurement ladder (apache/ossie-converters#24, formerly #576).

The grader answers one question per element: when a model is driven through a
converter and back, what happened to each metric and field expression it started
Expand Down Expand Up @@ -106,25 +106,99 @@ def _normalize(expression):
return re.sub(r"\s*([(),])\s*", r"\1", collapsed)


def _equivalent_tree(left, right):
"""Return True if two SQL expressions are equal after stripping table
qualifiers and quoting, False if they differ, or None if it cannot be decided
(sqlglot missing, or either side does not parse). Used only to tell a cosmetic
REWRITTEN from one that needs review."""
def _field_owners(document):
"""{field name: the datasets that declare it}, lower-cased, read from the input
document (the authored model), so a dataset qualifier can be checked against it."""
owners = {}
if isinstance(document, dict):
for dataset in document.get("datasets") or []:
if not isinstance(dataset, dict):
continue
dataset_name = str(dataset.get("name") or "").lower()
for field_def in dataset.get("fields") or []:
if isinstance(field_def, dict) and field_def.get("name"):
owners.setdefault(str(field_def["name"]).lower(), set()).add(dataset_name)
return {name: frozenset(datasets) for name, datasets in owners.items()}


def _source_key(dataset):
source = dataset.get("source")
if isinstance(source, dict):
return json.dumps(source, sort_keys=True).lower()
return str(source or "").strip().lower()


def _dataset_aliases(input_document, output_document):
"""{returned dataset: authored dataset}, lower-cased, for each returned dataset that
is not authored under its own name but reads the source of exactly one authored
dataset. A converter that names datasets after their source table (lightdash returns
``orders`` for an authored ``sales`` over ``samples.sales.orders``) renamed it, so
its qualifiers on the returned side name the authored dataset."""
def datasets(document):
if not isinstance(document, dict):
return []
return [d for d in document.get("datasets") or [] if isinstance(d, dict) and d.get("name")]

authored = {str(d["name"]).lower(): _source_key(d) for d in datasets(input_document)}
aliases = {}
for dataset in datasets(output_document):
name = str(dataset["name"]).lower()
source = _source_key(dataset)
if name in authored or not source:
continue
matches = [authored_name for authored_name, key in authored.items() if key == source]
if len(matches) == 1:
aliases[name] = matches[0]
return aliases


def _equivalent_tree(left, right, owners=None, home=None, aliases=None):
"""Return True if two SQL expressions are equal after resolving dataset
qualifiers and dropping quoting, False if they differ, or None if it cannot be
decided (sqlglot missing, or either side does not parse). Used only to tell a
cosmetic REWRITTEN from one that needs review.

A qualifier is meaning, not spelling, so each column is resolved to the dataset
it names before comparing: a bare name in a field expression or dataset-scoped
metric names ``home``, the element's own dataset; elsewhere a bare name resolves
to the one dataset that declares it (``owners``, from _field_owners) and stays
bare when several do. A written qualifier is kept as written, so
``customers.amount`` differs from ``sales.amount`` even if only sales declares
``amount``. A name no dataset declares, and every name without ``owners``, is
compared without its qualifier, since there is nothing to check it against.
``aliases`` (from _dataset_aliases) maps a renamed dataset's qualifiers on the
returned side, ``right``, to the authored dataset before resolving."""
try:
import sqlglot
from sqlglot import exp
except ImportError: # pragma: no cover - environment dependent
return None

def canonical(text):
home = (home or "").lower() or None

def resolved(column):
if owners is None:
return None
if home:
return column.table.lower() if column.table else home
declared_by = owners.get(column.name.lower(), frozenset())
if not declared_by:
return None # no dataset declares it, so there is nothing to check against
if column.table:
return column.table.lower()
Comment on lines +182 to +188

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A returned qualifier is now kept as written, so when a converter renames a dataset, every metric and field that names it is graded as dropped.

Lightdash names a dataset after its source table. For M0.ansi.qualified it returns a dataset orders (source: samples.sales.orders) and orders_total_amount = SUM(orders.amount) for the authored dataset sales and total_amount = SUM(sales.amount). Main pairs the two as "identity not preserved" (the review column). With this change orders stays orders, the trees differ, and total_amount is graded DROPPED_SILENT, plus an unrelated ADDED orders_total_amount.
The M1 field gets the same treatment (amount * 1.1 comes back as orders.amount * 1.1).

I graded all 120 portability cases from the latest Interop matrix run on apache/ossie-converters main with main's grader and with this one. 19 lightdash elements in 8 cases (M0 x3, M1, M2 x2, M3 x2) move from review to DROPPED_SILENT, and nothing else changes. The converters table would then show lightdash silently dropping metrics it actually returned.

I suggest when a returned dataset has the same source as an authored one, treat it as that dataset, and map its qualifiers on the returned side before resolving. I tried this locally. The 120 CI cases then grade exactly as on main, and all 43 tests here still pass, including test_a_field_qualified_by_another_dataset_needs_review.

Could we add a test built from lightdash's real M0 return, so this can't regress?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0995481 as you suggested: a returned dataset that reads the source of exactly one authored dataset is treated as that dataset, and its qualifiers are mapped on the returned side before resolving. The 120 CI cases now grade as on main, and test_a_dataset_renamed_after_its_source_is_the_authored_dataset is built from lightdash's real M0 return. Details in the comment below.

return next(iter(declared_by)) if len(declared_by) == 1 else None

def canonical(text, renamed=None):
try:
tree = sqlglot.parse_one(text)
except Exception:
return None
for column in tree.find_all(exp.Column):
# Drop the table qualifier so sales.amount and amount compare equal.
column.set("table", None)
if renamed and column.table and column.table.lower() in renamed:
column.set("table", exp.to_identifier(renamed[column.table.lower()]))
dataset = resolved(column)
# sales.amount and amount compare equal when amount resolves to sales.
column.set("table", exp.to_identifier(dataset) if dataset else None)
column.set("db", None)
column.set("catalog", None)
for identifier in tree.find_all(exp.Identifier):
Expand All @@ -140,7 +214,7 @@ def canonical(text):
return tree.sql(normalize=True)

left_sql = canonical(left)
right_sql = canonical(right)
right_sql = canonical(right, aliases)
if left_sql is None or right_sql is None:
return None
return left_sql == right_sql
Expand Down Expand Up @@ -176,10 +250,16 @@ class Element:
kind: str # "metric" or "field"
name: str
dialects: dict
dataset: str = "" # the declaring dataset of a field or dataset-scoped metric


def _collect(document):
"""Collect metrics and field expressions, keyed by (kind, name)."""
"""Collect metrics and field expressions, keyed by (kind, name).

A dataset-scoped metric (``datasets[].metrics``) is keyed ``dataset.metric``,
the name the spec references it by, so it cannot collide with a model-scoped
metric of the same name.
"""
elements = {}
if not isinstance(document, dict):
return elements
Expand All @@ -194,7 +274,11 @@ def _collect(document):
for field_def in dataset.get("fields") or []:
if isinstance(field_def, dict) and field_def.get("name"):
name = f"{dataset_name}.{field_def['name']}"
elements[("field", name)] = Element("field", name, _dialect_map(field_def.get("expression")))
elements[("field", name)] = Element("field", name, _dialect_map(field_def.get("expression")), dataset_name)
for metric in dataset.get("metrics") or []:
if isinstance(metric, dict) and metric.get("name"):
name = f"{dataset_name}.{metric['name']}"
elements[("metric", name)] = Element("metric", name, _dialect_map(metric.get("expression")), dataset_name)
return elements


Expand Down Expand Up @@ -239,9 +323,11 @@ def _diagnosed(name, diagnostics):
return short != name and _mentions(short, diagnostics)


def _rewritten(input_element, authored_text, returned_text):
def _rewritten(input_element, authored_text, returned_text, owners=None, aliases=None):
"""A REWRITTEN finding, with the tree comparison that tells cosmetic from review."""
equivalent = _equivalent_tree(authored_text, returned_text)
equivalent = _equivalent_tree(
authored_text, returned_text, owners, input_element.dataset, aliases
)
if equivalent is True:
note = "cosmetic (normalized trees equal)"
elif equivalent is False:
Expand All @@ -254,7 +340,7 @@ def _rewritten(input_element, authored_text, returned_text):
)


def _classify_present(input_element, output_element):
def _classify_present(input_element, output_element, owners=None, aliases=None):
"""Classify an input element that still has a counterpart in the output."""
in_dialects = input_element.dialects
out_dialects = output_element.dialects
Expand All @@ -279,7 +365,9 @@ def _classify_present(input_element, output_element):
# The changed form is the rewrite to report, ahead of a copy that came back.
authored_tag = changed[0]
authored_text = in_dialects[authored_tag]
return _rewritten(input_element, authored_text, out_dialects[authored_tag])
return _rewritten(
input_element, authored_text, out_dialects[authored_tag], owners, aliases
)
if "OSSIE_SQL_2026" in in_dialects:
kept = [d for d in kept if in_dialects[d] == in_dialects["OSSIE_SQL_2026"]]
if kept:
Expand All @@ -305,7 +393,7 @@ def _classify_present(input_element, output_element):
# REWRITTEN: a portable tag is present but the expression text changed.
if portable_out:
returned_text = portable_out.get(authored_tag) or next(iter(portable_out.values()))
return _rewritten(input_element, authored_text, returned_text)
return _rewritten(input_element, authored_text, returned_text, owners, aliases)

# No portable tag: either a placeholder stand-in or a real vendor-only return.
if out_dialects:
Expand All @@ -322,7 +410,7 @@ def _classify_present(input_element, output_element):
return Finding(input_element.kind, input_element.name, SURVIVED_VENDOR_ONLY, detail="no expression returned")


def _repair_by_expression(dropped, added):
def _repair_by_expression(dropped, added, owners=None, aliases=None):
"""Pair a DROPPED input element with an ADDED output element that carries an
equivalent expression, so a converter that did not preserve an element's name
(orionbelt writes a field's expression as its name) scores as one element whose
Expand All @@ -339,7 +427,9 @@ def _repair_by_expression(dropped, added):
continue
out_text = next(iter(out_el.dialects.values()), "")
if in_text and (_normalize(out_el.name) == in_text or out_text == in_text
or _equivalent_tree(in_text, out_text) is True):
or _equivalent_tree(
in_text, out_text, owners, in_el.dataset, aliases
) is True):
pairs.append((in_el, out_el))
used.add(id(out_el))
break
Expand All @@ -360,19 +450,22 @@ def grade(input_document, output_document, diagnostics_text="", converter=""):
return report

diagnostics = diagnostics_text or ""
# Qualifiers that carry meaning are read from the input, the authored model.
owners = _field_owners(input_document)
aliases = _dataset_aliases(input_document, output_document)

present = {}
dropped = []
for key, element in input_elements.items():
if key in output_elements:
present[key] = _classify_present(element, output_elements[key])
present[key] = _classify_present(element, output_elements[key], owners, aliases)
else:
dropped.append(element)

added_elements = [el for key, el in output_elements.items() if key not in input_elements]

# Recover identity: an unnamed-preserving rename shows up as drop + add.
repaired = _repair_by_expression(dropped, added_elements)
repaired = _repair_by_expression(dropped, added_elements, owners, aliases)
repaired_in = {id(a): b for a, b in repaired}
repaired_out = {id(b) for _, b in repaired}

Expand Down Expand Up @@ -410,7 +503,7 @@ def _format(report):


def main(argv=None):
parser = argparse.ArgumentParser(description="Grade a converter round-trip for #576.")
parser = argparse.ArgumentParser(description="Grade a converter round-trip (apache/ossie-converters#24).")
parser.add_argument("--input", required=True, help="the input .ossie.yaml/.json document")
parser.add_argument("--returned", required=True, help="the document the converter returned")
parser.add_argument("--diagnostics", help="a text file of the converter's warnings/notices")
Expand Down
Loading
Loading