Skip to content

[OSSIE][SIGMA] Add bidirectional Sigma Computing data model converter - #297

Open
mattsenicksigma wants to merge 3 commits into
apache:mainfrom
mattsenicksigma:feature/sigma-converter
Open

[OSSIE][SIGMA] Add bidirectional Sigma Computing data model converter#297
mattsenicksigma wants to merge 3 commits into
apache:mainfrom
mattsenicksigma:feature/sigma-converter

Conversation

@mattsenicksigma

Copy link
Copy Markdown

Summary

Adds converters/sigma, a bidirectional converter between Sigma Computing data model specs and Apache Ossie, following the same structure/tooling as the dbt and NVIDIA GSF converters (uv, the apache-ossie pydantic models).

  • A real tokenizer + recursive-descent parser + ANSI SQL renderer for Sigma's spreadsheet-style formula language (ossie_sigma.sigma_formula), covering ~30 functions and all operators with nested-call support — not a regex classifier. Every expression always preserves the original Sigma formula verbatim in a new SIGMA dialect entry, guaranteeing lossless round-tripping regardless of translation coverage, alongside a best-effort ANSI_SQL translation.
  • Sigma ⇄ OSI mapping for datasets, fields, relationships (including Sigma's two column-addressing schemes — modeled column id vs. raw inode-<file>/<PHYSICAL_COLUMN> warehouse references), and model-level metrics, with native Sigma ids preserved via custom_extensions so re-export reuses stable ids rather than minting new ones.
  • Controls and named/static element filters are intentionally not modeled as OSI concepts (no portable equivalent — see converters/sigma/LIMITATIONS.md §1) but round-trip byte-for-byte via custom_extensions.
  • Adds SIGMA to OSIDialect/OSIVendor (python/src/ossie/models.py), the core-spec schema/docs (core-spec/spec.md, core-spec/osi-schema.json), and a Sigma column in expression_language.md's cross-tool mapping tables.
  • Fixes two small pre-existing gaps found while validating output against the repo's own tooling (documented in LIMITATIONS.md): core-spec/osi-schema.json was missing root-level dialects/vendors properties already present in the pydantic model, and validation/validate.py didn't skip SQL-syntax checking for SIGMA the way it already does for MDX/TABLEAU/MAQL.

See converters/sigma/LIMITATIONS.md for a full, honest accounting of design tradeoffs, known gaps (relationship resolution edge cases, table-calculation functions with no portable form, cross-dataset metrics with no Sigma equivalent, etc.), the testing strategy, and a self-assessment of likely review concerns.

Opening as a draft to gather early feedback on the approach (particularly the relationship-resolution strategy and the SIGMA dialect/vendor enum additions) before finalizing.

Test plan

  • cd converters/sigma && uv sync && uv run pytest — 50 tests pass (formula parser unit tests, directional conversion tests, byte-for-byte round-trip tests for two synthetic fixtures, and a real-world-input test against examples/tpcds_semantic_model.yaml)
  • Verified sigma-to-osi output validates cleanly against core-spec/osi-schema.json and validation/validate.py for both fixtures
  • Re-ran python/, converters/dbt/, and converters/gsf/ test suites to confirm the shared enum/schema changes don't regress existing converters
  • Feedback from a committer on the relationship-resolution approach and whether the SIGMA enum additions need a dev@ discussion or can proceed via normal PR review (see LIMITATIONS.md "Assessment: likelihood of upstream approval")

🤖 Generated with Claude Code

mattsenicksigma and others added 2 commits August 3, 2026 08:28
Adds converters/sigma, a hub-and-spoke converter between Sigma Computing
data model specs and Apache Ossie, following the same structure/tooling
as the dbt and NVIDIA GSF converters (uv, apache-ossie pydantic models).

- A real tokenizer/parser/renderer for Sigma's formula language
  (ossie_sigma.sigma_formula), translating to ANSI SQL where a faithful
  mapping exists and always preserving the original formula verbatim in
  a new SIGMA dialect entry for lossless round-tripping.
- Sigma <-> OSI mapping for datasets, fields, relationships (including
  Sigma's two column-addressing schemes), and model-level metrics, with
  native Sigma ids preserved via custom_extensions for stable re-export.
- Controls and named/static filters are intentionally not modeled as OSI
  concepts (no portable equivalent) but round-trip byte-for-byte via
  custom_extensions; see converters/sigma/LIMITATIONS.md for this and
  other documented tradeoffs.
- Adds SIGMA to OSIDialect/OSIVendor (python/src/ossie/models.py) and the
  core-spec schema/docs, plus a Sigma column in the expression_language.md
  cross-tool mapping tables.
- Fixes two small pre-existing gaps found while validating output:
  core-spec/osi-schema.json was missing root-level dialects/vendors
  properties already present in the pydantic model, and
  validation/validate.py didn't skip SQL-syntax checking for the new
  SIGMA dialect the same way it already does for MDX/TABLEAU/MAQL.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Reviews the Sigma converter against Sigma's documented data-model-as-code
spec and fixes the places where it diverged, several of which would have
broken a real upload.

API-safety fixes:

- An expression with no translatable Sigma formula was given an invented
  `[Dataset/Field]` placeholder (columns) or an empty string (metrics).
  `formula` is required on both, and the data model API validates the whole
  document before applying any of it, so one bad formula failed the entire
  create/update. Untranslatable columns/metrics are now omitted, with an
  issue naming them.
- `_DATATYPE_TO_FORMAT` emitted format kinds (`string`, `integer`,
  `boolean`, `time`, `datetime`) that do not exist. The spec defines exactly
  two, `number` and `date`; datatypes with no display format now emit no
  `format` key at all. The native format object is always preserved, so
  formatString/currencySymbol/etc. survive.
- `schemaVersion` is required on create/update and is now always emitted.

Spec coverage:

- Preserve unmapped element/column/metric/relationship/model keys by
  subtraction under a `native` extension rather than an allow-list, so
  `sort`, `summary`, `groupings`, `columnSecurities`, `visibleAsSource`,
  `hidden`, `isHighlighted`, `timeline`, `relationshipType` — and fields a
  future schemaVersion adds — round-trip instead of being dropped.
- Handle all six source kinds; `sql`/`table`/`data-model`/`join`/`union` get
  a readable marker plus the verbatim native source block.
- Map `uniqueKeys` to OSIDataset.primary_key, and metric/model `description`
  to their portable homes.
- Drop the `kind: control` framing: the spec has no control element and the
  create endpoint's element kind enum is `table` only. Renamed the issue to
  UNSUPPORTED_ELEMENT_KIND as a defensive path, and modeled the real
  concept, element-level `filters[]`, across all six filter kinds.
- Split multi-model handling onto its own EXTRA_MODEL_DROPPED issue instead
  of reusing the control one.

Formula translation:

- Render through a sqlglot expression tree instead of hand-built SQL
  strings, matching how the SQL-native converters here work. Quoting,
  escaping, and dialect targeting (`to_sql(..., dialect=...)`) come from the
  library. This caught a silent correctness bug: sqlglot does not re-infer
  parentheses from tree shape, so `([Qty] + 1) * [Price]` rendered as
  `"Qty" + 1 * "Price"`. Added an explicit precedence table and tests.
- Added DateAdd/DateDiff/Null(), already documented in
  core-spec/expression_language.md but not implemented.

Tests and docs:

- Fixtures now cover the documented spec surface: all six filter kinds, all
  five non-warehouse source kinds, uniqueKeys, groupings, sort, summary,
  columnSecurities, visibleAsSource, hidden, metric timeline/isHighlighted/
  format, relationshipType, both format kinds, and unnamed objects. New
  fixtureC covers forward compatibility (unknown element kind and unknown
  keys at every level).
- Pin synthesized ids to their literal uuid5 values; comparing two
  in-process runs could not have caught hash randomization.
- 80 tests pass; all three fixtures round-trip byte-identically through the
  CLI and pass validation/validate.py against the core spec.
- LIMITATIONS.md cut to the point, upstream-approval assessment removed, and
  prose "OSI" replaced with "Ossie".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@mattsenicksigma
mattsenicksigma marked this pull request as ready for review August 8, 2026 19:10
@mattsenicksigma

Copy link
Copy Markdown
Author

A more human comment:

Looking to add a Sigma Data Model converter to the Ossie standard. I've implemented all required items of the Ossie spec along with some optionals.

Some limitations based on Sigma's specific semantic layer will include:

  • Any non-ANSI convertable Sigma formula's will not be able to be represented as metrics. This is true if the non-ANSI component is at any level of nesting in the Sigma formula
  • As a result of the above, a Sigma Dialect has been added here to represent any Sigma specific formulas and such
  • id stability is required for Sigma Data Models to be maintained. Thus, I've added functionality to preserve id's for all Sigma elements -> if going from OSI to Sigma, an id is hashed. If the opposite, the Sigma generated id is preserved. Both paths will lead to stable id's moving forward for the Sigma Data Model
  • Similar to Snowflake Semantic Views, Sigma Data Models give the option for a named filter (in Sigma-land this is a "control") -> would be interesting to make this part of the generic Ossie spec -> currently definable under the custom extension functionality
  • Any Sigma presentation specific items are definable in the custom extension functionality for this converter
  • This converter only allows for table elements -> there are other elements that can be in a data model but they are out of scope of the Ossie standard I believe (Things like custom python, etc.)
  • data types are translated as faithfully as possible
  • AI context can be set in a Sigma Data Model, but currently blocked by this being available to GET/POST in Sigma's REST API

Happy to try and promote convention for these things and/or be a part of talks on promotion of some things to the generic Ossie spec.

@QMalcolm QMalcolm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Howdy! Thank you for doing this work ❤️

There are some things we should probably take care of before proceeding:

  1. resolve the merge conflicts
  2. osi -> ossie renames
  3. perhaps some extra accessing guards
    a. and associated converter issues

Overall this looks really good, and I'm incredibly excited for us to get it in 🙂

@@ -0,0 +1,355 @@
# Licensed to the Apache Software Foundation (ASF) under one

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With the transition to Ossie, we should rename this fileossie_to_sigma.py

@@ -0,0 +1,406 @@
# Licensed to the Apache Software Foundation (ASF) under one

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With the transition to Ossie, we should rename this filesigma_to_ossie.py

Comment on lines +1 to +16
# 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm not sure we need this in every file. Doesn't hurt anything, just perhaps a bit of overkill 😅

from typing import Any, Optional
from uuid import NAMESPACE_URL, uuid5

from ossie import OSICustomExtension, OSIDataset, OSIDocument, OSIField, OSIMetric, OSIRelationship, OSIVendor

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I believe these imports need to all be updated to have Ossie instead of OSI
e.g.

Suggested change
from ossie import OSICustomExtension, OSIDataset, OSIDocument, OSIField, OSIMetric, OSIRelationship, OSIVendor
from ossie import OssieCustomExtension, OssieDataset, OssieDocument, OssieField, OssieMetric, OssieRelationship, OssieVendor

Comment on lines +32 to +34
from ossie import OSIDocument
from ossie_sigma.osi_to_sigma import OSIToSigmaConverter
from ossie_sigma.sigma_to_osi import SigmaToOSIConverter

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
from ossie import OSIDocument
from ossie_sigma.osi_to_sigma import OSIToSigmaConverter
from ossie_sigma.sigma_to_osi import SigmaToOSIConverter
from ossie import OssieDocument
from ossie_sigma.ossie_to_sigma import OssieToSigmaConverter
from ossie_sigma.sigma_to_ossie import SigmaToOssieConverter

f"was converted, {len(document.semantic_model) - 1} additional model(s) were dropped.",
)
)
model = document.semantic_model[0]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Technically document.semantic_model could be an empty list. If that happens, an IndexError will get raised. Is that desired? An error or a ConverterIssue probably should get raised. Not sure which. What ever we do though we should make sure it is informative.

Comment on lines +65 to +72
def _sigma_ext(item: Any) -> Optional[dict[str, Any]]:
for ext in item.custom_extensions or []:
if ext.vendor_name == OSIVendor.SIGMA.value:
try:
return json.loads(ext.data)
except json.JSONDecodeError:
return None
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think we have an issue here which either calls for bettor typing for item or better guards in the function. Right now as it is, item is Any, this means that:

  1. item.custom_extensions could raise an AttributeError
  2. ext.vendor_name could raise an AttributeError
  3. json.loads(ext.data)` doesn't guarantee that an object is returned
    a. returned type could be a list, truthy, etc

spec["description"] = model.description
for key in ("dataModelId", "folderId", "documentVersion", "latestDocumentVersion", "schemaVersion"):
if key in model_ext:
spec[key] = model_ext[key]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Model-level metadata (createdAt, createdBy, updatedAt, updatedBy, ownerId, url) gets captured into model_ext on Sigma -> Ossie conversion, but are not written back during Ossie -> Sigma conversion. I think this contradicts the PR's byte-for-byte round-trip claim. Should we copy back the full set?

)

index = index_by_id[element["id"]]
unique_keys = [name for name, _ in (index.resolve(c) for c in element.get("uniqueKeys") or [])]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think there are two issues issues with uniqueKeys handling.
I believe:

  1. unresolved entries are dropped silently (perhaps a ConverterIssue when this happens?)
  2. resolved entries are rewritten to the internal column id, losing whether the original was a raw warehouse ref. Should we try to preserve this?

def __init__(self, element: dict[str, Any]) -> None:
self.element = element
self.columns_by_id: dict[str, dict[str, Any]] = {c["id"]: c for c in element.get("columns") or []}
self.physical_by_upper: dict[str, str] = {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I believe _ElementIndex.physical_by_upper might have two bugs:

  1. it indexes cross-table qualified refs (e.g. [OtherTable/Y]) under the bare name without checking ref.table is None
  2. it uppercases names so case-distinct columns like [amount]/[Amount]
    collide and silently overwrite each other.

Would it be worthwhile to:

  1. scope by table
  2. either preserve column case or detect + warn on collision

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants